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