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