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