machdep.c revision 10358
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.136 1995/08/20 04:41:02 davidg Exp $
39 */
40
41#include "npx.h"
42#include "isa.h"
43
44#include <sys/param.h>
45#include <sys/systm.h>
46#include <sys/signalvar.h>
47#include <sys/kernel.h>
48#include <sys/proc.h>
49#include <sys/user.h>
50#include <sys/buf.h>
51#include <sys/reboot.h>
52#include <sys/conf.h>
53#include <sys/file.h>
54#include <sys/callout.h>
55#include <sys/malloc.h>
56#include <sys/mbuf.h>
57#include <sys/mount.h>
58#include <sys/msgbuf.h>
59#include <sys/ioctl.h>
60#include <sys/sysent.h>
61#include <sys/tty.h>
62#include <sys/sysctl.h>
63#include <sys/devconf.h>
64
65#ifdef SYSVSHM
66#include <sys/shm.h>
67#endif
68
69#ifdef SYSVMSG
70#include <sys/msg.h>
71#endif
72
73#ifdef SYSVSEM
74#include <sys/sem.h>
75#endif
76
77#include <vm/vm.h>
78#include <vm/vm_kern.h>
79#include <vm/vm_page.h>
80#include <vm/vm_pager.h>
81
82#include <sys/exec.h>
83#include <sys/vnode.h>
84
85#include <ddb/ddb.h>
86
87#include <net/netisr.h>
88
89/* XXX correctly declaring all the netisr's is painful. */
90#include <net/if.h>
91#include <net/route.h>
92
93#include <netinet/in.h>
94#include <netinet/in_systm.h>
95#include <netinet/ip.h>
96#include <netinet/if_ether.h>
97#include <netinet/ip_var.h>
98
99#include <netns/ns.h>
100#include <netns/ns_if.h>
101
102#include <netiso/iso.h>
103#include <netiso/iso_var.h>
104
105#include <netccitt/dll.h>
106#include <netccitt/x25.h>
107#include <netccitt/pk.h>
108#include <sys/socketvar.h>
109#include <netccitt/pk_var.h>
110
111#include "ether.h"
112
113#include <machine/cpu.h>
114#include <machine/npx.h>
115#include <machine/reg.h>
116#include <machine/psl.h>
117#include <machine/clock.h>
118#include <machine/specialreg.h>
119#include <machine/sysarch.h>
120#include <machine/cons.h>
121#include <machine/devconf.h>
122#include <machine/bootinfo.h>
123#include <machine/md_var.h>
124
125#include <i386/isa/isa.h>
126#include <i386/isa/isa_device.h>
127#include <i386/isa/rtc.h>
128
129/*
130 * System initialization
131 */
132
133static void cpu_startup __P(( caddr_t));
134
135SYSINIT(cpu, SI_SUB_CPU, SI_ORDER_FIRST, cpu_startup, NULL)
136
137
138static void identifycpu(void);
139static void initcpu(void);
140
141char machine[] = "i386";
142char cpu_model[128];
143
144struct kern_devconf kdc_cpu0 = {
145	0, 0, 0,		/* filled in by dev_attach */
146	"cpu", 0, { MDDT_CPU },
147	0, 0, 0, CPU_EXTERNALLEN,
148	0,			/* CPU has no parent */
149	0,			/* no parentdata */
150	DC_BUSY,		/* the CPU is always busy */
151	cpu_model,		/* no sense in duplication */
152	DC_CLS_CPU		/* class */
153};
154
155#ifndef PANIC_REBOOT_WAIT_TIME
156#define PANIC_REBOOT_WAIT_TIME 15 /* default to 15 seconds */
157#endif
158
159#ifdef BOUNCE_BUFFERS
160extern char *bouncememory;
161extern int maxbkva;
162#ifdef BOUNCEPAGES
163int	bouncepages = BOUNCEPAGES;
164#else
165int	bouncepages = 0;
166#endif
167#endif	/* BOUNCE_BUFFERS */
168
169extern int freebufspace;
170int	msgbufmapped = 0;		/* set when safe to use msgbuf */
171int _udatasel, _ucodesel;
172
173
174/*
175 * Machine-dependent startup code
176 */
177int boothowto = 0, bootverbose = 0, Maxmem = 0, badpages = 0, physmem = 0;
178long dumplo;
179extern int bootdev;
180int biosmem;
181
182vm_offset_t phys_avail[10];
183
184/* must be 2 less so 0 0 can signal end of chunks */
185#define PHYS_AVAIL_ARRAY_END ((sizeof(phys_avail) / sizeof(vm_offset_t)) - 2)
186
187int cpu_class;
188
189void dumpsys __P((void));
190void setup_netisrs __P((struct linker_set *)); /* XXX declare elsewhere */
191
192vm_offset_t buffer_sva, buffer_eva;
193vm_offset_t clean_sva, clean_eva;
194vm_offset_t pager_sva, pager_eva;
195extern struct linker_set netisr_set;
196
197#define offsetof(type, member)	((size_t)(&((type *)0)->member))
198
199/* ARGSUSED*/
200static void
201cpu_startup( udata)
202caddr_t		udata;	/* not used*/
203{
204	register unsigned i;
205	register caddr_t v;
206	vm_offset_t maxaddr;
207	vm_size_t size = 0;
208	int firstaddr, indx;
209	vm_offset_t minaddr;
210
211	if (boothowto & RB_VERBOSE)
212		bootverbose++;
213
214	/*
215	 * Initialize error message buffer (at end of core).
216	 */
217
218	/* avail_end was pre-decremented in init_386() to compensate */
219	for (i = 0; i < btoc(sizeof (struct msgbuf)); i++)
220		pmap_enter(pmap_kernel(), (vm_offset_t)msgbufp,
221			   avail_end + i * NBPG,
222			   VM_PROT_ALL, TRUE);
223	msgbufmapped = 1;
224
225	/*
226	 * Good {morning,afternoon,evening,night}.
227	 */
228	printf(version);
229	startrtclock();
230	identifycpu();
231	/*
232	 * Display any holes after the first chunk of extended memory.
233	 */
234	if (badpages != 0) {
235		int indx = 1;
236
237		/*
238		 * XXX skip reporting ISA hole & unmanaged kernel memory
239		 */
240		if (phys_avail[0] == PAGE_SIZE)
241			indx += 2;
242
243		printf("Physical memory hole(s):\n");
244		for (; phys_avail[indx + 1] != 0; indx += 2) {
245			int size = phys_avail[indx + 1] - phys_avail[indx];
246
247			printf("0x%08x - 0x%08x, %d bytes (%d pages)\n", phys_avail[indx],
248			    phys_avail[indx + 1] - 1, size, size / PAGE_SIZE);
249		}
250	}
251
252	/*
253	 * Quickly wire in netisrs.
254	 */
255	setup_netisrs(&netisr_set);
256
257/*
258#ifdef ISDN
259	DONET(isdnintr, NETISR_ISDN);
260#endif
261*/
262
263	/*
264	 * Allocate space for system data structures.
265	 * The first available kernel virtual address is in "v".
266	 * As pages of kernel virtual memory are allocated, "v" is incremented.
267	 * As pages of memory are allocated and cleared,
268	 * "firstaddr" is incremented.
269	 * An index into the kernel page table corresponding to the
270	 * virtual memory address maintained in "v" is kept in "mapaddr".
271	 */
272
273	/*
274	 * Make two passes.  The first pass calculates how much memory is
275	 * needed and allocates it.  The second pass assigns virtual
276	 * addresses to the various data structures.
277	 */
278	firstaddr = 0;
279again:
280	v = (caddr_t)firstaddr;
281
282#define	valloc(name, type, num) \
283	    (name) = (type *)v; v = (caddr_t)((name)+(num))
284#define	valloclim(name, type, num, lim) \
285	    (name) = (type *)v; v = (caddr_t)((lim) = ((name)+(num)))
286	valloc(callout, struct callout, ncallout);
287#ifdef SYSVSHM
288	valloc(shmsegs, struct shmid_ds, shminfo.shmmni);
289#endif
290#ifdef SYSVSEM
291	valloc(sema, struct semid_ds, seminfo.semmni);
292	valloc(sem, struct sem, seminfo.semmns);
293	/* This is pretty disgusting! */
294	valloc(semu, int, (seminfo.semmnu * seminfo.semusz) / sizeof(int));
295#endif
296#ifdef SYSVMSG
297	valloc(msgpool, char, msginfo.msgmax);
298	valloc(msgmaps, struct msgmap, msginfo.msgseg);
299	valloc(msghdrs, struct msg, msginfo.msgtql);
300	valloc(msqids, struct msqid_ds, msginfo.msgmni);
301#endif
302
303	if (nbuf == 0) {
304		nbuf = 30;
305		if( physmem > 1024)
306			nbuf += min((physmem - 1024) / 12, 1024);
307	}
308	nswbuf = min(nbuf, 128);
309
310	valloc(swbuf, struct buf, nswbuf);
311	valloc(buf, struct buf, nbuf);
312
313#ifdef BOUNCE_BUFFERS
314	/*
315	 * If there is more than 16MB of memory, allocate some bounce buffers
316	 */
317	if (Maxmem > 4096) {
318		if (bouncepages == 0) {
319			bouncepages = 64;
320			bouncepages += ((Maxmem - 4096) / 2048) * 32;
321		}
322		v = (caddr_t)((vm_offset_t)((vm_offset_t)v + PAGE_SIZE - 1) & ~(PAGE_SIZE - 1));
323		valloc(bouncememory, char, bouncepages * PAGE_SIZE);
324	}
325#endif
326
327	/*
328	 * End of first pass, size has been calculated so allocate memory
329	 */
330	if (firstaddr == 0) {
331		size = (vm_size_t)(v - firstaddr);
332		firstaddr = (int)kmem_alloc(kernel_map, round_page(size));
333		if (firstaddr == 0)
334			panic("startup: no room for tables");
335		goto again;
336	}
337
338	/*
339	 * End of second pass, addresses have been assigned
340	 */
341	if ((vm_size_t)(v - firstaddr) != size)
342		panic("startup: table size inconsistency");
343
344#ifdef BOUNCE_BUFFERS
345	clean_map = kmem_suballoc(kernel_map, &clean_sva, &clean_eva,
346			(nbuf*MAXBSIZE) + (nswbuf*MAXPHYS) +
347				maxbkva + pager_map_size, TRUE);
348	io_map = kmem_suballoc(clean_map, &minaddr, &maxaddr, maxbkva, FALSE);
349#else
350	clean_map = kmem_suballoc(kernel_map, &clean_sva, &clean_eva,
351			(nbuf*MAXBSIZE) + (nswbuf*MAXPHYS) + pager_map_size, TRUE);
352#endif
353	buffer_map = kmem_suballoc(clean_map, &buffer_sva, &buffer_eva,
354				(nbuf*MAXBSIZE), TRUE);
355	pager_map = kmem_suballoc(clean_map, &pager_sva, &pager_eva,
356				(nswbuf*MAXPHYS) + pager_map_size, TRUE);
357	exec_map = kmem_suballoc(kernel_map, &minaddr, &maxaddr,
358				(16*ARG_MAX), TRUE);
359	u_map = kmem_suballoc(kernel_map, &minaddr, &maxaddr,
360				(maxproc*UPAGES*PAGE_SIZE), FALSE);
361
362	/*
363	 * Finally, allocate mbuf pool.  Since mclrefcnt is an off-size
364	 * we use the more space efficient malloc in place of kmem_alloc.
365	 */
366	mclrefcnt = (char *)malloc(nmbclusters+CLBYTES/MCLBYTES,
367				   M_MBUF, M_NOWAIT);
368	bzero(mclrefcnt, nmbclusters+CLBYTES/MCLBYTES);
369	mb_map = kmem_suballoc(kmem_map, (vm_offset_t *)&mbutl, &maxaddr,
370			       nmbclusters * MCLBYTES, FALSE);
371	/*
372	 * Initialize callouts
373	 */
374	callfree = callout;
375	for (i = 1; i < ncallout; i++)
376		callout[i-1].c_next = &callout[i];
377
378        if (boothowto & RB_CONFIG)
379		userconfig();
380	printf("avail memory = %d (%d pages)\n", ptoa(cnt.v_free_count), cnt.v_free_count);
381
382#ifdef BOUNCE_BUFFERS
383	/*
384	 * init bounce buffers
385	 */
386	vm_bounce_init();
387#endif
388
389	/*
390	 * Set up CPU-specific registers, cache, etc.
391	 */
392	initcpu();
393
394	/*
395	 * Set up buffers, so they can be used to read disk labels.
396	 */
397	bufinit();
398	vm_pager_bufferinit();
399
400	/*
401	 * Configure the system.
402	 */
403	configure();
404	if (bootverbose) {
405		printf("BIOS Geometries:\n");
406		for (i=0; i < N_BIOS_GEOM; i++) {
407			int j = bootinfo.bi_bios_geom[i];
408			if (j == 0x4f010f)
409				continue;
410			printf(" %x:%08x", i, j);
411			printf(" %d cyl, %d heads, %d sects\n",
412				j >> 16, (j >> 8) & 0xff, j & 0xff);
413
414		}
415		printf(" %d accounted for\n", bootinfo.bi_n_bios_used);
416	}
417}
418
419void
420setup_netisrs(struct linker_set *ls)
421{
422	int i;
423	const struct netisrtab *nit;
424
425	for(i = 0; ls->ls_items[i]; i++) {
426		nit = (const struct netisrtab *)ls->ls_items[i];
427		netisrs[nit->nit_num] = nit->nit_isr;
428	}
429}
430
431struct cpu_nameclass i386_cpus[] = {
432	{ "Intel 80286",	CPUCLASS_286 },		/* CPU_286   */
433	{ "i386SX",		CPUCLASS_386 },		/* CPU_386SX */
434	{ "i386DX",		CPUCLASS_386 },		/* CPU_386   */
435	{ "i486SX",		CPUCLASS_486 },		/* CPU_486SX */
436	{ "i486DX",		CPUCLASS_486 },		/* CPU_486   */
437	{ "Pentium",		CPUCLASS_586 },		/* CPU_586   */
438	{ "Cy486DLC",		CPUCLASS_486 },		/* CPU_486DLC */
439};
440
441static void
442identifycpu()
443{
444	printf("CPU: ");
445	if (cpu >= 0
446	    && cpu < (sizeof i386_cpus/sizeof(struct cpu_nameclass))) {
447		cpu_class = i386_cpus[cpu].cpu_class;
448		strncpy(cpu_model, i386_cpus[cpu].cpu_name, sizeof cpu_model);
449	} else {
450		printf("unknown cpu type %d\n", cpu);
451		panic("startup: bad cpu id");
452	}
453
454#if defined(I586_CPU)
455	if(cpu_class == CPUCLASS_586) {
456		calibrate_cyclecounter();
457		printf("%d-MHz ", pentium_mhz);
458	}
459#endif
460#if defined(I486_CPU) || defined(I586_CPU)
461	if (!strcmp(cpu_vendor,"GenuineIntel")) {
462		if ((cpu_id & 0xf00) > 3) {
463			cpu_model[0] = '\0';
464
465			switch (cpu_id & 0x3000) {
466			case 0x1000:
467				strcpy(cpu_model, "Overdrive ");
468				break;
469			case 0x2000:
470				strcpy(cpu_model, "Dual ");
471				break;
472			}
473			if ((cpu_id & 0xf00) == 0x400) {
474				strcat(cpu_model, "i486 ");
475#if defined(I586_CPU)
476			} else if ((cpu_id & 0xf00) == 0x500) {
477				strcat(cpu_model, "Pentium ");
478#endif
479			} else {
480				strcat(cpu_model, "unknown ");
481			}
482
483			switch (cpu_id & 0xff0) {
484			case 0x400:
485				strcat(cpu_model, "DX"); break;
486			case 0x410:
487				strcat(cpu_model, "DX"); break;
488			case 0x420:
489				strcat(cpu_model, "SX"); break;
490			case 0x430:
491				strcat(cpu_model, "DX2"); break;
492			case 0x440:
493				strcat(cpu_model, "SL"); break;
494			case 0x450:
495				strcat(cpu_model, "SX2"); break;
496			case 0x470:
497				strcat(cpu_model, "DX2 Write-Back Enhanced");
498				break;
499			case 0x480:
500				strcat(cpu_model, "DX4"); break;
501#if defined(I586_CPU)
502			case 0x510:
503				if (pentium_mhz == 60) {
504					strcat(cpu_model, "510\\60");
505				} else if (pentium_mhz == 66) {
506					strcat(cpu_model, "567\\66");
507				} else {
508					strcat(cpu_model,"510\\60 or 567\\66");
509				}
510				break;
511			case 0x520:
512				if (pentium_mhz == 90) {
513					strcat(cpu_model, "735\\90");
514				} else if (pentium_mhz == 100) {
515					strcat(cpu_model, "815\\100");
516				} else {
517					strcat(cpu_model,"735\\90 or 815\\100");
518				}
519				break;
520#endif
521			}
522		}
523	}
524#endif
525	printf("%s (", cpu_model);
526	switch(cpu_class) {
527	case CPUCLASS_286:
528		printf("286");
529		break;
530#if defined(I386_CPU)
531	case CPUCLASS_386:
532		printf("386");
533		break;
534#endif
535#if defined(I486_CPU)
536	case CPUCLASS_486:
537		printf("486");
538		break;
539#endif
540#if defined(I586_CPU)
541	case CPUCLASS_586:
542		printf("Pentium");
543		break;
544#endif
545	default:
546		printf("unknown");	/* will panic below... */
547	}
548	printf("-class CPU)\n");
549#if defined(I486_CPU) || defined(I586_CPU)
550	if(*cpu_vendor)
551		printf("  Origin = \"%s\"",cpu_vendor);
552	if(cpu_id)
553		printf("  Id = 0x%lx",cpu_id);
554
555	if (!strcmp(cpu_vendor, "GenuineIntel")) {
556		printf("  Stepping=%ld", cpu_id & 0xf);
557		if (cpu_high > 0) {
558#define FEATUREFMT "\020\001FPU\002VME\003PSE\004MCE\005CX8\006APIC"
559			printf("\n  Features=0x%b", cpu_feature, FEATUREFMT);
560		}
561	}
562	/* Avoid ugly blank lines: only print newline when we have to. */
563	if (*cpu_vendor || cpu_id)
564		printf("\n");
565#endif
566	/*
567	 * Now that we have told the user what they have,
568	 * let them know if that machine type isn't configured.
569	 */
570	switch (cpu_class) {
571	case CPUCLASS_286:	/* a 286 should not make it this far, anyway */
572#if !defined(I386_CPU) && !defined(I486_CPU) && !defined(I586_CPU)
573#error This kernel is not configured for one of the supported CPUs
574#endif
575#if !defined(I386_CPU)
576	case CPUCLASS_386:
577#endif
578#if !defined(I486_CPU)
579	case CPUCLASS_486:
580#endif
581#if !defined(I586_CPU)
582	case CPUCLASS_586:
583#endif
584		panic("CPU class not configured");
585	default:
586		break;
587	}
588	dev_attach(&kdc_cpu0);
589}
590
591/*
592 * Send an interrupt to process.
593 *
594 * Stack is set up to allow sigcode stored
595 * in u. to call routine, followed by kcall
596 * to sigreturn routine below.  After sigreturn
597 * resets the signal mask, the stack, and the
598 * frame pointer, it returns to the user
599 * specified pc, psl.
600 */
601void
602sendsig(catcher, sig, mask, code)
603	sig_t catcher;
604	int sig, mask;
605	unsigned code;
606{
607	register struct proc *p = curproc;
608	register int *regs;
609	register struct sigframe *fp;
610	struct sigframe sf;
611	struct sigacts *psp = p->p_sigacts;
612	int oonstack;
613
614	regs = p->p_md.md_regs;
615        oonstack = psp->ps_sigstk.ss_flags & SA_ONSTACK;
616	/*
617	 * Allocate and validate space for the signal handler
618	 * context. Note that if the stack is in P0 space, the
619	 * call to grow() is a nop, and the useracc() check
620	 * will fail if the process has not already allocated
621	 * the space with a `brk'.
622	 */
623        if ((psp->ps_flags & SAS_ALTSTACK) &&
624	    (psp->ps_sigstk.ss_flags & SA_ONSTACK) == 0 &&
625	    (psp->ps_sigonstack & sigmask(sig))) {
626		fp = (struct sigframe *)(psp->ps_sigstk.ss_sp +
627		    psp->ps_sigstk.ss_size - sizeof(struct sigframe));
628		psp->ps_sigstk.ss_flags |= SA_ONSTACK;
629	} else {
630		fp = (struct sigframe *)(regs[tESP]
631			- sizeof(struct sigframe));
632	}
633
634	/*
635	 * grow() will return FALSE if the fp will not fit inside the stack
636	 *	and the stack can not be grown. useracc will return FALSE
637	 *	if access is denied.
638	 */
639	if ((grow(p, (int)fp) == FALSE) ||
640	    (useracc((caddr_t)fp, sizeof (struct sigframe), B_WRITE) == FALSE)) {
641		/*
642		 * Process has trashed its stack; give it an illegal
643		 * instruction to halt it in its tracks.
644		 */
645		SIGACTION(p, SIGILL) = SIG_DFL;
646		sig = sigmask(SIGILL);
647		p->p_sigignore &= ~sig;
648		p->p_sigcatch &= ~sig;
649		p->p_sigmask &= ~sig;
650		psignal(p, SIGILL);
651		return;
652	}
653
654	/*
655	 * Build the argument list for the signal handler.
656	 */
657	if (p->p_sysent->sv_sigtbl) {
658		if (sig < p->p_sysent->sv_sigsize)
659			sig = p->p_sysent->sv_sigtbl[sig];
660		else
661			sig = p->p_sysent->sv_sigsize + 1;
662	}
663	sf.sf_signum = sig;
664	sf.sf_code = code;
665	sf.sf_scp = &fp->sf_sc;
666	sf.sf_addr = (char *) regs[tERR];
667	sf.sf_handler = catcher;
668
669	/* save scratch registers */
670	sf.sf_sc.sc_eax = regs[tEAX];
671	sf.sf_sc.sc_ebx = regs[tEBX];
672	sf.sf_sc.sc_ecx = regs[tECX];
673	sf.sf_sc.sc_edx = regs[tEDX];
674	sf.sf_sc.sc_esi = regs[tESI];
675	sf.sf_sc.sc_edi = regs[tEDI];
676	sf.sf_sc.sc_cs = regs[tCS];
677	sf.sf_sc.sc_ds = regs[tDS];
678	sf.sf_sc.sc_ss = regs[tSS];
679	sf.sf_sc.sc_es = regs[tES];
680	sf.sf_sc.sc_isp = regs[tISP];
681
682	/*
683	 * Build the signal context to be used by sigreturn.
684	 */
685	sf.sf_sc.sc_onstack = oonstack;
686	sf.sf_sc.sc_mask = mask;
687	sf.sf_sc.sc_sp = regs[tESP];
688	sf.sf_sc.sc_fp = regs[tEBP];
689	sf.sf_sc.sc_pc = regs[tEIP];
690	sf.sf_sc.sc_ps = regs[tEFLAGS];
691
692	/*
693	 * Copy the sigframe out to the user's stack.
694	 */
695	if (copyout(&sf, fp, sizeof(struct sigframe)) != 0) {
696		/*
697		 * Something is wrong with the stack pointer.
698		 * ...Kill the process.
699		 */
700		sigexit(p, SIGILL);
701	};
702
703	regs[tESP] = (int)fp;
704	regs[tEIP] = (int)((struct pcb *)kstack)->pcb_sigc;
705	regs[tEFLAGS] &= ~PSL_VM;
706	regs[tCS] = _ucodesel;
707	regs[tDS] = _udatasel;
708	regs[tES] = _udatasel;
709	regs[tSS] = _udatasel;
710}
711
712/*
713 * System call to cleanup state after a signal
714 * has been taken.  Reset signal mask and
715 * stack state from context left by sendsig (above).
716 * Return to previous pc and psl as specified by
717 * context left by sendsig. Check carefully to
718 * make sure that the user has not modified the
719 * state to gain improper privileges.
720 */
721struct sigreturn_args {
722	struct sigcontext *sigcntxp;
723};
724
725int
726sigreturn(p, uap, retval)
727	struct proc *p;
728	struct sigreturn_args *uap;
729	int *retval;
730{
731	register struct sigcontext *scp;
732	register struct sigframe *fp;
733	register int *regs = p->p_md.md_regs;
734	int eflags;
735
736	/*
737	 * (XXX old comment) regs[tESP] points to the return address.
738	 * The user scp pointer is above that.
739	 * The return address is faked in the signal trampoline code
740	 * for consistency.
741	 */
742	scp = uap->sigcntxp;
743	fp = (struct sigframe *)
744	     ((caddr_t)scp - offsetof(struct sigframe, sf_sc));
745
746	if (useracc((caddr_t)fp, sizeof (*fp), 0) == 0)
747		return(EINVAL);
748
749	/*
750	 * Don't allow users to change privileged or reserved flags.
751	 */
752#define	EFLAGS_SECURE(ef, oef)	((((ef) ^ (oef)) & ~PSL_USERCHANGE) == 0)
753	eflags = scp->sc_ps;
754	/*
755	 * XXX do allow users to change the privileged flag PSL_RF.  The
756	 * cpu sets PSL_RF in tf_eflags for faults.  Debuggers should
757	 * sometimes set it there too.  tf_eflags is kept in the signal
758	 * context during signal handling and there is no other place
759	 * to remember it, so the PSL_RF bit may be corrupted by the
760	 * signal handler without us knowing.  Corruption of the PSL_RF
761	 * bit at worst causes one more or one less debugger trap, so
762	 * allowing it is fairly harmless.
763	 */
764	if (!EFLAGS_SECURE(eflags & ~PSL_RF, regs[tEFLAGS] & ~PSL_RF)) {
765#ifdef DEBUG
766    		printf("sigreturn: eflags = 0x%x\n", eflags);
767#endif
768    		return(EINVAL);
769	}
770
771	/*
772	 * Don't allow users to load a valid privileged %cs.  Let the
773	 * hardware check for invalid selectors, excess privilege in
774	 * other selectors, invalid %eip's and invalid %esp's.
775	 */
776#define	CS_SECURE(cs)	(ISPL(cs) == SEL_UPL)
777	if (!CS_SECURE(scp->sc_cs)) {
778#ifdef DEBUG
779    		printf("sigreturn: cs = 0x%x\n", scp->sc_cs);
780#endif
781		trapsignal(p, SIGBUS, T_PROTFLT);
782		return(EINVAL);
783	}
784
785	/* restore scratch registers */
786	regs[tEAX] = scp->sc_eax;
787	regs[tEBX] = scp->sc_ebx;
788	regs[tECX] = scp->sc_ecx;
789	regs[tEDX] = scp->sc_edx;
790	regs[tESI] = scp->sc_esi;
791	regs[tEDI] = scp->sc_edi;
792	regs[tCS] = scp->sc_cs;
793	regs[tDS] = scp->sc_ds;
794	regs[tES] = scp->sc_es;
795	regs[tSS] = scp->sc_ss;
796	regs[tISP] = scp->sc_isp;
797
798	if (useracc((caddr_t)scp, sizeof (*scp), 0) == 0)
799		return(EINVAL);
800
801	if (scp->sc_onstack & 01)
802		p->p_sigacts->ps_sigstk.ss_flags |= SA_ONSTACK;
803	else
804		p->p_sigacts->ps_sigstk.ss_flags &= ~SA_ONSTACK;
805	p->p_sigmask = scp->sc_mask &~
806	    (sigmask(SIGKILL)|sigmask(SIGCONT)|sigmask(SIGSTOP));
807	regs[tEBP] = scp->sc_fp;
808	regs[tESP] = scp->sc_sp;
809	regs[tEIP] = scp->sc_pc;
810	regs[tEFLAGS] = eflags;
811	return(EJUSTRETURN);
812}
813
814/*
815 * a simple function to make the system panic (and dump a vmcore)
816 * in a predictable fashion
817 */
818void diediedie()
819{
820	panic("because you said to!");
821}
822
823int	waittime = -1;
824struct pcb dumppcb;
825
826__dead void
827boot(howto)
828	int howto;
829{
830	if (!cold && (howto & RB_NOSYNC) == 0 && waittime < 0) {
831		register struct buf *bp;
832		int iter, nbusy;
833
834		waittime = 0;
835		printf("\nsyncing disks... ");
836
837		sync(&proc0, NULL, NULL);
838
839		for (iter = 0; iter < 20; iter++) {
840			nbusy = 0;
841			for (bp = &buf[nbuf]; --bp >= buf; ) {
842				if ((bp->b_flags & (B_BUSY | B_INVAL)) == B_BUSY) {
843					nbusy++;
844				}
845			}
846			if (nbusy == 0)
847				break;
848			printf("%d ", nbusy);
849			DELAY(40000 * iter);
850		}
851		if (nbusy) {
852			/*
853			 * Failed to sync all blocks. Indicate this and don't
854			 * unmount filesystems (thus forcing an fsck on reboot).
855			 */
856			printf("giving up\n");
857		} else {
858			printf("done\n");
859			/*
860			 * Unmount filesystems
861			 */
862			if (panicstr == 0)
863				vfs_unmountall();
864		}
865		DELAY(100000);			/* wait for console output to finish */
866		dev_shutdownall(FALSE);
867	}
868	splhigh();
869	if (howto & RB_HALT) {
870		printf("\n");
871		printf("The operating system has halted.\n");
872		printf("Please press any key to reboot.\n\n");
873		cngetc();
874	} else {
875		if (howto & RB_DUMP) {
876			if (!cold) {
877				savectx(&dumppcb, 0);
878				dumppcb.pcb_ptd = rcr3();
879				dumpsys();
880			}
881
882			if (PANIC_REBOOT_WAIT_TIME != 0) {
883				if (PANIC_REBOOT_WAIT_TIME != -1) {
884					int loop;
885					printf("Automatic reboot in %d seconds - press a key on the console to abort\n",
886						PANIC_REBOOT_WAIT_TIME);
887					for (loop = PANIC_REBOOT_WAIT_TIME * 10; loop > 0; --loop) {
888						DELAY(1000 * 100); /* 1/10th second */
889						if (cncheckc()) /* Did user type a key? */
890							break;
891					}
892					if (!loop)
893						goto die;
894				}
895			} else { /* zero time specified - reboot NOW */
896				goto die;
897			}
898			printf("--> Press a key on the console to reboot <--\n");
899			cngetc();
900		}
901	}
902die:
903	printf("Rebooting...\n");
904	DELAY(1000000);	/* wait 1 sec for printf's to complete and be read */
905	cpu_reset();
906	for(;;) ;
907	/* NOTREACHED */
908}
909
910unsigned long	dumpmag = 0x8fca0101UL;	/* magic number for savecore */
911int		dumpsize = 0;		/* also for savecore */
912
913int		dodump = 1;
914
915/*
916 * Doadump comes here after turning off memory management and
917 * getting on the dump stack, either when called above, or by
918 * the auto-restart code.
919 */
920void
921dumpsys()
922{
923
924	if (!dodump)
925		return;
926	if (dumpdev == NODEV)
927		return;
928	if ((minor(dumpdev)&07) != 1)
929		return;
930	dumpsize = Maxmem;
931	printf("\ndumping to dev %lx, offset %ld\n", dumpdev, dumplo);
932	printf("dump ");
933	switch ((*bdevsw[major(dumpdev)].d_dump)(dumpdev)) {
934
935	case ENXIO:
936		printf("device bad\n");
937		break;
938
939	case EFAULT:
940		printf("device not ready\n");
941		break;
942
943	case EINVAL:
944		printf("area improper\n");
945		break;
946
947	case EIO:
948		printf("i/o error\n");
949		break;
950
951	case EINTR:
952		printf("aborted from console\n");
953		break;
954
955	default:
956		printf("succeeded\n");
957		break;
958	}
959}
960
961static void
962initcpu()
963{
964}
965
966/*
967 * Clear registers on exec
968 */
969void
970setregs(p, entry, stack)
971	struct proc *p;
972	u_long entry;
973	u_long stack;
974{
975	int *regs = p->p_md.md_regs;
976
977	bzero(regs, sizeof(struct trapframe));
978	regs[tEIP] = entry;
979	regs[tESP] = stack;
980	regs[tEFLAGS] = PSL_USER | (regs[tEFLAGS] & PSL_T);
981	regs[tSS] = _udatasel;
982	regs[tDS] = _udatasel;
983	regs[tES] = _udatasel;
984	regs[tCS] = _ucodesel;
985
986	p->p_addr->u_pcb.pcb_flags = 0;	/* no fp at all */
987	load_cr0(rcr0() | CR0_TS);	/* start emulating */
988#if	NNPX > 0
989	npxinit(__INITIAL_NPXCW__);
990#endif	/* NNPX > 0 */
991}
992
993/*
994 * machine dependent system variables.
995 */
996int
997cpu_sysctl(name, namelen, oldp, oldlenp, newp, newlen, p)
998	int *name;
999	u_int namelen;
1000	void *oldp;
1001	size_t *oldlenp;
1002	void *newp;
1003	size_t newlen;
1004	struct proc *p;
1005{
1006	dev_t consdev;
1007	int error;
1008
1009	/* all sysctl names at this level are terminal */
1010	if (namelen != 1)
1011		return (ENOTDIR);               /* overloaded */
1012
1013	switch (name[0]) {
1014	case CPU_CONSDEV:
1015		consdev = (cn_tty == NULL ? NODEV : cn_tty->t_dev);
1016		return (sysctl_rdstruct(oldp, oldlenp, newp, &consdev,
1017					sizeof consdev));
1018	case CPU_ADJKERNTZ:
1019		error = sysctl_int(oldp, oldlenp, newp, newlen, &adjkerntz);
1020		if (!error && newp)
1021			resettodr();
1022		return error;
1023	case CPU_DISRTCSET:
1024		return (sysctl_int(oldp, oldlenp, newp,	newlen,	&disable_rtc_set));
1025	case CPU_BOOTINFO:
1026		return (sysctl_rdstruct(oldp, oldlenp, newp, &bootinfo,
1027					sizeof bootinfo));
1028	default:
1029		return (EOPNOTSUPP);
1030	}
1031	/* NOTREACHED */
1032}
1033
1034/*
1035 * Initialize 386 and configure to run kernel
1036 */
1037
1038/*
1039 * Initialize segments & interrupt table
1040 */
1041
1042int currentldt;
1043int _default_ldt;
1044union descriptor gdt[NGDT];		/* global descriptor table */
1045struct gate_descriptor idt[NIDT];	/* interrupt descriptor table */
1046union descriptor ldt[NLDT];		/* local descriptor table */
1047
1048struct	i386tss	tss, panic_tss;
1049
1050extern  struct user *proc0paddr;
1051
1052/* software prototypes -- in more palatable form */
1053struct soft_segment_descriptor gdt_segs[] = {
1054/* GNULL_SEL	0 Null Descriptor */
1055{	0x0,			/* segment base address  */
1056	0x0,			/* length */
1057	0,			/* segment type */
1058	0,			/* segment descriptor priority level */
1059	0,			/* segment descriptor present */
1060	0, 0,
1061	0,			/* default 32 vs 16 bit size */
1062	0  			/* limit granularity (byte/page units)*/ },
1063/* GCODE_SEL	1 Code Descriptor for kernel */
1064{	0x0,			/* segment base address  */
1065	0xfffff,		/* length - all address space */
1066	SDT_MEMERA,		/* segment type */
1067	0,			/* segment descriptor priority level */
1068	1,			/* segment descriptor present */
1069	0, 0,
1070	1,			/* default 32 vs 16 bit size */
1071	1  			/* limit granularity (byte/page units)*/ },
1072/* GDATA_SEL	2 Data Descriptor for kernel */
1073{	0x0,			/* segment base address  */
1074	0xfffff,		/* length - all address space */
1075	SDT_MEMRWA,		/* segment type */
1076	0,			/* segment descriptor priority level */
1077	1,			/* segment descriptor present */
1078	0, 0,
1079	1,			/* default 32 vs 16 bit size */
1080	1  			/* limit granularity (byte/page units)*/ },
1081/* GLDT_SEL	3 LDT Descriptor */
1082{	(int) ldt,		/* segment base address  */
1083	sizeof(ldt)-1,		/* length - all address space */
1084	SDT_SYSLDT,		/* segment type */
1085	0,			/* segment descriptor priority level */
1086	1,			/* segment descriptor present */
1087	0, 0,
1088	0,			/* unused - default 32 vs 16 bit size */
1089	0  			/* limit granularity (byte/page units)*/ },
1090/* GTGATE_SEL	4 Null Descriptor - Placeholder */
1091{	0x0,			/* segment base address  */
1092	0x0,			/* length - all address space */
1093	0,			/* segment type */
1094	0,			/* segment descriptor priority level */
1095	0,			/* segment descriptor present */
1096	0, 0,
1097	0,			/* default 32 vs 16 bit size */
1098	0  			/* limit granularity (byte/page units)*/ },
1099/* GPANIC_SEL	5 Panic Tss Descriptor */
1100{	(int) &panic_tss,	/* segment base address  */
1101	sizeof(tss)-1,		/* length - all address space */
1102	SDT_SYS386TSS,		/* segment type */
1103	0,			/* segment descriptor priority level */
1104	1,			/* segment descriptor present */
1105	0, 0,
1106	0,			/* unused - default 32 vs 16 bit size */
1107	0  			/* limit granularity (byte/page units)*/ },
1108/* GPROC0_SEL	6 Proc 0 Tss Descriptor */
1109{	(int) kstack,		/* segment base address  */
1110	sizeof(tss)-1,		/* length - all address space */
1111	SDT_SYS386TSS,		/* segment type */
1112	0,			/* segment descriptor priority level */
1113	1,			/* segment descriptor present */
1114	0, 0,
1115	0,			/* unused - default 32 vs 16 bit size */
1116	0  			/* limit granularity (byte/page units)*/ },
1117/* GUSERLDT_SEL	7 User LDT Descriptor per process */
1118{	(int) ldt,		/* segment base address  */
1119	(512 * sizeof(union descriptor)-1),		/* length */
1120	SDT_SYSLDT,		/* segment type */
1121	0,			/* segment descriptor priority level */
1122	1,			/* segment descriptor present */
1123	0, 0,
1124	0,			/* unused - default 32 vs 16 bit size */
1125	0  			/* limit granularity (byte/page units)*/ },
1126/* GAPMCODE32_SEL 8 APM BIOS 32-bit interface (32bit Code) */
1127{	0,			/* segment base address (overwritten by APM)  */
1128	0xfffff,		/* length */
1129	SDT_MEMERA,		/* segment type */
1130	0,			/* segment descriptor priority level */
1131	1,			/* segment descriptor present */
1132	0, 0,
1133	1,			/* default 32 vs 16 bit size */
1134	1  			/* limit granularity (byte/page units)*/ },
1135/* GAPMCODE16_SEL 9 APM BIOS 32-bit interface (16bit Code) */
1136{	0,			/* segment base address (overwritten by APM)  */
1137	0xfffff,		/* length */
1138	SDT_MEMERA,		/* segment type */
1139	0,			/* segment descriptor priority level */
1140	1,			/* segment descriptor present */
1141	0, 0,
1142	0,			/* default 32 vs 16 bit size */
1143	1  			/* limit granularity (byte/page units)*/ },
1144/* GAPMDATA_SEL	10 APM BIOS 32-bit interface (Data) */
1145{	0,			/* segment base address (overwritten by APM) */
1146	0xfffff,		/* length */
1147	SDT_MEMRWA,		/* segment type */
1148	0,			/* segment descriptor priority level */
1149	1,			/* segment descriptor present */
1150	0, 0,
1151	1,			/* default 32 vs 16 bit size */
1152	1  			/* limit granularity (byte/page units)*/ },
1153};
1154
1155struct soft_segment_descriptor ldt_segs[] = {
1156	/* Null Descriptor - overwritten by call gate */
1157{	0x0,			/* segment base address  */
1158	0x0,			/* length - all address space */
1159	0,			/* segment type */
1160	0,			/* segment descriptor priority level */
1161	0,			/* segment descriptor present */
1162	0, 0,
1163	0,			/* default 32 vs 16 bit size */
1164	0  			/* limit granularity (byte/page units)*/ },
1165	/* Null Descriptor - overwritten by call gate */
1166{	0x0,			/* segment base address  */
1167	0x0,			/* length - all address space */
1168	0,			/* segment type */
1169	0,			/* segment descriptor priority level */
1170	0,			/* segment descriptor present */
1171	0, 0,
1172	0,			/* default 32 vs 16 bit size */
1173	0  			/* limit granularity (byte/page units)*/ },
1174	/* Null Descriptor - overwritten by call gate */
1175{	0x0,			/* segment base address  */
1176	0x0,			/* length - all address space */
1177	0,			/* segment type */
1178	0,			/* segment descriptor priority level */
1179	0,			/* segment descriptor present */
1180	0, 0,
1181	0,			/* default 32 vs 16 bit size */
1182	0  			/* limit granularity (byte/page units)*/ },
1183	/* Code Descriptor for user */
1184{	0x0,			/* segment base address  */
1185	0xfffff,		/* length - all address space */
1186	SDT_MEMERA,		/* segment type */
1187	SEL_UPL,		/* segment descriptor priority level */
1188	1,			/* segment descriptor present */
1189	0, 0,
1190	1,			/* default 32 vs 16 bit size */
1191	1  			/* limit granularity (byte/page units)*/ },
1192	/* Data Descriptor for user */
1193{	0x0,			/* segment base address  */
1194	0xfffff,		/* length - all address space */
1195	SDT_MEMRWA,		/* segment type */
1196	SEL_UPL,		/* segment descriptor priority level */
1197	1,			/* segment descriptor present */
1198	0, 0,
1199	1,			/* default 32 vs 16 bit size */
1200	1  			/* limit granularity (byte/page units)*/ },
1201};
1202
1203void
1204setidt(idx, func, typ, dpl)
1205	int idx;
1206	inthand_t *func;
1207	int typ;
1208	int dpl;
1209{
1210	struct gate_descriptor *ip = idt + idx;
1211
1212	ip->gd_looffset = (int)func;
1213	ip->gd_selector = 8;
1214	ip->gd_stkcpy = 0;
1215	ip->gd_xx = 0;
1216	ip->gd_type = typ;
1217	ip->gd_dpl = dpl;
1218	ip->gd_p = 1;
1219	ip->gd_hioffset = ((int)func)>>16 ;
1220}
1221
1222#define	IDTVEC(name)	__CONCAT(X,name)
1223
1224extern inthand_t
1225	IDTVEC(div), IDTVEC(dbg), IDTVEC(nmi), IDTVEC(bpt), IDTVEC(ofl),
1226	IDTVEC(bnd), IDTVEC(ill), IDTVEC(dna), IDTVEC(dble), IDTVEC(fpusegm),
1227	IDTVEC(tss), IDTVEC(missing), IDTVEC(stk), IDTVEC(prot),
1228	IDTVEC(page), IDTVEC(rsvd), IDTVEC(fpu), IDTVEC(align),
1229	IDTVEC(syscall);
1230
1231#ifdef COMPAT_LINUX
1232extern inthand_t
1233	IDTVEC(linux_syscall);
1234#endif
1235
1236void
1237sdtossd(sd, ssd)
1238	struct segment_descriptor *sd;
1239	struct soft_segment_descriptor *ssd;
1240{
1241	ssd->ssd_base  = (sd->sd_hibase << 24) | sd->sd_lobase;
1242	ssd->ssd_limit = (sd->sd_hilimit << 16) | sd->sd_lolimit;
1243	ssd->ssd_type  = sd->sd_type;
1244	ssd->ssd_dpl   = sd->sd_dpl;
1245	ssd->ssd_p     = sd->sd_p;
1246	ssd->ssd_def32 = sd->sd_def32;
1247	ssd->ssd_gran  = sd->sd_gran;
1248}
1249
1250void
1251init386(first)
1252	int first;
1253{
1254	int x;
1255	unsigned biosbasemem, biosextmem;
1256	struct gate_descriptor *gdp;
1257	int gsel_tss;
1258	/* table descriptors - used to load tables by microp */
1259	struct region_descriptor r_gdt, r_idt;
1260	int	pagesinbase, pagesinext;
1261	int	target_page, pa_indx;
1262
1263	proc0.p_addr = proc0paddr;
1264
1265	/*
1266	 * Initialize the console before we print anything out.
1267	 */
1268
1269	cninit ();
1270
1271	/*
1272	 * make gdt memory segments, the code segment goes up to end of the
1273	 * page with etext in it, the data segment goes to the end of
1274	 * the address space
1275	 */
1276	/*
1277	 * XXX text protection is temporarily (?) disabled.  The limit was
1278	 * i386_btop(i386_round_page(etext)) - 1.
1279	 */
1280	gdt_segs[GCODE_SEL].ssd_limit = i386_btop(0) - 1;
1281	gdt_segs[GDATA_SEL].ssd_limit = i386_btop(0) - 1;
1282	for (x = 0; x < NGDT; x++)
1283		ssdtosd(&gdt_segs[x], &gdt[x].sd);
1284
1285	/* make ldt memory segments */
1286	/*
1287	 * The data segment limit must not cover the user area because we
1288	 * don't want the user area to be writable in copyout() etc. (page
1289	 * level protection is lost in kernel mode on 386's).  Also, we
1290	 * don't want the user area to be writable directly (page level
1291	 * protection of the user area is not available on 486's with
1292	 * CR0_WP set, because there is no user-read/kernel-write mode).
1293	 *
1294	 * XXX - VM_MAXUSER_ADDRESS is an end address, not a max.  And it
1295	 * should be spelled ...MAX_USER...
1296	 */
1297#define VM_END_USER_RW_ADDRESS	VM_MAXUSER_ADDRESS
1298	/*
1299	 * The code segment limit has to cover the user area until we move
1300	 * the signal trampoline out of the user area.  This is safe because
1301	 * the code segment cannot be written to directly.
1302	 */
1303#define VM_END_USER_R_ADDRESS	(VM_END_USER_RW_ADDRESS + UPAGES * NBPG)
1304	ldt_segs[LUCODE_SEL].ssd_limit = i386_btop(VM_END_USER_R_ADDRESS) - 1;
1305	ldt_segs[LUDATA_SEL].ssd_limit = i386_btop(VM_END_USER_RW_ADDRESS) - 1;
1306	/* Note. eventually want private ldts per process */
1307	for (x = 0; x < NLDT; x++)
1308		ssdtosd(&ldt_segs[x], &ldt[x].sd);
1309
1310	/* exceptions */
1311	for (x = 0; x < NIDT; x++)
1312		setidt(x, &IDTVEC(rsvd), SDT_SYS386TGT, SEL_KPL);
1313	setidt(0, &IDTVEC(div),  SDT_SYS386TGT, SEL_KPL);
1314	setidt(1, &IDTVEC(dbg),  SDT_SYS386TGT, SEL_KPL);
1315	setidt(2, &IDTVEC(nmi),  SDT_SYS386TGT, SEL_KPL);
1316 	setidt(3, &IDTVEC(bpt),  SDT_SYS386TGT, SEL_UPL);
1317	setidt(4, &IDTVEC(ofl),  SDT_SYS386TGT, SEL_UPL);
1318	setidt(5, &IDTVEC(bnd),  SDT_SYS386TGT, SEL_KPL);
1319	setidt(6, &IDTVEC(ill),  SDT_SYS386TGT, SEL_KPL);
1320	setidt(7, &IDTVEC(dna),  SDT_SYS386TGT, SEL_KPL);
1321	setidt(8, &IDTVEC(dble),  SDT_SYS386TGT, SEL_KPL);
1322	setidt(9, &IDTVEC(fpusegm),  SDT_SYS386TGT, SEL_KPL);
1323	setidt(10, &IDTVEC(tss),  SDT_SYS386TGT, SEL_KPL);
1324	setidt(11, &IDTVEC(missing),  SDT_SYS386TGT, SEL_KPL);
1325	setidt(12, &IDTVEC(stk),  SDT_SYS386TGT, SEL_KPL);
1326	setidt(13, &IDTVEC(prot),  SDT_SYS386TGT, SEL_KPL);
1327	setidt(14, &IDTVEC(page),  SDT_SYS386TGT, SEL_KPL);
1328	setidt(15, &IDTVEC(rsvd),  SDT_SYS386TGT, SEL_KPL);
1329	setidt(16, &IDTVEC(fpu),  SDT_SYS386TGT, SEL_KPL);
1330	setidt(17, &IDTVEC(align), SDT_SYS386TGT, SEL_KPL);
1331#ifdef COMPAT_LINUX
1332 	setidt(0x80, &IDTVEC(linux_syscall),  SDT_SYS386TGT, SEL_UPL);
1333#endif
1334
1335#include	"isa.h"
1336#if	NISA >0
1337	isa_defaultirq();
1338#endif
1339
1340	r_gdt.rd_limit = sizeof(gdt) - 1;
1341	r_gdt.rd_base =  (int) gdt;
1342	lgdt(&r_gdt);
1343
1344	r_idt.rd_limit = sizeof(idt) - 1;
1345	r_idt.rd_base = (int) idt;
1346	lidt(&r_idt);
1347
1348	_default_ldt = GSEL(GLDT_SEL, SEL_KPL);
1349	lldt(_default_ldt);
1350	currentldt = _default_ldt;
1351
1352#ifdef DDB
1353	kdb_init();
1354	if (boothowto & RB_KDB)
1355		Debugger("Boot flags requested debugger");
1356#endif
1357
1358	/* Use BIOS values stored in RTC CMOS RAM, since probing
1359	 * breaks certain 386 AT relics.
1360	 */
1361	biosbasemem = rtcin(RTC_BASELO)+ (rtcin(RTC_BASEHI)<<8);
1362	biosextmem = rtcin(RTC_EXTLO)+ (rtcin(RTC_EXTHI)<<8);
1363
1364	/*
1365	 * Print a warning if the official BIOS interface disagrees
1366	 * with the hackish interface used above.  Eventually only
1367	 * the official interface should be used.
1368	 */
1369	if (bootinfo.bi_memsizes_valid) {
1370		if (bootinfo.bi_basemem != biosbasemem)
1371			printf("BIOS basemem (%ldK) != RTC basemem (%dK)\n",
1372			       bootinfo.bi_basemem, biosbasemem);
1373		if (bootinfo.bi_extmem != biosextmem)
1374			printf("BIOS extmem (%ldK) != RTC extmem (%dK)\n",
1375			       bootinfo.bi_extmem, biosextmem);
1376	}
1377
1378	/*
1379	 * If BIOS tells us that it has more than 640k in the basemem,
1380	 *	don't believe it - set it to 640k.
1381	 */
1382	if (biosbasemem > 640)
1383		biosbasemem = 640;
1384
1385	/*
1386	 * Some 386 machines might give us a bogus number for extended
1387	 *	mem. If this happens, stop now.
1388	 */
1389#ifndef LARGEMEM
1390	if (biosextmem > 65536) {
1391		panic("extended memory beyond limit of 64MB");
1392		/* NOTREACHED */
1393	}
1394#endif
1395
1396	pagesinbase = biosbasemem * 1024 / NBPG;
1397	pagesinext = biosextmem * 1024 / NBPG;
1398
1399	/*
1400	 * Special hack for chipsets that still remap the 384k hole when
1401	 *	there's 16MB of memory - this really confuses people that
1402	 *	are trying to use bus mastering ISA controllers with the
1403	 *	"16MB limit"; they only have 16MB, but the remapping puts
1404	 *	them beyond the limit.
1405	 */
1406	/*
1407	 * If extended memory is between 15-16MB (16-17MB phys address range),
1408	 *	chop it to 15MB.
1409	 */
1410	if ((pagesinext > 3840) && (pagesinext < 4096))
1411		pagesinext = 3840;
1412
1413	/*
1414	 * Maxmem isn't the "maximum memory", it's one larger than the
1415	 * highest page of of the physical address space. It
1416	 */
1417	Maxmem = pagesinext + 0x100000/PAGE_SIZE;
1418
1419#ifdef MAXMEM
1420	Maxmem = MAXMEM/4;
1421#endif
1422
1423	/* call pmap initialization to make new kernel address space */
1424	pmap_bootstrap (first, 0);
1425
1426	/*
1427	 * Size up each available chunk of physical memory.
1428	 */
1429
1430	/*
1431	 * We currently don't bother testing base memory.
1432	 * XXX  ...but we probably should.
1433	 */
1434	pa_indx = 0;
1435	badpages = 0;
1436	if (pagesinbase > 1) {
1437		phys_avail[pa_indx++] = PAGE_SIZE;	/* skip first page of memory */
1438		phys_avail[pa_indx] = ptoa(pagesinbase);/* memory up to the ISA hole */
1439		physmem = pagesinbase - 1;
1440	} else {
1441		/* point at first chunk end */
1442		pa_indx++;
1443	}
1444
1445	for (target_page = avail_start; target_page < ptoa(Maxmem); target_page += PAGE_SIZE) {
1446		int tmp, page_bad = FALSE;
1447
1448		/*
1449		 * map page into kernel: valid, read/write, non-cacheable
1450		 */
1451		*(int *)CMAP1 = PG_V | PG_KW | PG_N | target_page;
1452		pmap_update();
1453
1454		tmp = *(int *)CADDR1;
1455		/*
1456		 * Test for alternating 1's and 0's
1457		 */
1458		*(int *)CADDR1 = 0xaaaaaaaa;
1459		if (*(int *)CADDR1 != 0xaaaaaaaa) {
1460			page_bad = TRUE;
1461		}
1462		/*
1463		 * Test for alternating 0's and 1's
1464		 */
1465		*(int *)CADDR1 = 0x55555555;
1466		if (*(int *)CADDR1 != 0x55555555) {
1467			page_bad = TRUE;
1468		}
1469		/*
1470		 * Test for all 1's
1471		 */
1472		*(int *)CADDR1 = 0xffffffff;
1473		if (*(int *)CADDR1 != 0xffffffff) {
1474			page_bad = TRUE;
1475		}
1476		/*
1477		 * Test for all 0's
1478		 */
1479		*(int *)CADDR1 = 0x0;
1480		if (*(int *)CADDR1 != 0x0) {
1481			/*
1482			 * test of page failed
1483			 */
1484			page_bad = TRUE;
1485		}
1486		/*
1487		 * Restore original value.
1488		 */
1489		*(int *)CADDR1 = tmp;
1490
1491		/*
1492		 * Adjust array of valid/good pages.
1493		 */
1494		if (page_bad == FALSE) {
1495			/*
1496			 * If this good page is a continuation of the
1497			 * previous set of good pages, then just increase
1498			 * the end pointer. Otherwise start a new chunk.
1499			 * Note that "end" points one higher than end,
1500			 * making the range >= start and < end.
1501			 */
1502			if (phys_avail[pa_indx] == target_page) {
1503				phys_avail[pa_indx] += PAGE_SIZE;
1504			} else {
1505				pa_indx++;
1506				if (pa_indx == PHYS_AVAIL_ARRAY_END) {
1507					printf("Too many holes in the physical address space, giving up\n");
1508					pa_indx--;
1509					break;
1510				}
1511				phys_avail[pa_indx++] = target_page;	/* start */
1512				phys_avail[pa_indx] = target_page + PAGE_SIZE;	/* end */
1513			}
1514			physmem++;
1515		} else {
1516			badpages++;
1517			page_bad = FALSE;
1518		}
1519	}
1520
1521	*(int *)CMAP1 = 0;
1522	pmap_update();
1523
1524	/*
1525	 * XXX
1526	 * The last chunk must contain at leat one page plus the message
1527	 * buffer to avoid complicating other code (message buffer address
1528	 * calculation, etc.).
1529	 */
1530	while (phys_avail[pa_indx - 1] + PAGE_SIZE +
1531	    round_page(sizeof(struct msgbuf)) >= phys_avail[pa_indx]) {
1532		physmem -= atop(phys_avail[pa_indx] - phys_avail[pa_indx - 1]);
1533		phys_avail[pa_indx--] = 0;
1534		phys_avail[pa_indx--] = 0;
1535	}
1536
1537	Maxmem = atop(phys_avail[pa_indx]);
1538
1539	/* Trim off space for the message buffer. */
1540	phys_avail[pa_indx] -= round_page(sizeof(struct msgbuf));
1541
1542	avail_end = phys_avail[pa_indx];
1543
1544	/* now running on new page tables, configured,and u/iom is accessible */
1545
1546	/* make a initial tss so microp can get interrupt stack on syscall! */
1547	proc0.p_addr->u_pcb.pcb_tss.tss_esp0 = (int) kstack + UPAGES*NBPG;
1548	proc0.p_addr->u_pcb.pcb_tss.tss_ss0 = GSEL(GDATA_SEL, SEL_KPL) ;
1549	gsel_tss = GSEL(GPROC0_SEL, SEL_KPL);
1550
1551	((struct i386tss *)gdt_segs[GPROC0_SEL].ssd_base)->tss_ioopt =
1552		(sizeof(tss))<<16;
1553
1554	ltr(gsel_tss);
1555
1556	/* make a call gate to reenter kernel with */
1557	gdp = &ldt[LSYS5CALLS_SEL].gd;
1558
1559	x = (int) &IDTVEC(syscall);
1560	gdp->gd_looffset = x++;
1561	gdp->gd_selector = GSEL(GCODE_SEL,SEL_KPL);
1562	gdp->gd_stkcpy = 1;
1563	gdp->gd_type = SDT_SYS386CGT;
1564	gdp->gd_dpl = SEL_UPL;
1565	gdp->gd_p = 1;
1566	gdp->gd_hioffset = ((int) &IDTVEC(syscall)) >>16;
1567
1568	/* transfer to user mode */
1569
1570	_ucodesel = LSEL(LUCODE_SEL, SEL_UPL);
1571	_udatasel = LSEL(LUDATA_SEL, SEL_UPL);
1572
1573	/* setup proc 0's pcb */
1574	bcopy(&sigcode, proc0.p_addr->u_pcb.pcb_sigc, szsigcode);
1575	proc0.p_addr->u_pcb.pcb_flags = 0;
1576	proc0.p_addr->u_pcb.pcb_ptd = IdlePTD;
1577}
1578
1579/*
1580 * The registers are in the frame; the frame is in the user area of
1581 * the process in question; when the process is active, the registers
1582 * are in "the kernel stack"; when it's not, they're still there, but
1583 * things get flipped around.  So, since p->p_md.md_regs is the whole address
1584 * of the register set, take its offset from the kernel stack, and
1585 * index into the user block.  Don't you just *love* virtual memory?
1586 * (I'm starting to think seymour is right...)
1587 */
1588#define	TF_REGP(p)	((struct trapframe *) \
1589			 ((char *)(p)->p_addr \
1590			  + ((char *)(p)->p_md.md_regs - kstack)))
1591
1592int
1593ptrace_set_pc(p, addr)
1594	struct proc *p;
1595	unsigned int addr;
1596{
1597	TF_REGP(p)->tf_eip = addr;
1598	return (0);
1599}
1600
1601int
1602ptrace_single_step(p)
1603	struct proc *p;
1604{
1605	TF_REGP(p)->tf_eflags |= PSL_T;
1606	return (0);
1607}
1608
1609int
1610ptrace_getregs(p, addr)
1611	struct proc *p;
1612	unsigned int *addr;
1613{
1614	int error;
1615	struct reg regs;
1616
1617	error = fill_regs(p, &regs);
1618	if (error)
1619		return (error);
1620	return (copyout(&regs, addr, sizeof regs));
1621}
1622
1623int
1624ptrace_setregs(p, addr)
1625	struct proc *p;
1626	unsigned int *addr;
1627{
1628	int error;
1629	struct reg regs;
1630
1631	error = copyin(addr, &regs, sizeof regs);
1632	if (error)
1633		return (error);
1634	return (set_regs(p, &regs));
1635}
1636
1637int ptrace_write_u(p, off, data)
1638	struct proc *p;
1639	vm_offset_t off;
1640	int data;
1641{
1642	struct trapframe frame_copy;
1643	vm_offset_t min;
1644	struct trapframe *tp;
1645
1646	/*
1647	 * Privileged kernel state is scattered all over the user area.
1648	 * Only allow write access to parts of regs and to fpregs.
1649	 */
1650	min = (char *)p->p_md.md_regs - kstack;
1651	if (off >= min && off <= min + sizeof(struct trapframe) - sizeof(int)) {
1652		tp = TF_REGP(p);
1653		frame_copy = *tp;
1654		*(int *)((char *)&frame_copy + (off - min)) = data;
1655		if (!EFLAGS_SECURE(frame_copy.tf_eflags, tp->tf_eflags) ||
1656		    !CS_SECURE(frame_copy.tf_cs))
1657			return (EINVAL);
1658		*(int*)((char *)p->p_addr + off) = data;
1659		return (0);
1660	}
1661	min = offsetof(struct user, u_pcb) + offsetof(struct pcb, pcb_savefpu);
1662	if (off >= min && off <= min + sizeof(struct save87) - sizeof(int)) {
1663		*(int*)((char *)p->p_addr + off) = data;
1664		return (0);
1665	}
1666	return (EFAULT);
1667}
1668
1669int
1670fill_regs(p, regs)
1671	struct proc *p;
1672	struct reg *regs;
1673{
1674	struct trapframe *tp;
1675
1676	tp = TF_REGP(p);
1677	regs->r_es = tp->tf_es;
1678	regs->r_ds = tp->tf_ds;
1679	regs->r_edi = tp->tf_edi;
1680	regs->r_esi = tp->tf_esi;
1681	regs->r_ebp = tp->tf_ebp;
1682	regs->r_ebx = tp->tf_ebx;
1683	regs->r_edx = tp->tf_edx;
1684	regs->r_ecx = tp->tf_ecx;
1685	regs->r_eax = tp->tf_eax;
1686	regs->r_eip = tp->tf_eip;
1687	regs->r_cs = tp->tf_cs;
1688	regs->r_eflags = tp->tf_eflags;
1689	regs->r_esp = tp->tf_esp;
1690	regs->r_ss = tp->tf_ss;
1691	return (0);
1692}
1693
1694int
1695set_regs(p, regs)
1696	struct proc *p;
1697	struct reg *regs;
1698{
1699	struct trapframe *tp;
1700
1701	tp = TF_REGP(p);
1702	if (!EFLAGS_SECURE(regs->r_eflags, tp->tf_eflags) ||
1703	    !CS_SECURE(regs->r_cs))
1704		return (EINVAL);
1705	tp->tf_es = regs->r_es;
1706	tp->tf_ds = regs->r_ds;
1707	tp->tf_edi = regs->r_edi;
1708	tp->tf_esi = regs->r_esi;
1709	tp->tf_ebp = regs->r_ebp;
1710	tp->tf_ebx = regs->r_ebx;
1711	tp->tf_edx = regs->r_edx;
1712	tp->tf_ecx = regs->r_ecx;
1713	tp->tf_eax = regs->r_eax;
1714	tp->tf_eip = regs->r_eip;
1715	tp->tf_cs = regs->r_cs;
1716	tp->tf_eflags = regs->r_eflags;
1717	tp->tf_esp = regs->r_esp;
1718	tp->tf_ss = regs->r_ss;
1719	return (0);
1720}
1721
1722#ifndef DDB
1723void
1724Debugger(const char *msg)
1725{
1726	printf("Debugger(\"%s\") called.\n", msg);
1727}
1728#endif /* no DDB */
1729
1730#include <sys/disklabel.h>
1731#define b_cylin	b_resid
1732/*
1733 * Determine the size of the transfer, and make sure it is
1734 * within the boundaries of the partition. Adjust transfer
1735 * if needed, and signal errors or early completion.
1736 */
1737int
1738bounds_check_with_label(struct buf *bp, struct disklabel *lp, int wlabel)
1739{
1740        struct partition *p = lp->d_partitions + dkpart(bp->b_dev);
1741        int labelsect = lp->d_partitions[0].p_offset;
1742        int maxsz = p->p_size,
1743                sz = (bp->b_bcount + DEV_BSIZE - 1) >> DEV_BSHIFT;
1744
1745        /* overwriting disk label ? */
1746        /* XXX should also protect bootstrap in first 8K */
1747        if (bp->b_blkno + p->p_offset <= LABELSECTOR + labelsect &&
1748#if LABELSECTOR != 0
1749            bp->b_blkno + p->p_offset + sz > LABELSECTOR + labelsect &&
1750#endif
1751            (bp->b_flags & B_READ) == 0 && wlabel == 0) {
1752                bp->b_error = EROFS;
1753                goto bad;
1754        }
1755
1756#if     defined(DOSBBSECTOR) && defined(notyet)
1757        /* overwriting master boot record? */
1758        if (bp->b_blkno + p->p_offset <= DOSBBSECTOR &&
1759            (bp->b_flags & B_READ) == 0 && wlabel == 0) {
1760                bp->b_error = EROFS;
1761                goto bad;
1762        }
1763#endif
1764
1765        /* beyond partition? */
1766        if (bp->b_blkno < 0 || bp->b_blkno + sz > maxsz) {
1767                /* if exactly at end of disk, return an EOF */
1768                if (bp->b_blkno == maxsz) {
1769                        bp->b_resid = bp->b_bcount;
1770                        return(0);
1771                }
1772                /* or truncate if part of it fits */
1773                sz = maxsz - bp->b_blkno;
1774                if (sz <= 0) {
1775                        bp->b_error = EINVAL;
1776                        goto bad;
1777                }
1778                bp->b_bcount = sz << DEV_BSHIFT;
1779        }
1780
1781        /* calculate cylinder for disksort to order transfers with */
1782        bp->b_pblkno = bp->b_blkno + p->p_offset;
1783        bp->b_cylin = bp->b_pblkno / lp->d_secpercyl;
1784        return(1);
1785
1786bad:
1787        bp->b_flags |= B_ERROR;
1788        return(-1);
1789}
1790
1791int
1792disk_externalize(int drive, void *userp, size_t *maxlen)
1793{
1794	if(*maxlen < sizeof drive) {
1795		return ENOMEM;
1796	}
1797
1798	*maxlen -= sizeof drive;
1799	return copyout(&drive, userp, sizeof drive);
1800}
1801