]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/i386/i386/machdep.c
Check the hw.proto.attach environment variable for devices that
[FreeBSD/FreeBSD.git] / sys / i386 / 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  */
39
40 #include <sys/cdefs.h>
41 __FBSDID("$FreeBSD$");
42
43 #include "opt_apic.h"
44 #include "opt_atpic.h"
45 #include "opt_compat.h"
46 #include "opt_cpu.h"
47 #include "opt_ddb.h"
48 #include "opt_inet.h"
49 #include "opt_isa.h"
50 #include "opt_kstack_pages.h"
51 #include "opt_maxmem.h"
52 #include "opt_mp_watchdog.h"
53 #include "opt_npx.h"
54 #include "opt_perfmon.h"
55 #include "opt_platform.h"
56 #include "opt_xbox.h"
57
58 #include <sys/param.h>
59 #include <sys/proc.h>
60 #include <sys/systm.h>
61 #include <sys/bio.h>
62 #include <sys/buf.h>
63 #include <sys/bus.h>
64 #include <sys/callout.h>
65 #include <sys/cons.h>
66 #include <sys/cpu.h>
67 #include <sys/eventhandler.h>
68 #include <sys/exec.h>
69 #include <sys/imgact.h>
70 #include <sys/kdb.h>
71 #include <sys/kernel.h>
72 #include <sys/ktr.h>
73 #include <sys/linker.h>
74 #include <sys/lock.h>
75 #include <sys/malloc.h>
76 #include <sys/memrange.h>
77 #include <sys/msgbuf.h>
78 #include <sys/mutex.h>
79 #include <sys/pcpu.h>
80 #include <sys/ptrace.h>
81 #include <sys/reboot.h>
82 #include <sys/rwlock.h>
83 #include <sys/sched.h>
84 #include <sys/signalvar.h>
85 #ifdef SMP
86 #include <sys/smp.h>
87 #endif
88 #include <sys/syscallsubr.h>
89 #include <sys/sysctl.h>
90 #include <sys/sysent.h>
91 #include <sys/sysproto.h>
92 #include <sys/ucontext.h>
93 #include <sys/vmmeter.h>
94
95 #include <vm/vm.h>
96 #include <vm/vm_extern.h>
97 #include <vm/vm_kern.h>
98 #include <vm/vm_page.h>
99 #include <vm/vm_map.h>
100 #include <vm/vm_object.h>
101 #include <vm/vm_pager.h>
102 #include <vm/vm_param.h>
103
104 #ifdef DDB
105 #ifndef KDB
106 #error KDB must be enabled in order for DDB to work!
107 #endif
108 #include <ddb/ddb.h>
109 #include <ddb/db_sym.h>
110 #endif
111
112 #ifdef PC98
113 #include <pc98/pc98/pc98_machdep.h>
114 #else
115 #include <isa/rtc.h>
116 #endif
117
118 #include <net/netisr.h>
119
120 #include <machine/bootinfo.h>
121 #include <machine/clock.h>
122 #include <machine/cpu.h>
123 #include <machine/cputypes.h>
124 #include <machine/intr_machdep.h>
125 #include <x86/mca.h>
126 #include <machine/md_var.h>
127 #include <machine/metadata.h>
128 #include <machine/mp_watchdog.h>
129 #include <machine/pc/bios.h>
130 #include <machine/pcb.h>
131 #include <machine/pcb_ext.h>
132 #include <machine/proc.h>
133 #include <machine/reg.h>
134 #include <machine/sigframe.h>
135 #include <machine/specialreg.h>
136 #include <machine/vm86.h>
137 #include <x86/init.h>
138 #ifdef PERFMON
139 #include <machine/perfmon.h>
140 #endif
141 #ifdef SMP
142 #include <machine/smp.h>
143 #endif
144 #ifdef FDT
145 #include <x86/fdt.h>
146 #endif
147
148 #ifdef DEV_APIC
149 #include <x86/apicvar.h>
150 #endif
151
152 #ifdef DEV_ISA
153 #include <x86/isa/icu.h>
154 #endif
155
156 #ifdef XBOX
157 #include <machine/xbox.h>
158
159 int arch_i386_is_xbox = 0;
160 uint32_t arch_i386_xbox_memsize = 0;
161 #endif
162
163 /* Sanity check for __curthread() */
164 CTASSERT(offsetof(struct pcpu, pc_curthread) == 0);
165
166 extern register_t init386(int first);
167 extern void dblfault_handler(void);
168
169 #if !defined(CPU_DISABLE_SSE) && defined(I686_CPU)
170 #define CPU_ENABLE_SSE
171 #endif
172
173 static void cpu_startup(void *);
174 static void fpstate_drop(struct thread *td);
175 static void get_fpcontext(struct thread *td, mcontext_t *mcp,
176     char *xfpusave, size_t xfpusave_len);
177 static int  set_fpcontext(struct thread *td, mcontext_t *mcp,
178     char *xfpustate, size_t xfpustate_len);
179 SYSINIT(cpu, SI_SUB_CPU, SI_ORDER_FIRST, cpu_startup, NULL);
180
181 /* Intel ICH registers */
182 #define ICH_PMBASE      0x400
183 #define ICH_SMI_EN      ICH_PMBASE + 0x30
184
185 int     _udatasel, _ucodesel;
186 u_int   basemem;
187
188 #ifdef PC98
189 int     need_pre_dma_flush;     /* If 1, use wbinvd befor DMA transfer. */
190 int     need_post_dma_flush;    /* If 1, use invd after DMA transfer. */
191
192 static int      ispc98 = 1;
193 SYSCTL_INT(_machdep, OID_AUTO, ispc98, CTLFLAG_RD, &ispc98, 0, "");
194 #endif
195
196 int cold = 1;
197
198 #ifdef COMPAT_43
199 static void osendsig(sig_t catcher, ksiginfo_t *, sigset_t *mask);
200 #endif
201 #ifdef COMPAT_FREEBSD4
202 static void freebsd4_sendsig(sig_t catcher, ksiginfo_t *, sigset_t *mask);
203 #endif
204
205 long Maxmem = 0;
206 long realmem = 0;
207
208 #ifdef PAE
209 FEATURE(pae, "Physical Address Extensions");
210 #endif
211
212 /*
213  * The number of PHYSMAP entries must be one less than the number of
214  * PHYSSEG entries because the PHYSMAP entry that spans the largest
215  * physical address that is accessible by ISA DMA is split into two
216  * PHYSSEG entries.
217  */
218 #define PHYSMAP_SIZE    (2 * (VM_PHYSSEG_MAX - 1))
219
220 vm_paddr_t phys_avail[PHYSMAP_SIZE + 2];
221 vm_paddr_t dump_avail[PHYSMAP_SIZE + 2];
222
223 /* must be 2 less so 0 0 can signal end of chunks */
224 #define PHYS_AVAIL_ARRAY_END ((sizeof(phys_avail) / sizeof(phys_avail[0])) - 2)
225 #define DUMP_AVAIL_ARRAY_END ((sizeof(dump_avail) / sizeof(dump_avail[0])) - 2)
226
227 struct kva_md_info kmi;
228
229 static struct trapframe proc0_tf;
230 struct pcpu __pcpu[MAXCPU];
231
232 struct mtx icu_lock;
233
234 struct mem_range_softc mem_range_softc;
235
236  /* Default init_ops implementation. */
237  struct init_ops init_ops = {
238         .early_clock_source_init =      i8254_init,
239         .early_delay =                  i8254_delay,
240 #ifdef DEV_APIC
241         .msi_init =                     msi_init,
242 #endif
243  };
244
245 static void
246 cpu_startup(dummy)
247         void *dummy;
248 {
249         uintmax_t memsize;
250         char *sysenv;
251
252 #ifndef PC98
253         /*
254          * On MacBooks, we need to disallow the legacy USB circuit to
255          * generate an SMI# because this can cause several problems,
256          * namely: incorrect CPU frequency detection and failure to
257          * start the APs.
258          * We do this by disabling a bit in the SMI_EN (SMI Control and
259          * Enable register) of the Intel ICH LPC Interface Bridge.
260          */
261         sysenv = kern_getenv("smbios.system.product");
262         if (sysenv != NULL) {
263                 if (strncmp(sysenv, "MacBook1,1", 10) == 0 ||
264                     strncmp(sysenv, "MacBook3,1", 10) == 0 ||
265                     strncmp(sysenv, "MacBook4,1", 10) == 0 ||
266                     strncmp(sysenv, "MacBookPro1,1", 13) == 0 ||
267                     strncmp(sysenv, "MacBookPro1,2", 13) == 0 ||
268                     strncmp(sysenv, "MacBookPro3,1", 13) == 0 ||
269                     strncmp(sysenv, "MacBookPro4,1", 13) == 0 ||
270                     strncmp(sysenv, "Macmini1,1", 10) == 0) {
271                         if (bootverbose)
272                                 printf("Disabling LEGACY_USB_EN bit on "
273                                     "Intel ICH.\n");
274                         outl(ICH_SMI_EN, inl(ICH_SMI_EN) & ~0x8);
275                 }
276                 freeenv(sysenv);
277         }
278 #endif /* !PC98 */
279
280         /*
281          * Good {morning,afternoon,evening,night}.
282          */
283         startrtclock();
284         printcpuinfo();
285         panicifcpuunsupported();
286 #ifdef PERFMON
287         perfmon_init();
288 #endif
289
290         /*
291          * Display physical memory if SMBIOS reports reasonable amount.
292          */
293         memsize = 0;
294         sysenv = kern_getenv("smbios.memory.enabled");
295         if (sysenv != NULL) {
296                 memsize = (uintmax_t)strtoul(sysenv, (char **)NULL, 10) << 10;
297                 freeenv(sysenv);
298         }
299         if (memsize < ptoa((uintmax_t)vm_cnt.v_free_count))
300                 memsize = ptoa((uintmax_t)Maxmem);
301         printf("real memory  = %ju (%ju MB)\n", memsize, memsize >> 20);
302         realmem = atop(memsize);
303
304         /*
305          * Display any holes after the first chunk of extended memory.
306          */
307         if (bootverbose) {
308                 int indx;
309
310                 printf("Physical memory chunk(s):\n");
311                 for (indx = 0; phys_avail[indx + 1] != 0; indx += 2) {
312                         vm_paddr_t size;
313
314                         size = phys_avail[indx + 1] - phys_avail[indx];
315                         printf(
316                             "0x%016jx - 0x%016jx, %ju bytes (%ju pages)\n",
317                             (uintmax_t)phys_avail[indx],
318                             (uintmax_t)phys_avail[indx + 1] - 1,
319                             (uintmax_t)size, (uintmax_t)size / PAGE_SIZE);
320                 }
321         }
322
323         vm_ksubmap_init(&kmi);
324
325         printf("avail memory = %ju (%ju MB)\n",
326             ptoa((uintmax_t)vm_cnt.v_free_count),
327             ptoa((uintmax_t)vm_cnt.v_free_count) / 1048576);
328
329         /*
330          * Set up buffers, so they can be used to read disk labels.
331          */
332         bufinit();
333         vm_pager_bufferinit();
334         cpu_setregs();
335 }
336
337 /*
338  * Send an interrupt to process.
339  *
340  * Stack is set up to allow sigcode stored
341  * at top to call routine, followed by call
342  * to sigreturn routine below.  After sigreturn
343  * resets the signal mask, the stack, and the
344  * frame pointer, it returns to the user
345  * specified pc, psl.
346  */
347 #ifdef COMPAT_43
348 static void
349 osendsig(sig_t catcher, ksiginfo_t *ksi, sigset_t *mask)
350 {
351         struct osigframe sf, *fp;
352         struct proc *p;
353         struct thread *td;
354         struct sigacts *psp;
355         struct trapframe *regs;
356         int sig;
357         int oonstack;
358
359         td = curthread;
360         p = td->td_proc;
361         PROC_LOCK_ASSERT(p, MA_OWNED);
362         sig = ksi->ksi_signo;
363         psp = p->p_sigacts;
364         mtx_assert(&psp->ps_mtx, MA_OWNED);
365         regs = td->td_frame;
366         oonstack = sigonstack(regs->tf_esp);
367
368         /* Allocate space for the signal handler context. */
369         if ((td->td_pflags & TDP_ALTSTACK) && !oonstack &&
370             SIGISMEMBER(psp->ps_sigonstack, sig)) {
371                 fp = (struct osigframe *)(td->td_sigstk.ss_sp +
372                     td->td_sigstk.ss_size - sizeof(struct osigframe));
373 #if defined(COMPAT_43)
374                 td->td_sigstk.ss_flags |= SS_ONSTACK;
375 #endif
376         } else
377                 fp = (struct osigframe *)regs->tf_esp - 1;
378
379         /* Build the argument list for the signal handler. */
380         sf.sf_signum = sig;
381         sf.sf_scp = (register_t)&fp->sf_siginfo.si_sc;
382         bzero(&sf.sf_siginfo, sizeof(sf.sf_siginfo));
383         if (SIGISMEMBER(psp->ps_siginfo, sig)) {
384                 /* Signal handler installed with SA_SIGINFO. */
385                 sf.sf_arg2 = (register_t)&fp->sf_siginfo;
386                 sf.sf_siginfo.si_signo = sig;
387                 sf.sf_siginfo.si_code = ksi->ksi_code;
388                 sf.sf_ahu.sf_action = (__osiginfohandler_t *)catcher;
389                 sf.sf_addr = 0;
390         } else {
391                 /* Old FreeBSD-style arguments. */
392                 sf.sf_arg2 = ksi->ksi_code;
393                 sf.sf_addr = (register_t)ksi->ksi_addr;
394                 sf.sf_ahu.sf_handler = catcher;
395         }
396         mtx_unlock(&psp->ps_mtx);
397         PROC_UNLOCK(p);
398
399         /* Save most if not all of trap frame. */
400         sf.sf_siginfo.si_sc.sc_eax = regs->tf_eax;
401         sf.sf_siginfo.si_sc.sc_ebx = regs->tf_ebx;
402         sf.sf_siginfo.si_sc.sc_ecx = regs->tf_ecx;
403         sf.sf_siginfo.si_sc.sc_edx = regs->tf_edx;
404         sf.sf_siginfo.si_sc.sc_esi = regs->tf_esi;
405         sf.sf_siginfo.si_sc.sc_edi = regs->tf_edi;
406         sf.sf_siginfo.si_sc.sc_cs = regs->tf_cs;
407         sf.sf_siginfo.si_sc.sc_ds = regs->tf_ds;
408         sf.sf_siginfo.si_sc.sc_ss = regs->tf_ss;
409         sf.sf_siginfo.si_sc.sc_es = regs->tf_es;
410         sf.sf_siginfo.si_sc.sc_fs = regs->tf_fs;
411         sf.sf_siginfo.si_sc.sc_gs = rgs();
412         sf.sf_siginfo.si_sc.sc_isp = regs->tf_isp;
413
414         /* Build the signal context to be used by osigreturn(). */
415         sf.sf_siginfo.si_sc.sc_onstack = (oonstack) ? 1 : 0;
416         SIG2OSIG(*mask, sf.sf_siginfo.si_sc.sc_mask);
417         sf.sf_siginfo.si_sc.sc_sp = regs->tf_esp;
418         sf.sf_siginfo.si_sc.sc_fp = regs->tf_ebp;
419         sf.sf_siginfo.si_sc.sc_pc = regs->tf_eip;
420         sf.sf_siginfo.si_sc.sc_ps = regs->tf_eflags;
421         sf.sf_siginfo.si_sc.sc_trapno = regs->tf_trapno;
422         sf.sf_siginfo.si_sc.sc_err = regs->tf_err;
423
424         /*
425          * If we're a vm86 process, we want to save the segment registers.
426          * We also change eflags to be our emulated eflags, not the actual
427          * eflags.
428          */
429         if (regs->tf_eflags & PSL_VM) {
430                 /* XXX confusing names: `tf' isn't a trapframe; `regs' is. */
431                 struct trapframe_vm86 *tf = (struct trapframe_vm86 *)regs;
432                 struct vm86_kernel *vm86 = &td->td_pcb->pcb_ext->ext_vm86;
433
434                 sf.sf_siginfo.si_sc.sc_gs = tf->tf_vm86_gs;
435                 sf.sf_siginfo.si_sc.sc_fs = tf->tf_vm86_fs;
436                 sf.sf_siginfo.si_sc.sc_es = tf->tf_vm86_es;
437                 sf.sf_siginfo.si_sc.sc_ds = tf->tf_vm86_ds;
438
439                 if (vm86->vm86_has_vme == 0)
440                         sf.sf_siginfo.si_sc.sc_ps =
441                             (tf->tf_eflags & ~(PSL_VIF | PSL_VIP)) |
442                             (vm86->vm86_eflags & (PSL_VIF | PSL_VIP));
443
444                 /* See sendsig() for comments. */
445                 tf->tf_eflags &= ~(PSL_VM | PSL_NT | PSL_VIF | PSL_VIP);
446         }
447
448         /*
449          * Copy the sigframe out to the user's stack.
450          */
451         if (copyout(&sf, fp, sizeof(*fp)) != 0) {
452 #ifdef DEBUG
453                 printf("process %ld has trashed its stack\n", (long)p->p_pid);
454 #endif
455                 PROC_LOCK(p);
456                 sigexit(td, SIGILL);
457         }
458
459         regs->tf_esp = (int)fp;
460         if (p->p_sysent->sv_sigcode_base != 0) {
461                 regs->tf_eip = p->p_sysent->sv_sigcode_base + szsigcode -
462                     szosigcode;
463         } else {
464                 /* a.out sysentvec does not use shared page */
465                 regs->tf_eip = p->p_sysent->sv_psstrings - szosigcode;
466         }
467         regs->tf_eflags &= ~(PSL_T | PSL_D);
468         regs->tf_cs = _ucodesel;
469         regs->tf_ds = _udatasel;
470         regs->tf_es = _udatasel;
471         regs->tf_fs = _udatasel;
472         load_gs(_udatasel);
473         regs->tf_ss = _udatasel;
474         PROC_LOCK(p);
475         mtx_lock(&psp->ps_mtx);
476 }
477 #endif /* COMPAT_43 */
478
479 #ifdef COMPAT_FREEBSD4
480 static void
481 freebsd4_sendsig(sig_t catcher, ksiginfo_t *ksi, sigset_t *mask)
482 {
483         struct sigframe4 sf, *sfp;
484         struct proc *p;
485         struct thread *td;
486         struct sigacts *psp;
487         struct trapframe *regs;
488         int sig;
489         int oonstack;
490
491         td = curthread;
492         p = td->td_proc;
493         PROC_LOCK_ASSERT(p, MA_OWNED);
494         sig = ksi->ksi_signo;
495         psp = p->p_sigacts;
496         mtx_assert(&psp->ps_mtx, MA_OWNED);
497         regs = td->td_frame;
498         oonstack = sigonstack(regs->tf_esp);
499
500         /* Save user context. */
501         bzero(&sf, sizeof(sf));
502         sf.sf_uc.uc_sigmask = *mask;
503         sf.sf_uc.uc_stack = td->td_sigstk;
504         sf.sf_uc.uc_stack.ss_flags = (td->td_pflags & TDP_ALTSTACK)
505             ? ((oonstack) ? SS_ONSTACK : 0) : SS_DISABLE;
506         sf.sf_uc.uc_mcontext.mc_onstack = (oonstack) ? 1 : 0;
507         sf.sf_uc.uc_mcontext.mc_gs = rgs();
508         bcopy(regs, &sf.sf_uc.uc_mcontext.mc_fs, sizeof(*regs));
509         bzero(sf.sf_uc.uc_mcontext.mc_fpregs,
510             sizeof(sf.sf_uc.uc_mcontext.mc_fpregs));
511         bzero(sf.sf_uc.uc_mcontext.__spare__,
512             sizeof(sf.sf_uc.uc_mcontext.__spare__));
513         bzero(sf.sf_uc.__spare__, sizeof(sf.sf_uc.__spare__));
514
515         /* Allocate space for the signal handler context. */
516         if ((td->td_pflags & TDP_ALTSTACK) != 0 && !oonstack &&
517             SIGISMEMBER(psp->ps_sigonstack, sig)) {
518                 sfp = (struct sigframe4 *)(td->td_sigstk.ss_sp +
519                     td->td_sigstk.ss_size - sizeof(struct sigframe4));
520 #if defined(COMPAT_43)
521                 td->td_sigstk.ss_flags |= SS_ONSTACK;
522 #endif
523         } else
524                 sfp = (struct sigframe4 *)regs->tf_esp - 1;
525
526         /* Build the argument list for the signal handler. */
527         sf.sf_signum = sig;
528         sf.sf_ucontext = (register_t)&sfp->sf_uc;
529         bzero(&sf.sf_si, sizeof(sf.sf_si));
530         if (SIGISMEMBER(psp->ps_siginfo, sig)) {
531                 /* Signal handler installed with SA_SIGINFO. */
532                 sf.sf_siginfo = (register_t)&sfp->sf_si;
533                 sf.sf_ahu.sf_action = (__siginfohandler_t *)catcher;
534
535                 /* Fill in POSIX parts */
536                 sf.sf_si.si_signo = sig;
537                 sf.sf_si.si_code = ksi->ksi_code;
538                 sf.sf_si.si_addr = ksi->ksi_addr;
539         } else {
540                 /* Old FreeBSD-style arguments. */
541                 sf.sf_siginfo = ksi->ksi_code;
542                 sf.sf_addr = (register_t)ksi->ksi_addr;
543                 sf.sf_ahu.sf_handler = catcher;
544         }
545         mtx_unlock(&psp->ps_mtx);
546         PROC_UNLOCK(p);
547
548         /*
549          * If we're a vm86 process, we want to save the segment registers.
550          * We also change eflags to be our emulated eflags, not the actual
551          * eflags.
552          */
553         if (regs->tf_eflags & PSL_VM) {
554                 struct trapframe_vm86 *tf = (struct trapframe_vm86 *)regs;
555                 struct vm86_kernel *vm86 = &td->td_pcb->pcb_ext->ext_vm86;
556
557                 sf.sf_uc.uc_mcontext.mc_gs = tf->tf_vm86_gs;
558                 sf.sf_uc.uc_mcontext.mc_fs = tf->tf_vm86_fs;
559                 sf.sf_uc.uc_mcontext.mc_es = tf->tf_vm86_es;
560                 sf.sf_uc.uc_mcontext.mc_ds = tf->tf_vm86_ds;
561
562                 if (vm86->vm86_has_vme == 0)
563                         sf.sf_uc.uc_mcontext.mc_eflags =
564                             (tf->tf_eflags & ~(PSL_VIF | PSL_VIP)) |
565                             (vm86->vm86_eflags & (PSL_VIF | PSL_VIP));
566
567                 /*
568                  * Clear PSL_NT to inhibit T_TSSFLT faults on return from
569                  * syscalls made by the signal handler.  This just avoids
570                  * wasting time for our lazy fixup of such faults.  PSL_NT
571                  * does nothing in vm86 mode, but vm86 programs can set it
572                  * almost legitimately in probes for old cpu types.
573                  */
574                 tf->tf_eflags &= ~(PSL_VM | PSL_NT | PSL_VIF | PSL_VIP);
575         }
576
577         /*
578          * Copy the sigframe out to the user's stack.
579          */
580         if (copyout(&sf, sfp, sizeof(*sfp)) != 0) {
581 #ifdef DEBUG
582                 printf("process %ld has trashed its stack\n", (long)p->p_pid);
583 #endif
584                 PROC_LOCK(p);
585                 sigexit(td, SIGILL);
586         }
587
588         regs->tf_esp = (int)sfp;
589         regs->tf_eip = p->p_sysent->sv_sigcode_base + szsigcode -
590             szfreebsd4_sigcode;
591         regs->tf_eflags &= ~(PSL_T | PSL_D);
592         regs->tf_cs = _ucodesel;
593         regs->tf_ds = _udatasel;
594         regs->tf_es = _udatasel;
595         regs->tf_fs = _udatasel;
596         regs->tf_ss = _udatasel;
597         PROC_LOCK(p);
598         mtx_lock(&psp->ps_mtx);
599 }
600 #endif  /* COMPAT_FREEBSD4 */
601
602 void
603 sendsig(sig_t catcher, ksiginfo_t *ksi, sigset_t *mask)
604 {
605         struct sigframe sf, *sfp;
606         struct proc *p;
607         struct thread *td;
608         struct sigacts *psp;
609         char *sp;
610         struct trapframe *regs;
611         struct segment_descriptor *sdp;
612         char *xfpusave;
613         size_t xfpusave_len;
614         int sig;
615         int oonstack;
616
617         td = curthread;
618         p = td->td_proc;
619         PROC_LOCK_ASSERT(p, MA_OWNED);
620         sig = ksi->ksi_signo;
621         psp = p->p_sigacts;
622         mtx_assert(&psp->ps_mtx, MA_OWNED);
623 #ifdef COMPAT_FREEBSD4
624         if (SIGISMEMBER(psp->ps_freebsd4, sig)) {
625                 freebsd4_sendsig(catcher, ksi, mask);
626                 return;
627         }
628 #endif
629 #ifdef COMPAT_43
630         if (SIGISMEMBER(psp->ps_osigset, sig)) {
631                 osendsig(catcher, ksi, mask);
632                 return;
633         }
634 #endif
635         regs = td->td_frame;
636         oonstack = sigonstack(regs->tf_esp);
637
638 #ifdef CPU_ENABLE_SSE
639         if (cpu_max_ext_state_size > sizeof(union savefpu) && use_xsave) {
640                 xfpusave_len = cpu_max_ext_state_size - sizeof(union savefpu);
641                 xfpusave = __builtin_alloca(xfpusave_len);
642         } else {
643 #else
644         {
645 #endif
646                 xfpusave_len = 0;
647                 xfpusave = NULL;
648         }
649
650         /* Save user context. */
651         bzero(&sf, sizeof(sf));
652         sf.sf_uc.uc_sigmask = *mask;
653         sf.sf_uc.uc_stack = td->td_sigstk;
654         sf.sf_uc.uc_stack.ss_flags = (td->td_pflags & TDP_ALTSTACK)
655             ? ((oonstack) ? SS_ONSTACK : 0) : SS_DISABLE;
656         sf.sf_uc.uc_mcontext.mc_onstack = (oonstack) ? 1 : 0;
657         sf.sf_uc.uc_mcontext.mc_gs = rgs();
658         bcopy(regs, &sf.sf_uc.uc_mcontext.mc_fs, sizeof(*regs));
659         sf.sf_uc.uc_mcontext.mc_len = sizeof(sf.sf_uc.uc_mcontext); /* magic */
660         get_fpcontext(td, &sf.sf_uc.uc_mcontext, xfpusave, xfpusave_len);
661         fpstate_drop(td);
662         /*
663          * Unconditionally fill the fsbase and gsbase into the mcontext.
664          */
665         sdp = &td->td_pcb->pcb_fsd;
666         sf.sf_uc.uc_mcontext.mc_fsbase = sdp->sd_hibase << 24 |
667             sdp->sd_lobase;
668         sdp = &td->td_pcb->pcb_gsd;
669         sf.sf_uc.uc_mcontext.mc_gsbase = sdp->sd_hibase << 24 |
670             sdp->sd_lobase;
671         bzero(sf.sf_uc.uc_mcontext.mc_spare2,
672             sizeof(sf.sf_uc.uc_mcontext.mc_spare2));
673         bzero(sf.sf_uc.__spare__, sizeof(sf.sf_uc.__spare__));
674
675         /* Allocate space for the signal handler context. */
676         if ((td->td_pflags & TDP_ALTSTACK) != 0 && !oonstack &&
677             SIGISMEMBER(psp->ps_sigonstack, sig)) {
678                 sp = td->td_sigstk.ss_sp + td->td_sigstk.ss_size;
679 #if defined(COMPAT_43)
680                 td->td_sigstk.ss_flags |= SS_ONSTACK;
681 #endif
682         } else
683                 sp = (char *)regs->tf_esp - 128;
684         if (xfpusave != NULL) {
685                 sp -= xfpusave_len;
686                 sp = (char *)((unsigned int)sp & ~0x3F);
687                 sf.sf_uc.uc_mcontext.mc_xfpustate = (register_t)sp;
688         }
689         sp -= sizeof(struct sigframe);
690
691         /* Align to 16 bytes. */
692         sfp = (struct sigframe *)((unsigned int)sp & ~0xF);
693
694         /* Translate the signal if appropriate. */
695         if (p->p_sysent->sv_sigtbl && sig <= p->p_sysent->sv_sigsize)
696                 sig = p->p_sysent->sv_sigtbl[_SIG_IDX(sig)];
697
698         /* Build the argument list for the signal handler. */
699         sf.sf_signum = sig;
700         sf.sf_ucontext = (register_t)&sfp->sf_uc;
701         bzero(&sf.sf_si, sizeof(sf.sf_si));
702         if (SIGISMEMBER(psp->ps_siginfo, sig)) {
703                 /* Signal handler installed with SA_SIGINFO. */
704                 sf.sf_siginfo = (register_t)&sfp->sf_si;
705                 sf.sf_ahu.sf_action = (__siginfohandler_t *)catcher;
706
707                 /* Fill in POSIX parts */
708                 sf.sf_si = ksi->ksi_info;
709                 sf.sf_si.si_signo = sig; /* maybe a translated signal */
710         } else {
711                 /* Old FreeBSD-style arguments. */
712                 sf.sf_siginfo = ksi->ksi_code;
713                 sf.sf_addr = (register_t)ksi->ksi_addr;
714                 sf.sf_ahu.sf_handler = catcher;
715         }
716         mtx_unlock(&psp->ps_mtx);
717         PROC_UNLOCK(p);
718
719         /*
720          * If we're a vm86 process, we want to save the segment registers.
721          * We also change eflags to be our emulated eflags, not the actual
722          * eflags.
723          */
724         if (regs->tf_eflags & PSL_VM) {
725                 struct trapframe_vm86 *tf = (struct trapframe_vm86 *)regs;
726                 struct vm86_kernel *vm86 = &td->td_pcb->pcb_ext->ext_vm86;
727
728                 sf.sf_uc.uc_mcontext.mc_gs = tf->tf_vm86_gs;
729                 sf.sf_uc.uc_mcontext.mc_fs = tf->tf_vm86_fs;
730                 sf.sf_uc.uc_mcontext.mc_es = tf->tf_vm86_es;
731                 sf.sf_uc.uc_mcontext.mc_ds = tf->tf_vm86_ds;
732
733                 if (vm86->vm86_has_vme == 0)
734                         sf.sf_uc.uc_mcontext.mc_eflags =
735                             (tf->tf_eflags & ~(PSL_VIF | PSL_VIP)) |
736                             (vm86->vm86_eflags & (PSL_VIF | PSL_VIP));
737
738                 /*
739                  * Clear PSL_NT to inhibit T_TSSFLT faults on return from
740                  * syscalls made by the signal handler.  This just avoids
741                  * wasting time for our lazy fixup of such faults.  PSL_NT
742                  * does nothing in vm86 mode, but vm86 programs can set it
743                  * almost legitimately in probes for old cpu types.
744                  */
745                 tf->tf_eflags &= ~(PSL_VM | PSL_NT | PSL_VIF | PSL_VIP);
746         }
747
748         /*
749          * Copy the sigframe out to the user's stack.
750          */
751         if (copyout(&sf, sfp, sizeof(*sfp)) != 0 ||
752             (xfpusave != NULL && copyout(xfpusave,
753             (void *)sf.sf_uc.uc_mcontext.mc_xfpustate, xfpusave_len)
754             != 0)) {
755 #ifdef DEBUG
756                 printf("process %ld has trashed its stack\n", (long)p->p_pid);
757 #endif
758                 PROC_LOCK(p);
759                 sigexit(td, SIGILL);
760         }
761
762         regs->tf_esp = (int)sfp;
763         regs->tf_eip = p->p_sysent->sv_sigcode_base;
764         if (regs->tf_eip == 0)
765                 regs->tf_eip = p->p_sysent->sv_psstrings - szsigcode;
766         regs->tf_eflags &= ~(PSL_T | PSL_D);
767         regs->tf_cs = _ucodesel;
768         regs->tf_ds = _udatasel;
769         regs->tf_es = _udatasel;
770         regs->tf_fs = _udatasel;
771         regs->tf_ss = _udatasel;
772         PROC_LOCK(p);
773         mtx_lock(&psp->ps_mtx);
774 }
775
776 /*
777  * System call to cleanup state after a signal
778  * has been taken.  Reset signal mask and
779  * stack state from context left by sendsig (above).
780  * Return to previous pc and psl as specified by
781  * context left by sendsig. Check carefully to
782  * make sure that the user has not modified the
783  * state to gain improper privileges.
784  *
785  * MPSAFE
786  */
787 #ifdef COMPAT_43
788 int
789 osigreturn(td, uap)
790         struct thread *td;
791         struct osigreturn_args /* {
792                 struct osigcontext *sigcntxp;
793         } */ *uap;
794 {
795         struct osigcontext sc;
796         struct trapframe *regs;
797         struct osigcontext *scp;
798         int eflags, error;
799         ksiginfo_t ksi;
800
801         regs = td->td_frame;
802         error = copyin(uap->sigcntxp, &sc, sizeof(sc));
803         if (error != 0)
804                 return (error);
805         scp = &sc;
806         eflags = scp->sc_ps;
807         if (eflags & PSL_VM) {
808                 struct trapframe_vm86 *tf = (struct trapframe_vm86 *)regs;
809                 struct vm86_kernel *vm86;
810
811                 /*
812                  * if pcb_ext == 0 or vm86_inited == 0, the user hasn't
813                  * set up the vm86 area, and we can't enter vm86 mode.
814                  */
815                 if (td->td_pcb->pcb_ext == 0)
816                         return (EINVAL);
817                 vm86 = &td->td_pcb->pcb_ext->ext_vm86;
818                 if (vm86->vm86_inited == 0)
819                         return (EINVAL);
820
821                 /* Go back to user mode if both flags are set. */
822                 if ((eflags & PSL_VIP) && (eflags & PSL_VIF)) {
823                         ksiginfo_init_trap(&ksi);
824                         ksi.ksi_signo = SIGBUS;
825                         ksi.ksi_code = BUS_OBJERR;
826                         ksi.ksi_addr = (void *)regs->tf_eip;
827                         trapsignal(td, &ksi);
828                 }
829
830                 if (vm86->vm86_has_vme) {
831                         eflags = (tf->tf_eflags & ~VME_USERCHANGE) |
832                             (eflags & VME_USERCHANGE) | PSL_VM;
833                 } else {
834                         vm86->vm86_eflags = eflags;     /* save VIF, VIP */
835                         eflags = (tf->tf_eflags & ~VM_USERCHANGE) |
836                             (eflags & VM_USERCHANGE) | PSL_VM;
837                 }
838                 tf->tf_vm86_ds = scp->sc_ds;
839                 tf->tf_vm86_es = scp->sc_es;
840                 tf->tf_vm86_fs = scp->sc_fs;
841                 tf->tf_vm86_gs = scp->sc_gs;
842                 tf->tf_ds = _udatasel;
843                 tf->tf_es = _udatasel;
844                 tf->tf_fs = _udatasel;
845         } else {
846                 /*
847                  * Don't allow users to change privileged or reserved flags.
848                  */
849                 if (!EFL_SECURE(eflags, regs->tf_eflags)) {
850                         return (EINVAL);
851                 }
852
853                 /*
854                  * Don't allow users to load a valid privileged %cs.  Let the
855                  * hardware check for invalid selectors, excess privilege in
856                  * other selectors, invalid %eip's and invalid %esp's.
857                  */
858                 if (!CS_SECURE(scp->sc_cs)) {
859                         ksiginfo_init_trap(&ksi);
860                         ksi.ksi_signo = SIGBUS;
861                         ksi.ksi_code = BUS_OBJERR;
862                         ksi.ksi_trapno = T_PROTFLT;
863                         ksi.ksi_addr = (void *)regs->tf_eip;
864                         trapsignal(td, &ksi);
865                         return (EINVAL);
866                 }
867                 regs->tf_ds = scp->sc_ds;
868                 regs->tf_es = scp->sc_es;
869                 regs->tf_fs = scp->sc_fs;
870         }
871
872         /* Restore remaining registers. */
873         regs->tf_eax = scp->sc_eax;
874         regs->tf_ebx = scp->sc_ebx;
875         regs->tf_ecx = scp->sc_ecx;
876         regs->tf_edx = scp->sc_edx;
877         regs->tf_esi = scp->sc_esi;
878         regs->tf_edi = scp->sc_edi;
879         regs->tf_cs = scp->sc_cs;
880         regs->tf_ss = scp->sc_ss;
881         regs->tf_isp = scp->sc_isp;
882         regs->tf_ebp = scp->sc_fp;
883         regs->tf_esp = scp->sc_sp;
884         regs->tf_eip = scp->sc_pc;
885         regs->tf_eflags = eflags;
886
887 #if defined(COMPAT_43)
888         if (scp->sc_onstack & 1)
889                 td->td_sigstk.ss_flags |= SS_ONSTACK;
890         else
891                 td->td_sigstk.ss_flags &= ~SS_ONSTACK;
892 #endif
893         kern_sigprocmask(td, SIG_SETMASK, (sigset_t *)&scp->sc_mask, NULL,
894             SIGPROCMASK_OLD);
895         return (EJUSTRETURN);
896 }
897 #endif /* COMPAT_43 */
898
899 #ifdef COMPAT_FREEBSD4
900 /*
901  * MPSAFE
902  */
903 int
904 freebsd4_sigreturn(td, uap)
905         struct thread *td;
906         struct freebsd4_sigreturn_args /* {
907                 const ucontext4 *sigcntxp;
908         } */ *uap;
909 {
910         struct ucontext4 uc;
911         struct trapframe *regs;
912         struct ucontext4 *ucp;
913         int cs, eflags, error;
914         ksiginfo_t ksi;
915
916         error = copyin(uap->sigcntxp, &uc, sizeof(uc));
917         if (error != 0)
918                 return (error);
919         ucp = &uc;
920         regs = td->td_frame;
921         eflags = ucp->uc_mcontext.mc_eflags;
922         if (eflags & PSL_VM) {
923                 struct trapframe_vm86 *tf = (struct trapframe_vm86 *)regs;
924                 struct vm86_kernel *vm86;
925
926                 /*
927                  * if pcb_ext == 0 or vm86_inited == 0, the user hasn't
928                  * set up the vm86 area, and we can't enter vm86 mode.
929                  */
930                 if (td->td_pcb->pcb_ext == 0)
931                         return (EINVAL);
932                 vm86 = &td->td_pcb->pcb_ext->ext_vm86;
933                 if (vm86->vm86_inited == 0)
934                         return (EINVAL);
935
936                 /* Go back to user mode if both flags are set. */
937                 if ((eflags & PSL_VIP) && (eflags & PSL_VIF)) {
938                         ksiginfo_init_trap(&ksi);
939                         ksi.ksi_signo = SIGBUS;
940                         ksi.ksi_code = BUS_OBJERR;
941                         ksi.ksi_addr = (void *)regs->tf_eip;
942                         trapsignal(td, &ksi);
943                 }
944                 if (vm86->vm86_has_vme) {
945                         eflags = (tf->tf_eflags & ~VME_USERCHANGE) |
946                             (eflags & VME_USERCHANGE) | PSL_VM;
947                 } else {
948                         vm86->vm86_eflags = eflags;     /* save VIF, VIP */
949                         eflags = (tf->tf_eflags & ~VM_USERCHANGE) |
950                             (eflags & VM_USERCHANGE) | PSL_VM;
951                 }
952                 bcopy(&ucp->uc_mcontext.mc_fs, tf, sizeof(struct trapframe));
953                 tf->tf_eflags = eflags;
954                 tf->tf_vm86_ds = tf->tf_ds;
955                 tf->tf_vm86_es = tf->tf_es;
956                 tf->tf_vm86_fs = tf->tf_fs;
957                 tf->tf_vm86_gs = ucp->uc_mcontext.mc_gs;
958                 tf->tf_ds = _udatasel;
959                 tf->tf_es = _udatasel;
960                 tf->tf_fs = _udatasel;
961         } else {
962                 /*
963                  * Don't allow users to change privileged or reserved flags.
964                  */
965                 if (!EFL_SECURE(eflags, regs->tf_eflags)) {
966                         uprintf("pid %d (%s): freebsd4_sigreturn eflags = 0x%x\n",
967                             td->td_proc->p_pid, td->td_name, eflags);
968                         return (EINVAL);
969                 }
970
971                 /*
972                  * Don't allow users to load a valid privileged %cs.  Let the
973                  * hardware check for invalid selectors, excess privilege in
974                  * other selectors, invalid %eip's and invalid %esp's.
975                  */
976                 cs = ucp->uc_mcontext.mc_cs;
977                 if (!CS_SECURE(cs)) {
978                         uprintf("pid %d (%s): freebsd4_sigreturn cs = 0x%x\n",
979                             td->td_proc->p_pid, td->td_name, cs);
980                         ksiginfo_init_trap(&ksi);
981                         ksi.ksi_signo = SIGBUS;
982                         ksi.ksi_code = BUS_OBJERR;
983                         ksi.ksi_trapno = T_PROTFLT;
984                         ksi.ksi_addr = (void *)regs->tf_eip;
985                         trapsignal(td, &ksi);
986                         return (EINVAL);
987                 }
988
989                 bcopy(&ucp->uc_mcontext.mc_fs, regs, sizeof(*regs));
990         }
991
992 #if defined(COMPAT_43)
993         if (ucp->uc_mcontext.mc_onstack & 1)
994                 td->td_sigstk.ss_flags |= SS_ONSTACK;
995         else
996                 td->td_sigstk.ss_flags &= ~SS_ONSTACK;
997 #endif
998         kern_sigprocmask(td, SIG_SETMASK, &ucp->uc_sigmask, NULL, 0);
999         return (EJUSTRETURN);
1000 }
1001 #endif  /* COMPAT_FREEBSD4 */
1002
1003 /*
1004  * MPSAFE
1005  */
1006 int
1007 sys_sigreturn(td, uap)
1008         struct thread *td;
1009         struct sigreturn_args /* {
1010                 const struct __ucontext *sigcntxp;
1011         } */ *uap;
1012 {
1013         ucontext_t uc;
1014         struct proc *p;
1015         struct trapframe *regs;
1016         ucontext_t *ucp;
1017         char *xfpustate;
1018         size_t xfpustate_len;
1019         int cs, eflags, error, ret;
1020         ksiginfo_t ksi;
1021
1022         p = td->td_proc;
1023
1024         error = copyin(uap->sigcntxp, &uc, sizeof(uc));
1025         if (error != 0)
1026                 return (error);
1027         ucp = &uc;
1028         if ((ucp->uc_mcontext.mc_flags & ~_MC_FLAG_MASK) != 0) {
1029                 uprintf("pid %d (%s): sigreturn mc_flags %x\n", p->p_pid,
1030                     td->td_name, ucp->uc_mcontext.mc_flags);
1031                 return (EINVAL);
1032         }
1033         regs = td->td_frame;
1034         eflags = ucp->uc_mcontext.mc_eflags;
1035         if (eflags & PSL_VM) {
1036                 struct trapframe_vm86 *tf = (struct trapframe_vm86 *)regs;
1037                 struct vm86_kernel *vm86;
1038
1039                 /*
1040                  * if pcb_ext == 0 or vm86_inited == 0, the user hasn't
1041                  * set up the vm86 area, and we can't enter vm86 mode.
1042                  */
1043                 if (td->td_pcb->pcb_ext == 0)
1044                         return (EINVAL);
1045                 vm86 = &td->td_pcb->pcb_ext->ext_vm86;
1046                 if (vm86->vm86_inited == 0)
1047                         return (EINVAL);
1048
1049                 /* Go back to user mode if both flags are set. */
1050                 if ((eflags & PSL_VIP) && (eflags & PSL_VIF)) {
1051                         ksiginfo_init_trap(&ksi);
1052                         ksi.ksi_signo = SIGBUS;
1053                         ksi.ksi_code = BUS_OBJERR;
1054                         ksi.ksi_addr = (void *)regs->tf_eip;
1055                         trapsignal(td, &ksi);
1056                 }
1057
1058                 if (vm86->vm86_has_vme) {
1059                         eflags = (tf->tf_eflags & ~VME_USERCHANGE) |
1060                             (eflags & VME_USERCHANGE) | PSL_VM;
1061                 } else {
1062                         vm86->vm86_eflags = eflags;     /* save VIF, VIP */
1063                         eflags = (tf->tf_eflags & ~VM_USERCHANGE) |
1064                             (eflags & VM_USERCHANGE) | PSL_VM;
1065                 }
1066                 bcopy(&ucp->uc_mcontext.mc_fs, tf, sizeof(struct trapframe));
1067                 tf->tf_eflags = eflags;
1068                 tf->tf_vm86_ds = tf->tf_ds;
1069                 tf->tf_vm86_es = tf->tf_es;
1070                 tf->tf_vm86_fs = tf->tf_fs;
1071                 tf->tf_vm86_gs = ucp->uc_mcontext.mc_gs;
1072                 tf->tf_ds = _udatasel;
1073                 tf->tf_es = _udatasel;
1074                 tf->tf_fs = _udatasel;
1075         } else {
1076                 /*
1077                  * Don't allow users to change privileged or reserved flags.
1078                  */
1079                 if (!EFL_SECURE(eflags, regs->tf_eflags)) {
1080                         uprintf("pid %d (%s): sigreturn eflags = 0x%x\n",
1081                             td->td_proc->p_pid, td->td_name, eflags);
1082                         return (EINVAL);
1083                 }
1084
1085                 /*
1086                  * Don't allow users to load a valid privileged %cs.  Let the
1087                  * hardware check for invalid selectors, excess privilege in
1088                  * other selectors, invalid %eip's and invalid %esp's.
1089                  */
1090                 cs = ucp->uc_mcontext.mc_cs;
1091                 if (!CS_SECURE(cs)) {
1092                         uprintf("pid %d (%s): sigreturn cs = 0x%x\n",
1093                             td->td_proc->p_pid, td->td_name, cs);
1094                         ksiginfo_init_trap(&ksi);
1095                         ksi.ksi_signo = SIGBUS;
1096                         ksi.ksi_code = BUS_OBJERR;
1097                         ksi.ksi_trapno = T_PROTFLT;
1098                         ksi.ksi_addr = (void *)regs->tf_eip;
1099                         trapsignal(td, &ksi);
1100                         return (EINVAL);
1101                 }
1102
1103                 if ((uc.uc_mcontext.mc_flags & _MC_HASFPXSTATE) != 0) {
1104                         xfpustate_len = uc.uc_mcontext.mc_xfpustate_len;
1105                         if (xfpustate_len > cpu_max_ext_state_size -
1106                             sizeof(union savefpu)) {
1107                                 uprintf(
1108                             "pid %d (%s): sigreturn xfpusave_len = 0x%zx\n",
1109                                     p->p_pid, td->td_name, xfpustate_len);
1110                                 return (EINVAL);
1111                         }
1112                         xfpustate = __builtin_alloca(xfpustate_len);
1113                         error = copyin((const void *)uc.uc_mcontext.mc_xfpustate,
1114                             xfpustate, xfpustate_len);
1115                         if (error != 0) {
1116                                 uprintf(
1117         "pid %d (%s): sigreturn copying xfpustate failed\n",
1118                                     p->p_pid, td->td_name);
1119                                 return (error);
1120                         }
1121                 } else {
1122                         xfpustate = NULL;
1123                         xfpustate_len = 0;
1124                 }
1125                 ret = set_fpcontext(td, &ucp->uc_mcontext, xfpustate,
1126                     xfpustate_len);
1127                 if (ret != 0)
1128                         return (ret);
1129                 bcopy(&ucp->uc_mcontext.mc_fs, regs, sizeof(*regs));
1130         }
1131
1132 #if defined(COMPAT_43)
1133         if (ucp->uc_mcontext.mc_onstack & 1)
1134                 td->td_sigstk.ss_flags |= SS_ONSTACK;
1135         else
1136                 td->td_sigstk.ss_flags &= ~SS_ONSTACK;
1137 #endif
1138
1139         kern_sigprocmask(td, SIG_SETMASK, &ucp->uc_sigmask, NULL, 0);
1140         return (EJUSTRETURN);
1141 }
1142
1143 /*
1144  * Reset registers to default values on exec.
1145  */
1146 void
1147 exec_setregs(struct thread *td, struct image_params *imgp, u_long stack)
1148 {
1149         struct trapframe *regs = td->td_frame;
1150         struct pcb *pcb = td->td_pcb;
1151
1152         /* Reset pc->pcb_gs and %gs before possibly invalidating it. */
1153         pcb->pcb_gs = _udatasel;
1154         load_gs(_udatasel);
1155
1156         mtx_lock_spin(&dt_lock);
1157         if (td->td_proc->p_md.md_ldt)
1158                 user_ldt_free(td);
1159         else
1160                 mtx_unlock_spin(&dt_lock);
1161   
1162         bzero((char *)regs, sizeof(struct trapframe));
1163         regs->tf_eip = imgp->entry_addr;
1164         regs->tf_esp = stack;
1165         regs->tf_eflags = PSL_USER | (regs->tf_eflags & PSL_T);
1166         regs->tf_ss = _udatasel;
1167         regs->tf_ds = _udatasel;
1168         regs->tf_es = _udatasel;
1169         regs->tf_fs = _udatasel;
1170         regs->tf_cs = _ucodesel;
1171
1172         /* PS_STRINGS value for BSD/OS binaries.  It is 0 for non-BSD/OS. */
1173         regs->tf_ebx = imgp->ps_strings;
1174
1175         /*
1176          * Reset the hardware debug registers if they were in use.
1177          * They won't have any meaning for the newly exec'd process.  
1178          */
1179         if (pcb->pcb_flags & PCB_DBREGS) {
1180                 pcb->pcb_dr0 = 0;
1181                 pcb->pcb_dr1 = 0;
1182                 pcb->pcb_dr2 = 0;
1183                 pcb->pcb_dr3 = 0;
1184                 pcb->pcb_dr6 = 0;
1185                 pcb->pcb_dr7 = 0;
1186                 if (pcb == curpcb) {
1187                         /*
1188                          * Clear the debug registers on the running
1189                          * CPU, otherwise they will end up affecting
1190                          * the next process we switch to.
1191                          */
1192                         reset_dbregs();
1193                 }
1194                 pcb->pcb_flags &= ~PCB_DBREGS;
1195         }
1196
1197         pcb->pcb_initial_npxcw = __INITIAL_NPXCW__;
1198
1199         /*
1200          * Drop the FP state if we hold it, so that the process gets a
1201          * clean FP state if it uses the FPU again.
1202          */
1203         fpstate_drop(td);
1204
1205         /*
1206          * XXX - Linux emulator
1207          * Make sure sure edx is 0x0 on entry. Linux binaries depend
1208          * on it.
1209          */
1210         td->td_retval[1] = 0;
1211 }
1212
1213 void
1214 cpu_setregs(void)
1215 {
1216         unsigned int cr0;
1217
1218         cr0 = rcr0();
1219
1220         /*
1221          * CR0_MP, CR0_NE and CR0_TS are set for NPX (FPU) support:
1222          *
1223          * Prepare to trap all ESC (i.e., NPX) instructions and all WAIT
1224          * instructions.  We must set the CR0_MP bit and use the CR0_TS
1225          * bit to control the trap, because setting the CR0_EM bit does
1226          * not cause WAIT instructions to trap.  It's important to trap
1227          * WAIT instructions - otherwise the "wait" variants of no-wait
1228          * control instructions would degenerate to the "no-wait" variants
1229          * after FP context switches but work correctly otherwise.  It's
1230          * particularly important to trap WAITs when there is no NPX -
1231          * otherwise the "wait" variants would always degenerate.
1232          *
1233          * Try setting CR0_NE to get correct error reporting on 486DX's.
1234          * Setting it should fail or do nothing on lesser processors.
1235          */
1236         cr0 |= CR0_MP | CR0_NE | CR0_TS | CR0_WP | CR0_AM;
1237         load_cr0(cr0);
1238         load_gs(_udatasel);
1239 }
1240
1241 u_long bootdev;         /* not a struct cdev *- encoding is different */
1242 SYSCTL_ULONG(_machdep, OID_AUTO, guessed_bootdev,
1243         CTLFLAG_RD, &bootdev, 0, "Maybe the Boot device (not in struct cdev *format)");
1244
1245 static char bootmethod[16] = "BIOS";
1246 SYSCTL_STRING(_machdep, OID_AUTO, bootmethod, CTLFLAG_RD, bootmethod, 0,
1247     "System firmware boot method");
1248
1249 /*
1250  * Initialize 386 and configure to run kernel
1251  */
1252
1253 /*
1254  * Initialize segments & interrupt table
1255  */
1256
1257 int _default_ldt;
1258
1259 union descriptor gdt[NGDT * MAXCPU];    /* global descriptor table */
1260 union descriptor ldt[NLDT];             /* local descriptor table */
1261 static struct gate_descriptor idt0[NIDT];
1262 struct gate_descriptor *idt = &idt0[0]; /* interrupt descriptor table */
1263 struct region_descriptor r_gdt, r_idt;  /* table descriptors */
1264 struct mtx dt_lock;                     /* lock for GDT and LDT */
1265
1266 static struct i386tss dblfault_tss;
1267 static char dblfault_stack[PAGE_SIZE];
1268
1269 extern  vm_offset_t     proc0kstack;
1270
1271
1272 /*
1273  * software prototypes -- in more palatable form.
1274  *
1275  * GCODE_SEL through GUDATA_SEL must be in this order for syscall/sysret
1276  * GUFS_SEL and GUGS_SEL must be in this order (swtch.s knows it)
1277  */
1278 struct soft_segment_descriptor gdt_segs[] = {
1279 /* GNULL_SEL    0 Null Descriptor */
1280 {       .ssd_base = 0x0,
1281         .ssd_limit = 0x0,
1282         .ssd_type = 0,
1283         .ssd_dpl = SEL_KPL,
1284         .ssd_p = 0,
1285         .ssd_xx = 0, .ssd_xx1 = 0,
1286         .ssd_def32 = 0,
1287         .ssd_gran = 0           },
1288 /* GPRIV_SEL    1 SMP Per-Processor Private Data Descriptor */
1289 {       .ssd_base = 0x0,
1290         .ssd_limit = 0xfffff,
1291         .ssd_type = SDT_MEMRWA,
1292         .ssd_dpl = SEL_KPL,
1293         .ssd_p = 1,
1294         .ssd_xx = 0, .ssd_xx1 = 0,
1295         .ssd_def32 = 1,
1296         .ssd_gran = 1           },
1297 /* GUFS_SEL     2 %fs Descriptor for user */
1298 {       .ssd_base = 0x0,
1299         .ssd_limit = 0xfffff,
1300         .ssd_type = SDT_MEMRWA,
1301         .ssd_dpl = SEL_UPL,
1302         .ssd_p = 1,
1303         .ssd_xx = 0, .ssd_xx1 = 0,
1304         .ssd_def32 = 1,
1305         .ssd_gran = 1           },
1306 /* GUGS_SEL     3 %gs Descriptor for user */
1307 {       .ssd_base = 0x0,
1308         .ssd_limit = 0xfffff,
1309         .ssd_type = SDT_MEMRWA,
1310         .ssd_dpl = SEL_UPL,
1311         .ssd_p = 1,
1312         .ssd_xx = 0, .ssd_xx1 = 0,
1313         .ssd_def32 = 1,
1314         .ssd_gran = 1           },
1315 /* GCODE_SEL    4 Code Descriptor for kernel */
1316 {       .ssd_base = 0x0,
1317         .ssd_limit = 0xfffff,
1318         .ssd_type = SDT_MEMERA,
1319         .ssd_dpl = SEL_KPL,
1320         .ssd_p = 1,
1321         .ssd_xx = 0, .ssd_xx1 = 0,
1322         .ssd_def32 = 1,
1323         .ssd_gran = 1           },
1324 /* GDATA_SEL    5 Data Descriptor for kernel */
1325 {       .ssd_base = 0x0,
1326         .ssd_limit = 0xfffff,
1327         .ssd_type = SDT_MEMRWA,
1328         .ssd_dpl = SEL_KPL,
1329         .ssd_p = 1,
1330         .ssd_xx = 0, .ssd_xx1 = 0,
1331         .ssd_def32 = 1,
1332         .ssd_gran = 1           },
1333 /* GUCODE_SEL   6 Code Descriptor for user */
1334 {       .ssd_base = 0x0,
1335         .ssd_limit = 0xfffff,
1336         .ssd_type = SDT_MEMERA,
1337         .ssd_dpl = SEL_UPL,
1338         .ssd_p = 1,
1339         .ssd_xx = 0, .ssd_xx1 = 0,
1340         .ssd_def32 = 1,
1341         .ssd_gran = 1           },
1342 /* GUDATA_SEL   7 Data Descriptor for user */
1343 {       .ssd_base = 0x0,
1344         .ssd_limit = 0xfffff,
1345         .ssd_type = SDT_MEMRWA,
1346         .ssd_dpl = SEL_UPL,
1347         .ssd_p = 1,
1348         .ssd_xx = 0, .ssd_xx1 = 0,
1349         .ssd_def32 = 1,
1350         .ssd_gran = 1           },
1351 /* GBIOSLOWMEM_SEL 8 BIOS access to realmode segment 0x40, must be #8 in GDT */
1352 {       .ssd_base = 0x400,
1353         .ssd_limit = 0xfffff,
1354         .ssd_type = SDT_MEMRWA,
1355         .ssd_dpl = SEL_KPL,
1356         .ssd_p = 1,
1357         .ssd_xx = 0, .ssd_xx1 = 0,
1358         .ssd_def32 = 1,
1359         .ssd_gran = 1           },
1360 /* GPROC0_SEL   9 Proc 0 Tss Descriptor */
1361 {
1362         .ssd_base = 0x0,
1363         .ssd_limit = sizeof(struct i386tss)-1,
1364         .ssd_type = SDT_SYS386TSS,
1365         .ssd_dpl = 0,
1366         .ssd_p = 1,
1367         .ssd_xx = 0, .ssd_xx1 = 0,
1368         .ssd_def32 = 0,
1369         .ssd_gran = 0           },
1370 /* GLDT_SEL     10 LDT Descriptor */
1371 {       .ssd_base = (int) ldt,
1372         .ssd_limit = sizeof(ldt)-1,
1373         .ssd_type = SDT_SYSLDT,
1374         .ssd_dpl = SEL_UPL,
1375         .ssd_p = 1,
1376         .ssd_xx = 0, .ssd_xx1 = 0,
1377         .ssd_def32 = 0,
1378         .ssd_gran = 0           },
1379 /* GUSERLDT_SEL 11 User LDT Descriptor per process */
1380 {       .ssd_base = (int) ldt,
1381         .ssd_limit = (512 * sizeof(union descriptor)-1),
1382         .ssd_type = SDT_SYSLDT,
1383         .ssd_dpl = 0,
1384         .ssd_p = 1,
1385         .ssd_xx = 0, .ssd_xx1 = 0,
1386         .ssd_def32 = 0,
1387         .ssd_gran = 0           },
1388 /* GPANIC_SEL   12 Panic Tss Descriptor */
1389 {       .ssd_base = (int) &dblfault_tss,
1390         .ssd_limit = sizeof(struct i386tss)-1,
1391         .ssd_type = SDT_SYS386TSS,
1392         .ssd_dpl = 0,
1393         .ssd_p = 1,
1394         .ssd_xx = 0, .ssd_xx1 = 0,
1395         .ssd_def32 = 0,
1396         .ssd_gran = 0           },
1397 /* GBIOSCODE32_SEL 13 BIOS 32-bit interface (32bit Code) */
1398 {       .ssd_base = 0,
1399         .ssd_limit = 0xfffff,
1400         .ssd_type = SDT_MEMERA,
1401         .ssd_dpl = 0,
1402         .ssd_p = 1,
1403         .ssd_xx = 0, .ssd_xx1 = 0,
1404         .ssd_def32 = 0,
1405         .ssd_gran = 1           },
1406 /* GBIOSCODE16_SEL 14 BIOS 32-bit interface (16bit Code) */
1407 {       .ssd_base = 0,
1408         .ssd_limit = 0xfffff,
1409         .ssd_type = SDT_MEMERA,
1410         .ssd_dpl = 0,
1411         .ssd_p = 1,
1412         .ssd_xx = 0, .ssd_xx1 = 0,
1413         .ssd_def32 = 0,
1414         .ssd_gran = 1           },
1415 /* GBIOSDATA_SEL 15 BIOS 32-bit interface (Data) */
1416 {       .ssd_base = 0,
1417         .ssd_limit = 0xfffff,
1418         .ssd_type = SDT_MEMRWA,
1419         .ssd_dpl = 0,
1420         .ssd_p = 1,
1421         .ssd_xx = 0, .ssd_xx1 = 0,
1422         .ssd_def32 = 1,
1423         .ssd_gran = 1           },
1424 /* GBIOSUTIL_SEL 16 BIOS 16-bit interface (Utility) */
1425 {       .ssd_base = 0,
1426         .ssd_limit = 0xfffff,
1427         .ssd_type = SDT_MEMRWA,
1428         .ssd_dpl = 0,
1429         .ssd_p = 1,
1430         .ssd_xx = 0, .ssd_xx1 = 0,
1431         .ssd_def32 = 0,
1432         .ssd_gran = 1           },
1433 /* GBIOSARGS_SEL 17 BIOS 16-bit interface (Arguments) */
1434 {       .ssd_base = 0,
1435         .ssd_limit = 0xfffff,
1436         .ssd_type = SDT_MEMRWA,
1437         .ssd_dpl = 0,
1438         .ssd_p = 1,
1439         .ssd_xx = 0, .ssd_xx1 = 0,
1440         .ssd_def32 = 0,
1441         .ssd_gran = 1           },
1442 /* GNDIS_SEL    18 NDIS Descriptor */
1443 {       .ssd_base = 0x0,
1444         .ssd_limit = 0x0,
1445         .ssd_type = 0,
1446         .ssd_dpl = 0,
1447         .ssd_p = 0,
1448         .ssd_xx = 0, .ssd_xx1 = 0,
1449         .ssd_def32 = 0,
1450         .ssd_gran = 0           },
1451 };
1452
1453 static struct soft_segment_descriptor ldt_segs[] = {
1454         /* Null Descriptor - overwritten by call gate */
1455 {       .ssd_base = 0x0,
1456         .ssd_limit = 0x0,
1457         .ssd_type = 0,
1458         .ssd_dpl = 0,
1459         .ssd_p = 0,
1460         .ssd_xx = 0, .ssd_xx1 = 0,
1461         .ssd_def32 = 0,
1462         .ssd_gran = 0           },
1463         /* Null Descriptor - overwritten by call gate */
1464 {       .ssd_base = 0x0,
1465         .ssd_limit = 0x0,
1466         .ssd_type = 0,
1467         .ssd_dpl = 0,
1468         .ssd_p = 0,
1469         .ssd_xx = 0, .ssd_xx1 = 0,
1470         .ssd_def32 = 0,
1471         .ssd_gran = 0           },
1472         /* Null Descriptor - overwritten by call gate */
1473 {       .ssd_base = 0x0,
1474         .ssd_limit = 0x0,
1475         .ssd_type = 0,
1476         .ssd_dpl = 0,
1477         .ssd_p = 0,
1478         .ssd_xx = 0, .ssd_xx1 = 0,
1479         .ssd_def32 = 0,
1480         .ssd_gran = 0           },
1481         /* Code Descriptor for user */
1482 {       .ssd_base = 0x0,
1483         .ssd_limit = 0xfffff,
1484         .ssd_type = SDT_MEMERA,
1485         .ssd_dpl = SEL_UPL,
1486         .ssd_p = 1,
1487         .ssd_xx = 0, .ssd_xx1 = 0,
1488         .ssd_def32 = 1,
1489         .ssd_gran = 1           },
1490         /* Null Descriptor - overwritten by call gate */
1491 {       .ssd_base = 0x0,
1492         .ssd_limit = 0x0,
1493         .ssd_type = 0,
1494         .ssd_dpl = 0,
1495         .ssd_p = 0,
1496         .ssd_xx = 0, .ssd_xx1 = 0,
1497         .ssd_def32 = 0,
1498         .ssd_gran = 0           },
1499         /* Data Descriptor for user */
1500 {       .ssd_base = 0x0,
1501         .ssd_limit = 0xfffff,
1502         .ssd_type = SDT_MEMRWA,
1503         .ssd_dpl = SEL_UPL,
1504         .ssd_p = 1,
1505         .ssd_xx = 0, .ssd_xx1 = 0,
1506         .ssd_def32 = 1,
1507         .ssd_gran = 1           },
1508 };
1509
1510 void
1511 setidt(idx, func, typ, dpl, selec)
1512         int idx;
1513         inthand_t *func;
1514         int typ;
1515         int dpl;
1516         int selec;
1517 {
1518         struct gate_descriptor *ip;
1519
1520         ip = idt + idx;
1521         ip->gd_looffset = (int)func;
1522         ip->gd_selector = selec;
1523         ip->gd_stkcpy = 0;
1524         ip->gd_xx = 0;
1525         ip->gd_type = typ;
1526         ip->gd_dpl = dpl;
1527         ip->gd_p = 1;
1528         ip->gd_hioffset = ((int)func)>>16 ;
1529 }
1530
1531 extern inthand_t
1532         IDTVEC(div), IDTVEC(dbg), IDTVEC(nmi), IDTVEC(bpt), IDTVEC(ofl),
1533         IDTVEC(bnd), IDTVEC(ill), IDTVEC(dna), IDTVEC(fpusegm),
1534         IDTVEC(tss), IDTVEC(missing), IDTVEC(stk), IDTVEC(prot),
1535         IDTVEC(page), IDTVEC(mchk), IDTVEC(rsvd), IDTVEC(fpu), IDTVEC(align),
1536         IDTVEC(xmm),
1537 #ifdef KDTRACE_HOOKS
1538         IDTVEC(dtrace_ret),
1539 #endif
1540 #ifdef XENHVM
1541         IDTVEC(xen_intr_upcall),
1542 #endif
1543         IDTVEC(lcall_syscall), IDTVEC(int0x80_syscall);
1544
1545 #ifdef DDB
1546 /*
1547  * Display the index and function name of any IDT entries that don't use
1548  * the default 'rsvd' entry point.
1549  */
1550 DB_SHOW_COMMAND(idt, db_show_idt)
1551 {
1552         struct gate_descriptor *ip;
1553         int idx;
1554         uintptr_t func;
1555
1556         ip = idt;
1557         for (idx = 0; idx < NIDT && !db_pager_quit; idx++) {
1558                 func = (ip->gd_hioffset << 16 | ip->gd_looffset);
1559                 if (func != (uintptr_t)&IDTVEC(rsvd)) {
1560                         db_printf("%3d\t", idx);
1561                         db_printsym(func, DB_STGY_PROC);
1562                         db_printf("\n");
1563                 }
1564                 ip++;
1565         }
1566 }
1567
1568 /* Show privileged registers. */
1569 DB_SHOW_COMMAND(sysregs, db_show_sysregs)
1570 {
1571         uint64_t idtr, gdtr;
1572
1573         idtr = ridt();
1574         db_printf("idtr\t0x%08x/%04x\n",
1575             (u_int)(idtr >> 16), (u_int)idtr & 0xffff);
1576         gdtr = rgdt();
1577         db_printf("gdtr\t0x%08x/%04x\n",
1578             (u_int)(gdtr >> 16), (u_int)gdtr & 0xffff);
1579         db_printf("ldtr\t0x%04x\n", rldt());
1580         db_printf("tr\t0x%04x\n", rtr());
1581         db_printf("cr0\t0x%08x\n", rcr0());
1582         db_printf("cr2\t0x%08x\n", rcr2());
1583         db_printf("cr3\t0x%08x\n", rcr3());
1584         db_printf("cr4\t0x%08x\n", rcr4());
1585 }
1586 #endif
1587
1588 void
1589 sdtossd(sd, ssd)
1590         struct segment_descriptor *sd;
1591         struct soft_segment_descriptor *ssd;
1592 {
1593         ssd->ssd_base  = (sd->sd_hibase << 24) | sd->sd_lobase;
1594         ssd->ssd_limit = (sd->sd_hilimit << 16) | sd->sd_lolimit;
1595         ssd->ssd_type  = sd->sd_type;
1596         ssd->ssd_dpl   = sd->sd_dpl;
1597         ssd->ssd_p     = sd->sd_p;
1598         ssd->ssd_def32 = sd->sd_def32;
1599         ssd->ssd_gran  = sd->sd_gran;
1600 }
1601
1602 #if !defined(PC98)
1603 static int
1604 add_physmap_entry(uint64_t base, uint64_t length, vm_paddr_t *physmap,
1605     int *physmap_idxp)
1606 {
1607         int i, insert_idx, physmap_idx;
1608
1609         physmap_idx = *physmap_idxp;
1610         
1611         if (length == 0)
1612                 return (1);
1613
1614 #ifndef PAE
1615         if (base > 0xffffffff) {
1616                 printf("%uK of memory above 4GB ignored\n",
1617                     (u_int)(length / 1024));
1618                 return (1);
1619         }
1620 #endif
1621
1622         /*
1623          * Find insertion point while checking for overlap.  Start off by
1624          * assuming the new entry will be added to the end.
1625          */
1626         insert_idx = physmap_idx + 2;
1627         for (i = 0; i <= physmap_idx; i += 2) {
1628                 if (base < physmap[i + 1]) {
1629                         if (base + length <= physmap[i]) {
1630                                 insert_idx = i;
1631                                 break;
1632                         }
1633                         if (boothowto & RB_VERBOSE)
1634                                 printf(
1635                     "Overlapping memory regions, ignoring second region\n");
1636                         return (1);
1637                 }
1638         }
1639
1640         /* See if we can prepend to the next entry. */
1641         if (insert_idx <= physmap_idx && base + length == physmap[insert_idx]) {
1642                 physmap[insert_idx] = base;
1643                 return (1);
1644         }
1645
1646         /* See if we can append to the previous entry. */
1647         if (insert_idx > 0 && base == physmap[insert_idx - 1]) {
1648                 physmap[insert_idx - 1] += length;
1649                 return (1);
1650         }
1651
1652         physmap_idx += 2;
1653         *physmap_idxp = physmap_idx;
1654         if (physmap_idx == PHYSMAP_SIZE) {
1655                 printf(
1656                 "Too many segments in the physical address map, giving up\n");
1657                 return (0);
1658         }
1659
1660         /*
1661          * Move the last 'N' entries down to make room for the new
1662          * entry if needed.
1663          */
1664         for (i = physmap_idx; i > insert_idx; i -= 2) {
1665                 physmap[i] = physmap[i - 2];
1666                 physmap[i + 1] = physmap[i - 1];
1667         }
1668
1669         /* Insert the new entry. */
1670         physmap[insert_idx] = base;
1671         physmap[insert_idx + 1] = base + length;
1672         return (1);
1673 }
1674
1675 static int
1676 add_smap_entry(struct bios_smap *smap, vm_paddr_t *physmap, int *physmap_idxp)
1677 {
1678         if (boothowto & RB_VERBOSE)
1679                 printf("SMAP type=%02x base=%016llx len=%016llx\n",
1680                     smap->type, smap->base, smap->length);
1681
1682         if (smap->type != SMAP_TYPE_MEMORY)
1683                 return (1);
1684
1685         return (add_physmap_entry(smap->base, smap->length, physmap,
1686             physmap_idxp));
1687 }
1688
1689 static void
1690 add_smap_entries(struct bios_smap *smapbase, vm_paddr_t *physmap,
1691     int *physmap_idxp)
1692 {
1693         struct bios_smap *smap, *smapend;
1694         u_int32_t smapsize;
1695         /*
1696          * Memory map from INT 15:E820.
1697          *
1698          * subr_module.c says:
1699          * "Consumer may safely assume that size value precedes data."
1700          * ie: an int32_t immediately precedes SMAP.
1701          */
1702         smapsize = *((u_int32_t *)smapbase - 1);
1703         smapend = (struct bios_smap *)((uintptr_t)smapbase + smapsize);
1704
1705         for (smap = smapbase; smap < smapend; smap++)
1706                 if (!add_smap_entry(smap, physmap, physmap_idxp))
1707                         break;
1708 }
1709 #endif /* !PC98 */
1710
1711 static void
1712 basemem_setup(void)
1713 {
1714         vm_paddr_t pa;
1715         pt_entry_t *pte;
1716         int i;
1717
1718         if (basemem > 640) {
1719                 printf("Preposterous BIOS basemem of %uK, truncating to 640K\n",
1720                         basemem);
1721                 basemem = 640;
1722         }
1723
1724         /*
1725          * XXX if biosbasemem is now < 640, there is a `hole'
1726          * between the end of base memory and the start of
1727          * ISA memory.  The hole may be empty or it may
1728          * contain BIOS code or data.  Map it read/write so
1729          * that the BIOS can write to it.  (Memory from 0 to
1730          * the physical end of the kernel is mapped read-only
1731          * to begin with and then parts of it are remapped.
1732          * The parts that aren't remapped form holes that
1733          * remain read-only and are unused by the kernel.
1734          * The base memory area is below the physical end of
1735          * the kernel and right now forms a read-only hole.
1736          * The part of it from PAGE_SIZE to
1737          * (trunc_page(biosbasemem * 1024) - 1) will be
1738          * remapped and used by the kernel later.)
1739          *
1740          * This code is similar to the code used in
1741          * pmap_mapdev, but since no memory needs to be
1742          * allocated we simply change the mapping.
1743          */
1744         for (pa = trunc_page(basemem * 1024);
1745              pa < ISA_HOLE_START; pa += PAGE_SIZE)
1746                 pmap_kenter(KERNBASE + pa, pa);
1747
1748         /*
1749          * Map pages between basemem and ISA_HOLE_START, if any, r/w into
1750          * the vm86 page table so that vm86 can scribble on them using
1751          * the vm86 map too.  XXX: why 2 ways for this and only 1 way for
1752          * page 0, at least as initialized here?
1753          */
1754         pte = (pt_entry_t *)vm86paddr;
1755         for (i = basemem / 4; i < 160; i++)
1756                 pte[i] = (i << PAGE_SHIFT) | PG_V | PG_RW | PG_U;
1757 }
1758
1759 /*
1760  * Populate the (physmap) array with base/bound pairs describing the
1761  * available physical memory in the system, then test this memory and
1762  * build the phys_avail array describing the actually-available memory.
1763  *
1764  * If we cannot accurately determine the physical memory map, then use
1765  * value from the 0xE801 call, and failing that, the RTC.
1766  *
1767  * Total memory size may be set by the kernel environment variable
1768  * hw.physmem or the compile-time define MAXMEM.
1769  *
1770  * XXX first should be vm_paddr_t.
1771  */
1772 #ifdef PC98
1773 static void
1774 getmemsize(int first)
1775 {
1776         int off, physmap_idx, pa_indx, da_indx;
1777         u_long physmem_tunable, memtest;
1778         vm_paddr_t physmap[PHYSMAP_SIZE];
1779         pt_entry_t *pte;
1780         quad_t dcons_addr, dcons_size;
1781         int i;
1782         int pg_n;
1783         u_int extmem;
1784         u_int under16;
1785         vm_paddr_t pa;
1786
1787         bzero(physmap, sizeof(physmap));
1788
1789         /* XXX - some of EPSON machines can't use PG_N */
1790         pg_n = PG_N;
1791         if (pc98_machine_type & M_EPSON_PC98) {
1792                 switch (epson_machine_id) {
1793 #ifdef WB_CACHE
1794                 default:
1795 #endif
1796                 case EPSON_PC486_HX:
1797                 case EPSON_PC486_HG:
1798                 case EPSON_PC486_HA:
1799                         pg_n = 0;
1800                         break;
1801                 }
1802         }
1803
1804         under16 = pc98_getmemsize(&basemem, &extmem);
1805         basemem_setup();
1806
1807         physmap[0] = 0;
1808         physmap[1] = basemem * 1024;
1809         physmap_idx = 2;
1810         physmap[physmap_idx] = 0x100000;
1811         physmap[physmap_idx + 1] = physmap[physmap_idx] + extmem * 1024;
1812
1813         /*
1814          * Now, physmap contains a map of physical memory.
1815          */
1816
1817 #ifdef SMP
1818         /* make hole for AP bootstrap code */
1819         physmap[1] = mp_bootaddress(physmap[1]);
1820 #endif
1821
1822         /*
1823          * Maxmem isn't the "maximum memory", it's one larger than the
1824          * highest page of the physical address space.  It should be
1825          * called something like "Maxphyspage".  We may adjust this 
1826          * based on ``hw.physmem'' and the results of the memory test.
1827          */
1828         Maxmem = atop(physmap[physmap_idx + 1]);
1829
1830 #ifdef MAXMEM
1831         Maxmem = MAXMEM / 4;
1832 #endif
1833
1834         if (TUNABLE_ULONG_FETCH("hw.physmem", &physmem_tunable))
1835                 Maxmem = atop(physmem_tunable);
1836
1837         /*
1838          * By default keep the memtest enabled.  Use a general name so that
1839          * one could eventually do more with the code than just disable it.
1840          */
1841         memtest = 1;
1842         TUNABLE_ULONG_FETCH("hw.memtest.tests", &memtest);
1843
1844         if (atop(physmap[physmap_idx + 1]) != Maxmem &&
1845             (boothowto & RB_VERBOSE))
1846                 printf("Physical memory use set to %ldK\n", Maxmem * 4);
1847
1848         /*
1849          * If Maxmem has been increased beyond what the system has detected,
1850          * extend the last memory segment to the new limit.
1851          */ 
1852         if (atop(physmap[physmap_idx + 1]) < Maxmem)
1853                 physmap[physmap_idx + 1] = ptoa((vm_paddr_t)Maxmem);
1854
1855         /*
1856          * We need to divide chunk if Maxmem is larger than 16MB and
1857          * under 16MB area is not full of memory.
1858          * (1) system area (15-16MB region) is cut off
1859          * (2) extended memory is only over 16MB area (ex. Melco "HYPERMEMORY")
1860          */
1861         if ((under16 != 16 * 1024) && (extmem > 15 * 1024)) {
1862                 /* 15M - 16M region is cut off, so need to divide chunk */
1863                 physmap[physmap_idx + 1] = under16 * 1024;
1864                 physmap_idx += 2;
1865                 physmap[physmap_idx] = 0x1000000;
1866                 physmap[physmap_idx + 1] = physmap[2] + extmem * 1024;
1867         }
1868
1869         /* call pmap initialization to make new kernel address space */
1870         pmap_bootstrap(first);
1871
1872         /*
1873          * Size up each available chunk of physical memory.
1874          */
1875         physmap[0] = PAGE_SIZE;         /* mask off page 0 */
1876         pa_indx = 0;
1877         da_indx = 1;
1878         phys_avail[pa_indx++] = physmap[0];
1879         phys_avail[pa_indx] = physmap[0];
1880         dump_avail[da_indx] = physmap[0];
1881         pte = CMAP3;
1882
1883         /*
1884          * Get dcons buffer address
1885          */
1886         if (getenv_quad("dcons.addr", &dcons_addr) == 0 ||
1887             getenv_quad("dcons.size", &dcons_size) == 0)
1888                 dcons_addr = 0;
1889
1890         /*
1891          * physmap is in bytes, so when converting to page boundaries,
1892          * round up the start address and round down the end address.
1893          */
1894         for (i = 0; i <= physmap_idx; i += 2) {
1895                 vm_paddr_t end;
1896
1897                 end = ptoa((vm_paddr_t)Maxmem);
1898                 if (physmap[i + 1] < end)
1899                         end = trunc_page(physmap[i + 1]);
1900                 for (pa = round_page(physmap[i]); pa < end; pa += PAGE_SIZE) {
1901                         int tmp, page_bad, full;
1902                         int *ptr = (int *)CADDR3;
1903
1904                         full = FALSE;
1905                         /*
1906                          * block out kernel memory as not available.
1907                          */
1908                         if (pa >= KERNLOAD && pa < first)
1909                                 goto do_dump_avail;
1910
1911                         /*
1912                          * block out dcons buffer
1913                          */
1914                         if (dcons_addr > 0
1915                             && pa >= trunc_page(dcons_addr)
1916                             && pa < dcons_addr + dcons_size)
1917                                 goto do_dump_avail;
1918
1919                         page_bad = FALSE;
1920                         if (memtest == 0)
1921                                 goto skip_memtest;
1922
1923                         /*
1924                          * map page into kernel: valid, read/write,non-cacheable
1925                          */
1926                         *pte = pa | PG_V | PG_RW | pg_n;
1927                         invltlb();
1928
1929                         tmp = *(int *)ptr;
1930                         /*
1931                          * Test for alternating 1's and 0's
1932                          */
1933                         *(volatile int *)ptr = 0xaaaaaaaa;
1934                         if (*(volatile int *)ptr != 0xaaaaaaaa)
1935                                 page_bad = TRUE;
1936                         /*
1937                          * Test for alternating 0's and 1's
1938                          */
1939                         *(volatile int *)ptr = 0x55555555;
1940                         if (*(volatile int *)ptr != 0x55555555)
1941                                 page_bad = TRUE;
1942                         /*
1943                          * Test for all 1's
1944                          */
1945                         *(volatile int *)ptr = 0xffffffff;
1946                         if (*(volatile int *)ptr != 0xffffffff)
1947                                 page_bad = TRUE;
1948                         /*
1949                          * Test for all 0's
1950                          */
1951                         *(volatile int *)ptr = 0x0;
1952                         if (*(volatile int *)ptr != 0x0)
1953                                 page_bad = TRUE;
1954                         /*
1955                          * Restore original value.
1956                          */
1957                         *(int *)ptr = tmp;
1958
1959 skip_memtest:
1960                         /*
1961                          * Adjust array of valid/good pages.
1962                          */
1963                         if (page_bad == TRUE)
1964                                 continue;
1965                         /*
1966                          * If this good page is a continuation of the
1967                          * previous set of good pages, then just increase
1968                          * the end pointer. Otherwise start a new chunk.
1969                          * Note that "end" points one higher than end,
1970                          * making the range >= start and < end.
1971                          * If we're also doing a speculative memory
1972                          * test and we at or past the end, bump up Maxmem
1973                          * so that we keep going. The first bad page
1974                          * will terminate the loop.
1975                          */
1976                         if (phys_avail[pa_indx] == pa) {
1977                                 phys_avail[pa_indx] += PAGE_SIZE;
1978                         } else {
1979                                 pa_indx++;
1980                                 if (pa_indx == PHYS_AVAIL_ARRAY_END) {
1981                                         printf(
1982                 "Too many holes in the physical address space, giving up\n");
1983                                         pa_indx--;
1984                                         full = TRUE;
1985                                         goto do_dump_avail;
1986                                 }
1987                                 phys_avail[pa_indx++] = pa;     /* start */
1988                                 phys_avail[pa_indx] = pa + PAGE_SIZE; /* end */
1989                         }
1990                         physmem++;
1991 do_dump_avail:
1992                         if (dump_avail[da_indx] == pa) {
1993                                 dump_avail[da_indx] += PAGE_SIZE;
1994                         } else {
1995                                 da_indx++;
1996                                 if (da_indx == DUMP_AVAIL_ARRAY_END) {
1997                                         da_indx--;
1998                                         goto do_next;
1999                                 }
2000                                 dump_avail[da_indx++] = pa;     /* start */
2001                                 dump_avail[da_indx] = pa + PAGE_SIZE; /* end */
2002                         }
2003 do_next:
2004                         if (full)
2005                                 break;
2006                 }
2007         }
2008         *pte = 0;
2009         invltlb();
2010         
2011         /*
2012          * XXX
2013          * The last chunk must contain at least one page plus the message
2014          * buffer to avoid complicating other code (message buffer address
2015          * calculation, etc.).
2016          */
2017         while (phys_avail[pa_indx - 1] + PAGE_SIZE +
2018             round_page(msgbufsize) >= phys_avail[pa_indx]) {
2019                 physmem -= atop(phys_avail[pa_indx] - phys_avail[pa_indx - 1]);
2020                 phys_avail[pa_indx--] = 0;
2021                 phys_avail[pa_indx--] = 0;
2022         }
2023
2024         Maxmem = atop(phys_avail[pa_indx]);
2025
2026         /* Trim off space for the message buffer. */
2027         phys_avail[pa_indx] -= round_page(msgbufsize);
2028
2029         /* Map the message buffer. */
2030         for (off = 0; off < round_page(msgbufsize); off += PAGE_SIZE)
2031                 pmap_kenter((vm_offset_t)msgbufp + off, phys_avail[pa_indx] +
2032                     off);
2033 }
2034 #else /* PC98 */
2035 static void
2036 getmemsize(int first)
2037 {
2038         int has_smap, off, physmap_idx, pa_indx, da_indx;
2039         u_long memtest;
2040         vm_paddr_t physmap[PHYSMAP_SIZE];
2041         pt_entry_t *pte;
2042         quad_t dcons_addr, dcons_size, physmem_tunable;
2043         int hasbrokenint12, i, res;
2044         u_int extmem;
2045         struct vm86frame vmf;
2046         struct vm86context vmc;
2047         vm_paddr_t pa;
2048         struct bios_smap *smap, *smapbase;
2049         caddr_t kmdp;
2050
2051         has_smap = 0;
2052 #ifdef XBOX
2053         if (arch_i386_is_xbox) {
2054                 /*
2055                  * We queried the memory size before, so chop off 4MB for
2056                  * the framebuffer and inform the OS of this.
2057                  */
2058                 physmap[0] = 0;
2059                 physmap[1] = (arch_i386_xbox_memsize * 1024 * 1024) - XBOX_FB_SIZE;
2060                 physmap_idx = 0;
2061                 goto physmap_done;
2062         }
2063 #endif
2064         bzero(&vmf, sizeof(vmf));
2065         bzero(physmap, sizeof(physmap));
2066         basemem = 0;
2067
2068         /*
2069          * Check if the loader supplied an SMAP memory map.  If so,
2070          * use that and do not make any VM86 calls.
2071          */
2072         physmap_idx = 0;
2073         smapbase = NULL;
2074         kmdp = preload_search_by_type("elf kernel");
2075         if (kmdp == NULL)
2076                 kmdp = preload_search_by_type("elf32 kernel");
2077         if (kmdp != NULL)
2078                 smapbase = (struct bios_smap *)preload_search_info(kmdp,
2079                     MODINFO_METADATA | MODINFOMD_SMAP);
2080         if (smapbase != NULL) {
2081                 add_smap_entries(smapbase, physmap, &physmap_idx);
2082                 has_smap = 1;
2083                 goto have_smap;
2084         }
2085
2086         /*
2087          * Some newer BIOSes have a broken INT 12H implementation
2088          * which causes a kernel panic immediately.  In this case, we
2089          * need use the SMAP to determine the base memory size.
2090          */
2091         hasbrokenint12 = 0;
2092         TUNABLE_INT_FETCH("hw.hasbrokenint12", &hasbrokenint12);
2093         if (hasbrokenint12 == 0) {
2094                 /* Use INT12 to determine base memory size. */
2095                 vm86_intcall(0x12, &vmf);
2096                 basemem = vmf.vmf_ax;
2097                 basemem_setup();
2098         }
2099
2100         /*
2101          * Fetch the memory map with INT 15:E820.  Map page 1 R/W into
2102          * the kernel page table so we can use it as a buffer.  The
2103          * kernel will unmap this page later.
2104          */
2105         pmap_kenter(KERNBASE + (1 << PAGE_SHIFT), 1 << PAGE_SHIFT);
2106         vmc.npages = 0;
2107         smap = (void *)vm86_addpage(&vmc, 1, KERNBASE + (1 << PAGE_SHIFT));
2108         res = vm86_getptr(&vmc, (vm_offset_t)smap, &vmf.vmf_es, &vmf.vmf_di);
2109         KASSERT(res != 0, ("vm86_getptr() failed: address not found"));
2110
2111         vmf.vmf_ebx = 0;
2112         do {
2113                 vmf.vmf_eax = 0xE820;
2114                 vmf.vmf_edx = SMAP_SIG;
2115                 vmf.vmf_ecx = sizeof(struct bios_smap);
2116                 i = vm86_datacall(0x15, &vmf, &vmc);
2117                 if (i || vmf.vmf_eax != SMAP_SIG)
2118                         break;
2119                 has_smap = 1;
2120                 if (!add_smap_entry(smap, physmap, &physmap_idx))
2121                         break;
2122         } while (vmf.vmf_ebx != 0);
2123
2124 have_smap:
2125         /*
2126          * If we didn't fetch the "base memory" size from INT12,
2127          * figure it out from the SMAP (or just guess).
2128          */
2129         if (basemem == 0) {
2130                 for (i = 0; i <= physmap_idx; i += 2) {
2131                         if (physmap[i] == 0x00000000) {
2132                                 basemem = physmap[i + 1] / 1024;
2133                                 break;
2134                         }
2135                 }
2136
2137                 /* XXX: If we couldn't find basemem from SMAP, just guess. */
2138                 if (basemem == 0)
2139                         basemem = 640;
2140                 basemem_setup();
2141         }
2142
2143         if (physmap[1] != 0)
2144                 goto physmap_done;
2145
2146         /*
2147          * If we failed to find an SMAP, figure out the extended
2148          * memory size.  We will then build a simple memory map with
2149          * two segments, one for "base memory" and the second for
2150          * "extended memory".  Note that "extended memory" starts at a
2151          * physical address of 1MB and that both basemem and extmem
2152          * are in units of 1KB.
2153          *
2154          * First, try to fetch the extended memory size via INT 15:E801.
2155          */
2156         vmf.vmf_ax = 0xE801;
2157         if (vm86_intcall(0x15, &vmf) == 0) {
2158                 extmem = vmf.vmf_cx + vmf.vmf_dx * 64;
2159         } else {
2160                 /*
2161                  * If INT15:E801 fails, this is our last ditch effort
2162                  * to determine the extended memory size.  Currently
2163                  * we prefer the RTC value over INT15:88.
2164                  */
2165 #if 0
2166                 vmf.vmf_ah = 0x88;
2167                 vm86_intcall(0x15, &vmf);
2168                 extmem = vmf.vmf_ax;
2169 #else
2170                 extmem = rtcin(RTC_EXTLO) + (rtcin(RTC_EXTHI) << 8);
2171 #endif
2172         }
2173
2174         /*
2175          * Special hack for chipsets that still remap the 384k hole when
2176          * there's 16MB of memory - this really confuses people that
2177          * are trying to use bus mastering ISA controllers with the
2178          * "16MB limit"; they only have 16MB, but the remapping puts
2179          * them beyond the limit.
2180          *
2181          * If extended memory is between 15-16MB (16-17MB phys address range),
2182          *      chop it to 15MB.
2183          */
2184         if ((extmem > 15 * 1024) && (extmem < 16 * 1024))
2185                 extmem = 15 * 1024;
2186
2187         physmap[0] = 0;
2188         physmap[1] = basemem * 1024;
2189         physmap_idx = 2;
2190         physmap[physmap_idx] = 0x100000;
2191         physmap[physmap_idx + 1] = physmap[physmap_idx] + extmem * 1024;
2192
2193 physmap_done:
2194         /*
2195          * Now, physmap contains a map of physical memory.
2196          */
2197
2198 #ifdef SMP
2199         /* make hole for AP bootstrap code */
2200         physmap[1] = mp_bootaddress(physmap[1]);
2201 #endif
2202
2203         /*
2204          * Maxmem isn't the "maximum memory", it's one larger than the
2205          * highest page of the physical address space.  It should be
2206          * called something like "Maxphyspage".  We may adjust this 
2207          * based on ``hw.physmem'' and the results of the memory test.
2208          */
2209         Maxmem = atop(physmap[physmap_idx + 1]);
2210
2211 #ifdef MAXMEM
2212         Maxmem = MAXMEM / 4;
2213 #endif
2214
2215         if (TUNABLE_QUAD_FETCH("hw.physmem", &physmem_tunable))
2216                 Maxmem = atop(physmem_tunable);
2217
2218         /*
2219          * If we have an SMAP, don't allow MAXMEM or hw.physmem to extend
2220          * the amount of memory in the system.
2221          */
2222         if (has_smap && Maxmem > atop(physmap[physmap_idx + 1]))
2223                 Maxmem = atop(physmap[physmap_idx + 1]);
2224
2225         /*
2226          * By default enable the memory test on real hardware, and disable
2227          * it if we appear to be running in a VM.  This avoids touching all
2228          * pages unnecessarily, which doesn't matter on real hardware but is
2229          * bad for shared VM hosts.  Use a general name so that
2230          * one could eventually do more with the code than just disable it.
2231          */
2232         memtest = (vm_guest > VM_GUEST_NO) ? 0 : 1;
2233         TUNABLE_ULONG_FETCH("hw.memtest.tests", &memtest);
2234
2235         if (atop(physmap[physmap_idx + 1]) != Maxmem &&
2236             (boothowto & RB_VERBOSE))
2237                 printf("Physical memory use set to %ldK\n", Maxmem * 4);
2238
2239         /*
2240          * If Maxmem has been increased beyond what the system has detected,
2241          * extend the last memory segment to the new limit.
2242          */ 
2243         if (atop(physmap[physmap_idx + 1]) < Maxmem)
2244                 physmap[physmap_idx + 1] = ptoa((vm_paddr_t)Maxmem);
2245
2246         /* call pmap initialization to make new kernel address space */
2247         pmap_bootstrap(first);
2248
2249         /*
2250          * Size up each available chunk of physical memory.
2251          */
2252         physmap[0] = PAGE_SIZE;         /* mask off page 0 */
2253         pa_indx = 0;
2254         da_indx = 1;
2255         phys_avail[pa_indx++] = physmap[0];
2256         phys_avail[pa_indx] = physmap[0];
2257         dump_avail[da_indx] = physmap[0];
2258         pte = CMAP3;
2259
2260         /*
2261          * Get dcons buffer address
2262          */
2263         if (getenv_quad("dcons.addr", &dcons_addr) == 0 ||
2264             getenv_quad("dcons.size", &dcons_size) == 0)
2265                 dcons_addr = 0;
2266
2267         /*
2268          * physmap is in bytes, so when converting to page boundaries,
2269          * round up the start address and round down the end address.
2270          */
2271         for (i = 0; i <= physmap_idx; i += 2) {
2272                 vm_paddr_t end;
2273
2274                 end = ptoa((vm_paddr_t)Maxmem);
2275                 if (physmap[i + 1] < end)
2276                         end = trunc_page(physmap[i + 1]);
2277                 for (pa = round_page(physmap[i]); pa < end; pa += PAGE_SIZE) {
2278                         int tmp, page_bad, full;
2279                         int *ptr = (int *)CADDR3;
2280
2281                         full = FALSE;
2282                         /*
2283                          * block out kernel memory as not available.
2284                          */
2285                         if (pa >= KERNLOAD && pa < first)
2286                                 goto do_dump_avail;
2287
2288                         /*
2289                          * block out dcons buffer
2290                          */
2291                         if (dcons_addr > 0
2292                             && pa >= trunc_page(dcons_addr)
2293                             && pa < dcons_addr + dcons_size)
2294                                 goto do_dump_avail;
2295
2296                         page_bad = FALSE;
2297                         if (memtest == 0)
2298                                 goto skip_memtest;
2299
2300                         /*
2301                          * map page into kernel: valid, read/write,non-cacheable
2302                          */
2303                         *pte = pa | PG_V | PG_RW | PG_N;
2304                         invltlb();
2305
2306                         tmp = *(int *)ptr;
2307                         /*
2308                          * Test for alternating 1's and 0's
2309                          */
2310                         *(volatile int *)ptr = 0xaaaaaaaa;
2311                         if (*(volatile int *)ptr != 0xaaaaaaaa)
2312                                 page_bad = TRUE;
2313                         /*
2314                          * Test for alternating 0's and 1's
2315                          */
2316                         *(volatile int *)ptr = 0x55555555;
2317                         if (*(volatile int *)ptr != 0x55555555)
2318                                 page_bad = TRUE;
2319                         /*
2320                          * Test for all 1's
2321                          */
2322                         *(volatile int *)ptr = 0xffffffff;
2323                         if (*(volatile int *)ptr != 0xffffffff)
2324                                 page_bad = TRUE;
2325                         /*
2326                          * Test for all 0's
2327                          */
2328                         *(volatile int *)ptr = 0x0;
2329                         if (*(volatile int *)ptr != 0x0)
2330                                 page_bad = TRUE;
2331                         /*
2332                          * Restore original value.
2333                          */
2334                         *(int *)ptr = tmp;
2335
2336 skip_memtest:
2337                         /*
2338                          * Adjust array of valid/good pages.
2339                          */
2340                         if (page_bad == TRUE)
2341                                 continue;
2342                         /*
2343                          * If this good page is a continuation of the
2344                          * previous set of good pages, then just increase
2345                          * the end pointer. Otherwise start a new chunk.
2346                          * Note that "end" points one higher than end,
2347                          * making the range >= start and < end.
2348                          * If we're also doing a speculative memory
2349                          * test and we at or past the end, bump up Maxmem
2350                          * so that we keep going. The first bad page
2351                          * will terminate the loop.
2352                          */
2353                         if (phys_avail[pa_indx] == pa) {
2354                                 phys_avail[pa_indx] += PAGE_SIZE;
2355                         } else {
2356                                 pa_indx++;
2357                                 if (pa_indx == PHYS_AVAIL_ARRAY_END) {
2358                                         printf(
2359                 "Too many holes in the physical address space, giving up\n");
2360                                         pa_indx--;
2361                                         full = TRUE;
2362                                         goto do_dump_avail;
2363                                 }
2364                                 phys_avail[pa_indx++] = pa;     /* start */
2365                                 phys_avail[pa_indx] = pa + PAGE_SIZE; /* end */
2366                         }
2367                         physmem++;
2368 do_dump_avail:
2369                         if (dump_avail[da_indx] == pa) {
2370                                 dump_avail[da_indx] += PAGE_SIZE;
2371                         } else {
2372                                 da_indx++;
2373                                 if (da_indx == DUMP_AVAIL_ARRAY_END) {
2374                                         da_indx--;
2375                                         goto do_next;
2376                                 }
2377                                 dump_avail[da_indx++] = pa;     /* start */
2378                                 dump_avail[da_indx] = pa + PAGE_SIZE; /* end */
2379                         }
2380 do_next:
2381                         if (full)
2382                                 break;
2383                 }
2384         }
2385         *pte = 0;
2386         invltlb();
2387         
2388         /*
2389          * XXX
2390          * The last chunk must contain at least one page plus the message
2391          * buffer to avoid complicating other code (message buffer address
2392          * calculation, etc.).
2393          */
2394         while (phys_avail[pa_indx - 1] + PAGE_SIZE +
2395             round_page(msgbufsize) >= phys_avail[pa_indx]) {
2396                 physmem -= atop(phys_avail[pa_indx] - phys_avail[pa_indx - 1]);
2397                 phys_avail[pa_indx--] = 0;
2398                 phys_avail[pa_indx--] = 0;
2399         }
2400
2401         Maxmem = atop(phys_avail[pa_indx]);
2402
2403         /* Trim off space for the message buffer. */
2404         phys_avail[pa_indx] -= round_page(msgbufsize);
2405
2406         /* Map the message buffer. */
2407         for (off = 0; off < round_page(msgbufsize); off += PAGE_SIZE)
2408                 pmap_kenter((vm_offset_t)msgbufp + off, phys_avail[pa_indx] +
2409                     off);
2410 }
2411 #endif /* PC98 */
2412
2413 register_t
2414 init386(first)
2415         int first;
2416 {
2417         struct gate_descriptor *gdp;
2418         int gsel_tss, metadata_missing, x, pa;
2419         struct pcpu *pc;
2420 #ifdef CPU_ENABLE_SSE
2421         struct xstate_hdr *xhdr;
2422 #endif
2423
2424         thread0.td_kstack = proc0kstack;
2425         thread0.td_kstack_pages = KSTACK_PAGES;
2426
2427         /*
2428          * This may be done better later if it gets more high level
2429          * components in it. If so just link td->td_proc here.
2430          */
2431         proc_linkup0(&proc0, &thread0);
2432
2433 #ifdef PC98
2434         /*
2435          * Initialize DMAC
2436          */
2437         pc98_init_dmac();
2438 #endif
2439
2440         metadata_missing = 0;
2441         if (bootinfo.bi_modulep) {
2442                 preload_metadata = (caddr_t)bootinfo.bi_modulep + KERNBASE;
2443                 preload_bootstrap_relocate(KERNBASE);
2444         } else {
2445                 metadata_missing = 1;
2446         }
2447         if (envmode == 1)
2448                 kern_envp = static_env;
2449         else if (bootinfo.bi_envp)
2450                 kern_envp = (caddr_t)bootinfo.bi_envp + KERNBASE;
2451
2452         /* Init basic tunables, hz etc */
2453         init_param1();
2454
2455         /*
2456          * Make gdt memory segments.  All segments cover the full 4GB
2457          * of address space and permissions are enforced at page level.
2458          */
2459         gdt_segs[GCODE_SEL].ssd_limit = atop(0 - 1);
2460         gdt_segs[GDATA_SEL].ssd_limit = atop(0 - 1);
2461         gdt_segs[GUCODE_SEL].ssd_limit = atop(0 - 1);
2462         gdt_segs[GUDATA_SEL].ssd_limit = atop(0 - 1);
2463         gdt_segs[GUFS_SEL].ssd_limit = atop(0 - 1);
2464         gdt_segs[GUGS_SEL].ssd_limit = atop(0 - 1);
2465
2466         pc = &__pcpu[0];
2467         gdt_segs[GPRIV_SEL].ssd_limit = atop(0 - 1);
2468         gdt_segs[GPRIV_SEL].ssd_base = (int) pc;
2469         gdt_segs[GPROC0_SEL].ssd_base = (int) &pc->pc_common_tss;
2470
2471         for (x = 0; x < NGDT; x++)
2472                 ssdtosd(&gdt_segs[x], &gdt[x].sd);
2473
2474         r_gdt.rd_limit = NGDT * sizeof(gdt[0]) - 1;
2475         r_gdt.rd_base =  (int) gdt;
2476         mtx_init(&dt_lock, "descriptor tables", NULL, MTX_SPIN);
2477         lgdt(&r_gdt);
2478
2479         pcpu_init(pc, 0, sizeof(struct pcpu));
2480         for (pa = first; pa < first + DPCPU_SIZE; pa += PAGE_SIZE)
2481                 pmap_kenter(pa + KERNBASE, pa);
2482         dpcpu_init((void *)(first + KERNBASE), 0);
2483         first += DPCPU_SIZE;
2484         PCPU_SET(prvspace, pc);
2485         PCPU_SET(curthread, &thread0);
2486
2487         /*
2488          * Initialize mutexes.
2489          *
2490          * icu_lock: in order to allow an interrupt to occur in a critical
2491          *           section, to set pcpu->ipending (etc...) properly, we
2492          *           must be able to get the icu lock, so it can't be
2493          *           under witness.
2494          */
2495         mutex_init();
2496         mtx_init(&icu_lock, "icu", NULL, MTX_SPIN | MTX_NOWITNESS | MTX_NOPROFILE);
2497
2498         /* make ldt memory segments */
2499         ldt_segs[LUCODE_SEL].ssd_limit = atop(0 - 1);
2500         ldt_segs[LUDATA_SEL].ssd_limit = atop(0 - 1);
2501         for (x = 0; x < sizeof ldt_segs / sizeof ldt_segs[0]; x++)
2502                 ssdtosd(&ldt_segs[x], &ldt[x].sd);
2503
2504         _default_ldt = GSEL(GLDT_SEL, SEL_KPL);
2505         lldt(_default_ldt);
2506         PCPU_SET(currentldt, _default_ldt);
2507
2508         /* exceptions */
2509         for (x = 0; x < NIDT; x++)
2510                 setidt(x, &IDTVEC(rsvd), SDT_SYS386TGT, SEL_KPL,
2511                     GSEL(GCODE_SEL, SEL_KPL));
2512         setidt(IDT_DE, &IDTVEC(div),  SDT_SYS386TGT, SEL_KPL,
2513             GSEL(GCODE_SEL, SEL_KPL));
2514         setidt(IDT_DB, &IDTVEC(dbg),  SDT_SYS386IGT, SEL_KPL,
2515             GSEL(GCODE_SEL, SEL_KPL));
2516         setidt(IDT_NMI, &IDTVEC(nmi),  SDT_SYS386IGT, SEL_KPL,
2517             GSEL(GCODE_SEL, SEL_KPL));
2518         setidt(IDT_BP, &IDTVEC(bpt),  SDT_SYS386IGT, SEL_UPL,
2519             GSEL(GCODE_SEL, SEL_KPL));
2520         setidt(IDT_OF, &IDTVEC(ofl),  SDT_SYS386TGT, SEL_UPL,
2521             GSEL(GCODE_SEL, SEL_KPL));
2522         setidt(IDT_BR, &IDTVEC(bnd),  SDT_SYS386TGT, SEL_KPL,
2523             GSEL(GCODE_SEL, SEL_KPL));
2524         setidt(IDT_UD, &IDTVEC(ill),  SDT_SYS386TGT, SEL_KPL,
2525             GSEL(GCODE_SEL, SEL_KPL));
2526         setidt(IDT_NM, &IDTVEC(dna),  SDT_SYS386TGT, SEL_KPL
2527             , GSEL(GCODE_SEL, SEL_KPL));
2528         setidt(IDT_DF, 0,  SDT_SYSTASKGT, SEL_KPL, GSEL(GPANIC_SEL, SEL_KPL));
2529         setidt(IDT_FPUGP, &IDTVEC(fpusegm),  SDT_SYS386TGT, SEL_KPL,
2530             GSEL(GCODE_SEL, SEL_KPL));
2531         setidt(IDT_TS, &IDTVEC(tss),  SDT_SYS386TGT, SEL_KPL,
2532             GSEL(GCODE_SEL, SEL_KPL));
2533         setidt(IDT_NP, &IDTVEC(missing),  SDT_SYS386TGT, SEL_KPL,
2534             GSEL(GCODE_SEL, SEL_KPL));
2535         setidt(IDT_SS, &IDTVEC(stk),  SDT_SYS386TGT, SEL_KPL,
2536             GSEL(GCODE_SEL, SEL_KPL));
2537         setidt(IDT_GP, &IDTVEC(prot),  SDT_SYS386TGT, SEL_KPL,
2538             GSEL(GCODE_SEL, SEL_KPL));
2539         setidt(IDT_PF, &IDTVEC(page),  SDT_SYS386IGT, SEL_KPL,
2540             GSEL(GCODE_SEL, SEL_KPL));
2541         setidt(IDT_MF, &IDTVEC(fpu),  SDT_SYS386TGT, SEL_KPL,
2542             GSEL(GCODE_SEL, SEL_KPL));
2543         setidt(IDT_AC, &IDTVEC(align), SDT_SYS386TGT, SEL_KPL,
2544             GSEL(GCODE_SEL, SEL_KPL));
2545         setidt(IDT_MC, &IDTVEC(mchk),  SDT_SYS386TGT, SEL_KPL,
2546             GSEL(GCODE_SEL, SEL_KPL));
2547         setidt(IDT_XF, &IDTVEC(xmm), SDT_SYS386TGT, SEL_KPL,
2548             GSEL(GCODE_SEL, SEL_KPL));
2549         setidt(IDT_SYSCALL, &IDTVEC(int0x80_syscall), SDT_SYS386TGT, SEL_UPL,
2550             GSEL(GCODE_SEL, SEL_KPL));
2551 #ifdef KDTRACE_HOOKS
2552         setidt(IDT_DTRACE_RET, &IDTVEC(dtrace_ret), SDT_SYS386TGT, SEL_UPL,
2553             GSEL(GCODE_SEL, SEL_KPL));
2554 #endif
2555 #ifdef XENHVM
2556         setidt(IDT_EVTCHN, &IDTVEC(xen_intr_upcall), SDT_SYS386IGT, SEL_UPL,
2557             GSEL(GCODE_SEL, SEL_KPL));
2558 #endif
2559
2560         r_idt.rd_limit = sizeof(idt0) - 1;
2561         r_idt.rd_base = (int) idt;
2562         lidt(&r_idt);
2563
2564 #ifdef XBOX
2565         /*
2566          * The following code queries the PCI ID of 0:0:0. For the XBOX,
2567          * This should be 0x10de / 0x02a5.
2568          *
2569          * This is exactly what Linux does.
2570          */
2571         outl(0xcf8, 0x80000000);
2572         if (inl(0xcfc) == 0x02a510de) {
2573                 arch_i386_is_xbox = 1;
2574                 pic16l_setled(XBOX_LED_GREEN);
2575
2576                 /*
2577                  * We are an XBOX, but we may have either 64MB or 128MB of
2578                  * memory. The PCI host bridge should be programmed for this,
2579                  * so we just query it. 
2580                  */
2581                 outl(0xcf8, 0x80000084);
2582                 arch_i386_xbox_memsize = (inl(0xcfc) == 0x7FFFFFF) ? 128 : 64;
2583         }
2584 #endif /* XBOX */
2585
2586         /*
2587          * Initialize the clock before the console so that console
2588          * initialization can use DELAY().
2589          */
2590         clock_init();
2591
2592         /*
2593          * Initialize the console before we print anything out.
2594          */
2595         cninit();
2596
2597         if (metadata_missing)
2598                 printf("WARNING: loader(8) metadata is missing!\n");
2599
2600 #ifdef DEV_ISA
2601 #ifdef DEV_ATPIC
2602 #ifndef PC98
2603         elcr_probe();
2604 #endif
2605         atpic_startup();
2606 #else
2607         /* Reset and mask the atpics and leave them shut down. */
2608         atpic_reset();
2609
2610         /*
2611          * Point the ICU spurious interrupt vectors at the APIC spurious
2612          * interrupt handler.
2613          */
2614         setidt(IDT_IO_INTS + 7, IDTVEC(spuriousint), SDT_SYS386IGT, SEL_KPL,
2615             GSEL(GCODE_SEL, SEL_KPL));
2616         setidt(IDT_IO_INTS + 15, IDTVEC(spuriousint), SDT_SYS386IGT, SEL_KPL,
2617             GSEL(GCODE_SEL, SEL_KPL));
2618 #endif
2619 #endif
2620
2621 #ifdef DDB
2622         db_fetch_ksymtab(bootinfo.bi_symtab, bootinfo.bi_esymtab);
2623 #endif
2624
2625         kdb_init();
2626
2627 #ifdef KDB
2628         if (boothowto & RB_KDB)
2629                 kdb_enter(KDB_WHY_BOOTFLAGS, "Boot flags requested debugger");
2630 #endif
2631
2632         finishidentcpu();       /* Final stage of CPU initialization */
2633         setidt(IDT_UD, &IDTVEC(ill),  SDT_SYS386TGT, SEL_KPL,
2634             GSEL(GCODE_SEL, SEL_KPL));
2635         setidt(IDT_GP, &IDTVEC(prot),  SDT_SYS386TGT, SEL_KPL,
2636             GSEL(GCODE_SEL, SEL_KPL));
2637         initializecpu();        /* Initialize CPU registers */
2638         initializecpucache();
2639
2640         /* pointer to selector slot for %fs/%gs */
2641         PCPU_SET(fsgs_gdt, &gdt[GUFS_SEL].sd);
2642
2643         dblfault_tss.tss_esp = dblfault_tss.tss_esp0 = dblfault_tss.tss_esp1 =
2644             dblfault_tss.tss_esp2 = (int)&dblfault_stack[sizeof(dblfault_stack)];
2645         dblfault_tss.tss_ss = dblfault_tss.tss_ss0 = dblfault_tss.tss_ss1 =
2646             dblfault_tss.tss_ss2 = GSEL(GDATA_SEL, SEL_KPL);
2647 #if defined(PAE) || defined(PAE_TABLES)
2648         dblfault_tss.tss_cr3 = (int)IdlePDPT;
2649 #else
2650         dblfault_tss.tss_cr3 = (int)IdlePTD;
2651 #endif
2652         dblfault_tss.tss_eip = (int)dblfault_handler;
2653         dblfault_tss.tss_eflags = PSL_KERNEL;
2654         dblfault_tss.tss_ds = dblfault_tss.tss_es =
2655             dblfault_tss.tss_gs = GSEL(GDATA_SEL, SEL_KPL);
2656         dblfault_tss.tss_fs = GSEL(GPRIV_SEL, SEL_KPL);
2657         dblfault_tss.tss_cs = GSEL(GCODE_SEL, SEL_KPL);
2658         dblfault_tss.tss_ldt = GSEL(GLDT_SEL, SEL_KPL);
2659
2660         vm86_initialize();
2661         getmemsize(first);
2662         init_param2(physmem);
2663
2664         /* now running on new page tables, configured,and u/iom is accessible */
2665
2666         msgbufinit(msgbufp, msgbufsize);
2667 #ifdef DEV_NPX
2668         npxinit(true);
2669 #endif
2670         /*
2671          * Set up thread0 pcb after npxinit calculated pcb + fpu save
2672          * area size.  Zero out the extended state header in fpu save
2673          * area.
2674          */
2675         thread0.td_pcb = get_pcb_td(&thread0);
2676         bzero(get_pcb_user_save_td(&thread0), cpu_max_ext_state_size);
2677 #ifdef CPU_ENABLE_SSE
2678         if (use_xsave) {
2679                 xhdr = (struct xstate_hdr *)(get_pcb_user_save_td(&thread0) +
2680                     1);
2681                 xhdr->xstate_bv = xsave_mask;
2682         }
2683 #endif
2684         PCPU_SET(curpcb, thread0.td_pcb);
2685         /* make an initial tss so cpu can get interrupt stack on syscall! */
2686         /* Note: -16 is so we can grow the trapframe if we came from vm86 */
2687         PCPU_SET(common_tss.tss_esp0, (vm_offset_t)thread0.td_pcb - 16);
2688         PCPU_SET(common_tss.tss_ss0, GSEL(GDATA_SEL, SEL_KPL));
2689         gsel_tss = GSEL(GPROC0_SEL, SEL_KPL);
2690         PCPU_SET(tss_gdt, &gdt[GPROC0_SEL].sd);
2691         PCPU_SET(common_tssd, *PCPU_GET(tss_gdt));
2692         PCPU_SET(common_tss.tss_ioopt, (sizeof (struct i386tss)) << 16);
2693         ltr(gsel_tss);
2694
2695         /* make a call gate to reenter kernel with */
2696         gdp = &ldt[LSYS5CALLS_SEL].gd;
2697
2698         x = (int) &IDTVEC(lcall_syscall);
2699         gdp->gd_looffset = x;
2700         gdp->gd_selector = GSEL(GCODE_SEL,SEL_KPL);
2701         gdp->gd_stkcpy = 1;
2702         gdp->gd_type = SDT_SYS386CGT;
2703         gdp->gd_dpl = SEL_UPL;
2704         gdp->gd_p = 1;
2705         gdp->gd_hioffset = x >> 16;
2706
2707         /* XXX does this work? */
2708         /* XXX yes! */
2709         ldt[LBSDICALLS_SEL] = ldt[LSYS5CALLS_SEL];
2710         ldt[LSOL26CALLS_SEL] = ldt[LSYS5CALLS_SEL];
2711
2712         /* transfer to user mode */
2713
2714         _ucodesel = GSEL(GUCODE_SEL, SEL_UPL);
2715         _udatasel = GSEL(GUDATA_SEL, SEL_UPL);
2716
2717         /* setup proc 0's pcb */
2718         thread0.td_pcb->pcb_flags = 0;
2719 #if defined(PAE) || defined(PAE_TABLES)
2720         thread0.td_pcb->pcb_cr3 = (int)IdlePDPT;
2721 #else
2722         thread0.td_pcb->pcb_cr3 = (int)IdlePTD;
2723 #endif
2724         thread0.td_pcb->pcb_ext = 0;
2725         thread0.td_frame = &proc0_tf;
2726
2727         cpu_probe_amdc1e();
2728
2729 #ifdef FDT
2730         x86_init_fdt();
2731 #endif
2732
2733         /* Location of kernel stack for locore */
2734         return ((register_t)thread0.td_pcb);
2735 }
2736
2737 void
2738 cpu_pcpu_init(struct pcpu *pcpu, int cpuid, size_t size)
2739 {
2740
2741         pcpu->pc_acpi_id = 0xffffffff;
2742 }
2743
2744 #ifndef PC98
2745 static int
2746 smap_sysctl_handler(SYSCTL_HANDLER_ARGS)
2747 {
2748         struct bios_smap *smapbase;
2749         struct bios_smap_xattr smap;
2750         caddr_t kmdp;
2751         uint32_t *smapattr;
2752         int count, error, i;
2753
2754         /* Retrieve the system memory map from the loader. */
2755         kmdp = preload_search_by_type("elf kernel");
2756         if (kmdp == NULL)
2757                 kmdp = preload_search_by_type("elf32 kernel");
2758         if (kmdp == NULL)
2759                 return (0);
2760         smapbase = (struct bios_smap *)preload_search_info(kmdp,
2761             MODINFO_METADATA | MODINFOMD_SMAP);
2762         if (smapbase == NULL)
2763                 return (0);
2764         smapattr = (uint32_t *)preload_search_info(kmdp,
2765             MODINFO_METADATA | MODINFOMD_SMAP_XATTR);
2766         count = *((u_int32_t *)smapbase - 1) / sizeof(*smapbase);
2767         error = 0;
2768         for (i = 0; i < count; i++) {
2769                 smap.base = smapbase[i].base;
2770                 smap.length = smapbase[i].length;
2771                 smap.type = smapbase[i].type;
2772                 if (smapattr != NULL)
2773                         smap.xattr = smapattr[i];
2774                 else
2775                         smap.xattr = 0;
2776                 error = SYSCTL_OUT(req, &smap, sizeof(smap));
2777         }
2778         return (error);
2779 }
2780 SYSCTL_PROC(_machdep, OID_AUTO, smap, CTLTYPE_OPAQUE|CTLFLAG_RD, NULL, 0,
2781     smap_sysctl_handler, "S,bios_smap_xattr", "Raw BIOS SMAP data");
2782 #endif /* !PC98 */
2783
2784 void
2785 spinlock_enter(void)
2786 {
2787         struct thread *td;
2788         register_t flags;
2789
2790         td = curthread;
2791         if (td->td_md.md_spinlock_count == 0) {
2792                 flags = intr_disable();
2793                 td->td_md.md_spinlock_count = 1;
2794                 td->td_md.md_saved_flags = flags;
2795         } else
2796                 td->td_md.md_spinlock_count++;
2797         critical_enter();
2798 }
2799
2800 void
2801 spinlock_exit(void)
2802 {
2803         struct thread *td;
2804         register_t flags;
2805
2806         td = curthread;
2807         critical_exit();
2808         flags = td->td_md.md_saved_flags;
2809         td->td_md.md_spinlock_count--;
2810         if (td->td_md.md_spinlock_count == 0)
2811                 intr_restore(flags);
2812 }
2813
2814 #if defined(I586_CPU) && !defined(NO_F00F_HACK)
2815 static void f00f_hack(void *unused);
2816 SYSINIT(f00f_hack, SI_SUB_INTRINSIC, SI_ORDER_FIRST, f00f_hack, NULL);
2817
2818 static void
2819 f00f_hack(void *unused)
2820 {
2821         struct gate_descriptor *new_idt;
2822         vm_offset_t tmp;
2823
2824         if (!has_f00f_bug)
2825                 return;
2826
2827         GIANT_REQUIRED;
2828
2829         printf("Intel Pentium detected, installing workaround for F00F bug\n");
2830
2831         tmp = kmem_malloc(kernel_arena, PAGE_SIZE * 2, M_WAITOK | M_ZERO);
2832         if (tmp == 0)
2833                 panic("kmem_malloc returned 0");
2834
2835         /* Put the problematic entry (#6) at the end of the lower page. */
2836         new_idt = (struct gate_descriptor*)
2837             (tmp + PAGE_SIZE - 7 * sizeof(struct gate_descriptor));
2838         bcopy(idt, new_idt, sizeof(idt0));
2839         r_idt.rd_base = (u_int)new_idt;
2840         lidt(&r_idt);
2841         idt = new_idt;
2842         pmap_protect(kernel_pmap, tmp, tmp + PAGE_SIZE, VM_PROT_READ);
2843 }
2844 #endif /* defined(I586_CPU) && !NO_F00F_HACK */
2845
2846 /*
2847  * Construct a PCB from a trapframe. This is called from kdb_trap() where
2848  * we want to start a backtrace from the function that caused us to enter
2849  * the debugger. We have the context in the trapframe, but base the trace
2850  * on the PCB. The PCB doesn't have to be perfect, as long as it contains
2851  * enough for a backtrace.
2852  */
2853 void
2854 makectx(struct trapframe *tf, struct pcb *pcb)
2855 {
2856
2857         pcb->pcb_edi = tf->tf_edi;
2858         pcb->pcb_esi = tf->tf_esi;
2859         pcb->pcb_ebp = tf->tf_ebp;
2860         pcb->pcb_ebx = tf->tf_ebx;
2861         pcb->pcb_eip = tf->tf_eip;
2862         pcb->pcb_esp = (ISPL(tf->tf_cs)) ? tf->tf_esp : (int)(tf + 1) - 8;
2863         pcb->pcb_gs = rgs();
2864 }
2865
2866 int
2867 ptrace_set_pc(struct thread *td, u_long addr)
2868 {
2869
2870         td->td_frame->tf_eip = addr;
2871         return (0);
2872 }
2873
2874 int
2875 ptrace_single_step(struct thread *td)
2876 {
2877         td->td_frame->tf_eflags |= PSL_T;
2878         return (0);
2879 }
2880
2881 int
2882 ptrace_clear_single_step(struct thread *td)
2883 {
2884         td->td_frame->tf_eflags &= ~PSL_T;
2885         return (0);
2886 }
2887
2888 int
2889 fill_regs(struct thread *td, struct reg *regs)
2890 {
2891         struct pcb *pcb;
2892         struct trapframe *tp;
2893
2894         tp = td->td_frame;
2895         pcb = td->td_pcb;
2896         regs->r_gs = pcb->pcb_gs;
2897         return (fill_frame_regs(tp, regs));
2898 }
2899
2900 int
2901 fill_frame_regs(struct trapframe *tp, struct reg *regs)
2902 {
2903         regs->r_fs = tp->tf_fs;
2904         regs->r_es = tp->tf_es;
2905         regs->r_ds = tp->tf_ds;
2906         regs->r_edi = tp->tf_edi;
2907         regs->r_esi = tp->tf_esi;
2908         regs->r_ebp = tp->tf_ebp;
2909         regs->r_ebx = tp->tf_ebx;
2910         regs->r_edx = tp->tf_edx;
2911         regs->r_ecx = tp->tf_ecx;
2912         regs->r_eax = tp->tf_eax;
2913         regs->r_eip = tp->tf_eip;
2914         regs->r_cs = tp->tf_cs;
2915         regs->r_eflags = tp->tf_eflags;
2916         regs->r_esp = tp->tf_esp;
2917         regs->r_ss = tp->tf_ss;
2918         return (0);
2919 }
2920
2921 int
2922 set_regs(struct thread *td, struct reg *regs)
2923 {
2924         struct pcb *pcb;
2925         struct trapframe *tp;
2926
2927         tp = td->td_frame;
2928         if (!EFL_SECURE(regs->r_eflags, tp->tf_eflags) ||
2929             !CS_SECURE(regs->r_cs))
2930                 return (EINVAL);
2931         pcb = td->td_pcb;
2932         tp->tf_fs = regs->r_fs;
2933         tp->tf_es = regs->r_es;
2934         tp->tf_ds = regs->r_ds;
2935         tp->tf_edi = regs->r_edi;
2936         tp->tf_esi = regs->r_esi;
2937         tp->tf_ebp = regs->r_ebp;
2938         tp->tf_ebx = regs->r_ebx;
2939         tp->tf_edx = regs->r_edx;
2940         tp->tf_ecx = regs->r_ecx;
2941         tp->tf_eax = regs->r_eax;
2942         tp->tf_eip = regs->r_eip;
2943         tp->tf_cs = regs->r_cs;
2944         tp->tf_eflags = regs->r_eflags;
2945         tp->tf_esp = regs->r_esp;
2946         tp->tf_ss = regs->r_ss;
2947         pcb->pcb_gs = regs->r_gs;
2948         return (0);
2949 }
2950
2951 int
2952 fill_fpregs(struct thread *td, struct fpreg *fpregs)
2953 {
2954
2955         KASSERT(td == curthread || TD_IS_SUSPENDED(td) ||
2956             P_SHOULDSTOP(td->td_proc),
2957             ("not suspended thread %p", td));
2958 #ifdef DEV_NPX
2959         npxgetregs(td);
2960 #else
2961         bzero(fpregs, sizeof(*fpregs));
2962 #endif
2963 #ifdef CPU_ENABLE_SSE
2964         if (cpu_fxsr)
2965                 npx_fill_fpregs_xmm(&get_pcb_user_save_td(td)->sv_xmm,
2966                     (struct save87 *)fpregs);
2967         else
2968 #endif /* CPU_ENABLE_SSE */
2969                 bcopy(&get_pcb_user_save_td(td)->sv_87, fpregs,
2970                     sizeof(*fpregs));
2971         return (0);
2972 }
2973
2974 int
2975 set_fpregs(struct thread *td, struct fpreg *fpregs)
2976 {
2977
2978 #ifdef CPU_ENABLE_SSE
2979         if (cpu_fxsr)
2980                 npx_set_fpregs_xmm((struct save87 *)fpregs,
2981                     &get_pcb_user_save_td(td)->sv_xmm);
2982         else
2983 #endif /* CPU_ENABLE_SSE */
2984                 bcopy(fpregs, &get_pcb_user_save_td(td)->sv_87,
2985                     sizeof(*fpregs));
2986 #ifdef DEV_NPX
2987         npxuserinited(td);
2988 #endif
2989         return (0);
2990 }
2991
2992 /*
2993  * Get machine context.
2994  */
2995 int
2996 get_mcontext(struct thread *td, mcontext_t *mcp, int flags)
2997 {
2998         struct trapframe *tp;
2999         struct segment_descriptor *sdp;
3000
3001         tp = td->td_frame;
3002
3003         PROC_LOCK(curthread->td_proc);
3004         mcp->mc_onstack = sigonstack(tp->tf_esp);
3005         PROC_UNLOCK(curthread->td_proc);
3006         mcp->mc_gs = td->td_pcb->pcb_gs;
3007         mcp->mc_fs = tp->tf_fs;
3008         mcp->mc_es = tp->tf_es;
3009         mcp->mc_ds = tp->tf_ds;
3010         mcp->mc_edi = tp->tf_edi;
3011         mcp->mc_esi = tp->tf_esi;
3012         mcp->mc_ebp = tp->tf_ebp;
3013         mcp->mc_isp = tp->tf_isp;
3014         mcp->mc_eflags = tp->tf_eflags;
3015         if (flags & GET_MC_CLEAR_RET) {
3016                 mcp->mc_eax = 0;
3017                 mcp->mc_edx = 0;
3018                 mcp->mc_eflags &= ~PSL_C;
3019         } else {
3020                 mcp->mc_eax = tp->tf_eax;
3021                 mcp->mc_edx = tp->tf_edx;
3022         }
3023         mcp->mc_ebx = tp->tf_ebx;
3024         mcp->mc_ecx = tp->tf_ecx;
3025         mcp->mc_eip = tp->tf_eip;
3026         mcp->mc_cs = tp->tf_cs;
3027         mcp->mc_esp = tp->tf_esp;
3028         mcp->mc_ss = tp->tf_ss;
3029         mcp->mc_len = sizeof(*mcp);
3030         get_fpcontext(td, mcp, NULL, 0);
3031         sdp = &td->td_pcb->pcb_fsd;
3032         mcp->mc_fsbase = sdp->sd_hibase << 24 | sdp->sd_lobase;
3033         sdp = &td->td_pcb->pcb_gsd;
3034         mcp->mc_gsbase = sdp->sd_hibase << 24 | sdp->sd_lobase;
3035         mcp->mc_flags = 0;
3036         mcp->mc_xfpustate = 0;
3037         mcp->mc_xfpustate_len = 0;
3038         bzero(mcp->mc_spare2, sizeof(mcp->mc_spare2));
3039         return (0);
3040 }
3041
3042 /*
3043  * Set machine context.
3044  *
3045  * However, we don't set any but the user modifiable flags, and we won't
3046  * touch the cs selector.
3047  */
3048 int
3049 set_mcontext(struct thread *td, mcontext_t *mcp)
3050 {
3051         struct trapframe *tp;
3052         char *xfpustate;
3053         int eflags, ret;
3054
3055         tp = td->td_frame;
3056         if (mcp->mc_len != sizeof(*mcp) ||
3057             (mcp->mc_flags & ~_MC_FLAG_MASK) != 0)
3058                 return (EINVAL);
3059         eflags = (mcp->mc_eflags & PSL_USERCHANGE) |
3060             (tp->tf_eflags & ~PSL_USERCHANGE);
3061         if (mcp->mc_flags & _MC_HASFPXSTATE) {
3062                 if (mcp->mc_xfpustate_len > cpu_max_ext_state_size -
3063                     sizeof(union savefpu))
3064                         return (EINVAL);
3065                 xfpustate = __builtin_alloca(mcp->mc_xfpustate_len);
3066                 ret = copyin((void *)mcp->mc_xfpustate, xfpustate,
3067                     mcp->mc_xfpustate_len);
3068                 if (ret != 0)
3069                         return (ret);
3070         } else
3071                 xfpustate = NULL;
3072         ret = set_fpcontext(td, mcp, xfpustate, mcp->mc_xfpustate_len);
3073         if (ret != 0)
3074                 return (ret);
3075         tp->tf_fs = mcp->mc_fs;
3076         tp->tf_es = mcp->mc_es;
3077         tp->tf_ds = mcp->mc_ds;
3078         tp->tf_edi = mcp->mc_edi;
3079         tp->tf_esi = mcp->mc_esi;
3080         tp->tf_ebp = mcp->mc_ebp;
3081         tp->tf_ebx = mcp->mc_ebx;
3082         tp->tf_edx = mcp->mc_edx;
3083         tp->tf_ecx = mcp->mc_ecx;
3084         tp->tf_eax = mcp->mc_eax;
3085         tp->tf_eip = mcp->mc_eip;
3086         tp->tf_eflags = eflags;
3087         tp->tf_esp = mcp->mc_esp;
3088         tp->tf_ss = mcp->mc_ss;
3089         td->td_pcb->pcb_gs = mcp->mc_gs;
3090         return (0);
3091 }
3092
3093 static void
3094 get_fpcontext(struct thread *td, mcontext_t *mcp, char *xfpusave,
3095     size_t xfpusave_len)
3096 {
3097 #ifdef CPU_ENABLE_SSE
3098         size_t max_len, len;
3099 #endif
3100
3101 #ifndef DEV_NPX
3102         mcp->mc_fpformat = _MC_FPFMT_NODEV;
3103         mcp->mc_ownedfp = _MC_FPOWNED_NONE;
3104         bzero(mcp->mc_fpstate, sizeof(mcp->mc_fpstate));
3105 #else
3106         mcp->mc_ownedfp = npxgetregs(td);
3107         bcopy(get_pcb_user_save_td(td), &mcp->mc_fpstate[0],
3108             sizeof(mcp->mc_fpstate));
3109         mcp->mc_fpformat = npxformat();
3110 #ifdef CPU_ENABLE_SSE
3111         if (!use_xsave || xfpusave_len == 0)
3112                 return;
3113         max_len = cpu_max_ext_state_size - sizeof(union savefpu);
3114         len = xfpusave_len;
3115         if (len > max_len) {
3116                 len = max_len;
3117                 bzero(xfpusave + max_len, len - max_len);
3118         }
3119         mcp->mc_flags |= _MC_HASFPXSTATE;
3120         mcp->mc_xfpustate_len = len;
3121         bcopy(get_pcb_user_save_td(td) + 1, xfpusave, len);
3122 #endif
3123 #endif
3124 }
3125
3126 static int
3127 set_fpcontext(struct thread *td, mcontext_t *mcp, char *xfpustate,
3128     size_t xfpustate_len)
3129 {
3130         union savefpu *fpstate;
3131         int error;
3132
3133         if (mcp->mc_fpformat == _MC_FPFMT_NODEV)
3134                 return (0);
3135         else if (mcp->mc_fpformat != _MC_FPFMT_387 &&
3136             mcp->mc_fpformat != _MC_FPFMT_XMM)
3137                 return (EINVAL);
3138         else if (mcp->mc_ownedfp == _MC_FPOWNED_NONE) {
3139                 /* We don't care what state is left in the FPU or PCB. */
3140                 fpstate_drop(td);
3141                 error = 0;
3142         } else if (mcp->mc_ownedfp == _MC_FPOWNED_FPU ||
3143             mcp->mc_ownedfp == _MC_FPOWNED_PCB) {
3144 #ifdef DEV_NPX
3145                 fpstate = (union savefpu *)&mcp->mc_fpstate;
3146 #ifdef CPU_ENABLE_SSE
3147                 if (cpu_fxsr)
3148                         fpstate->sv_xmm.sv_env.en_mxcsr &= cpu_mxcsr_mask;
3149 #endif
3150                 error = npxsetregs(td, fpstate, xfpustate, xfpustate_len);
3151 #else
3152                 error = EINVAL;
3153 #endif
3154         } else
3155                 return (EINVAL);
3156         return (error);
3157 }
3158
3159 static void
3160 fpstate_drop(struct thread *td)
3161 {
3162
3163         KASSERT(PCB_USER_FPU(td->td_pcb), ("fpstate_drop: kernel-owned fpu"));
3164         critical_enter();
3165 #ifdef DEV_NPX
3166         if (PCPU_GET(fpcurthread) == td)
3167                 npxdrop();
3168 #endif
3169         /*
3170          * XXX force a full drop of the npx.  The above only drops it if we
3171          * owned it.  npxgetregs() has the same bug in the !cpu_fxsr case.
3172          *
3173          * XXX I don't much like npxgetregs()'s semantics of doing a full
3174          * drop.  Dropping only to the pcb matches fnsave's behaviour.
3175          * We only need to drop to !PCB_INITDONE in sendsig().  But
3176          * sendsig() is the only caller of npxgetregs()... perhaps we just
3177          * have too many layers.
3178          */
3179         curthread->td_pcb->pcb_flags &= ~(PCB_NPXINITDONE |
3180             PCB_NPXUSERINITDONE);
3181         critical_exit();
3182 }
3183
3184 int
3185 fill_dbregs(struct thread *td, struct dbreg *dbregs)
3186 {
3187         struct pcb *pcb;
3188
3189         if (td == NULL) {
3190                 dbregs->dr[0] = rdr0();
3191                 dbregs->dr[1] = rdr1();
3192                 dbregs->dr[2] = rdr2();
3193                 dbregs->dr[3] = rdr3();
3194                 dbregs->dr[4] = rdr4();
3195                 dbregs->dr[5] = rdr5();
3196                 dbregs->dr[6] = rdr6();
3197                 dbregs->dr[7] = rdr7();
3198         } else {
3199                 pcb = td->td_pcb;
3200                 dbregs->dr[0] = pcb->pcb_dr0;
3201                 dbregs->dr[1] = pcb->pcb_dr1;
3202                 dbregs->dr[2] = pcb->pcb_dr2;
3203                 dbregs->dr[3] = pcb->pcb_dr3;
3204                 dbregs->dr[4] = 0;
3205                 dbregs->dr[5] = 0;
3206                 dbregs->dr[6] = pcb->pcb_dr6;
3207                 dbregs->dr[7] = pcb->pcb_dr7;
3208         }
3209         return (0);
3210 }
3211
3212 int
3213 set_dbregs(struct thread *td, struct dbreg *dbregs)
3214 {
3215         struct pcb *pcb;
3216         int i;
3217
3218         if (td == NULL) {
3219                 load_dr0(dbregs->dr[0]);
3220                 load_dr1(dbregs->dr[1]);
3221                 load_dr2(dbregs->dr[2]);
3222                 load_dr3(dbregs->dr[3]);
3223                 load_dr4(dbregs->dr[4]);
3224                 load_dr5(dbregs->dr[5]);
3225                 load_dr6(dbregs->dr[6]);
3226                 load_dr7(dbregs->dr[7]);
3227         } else {
3228                 /*
3229                  * Don't let an illegal value for dr7 get set.  Specifically,
3230                  * check for undefined settings.  Setting these bit patterns
3231                  * result in undefined behaviour and can lead to an unexpected
3232                  * TRCTRAP.
3233                  */
3234                 for (i = 0; i < 4; i++) {
3235                         if (DBREG_DR7_ACCESS(dbregs->dr[7], i) == 0x02)
3236                                 return (EINVAL);
3237                         if (DBREG_DR7_LEN(dbregs->dr[7], i) == 0x02)
3238                                 return (EINVAL);
3239                 }
3240                 
3241                 pcb = td->td_pcb;
3242                 
3243                 /*
3244                  * Don't let a process set a breakpoint that is not within the
3245                  * process's address space.  If a process could do this, it
3246                  * could halt the system by setting a breakpoint in the kernel
3247                  * (if ddb was enabled).  Thus, we need to check to make sure
3248                  * that no breakpoints are being enabled for addresses outside
3249                  * process's address space.
3250                  *
3251                  * XXX - what about when the watched area of the user's
3252                  * address space is written into from within the kernel
3253                  * ... wouldn't that still cause a breakpoint to be generated
3254                  * from within kernel mode?
3255                  */
3256
3257                 if (DBREG_DR7_ENABLED(dbregs->dr[7], 0)) {
3258                         /* dr0 is enabled */
3259                         if (dbregs->dr[0] >= VM_MAXUSER_ADDRESS)
3260                                 return (EINVAL);
3261                 }
3262                         
3263                 if (DBREG_DR7_ENABLED(dbregs->dr[7], 1)) {
3264                         /* dr1 is enabled */
3265                         if (dbregs->dr[1] >= VM_MAXUSER_ADDRESS)
3266                                 return (EINVAL);
3267                 }
3268                         
3269                 if (DBREG_DR7_ENABLED(dbregs->dr[7], 2)) {
3270                         /* dr2 is enabled */
3271                         if (dbregs->dr[2] >= VM_MAXUSER_ADDRESS)
3272                                 return (EINVAL);
3273                 }
3274                         
3275                 if (DBREG_DR7_ENABLED(dbregs->dr[7], 3)) {
3276                         /* dr3 is enabled */
3277                         if (dbregs->dr[3] >= VM_MAXUSER_ADDRESS)
3278                                 return (EINVAL);
3279                 }
3280
3281                 pcb->pcb_dr0 = dbregs->dr[0];
3282                 pcb->pcb_dr1 = dbregs->dr[1];
3283                 pcb->pcb_dr2 = dbregs->dr[2];
3284                 pcb->pcb_dr3 = dbregs->dr[3];
3285                 pcb->pcb_dr6 = dbregs->dr[6];
3286                 pcb->pcb_dr7 = dbregs->dr[7];
3287
3288                 pcb->pcb_flags |= PCB_DBREGS;
3289         }
3290
3291         return (0);
3292 }
3293
3294 /*
3295  * Return > 0 if a hardware breakpoint has been hit, and the
3296  * breakpoint was in user space.  Return 0, otherwise.
3297  */
3298 int
3299 user_dbreg_trap(void)
3300 {
3301         u_int32_t dr7, dr6; /* debug registers dr6 and dr7 */
3302         u_int32_t bp;       /* breakpoint bits extracted from dr6 */
3303         int nbp;            /* number of breakpoints that triggered */
3304         caddr_t addr[4];    /* breakpoint addresses */
3305         int i;
3306         
3307         dr7 = rdr7();
3308         if ((dr7 & 0x000000ff) == 0) {
3309                 /*
3310                  * all GE and LE bits in the dr7 register are zero,
3311                  * thus the trap couldn't have been caused by the
3312                  * hardware debug registers
3313                  */
3314                 return 0;
3315         }
3316
3317         nbp = 0;
3318         dr6 = rdr6();
3319         bp = dr6 & 0x0000000f;
3320
3321         if (!bp) {
3322                 /*
3323                  * None of the breakpoint bits are set meaning this
3324                  * trap was not caused by any of the debug registers
3325                  */
3326                 return 0;
3327         }
3328
3329         /*
3330          * at least one of the breakpoints were hit, check to see
3331          * which ones and if any of them are user space addresses
3332          */
3333
3334         if (bp & 0x01) {
3335                 addr[nbp++] = (caddr_t)rdr0();
3336         }
3337         if (bp & 0x02) {
3338                 addr[nbp++] = (caddr_t)rdr1();
3339         }
3340         if (bp & 0x04) {
3341                 addr[nbp++] = (caddr_t)rdr2();
3342         }
3343         if (bp & 0x08) {
3344                 addr[nbp++] = (caddr_t)rdr3();
3345         }
3346
3347         for (i = 0; i < nbp; i++) {
3348                 if (addr[i] < (caddr_t)VM_MAXUSER_ADDRESS) {
3349                         /*
3350                          * addr[i] is in user space
3351                          */
3352                         return nbp;
3353                 }
3354         }
3355
3356         /*
3357          * None of the breakpoints are in user space.
3358          */
3359         return 0;
3360 }
3361
3362 #ifdef KDB
3363
3364 /*
3365  * Provide inb() and outb() as functions.  They are normally only available as
3366  * inline functions, thus cannot be called from the debugger.
3367  */
3368
3369 /* silence compiler warnings */
3370 u_char inb_(u_short);
3371 void outb_(u_short, u_char);
3372
3373 u_char
3374 inb_(u_short port)
3375 {
3376         return inb(port);
3377 }
3378
3379 void
3380 outb_(u_short port, u_char data)
3381 {
3382         outb(port, data);
3383 }
3384
3385 #endif /* KDB */