machdep.c revision 61220
125428Speter/*-
250477Speter * Copyright (c) 1992 Terrence R. Lambert.
325428Speter * Copyright (c) 1982, 1987, 1990 The Regents of the University of California.
4139823Simp * All rights reserved.
525428Speter *
625428Speter * This code is derived from software contributed to Berkeley by
725428Speter * William Jolitz.
825428Speter *
925428Speter * Redistribution and use in source and binary forms, with or without
1025428Speter * modification, are permitted provided that the following conditions
1125428Speter * are met:
1225428Speter * 1. Redistributions of source code must retain the above copyright
1325428Speter *    notice, this list of conditions and the following disclaimer.
1425428Speter * 2. Redistributions in binary form must reproduce the above copyright
1525428Speter *    notice, this list of conditions and the following disclaimer in the
1625428Speter *    documentation and/or other materials provided with the distribution.
1725428Speter * 3. All advertising materials mentioning features or use of this software
1825428Speter *    must display the following acknowledgement:
1925428Speter *	This product includes software developed by the University of
2025428Speter *	California, Berkeley and its contributors.
2125428Speter * 4. Neither the name of the University nor the names of its contributors
2225428Speter *    may be used to endorse or promote products derived from this software
2325428Speter *    without specific prior written permission.
2425428Speter *
2525428Speter * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
2625428Speter * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
2725428Speter * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
2825428Speter * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
2925428Speter * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
3025428Speter * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
3125428Speter * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
3225428Speter * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
3325428Speter * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
3425428Speter * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
3525428Speter * SUCH DAMAGE.
3625428Speter *
3725428Speter *	from: @(#)machdep.c	7.4 (Berkeley) 6/3/91
3825428Speter * $FreeBSD: head/sys/amd64/amd64/machdep.c 61220 2000-06-03 14:19:01Z bde $
39217010Smarius */
4025428Speter
4125428Speter#include "apm.h"
4225428Speter#include "ether.h"
4325428Speter#include "npx.h"
4425428Speter#include "opt_atalk.h"
4525428Speter#include "opt_compat.h"
4625428Speter#include "opt_cpu.h"
4725428Speter#include "opt_ddb.h"
4825428Speter#include "opt_inet.h"
4925428Speter#include "opt_ipx.h"
5025428Speter#include "opt_maxmem.h"
5125428Speter#include "opt_msgbuf.h"
5225428Speter#include "opt_perfmon.h"
5355205Speter#include "opt_smp.h"
5425428Speter#include "opt_user_ldt.h"
5525428Speter#include "opt_userconfig.h"
5625428Speter
5725428Speter#include <sys/param.h>
5825428Speter#include <sys/systm.h>
5925428Speter#include <sys/sysproto.h>
6092725Salfred#include <sys/signalvar.h>
6192725Salfred#include <sys/kernel.h>
6225428Speter#include <sys/linker.h>
6325428Speter#include <sys/malloc.h>
6425428Speter#include <sys/proc.h>
6525428Speter#include <sys/bio.h>
6625428Speter#include <sys/buf.h>
6760938Sjake#include <sys/reboot.h>
6825428Speter#include <sys/callout.h>
6925428Speter#include <sys/mbuf.h>
7025428Speter#include <sys/msgbuf.h>
7125428Speter#include <sys/sysent.h>
7225428Speter#include <sys/sysctl.h>
7325428Speter#include <sys/vmmeter.h>
7425428Speter#include <sys/bus.h>
7525428Speter
7625428Speter#include <vm/vm.h>
7725428Speter#include <vm/vm_param.h>
7825428Speter#include <sys/lock.h>
7925428Speter#include <vm/vm_kern.h>
8025428Speter#include <vm/vm_object.h>
8160938Sjake#include <vm/vm_page.h>
8225428Speter#include <vm/vm_map.h>
8325428Speter#include <vm/vm_pager.h>
8425428Speter#include <vm/vm_extern.h>
8525428Speter
8625428Speter#include <sys/user.h>
8792725Salfred#include <sys/exec.h>
8892725Salfred#include <sys/cons.h>
8925428Speter
9045720Speter#include <ddb/ddb.h>
9192725Salfred
9245720Speter#include <net/netisr.h>
9325428Speter
9492725Salfred#include <machine/cpu.h>
9525428Speter#include <machine/reg.h>
9625428Speter#include <machine/clock.h>
9725428Speter#include <machine/specialreg.h>
9825428Speter#include <machine/bootinfo.h>
9925428Speter#include <machine/ipl.h>
10025428Speter#include <machine/md_var.h>
10192725Salfred#include <machine/pcb_ext.h>		/* pcb.h included via sys/user.h */
10225428Speter#ifdef SMP
10325428Speter#include <machine/smp.h>
10492725Salfred#include <machine/globaldata.h>
10592725Salfred#endif
10625428Speter#ifdef PERFMON
107155669Sglebius#include <machine/perfmon.h>
108155669Sglebius#endif
109155669Sglebius
11055205Speter#ifdef OLD_BUS_ARCH
11125428Speter#include <i386/isa/isa_device.h>
11225428Speter#endif
11325428Speter#include <i386/isa/intr_machdep.h>
11425428Speter#include <isa/rtc.h>
11525428Speter#include <machine/vm86.h>
11653649Sjulian#include <sys/random.h>
11725428Speter#include <sys/ptrace.h>
11825428Speter#include <machine/sigframe.h>
119114163Ssam
120114163Ssamextern void init386 __P((int first));
12125428Speterextern void dblfault_handler __P((void));
12225428Speter
12325428Speterextern void printcpuinfo(void);	/* XXX header file */
12425428Speterextern void earlysetcpuclass(void);	/* same header file */
12525428Speterextern void finishidentcpu(void);
12625428Speterextern void panicifcpuunsupported(void);
12725428Speterextern void initializecpu(void);
12895702Sphk
12925428Speter#define	CS_SECURE(cs)		(ISPL(cs) == SEL_UPL)
13025428Speter#define	EFL_SECURE(ef, oef)	((((ef) ^ (oef)) & ~PSL_USERCHANGE) == 0)
13125428Speter
13225428Speterstatic void cpu_startup __P((void *));
13325428SpeterSYSINIT(cpu, SI_SUB_CPU, SI_ORDER_FIRST, cpu_startup, NULL)
13425428Speter
13525428Speterstatic MALLOC_DEFINE(M_MBUF, "mbuf", "mbuf");
13625428Speter
13795702Sphkint	_udatasel, _ucodesel;
13895702Sphku_int	atdevbase;
13995702Sphk
14095702Sphk#if defined(SWTCH_OPTIM_STATS)
14195702Sphkextern int swtch_optim_stats;
14295702SphkSYSCTL_INT(_debug, OID_AUTO, swtch_optim_stats,
14395702Sphk	CTLFLAG_RD, &swtch_optim_stats, 0, "");
144155669SglebiusSYSCTL_INT(_debug, OID_AUTO, tlb_flush_count,
145155669Sglebius	CTLFLAG_RD, &tlb_flush_count, 0, "");
146159162Sglebius#endif
147217010Smarius
148217010Smarius#ifdef PC98
149217010Smariusstatic int	ispc98 = 1;
150217010Smarius#else
151217010Smariusstatic int	ispc98 = 0;
152217010Smarius#endif
153234098SjhbSYSCTL_INT(_machdep, OID_AUTO, ispc98, CTLFLAG_RD, &ispc98, 0, "");
154234098Sjhb
155234098Sjhbint physmem = 0;
156256832Saeint cold = 1;
157256832Sae
158256832Saestatic void osendsig __P((sig_t catcher, int sig, sigset_t *mask, u_long code));
159256832Sae
16053649Sjulianstatic int
16125428Spetersysctl_hw_physmem SYSCTL_HANDLER_ARGS
16295702Sphk{
163215297Smarius	int error = sysctl_handle_int(oidp, 0, ctob(physmem), req);
164215297Smarius	return (error);
16595702Sphk}
16625428Speter
16725428SpeterSYSCTL_PROC(_hw, HW_PHYSMEM, physmem, CTLTYPE_INT|CTLFLAG_RD,
16825428Speter	0, 0, sysctl_hw_physmem, "I", "");
16925428Speter
17025428Speterstatic int
17125428Spetersysctl_hw_usermem SYSCTL_HANDLER_ARGS
17225428Speter{
17325428Speter	int error = sysctl_handle_int(oidp, 0,
17495702Sphk		ctob(physmem - cnt.v_wire_count), req);
17595702Sphk	return (error);
17625428Speter}
17725428Speter
17825428SpeterSYSCTL_PROC(_hw, HW_USERMEM, usermem, CTLTYPE_INT|CTLFLAG_RD,
17995702Sphk	0, 0, sysctl_hw_usermem, "I", "");
18095702Sphk
18195702Sphkstatic int
18225428Spetersysctl_hw_availpages SYSCTL_HANDLER_ARGS
18325428Speter{
18425428Speter	int error = sysctl_handle_int(oidp, 0,
18525428Speter		i386_btop(avail_end - avail_start), req);
18625428Speter	return (error);
18725428Speter}
18825428Speter
18995702SphkSYSCTL_PROC(_hw, OID_AUTO, availpages, CTLTYPE_INT|CTLFLAG_RD,
19095702Sphk	0, 0, sysctl_hw_availpages, "I", "");
19125428Speter
19225428Speterstatic int
19377217Sphksysctl_machdep_msgbuf SYSCTL_HANDLER_ARGS
19477217Sphk{
19595702Sphk	int error;
196114163Ssam
19795702Sphk	/* Unwind the buffer, so that it's linear (possibly starting with
19895702Sphk	 * some initial nulls).
19995702Sphk	 */
20095702Sphk	error=sysctl_handle_opaque(oidp,msgbufp->msg_ptr+msgbufp->msg_bufr,
20195702Sphk		msgbufp->msg_size-msgbufp->msg_bufr,req);
20295702Sphk	if(error) return(error);
20395702Sphk	if(msgbufp->msg_bufr>0) {
204114163Ssam		error=sysctl_handle_opaque(oidp,msgbufp->msg_ptr,
205114163Ssam			msgbufp->msg_bufr,req);
206114163Ssam	}
207114163Ssam	return(error);
208114163Ssam}
209114163Ssam
210114163SsamSYSCTL_PROC(_machdep, OID_AUTO, msgbuf, CTLTYPE_STRING|CTLFLAG_RD,
211114163Ssam	0, 0, sysctl_machdep_msgbuf, "A","Contents of kernel message buffer");
212114163Ssam
213128195Sfjoestatic int msgbuf_clear;
214128195Sfjoe
215165569Ssamstatic int
216165569Ssamsysctl_machdep_msgbuf_clear SYSCTL_HANDLER_ARGS
217165569Ssam{
218170530Ssam	int error;
219170530Ssam	error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2,
220124543Sonoe		req);
22195702Sphk	if (!error && req->newptr) {
22295702Sphk		/* Clear the buffer and reset write pointer */
22396174Simp		bzero(msgbufp->msg_ptr,msgbufp->msg_size);
224177616Ssam		msgbufp->msg_bufr=msgbufp->msg_bufx=0;
225114163Ssam		msgbuf_clear=0;
226117817Ssam	}
227195618Srpaulo	return (error);
228124543Sonoe}
229114163Ssam
230124543SonoeSYSCTL_PROC(_machdep, OID_AUTO, msgbuf_clear, CTLTYPE_INT|CTLFLAG_RW,
231124543Sonoe	&msgbuf_clear, 0, sysctl_machdep_msgbuf_clear, "I",
232124543Sonoe	"Clear kernel message buffer");
233124543Sonoe
234170530Ssamint bootverbose = 0, Maxmem = 0;
235170530Ssamlong dumplo;
23677217Sphk
23777217Sphkvm_offset_t phys_avail[10];
238114232Sharti
239114232Sharti/* must be 2 less so 0 0 can signal end of chunks */
240217010Smarius#define PHYS_AVAIL_ARRAY_END ((sizeof(phys_avail) / sizeof(vm_offset_t)) - 2)
241217010Smarius
242217010Smariusstatic vm_offset_t buffer_sva, buffer_eva;
243217010Smariusvm_offset_t clean_sva, clean_eva;
244217010Smariusstatic vm_offset_t pager_sva, pager_eva;
245217010Smarius
246217010Smarius#define offsetof(type, member)	((size_t)(&((type *)0)->member))
247217010Smarius
248217010Smariusstatic void
249217010Smariuscpu_startup(dummy)
250125015Sharti	void *dummy;
251217010Smarius{
252217010Smarius	register unsigned i;
253217010Smarius	register caddr_t v;
254114232Sharti	vm_offset_t maxaddr;
255114232Sharti	vm_size_t size = 0;
25625428Speter	int firstaddr;
25725428Speter	vm_offset_t minaddr;
25825428Speter
25925428Speter	if (boothowto & RB_VERBOSE)
26025428Speter		bootverbose++;
26125428Speter
26225428Speter	/*
26325428Speter	 * Good {morning,afternoon,evening,night}.
26425428Speter	 */
26595702Sphk	printf(version);
26625428Speter	earlysetcpuclass();
267215297Smarius	startrtclock();
26895702Sphk	printcpuinfo();
26995702Sphk	panicifcpuunsupported();
27095702Sphk#ifdef PERFMON
27125428Speter	perfmon_init();
27225428Speter#endif
27325428Speter	printf("real memory  = %u (%uK bytes)\n", ptoa(Maxmem), ptoa(Maxmem) / 1024);
27425428Speter	/*
27525428Speter	 * Display any holes after the first chunk of extended memory.
27625428Speter	 */
27753649Sjulian	if (bootverbose) {
27825428Speter		int indx;
27925428Speter
28025428Speter		printf("Physical memory chunk(s):\n");
281114163Ssam		for (indx = 0; phys_avail[indx + 1] != 0; indx += 2) {
282114163Ssam			int size1 = phys_avail[indx + 1] - phys_avail[indx];
28325428Speter
28425428Speter			printf("0x%08x - 0x%08x, %u bytes (%u pages)\n",
285215297Smarius			    phys_avail[indx], phys_avail[indx + 1] - 1, size1,
286215297Smarius			    size1 / PAGE_SIZE);
287215297Smarius		}
28825428Speter	}
28925428Speter
29025428Speter	/*
29125428Speter	 * Calculate callout wheel size
29225428Speter	 */
29325428Speter	for (callwheelsize = 1, callwheelbits = 0;
294156751Sandre	     callwheelsize < ncallout;
295156751Sandre	     callwheelsize <<= 1, ++callwheelbits)
296156751Sandre		;
297156751Sandre	callwheelmask = callwheelsize - 1;
298217010Smarius
299217010Smarius	/*
300217010Smarius	 * Allocate space for system data structures.
301156751Sandre	 * The first available kernel virtual address is in "v".
302156751Sandre	 * As pages of kernel virtual memory are allocated, "v" is incremented.
30325428Speter	 * As pages of memory are allocated and cleared,
30425428Speter	 * "firstaddr" is incremented.
30525428Speter	 * An index into the kernel page table corresponding to the
306217010Smarius	 * virtual memory address maintained in "v" is kept in "mapaddr".
307217010Smarius	 */
308217010Smarius
309217010Smarius	/*
310217010Smarius	 * Make two passes.  The first pass calculates how much memory is
311217010Smarius	 * needed and allocates it.  The second pass assigns virtual
31225428Speter	 * addresses to the various data structures.
313217010Smarius	 */
31444521Swpaul	firstaddr = 0;
31525428Speteragain:
31644521Swpaul	v = (caddr_t)firstaddr;
31744521Swpaul
31895702Sphk#define	valloc(name, type, num) \
31944521Swpaul	    (name) = (type *)v; v = (caddr_t)((name)+(num))
320114163Ssam#define	valloclim(name, type, num, lim) \
321114163Ssam	    (name) = (type *)v; v = (caddr_t)((lim) = ((name)+(num)))
32244521Swpaul
32344521Swpaul	valloc(callout, struct callout, ncallout);
32425428Speter	valloc(callwheel, struct callout_tailq, callwheelsize);
32525428Speter
32625428Speter	/*
32725428Speter	 * The nominal buffer size (and minimum KVA allocation) is BKVASIZE.
32825428Speter	 * For the first 64MB of ram nominally allocate sufficient buffers to
32925428Speter	 * cover 1/4 of our ram.  Beyond the first 64MB allocate additional
33025428Speter	 * buffers to cover 1/20 of our ram over 64MB.
33125428Speter	 *
33225428Speter	 * factor represents the 1/4 x ram conversion.
33325428Speter	 */
33425428Speter	if (nbuf == 0) {
33525428Speter		int factor = 4 * BKVASIZE / PAGE_SIZE;
33677217Sphk
33777217Sphk		nbuf = 50;
33877217Sphk		if (physmem > 1024)
33977217Sphk			nbuf += min((physmem - 1024) / factor, 16384 / factor);
340114232Sharti		if (physmem > 16384)
34125428Speter			nbuf += (physmem - 16384) * 2 / (factor * 5);
34225428Speter	}
34325428Speter
34425428Speter	/*
34525428Speter	 * Do not allow the buffer_map to be more then 1/2 the size of the
34625428Speter	 * kernel_map.
34725428Speter	 */
34825428Speter	if (nbuf > (kernel_map->max_offset - kernel_map->min_offset) /
34925428Speter	    (BKVASIZE * 2)) {
35025428Speter		nbuf = (kernel_map->max_offset - kernel_map->min_offset) /
35125428Speter		    (BKVASIZE * 2);
35225428Speter		printf("Warning: nbufs capped at %d\n", nbuf);
35344521Swpaul	}
35444521Swpaul
35544542Swpaul	nswbuf = max(min(nbuf/4, 256), 16);
35644542Swpaul
35744542Swpaul	valloc(swbuf, struct buf, nswbuf);
358181138Santoine	valloc(buf, struct buf, nbuf);
35995702Sphk	v = bufhashinit(v);
360155708Sglebius
361155708Sglebius	/*
362159162Sglebius	 * End of first pass, size has been calculated so allocate memory
363170311Sdavidch	 */
364194917Snp	if (firstaddr == 0) {
365194917Snp		size = (vm_size_t)(v - firstaddr);
366194917Snp		firstaddr = (int)kmem_alloc(kernel_map, round_page(size));
367194917Snp		if (firstaddr == 0)
368194918Snp			panic("startup: no room for tables");
369234098Sjhb		goto again;
370234098Sjhb	}
371234098Sjhb
37225428Speter	/*
37325428Speter	 * End of second pass, addresses have been assigned
37425428Speter	 */
37525428Speter	if ((vm_size_t)(v - firstaddr) != size)
376221955Smarius		panic("startup: table size inconsistency");
37725428Speter
37825428Speter	clean_map = kmem_suballoc(kernel_map, &clean_sva, &clean_eva,
37925428Speter			(nbuf*BKVASIZE) + (nswbuf*MAXPHYS) + pager_map_size);
38025428Speter	buffer_map = kmem_suballoc(clean_map, &buffer_sva, &buffer_eva,
38125428Speter				(nbuf*BKVASIZE));
38225428Speter	pager_map = kmem_suballoc(clean_map, &pager_sva, &pager_eva,
38325428Speter				(nswbuf*MAXPHYS) + pager_map_size);
38425428Speter	pager_map->system_map = 1;
38525428Speter	exec_map = kmem_suballoc(kernel_map, &minaddr, &maxaddr,
38625428Speter				(16*(ARG_MAX+(PAGE_SIZE*3))));
38744521Swpaul
38844521Swpaul	/*
38995702Sphk	 * Finally, allocate mbuf pool.  Since mclrefcnt is an off-size
39095702Sphk	 * we use the more space efficient malloc in place of kmem_alloc.
39195702Sphk	 */
392181138Santoine	{
39395702Sphk		vm_offset_t mb_map_size;
39495702Sphk
395170311Sdavidch		mb_map_size = nmbufs * MSIZE + nmbclusters * MCLBYTES;
396221955Smarius		mb_map_size = roundup2(mb_map_size, max(MCLBYTES, PAGE_SIZE));
397221955Smarius		mclrefcnt = malloc(mb_map_size / MCLBYTES, M_MBUF, M_NOWAIT);
398221955Smarius		bzero(mclrefcnt, mb_map_size / MCLBYTES);
399221955Smarius		mb_map = kmem_suballoc(kmem_map, (vm_offset_t *)&mbutl, &maxaddr,
400221955Smarius			mb_map_size);
401221955Smarius		mb_map->system_map = 1;
402221955Smarius	}
403221955Smarius
404221955Smarius	/*
405221955Smarius	 * Initialize callouts
406221955Smarius	 */
407221955Smarius	SLIST_INIT(&callfree);
408221955Smarius	for (i = 0; i < ncallout; i++) {
409221955Smarius		callout_init(&callout[i]);
410221955Smarius		callout[i].c_flags = CALLOUT_LOCAL_ALLOC;
411221955Smarius		SLIST_INSERT_HEAD(&callfree, &callout[i], c_links.sle);
412221955Smarius	}
41325428Speter
41425428Speter	for (i = 0; i < callwheelsize; i++) {
41525428Speter		TAILQ_INIT(&callwheel[i]);
41625428Speter	}
417215297Smarius
418215297Smarius#if defined(USERCONFIG)
419215297Smarius	userconfig();
42025428Speter	cninit();		/* the preferred console may have changed */
42125428Speter#endif
42225428Speter
42325428Speter	printf("avail memory = %u (%uK bytes)\n", ptoa(cnt.v_free_count),
42425428Speter	    ptoa(cnt.v_free_count) / 1024);
42525428Speter
42625428Speter	/*
42725428Speter	 * Set up buffers, so they can be used to read disk labels.
42844165Sjulian	 */
42944165Sjulian	bufinit();
43025428Speter	vm_pager_bufferinit();
43125428Speter
43225428Speter#ifdef SMP
43325428Speter	/*
43425428Speter	 * OK, enough kmem_alloc/malloc state should be up, lets get on with it!
43525428Speter	 */
43625428Speter	mp_start();			/* fire up the APs and APICs */
43725428Speter	mp_announce();
43844165Sjulian#endif  /* SMP */
43944165Sjulian}
44025428Speter
44125428Speterint
44225428Speterregister_netisr(num, handler)
44325428Speter	int num;
44425428Speter	netisr_t *handler;
44525428Speter{
44625428Speter
44744165Sjulian	if (num < 0 || num >= (sizeof(netisrs)/sizeof(*netisrs)) ) {
44844165Sjulian		printf("register_netisr: bad isr number: %d\n", num);
44944165Sjulian		return (EINVAL);
45025428Speter	}
45125428Speter	netisrs[num] = handler;
45225428Speter	return (0);
45325428Speter}
45425428Speter
45525428Speterint
45625428Speterunregister_netisr(num)
45725428Speter	int num;
45825428Speter{
45925428Speter
46025428Speter	if (num < 0 || num >= (sizeof(netisrs)/sizeof(*netisrs)) ) {
46125428Speter		printf("unregister_netisr: bad isr number: %d\n", num);
46225428Speter		return (EINVAL);
46325428Speter	}
46425428Speter	netisrs[num] = NULL;
46525428Speter	return (0);
46625428Speter}
46725428Speter
46825428Speter/*
46925428Speter * Send an interrupt to process.
47025428Speter *
47125428Speter * Stack is set up to allow sigcode stored
47277217Sphk * at top to call routine, followed by kcall
47377217Sphk * to sigreturn routine below.  After sigreturn
47477217Sphk * resets the signal mask, the stack, and the
47577217Sphk * frame pointer, it returns to the user
47677217Sphk * specified pc, psl.
47777217Sphk */
47877217Sphkstatic void
47977217Sphkosendsig(catcher, sig, mask, code)
480114163Ssam	sig_t catcher;
481114163Ssam	int sig;
482114163Ssam	sigset_t *mask;
483114163Ssam	u_long code;
484114163Ssam{
485114163Ssam	struct osigframe sf;
486114163Ssam	struct osigframe *fp;
487114163Ssam	struct proc *p;
488114163Ssam	struct sigacts *psp;
489128195Sfjoe	struct trapframe *regs;
490128195Sfjoe	int oonstack;
491165569Ssam
492165569Ssam	p = curproc;
493165569Ssam	psp = p->p_sigacts;
494205515Srpaulo	regs = p->p_md.md_regs;
49577217Sphk	oonstack = p->p_sigstk.ss_flags & SS_ONSTACK;
49677217Sphk
49777217Sphk	/* Allocate and validate space for the signal handler context. */
49877217Sphk	if ((p->p_flag & P_ALTSTACK) && !oonstack &&
49977217Sphk	    SIGISMEMBER(psp->ps_sigonstack, sig)) {
50077217Sphk		fp = (struct osigframe *)(p->p_sigstk.ss_sp +
50177217Sphk		    p->p_sigstk.ss_size - sizeof(struct osigframe));
50277217Sphk		p->p_sigstk.ss_flags |= SS_ONSTACK;
50377217Sphk	} else
50477217Sphk		fp = (struct osigframe *)regs->tf_esp - 1;
50577217Sphk
50677217Sphk	/*
50777217Sphk	 * grow_stack() will return 0 if *fp does not fit inside the stack
50877217Sphk	 * and the stack can not be grown.
50977217Sphk	 * useracc() will return FALSE if access is denied.
51077217Sphk	 */
51177217Sphk	if (grow_stack(p, (int)fp) == 0 ||
51277217Sphk	    !useracc((caddr_t)fp, sizeof(*fp), VM_PROT_WRITE)) {
513114163Ssam		/*
514114163Ssam		 * Process has trashed its stack; give it an illegal
515114163Ssam		 * instruction to halt it in its tracks.
516114163Ssam		 */
517114163Ssam		SIGACTION(p, SIGILL) = SIG_DFL;
518114163Ssam		SIGDELSET(p->p_sigignore, SIGILL);
519114163Ssam		SIGDELSET(p->p_sigcatch, SIGILL);
520114163Ssam		SIGDELSET(p->p_sigmask, SIGILL);
521114163Ssam		psignal(p, SIGILL);
522114163Ssam		return;
523114163Ssam	}
524114163Ssam
525114163Ssam	/* Translate the signal if appropriate. */
526128195Sfjoe	if (p->p_sysent->sv_sigtbl && sig <= p->p_sysent->sv_sigsize)
527128195Sfjoe		sig = p->p_sysent->sv_sigtbl[_SIG_IDX(sig)];
528128195Sfjoe
529128195Sfjoe	/* Build the argument list for the signal handler. */
530165569Ssam	sf.sf_signum = sig;
531165569Ssam	sf.sf_scp = (register_t)&fp->sf_siginfo.si_sc;
532165569Ssam	if (SIGISMEMBER(p->p_sigacts->ps_siginfo, sig)) {
533205515Srpaulo		/* Signal handler installed with SA_SIGINFO. */
53477217Sphk		sf.sf_arg2 = (register_t)&fp->sf_siginfo;
53577217Sphk		sf.sf_siginfo.si_signo = sig;
53677217Sphk		sf.sf_siginfo.si_code = code;
53777217Sphk		sf.sf_ahu.sf_action = (__osiginfohandler_t *)catcher;
53877217Sphk	} else {
53994489Simp		/* Old FreeBSD-style arguments. */
54096174Simp		sf.sf_arg2 = code;
541177616Ssam		sf.sf_addr = regs->tf_err;
542114163Ssam		sf.sf_ahu.sf_handler = catcher;
543117817Ssam	}
544195618Srpaulo
54577217Sphk	/* Save most if not all of trap frame. */
54677217Sphk	sf.sf_siginfo.si_sc.sc_eax = regs->tf_eax;
54777217Sphk	sf.sf_siginfo.si_sc.sc_ebx = regs->tf_ebx;
548114163Ssam	sf.sf_siginfo.si_sc.sc_ecx = regs->tf_ecx;
549116819Ssam	sf.sf_siginfo.si_sc.sc_edx = regs->tf_edx;
550114163Ssam	sf.sf_siginfo.si_sc.sc_esi = regs->tf_esi;
551114163Ssam	sf.sf_siginfo.si_sc.sc_edi = regs->tf_edi;
552114163Ssam	sf.sf_siginfo.si_sc.sc_cs = regs->tf_cs;
553124543Sonoe	sf.sf_siginfo.si_sc.sc_ds = regs->tf_ds;
554170530Ssam	sf.sf_siginfo.si_sc.sc_ss = regs->tf_ss;
555170530Ssam	sf.sf_siginfo.si_sc.sc_es = regs->tf_es;
556114163Ssam	sf.sf_siginfo.si_sc.sc_fs = regs->tf_fs;
557114163Ssam	sf.sf_siginfo.si_sc.sc_gs = rgs();
558114163Ssam	sf.sf_siginfo.si_sc.sc_isp = regs->tf_isp;
559116819Ssam
560116819Ssam	/* Build the signal context to be used by osigreturn(). */
561116819Ssam	sf.sf_siginfo.si_sc.sc_onstack = oonstack;
562116819Ssam	SIG2OSIG(*mask, sf.sf_siginfo.si_sc.sc_mask);
563116819Ssam	sf.sf_siginfo.si_sc.sc_sp = regs->tf_esp;
564217010Smarius	sf.sf_siginfo.si_sc.sc_fp = regs->tf_ebp;
565114232Sharti	sf.sf_siginfo.si_sc.sc_pc = regs->tf_eip;
566114232Sharti	sf.sf_siginfo.si_sc.sc_ps = regs->tf_eflags;
567114232Sharti	sf.sf_siginfo.si_sc.sc_trapno = regs->tf_trapno;
568114232Sharti	sf.sf_siginfo.si_sc.sc_err = regs->tf_err;
569114232Sharti
570114232Sharti	/*
571114232Sharti	 * If we're a vm86 process, we want to save the segment registers.
572115690Sharti	 * We also change eflags to be our emulated eflags, not the actual
573114232Sharti	 * eflags.
574125015Sharti	 */
575114232Sharti	if (regs->tf_eflags & PSL_VM) {
576114232Sharti		/* XXX confusing names: `tf' isn't a trapframe; `regs' is. */
577114232Sharti		struct trapframe_vm86 *tf = (struct trapframe_vm86 *)regs;
578217010Smarius		struct vm86_kernel *vm86 = &p->p_addr->u_pcb.pcb_ext->ext_vm86;
579114232Sharti
580114232Sharti		sf.sf_siginfo.si_sc.sc_gs = tf->tf_vm86_gs;
581114232Sharti		sf.sf_siginfo.si_sc.sc_fs = tf->tf_vm86_fs;
582114232Sharti		sf.sf_siginfo.si_sc.sc_es = tf->tf_vm86_es;
583114232Sharti		sf.sf_siginfo.si_sc.sc_ds = tf->tf_vm86_ds;
584114232Sharti
585114232Sharti		if (vm86->vm86_has_vme == 0)
586114232Sharti			sf.sf_siginfo.si_sc.sc_ps =
587114232Sharti			    (tf->tf_eflags & ~(PSL_VIF | PSL_VIP)) |
588125015Sharti			    (vm86->vm86_eflags & (PSL_VIF | PSL_VIP));
589114232Sharti
590114232Sharti		/* See sendsig() for comments. */
591114232Sharti		tf->tf_eflags &= ~(PSL_VM | PSL_NT | PSL_T | PSL_VIF | PSL_VIP);
592114232Sharti	}
593114232Sharti
594114232Sharti	/* Copy the sigframe out to the user's stack. */
595114232Sharti	if (copyout(&sf, fp, sizeof(*fp)) != 0) {
596114232Sharti		/*
597114232Sharti		 * Something is wrong with the stack pointer.
598114232Sharti		 * ...Kill the process.
59925428Speter		 */
60025428Speter		sigexit(p, SIGILL);
60125428Speter	}
60225428Speter
60325428Speter	regs->tf_esp = (int)fp;
60425428Speter	regs->tf_eip = PS_STRINGS - szosigcode;
60525428Speter	regs->tf_cs = _ucodesel;
60625428Speter	regs->tf_ds = _udatasel;
60725428Speter	regs->tf_es = _udatasel;
608221955Smarius	regs->tf_fs = _udatasel;
609221955Smarius	load_gs(_udatasel);
610221955Smarius	regs->tf_ss = _udatasel;
611221955Smarius}
612221955Smarius
613221955Smariusvoid
614221955Smariussendsig(catcher, sig, mask, code)
61525428Speter	sig_t catcher;
61625428Speter	int sig;
61725428Speter	sigset_t *mask;
61825428Speter	u_long code;
61925428Speter{
62025428Speter	struct sigframe sf;
621215297Smarius	struct proc *p;
62225428Speter	struct sigacts *psp;
62325428Speter	struct trapframe *regs;
62425428Speter	struct sigframe *sfp;
62525428Speter	int oonstack;
62625428Speter
62725428Speter	p = curproc;
62825428Speter	psp = p->p_sigacts;
629217013Smarius	if (SIGISMEMBER(psp->ps_osigset, sig)) {
630217013Smarius		osendsig(catcher, sig, mask, code);
631217013Smarius		return;
632217013Smarius	}
633217013Smarius	regs = p->p_md.md_regs;
634217013Smarius	oonstack = p->p_sigstk.ss_flags & SS_ONSTACK;
635217013Smarius
636217013Smarius	/* Save user context. */
637217013Smarius	bzero(&sf, sizeof(sf));
638155669Sglebius	sf.sf_uc.uc_sigmask = *mask;
639155669Sglebius	sf.sf_uc.uc_stack = p->p_sigstk;
640155669Sglebius	sf.sf_uc.uc_mcontext.mc_onstack = oonstack;
641155669Sglebius	sf.sf_uc.uc_mcontext.mc_gs = rgs();
642155669Sglebius	bcopy(regs, &sf.sf_uc.uc_mcontext.mc_fs, sizeof(*regs));
643155669Sglebius
644155669Sglebius	/* Allocate and validate space for the signal handler context. */
645155669Sglebius	if ((p->p_flag & P_ALTSTACK) != 0 && !oonstack &&
646217010Smarius	    SIGISMEMBER(psp->ps_sigonstack, sig)) {
647155669Sglebius		sfp = (struct sigframe *)(p->p_sigstk.ss_sp +
648155669Sglebius		    p->p_sigstk.ss_size - sizeof(struct sigframe));
649155669Sglebius		p->p_sigstk.ss_flags |= SS_ONSTACK;
650155669Sglebius	} else
651155669Sglebius		sfp = (struct sigframe *)regs->tf_esp - 1;
652155669Sglebius
653155669Sglebius	/*
654155669Sglebius	 * grow_stack() will return 0 if *sfp does not fit inside the stack
655155669Sglebius	 * and the stack can not be grown.
656155669Sglebius	 * useracc() will return FALSE if access is denied.
657155669Sglebius	 */
658155669Sglebius	if (grow_stack(p, (int)sfp) == 0 ||
659155669Sglebius	    !useracc((caddr_t)sfp, sizeof(*sfp), VM_PROT_WRITE)) {
660155669Sglebius		/*
661155669Sglebius		 * Process has trashed its stack; give it an illegal
662155669Sglebius		 * instruction to halt it in its tracks.
663159162Sglebius		 */
664159162Sglebius#ifdef DEBUG
665170311Sdavidch		printf("process %d has trashed its stack\n", p->p_pid);
666186260Sgnn#endif
667194917Snp		SIGACTION(p, SIGILL) = SIG_DFL;
668186260Sgnn		SIGDELSET(p->p_sigignore, SIGILL);
669194918Snp		SIGDELSET(p->p_sigcatch, SIGILL);
670234098Sjhb		SIGDELSET(p->p_sigmask, SIGILL);
671234098Sjhb		psignal(p, SIGILL);
672234098Sjhb		return;
673155669Sglebius	}
674155669Sglebius
675155669Sglebius	/* Translate the signal if appropriate. */
676155669Sglebius	if (p->p_sysent->sv_sigtbl && sig <= p->p_sysent->sv_sigsize)
677155669Sglebius		sig = p->p_sysent->sv_sigtbl[_SIG_IDX(sig)];
678155669Sglebius
679155669Sglebius	/* Build the argument list for the signal handler. */
680155669Sglebius	sf.sf_signum = sig;
681155669Sglebius	sf.sf_ucontext = (register_t)&sfp->sf_uc;
682155669Sglebius	if (SIGISMEMBER(p->p_sigacts->ps_siginfo, sig)) {
683155669Sglebius		/* Signal handler installed with SA_SIGINFO. */
684155669Sglebius		sf.sf_siginfo = (register_t)&sfp->sf_si;
685155669Sglebius		sf.sf_ahu.sf_action = (__siginfohandler_t *)catcher;
686155669Sglebius
687155669Sglebius		/* Fill siginfo structure. */
688155669Sglebius		sf.sf_si.si_signo = sig;
689155669Sglebius		sf.sf_si.si_code = code;
690155669Sglebius		sf.sf_si.si_addr = (void *)regs->tf_err;
691155669Sglebius	} else {
692155669Sglebius		/* Old FreeBSD-style arguments. */
693155669Sglebius		sf.sf_siginfo = code;
694155669Sglebius		sf.sf_addr = regs->tf_err;
695155669Sglebius		sf.sf_ahu.sf_handler = catcher;
696155669Sglebius	}
697155669Sglebius
698155669Sglebius	/*
699155669Sglebius	 * If we're a vm86 process, we want to save the segment registers.
700155669Sglebius	 * We also change eflags to be our emulated eflags, not the actual
701155669Sglebius	 * eflags.
702155669Sglebius	 */
703156751Sandre	if (regs->tf_eflags & PSL_VM) {
704156751Sandre		struct trapframe_vm86 *tf = (struct trapframe_vm86 *)regs;
705156751Sandre		struct vm86_kernel *vm86 = &p->p_addr->u_pcb.pcb_ext->ext_vm86;
706156751Sandre
707156751Sandre		sf.sf_uc.uc_mcontext.mc_gs = tf->tf_vm86_gs;
708156751Sandre		sf.sf_uc.uc_mcontext.mc_fs = tf->tf_vm86_fs;
709156751Sandre		sf.sf_uc.uc_mcontext.mc_es = tf->tf_vm86_es;
710156751Sandre		sf.sf_uc.uc_mcontext.mc_ds = tf->tf_vm86_ds;
711156751Sandre
712156751Sandre		if (vm86->vm86_has_vme == 0)
713217010Smarius			sf.sf_uc.uc_mcontext.mc_eflags =
714156751Sandre			    (tf->tf_eflags & ~(PSL_VIF | PSL_VIP)) |
715156751Sandre			    (vm86->vm86_eflags & (PSL_VIF | PSL_VIP));
716217010Smarius
717156751Sandre		/*
718156751Sandre		 * We should never have PSL_T set when returning from vm86
719156751Sandre		 * mode.  It may be set here if we deliver a signal before
720156751Sandre		 * getting to vm86 mode, so turn it off.
721156751Sandre		 *
722156751Sandre		 * Clear PSL_NT to inhibit T_TSSFLT faults on return from
723156751Sandre		 * syscalls made by the signal handler.  This just avoids
724156751Sandre		 * wasting time for our lazy fixup of such faults.  PSL_NT
725156751Sandre		 * does nothing in vm86 mode, but vm86 programs can set it
726156751Sandre		 * almost legitimately in probes for old cpu types.
727156751Sandre		 */
728156751Sandre		tf->tf_eflags &= ~(PSL_VM | PSL_NT | PSL_T | PSL_VIF | PSL_VIP);
729156751Sandre	}
73025428Speter
731	/* Copy the sigframe out to the user's stack. */
732	if (copyout(&sf, sfp, sizeof(*sfp)) != 0) {
733		/*
734		 * Something is wrong with the stack pointer.
735		 * ...Kill the process.
736		 */
737		sigexit(p, SIGILL);
738	}
739
740	regs->tf_esp = (int)sfp;
741	regs->tf_eip = PS_STRINGS - *(p->p_sysent->sv_szsigcode);
742	regs->tf_cs = _ucodesel;
743	regs->tf_ds = _udatasel;
744	regs->tf_es = _udatasel;
745	regs->tf_fs = _udatasel;
746	load_gs(_udatasel);
747	regs->tf_ss = _udatasel;
748}
749
750/*
751 * System call to cleanup state after a signal
752 * has been taken.  Reset signal mask and
753 * stack state from context left by sendsig (above).
754 * Return to previous pc and psl as specified by
755 * context left by sendsig. Check carefully to
756 * make sure that the user has not modified the
757 * state to gain improper privileges.
758 */
759int
760osigreturn(p, uap)
761	struct proc *p;
762	struct osigreturn_args /* {
763		struct osigcontext *sigcntxp;
764	} */ *uap;
765{
766	struct trapframe *regs;
767	struct osigcontext *scp;
768	int eflags;
769
770	regs = p->p_md.md_regs;
771	scp = uap->sigcntxp;
772	if (!useracc((caddr_t)scp, sizeof(*scp), VM_PROT_READ))
773		return (EFAULT);
774	eflags = scp->sc_ps;
775	if (eflags & PSL_VM) {
776		struct trapframe_vm86 *tf = (struct trapframe_vm86 *)regs;
777		struct vm86_kernel *vm86;
778
779		/*
780		 * if pcb_ext == 0 or vm86_inited == 0, the user hasn't
781		 * set up the vm86 area, and we can't enter vm86 mode.
782		 */
783		if (p->p_addr->u_pcb.pcb_ext == 0)
784			return (EINVAL);
785		vm86 = &p->p_addr->u_pcb.pcb_ext->ext_vm86;
786		if (vm86->vm86_inited == 0)
787			return (EINVAL);
788
789		/* Go back to user mode if both flags are set. */
790		if ((eflags & PSL_VIP) && (eflags & PSL_VIF))
791			trapsignal(p, SIGBUS, 0);
792
793		if (vm86->vm86_has_vme) {
794			eflags = (tf->tf_eflags & ~VME_USERCHANGE) |
795			    (eflags & VME_USERCHANGE) | PSL_VM;
796		} else {
797			vm86->vm86_eflags = eflags;	/* save VIF, VIP */
798			eflags = (tf->tf_eflags & ~VM_USERCHANGE) |					    (eflags & VM_USERCHANGE) | PSL_VM;
799		}
800		tf->tf_vm86_ds = scp->sc_ds;
801		tf->tf_vm86_es = scp->sc_es;
802		tf->tf_vm86_fs = scp->sc_fs;
803		tf->tf_vm86_gs = scp->sc_gs;
804		tf->tf_ds = _udatasel;
805		tf->tf_es = _udatasel;
806		tf->tf_fs = _udatasel;
807	} else {
808		/*
809		 * Don't allow users to change privileged or reserved flags.
810		 */
811		/*
812		 * XXX do allow users to change the privileged flag PSL_RF.
813		 * The cpu sets PSL_RF in tf_eflags for faults.  Debuggers
814		 * should sometimes set it there too.  tf_eflags is kept in
815		 * the signal context during signal handling and there is no
816		 * other place to remember it, so the PSL_RF bit may be
817		 * corrupted by the signal handler without us knowing.
818		 * Corruption of the PSL_RF bit at worst causes one more or
819		 * one less debugger trap, so allowing it is fairly harmless.
820		 */
821		if (!EFL_SECURE(eflags & ~PSL_RF, regs->tf_eflags & ~PSL_RF)) {
822	    		return (EINVAL);
823		}
824
825		/*
826		 * Don't allow users to load a valid privileged %cs.  Let the
827		 * hardware check for invalid selectors, excess privilege in
828		 * other selectors, invalid %eip's and invalid %esp's.
829		 */
830		if (!CS_SECURE(scp->sc_cs)) {
831			trapsignal(p, SIGBUS, T_PROTFLT);
832			return (EINVAL);
833		}
834		regs->tf_ds = scp->sc_ds;
835		regs->tf_es = scp->sc_es;
836		regs->tf_fs = scp->sc_fs;
837	}
838
839	/* Restore remaining registers. */
840	regs->tf_eax = scp->sc_eax;
841	regs->tf_ebx = scp->sc_ebx;
842	regs->tf_ecx = scp->sc_ecx;
843	regs->tf_edx = scp->sc_edx;
844	regs->tf_esi = scp->sc_esi;
845	regs->tf_edi = scp->sc_edi;
846	regs->tf_cs = scp->sc_cs;
847	regs->tf_ss = scp->sc_ss;
848	regs->tf_isp = scp->sc_isp;
849
850	if (scp->sc_onstack & 01)
851		p->p_sigstk.ss_flags |= SS_ONSTACK;
852	else
853		p->p_sigstk.ss_flags &= ~SS_ONSTACK;
854	SIGSETOLD(p->p_sigmask, scp->sc_mask);
855	SIG_CANTMASK(p->p_sigmask);
856	regs->tf_ebp = scp->sc_fp;
857	regs->tf_esp = scp->sc_sp;
858	regs->tf_eip = scp->sc_pc;
859	regs->tf_eflags = eflags;
860	return (EJUSTRETURN);
861}
862
863int
864sigreturn(p, uap)
865	struct proc *p;
866	struct sigreturn_args /* {
867		ucontext_t *sigcntxp;
868	} */ *uap;
869{
870	struct trapframe *regs;
871	ucontext_t *ucp;
872	int cs, eflags;
873
874	ucp = uap->sigcntxp;
875	if (!useracc((caddr_t)ucp, sizeof(struct osigcontext), VM_PROT_READ))
876		return (EFAULT);
877	if (((struct osigcontext *)ucp)->sc_trapno == 0x01d516)
878		return (osigreturn(p, (struct osigreturn_args *)uap));
879
880	/*
881	 * Since ucp is not an osigcontext but a ucontext_t, we have to
882	 * check again if all of it is accessible.  A ucontext_t is
883	 * much larger, so instead of just checking for the pointer
884	 * being valid for the size of an osigcontext, now check for
885	 * it being valid for a whole, new-style ucontext_t.
886	 */
887	if (!useracc((caddr_t)ucp, sizeof(*ucp), VM_PROT_READ))
888		return (EFAULT);
889
890	regs = p->p_md.md_regs;
891	eflags = ucp->uc_mcontext.mc_eflags;
892	if (eflags & PSL_VM) {
893		struct trapframe_vm86 *tf = (struct trapframe_vm86 *)regs;
894		struct vm86_kernel *vm86;
895
896		/*
897		 * if pcb_ext == 0 or vm86_inited == 0, the user hasn't
898		 * set up the vm86 area, and we can't enter vm86 mode.
899		 */
900		if (p->p_addr->u_pcb.pcb_ext == 0)
901			return (EINVAL);
902		vm86 = &p->p_addr->u_pcb.pcb_ext->ext_vm86;
903		if (vm86->vm86_inited == 0)
904			return (EINVAL);
905
906		/* Go back to user mode if both flags are set. */
907		if ((eflags & PSL_VIP) && (eflags & PSL_VIF))
908			trapsignal(p, SIGBUS, 0);
909
910		if (vm86->vm86_has_vme) {
911			eflags = (tf->tf_eflags & ~VME_USERCHANGE) |
912			    (eflags & VME_USERCHANGE) | PSL_VM;
913		} else {
914			vm86->vm86_eflags = eflags;	/* save VIF, VIP */
915			eflags = (tf->tf_eflags & ~VM_USERCHANGE) |					    (eflags & VM_USERCHANGE) | PSL_VM;
916		}
917		bcopy(&ucp->uc_mcontext.mc_fs, tf, sizeof(struct trapframe));
918		tf->tf_eflags = eflags;
919		tf->tf_vm86_ds = tf->tf_ds;
920		tf->tf_vm86_es = tf->tf_es;
921		tf->tf_vm86_fs = tf->tf_fs;
922		tf->tf_vm86_gs = ucp->uc_mcontext.mc_gs;
923		tf->tf_ds = _udatasel;
924		tf->tf_es = _udatasel;
925		tf->tf_fs = _udatasel;
926	} else {
927		/*
928		 * Don't allow users to change privileged or reserved flags.
929		 */
930		/*
931		 * XXX do allow users to change the privileged flag PSL_RF.
932		 * The cpu sets PSL_RF in tf_eflags for faults.  Debuggers
933		 * should sometimes set it there too.  tf_eflags is kept in
934		 * the signal context during signal handling and there is no
935		 * other place to remember it, so the PSL_RF bit may be
936		 * corrupted by the signal handler without us knowing.
937		 * Corruption of the PSL_RF bit at worst causes one more or
938		 * one less debugger trap, so allowing it is fairly harmless.
939		 */
940		if (!EFL_SECURE(eflags & ~PSL_RF, regs->tf_eflags & ~PSL_RF)) {
941			printf("sigreturn: eflags = 0x%x\n", eflags);
942	    		return (EINVAL);
943		}
944
945		/*
946		 * Don't allow users to load a valid privileged %cs.  Let the
947		 * hardware check for invalid selectors, excess privilege in
948		 * other selectors, invalid %eip's and invalid %esp's.
949		 */
950		cs = ucp->uc_mcontext.mc_cs;
951		if (!CS_SECURE(cs)) {
952			printf("sigreturn: cs = 0x%x\n", cs);
953			trapsignal(p, SIGBUS, T_PROTFLT);
954			return (EINVAL);
955		}
956
957		bcopy(&ucp->uc_mcontext.mc_fs, regs, sizeof(*regs));
958	}
959	if (ucp->uc_mcontext.mc_onstack & 1)
960		p->p_sigstk.ss_flags |= SS_ONSTACK;
961	else
962		p->p_sigstk.ss_flags &= ~SS_ONSTACK;
963
964	p->p_sigmask = ucp->uc_sigmask;
965	SIG_CANTMASK(p->p_sigmask);
966	return (EJUSTRETURN);
967}
968
969/*
970 * Machine dependent boot() routine
971 *
972 * I haven't seen anything to put here yet
973 * Possibly some stuff might be grafted back here from boot()
974 */
975void
976cpu_boot(int howto)
977{
978}
979
980/*
981 * Shutdown the CPU as much as possible
982 */
983void
984cpu_halt(void)
985{
986	for (;;)
987		__asm__ ("hlt");
988}
989
990/*
991 * Clear registers on exec
992 */
993void
994setregs(p, entry, stack, ps_strings)
995	struct proc *p;
996	u_long entry;
997	u_long stack;
998	u_long ps_strings;
999{
1000	struct trapframe *regs = p->p_md.md_regs;
1001	struct pcb *pcb = &p->p_addr->u_pcb;
1002
1003#ifdef USER_LDT
1004	/* was i386_user_cleanup() in NetBSD */
1005	user_ldt_free(pcb);
1006#endif
1007
1008	bzero((char *)regs, sizeof(struct trapframe));
1009	regs->tf_eip = entry;
1010	regs->tf_esp = stack;
1011	regs->tf_eflags = PSL_USER | (regs->tf_eflags & PSL_T);
1012	regs->tf_ss = _udatasel;
1013	regs->tf_ds = _udatasel;
1014	regs->tf_es = _udatasel;
1015	regs->tf_fs = _udatasel;
1016	regs->tf_cs = _ucodesel;
1017
1018	/* PS_STRINGS value for BSD/OS binaries.  It is 0 for non-BSD/OS. */
1019	regs->tf_ebx = ps_strings;
1020
1021	/* reset %gs as well */
1022	if (pcb == curpcb)
1023		load_gs(_udatasel);
1024	else
1025		pcb->pcb_gs = _udatasel;
1026
1027        /*
1028         * Reset the hardware debug registers if they were in use.
1029         * They won't have any meaning for the newly exec'd process.
1030         */
1031        if (pcb->pcb_flags & PCB_DBREGS) {
1032                pcb->pcb_dr0 = 0;
1033                pcb->pcb_dr1 = 0;
1034                pcb->pcb_dr2 = 0;
1035                pcb->pcb_dr3 = 0;
1036                pcb->pcb_dr6 = 0;
1037                pcb->pcb_dr7 = 0;
1038                if (pcb == curpcb) {
1039		        /*
1040			 * Clear the debug registers on the running
1041			 * CPU, otherwise they will end up affecting
1042			 * the next process we switch to.
1043			 */
1044		        reset_dbregs();
1045                }
1046                pcb->pcb_flags &= ~PCB_DBREGS;
1047        }
1048
1049	/*
1050	 * Initialize the math emulator (if any) for the current process.
1051	 * Actually, just clear the bit that says that the emulator has
1052	 * been initialized.  Initialization is delayed until the process
1053	 * traps to the emulator (if it is done at all) mainly because
1054	 * emulators don't provide an entry point for initialization.
1055	 */
1056	p->p_addr->u_pcb.pcb_flags &= ~FP_SOFTFP;
1057
1058	/*
1059	 * Arrange to trap the next npx or `fwait' instruction (see npx.c
1060	 * for why fwait must be trapped at least if there is an npx or an
1061	 * emulator).  This is mainly to handle the case where npx0 is not
1062	 * configured, since the npx routines normally set up the trap
1063	 * otherwise.  It should be done only at boot time, but doing it
1064	 * here allows modifying `npx_exists' for testing the emulator on
1065	 * systems with an npx.
1066	 */
1067	load_cr0(rcr0() | CR0_MP | CR0_TS);
1068
1069#if NNPX > 0
1070	/* Initialize the npx (if any) for the current process. */
1071	npxinit(__INITIAL_NPXCW__);
1072#endif
1073
1074      /*
1075       * XXX - Linux emulator
1076       * Make sure sure edx is 0x0 on entry. Linux binaries depend
1077       * on it.
1078       */
1079      p->p_retval[1] = 0;
1080}
1081
1082static int
1083sysctl_machdep_adjkerntz SYSCTL_HANDLER_ARGS
1084{
1085	int error;
1086	error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2,
1087		req);
1088	if (!error && req->newptr)
1089		resettodr();
1090	return (error);
1091}
1092
1093SYSCTL_PROC(_machdep, CPU_ADJKERNTZ, adjkerntz, CTLTYPE_INT|CTLFLAG_RW,
1094	&adjkerntz, 0, sysctl_machdep_adjkerntz, "I", "");
1095
1096SYSCTL_INT(_machdep, CPU_DISRTCSET, disable_rtc_set,
1097	CTLFLAG_RW, &disable_rtc_set, 0, "");
1098
1099SYSCTL_STRUCT(_machdep, CPU_BOOTINFO, bootinfo,
1100	CTLFLAG_RD, &bootinfo, bootinfo, "");
1101
1102SYSCTL_INT(_machdep, CPU_WALLCLOCK, wall_cmos_clock,
1103	CTLFLAG_RW, &wall_cmos_clock, 0, "");
1104
1105/*
1106 * Initialize 386 and configure to run kernel
1107 */
1108
1109/*
1110 * Initialize segments & interrupt table
1111 */
1112
1113int _default_ldt;
1114#ifdef SMP
1115union descriptor gdt[NGDT * NCPU];	/* global descriptor table */
1116#else
1117union descriptor gdt[NGDT];		/* global descriptor table */
1118#endif
1119static struct gate_descriptor idt0[NIDT];
1120struct gate_descriptor *idt = &idt0[0];	/* interrupt descriptor table */
1121union descriptor ldt[NLDT];		/* local descriptor table */
1122#ifdef SMP
1123/* table descriptors - used to load tables by microp */
1124struct region_descriptor r_gdt, r_idt;
1125#endif
1126
1127#ifndef SMP
1128extern struct segment_descriptor common_tssd, *tss_gdt;
1129#endif
1130int private_tss;			/* flag indicating private tss */
1131
1132#if defined(I586_CPU) && !defined(NO_F00F_HACK)
1133extern int has_f00f_bug;
1134#endif
1135
1136static struct i386tss dblfault_tss;
1137static char dblfault_stack[PAGE_SIZE];
1138
1139extern  struct user *proc0paddr;
1140
1141
1142/* software prototypes -- in more palatable form */
1143struct soft_segment_descriptor gdt_segs[] = {
1144/* GNULL_SEL	0 Null Descriptor */
1145{	0x0,			/* segment base address  */
1146	0x0,			/* length */
1147	0,			/* segment type */
1148	0,			/* segment descriptor priority level */
1149	0,			/* segment descriptor present */
1150	0, 0,
1151	0,			/* default 32 vs 16 bit size */
1152	0  			/* limit granularity (byte/page units)*/ },
1153/* GCODE_SEL	1 Code Descriptor for kernel */
1154{	0x0,			/* segment base address  */
1155	0xfffff,		/* length - all address space */
1156	SDT_MEMERA,		/* segment type */
1157	0,			/* segment descriptor priority level */
1158	1,			/* segment descriptor present */
1159	0, 0,
1160	1,			/* default 32 vs 16 bit size */
1161	1  			/* limit granularity (byte/page units)*/ },
1162/* GDATA_SEL	2 Data Descriptor for kernel */
1163{	0x0,			/* segment base address  */
1164	0xfffff,		/* length - all address space */
1165	SDT_MEMRWA,		/* segment type */
1166	0,			/* segment descriptor priority level */
1167	1,			/* segment descriptor present */
1168	0, 0,
1169	1,			/* default 32 vs 16 bit size */
1170	1  			/* limit granularity (byte/page units)*/ },
1171/* GPRIV_SEL	3 SMP Per-Processor Private Data Descriptor */
1172{	0x0,			/* segment base address  */
1173	0xfffff,		/* length - all address space */
1174	SDT_MEMRWA,		/* segment type */
1175	0,			/* segment descriptor priority level */
1176	1,			/* segment descriptor present */
1177	0, 0,
1178	1,			/* default 32 vs 16 bit size */
1179	1  			/* limit granularity (byte/page units)*/ },
1180/* GPROC0_SEL	4 Proc 0 Tss Descriptor */
1181{
1182	0x0,			/* segment base address */
1183	sizeof(struct i386tss)-1,/* length - all address space */
1184	SDT_SYS386TSS,		/* segment type */
1185	0,			/* segment descriptor priority level */
1186	1,			/* segment descriptor present */
1187	0, 0,
1188	0,			/* unused - default 32 vs 16 bit size */
1189	0  			/* limit granularity (byte/page units)*/ },
1190/* GLDT_SEL	5 LDT Descriptor */
1191{	(int) ldt,		/* segment base address  */
1192	sizeof(ldt)-1,		/* length - all address space */
1193	SDT_SYSLDT,		/* segment type */
1194	SEL_UPL,		/* segment descriptor priority level */
1195	1,			/* segment descriptor present */
1196	0, 0,
1197	0,			/* unused - default 32 vs 16 bit size */
1198	0  			/* limit granularity (byte/page units)*/ },
1199/* GUSERLDT_SEL	6 User LDT Descriptor per process */
1200{	(int) ldt,		/* segment base address  */
1201	(512 * sizeof(union descriptor)-1),		/* length */
1202	SDT_SYSLDT,		/* segment type */
1203	0,			/* segment descriptor priority level */
1204	1,			/* segment descriptor present */
1205	0, 0,
1206	0,			/* unused - default 32 vs 16 bit size */
1207	0  			/* limit granularity (byte/page units)*/ },
1208/* GTGATE_SEL	7 Null Descriptor - Placeholder */
1209{	0x0,			/* segment base address  */
1210	0x0,			/* length - all address space */
1211	0,			/* segment type */
1212	0,			/* segment descriptor priority level */
1213	0,			/* segment descriptor present */
1214	0, 0,
1215	0,			/* default 32 vs 16 bit size */
1216	0  			/* limit granularity (byte/page units)*/ },
1217/* GBIOSLOWMEM_SEL 8 BIOS access to realmode segment 0x40, must be #8 in GDT */
1218{	0x400,			/* segment base address */
1219	0xfffff,		/* length */
1220	SDT_MEMRWA,		/* segment type */
1221	0,			/* segment descriptor priority level */
1222	1,			/* segment descriptor present */
1223	0, 0,
1224	1,			/* default 32 vs 16 bit size */
1225	1  			/* limit granularity (byte/page units)*/ },
1226/* GPANIC_SEL	9 Panic Tss Descriptor */
1227{	(int) &dblfault_tss,	/* segment base address  */
1228	sizeof(struct i386tss)-1,/* length - all address space */
1229	SDT_SYS386TSS,		/* segment type */
1230	0,			/* segment descriptor priority level */
1231	1,			/* segment descriptor present */
1232	0, 0,
1233	0,			/* unused - default 32 vs 16 bit size */
1234	0  			/* limit granularity (byte/page units)*/ },
1235/* GBIOSCODE32_SEL 10 BIOS 32-bit interface (32bit Code) */
1236{	0,			/* segment base address (overwritten)  */
1237	0xfffff,		/* length */
1238	SDT_MEMERA,		/* segment type */
1239	0,			/* segment descriptor priority level */
1240	1,			/* segment descriptor present */
1241	0, 0,
1242	0,			/* default 32 vs 16 bit size */
1243	1  			/* limit granularity (byte/page units)*/ },
1244/* GBIOSCODE16_SEL 11 BIOS 32-bit interface (16bit Code) */
1245{	0,			/* segment base address (overwritten)  */
1246	0xfffff,		/* length */
1247	SDT_MEMERA,		/* segment type */
1248	0,			/* segment descriptor priority level */
1249	1,			/* segment descriptor present */
1250	0, 0,
1251	0,			/* default 32 vs 16 bit size */
1252	1  			/* limit granularity (byte/page units)*/ },
1253/* GBIOSDATA_SEL 12 BIOS 32-bit interface (Data) */
1254{	0,			/* segment base address (overwritten) */
1255	0xfffff,		/* length */
1256	SDT_MEMRWA,		/* segment type */
1257	0,			/* segment descriptor priority level */
1258	1,			/* segment descriptor present */
1259	0, 0,
1260	1,			/* default 32 vs 16 bit size */
1261	1  			/* limit granularity (byte/page units)*/ },
1262/* GBIOSUTIL_SEL 13 BIOS 16-bit interface (Utility) */
1263{	0,			/* segment base address (overwritten) */
1264	0xfffff,		/* length */
1265	SDT_MEMRWA,		/* segment type */
1266	0,			/* segment descriptor priority level */
1267	1,			/* segment descriptor present */
1268	0, 0,
1269	0,			/* default 32 vs 16 bit size */
1270	1  			/* limit granularity (byte/page units)*/ },
1271/* GBIOSARGS_SEL 14 BIOS 16-bit interface (Arguments) */
1272{	0,			/* segment base address (overwritten) */
1273	0xfffff,		/* length */
1274	SDT_MEMRWA,		/* segment type */
1275	0,			/* segment descriptor priority level */
1276	1,			/* segment descriptor present */
1277	0, 0,
1278	0,			/* default 32 vs 16 bit size */
1279	1  			/* limit granularity (byte/page units)*/ },
1280};
1281
1282static struct soft_segment_descriptor ldt_segs[] = {
1283	/* Null Descriptor - overwritten by call gate */
1284{	0x0,			/* segment base address  */
1285	0x0,			/* length - all address space */
1286	0,			/* segment type */
1287	0,			/* segment descriptor priority level */
1288	0,			/* segment descriptor present */
1289	0, 0,
1290	0,			/* default 32 vs 16 bit size */
1291	0  			/* limit granularity (byte/page units)*/ },
1292	/* Null Descriptor - overwritten by call gate */
1293{	0x0,			/* segment base address  */
1294	0x0,			/* length - all address space */
1295	0,			/* segment type */
1296	0,			/* segment descriptor priority level */
1297	0,			/* segment descriptor present */
1298	0, 0,
1299	0,			/* default 32 vs 16 bit size */
1300	0  			/* limit granularity (byte/page units)*/ },
1301	/* Null Descriptor - overwritten by call gate */
1302{	0x0,			/* segment base address  */
1303	0x0,			/* length - all address space */
1304	0,			/* segment type */
1305	0,			/* segment descriptor priority level */
1306	0,			/* segment descriptor present */
1307	0, 0,
1308	0,			/* default 32 vs 16 bit size */
1309	0  			/* limit granularity (byte/page units)*/ },
1310	/* Code Descriptor for user */
1311{	0x0,			/* segment base address  */
1312	0xfffff,		/* length - all address space */
1313	SDT_MEMERA,		/* segment type */
1314	SEL_UPL,		/* segment descriptor priority level */
1315	1,			/* segment descriptor present */
1316	0, 0,
1317	1,			/* default 32 vs 16 bit size */
1318	1  			/* limit granularity (byte/page units)*/ },
1319	/* Null Descriptor - overwritten by call gate */
1320{	0x0,			/* segment base address  */
1321	0x0,			/* length - all address space */
1322	0,			/* segment type */
1323	0,			/* segment descriptor priority level */
1324	0,			/* segment descriptor present */
1325	0, 0,
1326	0,			/* default 32 vs 16 bit size */
1327	0  			/* limit granularity (byte/page units)*/ },
1328	/* Data Descriptor for user */
1329{	0x0,			/* segment base address  */
1330	0xfffff,		/* length - all address space */
1331	SDT_MEMRWA,		/* segment type */
1332	SEL_UPL,		/* segment descriptor priority level */
1333	1,			/* segment descriptor present */
1334	0, 0,
1335	1,			/* default 32 vs 16 bit size */
1336	1  			/* limit granularity (byte/page units)*/ },
1337};
1338
1339void
1340setidt(idx, func, typ, dpl, selec)
1341	int idx;
1342	inthand_t *func;
1343	int typ;
1344	int dpl;
1345	int selec;
1346{
1347	struct gate_descriptor *ip;
1348
1349	ip = idt + idx;
1350	ip->gd_looffset = (int)func;
1351	ip->gd_selector = selec;
1352	ip->gd_stkcpy = 0;
1353	ip->gd_xx = 0;
1354	ip->gd_type = typ;
1355	ip->gd_dpl = dpl;
1356	ip->gd_p = 1;
1357	ip->gd_hioffset = ((int)func)>>16 ;
1358}
1359
1360#define	IDTVEC(name)	__CONCAT(X,name)
1361
1362extern inthand_t
1363	IDTVEC(div), IDTVEC(dbg), IDTVEC(nmi), IDTVEC(bpt), IDTVEC(ofl),
1364	IDTVEC(bnd), IDTVEC(ill), IDTVEC(dna), IDTVEC(fpusegm),
1365	IDTVEC(tss), IDTVEC(missing), IDTVEC(stk), IDTVEC(prot),
1366	IDTVEC(page), IDTVEC(mchk), IDTVEC(rsvd), IDTVEC(fpu), IDTVEC(align),
1367	IDTVEC(syscall), IDTVEC(int0x80_syscall);
1368
1369void
1370sdtossd(sd, ssd)
1371	struct segment_descriptor *sd;
1372	struct soft_segment_descriptor *ssd;
1373{
1374	ssd->ssd_base  = (sd->sd_hibase << 24) | sd->sd_lobase;
1375	ssd->ssd_limit = (sd->sd_hilimit << 16) | sd->sd_lolimit;
1376	ssd->ssd_type  = sd->sd_type;
1377	ssd->ssd_dpl   = sd->sd_dpl;
1378	ssd->ssd_p     = sd->sd_p;
1379	ssd->ssd_def32 = sd->sd_def32;
1380	ssd->ssd_gran  = sd->sd_gran;
1381}
1382
1383#define PHYSMAP_SIZE	(2 * 8)
1384
1385/*
1386 * Populate the (physmap) array with base/bound pairs describing the
1387 * available physical memory in the system, then test this memory and
1388 * build the phys_avail array describing the actually-available memory.
1389 *
1390 * If we cannot accurately determine the physical memory map, then use
1391 * value from the 0xE801 call, and failing that, the RTC.
1392 *
1393 * Total memory size may be set by the kernel environment variable
1394 * hw.physmem or the compile-time define MAXMEM.
1395 */
1396static void
1397getmemsize(int first)
1398{
1399	int i, physmap_idx, pa_indx;
1400	u_int basemem, extmem;
1401	struct vm86frame vmf;
1402	struct vm86context vmc;
1403	vm_offset_t pa, physmap[PHYSMAP_SIZE];
1404	pt_entry_t pte;
1405	const char *cp;
1406	struct {
1407		u_int64_t base;
1408		u_int64_t length;
1409		u_int32_t type;
1410	} *smap;
1411
1412	bzero(&vmf, sizeof(struct vm86frame));
1413	bzero(physmap, sizeof(physmap));
1414
1415	/*
1416	 * Perform "base memory" related probes & setup
1417	 */
1418	vm86_intcall(0x12, &vmf);
1419	basemem = vmf.vmf_ax;
1420	if (basemem > 640) {
1421		printf("Preposterous BIOS basemem of %uK, truncating to 640K\n",
1422			basemem);
1423		basemem = 640;
1424	}
1425
1426	/*
1427	 * XXX if biosbasemem is now < 640, there is a `hole'
1428	 * between the end of base memory and the start of
1429	 * ISA memory.  The hole may be empty or it may
1430	 * contain BIOS code or data.  Map it read/write so
1431	 * that the BIOS can write to it.  (Memory from 0 to
1432	 * the physical end of the kernel is mapped read-only
1433	 * to begin with and then parts of it are remapped.
1434	 * The parts that aren't remapped form holes that
1435	 * remain read-only and are unused by the kernel.
1436	 * The base memory area is below the physical end of
1437	 * the kernel and right now forms a read-only hole.
1438	 * The part of it from PAGE_SIZE to
1439	 * (trunc_page(biosbasemem * 1024) - 1) will be
1440	 * remapped and used by the kernel later.)
1441	 *
1442	 * This code is similar to the code used in
1443	 * pmap_mapdev, but since no memory needs to be
1444	 * allocated we simply change the mapping.
1445	 */
1446	for (pa = trunc_page(basemem * 1024);
1447	     pa < ISA_HOLE_START; pa += PAGE_SIZE) {
1448		pte = (pt_entry_t)vtopte(pa + KERNBASE);
1449		*pte = pa | PG_RW | PG_V;
1450	}
1451
1452	/*
1453	 * if basemem != 640, map pages r/w into vm86 page table so
1454	 * that the bios can scribble on it.
1455	 */
1456	pte = (pt_entry_t)vm86paddr;
1457	for (i = basemem / 4; i < 160; i++)
1458		pte[i] = (i << PAGE_SHIFT) | PG_V | PG_RW | PG_U;
1459
1460	/*
1461	 * map page 1 R/W into the kernel page table so we can use it
1462	 * as a buffer.  The kernel will unmap this page later.
1463	 */
1464	pte = (pt_entry_t)vtopte(KERNBASE + (1 << PAGE_SHIFT));
1465	*pte = (1 << PAGE_SHIFT) | PG_RW | PG_V;
1466
1467	/*
1468	 * get memory map with INT 15:E820
1469	 */
1470#define SMAPSIZ 	sizeof(*smap)
1471#define SMAP_SIG	0x534D4150			/* 'SMAP' */
1472
1473	vmc.npages = 0;
1474	smap = (void *)vm86_addpage(&vmc, 1, KERNBASE + (1 << PAGE_SHIFT));
1475	vm86_getptr(&vmc, (vm_offset_t)smap, &vmf.vmf_es, &vmf.vmf_di);
1476
1477	physmap_idx = 0;
1478	vmf.vmf_ebx = 0;
1479	do {
1480		vmf.vmf_eax = 0xE820;
1481		vmf.vmf_edx = SMAP_SIG;
1482		vmf.vmf_ecx = SMAPSIZ;
1483		i = vm86_datacall(0x15, &vmf, &vmc);
1484		if (i || vmf.vmf_eax != SMAP_SIG)
1485			break;
1486		if (boothowto & RB_VERBOSE)
1487			printf("SMAP type=%02x base=%08x %08x len=%08x %08x\n",
1488				smap->type,
1489				*(u_int32_t *)((char *)&smap->base + 4),
1490				(u_int32_t)smap->base,
1491				*(u_int32_t *)((char *)&smap->length + 4),
1492				(u_int32_t)smap->length);
1493
1494		if (smap->type != 0x01)
1495			goto next_run;
1496
1497		if (smap->length == 0)
1498			goto next_run;
1499
1500		if (smap->base >= 0xffffffff) {
1501			printf("%uK of memory above 4GB ignored\n",
1502			    (u_int)(smap->length / 1024));
1503			goto next_run;
1504		}
1505
1506		for (i = 0; i <= physmap_idx; i += 2) {
1507			if (smap->base < physmap[i + 1]) {
1508				if (boothowto & RB_VERBOSE)
1509					printf(
1510	"Overlapping or non-montonic memory region, ignoring second region\n");
1511				goto next_run;
1512			}
1513		}
1514
1515		if (smap->base == physmap[physmap_idx + 1]) {
1516			physmap[physmap_idx + 1] += smap->length;
1517			goto next_run;
1518		}
1519
1520		physmap_idx += 2;
1521		if (physmap_idx == PHYSMAP_SIZE) {
1522			printf(
1523		"Too many segments in the physical address map, giving up\n");
1524			break;
1525		}
1526		physmap[physmap_idx] = smap->base;
1527		physmap[physmap_idx + 1] = smap->base + smap->length;
1528next_run:
1529	} while (vmf.vmf_ebx != 0);
1530
1531	if (physmap[1] != 0)
1532		goto physmap_done;
1533
1534	/*
1535	 * If we failed above, try memory map with INT 15:E801
1536	 */
1537	vmf.vmf_ax = 0xE801;
1538	if (vm86_intcall(0x15, &vmf) == 0) {
1539		extmem = vmf.vmf_cx + vmf.vmf_dx * 64;
1540	} else {
1541#if 0
1542		vmf.vmf_ah = 0x88;
1543		vm86_intcall(0x15, &vmf);
1544		extmem = vmf.vmf_ax;
1545#else
1546		/*
1547		 * Prefer the RTC value for extended memory.
1548		 */
1549		extmem = rtcin(RTC_EXTLO) + (rtcin(RTC_EXTHI) << 8);
1550#endif
1551	}
1552
1553	/*
1554	 * Special hack for chipsets that still remap the 384k hole when
1555	 * there's 16MB of memory - this really confuses people that
1556	 * are trying to use bus mastering ISA controllers with the
1557	 * "16MB limit"; they only have 16MB, but the remapping puts
1558	 * them beyond the limit.
1559	 *
1560	 * If extended memory is between 15-16MB (16-17MB phys address range),
1561	 *	chop it to 15MB.
1562	 */
1563	if ((extmem > 15 * 1024) && (extmem < 16 * 1024))
1564		extmem = 15 * 1024;
1565
1566	physmap[0] = 0;
1567	physmap[1] = basemem * 1024;
1568	physmap_idx = 2;
1569	physmap[physmap_idx] = 0x100000;
1570	physmap[physmap_idx + 1] = physmap[physmap_idx] + extmem * 1024;
1571
1572physmap_done:
1573	/*
1574	 * Now, physmap contains a map of physical memory.
1575	 */
1576
1577#ifdef SMP
1578	/* make hole for AP bootstrap code */
1579	physmap[1] = mp_bootaddress(physmap[1] / 1024);
1580
1581	/* look for the MP hardware - needed for apic addresses */
1582	mp_probe();
1583#endif
1584
1585	/*
1586	 * Maxmem isn't the "maximum memory", it's one larger than the
1587	 * highest page of the physical address space.  It should be
1588	 * called something like "Maxphyspage".  We may adjust this
1589	 * based on ``hw.physmem'' and the results of the memory test.
1590	 */
1591	Maxmem = atop(physmap[physmap_idx + 1]);
1592
1593#ifdef MAXMEM
1594	Maxmem = MAXMEM / 4;
1595#endif
1596
1597	/*
1598	 * hw.maxmem is a size in bytes; we also allow k, m, and g suffixes
1599	 * for the appropriate modifiers.  This overrides MAXMEM.
1600	 */
1601	if ((cp = getenv("hw.physmem")) != NULL) {
1602		u_int64_t AllowMem, sanity;
1603		char *ep;
1604
1605		sanity = AllowMem = strtouq(cp, &ep, 0);
1606		if ((ep != cp) && (*ep != 0)) {
1607			switch(*ep) {
1608			case 'g':
1609			case 'G':
1610				AllowMem <<= 10;
1611			case 'm':
1612			case 'M':
1613				AllowMem <<= 10;
1614			case 'k':
1615			case 'K':
1616				AllowMem <<= 10;
1617				break;
1618			default:
1619				AllowMem = sanity = 0;
1620			}
1621			if (AllowMem < sanity)
1622				AllowMem = 0;
1623		}
1624		if (AllowMem == 0)
1625			printf("Ignoring invalid memory size of '%s'\n", cp);
1626		else
1627			Maxmem = atop(AllowMem);
1628	}
1629
1630	if (atop(physmap[physmap_idx + 1]) != Maxmem &&
1631	    (boothowto & RB_VERBOSE))
1632		printf("Physical memory use set to %uK\n", Maxmem * 4);
1633
1634	/*
1635	 * If Maxmem has been increased beyond what the system has detected,
1636	 * extend the last memory segment to the new limit.
1637	 */
1638	if (atop(physmap[physmap_idx + 1]) < Maxmem)
1639		physmap[physmap_idx + 1] = ptoa(Maxmem);
1640
1641	/* call pmap initialization to make new kernel address space */
1642	pmap_bootstrap(first, 0);
1643
1644	/*
1645	 * Size up each available chunk of physical memory.
1646	 */
1647	physmap[0] = PAGE_SIZE;		/* mask off page 0 */
1648	pa_indx = 0;
1649	phys_avail[pa_indx++] = physmap[0];
1650	phys_avail[pa_indx] = physmap[0];
1651#if 0
1652	pte = (pt_entry_t)vtopte(KERNBASE);
1653#else
1654	pte = (pt_entry_t)CMAP1;
1655#endif
1656
1657	/*
1658	 * physmap is in bytes, so when converting to page boundaries,
1659	 * round up the start address and round down the end address.
1660	 */
1661	for (i = 0; i <= physmap_idx; i += 2) {
1662		vm_offset_t end;
1663
1664		end = ptoa(Maxmem);
1665		if (physmap[i + 1] < end)
1666			end = trunc_page(physmap[i + 1]);
1667		for (pa = round_page(physmap[i]); pa < end; pa += PAGE_SIZE) {
1668			int tmp, page_bad;
1669#if 0
1670			int *ptr = 0;
1671#else
1672			int *ptr = (int *)CADDR1;
1673#endif
1674
1675			/*
1676			 * block out kernel memory as not available.
1677			 */
1678			if (pa >= 0x100000 && pa < first)
1679				continue;
1680
1681			page_bad = FALSE;
1682
1683			/*
1684			 * map page into kernel: valid, read/write,non-cacheable
1685			 */
1686			*pte = pa | PG_V | PG_RW | PG_N;
1687			invltlb();
1688
1689			tmp = *(int *)ptr;
1690			/*
1691			 * Test for alternating 1's and 0's
1692			 */
1693			*(volatile int *)ptr = 0xaaaaaaaa;
1694			if (*(volatile int *)ptr != 0xaaaaaaaa) {
1695				page_bad = TRUE;
1696			}
1697			/*
1698			 * Test for alternating 0's and 1's
1699			 */
1700			*(volatile int *)ptr = 0x55555555;
1701			if (*(volatile int *)ptr != 0x55555555) {
1702			page_bad = TRUE;
1703			}
1704			/*
1705			 * Test for all 1's
1706			 */
1707			*(volatile int *)ptr = 0xffffffff;
1708			if (*(volatile int *)ptr != 0xffffffff) {
1709				page_bad = TRUE;
1710			}
1711			/*
1712			 * Test for all 0's
1713			 */
1714			*(volatile int *)ptr = 0x0;
1715			if (*(volatile int *)ptr != 0x0) {
1716				page_bad = TRUE;
1717			}
1718			/*
1719			 * Restore original value.
1720			 */
1721			*(int *)ptr = tmp;
1722
1723			/*
1724			 * Adjust array of valid/good pages.
1725			 */
1726			if (page_bad == TRUE) {
1727				continue;
1728			}
1729			/*
1730			 * If this good page is a continuation of the
1731			 * previous set of good pages, then just increase
1732			 * the end pointer. Otherwise start a new chunk.
1733			 * Note that "end" points one higher than end,
1734			 * making the range >= start and < end.
1735			 * If we're also doing a speculative memory
1736			 * test and we at or past the end, bump up Maxmem
1737			 * so that we keep going. The first bad page
1738			 * will terminate the loop.
1739			 */
1740			if (phys_avail[pa_indx] == pa) {
1741				phys_avail[pa_indx] += PAGE_SIZE;
1742			} else {
1743				pa_indx++;
1744				if (pa_indx == PHYS_AVAIL_ARRAY_END) {
1745					printf("Too many holes in the physical address space, giving up\n");
1746					pa_indx--;
1747					break;
1748				}
1749				phys_avail[pa_indx++] = pa;	/* start */
1750				phys_avail[pa_indx] = pa + PAGE_SIZE;	/* end */
1751			}
1752			physmem++;
1753		}
1754	}
1755	*pte = 0;
1756	invltlb();
1757
1758	/*
1759	 * XXX
1760	 * The last chunk must contain at least one page plus the message
1761	 * buffer to avoid complicating other code (message buffer address
1762	 * calculation, etc.).
1763	 */
1764	while (phys_avail[pa_indx - 1] + PAGE_SIZE +
1765	    round_page(MSGBUF_SIZE) >= phys_avail[pa_indx]) {
1766		physmem -= atop(phys_avail[pa_indx] - phys_avail[pa_indx - 1]);
1767		phys_avail[pa_indx--] = 0;
1768		phys_avail[pa_indx--] = 0;
1769	}
1770
1771	Maxmem = atop(phys_avail[pa_indx]);
1772
1773	/* Trim off space for the message buffer. */
1774	phys_avail[pa_indx] -= round_page(MSGBUF_SIZE);
1775
1776	avail_end = phys_avail[pa_indx];
1777}
1778
1779void
1780init386(first)
1781	int first;
1782{
1783	int x;
1784	struct gate_descriptor *gdp;
1785	int gsel_tss;
1786#ifndef SMP
1787	/* table descriptors - used to load tables by microp */
1788	struct region_descriptor r_gdt, r_idt;
1789#endif
1790	int off;
1791
1792	/*
1793	 * Prevent lowering of the ipl if we call tsleep() early.
1794	 */
1795	safepri = cpl;
1796
1797	proc0.p_addr = proc0paddr;
1798
1799	atdevbase = ISA_HOLE_START + KERNBASE;
1800
1801	if (bootinfo.bi_modulep) {
1802		preload_metadata = (caddr_t)bootinfo.bi_modulep + KERNBASE;
1803		preload_bootstrap_relocate(KERNBASE);
1804	}
1805	if (bootinfo.bi_envp)
1806		kern_envp = (caddr_t)bootinfo.bi_envp + KERNBASE;
1807
1808	/*
1809	 * make gdt memory segments, the code segment goes up to end of the
1810	 * page with etext in it, the data segment goes to the end of
1811	 * the address space
1812	 */
1813	/*
1814	 * XXX text protection is temporarily (?) disabled.  The limit was
1815	 * i386_btop(round_page(etext)) - 1.
1816	 */
1817	gdt_segs[GCODE_SEL].ssd_limit = i386_btop(0) - 1;
1818	gdt_segs[GDATA_SEL].ssd_limit = i386_btop(0) - 1;
1819#ifdef SMP
1820	gdt_segs[GPRIV_SEL].ssd_limit =
1821		i386_btop(sizeof(struct privatespace)) - 1;
1822	gdt_segs[GPRIV_SEL].ssd_base = (int) &SMP_prvspace[0];
1823	gdt_segs[GPROC0_SEL].ssd_base =
1824		(int) &SMP_prvspace[0].globaldata.gd_common_tss;
1825	SMP_prvspace[0].globaldata.gd_prvspace = &SMP_prvspace[0];
1826#else
1827	gdt_segs[GPRIV_SEL].ssd_limit = i386_btop(0) - 1;
1828	gdt_segs[GPROC0_SEL].ssd_base = (int) &common_tss;
1829#endif
1830
1831	for (x = 0; x < NGDT; x++) {
1832#ifdef BDE_DEBUGGER
1833		/* avoid overwriting db entries with APM ones */
1834		if (x >= GAPMCODE32_SEL && x <= GAPMDATA_SEL)
1835			continue;
1836#endif
1837		ssdtosd(&gdt_segs[x], &gdt[x].sd);
1838	}
1839
1840	r_gdt.rd_limit = NGDT * sizeof(gdt[0]) - 1;
1841	r_gdt.rd_base =  (int) gdt;
1842	lgdt(&r_gdt);
1843
1844	/* make ldt memory segments */
1845	/*
1846	 * The data segment limit must not cover the user area because we
1847	 * don't want the user area to be writable in copyout() etc. (page
1848	 * level protection is lost in kernel mode on 386's).  Also, we
1849	 * don't want the user area to be writable directly (page level
1850	 * protection of the user area is not available on 486's with
1851	 * CR0_WP set, because there is no user-read/kernel-write mode).
1852	 *
1853	 * XXX - VM_MAXUSER_ADDRESS is an end address, not a max.  And it
1854	 * should be spelled ...MAX_USER...
1855	 */
1856#define VM_END_USER_RW_ADDRESS	VM_MAXUSER_ADDRESS
1857	/*
1858	 * The code segment limit has to cover the user area until we move
1859	 * the signal trampoline out of the user area.  This is safe because
1860	 * the code segment cannot be written to directly.
1861	 */
1862#define VM_END_USER_R_ADDRESS	(VM_END_USER_RW_ADDRESS + UPAGES * PAGE_SIZE)
1863	ldt_segs[LUCODE_SEL].ssd_limit = i386_btop(VM_END_USER_R_ADDRESS) - 1;
1864	ldt_segs[LUDATA_SEL].ssd_limit = i386_btop(VM_END_USER_RW_ADDRESS) - 1;
1865	for (x = 0; x < sizeof ldt_segs / sizeof ldt_segs[0]; x++)
1866		ssdtosd(&ldt_segs[x], &ldt[x].sd);
1867
1868	_default_ldt = GSEL(GLDT_SEL, SEL_KPL);
1869	lldt(_default_ldt);
1870#ifdef USER_LDT
1871	currentldt = _default_ldt;
1872#endif
1873
1874	/* exceptions */
1875	for (x = 0; x < NIDT; x++)
1876		setidt(x, &IDTVEC(rsvd), SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1877	setidt(0, &IDTVEC(div),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1878	setidt(1, &IDTVEC(dbg),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1879	setidt(2, &IDTVEC(nmi),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1880 	setidt(3, &IDTVEC(bpt),  SDT_SYS386TGT, SEL_UPL, GSEL(GCODE_SEL, SEL_KPL));
1881	setidt(4, &IDTVEC(ofl),  SDT_SYS386TGT, SEL_UPL, GSEL(GCODE_SEL, SEL_KPL));
1882	setidt(5, &IDTVEC(bnd),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1883	setidt(6, &IDTVEC(ill),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1884	setidt(7, &IDTVEC(dna),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1885	setidt(8, 0,  SDT_SYSTASKGT, SEL_KPL, GSEL(GPANIC_SEL, SEL_KPL));
1886	setidt(9, &IDTVEC(fpusegm),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1887	setidt(10, &IDTVEC(tss),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1888	setidt(11, &IDTVEC(missing),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1889	setidt(12, &IDTVEC(stk),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1890	setidt(13, &IDTVEC(prot),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1891	setidt(14, &IDTVEC(page),  SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1892	setidt(15, &IDTVEC(rsvd),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1893	setidt(16, &IDTVEC(fpu),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1894	setidt(17, &IDTVEC(align), SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1895	setidt(18, &IDTVEC(mchk),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1896 	setidt(0x80, &IDTVEC(int0x80_syscall),
1897			SDT_SYS386TGT, SEL_UPL, GSEL(GCODE_SEL, SEL_KPL));
1898
1899	r_idt.rd_limit = sizeof(idt0) - 1;
1900	r_idt.rd_base = (int) idt;
1901	lidt(&r_idt);
1902
1903	/*
1904	 * Initialize the console before we print anything out.
1905	 */
1906	cninit();
1907
1908#include	"isa.h"
1909#if	NISA >0
1910	isa_defaultirq();
1911#endif
1912	rand_initialize();
1913
1914#ifdef DDB
1915	kdb_init();
1916	if (boothowto & RB_KDB)
1917		Debugger("Boot flags requested debugger");
1918#endif
1919
1920	finishidentcpu();	/* Final stage of CPU initialization */
1921	setidt(6, &IDTVEC(ill),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1922	setidt(13, &IDTVEC(prot),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1923	initializecpu();	/* Initialize CPU registers */
1924
1925	/* make an initial tss so cpu can get interrupt stack on syscall! */
1926	common_tss.tss_esp0 = (int) proc0.p_addr + UPAGES*PAGE_SIZE - 16;
1927	common_tss.tss_ss0 = GSEL(GDATA_SEL, SEL_KPL) ;
1928	gsel_tss = GSEL(GPROC0_SEL, SEL_KPL);
1929	private_tss = 0;
1930	tss_gdt = &gdt[GPROC0_SEL].sd;
1931	common_tssd = *tss_gdt;
1932	common_tss.tss_ioopt = (sizeof common_tss) << 16;
1933	ltr(gsel_tss);
1934
1935	dblfault_tss.tss_esp = dblfault_tss.tss_esp0 = dblfault_tss.tss_esp1 =
1936	    dblfault_tss.tss_esp2 = (int) &dblfault_stack[sizeof(dblfault_stack)];
1937	dblfault_tss.tss_ss = dblfault_tss.tss_ss0 = dblfault_tss.tss_ss1 =
1938	    dblfault_tss.tss_ss2 = GSEL(GDATA_SEL, SEL_KPL);
1939	dblfault_tss.tss_cr3 = (int)IdlePTD;
1940	dblfault_tss.tss_eip = (int) dblfault_handler;
1941	dblfault_tss.tss_eflags = PSL_KERNEL;
1942	dblfault_tss.tss_ds = dblfault_tss.tss_es =
1943	    dblfault_tss.tss_gs = GSEL(GDATA_SEL, SEL_KPL);
1944	dblfault_tss.tss_fs = GSEL(GPRIV_SEL, SEL_KPL);
1945	dblfault_tss.tss_cs = GSEL(GCODE_SEL, SEL_KPL);
1946	dblfault_tss.tss_ldt = GSEL(GLDT_SEL, SEL_KPL);
1947
1948	vm86_initialize();
1949	getmemsize(first);
1950
1951	/* now running on new page tables, configured,and u/iom is accessible */
1952
1953	/* Map the message buffer. */
1954	for (off = 0; off < round_page(MSGBUF_SIZE); off += PAGE_SIZE)
1955		pmap_kenter((vm_offset_t)msgbufp + off, avail_end + off);
1956
1957	msgbufinit(msgbufp, MSGBUF_SIZE);
1958
1959	/* make a call gate to reenter kernel with */
1960	gdp = &ldt[LSYS5CALLS_SEL].gd;
1961
1962	x = (int) &IDTVEC(syscall);
1963	gdp->gd_looffset = x++;
1964	gdp->gd_selector = GSEL(GCODE_SEL,SEL_KPL);
1965	gdp->gd_stkcpy = 1;
1966	gdp->gd_type = SDT_SYS386CGT;
1967	gdp->gd_dpl = SEL_UPL;
1968	gdp->gd_p = 1;
1969	gdp->gd_hioffset = ((int) &IDTVEC(syscall)) >>16;
1970
1971	/* XXX does this work? */
1972	ldt[LBSDICALLS_SEL] = ldt[LSYS5CALLS_SEL];
1973	ldt[LSOL26CALLS_SEL] = ldt[LSYS5CALLS_SEL];
1974
1975	/* transfer to user mode */
1976
1977	_ucodesel = LSEL(LUCODE_SEL, SEL_UPL);
1978	_udatasel = LSEL(LUDATA_SEL, SEL_UPL);
1979
1980	/* setup proc 0's pcb */
1981	proc0.p_addr->u_pcb.pcb_flags = 0;
1982	proc0.p_addr->u_pcb.pcb_cr3 = (int)IdlePTD;
1983#ifdef SMP
1984	proc0.p_addr->u_pcb.pcb_mpnest = 1;
1985#endif
1986	proc0.p_addr->u_pcb.pcb_ext = 0;
1987}
1988
1989#if defined(I586_CPU) && !defined(NO_F00F_HACK)
1990static void f00f_hack(void *unused);
1991SYSINIT(f00f_hack, SI_SUB_INTRINSIC, SI_ORDER_FIRST, f00f_hack, NULL);
1992
1993static void
1994f00f_hack(void *unused) {
1995	struct gate_descriptor *new_idt;
1996#ifndef SMP
1997	struct region_descriptor r_idt;
1998#endif
1999	vm_offset_t tmp;
2000
2001	if (!has_f00f_bug)
2002		return;
2003
2004	printf("Intel Pentium detected, installing workaround for F00F bug\n");
2005
2006	r_idt.rd_limit = sizeof(idt0) - 1;
2007
2008	tmp = kmem_alloc(kernel_map, PAGE_SIZE * 2);
2009	if (tmp == 0)
2010		panic("kmem_alloc returned 0");
2011	if (((unsigned int)tmp & (PAGE_SIZE-1)) != 0)
2012		panic("kmem_alloc returned non-page-aligned memory");
2013	/* Put the first seven entries in the lower page */
2014	new_idt = (struct gate_descriptor*)(tmp + PAGE_SIZE - (7*8));
2015	bcopy(idt, new_idt, sizeof(idt0));
2016	r_idt.rd_base = (int)new_idt;
2017	lidt(&r_idt);
2018	idt = new_idt;
2019	if (vm_map_protect(kernel_map, tmp, tmp + PAGE_SIZE,
2020			   VM_PROT_READ, FALSE) != KERN_SUCCESS)
2021		panic("vm_map_protect failed");
2022	return;
2023}
2024#endif /* defined(I586_CPU) && !NO_F00F_HACK */
2025
2026int
2027ptrace_set_pc(p, addr)
2028	struct proc *p;
2029	unsigned long addr;
2030{
2031	p->p_md.md_regs->tf_eip = addr;
2032	return (0);
2033}
2034
2035int
2036ptrace_single_step(p)
2037	struct proc *p;
2038{
2039	p->p_md.md_regs->tf_eflags |= PSL_T;
2040	return (0);
2041}
2042
2043int ptrace_read_u_check(p, addr, len)
2044	struct proc *p;
2045	vm_offset_t addr;
2046	size_t len;
2047{
2048	vm_offset_t gap;
2049
2050	if ((vm_offset_t) (addr + len) < addr)
2051		return EPERM;
2052	if ((vm_offset_t) (addr + len) <= sizeof(struct user))
2053		return 0;
2054
2055	gap = (char *) p->p_md.md_regs - (char *) p->p_addr;
2056
2057	if ((vm_offset_t) addr < gap)
2058		return EPERM;
2059	if ((vm_offset_t) (addr + len) <=
2060	    (vm_offset_t) (gap + sizeof(struct trapframe)))
2061		return 0;
2062	return EPERM;
2063}
2064
2065int ptrace_write_u(p, off, data)
2066	struct proc *p;
2067	vm_offset_t off;
2068	long data;
2069{
2070	struct trapframe frame_copy;
2071	vm_offset_t min;
2072	struct trapframe *tp;
2073
2074	/*
2075	 * Privileged kernel state is scattered all over the user area.
2076	 * Only allow write access to parts of regs and to fpregs.
2077	 */
2078	min = (char *)p->p_md.md_regs - (char *)p->p_addr;
2079	if (off >= min && off <= min + sizeof(struct trapframe) - sizeof(int)) {
2080		tp = p->p_md.md_regs;
2081		frame_copy = *tp;
2082		*(int *)((char *)&frame_copy + (off - min)) = data;
2083		if (!EFL_SECURE(frame_copy.tf_eflags, tp->tf_eflags) ||
2084		    !CS_SECURE(frame_copy.tf_cs))
2085			return (EINVAL);
2086		*(int*)((char *)p->p_addr + off) = data;
2087		return (0);
2088	}
2089	min = offsetof(struct user, u_pcb) + offsetof(struct pcb, pcb_savefpu);
2090	if (off >= min && off <= min + sizeof(struct save87) - sizeof(int)) {
2091		*(int*)((char *)p->p_addr + off) = data;
2092		return (0);
2093	}
2094	return (EFAULT);
2095}
2096
2097int
2098fill_regs(p, regs)
2099	struct proc *p;
2100	struct reg *regs;
2101{
2102	struct pcb *pcb;
2103	struct trapframe *tp;
2104
2105	tp = p->p_md.md_regs;
2106	regs->r_fs = tp->tf_fs;
2107	regs->r_es = tp->tf_es;
2108	regs->r_ds = tp->tf_ds;
2109	regs->r_edi = tp->tf_edi;
2110	regs->r_esi = tp->tf_esi;
2111	regs->r_ebp = tp->tf_ebp;
2112	regs->r_ebx = tp->tf_ebx;
2113	regs->r_edx = tp->tf_edx;
2114	regs->r_ecx = tp->tf_ecx;
2115	regs->r_eax = tp->tf_eax;
2116	regs->r_eip = tp->tf_eip;
2117	regs->r_cs = tp->tf_cs;
2118	regs->r_eflags = tp->tf_eflags;
2119	regs->r_esp = tp->tf_esp;
2120	regs->r_ss = tp->tf_ss;
2121	pcb = &p->p_addr->u_pcb;
2122	regs->r_gs = pcb->pcb_gs;
2123	return (0);
2124}
2125
2126int
2127set_regs(p, regs)
2128	struct proc *p;
2129	struct reg *regs;
2130{
2131	struct pcb *pcb;
2132	struct trapframe *tp;
2133
2134	tp = p->p_md.md_regs;
2135	if (!EFL_SECURE(regs->r_eflags, tp->tf_eflags) ||
2136	    !CS_SECURE(regs->r_cs))
2137		return (EINVAL);
2138	tp->tf_fs = regs->r_fs;
2139	tp->tf_es = regs->r_es;
2140	tp->tf_ds = regs->r_ds;
2141	tp->tf_edi = regs->r_edi;
2142	tp->tf_esi = regs->r_esi;
2143	tp->tf_ebp = regs->r_ebp;
2144	tp->tf_ebx = regs->r_ebx;
2145	tp->tf_edx = regs->r_edx;
2146	tp->tf_ecx = regs->r_ecx;
2147	tp->tf_eax = regs->r_eax;
2148	tp->tf_eip = regs->r_eip;
2149	tp->tf_cs = regs->r_cs;
2150	tp->tf_eflags = regs->r_eflags;
2151	tp->tf_esp = regs->r_esp;
2152	tp->tf_ss = regs->r_ss;
2153	pcb = &p->p_addr->u_pcb;
2154	pcb->pcb_gs = regs->r_gs;
2155	return (0);
2156}
2157
2158int
2159fill_fpregs(p, fpregs)
2160	struct proc *p;
2161	struct fpreg *fpregs;
2162{
2163	bcopy(&p->p_addr->u_pcb.pcb_savefpu, fpregs, sizeof *fpregs);
2164	return (0);
2165}
2166
2167int
2168set_fpregs(p, fpregs)
2169	struct proc *p;
2170	struct fpreg *fpregs;
2171{
2172	bcopy(fpregs, &p->p_addr->u_pcb.pcb_savefpu, sizeof *fpregs);
2173	return (0);
2174}
2175
2176int
2177fill_dbregs(p, dbregs)
2178	struct proc *p;
2179	struct dbreg *dbregs;
2180{
2181	struct pcb *pcb;
2182
2183	pcb = &p->p_addr->u_pcb;
2184	dbregs->dr0 = pcb->pcb_dr0;
2185	dbregs->dr1 = pcb->pcb_dr1;
2186	dbregs->dr2 = pcb->pcb_dr2;
2187	dbregs->dr3 = pcb->pcb_dr3;
2188	dbregs->dr4 = 0;
2189	dbregs->dr5 = 0;
2190	dbregs->dr6 = pcb->pcb_dr6;
2191	dbregs->dr7 = pcb->pcb_dr7;
2192	return (0);
2193}
2194
2195int
2196set_dbregs(p, dbregs)
2197	struct proc *p;
2198	struct dbreg *dbregs;
2199{
2200	struct pcb *pcb;
2201
2202	pcb = &p->p_addr->u_pcb;
2203
2204	/*
2205	 * Don't let a process set a breakpoint that is not within the
2206	 * process's address space.  If a process could do this, it
2207	 * could halt the system by setting a breakpoint in the kernel
2208	 * (if ddb was enabled).  Thus, we need to check to make sure
2209	 * that no breakpoints are being enabled for addresses outside
2210	 * process's address space, unless, perhaps, we were called by
2211	 * uid 0.
2212	 *
2213	 * XXX - what about when the watched area of the user's
2214	 * address space is written into from within the kernel
2215	 * ... wouldn't that still cause a breakpoint to be generated
2216	 * from within kernel mode?
2217	 */
2218
2219	if (p->p_ucred->cr_uid != 0) {
2220		if (dbregs->dr7 & 0x3) {
2221			/* dr0 is enabled */
2222			if (dbregs->dr0 >= VM_MAXUSER_ADDRESS)
2223				return (EINVAL);
2224		}
2225
2226		if (dbregs->dr7 & (0x3<<2)) {
2227			/* dr1 is enabled */
2228			if (dbregs->dr1 >= VM_MAXUSER_ADDRESS)
2229				return (EINVAL);
2230		}
2231
2232		if (dbregs->dr7 & (0x3<<4)) {
2233			/* dr2 is enabled */
2234			if (dbregs->dr2 >= VM_MAXUSER_ADDRESS)
2235       				return (EINVAL);
2236		}
2237
2238		if (dbregs->dr7 & (0x3<<6)) {
2239			/* dr3 is enabled */
2240			if (dbregs->dr3 >= VM_MAXUSER_ADDRESS)
2241				return (EINVAL);
2242		}
2243	}
2244
2245	pcb->pcb_dr0 = dbregs->dr0;
2246	pcb->pcb_dr1 = dbregs->dr1;
2247	pcb->pcb_dr2 = dbregs->dr2;
2248	pcb->pcb_dr3 = dbregs->dr3;
2249	pcb->pcb_dr6 = dbregs->dr6;
2250	pcb->pcb_dr7 = dbregs->dr7;
2251
2252	pcb->pcb_flags |= PCB_DBREGS;
2253
2254	return (0);
2255}
2256
2257/*
2258 * Return > 0 if a hardware breakpoint has been hit, and the
2259 * breakpoint was in user space.  Return 0, otherwise.
2260 */
2261int
2262user_dbreg_trap(void)
2263{
2264        u_int32_t dr7, dr6; /* debug registers dr6 and dr7 */
2265        u_int32_t bp;       /* breakpoint bits extracted from dr6 */
2266        int nbp;            /* number of breakpoints that triggered */
2267        caddr_t addr[4];    /* breakpoint addresses */
2268        int i;
2269
2270        dr7 = rdr7();
2271        if ((dr7 & 0x000000ff) == 0) {
2272                /*
2273                 * all GE and LE bits in the dr7 register are zero,
2274                 * thus the trap couldn't have been caused by the
2275                 * hardware debug registers
2276                 */
2277                return 0;
2278        }
2279
2280        nbp = 0;
2281        dr6 = rdr6();
2282        bp = dr6 & 0x0000000f;
2283
2284        if (!bp) {
2285                /*
2286                 * None of the breakpoint bits are set meaning this
2287                 * trap was not caused by any of the debug registers
2288                 */
2289                return 0;
2290        }
2291
2292        /*
2293         * at least one of the breakpoints were hit, check to see
2294         * which ones and if any of them are user space addresses
2295         */
2296
2297        if (bp & 0x01) {
2298                addr[nbp++] = (caddr_t)rdr0();
2299        }
2300        if (bp & 0x02) {
2301                addr[nbp++] = (caddr_t)rdr1();
2302        }
2303        if (bp & 0x04) {
2304                addr[nbp++] = (caddr_t)rdr2();
2305        }
2306        if (bp & 0x08) {
2307                addr[nbp++] = (caddr_t)rdr3();
2308        }
2309
2310        for (i=0; i<nbp; i++) {
2311                if (addr[i] <
2312                    (caddr_t)VM_MAXUSER_ADDRESS) {
2313                        /*
2314                         * addr[i] is in user space
2315                         */
2316                        return nbp;
2317                }
2318        }
2319
2320        /*
2321         * None of the breakpoints are in user space.
2322         */
2323        return 0;
2324}
2325
2326
2327#ifndef DDB
2328void
2329Debugger(const char *msg)
2330{
2331	printf("Debugger(\"%s\") called.\n", msg);
2332}
2333#endif /* no DDB */
2334
2335#include <sys/disklabel.h>
2336
2337/*
2338 * Determine the size of the transfer, and make sure it is
2339 * within the boundaries of the partition. Adjust transfer
2340 * if needed, and signal errors or early completion.
2341 */
2342int
2343bounds_check_with_label(struct bio *bp, struct disklabel *lp, int wlabel)
2344{
2345        struct partition *p = lp->d_partitions + dkpart(bp->bio_dev);
2346        int labelsect = lp->d_partitions[0].p_offset;
2347        int maxsz = p->p_size,
2348                sz = (bp->bio_bcount + DEV_BSIZE - 1) >> DEV_BSHIFT;
2349
2350        /* overwriting disk label ? */
2351        /* XXX should also protect bootstrap in first 8K */
2352        if (bp->bio_blkno + p->p_offset <= LABELSECTOR + labelsect &&
2353#if LABELSECTOR != 0
2354            bp->bio_blkno + p->p_offset + sz > LABELSECTOR + labelsect &&
2355#endif
2356            (bp->bio_cmd == BIO_WRITE) && wlabel == 0) {
2357                bp->bio_error = EROFS;
2358                goto bad;
2359        }
2360
2361#if     defined(DOSBBSECTOR) && defined(notyet)
2362        /* overwriting master boot record? */
2363        if (bp->bio_blkno + p->p_offset <= DOSBBSECTOR &&
2364            (bp->bio_cmd == BIO_WRITE) && wlabel == 0) {
2365                bp->bio_error = EROFS;
2366                goto bad;
2367        }
2368#endif
2369
2370        /* beyond partition? */
2371        if (bp->bio_blkno < 0 || bp->bio_blkno + sz > maxsz) {
2372                /* if exactly at end of disk, return an EOF */
2373                if (bp->bio_blkno == maxsz) {
2374                        bp->bio_resid = bp->bio_bcount;
2375                        return(0);
2376                }
2377                /* or truncate if part of it fits */
2378                sz = maxsz - bp->bio_blkno;
2379                if (sz <= 0) {
2380                        bp->bio_error = EINVAL;
2381                        goto bad;
2382                }
2383                bp->bio_bcount = sz << DEV_BSHIFT;
2384        }
2385
2386        bp->bio_pblkno = bp->bio_blkno + p->p_offset;
2387        return(1);
2388
2389bad:
2390        bp->bio_flags |= BIO_ERROR;
2391        return(-1);
2392}
2393
2394#ifdef DDB
2395
2396/*
2397 * Provide inb() and outb() as functions.  They are normally only
2398 * available as macros calling inlined functions, thus cannot be
2399 * called inside DDB.
2400 *
2401 * The actual code is stolen from <machine/cpufunc.h>, and de-inlined.
2402 */
2403
2404#undef inb
2405#undef outb
2406
2407/* silence compiler warnings */
2408u_char inb(u_int);
2409void outb(u_int, u_char);
2410
2411u_char
2412inb(u_int port)
2413{
2414	u_char	data;
2415	/*
2416	 * We use %%dx and not %1 here because i/o is done at %dx and not at
2417	 * %edx, while gcc generates inferior code (movw instead of movl)
2418	 * if we tell it to load (u_short) port.
2419	 */
2420	__asm __volatile("inb %%dx,%0" : "=a" (data) : "d" (port));
2421	return (data);
2422}
2423
2424void
2425outb(u_int port, u_char data)
2426{
2427	u_char	al;
2428	/*
2429	 * Use an unnecessary assignment to help gcc's register allocator.
2430	 * This make a large difference for gcc-1.40 and a tiny difference
2431	 * for gcc-2.6.0.  For gcc-1.40, al had to be ``asm("ax")'' for
2432	 * best results.  gcc-2.6.0 can't handle this.
2433	 */
2434	al = data;
2435	__asm __volatile("outb %0,%%dx" : : "a" (al), "d" (port));
2436}
2437
2438#endif /* DDB */
2439