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