]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/amd64/amd64/machdep.c
Save %gs in sigcontext when delivering a signal and restore them upon
[FreeBSD/FreeBSD.git] / sys / amd64 / amd64 / machdep.c
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  * $FreeBSD$
39  */
40
41 #include "apm.h"
42 #include "ether.h"
43 #include "npx.h"
44 #include "opt_atalk.h"
45 #include "opt_cpu.h"
46 #include "opt_ddb.h"
47 #include "opt_inet.h"
48 #include "opt_ipx.h"
49 #include "opt_maxmem.h"
50 #include "opt_msgbuf.h"
51 #include "opt_perfmon.h"
52 #include "opt_smp.h"
53 #include "opt_sysvipc.h"
54 #include "opt_user_ldt.h"
55 #include "opt_userconfig.h"
56
57 #include <sys/param.h>
58 #include <sys/systm.h>
59 #include <sys/sysproto.h>
60 #include <sys/signalvar.h>
61 #include <sys/kernel.h>
62 #include <sys/linker.h>
63 #include <sys/proc.h>
64 #include <sys/buf.h>
65 #include <sys/reboot.h>
66 #include <sys/callout.h>
67 #include <sys/malloc.h>
68 #include <sys/mbuf.h>
69 #include <sys/msgbuf.h>
70 #include <sys/sysent.h>
71 #include <sys/sysctl.h>
72 #include <sys/vmmeter.h>
73 #include <sys/bus.h>
74
75 #ifdef SYSVSHM
76 #include <sys/shm.h>
77 #endif
78
79 #ifdef SYSVMSG
80 #include <sys/msg.h>
81 #endif
82
83 #ifdef SYSVSEM
84 #include <sys/sem.h>
85 #endif
86
87 #include <vm/vm.h>
88 #include <vm/vm_param.h>
89 #include <vm/vm_prot.h>
90 #include <sys/lock.h>
91 #include <vm/vm_kern.h>
92 #include <vm/vm_object.h>
93 #include <vm/vm_page.h>
94 #include <vm/vm_map.h>
95 #include <vm/vm_pager.h>
96 #include <vm/vm_extern.h>
97
98 #include <sys/user.h>
99 #include <sys/exec.h>
100 #include <sys/cons.h>
101
102 #include <ddb/ddb.h>
103
104 #include <net/netisr.h>
105
106 #include <machine/cpu.h>
107 #include <machine/reg.h>
108 #include <machine/clock.h>
109 #include <machine/specialreg.h>
110 #include <machine/bootinfo.h>
111 #include <machine/ipl.h>
112 #include <machine/md_var.h>
113 #include <machine/pcb_ext.h>            /* pcb.h included via sys/user.h */
114 #ifdef SMP
115 #include <machine/smp.h>
116 #include <machine/globaldata.h>
117 #endif
118 #ifdef PERFMON
119 #include <machine/perfmon.h>
120 #endif
121
122 #ifdef OLD_BUS_ARCH
123 #include <i386/isa/isa_device.h>
124 #endif
125 #include <i386/isa/intr_machdep.h>
126 #include <isa/rtc.h>
127 #include <machine/vm86.h>
128 #include <machine/random.h>
129 #include <sys/ptrace.h>
130
131 extern void init386 __P((int first));
132 extern void dblfault_handler __P((void));
133
134 extern void printcpuinfo(void); /* XXX header file */
135 extern void earlysetcpuclass(void);     /* same header file */
136 extern void finishidentcpu(void);
137 extern void panicifcpuunsupported(void);
138 extern void initializecpu(void);
139
140 static void cpu_startup __P((void *));
141 SYSINIT(cpu, SI_SUB_CPU, SI_ORDER_FIRST, cpu_startup, NULL)
142
143 static MALLOC_DEFINE(M_MBUF, "mbuf", "mbuf");
144
145 int     _udatasel, _ucodesel;
146 u_int   atdevbase;
147
148 #if defined(SWTCH_OPTIM_STATS)
149 extern int swtch_optim_stats;
150 SYSCTL_INT(_debug, OID_AUTO, swtch_optim_stats,
151         CTLFLAG_RD, &swtch_optim_stats, 0, "");
152 SYSCTL_INT(_debug, OID_AUTO, tlb_flush_count,
153         CTLFLAG_RD, &tlb_flush_count, 0, "");
154 #endif
155
156 #ifdef PC98
157 static int      ispc98 = 1;
158 #else
159 static int      ispc98 = 0;
160 #endif
161 SYSCTL_INT(_machdep, OID_AUTO, ispc98, CTLFLAG_RD, &ispc98, 0, "");
162
163 int physmem = 0;
164 int cold = 1;
165
166 static int
167 sysctl_hw_physmem SYSCTL_HANDLER_ARGS
168 {
169         int error = sysctl_handle_int(oidp, 0, ctob(physmem), req);
170         return (error);
171 }
172
173 SYSCTL_PROC(_hw, HW_PHYSMEM, physmem, CTLTYPE_INT|CTLFLAG_RD,
174         0, 0, sysctl_hw_physmem, "I", "");
175
176 static int
177 sysctl_hw_usermem SYSCTL_HANDLER_ARGS
178 {
179         int error = sysctl_handle_int(oidp, 0,
180                 ctob(physmem - cnt.v_wire_count), req);
181         return (error);
182 }
183
184 SYSCTL_PROC(_hw, HW_USERMEM, usermem, CTLTYPE_INT|CTLFLAG_RD,
185         0, 0, sysctl_hw_usermem, "I", "");
186
187 static int
188 sysctl_hw_availpages SYSCTL_HANDLER_ARGS
189 {
190         int error = sysctl_handle_int(oidp, 0,
191                 i386_btop(avail_end - avail_start), req);
192         return (error);
193 }
194
195 SYSCTL_PROC(_hw, OID_AUTO, availpages, CTLTYPE_INT|CTLFLAG_RD,
196         0, 0, sysctl_hw_availpages, "I", "");
197
198 static int
199 sysctl_machdep_msgbuf SYSCTL_HANDLER_ARGS
200 {
201         int error;
202
203         /* Unwind the buffer, so that it's linear (possibly starting with
204          * some initial nulls).
205          */
206         error=sysctl_handle_opaque(oidp,msgbufp->msg_ptr+msgbufp->msg_bufr,
207                 msgbufp->msg_size-msgbufp->msg_bufr,req);
208         if(error) return(error);
209         if(msgbufp->msg_bufr>0) {
210                 error=sysctl_handle_opaque(oidp,msgbufp->msg_ptr,
211                         msgbufp->msg_bufr,req);
212         }
213         return(error);
214 }
215
216 SYSCTL_PROC(_machdep, OID_AUTO, msgbuf, CTLTYPE_STRING|CTLFLAG_RD,
217         0, 0, sysctl_machdep_msgbuf, "A","Contents of kernel message buffer");
218
219 static int msgbuf_clear;
220
221 static int
222 sysctl_machdep_msgbuf_clear SYSCTL_HANDLER_ARGS
223 {
224         int error;
225         error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2,
226                 req);
227         if (!error && req->newptr) {
228                 /* Clear the buffer and reset write pointer */
229                 bzero(msgbufp->msg_ptr,msgbufp->msg_size);
230                 msgbufp->msg_bufr=msgbufp->msg_bufx=0;
231                 msgbuf_clear=0;
232         }
233         return (error);
234 }
235
236 SYSCTL_PROC(_machdep, OID_AUTO, msgbuf_clear, CTLTYPE_INT|CTLFLAG_RW,
237         &msgbuf_clear, 0, sysctl_machdep_msgbuf_clear, "I",
238         "Clear kernel message buffer");
239
240 int bootverbose = 0, Maxmem = 0;
241 long dumplo;
242
243 vm_offset_t phys_avail[10];
244
245 /* must be 2 less so 0 0 can signal end of chunks */
246 #define PHYS_AVAIL_ARRAY_END ((sizeof(phys_avail) / sizeof(vm_offset_t)) - 2)
247
248 static vm_offset_t buffer_sva, buffer_eva;
249 vm_offset_t clean_sva, clean_eva;
250 static vm_offset_t pager_sva, pager_eva;
251
252 #define offsetof(type, member)  ((size_t)(&((type *)0)->member))
253
254 static void
255 cpu_startup(dummy)
256         void *dummy;
257 {
258         register unsigned i;
259         register caddr_t v;
260         vm_offset_t maxaddr;
261         vm_size_t size = 0;
262         int firstaddr;
263         vm_offset_t minaddr;
264
265         if (boothowto & RB_VERBOSE)
266                 bootverbose++;
267
268         /*
269          * Good {morning,afternoon,evening,night}.
270          */
271         printf(version);
272         earlysetcpuclass();
273         startrtclock();
274         printcpuinfo();
275         panicifcpuunsupported();
276 #ifdef PERFMON
277         perfmon_init();
278 #endif
279         printf("real memory  = %u (%uK bytes)\n", ptoa(Maxmem), ptoa(Maxmem) / 1024);
280         /*
281          * Display any holes after the first chunk of extended memory.
282          */
283         if (bootverbose) {
284                 int indx;
285
286                 printf("Physical memory chunk(s):\n");
287                 for (indx = 0; phys_avail[indx + 1] != 0; indx += 2) {
288                         int size1 = phys_avail[indx + 1] - phys_avail[indx];
289
290                         printf("0x%08x - 0x%08x, %u bytes (%u pages)\n",
291                             phys_avail[indx], phys_avail[indx + 1] - 1, size1,
292                             size1 / PAGE_SIZE);
293                 }
294         }
295
296         /*
297          * Calculate callout wheel size
298          */
299         for (callwheelsize = 1, callwheelbits = 0;
300              callwheelsize < ncallout;
301              callwheelsize <<= 1, ++callwheelbits)
302                 ;
303         callwheelmask = callwheelsize - 1;
304
305         /*
306          * Allocate space for system data structures.
307          * The first available kernel virtual address is in "v".
308          * As pages of kernel virtual memory are allocated, "v" is incremented.
309          * As pages of memory are allocated and cleared,
310          * "firstaddr" is incremented.
311          * An index into the kernel page table corresponding to the
312          * virtual memory address maintained in "v" is kept in "mapaddr".
313          */
314
315         /*
316          * Make two passes.  The first pass calculates how much memory is
317          * needed and allocates it.  The second pass assigns virtual
318          * addresses to the various data structures.
319          */
320         firstaddr = 0;
321 again:
322         v = (caddr_t)firstaddr;
323
324 #define valloc(name, type, num) \
325             (name) = (type *)v; v = (caddr_t)((name)+(num))
326 #define valloclim(name, type, num, lim) \
327             (name) = (type *)v; v = (caddr_t)((lim) = ((name)+(num)))
328
329         valloc(callout, struct callout, ncallout);
330         valloc(callwheel, struct callout_tailq, callwheelsize);
331 #ifdef SYSVSHM
332         valloc(shmsegs, struct shmid_ds, shminfo.shmmni);
333 #endif
334 #ifdef SYSVSEM
335         valloc(sema, struct semid_ds, seminfo.semmni);
336         valloc(sem, struct sem, seminfo.semmns);
337         /* This is pretty disgusting! */
338         valloc(semu, int, (seminfo.semmnu * seminfo.semusz) / sizeof(int));
339 #endif
340 #ifdef SYSVMSG
341         valloc(msgpool, char, msginfo.msgmax);
342         valloc(msgmaps, struct msgmap, msginfo.msgseg);
343         valloc(msghdrs, struct msg, msginfo.msgtql);
344         valloc(msqids, struct msqid_ds, msginfo.msgmni);
345 #endif
346
347         if (nbuf == 0) {
348                 nbuf = 30;
349                 if (physmem > 1024)
350                         nbuf += min((physmem - 1024) / 8, 2048);
351                 if (physmem > 16384)
352                         nbuf += (physmem - 16384) / 20;
353         }
354         nswbuf = max(min(nbuf/4, 256), 16);
355
356         valloc(swbuf, struct buf, nswbuf);
357         valloc(buf, struct buf, nbuf);
358         v = bufhashinit(v);
359
360         /*
361          * End of first pass, size has been calculated so allocate memory
362          */
363         if (firstaddr == 0) {
364                 size = (vm_size_t)(v - firstaddr);
365                 firstaddr = (int)kmem_alloc(kernel_map, round_page(size));
366                 if (firstaddr == 0)
367                         panic("startup: no room for tables");
368                 goto again;
369         }
370
371         /*
372          * End of second pass, addresses have been assigned
373          */
374         if ((vm_size_t)(v - firstaddr) != size)
375                 panic("startup: table size inconsistency");
376
377         clean_map = kmem_suballoc(kernel_map, &clean_sva, &clean_eva,
378                         (nbuf*BKVASIZE) + (nswbuf*MAXPHYS) + pager_map_size);
379         buffer_map = kmem_suballoc(clean_map, &buffer_sva, &buffer_eva,
380                                 (nbuf*BKVASIZE));
381         pager_map = kmem_suballoc(clean_map, &pager_sva, &pager_eva,
382                                 (nswbuf*MAXPHYS) + pager_map_size);
383         pager_map->system_map = 1;
384         exec_map = kmem_suballoc(kernel_map, &minaddr, &maxaddr,
385                                 (16*(ARG_MAX+(PAGE_SIZE*3))));
386
387         /*
388          * Finally, allocate mbuf pool.  Since mclrefcnt is an off-size
389          * we use the more space efficient malloc in place of kmem_alloc.
390          */
391         {
392                 vm_offset_t mb_map_size;
393
394                 mb_map_size = nmbufs * MSIZE + nmbclusters * MCLBYTES;
395                 mb_map_size = roundup2(mb_map_size, max(MCLBYTES, PAGE_SIZE));
396                 mclrefcnt = malloc(mb_map_size / MCLBYTES, M_MBUF, M_NOWAIT);
397                 bzero(mclrefcnt, mb_map_size / MCLBYTES);
398                 mb_map = kmem_suballoc(kmem_map, (vm_offset_t *)&mbutl, &maxaddr,
399                         mb_map_size);
400                 mb_map->system_map = 1;
401         }
402
403         /*
404          * Initialize callouts
405          */
406         SLIST_INIT(&callfree);
407         for (i = 0; i < ncallout; i++) {
408                 callout_init(&callout[i]);
409                 callout[i].c_flags = CALLOUT_LOCAL_ALLOC;
410                 SLIST_INSERT_HEAD(&callfree, &callout[i], c_links.sle);
411         }
412
413         for (i = 0; i < callwheelsize; i++) {
414                 TAILQ_INIT(&callwheel[i]);
415         }
416
417 #if defined(USERCONFIG)
418         userconfig();
419         cninit();               /* the preferred console may have changed */
420 #endif
421
422         printf("avail memory = %u (%uK bytes)\n", ptoa(cnt.v_free_count),
423             ptoa(cnt.v_free_count) / 1024);
424
425         /*
426          * Set up buffers, so they can be used to read disk labels.
427          */
428         bufinit();
429         vm_pager_bufferinit();
430
431 #ifdef SMP
432         /*
433          * OK, enough kmem_alloc/malloc state should be up, lets get on with it!
434          */
435         mp_start();                     /* fire up the APs and APICs */
436         mp_announce();
437 #endif  /* SMP */
438 }
439
440 int
441 register_netisr(num, handler)
442         int num;
443         netisr_t *handler;
444 {
445         
446         if (num < 0 || num >= (sizeof(netisrs)/sizeof(*netisrs)) ) {
447                 printf("register_netisr: bad isr number: %d\n", num);
448                 return (EINVAL);
449         }
450         netisrs[num] = handler;
451         return (0);
452 }
453
454 void
455 netisr_sysinit(data)
456         void *data;
457 {
458         const struct netisrtab *nit;
459
460         nit = (const struct netisrtab *)data;
461         register_netisr(nit->nit_num, nit->nit_isr);
462 }
463
464 /*
465  * Send an interrupt to process.
466  *
467  * Stack is set up to allow sigcode stored
468  * at top to call routine, followed by kcall
469  * to sigreturn routine below.  After sigreturn
470  * resets the signal mask, the stack, and the
471  * frame pointer, it returns to the user
472  * specified pc, psl.
473  */
474 void
475 sendsig(catcher, sig, mask, code)
476         sig_t catcher;
477         int sig, mask;
478         u_long code;
479 {
480         register struct proc *p = curproc;
481         register struct trapframe *regs;
482         register struct sigframe *fp;
483         struct sigframe sf;
484         struct sigacts *psp = p->p_sigacts;
485         int oonstack;
486
487         regs = p->p_md.md_regs;
488         oonstack = psp->ps_sigstk.ss_flags & SS_ONSTACK;
489         /*
490          * Allocate and validate space for the signal handler context.
491          */
492         if ((psp->ps_flags & SAS_ALTSTACK) && !oonstack &&
493             (psp->ps_sigonstack & sigmask(sig))) {
494                 fp = (struct sigframe *)(psp->ps_sigstk.ss_sp +
495                     psp->ps_sigstk.ss_size - sizeof(struct sigframe));
496                 psp->ps_sigstk.ss_flags |= SS_ONSTACK;
497         } else {
498                 fp = (struct sigframe *)regs->tf_esp - 1;
499         }
500
501         /*
502          * grow() will return FALSE if the fp will not fit inside the stack
503          *      and the stack can not be grown. useracc will return FALSE
504          *      if access is denied.
505          */
506         if ((grow_stack (p, (int)fp) == FALSE) ||
507             (useracc((caddr_t)fp, sizeof(struct sigframe), B_WRITE) == FALSE)) {
508                 /*
509                  * Process has trashed its stack; give it an illegal
510                  * instruction to halt it in its tracks.
511                  */
512 #ifdef DEBUG
513                 printf("process %d has trashed its stack\n", p->p_pid);
514 #endif
515                 SIGACTION(p, SIGILL) = SIG_DFL;
516                 sig = sigmask(SIGILL);
517                 p->p_sigignore &= ~sig;
518                 p->p_sigcatch &= ~sig;
519                 p->p_sigmask &= ~sig;
520                 psignal(p, SIGILL);
521                 return;
522         }
523
524         /*
525          * Build the argument list for the signal handler.
526          */
527         if (p->p_sysent->sv_sigtbl) {
528                 if (sig < p->p_sysent->sv_sigsize)
529                         sig = p->p_sysent->sv_sigtbl[sig];
530                 else
531                         sig = p->p_sysent->sv_sigsize + 1;
532         }
533         sf.sf_signum = sig;
534         sf.sf_scp = (register_t)&fp->sf_siginfo.si_sc;
535         if (p->p_sigacts->ps_siginfo & sigmask(sig)) {
536                 /*
537                  * Signal handler installed with SA_SIGINFO.
538                  */
539                 sf.sf_arg2 = (register_t)&fp->sf_siginfo;
540                 sf.sf_siginfo.si_signo = sig;
541                 sf.sf_siginfo.si_code = code;
542                 sf.sf_ahu.sf_action = (__siginfohandler_t *)catcher;
543         } else {
544                 /* 
545                  * Old FreeBSD-style arguments.
546                  */
547                 sf.sf_arg2 = code;
548                 sf.sf_ahu.sf_handler = catcher;
549         }
550
551         sf.sf_addr = (char *) regs->tf_err;
552
553         /* save scratch registers */
554         sf.sf_siginfo.si_sc.sc_eax = regs->tf_eax;
555         sf.sf_siginfo.si_sc.sc_ebx = regs->tf_ebx;
556         sf.sf_siginfo.si_sc.sc_ecx = regs->tf_ecx;
557         sf.sf_siginfo.si_sc.sc_edx = regs->tf_edx;
558         sf.sf_siginfo.si_sc.sc_esi = regs->tf_esi;
559         sf.sf_siginfo.si_sc.sc_edi = regs->tf_edi;
560         sf.sf_siginfo.si_sc.sc_cs = regs->tf_cs;
561         sf.sf_siginfo.si_sc.sc_ds = regs->tf_ds;
562         sf.sf_siginfo.si_sc.sc_ss = regs->tf_ss;
563         sf.sf_siginfo.si_sc.sc_es = regs->tf_es;
564         sf.sf_siginfo.si_sc.sc_fs = regs->tf_fs;
565         sf.sf_siginfo.si_sc.sc_gs = rgs();
566         sf.sf_siginfo.si_sc.sc_isp = regs->tf_isp;
567
568         /*
569          * Build the signal context to be used by sigreturn.
570          */
571         sf.sf_siginfo.si_sc.sc_onstack = oonstack;
572         sf.sf_siginfo.si_sc.sc_mask = mask;
573         sf.sf_siginfo.si_sc.sc_sp = regs->tf_esp;
574         sf.sf_siginfo.si_sc.sc_fp = regs->tf_ebp;
575         sf.sf_siginfo.si_sc.sc_pc = regs->tf_eip;
576         sf.sf_siginfo.si_sc.sc_ps = regs->tf_eflags;
577         sf.sf_siginfo.si_sc.sc_trapno = regs->tf_trapno;
578         sf.sf_siginfo.si_sc.sc_err = regs->tf_err;
579
580         /*
581          * If we're a vm86 process, we want to save the segment registers.
582          * We also change eflags to be our emulated eflags, not the actual
583          * eflags.
584          */
585         if (regs->tf_eflags & PSL_VM) {
586                 struct trapframe_vm86 *tf = (struct trapframe_vm86 *)regs;
587                 struct vm86_kernel *vm86 = &p->p_addr->u_pcb.pcb_ext->ext_vm86;
588
589                 sf.sf_siginfo.si_sc.sc_gs = tf->tf_vm86_gs;
590                 sf.sf_siginfo.si_sc.sc_fs = tf->tf_vm86_fs;
591                 sf.sf_siginfo.si_sc.sc_es = tf->tf_vm86_es;
592                 sf.sf_siginfo.si_sc.sc_ds = tf->tf_vm86_ds;
593
594                 if (vm86->vm86_has_vme == 0)
595                         sf.sf_siginfo.si_sc.sc_ps = (tf->tf_eflags & ~(PSL_VIF | PSL_VIP))
596                             | (vm86->vm86_eflags & (PSL_VIF | PSL_VIP));
597
598                 /*
599                  * We should never have PSL_T set when returning from vm86
600                  * mode.  It may be set here if we deliver a signal before
601                  * getting to vm86 mode, so turn it off.
602                  *
603                  * Clear PSL_NT to inhibit T_TSSFLT faults on return from
604                  * syscalls made by the signal handler.  This just avoids
605                  * wasting time for our lazy fixup of such faults.  PSL_NT
606                  * does nothing in vm86 mode, but vm86 programs can set it
607                  * almost legitimately in probes for old cpu types.
608                  */
609                 tf->tf_eflags &= ~(PSL_VM | PSL_NT | PSL_T | PSL_VIF | PSL_VIP);
610         }
611
612         /*
613          * Copy the sigframe out to the user's stack.
614          */
615         if (copyout(&sf, fp, sizeof(struct sigframe)) != 0) {
616                 /*
617                  * Something is wrong with the stack pointer.
618                  * ...Kill the process.
619                  */
620                 sigexit(p, SIGILL);
621         }
622
623         regs->tf_esp = (int)fp;
624         regs->tf_eip = PS_STRINGS - *(p->p_sysent->sv_szsigcode);
625         regs->tf_cs = _ucodesel;
626         regs->tf_ds = _udatasel;
627         regs->tf_es = _udatasel;
628         regs->tf_fs = _udatasel;
629         regs->tf_ss = _udatasel;
630 }
631
632 /*
633  * System call to cleanup state after a signal
634  * has been taken.  Reset signal mask and
635  * stack state from context left by sendsig (above).
636  * Return to previous pc and psl as specified by
637  * context left by sendsig. Check carefully to
638  * make sure that the user has not modified the
639  * state to gain improper privileges.
640  */
641 int
642 sigreturn(p, uap)
643         struct proc *p;
644         struct sigreturn_args /* {
645                 struct sigcontext *sigcntxp;
646         } */ *uap;
647 {
648         register struct sigcontext *scp;
649         register struct sigframe *fp;
650         register struct trapframe *regs = p->p_md.md_regs;
651         int eflags;
652
653         /*
654          * (XXX old comment) regs->tf_esp points to the return address.
655          * The user scp pointer is above that.
656          * The return address is faked in the signal trampoline code
657          * for consistency.
658          */
659         scp = uap->sigcntxp;
660         fp = (struct sigframe *)
661              ((caddr_t)scp - offsetof(struct sigframe, sf_siginfo.si_sc));
662
663         if (useracc((caddr_t)fp, sizeof (*fp), B_WRITE) == 0)
664                 return(EFAULT);
665
666         eflags = scp->sc_ps;
667         if (eflags & PSL_VM) {
668                 struct trapframe_vm86 *tf = (struct trapframe_vm86 *)regs;
669                 struct vm86_kernel *vm86;
670
671                 /*
672                  * if pcb_ext == 0 or vm86_inited == 0, the user hasn't
673                  * set up the vm86 area, and we can't enter vm86 mode.
674                  */
675                 if (p->p_addr->u_pcb.pcb_ext == 0)
676                         return (EINVAL);
677                 vm86 = &p->p_addr->u_pcb.pcb_ext->ext_vm86;
678                 if (vm86->vm86_inited == 0)
679                         return (EINVAL);
680
681                 /* go back to user mode if both flags are set */
682                 if ((eflags & PSL_VIP) && (eflags & PSL_VIF))
683                         trapsignal(p, SIGBUS, 0);
684
685                 if (vm86->vm86_has_vme) {
686                         eflags = (tf->tf_eflags & ~VME_USERCHANGE) |
687                             (eflags & VME_USERCHANGE) | PSL_VM;
688                 } else {
689                         vm86->vm86_eflags = eflags;     /* save VIF, VIP */
690                         eflags = (tf->tf_eflags & ~VM_USERCHANGE) |                                         (eflags & VM_USERCHANGE) | PSL_VM;
691                 }
692                 tf->tf_vm86_ds = scp->sc_ds;
693                 tf->tf_vm86_es = scp->sc_es;
694                 tf->tf_vm86_fs = scp->sc_fs;
695                 tf->tf_vm86_gs = scp->sc_gs;
696                 tf->tf_ds = _udatasel;
697                 tf->tf_es = _udatasel;
698                 tf->tf_fs = _udatasel;
699         } else {
700                 /*
701                  * Don't allow users to change privileged or reserved flags.
702                  */
703 #define EFLAGS_SECURE(ef, oef)  ((((ef) ^ (oef)) & ~PSL_USERCHANGE) == 0)
704                 /*
705                  * XXX do allow users to change the privileged flag PSL_RF.
706                  * The cpu sets PSL_RF in tf_eflags for faults.  Debuggers
707                  * should sometimes set it there too.  tf_eflags is kept in
708                  * the signal context during signal handling and there is no
709                  * other place to remember it, so the PSL_RF bit may be
710                  * corrupted by the signal handler without us knowing.
711                  * Corruption of the PSL_RF bit at worst causes one more or
712                  * one less debugger trap, so allowing it is fairly harmless.
713                  */
714                 if (!EFLAGS_SECURE(eflags & ~PSL_RF, regs->tf_eflags & ~PSL_RF)) {
715 #ifdef DEBUG
716                         printf("sigreturn: eflags = 0x%x\n", eflags);
717 #endif
718                         return(EINVAL);
719                 }
720
721                 /*
722                  * Don't allow users to load a valid privileged %cs.  Let the
723                  * hardware check for invalid selectors, excess privilege in
724                  * other selectors, invalid %eip's and invalid %esp's.
725                  */
726 #define CS_SECURE(cs)   (ISPL(cs) == SEL_UPL)
727                 if (!CS_SECURE(scp->sc_cs)) {
728 #ifdef DEBUG
729                         printf("sigreturn: cs = 0x%x\n", scp->sc_cs);
730 #endif
731                         trapsignal(p, SIGBUS, T_PROTFLT);
732                         return(EINVAL);
733                 }
734                 regs->tf_ds = scp->sc_ds;
735                 regs->tf_es = scp->sc_es;
736                 regs->tf_fs = scp->sc_fs;
737         }
738
739         /* restore scratch registers */
740         regs->tf_eax = scp->sc_eax;
741         regs->tf_ebx = scp->sc_ebx;
742         regs->tf_ecx = scp->sc_ecx;
743         regs->tf_edx = scp->sc_edx;
744         regs->tf_esi = scp->sc_esi;
745         regs->tf_edi = scp->sc_edi;
746         regs->tf_cs = scp->sc_cs;
747         regs->tf_ss = scp->sc_ss;
748         regs->tf_isp = scp->sc_isp;
749
750         if (useracc((caddr_t)scp, sizeof (*scp), B_WRITE) == 0)
751                 return(EINVAL);
752
753         if (scp->sc_onstack & 01)
754                 p->p_sigacts->ps_sigstk.ss_flags |= SS_ONSTACK;
755         else
756                 p->p_sigacts->ps_sigstk.ss_flags &= ~SS_ONSTACK;
757         p->p_sigmask = scp->sc_mask & ~sigcantmask;
758         regs->tf_ebp = scp->sc_fp;
759         regs->tf_esp = scp->sc_sp;
760         regs->tf_eip = scp->sc_pc;
761         regs->tf_eflags = eflags;
762         return(EJUSTRETURN);
763 }
764
765 /*
766  * Machine dependent boot() routine
767  *
768  * I haven't seen anything to put here yet
769  * Possibly some stuff might be grafted back here from boot()
770  */
771 void
772 cpu_boot(int howto)
773 {
774 }
775
776 /*
777  * Shutdown the CPU as much as possible
778  */
779 void
780 cpu_halt(void)
781 {
782         for (;;)
783                 __asm__ ("hlt");
784 }
785
786 /*
787  * Clear registers on exec
788  */
789 void
790 setregs(p, entry, stack, ps_strings)
791         struct proc *p;
792         u_long entry;
793         u_long stack;
794         u_long ps_strings;
795 {
796         struct trapframe *regs = p->p_md.md_regs;
797         struct pcb *pcb = &p->p_addr->u_pcb;
798
799 #ifdef USER_LDT
800         /* was i386_user_cleanup() in NetBSD */
801         if (pcb->pcb_ldt) {
802                 if (pcb == curpcb) {
803                         lldt(_default_ldt);
804                         currentldt = _default_ldt;
805                 }
806                 kmem_free(kernel_map, (vm_offset_t)pcb->pcb_ldt,
807                         pcb->pcb_ldt_len * sizeof(union descriptor));
808                 pcb->pcb_ldt_len = (int)pcb->pcb_ldt = 0;
809         }
810 #endif
811   
812         bzero((char *)regs, sizeof(struct trapframe));
813         regs->tf_eip = entry;
814         regs->tf_esp = stack;
815         regs->tf_eflags = PSL_USER | (regs->tf_eflags & PSL_T);
816         regs->tf_ss = _udatasel;
817         regs->tf_ds = _udatasel;
818         regs->tf_es = _udatasel;
819         regs->tf_fs = _udatasel;
820         regs->tf_cs = _ucodesel;
821
822         /* PS_STRINGS value for BSD/OS binaries.  It is 0 for non-BSD/OS. */
823         regs->tf_ebx = ps_strings;
824
825         /* reset %gs as well */
826         pcb->pcb_gs = _udatasel;
827         if (pcb == curpcb) {
828                 load_gs(_udatasel);
829         }
830
831         /*
832          * Initialize the math emulator (if any) for the current process.
833          * Actually, just clear the bit that says that the emulator has
834          * been initialized.  Initialization is delayed until the process
835          * traps to the emulator (if it is done at all) mainly because
836          * emulators don't provide an entry point for initialization.
837          */
838         p->p_addr->u_pcb.pcb_flags &= ~FP_SOFTFP;
839
840         /*
841          * Arrange to trap the next npx or `fwait' instruction (see npx.c
842          * for why fwait must be trapped at least if there is an npx or an
843          * emulator).  This is mainly to handle the case where npx0 is not
844          * configured, since the npx routines normally set up the trap
845          * otherwise.  It should be done only at boot time, but doing it
846          * here allows modifying `npx_exists' for testing the emulator on
847          * systems with an npx.
848          */
849         load_cr0(rcr0() | CR0_MP | CR0_TS);
850
851 #if NNPX > 0
852         /* Initialize the npx (if any) for the current process. */
853         npxinit(__INITIAL_NPXCW__);
854 #endif
855
856       /*
857        * XXX - Linux emulator
858        * Make sure sure edx is 0x0 on entry. Linux binaries depend
859        * on it.
860        */
861       p->p_retval[1] = 0;
862 }
863
864 static int
865 sysctl_machdep_adjkerntz SYSCTL_HANDLER_ARGS
866 {
867         int error;
868         error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2,
869                 req);
870         if (!error && req->newptr)
871                 resettodr();
872         return (error);
873 }
874
875 SYSCTL_PROC(_machdep, CPU_ADJKERNTZ, adjkerntz, CTLTYPE_INT|CTLFLAG_RW,
876         &adjkerntz, 0, sysctl_machdep_adjkerntz, "I", "");
877
878 SYSCTL_INT(_machdep, CPU_DISRTCSET, disable_rtc_set,
879         CTLFLAG_RW, &disable_rtc_set, 0, "");
880
881 SYSCTL_STRUCT(_machdep, CPU_BOOTINFO, bootinfo, 
882         CTLFLAG_RD, &bootinfo, bootinfo, "");
883
884 SYSCTL_INT(_machdep, CPU_WALLCLOCK, wall_cmos_clock,
885         CTLFLAG_RW, &wall_cmos_clock, 0, "");
886
887 /*
888  * Initialize 386 and configure to run kernel
889  */
890
891 /*
892  * Initialize segments & interrupt table
893  */
894
895 int _default_ldt;
896 #ifdef SMP
897 union descriptor gdt[NGDT * NCPU];      /* global descriptor table */
898 #else
899 union descriptor gdt[NGDT];             /* global descriptor table */
900 #endif
901 static struct gate_descriptor idt0[NIDT];
902 struct gate_descriptor *idt = &idt0[0]; /* interrupt descriptor table */
903 union descriptor ldt[NLDT];             /* local descriptor table */
904 #ifdef SMP
905 /* table descriptors - used to load tables by microp */
906 struct region_descriptor r_gdt, r_idt;
907 #endif
908
909 #ifndef SMP
910 extern struct segment_descriptor common_tssd, *tss_gdt;
911 #endif
912 int private_tss;                        /* flag indicating private tss */
913
914 #if defined(I586_CPU) && !defined(NO_F00F_HACK)
915 extern int has_f00f_bug;
916 #endif
917
918 static struct i386tss dblfault_tss;
919 static char dblfault_stack[PAGE_SIZE];
920
921 extern  struct user *proc0paddr;
922
923
924 /* software prototypes -- in more palatable form */
925 struct soft_segment_descriptor gdt_segs[] = {
926 /* GNULL_SEL    0 Null Descriptor */
927 {       0x0,                    /* segment base address  */
928         0x0,                    /* length */
929         0,                      /* segment type */
930         0,                      /* segment descriptor priority level */
931         0,                      /* segment descriptor present */
932         0, 0,
933         0,                      /* default 32 vs 16 bit size */
934         0                       /* limit granularity (byte/page units)*/ },
935 /* GCODE_SEL    1 Code Descriptor for kernel */
936 {       0x0,                    /* segment base address  */
937         0xfffff,                /* length - all address space */
938         SDT_MEMERA,             /* segment type */
939         0,                      /* segment descriptor priority level */
940         1,                      /* segment descriptor present */
941         0, 0,
942         1,                      /* default 32 vs 16 bit size */
943         1                       /* limit granularity (byte/page units)*/ },
944 /* GDATA_SEL    2 Data Descriptor for kernel */
945 {       0x0,                    /* segment base address  */
946         0xfffff,                /* length - all address space */
947         SDT_MEMRWA,             /* segment type */
948         0,                      /* segment descriptor priority level */
949         1,                      /* segment descriptor present */
950         0, 0,
951         1,                      /* default 32 vs 16 bit size */
952         1                       /* limit granularity (byte/page units)*/ },
953 /* GPRIV_SEL    3 SMP Per-Processor Private Data Descriptor */
954 {       0x0,                    /* segment base address  */
955         0xfffff,                /* length - all address space */
956         SDT_MEMRWA,             /* segment type */
957         0,                      /* segment descriptor priority level */
958         1,                      /* segment descriptor present */
959         0, 0,
960         1,                      /* default 32 vs 16 bit size */
961         1                       /* limit granularity (byte/page units)*/ },
962 /* GPROC0_SEL   4 Proc 0 Tss Descriptor */
963 {
964         0x0,                    /* segment base address */
965         sizeof(struct i386tss)-1,/* length - all address space */
966         SDT_SYS386TSS,          /* segment type */
967         0,                      /* segment descriptor priority level */
968         1,                      /* segment descriptor present */
969         0, 0,
970         0,                      /* unused - default 32 vs 16 bit size */
971         0                       /* limit granularity (byte/page units)*/ },
972 /* GLDT_SEL     5 LDT Descriptor */
973 {       (int) ldt,              /* segment base address  */
974         sizeof(ldt)-1,          /* length - all address space */
975         SDT_SYSLDT,             /* segment type */
976         SEL_UPL,                /* segment descriptor priority level */
977         1,                      /* segment descriptor present */
978         0, 0,
979         0,                      /* unused - default 32 vs 16 bit size */
980         0                       /* limit granularity (byte/page units)*/ },
981 /* GUSERLDT_SEL 6 User LDT Descriptor per process */
982 {       (int) ldt,              /* segment base address  */
983         (512 * sizeof(union descriptor)-1),             /* length */
984         SDT_SYSLDT,             /* segment type */
985         0,                      /* segment descriptor priority level */
986         1,                      /* segment descriptor present */
987         0, 0,
988         0,                      /* unused - default 32 vs 16 bit size */
989         0                       /* limit granularity (byte/page units)*/ },
990 /* GTGATE_SEL   7 Null Descriptor - Placeholder */
991 {       0x0,                    /* segment base address  */
992         0x0,                    /* length - all address space */
993         0,                      /* segment type */
994         0,                      /* segment descriptor priority level */
995         0,                      /* segment descriptor present */
996         0, 0,
997         0,                      /* default 32 vs 16 bit size */
998         0                       /* limit granularity (byte/page units)*/ },
999 /* GBIOSLOWMEM_SEL 8 BIOS access to realmode segment 0x40, must be #8 in GDT */
1000 {       0x400,                  /* segment base address */
1001         0xfffff,                /* length */
1002         SDT_MEMRWA,             /* segment type */
1003         0,                      /* segment descriptor priority level */
1004         1,                      /* segment descriptor present */
1005         0, 0,
1006         1,                      /* default 32 vs 16 bit size */
1007         1                       /* limit granularity (byte/page units)*/ },
1008 /* GPANIC_SEL   9 Panic Tss Descriptor */
1009 {       (int) &dblfault_tss,    /* segment base address  */
1010         sizeof(struct i386tss)-1,/* length - all address space */
1011         SDT_SYS386TSS,          /* segment type */
1012         0,                      /* segment descriptor priority level */
1013         1,                      /* segment descriptor present */
1014         0, 0,
1015         0,                      /* unused - default 32 vs 16 bit size */
1016         0                       /* limit granularity (byte/page units)*/ },
1017 /* GBIOSCODE32_SEL 10 BIOS 32-bit interface (32bit Code) */
1018 {       0,                      /* segment base address (overwritten)  */
1019         0xfffff,                /* length */
1020         SDT_MEMERA,             /* segment type */
1021         0,                      /* segment descriptor priority level */
1022         1,                      /* segment descriptor present */
1023         0, 0,
1024         0,                      /* default 32 vs 16 bit size */
1025         1                       /* limit granularity (byte/page units)*/ },
1026 /* GBIOSCODE16_SEL 11 BIOS 32-bit interface (16bit Code) */
1027 {       0,                      /* segment base address (overwritten)  */
1028         0xfffff,                /* length */
1029         SDT_MEMERA,             /* segment type */
1030         0,                      /* segment descriptor priority level */
1031         1,                      /* segment descriptor present */
1032         0, 0,
1033         0,                      /* default 32 vs 16 bit size */
1034         1                       /* limit granularity (byte/page units)*/ },
1035 /* GBIOSDATA_SEL 12 BIOS 32-bit interface (Data) */
1036 {       0,                      /* segment base address (overwritten) */
1037         0xfffff,                /* length */
1038         SDT_MEMRWA,             /* segment type */
1039         0,                      /* segment descriptor priority level */
1040         1,                      /* segment descriptor present */
1041         0, 0,
1042         1,                      /* default 32 vs 16 bit size */
1043         1                       /* limit granularity (byte/page units)*/ },
1044 /* GBIOSUTIL_SEL 13 BIOS 16-bit interface (Utility) */
1045 {       0,                      /* segment base address (overwritten) */
1046         0xfffff,                /* length */
1047         SDT_MEMRWA,             /* segment type */
1048         0,                      /* segment descriptor priority level */
1049         1,                      /* segment descriptor present */
1050         0, 0,
1051         0,                      /* default 32 vs 16 bit size */
1052         1                       /* limit granularity (byte/page units)*/ },
1053 /* GBIOSARGS_SEL 14 BIOS 16-bit interface (Arguments) */
1054 {       0,                      /* segment base address (overwritten) */
1055         0xfffff,                /* length */
1056         SDT_MEMRWA,             /* segment type */
1057         0,                      /* segment descriptor priority level */
1058         1,                      /* segment descriptor present */
1059         0, 0,
1060         0,                      /* default 32 vs 16 bit size */
1061         1                       /* limit granularity (byte/page units)*/ },
1062 };
1063
1064 static struct soft_segment_descriptor ldt_segs[] = {
1065         /* Null Descriptor - overwritten by call gate */
1066 {       0x0,                    /* segment base address  */
1067         0x0,                    /* length - all address space */
1068         0,                      /* segment type */
1069         0,                      /* segment descriptor priority level */
1070         0,                      /* segment descriptor present */
1071         0, 0,
1072         0,                      /* default 32 vs 16 bit size */
1073         0                       /* limit granularity (byte/page units)*/ },
1074         /* Null Descriptor - overwritten by call gate */
1075 {       0x0,                    /* segment base address  */
1076         0x0,                    /* length - all address space */
1077         0,                      /* segment type */
1078         0,                      /* segment descriptor priority level */
1079         0,                      /* segment descriptor present */
1080         0, 0,
1081         0,                      /* default 32 vs 16 bit size */
1082         0                       /* limit granularity (byte/page units)*/ },
1083         /* Null Descriptor - overwritten by call gate */
1084 {       0x0,                    /* segment base address  */
1085         0x0,                    /* length - all address space */
1086         0,                      /* segment type */
1087         0,                      /* segment descriptor priority level */
1088         0,                      /* segment descriptor present */
1089         0, 0,
1090         0,                      /* default 32 vs 16 bit size */
1091         0                       /* limit granularity (byte/page units)*/ },
1092         /* Code Descriptor for user */
1093 {       0x0,                    /* segment base address  */
1094         0xfffff,                /* length - all address space */
1095         SDT_MEMERA,             /* segment type */
1096         SEL_UPL,                /* segment descriptor priority level */
1097         1,                      /* segment descriptor present */
1098         0, 0,
1099         1,                      /* default 32 vs 16 bit size */
1100         1                       /* limit granularity (byte/page units)*/ },
1101         /* Null Descriptor - overwritten by call gate */
1102 {       0x0,                    /* segment base address  */
1103         0x0,                    /* length - all address space */
1104         0,                      /* segment type */
1105         0,                      /* segment descriptor priority level */
1106         0,                      /* segment descriptor present */
1107         0, 0,
1108         0,                      /* default 32 vs 16 bit size */
1109         0                       /* limit granularity (byte/page units)*/ },
1110         /* Data Descriptor for user */
1111 {       0x0,                    /* segment base address  */
1112         0xfffff,                /* length - all address space */
1113         SDT_MEMRWA,             /* segment type */
1114         SEL_UPL,                /* segment descriptor priority level */
1115         1,                      /* segment descriptor present */
1116         0, 0,
1117         1,                      /* default 32 vs 16 bit size */
1118         1                       /* limit granularity (byte/page units)*/ },
1119 };
1120
1121 void
1122 setidt(idx, func, typ, dpl, selec)
1123         int idx;
1124         inthand_t *func;
1125         int typ;
1126         int dpl;
1127         int selec;
1128 {
1129         struct gate_descriptor *ip;
1130
1131         ip = idt + idx;
1132         ip->gd_looffset = (int)func;
1133         ip->gd_selector = selec;
1134         ip->gd_stkcpy = 0;
1135         ip->gd_xx = 0;
1136         ip->gd_type = typ;
1137         ip->gd_dpl = dpl;
1138         ip->gd_p = 1;
1139         ip->gd_hioffset = ((int)func)>>16 ;
1140 }
1141
1142 #define IDTVEC(name)    __CONCAT(X,name)
1143
1144 extern inthand_t
1145         IDTVEC(div), IDTVEC(dbg), IDTVEC(nmi), IDTVEC(bpt), IDTVEC(ofl),
1146         IDTVEC(bnd), IDTVEC(ill), IDTVEC(dna), IDTVEC(fpusegm),
1147         IDTVEC(tss), IDTVEC(missing), IDTVEC(stk), IDTVEC(prot),
1148         IDTVEC(page), IDTVEC(mchk), IDTVEC(rsvd), IDTVEC(fpu), IDTVEC(align),
1149         IDTVEC(syscall), IDTVEC(int0x80_syscall);
1150
1151 void
1152 sdtossd(sd, ssd)
1153         struct segment_descriptor *sd;
1154         struct soft_segment_descriptor *ssd;
1155 {
1156         ssd->ssd_base  = (sd->sd_hibase << 24) | sd->sd_lobase;
1157         ssd->ssd_limit = (sd->sd_hilimit << 16) | sd->sd_lolimit;
1158         ssd->ssd_type  = sd->sd_type;
1159         ssd->ssd_dpl   = sd->sd_dpl;
1160         ssd->ssd_p     = sd->sd_p;
1161         ssd->ssd_def32 = sd->sd_def32;
1162         ssd->ssd_gran  = sd->sd_gran;
1163 }
1164
1165 #define PHYSMAP_SIZE    (2 * 8)
1166
1167 /*
1168  * Populate the (physmap) array with base/bound pairs describing the
1169  * available physical memory in the system, then test this memory and
1170  * build the phys_avail array describing the actually-available memory.
1171  *
1172  * If we cannot accurately determine the physical memory map, then use
1173  * value from the 0xE801 call, and failing that, the RTC.
1174  *
1175  * Total memory size may be set by the kernel environment variable
1176  * hw.physmem or the compile-time define MAXMEM.
1177  */
1178 static void
1179 getmemsize(int first)
1180 {
1181         int i, physmap_idx, pa_indx;
1182         u_int basemem, extmem;
1183         struct vm86frame vmf;
1184         struct vm86context vmc;
1185         vm_offset_t pa, physmap[PHYSMAP_SIZE];
1186         pt_entry_t pte;
1187         const char *cp;
1188         struct {
1189                 u_int64_t base;
1190                 u_int64_t length;
1191                 u_int32_t type;
1192         } *smap;
1193
1194         bzero(&vmf, sizeof(struct vm86frame));
1195         bzero(physmap, sizeof(physmap));
1196
1197         /*
1198          * Perform "base memory" related probes & setup
1199          */
1200         vm86_intcall(0x12, &vmf);
1201         basemem = vmf.vmf_ax;
1202         if (basemem > 640) {
1203                 printf("Preposterous BIOS basemem of %uK, truncating to 640K\n",
1204                         basemem);
1205                 basemem = 640;
1206         }
1207
1208         /*
1209          * XXX if biosbasemem is now < 640, there is a `hole'
1210          * between the end of base memory and the start of
1211          * ISA memory.  The hole may be empty or it may
1212          * contain BIOS code or data.  Map it read/write so
1213          * that the BIOS can write to it.  (Memory from 0 to
1214          * the physical end of the kernel is mapped read-only
1215          * to begin with and then parts of it are remapped.
1216          * The parts that aren't remapped form holes that
1217          * remain read-only and are unused by the kernel.
1218          * The base memory area is below the physical end of
1219          * the kernel and right now forms a read-only hole.
1220          * The part of it from PAGE_SIZE to
1221          * (trunc_page(biosbasemem * 1024) - 1) will be
1222          * remapped and used by the kernel later.)
1223          *
1224          * This code is similar to the code used in
1225          * pmap_mapdev, but since no memory needs to be
1226          * allocated we simply change the mapping.
1227          */
1228         for (pa = trunc_page(basemem * 1024);
1229              pa < ISA_HOLE_START; pa += PAGE_SIZE) {
1230                 pte = (pt_entry_t)vtopte(pa + KERNBASE);
1231                 *pte = pa | PG_RW | PG_V;
1232         }
1233
1234         /*
1235          * if basemem != 640, map pages r/w into vm86 page table so 
1236          * that the bios can scribble on it.
1237          */
1238         pte = (pt_entry_t)vm86paddr;
1239         for (i = basemem / 4; i < 160; i++)
1240                 pte[i] = (i << PAGE_SHIFT) | PG_V | PG_RW | PG_U;
1241
1242         /*
1243          * map page 1 R/W into the kernel page table so we can use it
1244          * as a buffer.  The kernel will unmap this page later.
1245          */
1246         pte = (pt_entry_t)vtopte(KERNBASE + (1 << PAGE_SHIFT));
1247         *pte = (1 << PAGE_SHIFT) | PG_RW | PG_V;
1248
1249         /*
1250          * get memory map with INT 15:E820
1251          */
1252 #define SMAPSIZ         sizeof(*smap)
1253 #define SMAP_SIG        0x534D4150                      /* 'SMAP' */
1254
1255         vmc.npages = 0;
1256         smap = (void *)vm86_addpage(&vmc, 1, KERNBASE + (1 << PAGE_SHIFT));
1257         vm86_getptr(&vmc, (vm_offset_t)smap, &vmf.vmf_es, &vmf.vmf_di);
1258
1259         physmap_idx = 0;
1260         vmf.vmf_ebx = 0;
1261         do {
1262                 vmf.vmf_eax = 0xE820;
1263                 vmf.vmf_edx = SMAP_SIG;
1264                 vmf.vmf_ecx = SMAPSIZ;
1265                 i = vm86_datacall(0x15, &vmf, &vmc);
1266                 if (i || vmf.vmf_eax != SMAP_SIG)
1267                         break;
1268                 if (boothowto & RB_VERBOSE)
1269                         printf("SMAP type=%02x base=%08x %08x len=%08x %08x\n",
1270                                 smap->type,
1271                                 *(u_int32_t *)((char *)&smap->base + 4),
1272                                 (u_int32_t)smap->base,
1273                                 *(u_int32_t *)((char *)&smap->length + 4),
1274                                 (u_int32_t)smap->length);
1275
1276                 if (smap->type != 0x01)
1277                         goto next_run;
1278
1279                 if (smap->length == 0)
1280                         goto next_run;
1281
1282                 if (smap->base >= 0xffffffff) {
1283                         printf("%uK of memory above 4GB ignored\n",
1284                             (u_int)(smap->length / 1024));
1285                         goto next_run;
1286                 }
1287
1288                 for (i = 0; i <= physmap_idx; i += 2) {
1289                         if (smap->base < physmap[i + 1]) {
1290                                 if (boothowto & RB_VERBOSE)
1291                                         printf(
1292         "Overlapping or non-montonic memory region, ignoring second region\n");
1293                                 goto next_run;
1294                         }
1295                 }
1296
1297                 if (smap->base == physmap[physmap_idx + 1]) {
1298                         physmap[physmap_idx + 1] += smap->length;
1299                         goto next_run;
1300                 }
1301
1302                 physmap_idx += 2;
1303                 if (physmap_idx == PHYSMAP_SIZE) {
1304                         printf(
1305                 "Too many segments in the physical address map, giving up\n");
1306                         break;
1307                 }
1308                 physmap[physmap_idx] = smap->base;
1309                 physmap[physmap_idx + 1] = smap->base + smap->length;
1310 next_run:
1311         } while (vmf.vmf_ebx != 0);
1312
1313         if (physmap[1] != 0)
1314                 goto physmap_done;
1315
1316         /*
1317          * If we failed above, try memory map with INT 15:E801
1318          */
1319         vmf.vmf_ax = 0xE801;
1320         if (vm86_intcall(0x15, &vmf) == 0) {
1321                 extmem = vmf.vmf_cx + vmf.vmf_dx * 64;
1322         } else {
1323 #if 0
1324                 vmf.vmf_ah = 0x88;
1325                 vm86_intcall(0x15, &vmf);
1326                 extmem = vmf.vmf_ax;
1327 #else
1328                 /*
1329                  * Prefer the RTC value for extended memory.
1330                  */
1331                 extmem = rtcin(RTC_EXTLO) + (rtcin(RTC_EXTHI) << 8);
1332 #endif
1333         }
1334
1335         /*
1336          * Special hack for chipsets that still remap the 384k hole when
1337          * there's 16MB of memory - this really confuses people that
1338          * are trying to use bus mastering ISA controllers with the
1339          * "16MB limit"; they only have 16MB, but the remapping puts
1340          * them beyond the limit.
1341          *
1342          * If extended memory is between 15-16MB (16-17MB phys address range),
1343          *      chop it to 15MB.
1344          */
1345         if ((extmem > 15 * 1024) && (extmem < 16 * 1024))
1346                 extmem = 15 * 1024;
1347
1348         physmap[0] = 0;
1349         physmap[1] = basemem * 1024;
1350         physmap_idx = 2;
1351         physmap[physmap_idx] = 0x100000;
1352         physmap[physmap_idx + 1] = physmap[physmap_idx] + extmem * 1024;
1353
1354 physmap_done:
1355         /*
1356          * Now, physmap contains a map of physical memory.
1357          */
1358
1359 #ifdef SMP
1360         /* make hole for AP bootstrap code */
1361         physmap[1] = mp_bootaddress(physmap[1] / 1024);
1362
1363         /* look for the MP hardware - needed for apic addresses */
1364         mp_probe();
1365 #endif
1366
1367         /*
1368          * Maxmem isn't the "maximum memory", it's one larger than the
1369          * highest page of the physical address space.  It should be
1370          * called something like "Maxphyspage".  We may adjust this 
1371          * based on ``hw.physmem'' and the results of the memory test.
1372          */
1373         Maxmem = atop(physmap[physmap_idx + 1]);
1374
1375 #ifdef MAXMEM
1376         Maxmem = MAXMEM / 4;
1377 #endif
1378
1379         /*
1380          * hw.maxmem is a size in bytes; we also allow k, m, and g suffixes
1381          * for the appropriate modifiers.  This overrides MAXMEM.
1382          */
1383         if ((cp = getenv("hw.physmem")) != NULL) {
1384                 u_int64_t AllowMem, sanity;
1385                 const char *ep;
1386
1387                 sanity = AllowMem = strtouq(cp, &ep, 0);
1388                 if ((ep != cp) && (*ep != 0)) {
1389                         switch(*ep) {
1390                         case 'g':
1391                         case 'G':
1392                                 AllowMem <<= 10;
1393                         case 'm':
1394                         case 'M':
1395                                 AllowMem <<= 10;
1396                         case 'k':
1397                         case 'K':
1398                                 AllowMem <<= 10;
1399                                 break;
1400                         default:
1401                                 AllowMem = sanity = 0;
1402                         }
1403                         if (AllowMem < sanity)
1404                                 AllowMem = 0;
1405                 }
1406                 if (AllowMem == 0)
1407                         printf("Ignoring invalid memory size of '%s'\n", cp);
1408                 else
1409                         Maxmem = atop(AllowMem);
1410         }
1411
1412         if (atop(physmap[physmap_idx + 1]) != Maxmem &&
1413             (boothowto & RB_VERBOSE))
1414                 printf("Physical memory use set to %uK\n", Maxmem * 4);
1415
1416         /*
1417          * If Maxmem has been increased beyond what the system has detected,
1418          * extend the last memory segment to the new limit.
1419          */ 
1420         if (atop(physmap[physmap_idx + 1]) < Maxmem)
1421                 physmap[physmap_idx + 1] = ptoa(Maxmem);
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         physmap[0] = PAGE_SIZE;         /* mask off page 0 */
1430         pa_indx = 0;
1431         phys_avail[pa_indx++] = physmap[0];
1432         phys_avail[pa_indx] = physmap[0];
1433 #if 0
1434         pte = (pt_entry_t)vtopte(KERNBASE);
1435 #else
1436         pte = (pt_entry_t)CMAP1;
1437 #endif
1438
1439         /*
1440          * physmap is in bytes, so when converting to page boundaries,
1441          * round up the start address and round down the end address.
1442          */
1443         for (i = 0; i <= physmap_idx; i += 2) {
1444                 vm_offset_t end;
1445
1446                 end = ptoa(Maxmem);
1447                 if (physmap[i + 1] < end)
1448                         end = trunc_page(physmap[i + 1]);
1449                 for (pa = round_page(physmap[i]); pa < end; pa += PAGE_SIZE) {
1450                         int tmp, page_bad;
1451 #if 0
1452                         int *ptr = 0;
1453 #else
1454                         int *ptr = (int *)CADDR1;
1455 #endif
1456
1457                         /*
1458                          * block out kernel memory as not available.
1459                          */
1460                         if (pa >= 0x100000 && pa < first)
1461                                 continue;
1462         
1463                         page_bad = FALSE;
1464
1465                         /*
1466                          * map page into kernel: valid, read/write,non-cacheable
1467                          */
1468                         *pte = pa | PG_V | PG_RW | PG_N;
1469                         invltlb();
1470
1471                         tmp = *(int *)ptr;
1472                         /*
1473                          * Test for alternating 1's and 0's
1474                          */
1475                         *(volatile int *)ptr = 0xaaaaaaaa;
1476                         if (*(volatile int *)ptr != 0xaaaaaaaa) {
1477                                 page_bad = TRUE;
1478                         }
1479                         /*
1480                          * Test for alternating 0's and 1's
1481                          */
1482                         *(volatile int *)ptr = 0x55555555;
1483                         if (*(volatile int *)ptr != 0x55555555) {
1484                         page_bad = TRUE;
1485                         }
1486                         /*
1487                          * Test for all 1's
1488                          */
1489                         *(volatile int *)ptr = 0xffffffff;
1490                         if (*(volatile int *)ptr != 0xffffffff) {
1491                                 page_bad = TRUE;
1492                         }
1493                         /*
1494                          * Test for all 0's
1495                          */
1496                         *(volatile int *)ptr = 0x0;
1497                         if (*(volatile int *)ptr != 0x0) {
1498                                 page_bad = TRUE;
1499                         }
1500                         /*
1501                          * Restore original value.
1502                          */
1503                         *(int *)ptr = tmp;
1504
1505                         /*
1506                          * Adjust array of valid/good pages.
1507                          */
1508                         if (page_bad == TRUE) {
1509                                 continue;
1510                         }
1511                         /*
1512                          * If this good page is a continuation of the
1513                          * previous set of good pages, then just increase
1514                          * the end pointer. Otherwise start a new chunk.
1515                          * Note that "end" points one higher than end,
1516                          * making the range >= start and < end.
1517                          * If we're also doing a speculative memory
1518                          * test and we at or past the end, bump up Maxmem
1519                          * so that we keep going. The first bad page
1520                          * will terminate the loop.
1521                          */
1522                         if (phys_avail[pa_indx] == pa) {
1523                                 phys_avail[pa_indx] += PAGE_SIZE;
1524                         } else {
1525                                 pa_indx++;
1526                                 if (pa_indx == PHYS_AVAIL_ARRAY_END) {
1527                                         printf("Too many holes in the physical address space, giving up\n");
1528                                         pa_indx--;
1529                                         break;
1530                                 }
1531                                 phys_avail[pa_indx++] = pa;     /* start */
1532                                 phys_avail[pa_indx] = pa + PAGE_SIZE;   /* end */
1533                         }
1534                         physmem++;
1535                 }
1536         }
1537         *pte = 0;
1538         invltlb();
1539
1540         /*
1541          * XXX
1542          * The last chunk must contain at least one page plus the message
1543          * buffer to avoid complicating other code (message buffer address
1544          * calculation, etc.).
1545          */
1546         while (phys_avail[pa_indx - 1] + PAGE_SIZE +
1547             round_page(MSGBUF_SIZE) >= phys_avail[pa_indx]) {
1548                 physmem -= atop(phys_avail[pa_indx] - phys_avail[pa_indx - 1]);
1549                 phys_avail[pa_indx--] = 0;
1550                 phys_avail[pa_indx--] = 0;
1551         }
1552
1553         Maxmem = atop(phys_avail[pa_indx]);
1554
1555         /* Trim off space for the message buffer. */
1556         phys_avail[pa_indx] -= round_page(MSGBUF_SIZE);
1557
1558         avail_end = phys_avail[pa_indx];
1559 }
1560
1561 void
1562 init386(first)
1563         int first;
1564 {
1565         int x;
1566         struct gate_descriptor *gdp;
1567         int gsel_tss;
1568 #ifndef SMP
1569         /* table descriptors - used to load tables by microp */
1570         struct region_descriptor r_gdt, r_idt;
1571 #endif
1572         int off;
1573
1574         /*
1575          * Prevent lowering of the ipl if we call tsleep() early.
1576          */
1577         safepri = cpl;
1578
1579         proc0.p_addr = proc0paddr;
1580
1581         atdevbase = ISA_HOLE_START + KERNBASE;
1582
1583         if (bootinfo.bi_modulep) {
1584                 preload_metadata = (caddr_t)bootinfo.bi_modulep + KERNBASE;
1585                 preload_bootstrap_relocate(KERNBASE);
1586         }
1587         if (bootinfo.bi_envp)
1588                 kern_envp = (caddr_t)bootinfo.bi_envp + KERNBASE;
1589
1590         /*
1591          * make gdt memory segments, the code segment goes up to end of the
1592          * page with etext in it, the data segment goes to the end of
1593          * the address space
1594          */
1595         /*
1596          * XXX text protection is temporarily (?) disabled.  The limit was
1597          * i386_btop(round_page(etext)) - 1.
1598          */
1599         gdt_segs[GCODE_SEL].ssd_limit = i386_btop(0) - 1;
1600         gdt_segs[GDATA_SEL].ssd_limit = i386_btop(0) - 1;
1601 #ifdef SMP
1602         gdt_segs[GPRIV_SEL].ssd_limit =
1603                 i386_btop(sizeof(struct privatespace)) - 1;
1604         gdt_segs[GPRIV_SEL].ssd_base = (int) &SMP_prvspace[0];
1605         gdt_segs[GPROC0_SEL].ssd_base =
1606                 (int) &SMP_prvspace[0].globaldata.gd_common_tss;
1607         SMP_prvspace[0].globaldata.gd_prvspace = &SMP_prvspace[0];
1608 #else
1609         gdt_segs[GPRIV_SEL].ssd_limit = i386_btop(0) - 1;
1610         gdt_segs[GPROC0_SEL].ssd_base = (int) &common_tss;
1611 #endif
1612
1613         for (x = 0; x < NGDT; x++) {
1614 #ifdef BDE_DEBUGGER
1615                 /* avoid overwriting db entries with APM ones */
1616                 if (x >= GAPMCODE32_SEL && x <= GAPMDATA_SEL)
1617                         continue;
1618 #endif
1619                 ssdtosd(&gdt_segs[x], &gdt[x].sd);
1620         }
1621
1622         r_gdt.rd_limit = NGDT * sizeof(gdt[0]) - 1;
1623         r_gdt.rd_base =  (int) gdt;
1624         lgdt(&r_gdt);
1625
1626         /* make ldt memory segments */
1627         /*
1628          * The data segment limit must not cover the user area because we
1629          * don't want the user area to be writable in copyout() etc. (page
1630          * level protection is lost in kernel mode on 386's).  Also, we
1631          * don't want the user area to be writable directly (page level
1632          * protection of the user area is not available on 486's with
1633          * CR0_WP set, because there is no user-read/kernel-write mode).
1634          *
1635          * XXX - VM_MAXUSER_ADDRESS is an end address, not a max.  And it
1636          * should be spelled ...MAX_USER...
1637          */
1638 #define VM_END_USER_RW_ADDRESS  VM_MAXUSER_ADDRESS
1639         /*
1640          * The code segment limit has to cover the user area until we move
1641          * the signal trampoline out of the user area.  This is safe because
1642          * the code segment cannot be written to directly.
1643          */
1644 #define VM_END_USER_R_ADDRESS   (VM_END_USER_RW_ADDRESS + UPAGES * PAGE_SIZE)
1645         ldt_segs[LUCODE_SEL].ssd_limit = i386_btop(VM_END_USER_R_ADDRESS) - 1;
1646         ldt_segs[LUDATA_SEL].ssd_limit = i386_btop(VM_END_USER_RW_ADDRESS) - 1;
1647         for (x = 0; x < sizeof ldt_segs / sizeof ldt_segs[0]; x++)
1648                 ssdtosd(&ldt_segs[x], &ldt[x].sd);
1649
1650         _default_ldt = GSEL(GLDT_SEL, SEL_KPL);
1651         lldt(_default_ldt);
1652 #ifdef USER_LDT
1653         currentldt = _default_ldt;
1654 #endif
1655
1656         /* exceptions */
1657         for (x = 0; x < NIDT; x++)
1658                 setidt(x, &IDTVEC(rsvd), SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1659         setidt(0, &IDTVEC(div),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1660         setidt(1, &IDTVEC(dbg),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1661         setidt(2, &IDTVEC(nmi),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1662         setidt(3, &IDTVEC(bpt),  SDT_SYS386TGT, SEL_UPL, GSEL(GCODE_SEL, SEL_KPL));
1663         setidt(4, &IDTVEC(ofl),  SDT_SYS386TGT, SEL_UPL, GSEL(GCODE_SEL, SEL_KPL));
1664         setidt(5, &IDTVEC(bnd),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1665         setidt(6, &IDTVEC(ill),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1666         setidt(7, &IDTVEC(dna),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1667         setidt(8, 0,  SDT_SYSTASKGT, SEL_KPL, GSEL(GPANIC_SEL, SEL_KPL));
1668         setidt(9, &IDTVEC(fpusegm),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1669         setidt(10, &IDTVEC(tss),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1670         setidt(11, &IDTVEC(missing),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1671         setidt(12, &IDTVEC(stk),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1672         setidt(13, &IDTVEC(prot),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1673         setidt(14, &IDTVEC(page),  SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1674         setidt(15, &IDTVEC(rsvd),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1675         setidt(16, &IDTVEC(fpu),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1676         setidt(17, &IDTVEC(align), SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1677         setidt(18, &IDTVEC(mchk),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1678         setidt(0x80, &IDTVEC(int0x80_syscall),
1679                         SDT_SYS386TGT, SEL_UPL, GSEL(GCODE_SEL, SEL_KPL));
1680
1681         r_idt.rd_limit = sizeof(idt0) - 1;
1682         r_idt.rd_base = (int) idt;
1683         lidt(&r_idt);
1684
1685         /*
1686          * Initialize the console before we print anything out.
1687          */
1688         cninit();
1689
1690 #include        "isa.h"
1691 #if     NISA >0
1692         isa_defaultirq();
1693 #endif
1694         rand_initialize();
1695
1696 #ifdef DDB
1697         kdb_init();
1698         if (boothowto & RB_KDB)
1699                 Debugger("Boot flags requested debugger");
1700 #endif
1701
1702         finishidentcpu();       /* Final stage of CPU initialization */
1703         setidt(6, &IDTVEC(ill),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1704         setidt(13, &IDTVEC(prot),  SDT_SYS386TGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1705         initializecpu();        /* Initialize CPU registers */
1706
1707         /* make an initial tss so cpu can get interrupt stack on syscall! */
1708         common_tss.tss_esp0 = (int) proc0.p_addr + UPAGES*PAGE_SIZE - 16;
1709         common_tss.tss_ss0 = GSEL(GDATA_SEL, SEL_KPL) ;
1710         gsel_tss = GSEL(GPROC0_SEL, SEL_KPL);
1711         private_tss = 0;
1712         tss_gdt = &gdt[GPROC0_SEL].sd;
1713         common_tssd = *tss_gdt;
1714         common_tss.tss_ioopt = (sizeof common_tss) << 16;
1715         ltr(gsel_tss);
1716
1717         dblfault_tss.tss_esp = dblfault_tss.tss_esp0 = dblfault_tss.tss_esp1 =
1718             dblfault_tss.tss_esp2 = (int) &dblfault_stack[sizeof(dblfault_stack)];
1719         dblfault_tss.tss_ss = dblfault_tss.tss_ss0 = dblfault_tss.tss_ss1 =
1720             dblfault_tss.tss_ss2 = GSEL(GDATA_SEL, SEL_KPL);
1721         dblfault_tss.tss_cr3 = (int)IdlePTD;
1722         dblfault_tss.tss_eip = (int) dblfault_handler;
1723         dblfault_tss.tss_eflags = PSL_KERNEL;
1724         dblfault_tss.tss_ds = dblfault_tss.tss_es =
1725             dblfault_tss.tss_gs = GSEL(GDATA_SEL, SEL_KPL);
1726         dblfault_tss.tss_fs = GSEL(GPRIV_SEL, SEL_KPL);
1727         dblfault_tss.tss_cs = GSEL(GCODE_SEL, SEL_KPL);
1728         dblfault_tss.tss_ldt = GSEL(GLDT_SEL, SEL_KPL);
1729
1730         vm86_initialize();
1731         getmemsize(first);
1732
1733         /* now running on new page tables, configured,and u/iom is accessible */
1734
1735         /* Map the message buffer. */
1736         for (off = 0; off < round_page(MSGBUF_SIZE); off += PAGE_SIZE)
1737                 pmap_kenter((vm_offset_t)msgbufp + off, avail_end + off);
1738
1739         msgbufinit(msgbufp, MSGBUF_SIZE);
1740
1741         /* make a call gate to reenter kernel with */
1742         gdp = &ldt[LSYS5CALLS_SEL].gd;
1743
1744         x = (int) &IDTVEC(syscall);
1745         gdp->gd_looffset = x++;
1746         gdp->gd_selector = GSEL(GCODE_SEL,SEL_KPL);
1747         gdp->gd_stkcpy = 1;
1748         gdp->gd_type = SDT_SYS386CGT;
1749         gdp->gd_dpl = SEL_UPL;
1750         gdp->gd_p = 1;
1751         gdp->gd_hioffset = ((int) &IDTVEC(syscall)) >>16;
1752
1753         /* XXX does this work? */
1754         ldt[LBSDICALLS_SEL] = ldt[LSYS5CALLS_SEL];
1755         ldt[LSOL26CALLS_SEL] = ldt[LSYS5CALLS_SEL];
1756
1757         /* transfer to user mode */
1758
1759         _ucodesel = LSEL(LUCODE_SEL, SEL_UPL);
1760         _udatasel = LSEL(LUDATA_SEL, SEL_UPL);
1761
1762         /* setup proc 0's pcb */
1763         proc0.p_addr->u_pcb.pcb_flags = 0;
1764         proc0.p_addr->u_pcb.pcb_cr3 = (int)IdlePTD;
1765 #ifdef SMP
1766         proc0.p_addr->u_pcb.pcb_mpnest = 1;
1767 #endif
1768         proc0.p_addr->u_pcb.pcb_ext = 0;
1769 }
1770
1771 #if defined(I586_CPU) && !defined(NO_F00F_HACK)
1772 static void f00f_hack(void *unused);
1773 SYSINIT(f00f_hack, SI_SUB_INTRINSIC, SI_ORDER_FIRST, f00f_hack, NULL);
1774
1775 static void
1776 f00f_hack(void *unused) {
1777         struct gate_descriptor *new_idt;
1778 #ifndef SMP
1779         struct region_descriptor r_idt;
1780 #endif
1781         vm_offset_t tmp;
1782
1783         if (!has_f00f_bug)
1784                 return;
1785
1786         printf("Intel Pentium detected, installing workaround for F00F bug\n");
1787
1788         r_idt.rd_limit = sizeof(idt0) - 1;
1789
1790         tmp = kmem_alloc(kernel_map, PAGE_SIZE * 2);
1791         if (tmp == 0)
1792                 panic("kmem_alloc returned 0");
1793         if (((unsigned int)tmp & (PAGE_SIZE-1)) != 0)
1794                 panic("kmem_alloc returned non-page-aligned memory");
1795         /* Put the first seven entries in the lower page */
1796         new_idt = (struct gate_descriptor*)(tmp + PAGE_SIZE - (7*8));
1797         bcopy(idt, new_idt, sizeof(idt0));
1798         r_idt.rd_base = (int)new_idt;
1799         lidt(&r_idt);
1800         idt = new_idt;
1801         if (vm_map_protect(kernel_map, tmp, tmp + PAGE_SIZE,
1802                            VM_PROT_READ, FALSE) != KERN_SUCCESS)
1803                 panic("vm_map_protect failed");
1804         return;
1805 }
1806 #endif /* defined(I586_CPU) && !NO_F00F_HACK */
1807
1808 int
1809 ptrace_set_pc(p, addr)
1810         struct proc *p;
1811         unsigned long addr;
1812 {
1813         p->p_md.md_regs->tf_eip = addr;
1814         return (0);
1815 }
1816
1817 int
1818 ptrace_single_step(p)
1819         struct proc *p;
1820 {
1821         p->p_md.md_regs->tf_eflags |= PSL_T;
1822         return (0);
1823 }
1824
1825 int ptrace_read_u_check(p, addr, len)
1826         struct proc *p;
1827         vm_offset_t addr;
1828         size_t len;
1829 {
1830         vm_offset_t gap;
1831
1832         if ((vm_offset_t) (addr + len) < addr)
1833                 return EPERM;
1834         if ((vm_offset_t) (addr + len) <= sizeof(struct user))
1835                 return 0;
1836
1837         gap = (char *) p->p_md.md_regs - (char *) p->p_addr;
1838         
1839         if ((vm_offset_t) addr < gap)
1840                 return EPERM;
1841         if ((vm_offset_t) (addr + len) <= 
1842             (vm_offset_t) (gap + sizeof(struct trapframe)))
1843                 return 0;
1844         return EPERM;
1845 }
1846
1847 int ptrace_write_u(p, off, data)
1848         struct proc *p;
1849         vm_offset_t off;
1850         long data;
1851 {
1852         struct trapframe frame_copy;
1853         vm_offset_t min;
1854         struct trapframe *tp;
1855
1856         /*
1857          * Privileged kernel state is scattered all over the user area.
1858          * Only allow write access to parts of regs and to fpregs.
1859          */
1860         min = (char *)p->p_md.md_regs - (char *)p->p_addr;
1861         if (off >= min && off <= min + sizeof(struct trapframe) - sizeof(int)) {
1862                 tp = p->p_md.md_regs;
1863                 frame_copy = *tp;
1864                 *(int *)((char *)&frame_copy + (off - min)) = data;
1865                 if (!EFLAGS_SECURE(frame_copy.tf_eflags, tp->tf_eflags) ||
1866                     !CS_SECURE(frame_copy.tf_cs))
1867                         return (EINVAL);
1868                 *(int*)((char *)p->p_addr + off) = data;
1869                 return (0);
1870         }
1871         min = offsetof(struct user, u_pcb) + offsetof(struct pcb, pcb_savefpu);
1872         if (off >= min && off <= min + sizeof(struct save87) - sizeof(int)) {
1873                 *(int*)((char *)p->p_addr + off) = data;
1874                 return (0);
1875         }
1876         return (EFAULT);
1877 }
1878
1879 int
1880 fill_regs(p, regs)
1881         struct proc *p;
1882         struct reg *regs;
1883 {
1884         struct pcb *pcb;
1885         struct trapframe *tp;
1886
1887         tp = p->p_md.md_regs;
1888         regs->r_fs = tp->tf_fs;
1889         regs->r_es = tp->tf_es;
1890         regs->r_ds = tp->tf_ds;
1891         regs->r_edi = tp->tf_edi;
1892         regs->r_esi = tp->tf_esi;
1893         regs->r_ebp = tp->tf_ebp;
1894         regs->r_ebx = tp->tf_ebx;
1895         regs->r_edx = tp->tf_edx;
1896         regs->r_ecx = tp->tf_ecx;
1897         regs->r_eax = tp->tf_eax;
1898         regs->r_eip = tp->tf_eip;
1899         regs->r_cs = tp->tf_cs;
1900         regs->r_eflags = tp->tf_eflags;
1901         regs->r_esp = tp->tf_esp;
1902         regs->r_ss = tp->tf_ss;
1903         pcb = &p->p_addr->u_pcb;
1904         regs->r_gs = pcb->pcb_gs;
1905         return (0);
1906 }
1907
1908 int
1909 set_regs(p, regs)
1910         struct proc *p;
1911         struct reg *regs;
1912 {
1913         struct pcb *pcb;
1914         struct trapframe *tp;
1915
1916         tp = p->p_md.md_regs;
1917         if (!EFLAGS_SECURE(regs->r_eflags, tp->tf_eflags) ||
1918             !CS_SECURE(regs->r_cs))
1919                 return (EINVAL);
1920         tp->tf_fs = regs->r_fs;
1921         tp->tf_es = regs->r_es;
1922         tp->tf_ds = regs->r_ds;
1923         tp->tf_edi = regs->r_edi;
1924         tp->tf_esi = regs->r_esi;
1925         tp->tf_ebp = regs->r_ebp;
1926         tp->tf_ebx = regs->r_ebx;
1927         tp->tf_edx = regs->r_edx;
1928         tp->tf_ecx = regs->r_ecx;
1929         tp->tf_eax = regs->r_eax;
1930         tp->tf_eip = regs->r_eip;
1931         tp->tf_cs = regs->r_cs;
1932         tp->tf_eflags = regs->r_eflags;
1933         tp->tf_esp = regs->r_esp;
1934         tp->tf_ss = regs->r_ss;
1935         pcb = &p->p_addr->u_pcb;
1936         pcb->pcb_gs = regs->r_gs;
1937         return (0);
1938 }
1939
1940 int
1941 fill_fpregs(p, fpregs)
1942         struct proc *p;
1943         struct fpreg *fpregs;
1944 {
1945         bcopy(&p->p_addr->u_pcb.pcb_savefpu, fpregs, sizeof *fpregs);
1946         return (0);
1947 }
1948
1949 int
1950 set_fpregs(p, fpregs)
1951         struct proc *p;
1952         struct fpreg *fpregs;
1953 {
1954         bcopy(fpregs, &p->p_addr->u_pcb.pcb_savefpu, sizeof *fpregs);
1955         return (0);
1956 }
1957
1958 int
1959 fill_dbregs(p, dbregs)
1960         struct proc *p;
1961         struct dbreg *dbregs;
1962 {
1963         struct pcb *pcb;
1964
1965         pcb = &p->p_addr->u_pcb;
1966         dbregs->dr0 = pcb->pcb_dr0;
1967         dbregs->dr1 = pcb->pcb_dr1;
1968         dbregs->dr2 = pcb->pcb_dr2;
1969         dbregs->dr3 = pcb->pcb_dr3;
1970         dbregs->dr4 = 0;
1971         dbregs->dr5 = 0;
1972         dbregs->dr6 = pcb->pcb_dr6;
1973         dbregs->dr7 = pcb->pcb_dr7;
1974         return (0);
1975 }
1976
1977 int
1978 set_dbregs(p, dbregs)
1979         struct proc *p;
1980         struct dbreg *dbregs;
1981 {
1982         struct pcb *pcb;
1983
1984         pcb = &p->p_addr->u_pcb;
1985
1986         /*
1987          * Don't let a process set a breakpoint that is not within the
1988          * process's address space.  If a process could do this, it
1989          * could halt the system by setting a breakpoint in the kernel
1990          * (if ddb was enabled).  Thus, we need to check to make sure
1991          * that no breakpoints are being enabled for addresses outside
1992          * process's address space, unless, perhaps, we were called by
1993          * uid 0.
1994          *
1995          * XXX - what about when the watched area of the user's
1996          * address space is written into from within the kernel
1997          * ... wouldn't that still cause a breakpoint to be generated
1998          * from within kernel mode?
1999          */
2000
2001         if (p->p_cred->pc_ucred->cr_uid != 0) {
2002                 if (dbregs->dr7 & 0x3) {
2003                         /* dr0 is enabled */
2004                         if (dbregs->dr0 >= VM_MAXUSER_ADDRESS)
2005                                 return (EINVAL);
2006                 }
2007
2008                 if (dbregs->dr7 & (0x3<<2)) {
2009                         /* dr1 is enabled */
2010                         if (dbregs->dr1 >= VM_MAXUSER_ADDRESS)
2011                                 return (EINVAL);
2012                 }
2013
2014                 if (dbregs->dr7 & (0x3<<4)) {
2015                         /* dr2 is enabled */
2016                         if (dbregs->dr2 >= VM_MAXUSER_ADDRESS)
2017                                 return (EINVAL);
2018                 }
2019
2020                 if (dbregs->dr7 & (0x3<<6)) {
2021                         /* dr3 is enabled */
2022                         if (dbregs->dr3 >= VM_MAXUSER_ADDRESS)
2023                                 return (EINVAL);
2024                 }
2025         }
2026
2027         pcb->pcb_dr0 = dbregs->dr0;
2028         pcb->pcb_dr1 = dbregs->dr1;
2029         pcb->pcb_dr2 = dbregs->dr2;
2030         pcb->pcb_dr3 = dbregs->dr3;
2031         pcb->pcb_dr6 = dbregs->dr6;
2032         pcb->pcb_dr7 = dbregs->dr7;
2033
2034         pcb->pcb_flags |= PCB_DBREGS;
2035
2036         return (0);
2037 }
2038
2039 #ifndef DDB
2040 void
2041 Debugger(const char *msg)
2042 {
2043         printf("Debugger(\"%s\") called.\n", msg);
2044 }
2045 #endif /* no DDB */
2046
2047 #include <sys/disklabel.h>
2048
2049 /*
2050  * Determine the size of the transfer, and make sure it is
2051  * within the boundaries of the partition. Adjust transfer
2052  * if needed, and signal errors or early completion.
2053  */
2054 int
2055 bounds_check_with_label(struct buf *bp, struct disklabel *lp, int wlabel)
2056 {
2057         struct partition *p = lp->d_partitions + dkpart(bp->b_dev);
2058         int labelsect = lp->d_partitions[0].p_offset;
2059         int maxsz = p->p_size,
2060                 sz = (bp->b_bcount + DEV_BSIZE - 1) >> DEV_BSHIFT;
2061
2062         /* overwriting disk label ? */
2063         /* XXX should also protect bootstrap in first 8K */
2064         if (bp->b_blkno + p->p_offset <= LABELSECTOR + labelsect &&
2065 #if LABELSECTOR != 0
2066             bp->b_blkno + p->p_offset + sz > LABELSECTOR + labelsect &&
2067 #endif
2068             (bp->b_flags & B_READ) == 0 && wlabel == 0) {
2069                 bp->b_error = EROFS;
2070                 goto bad;
2071         }
2072
2073 #if     defined(DOSBBSECTOR) && defined(notyet)
2074         /* overwriting master boot record? */
2075         if (bp->b_blkno + p->p_offset <= DOSBBSECTOR &&
2076             (bp->b_flags & B_READ) == 0 && wlabel == 0) {
2077                 bp->b_error = EROFS;
2078                 goto bad;
2079         }
2080 #endif
2081
2082         /* beyond partition? */
2083         if (bp->b_blkno < 0 || bp->b_blkno + sz > maxsz) {
2084                 /* if exactly at end of disk, return an EOF */
2085                 if (bp->b_blkno == maxsz) {
2086                         bp->b_resid = bp->b_bcount;
2087                         return(0);
2088                 }
2089                 /* or truncate if part of it fits */
2090                 sz = maxsz - bp->b_blkno;
2091                 if (sz <= 0) {
2092                         bp->b_error = EINVAL;
2093                         goto bad;
2094                 }
2095                 bp->b_bcount = sz << DEV_BSHIFT;
2096         }
2097
2098         bp->b_pblkno = bp->b_blkno + p->p_offset;
2099         return(1);
2100
2101 bad:
2102         bp->b_flags |= B_ERROR;
2103         return(-1);
2104 }
2105
2106 #ifdef DDB
2107
2108 /*
2109  * Provide inb() and outb() as functions.  They are normally only
2110  * available as macros calling inlined functions, thus cannot be
2111  * called inside DDB.
2112  *
2113  * The actual code is stolen from <machine/cpufunc.h>, and de-inlined.
2114  */
2115
2116 #undef inb
2117 #undef outb
2118
2119 /* silence compiler warnings */
2120 u_char inb(u_int);
2121 void outb(u_int, u_char);
2122
2123 u_char
2124 inb(u_int port)
2125 {
2126         u_char  data;
2127         /*
2128          * We use %%dx and not %1 here because i/o is done at %dx and not at
2129          * %edx, while gcc generates inferior code (movw instead of movl)
2130          * if we tell it to load (u_short) port.
2131          */
2132         __asm __volatile("inb %%dx,%0" : "=a" (data) : "d" (port));
2133         return (data);
2134 }
2135
2136 void
2137 outb(u_int port, u_char data)
2138 {
2139         u_char  al;
2140         /*
2141          * Use an unnecessary assignment to help gcc's register allocator.
2142          * This make a large difference for gcc-1.40 and a tiny difference
2143          * for gcc-2.6.0.  For gcc-1.40, al had to be ``asm("ax")'' for
2144          * best results.  gcc-2.6.0 can't handle this.
2145          */
2146         al = data;
2147         __asm __volatile("outb %0,%%dx" : : "a" (al), "d" (port));
2148 }
2149
2150 #endif /* DDB */