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