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