]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/amd64/amd64/machdep.c
This commit was generated by cvs2svn to compensate for changes in r159985,
[FreeBSD/FreeBSD.git] / sys / amd64 / amd64 / machdep.c
1 /*-
2  * Copyright (c) 2003 Peter Wemm.
3  * Copyright (c) 1992 Terrence R. Lambert.
4  * Copyright (c) 1982, 1987, 1990 The Regents of the University of California.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * William Jolitz.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *      This product includes software developed by the University of
21  *      California, Berkeley and its contributors.
22  * 4. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  *
38  *      from: @(#)machdep.c     7.4 (Berkeley) 6/3/91
39  */
40
41 #include <sys/cdefs.h>
42 __FBSDID("$FreeBSD$");
43
44 #include "opt_atalk.h"
45 #include "opt_atpic.h"
46 #include "opt_compat.h"
47 #include "opt_cpu.h"
48 #include "opt_ddb.h"
49 #include "opt_inet.h"
50 #include "opt_ipx.h"
51 #include "opt_isa.h"
52 #include "opt_kstack_pages.h"
53 #include "opt_maxmem.h"
54 #include "opt_msgbuf.h"
55 #include "opt_perfmon.h"
56
57 #include <sys/param.h>
58 #include <sys/proc.h>
59 #include <sys/systm.h>
60 #include <sys/bio.h>
61 #include <sys/buf.h>
62 #include <sys/bus.h>
63 #include <sys/callout.h>
64 #include <sys/cons.h>
65 #include <sys/cpu.h>
66 #include <sys/eventhandler.h>
67 #include <sys/exec.h>
68 #include <sys/imgact.h>
69 #include <sys/kdb.h>
70 #include <sys/kernel.h>
71 #include <sys/ktr.h>
72 #include <sys/linker.h>
73 #include <sys/lock.h>
74 #include <sys/malloc.h>
75 #include <sys/memrange.h>
76 #include <sys/msgbuf.h>
77 #include <sys/mutex.h>
78 #include <sys/pcpu.h>
79 #include <sys/ptrace.h>
80 #include <sys/reboot.h>
81 #include <sys/sched.h>
82 #include <sys/signalvar.h>
83 #include <sys/sysctl.h>
84 #include <sys/sysent.h>
85 #include <sys/sysproto.h>
86 #include <sys/ucontext.h>
87 #include <sys/vmmeter.h>
88
89 #include <vm/vm.h>
90 #include <vm/vm_extern.h>
91 #include <vm/vm_kern.h>
92 #include <vm/vm_page.h>
93 #include <vm/vm_map.h>
94 #include <vm/vm_object.h>
95 #include <vm/vm_pager.h>
96 #include <vm/vm_param.h>
97
98 #ifdef DDB
99 #ifndef KDB
100 #error KDB must be enabled in order for DDB to work!
101 #endif
102 #endif
103 #include <ddb/ddb.h>
104
105 #include <net/netisr.h>
106
107 #include <machine/clock.h>
108 #include <machine/cpu.h>
109 #include <machine/cputypes.h>
110 #include <machine/intr_machdep.h>
111 #include <machine/md_var.h>
112 #include <machine/metadata.h>
113 #include <machine/pc/bios.h>
114 #include <machine/pcb.h>
115 #include <machine/proc.h>
116 #include <machine/reg.h>
117 #include <machine/sigframe.h>
118 #include <machine/specialreg.h>
119 #ifdef PERFMON
120 #include <machine/perfmon.h>
121 #endif
122 #include <machine/tss.h>
123 #ifdef SMP
124 #include <machine/smp.h>
125 #endif
126
127 #include <dev/ic/i8259.h>
128 #include <amd64/isa/icu.h>
129 #include <machine/apicvar.h>
130
131 #include <isa/isareg.h>
132 #include <isa/rtc.h>
133
134 /* Sanity check for __curthread() */
135 CTASSERT(offsetof(struct pcpu, pc_curthread) == 0);
136
137 extern u_int64_t hammer_time(u_int64_t, u_int64_t);
138 extern void dblfault_handler(void);
139
140 extern void printcpuinfo(void); /* XXX header file */
141 extern void identify_cpu(void);
142 extern void panicifcpuunsupported(void);
143
144 #define CS_SECURE(cs)           (ISPL(cs) == SEL_UPL)
145 #define EFL_SECURE(ef, oef)     ((((ef) ^ (oef)) & ~PSL_USERCHANGE) == 0)
146
147 static void cpu_startup(void *);
148 static void get_fpcontext(struct thread *td, mcontext_t *mcp);
149 static int  set_fpcontext(struct thread *td, const mcontext_t *mcp);
150 SYSINIT(cpu, SI_SUB_CPU, SI_ORDER_FIRST, cpu_startup, NULL)
151
152 #ifdef DDB
153 extern vm_offset_t ksym_start, ksym_end;
154 #endif
155
156 int     _udatasel, _ucodesel, _ucode32sel;
157
158 int cold = 1;
159
160 long Maxmem = 0;
161 long realmem = 0;
162
163 vm_paddr_t phys_avail[20];
164 vm_paddr_t dump_avail[20];
165
166 /* must be 2 less so 0 0 can signal end of chunks */
167 #define PHYS_AVAIL_ARRAY_END ((sizeof(phys_avail) / sizeof(phys_avail[0])) - 2)
168 #define DUMP_AVAIL_ARRAY_END ((sizeof(dump_avail) / sizeof(dump_avail[0])) - 2)
169
170 struct kva_md_info kmi;
171
172 static struct trapframe proc0_tf;
173 struct region_descriptor r_gdt, r_idt;
174
175 struct pcpu __pcpu[MAXCPU];
176
177 struct mtx icu_lock;
178
179 struct mem_range_softc mem_range_softc;
180
181 static void
182 cpu_startup(dummy)
183         void *dummy;
184 {
185         /*
186          * Good {morning,afternoon,evening,night}.
187          */
188         startrtclock();
189         printcpuinfo();
190         panicifcpuunsupported();
191 #ifdef PERFMON
192         perfmon_init();
193 #endif
194         printf("usable memory  = %ju (%ju MB)\n", ptoa((uintmax_t)physmem),
195             ptoa((uintmax_t)physmem) / 1048576);
196         realmem = Maxmem;
197         /*
198          * Display any holes after the first chunk of extended memory.
199          */
200         if (bootverbose) {
201                 int indx;
202
203                 printf("Physical memory chunk(s):\n");
204                 for (indx = 0; phys_avail[indx + 1] != 0; indx += 2) {
205                         vm_paddr_t size;
206
207                         size = phys_avail[indx + 1] - phys_avail[indx];
208                         printf(
209                             "0x%016jx - 0x%016jx, %ju bytes (%ju pages)\n",
210                             (uintmax_t)phys_avail[indx],
211                             (uintmax_t)phys_avail[indx + 1] - 1,
212                             (uintmax_t)size, (uintmax_t)size / PAGE_SIZE);
213                 }
214         }
215
216         vm_ksubmap_init(&kmi);
217
218         printf("avail memory = %ju (%ju MB)\n",
219             ptoa((uintmax_t)cnt.v_free_count),
220             ptoa((uintmax_t)cnt.v_free_count) / 1048576);
221
222         /*
223          * Set up buffers, so they can be used to read disk labels.
224          */
225         bufinit();
226         vm_pager_bufferinit();
227
228         cpu_setregs();
229 }
230
231 /*
232  * Send an interrupt to process.
233  *
234  * Stack is set up to allow sigcode stored
235  * at top to call routine, followed by kcall
236  * to sigreturn routine below.  After sigreturn
237  * resets the signal mask, the stack, and the
238  * frame pointer, it returns to the user
239  * specified pc, psl.
240  */
241 void
242 sendsig(sig_t catcher, ksiginfo_t *ksi, sigset_t *mask)
243 {
244         struct sigframe sf, *sfp;
245         struct proc *p;
246         struct thread *td;
247         struct sigacts *psp;
248         char *sp;
249         struct trapframe *regs;
250         int sig;
251         int oonstack;
252
253         td = curthread;
254         p = td->td_proc;
255         PROC_LOCK_ASSERT(p, MA_OWNED);
256         sig = ksi->ksi_signo;
257         psp = p->p_sigacts;
258         mtx_assert(&psp->ps_mtx, MA_OWNED);
259         regs = td->td_frame;
260         oonstack = sigonstack(regs->tf_rsp);
261
262         /* Save user context. */
263         bzero(&sf, sizeof(sf));
264         sf.sf_uc.uc_sigmask = *mask;
265         sf.sf_uc.uc_stack = td->td_sigstk;
266         sf.sf_uc.uc_stack.ss_flags = (td->td_pflags & TDP_ALTSTACK)
267             ? ((oonstack) ? SS_ONSTACK : 0) : SS_DISABLE;
268         sf.sf_uc.uc_mcontext.mc_onstack = (oonstack) ? 1 : 0;
269         bcopy(regs, &sf.sf_uc.uc_mcontext.mc_rdi, sizeof(*regs));
270         sf.sf_uc.uc_mcontext.mc_len = sizeof(sf.sf_uc.uc_mcontext); /* magic */
271         get_fpcontext(td, &sf.sf_uc.uc_mcontext);
272         fpstate_drop(td);
273
274         /* Allocate space for the signal handler context. */
275         if ((td->td_pflags & TDP_ALTSTACK) != 0 && !oonstack &&
276             SIGISMEMBER(psp->ps_sigonstack, sig)) {
277                 sp = td->td_sigstk.ss_sp +
278                     td->td_sigstk.ss_size - sizeof(struct sigframe);
279 #if defined(COMPAT_43)
280                 td->td_sigstk.ss_flags |= SS_ONSTACK;
281 #endif
282         } else
283                 sp = (char *)regs->tf_rsp - sizeof(struct sigframe) - 128;
284         /* Align to 16 bytes. */
285         sfp = (struct sigframe *)((unsigned long)sp & ~0xFul);
286
287         /* Translate the signal if appropriate. */
288         if (p->p_sysent->sv_sigtbl && sig <= p->p_sysent->sv_sigsize)
289                 sig = p->p_sysent->sv_sigtbl[_SIG_IDX(sig)];
290
291         /* Build the argument list for the signal handler. */
292         regs->tf_rdi = sig;                     /* arg 1 in %rdi */
293         regs->tf_rdx = (register_t)&sfp->sf_uc; /* arg 3 in %rdx */
294         if (SIGISMEMBER(psp->ps_siginfo, sig)) {
295                 /* Signal handler installed with SA_SIGINFO. */
296                 regs->tf_rsi = (register_t)&sfp->sf_si; /* arg 2 in %rsi */
297                 sf.sf_ahu.sf_action = (__siginfohandler_t *)catcher;
298
299                 /* Fill in POSIX parts */
300                 sf.sf_si = ksi->ksi_info;
301                 sf.sf_si.si_signo = sig; /* maybe a translated signal */
302                 regs->tf_rcx = (register_t)ksi->ksi_addr; /* arg 4 in %rcx */
303         } else {
304                 /* Old FreeBSD-style arguments. */
305                 regs->tf_rsi = ksi->ksi_code;   /* arg 2 in %rsi */
306                 regs->tf_rcx = (register_t)ksi->ksi_addr; /* arg 4 in %rcx */
307                 sf.sf_ahu.sf_handler = catcher;
308         }
309         mtx_unlock(&psp->ps_mtx);
310         PROC_UNLOCK(p);
311
312         /*
313          * Copy the sigframe out to the user's stack.
314          */
315         if (copyout(&sf, sfp, sizeof(*sfp)) != 0) {
316 #ifdef DEBUG
317                 printf("process %ld has trashed its stack\n", (long)p->p_pid);
318 #endif
319                 PROC_LOCK(p);
320                 sigexit(td, SIGILL);
321         }
322
323         regs->tf_rsp = (long)sfp;
324         regs->tf_rip = PS_STRINGS - *(p->p_sysent->sv_szsigcode);
325         regs->tf_rflags &= ~PSL_T;
326         regs->tf_cs = _ucodesel;
327         PROC_LOCK(p);
328         mtx_lock(&psp->ps_mtx);
329 }
330
331 /*
332  * System call to cleanup state after a signal
333  * has been taken.  Reset signal mask and
334  * stack state from context left by sendsig (above).
335  * Return to previous pc and psl as specified by
336  * context left by sendsig. Check carefully to
337  * make sure that the user has not modified the
338  * state to gain improper privileges.
339  *
340  * MPSAFE
341  */
342 int
343 sigreturn(td, uap)
344         struct thread *td;
345         struct sigreturn_args /* {
346                 const struct __ucontext *sigcntxp;
347         } */ *uap;
348 {
349         ucontext_t uc;
350         struct proc *p = td->td_proc;
351         struct trapframe *regs;
352         const ucontext_t *ucp;
353         long rflags;
354         int cs, error, ret;
355         ksiginfo_t ksi;
356
357         error = copyin(uap->sigcntxp, &uc, sizeof(uc));
358         if (error != 0)
359                 return (error);
360         ucp = &uc;
361         regs = td->td_frame;
362         rflags = ucp->uc_mcontext.mc_rflags;
363         /*
364          * Don't allow users to change privileged or reserved flags.
365          */
366         /*
367          * XXX do allow users to change the privileged flag PSL_RF.
368          * The cpu sets PSL_RF in tf_rflags for faults.  Debuggers
369          * should sometimes set it there too.  tf_rflags is kept in
370          * the signal context during signal handling and there is no
371          * other place to remember it, so the PSL_RF bit may be
372          * corrupted by the signal handler without us knowing.
373          * Corruption of the PSL_RF bit at worst causes one more or
374          * one less debugger trap, so allowing it is fairly harmless.
375          */
376         if (!EFL_SECURE(rflags & ~PSL_RF, regs->tf_rflags & ~PSL_RF)) {
377                 printf("sigreturn: rflags = 0x%lx\n", rflags);
378                 return (EINVAL);
379         }
380
381         /*
382          * Don't allow users to load a valid privileged %cs.  Let the
383          * hardware check for invalid selectors, excess privilege in
384          * other selectors, invalid %eip's and invalid %esp's.
385          */
386         cs = ucp->uc_mcontext.mc_cs;
387         if (!CS_SECURE(cs)) {
388                 printf("sigreturn: cs = 0x%x\n", cs);
389                 ksiginfo_init_trap(&ksi);
390                 ksi.ksi_signo = SIGBUS;
391                 ksi.ksi_code = BUS_OBJERR;
392                 ksi.ksi_trapno = T_PROTFLT;
393                 ksi.ksi_addr = (void *)regs->tf_rip;
394                 trapsignal(td, &ksi);
395                 return (EINVAL);
396         }
397
398         ret = set_fpcontext(td, &ucp->uc_mcontext);
399         if (ret != 0)
400                 return (ret);
401         bcopy(&ucp->uc_mcontext.mc_rdi, regs, sizeof(*regs));
402
403         PROC_LOCK(p);
404 #if defined(COMPAT_43)
405         if (ucp->uc_mcontext.mc_onstack & 1)
406                 td->td_sigstk.ss_flags |= SS_ONSTACK;
407         else
408                 td->td_sigstk.ss_flags &= ~SS_ONSTACK;
409 #endif
410
411         td->td_sigmask = ucp->uc_sigmask;
412         SIG_CANTMASK(td->td_sigmask);
413         signotify(td);
414         PROC_UNLOCK(p);
415         td->td_pcb->pcb_flags |= PCB_FULLCTX;
416         return (EJUSTRETURN);
417 }
418
419 #ifdef COMPAT_FREEBSD4
420 int
421 freebsd4_sigreturn(struct thread *td, struct freebsd4_sigreturn_args *uap)
422 {
423  
424         return sigreturn(td, (struct sigreturn_args *)uap);
425 }
426 #endif
427
428
429 /*
430  * Machine dependent boot() routine
431  *
432  * I haven't seen anything to put here yet
433  * Possibly some stuff might be grafted back here from boot()
434  */
435 void
436 cpu_boot(int howto)
437 {
438 }
439
440 /* Get current clock frequency for the given cpu id. */
441 int
442 cpu_est_clockrate(int cpu_id, uint64_t *rate)
443 {
444         register_t reg;
445         uint64_t tsc1, tsc2;
446
447         if (pcpu_find(cpu_id) == NULL || rate == NULL)
448                 return (EINVAL);
449
450         /* If we're booting, trust the rate calibrated moments ago. */
451         if (cold) {
452                 *rate = tsc_freq;
453                 return (0);
454         }
455
456 #ifdef SMP
457         /* Schedule ourselves on the indicated cpu. */
458         mtx_lock_spin(&sched_lock);
459         sched_bind(curthread, cpu_id);
460         mtx_unlock_spin(&sched_lock);
461 #endif
462
463         /* Calibrate by measuring a short delay. */
464         reg = intr_disable();
465         tsc1 = rdtsc();
466         DELAY(1000);
467         tsc2 = rdtsc();
468         intr_restore(reg);
469
470 #ifdef SMP
471         mtx_lock_spin(&sched_lock);
472         sched_unbind(curthread);
473         mtx_unlock_spin(&sched_lock);
474 #endif
475
476         /*
477          * Calculate the difference in readings, convert to Mhz, and
478          * subtract 0.5% of the total.  Empirical testing has shown that
479          * overhead in DELAY() works out to approximately this value.
480          */
481         tsc2 -= tsc1;
482         *rate = tsc2 * 1000 - tsc2 * 5;
483         return (0);
484 }
485
486 /*
487  * Shutdown the CPU as much as possible
488  */
489 void
490 cpu_halt(void)
491 {
492         for (;;)
493                 __asm__ ("hlt");
494 }
495
496 /*
497  * Hook to idle the CPU when possible.  In the SMP case we default to
498  * off because a halted cpu will not currently pick up a new thread in the
499  * run queue until the next timer tick.  If turned on this will result in
500  * approximately a 4.2% loss in real time performance in buildworld tests
501  * (but improves user and sys times oddly enough), and saves approximately
502  * 5% in power consumption on an idle machine (tests w/2xCPU 1.1GHz P3).
503  *
504  * XXX we need to have a cpu mask of idle cpus and generate an IPI or
505  * otherwise generate some sort of interrupt to wake up cpus sitting in HLT.
506  * Then we can have our cake and eat it too.
507  *
508  * XXX I'm turning it on for SMP as well by default for now.  It seems to
509  * help lock contention somewhat, and this is critical for HTT. -Peter
510  */
511 static int      cpu_idle_hlt = 1;
512 SYSCTL_INT(_machdep, OID_AUTO, cpu_idle_hlt, CTLFLAG_RW,
513     &cpu_idle_hlt, 0, "Idle loop HLT enable");
514
515 static void
516 cpu_idle_default(void)
517 {
518         /*
519          * we must absolutely guarentee that hlt is the
520          * absolute next instruction after sti or we
521          * introduce a timing window.
522          */
523         __asm __volatile("sti; hlt");
524 }
525
526 /*
527  * Note that we have to be careful here to avoid a race between checking
528  * sched_runnable() and actually halting.  If we don't do this, we may waste
529  * the time between calling hlt and the next interrupt even though there
530  * is a runnable process.
531  */
532 void
533 cpu_idle(void)
534 {
535
536 #ifdef SMP
537         if (mp_grab_cpu_hlt())
538                 return;
539 #endif
540         if (cpu_idle_hlt) {
541                 disable_intr();
542                 if (sched_runnable())
543                         enable_intr();
544                 else
545                         (*cpu_idle_hook)();
546         }
547 }
548
549 /* Other subsystems (e.g., ACPI) can hook this later. */
550 void (*cpu_idle_hook)(void) = cpu_idle_default;
551
552 /*
553  * Clear registers on exec
554  */
555 void
556 exec_setregs(td, entry, stack, ps_strings)
557         struct thread *td;
558         u_long entry;
559         u_long stack;
560         u_long ps_strings;
561 {
562         struct trapframe *regs = td->td_frame;
563         struct pcb *pcb = td->td_pcb;
564         
565         critical_enter();
566         wrmsr(MSR_FSBASE, 0);
567         wrmsr(MSR_KGSBASE, 0);  /* User value while we're in the kernel */
568         pcb->pcb_fsbase = 0;
569         pcb->pcb_gsbase = 0;
570         critical_exit();
571         load_ds(_udatasel);
572         load_es(_udatasel);
573         load_fs(_udatasel);
574         load_gs(_udatasel);
575         pcb->pcb_ds = _udatasel;
576         pcb->pcb_es = _udatasel;
577         pcb->pcb_fs = _udatasel;
578         pcb->pcb_gs = _udatasel;
579
580         bzero((char *)regs, sizeof(struct trapframe));
581         regs->tf_rip = entry;
582         regs->tf_rsp = ((stack - 8) & ~0xFul) + 8;
583         regs->tf_rdi = stack;           /* argv */
584         regs->tf_rflags = PSL_USER | (regs->tf_rflags & PSL_T);
585         regs->tf_ss = _udatasel;
586         regs->tf_cs = _ucodesel;
587
588         /*
589          * Reset the hardware debug registers if they were in use.
590          * They won't have any meaning for the newly exec'd process.
591          */
592         if (pcb->pcb_flags & PCB_DBREGS) {
593                 pcb->pcb_dr0 = 0;
594                 pcb->pcb_dr1 = 0;
595                 pcb->pcb_dr2 = 0;
596                 pcb->pcb_dr3 = 0;
597                 pcb->pcb_dr6 = 0;
598                 pcb->pcb_dr7 = 0;
599                 if (pcb == PCPU_GET(curpcb)) {
600                         /*
601                          * Clear the debug registers on the running
602                          * CPU, otherwise they will end up affecting
603                          * the next process we switch to.
604                          */
605                         reset_dbregs();
606                 }
607                 pcb->pcb_flags &= ~PCB_DBREGS;
608         }
609
610         /*
611          * Drop the FP state if we hold it, so that the process gets a
612          * clean FP state if it uses the FPU again.
613          */
614         fpstate_drop(td);
615 }
616
617 void
618 cpu_setregs(void)
619 {
620         register_t cr0;
621
622         cr0 = rcr0();
623         /*
624          * CR0_MP, CR0_NE and CR0_TS are also set by npx_probe() for the
625          * BSP.  See the comments there about why we set them.
626          */
627         cr0 |= CR0_MP | CR0_NE | CR0_TS | CR0_WP | CR0_AM;
628         load_cr0(cr0);
629 }
630
631 static int
632 sysctl_machdep_adjkerntz(SYSCTL_HANDLER_ARGS)
633 {
634         int error;
635         error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2,
636                 req);
637         if (!error && req->newptr)
638                 resettodr();
639         return (error);
640 }
641
642 SYSCTL_PROC(_machdep, OID_AUTO, adjkerntz, CTLTYPE_INT|CTLFLAG_RW,
643         &adjkerntz, 0, sysctl_machdep_adjkerntz, "I", "");
644
645 SYSCTL_INT(_machdep, OID_AUTO, disable_rtc_set,
646         CTLFLAG_RW, &disable_rtc_set, 0, "");
647
648 SYSCTL_INT(_machdep, OID_AUTO, wall_cmos_clock,
649         CTLFLAG_RW, &wall_cmos_clock, 0, "");
650
651 /*
652  * Initialize amd64 and configure to run kernel
653  */
654
655 /*
656  * Initialize segments & interrupt table
657  */
658
659 struct user_segment_descriptor gdt[NGDT * MAXCPU];/* global descriptor table */
660 static struct gate_descriptor idt0[NIDT];
661 struct gate_descriptor *idt = &idt0[0]; /* interrupt descriptor table */
662
663 static char dblfault_stack[PAGE_SIZE] __aligned(16);
664
665 struct amd64tss common_tss[MAXCPU];
666
667 /* software prototypes -- in more palatable form */
668 struct soft_segment_descriptor gdt_segs[] = {
669 /* GNULL_SEL    0 Null Descriptor */
670 {       0x0,                    /* segment base address  */
671         0x0,                    /* length */
672         0,                      /* segment type */
673         0,                      /* segment descriptor priority level */
674         0,                      /* segment descriptor present */
675         0,                      /* long */
676         0,                      /* default 32 vs 16 bit size */
677         0                       /* limit granularity (byte/page units)*/ },
678 /* GCODE_SEL    1 Code Descriptor for kernel */
679 {       0x0,                    /* segment base address  */
680         0xfffff,                /* length - all address space */
681         SDT_MEMERA,             /* segment type */
682         SEL_KPL,                /* segment descriptor priority level */
683         1,                      /* segment descriptor present */
684         1,                      /* long */
685         0,                      /* default 32 vs 16 bit size */
686         1                       /* limit granularity (byte/page units)*/ },
687 /* GDATA_SEL    2 Data Descriptor for kernel */
688 {       0x0,                    /* segment base address  */
689         0xfffff,                /* length - all address space */
690         SDT_MEMRWA,             /* segment type */
691         SEL_KPL,                /* segment descriptor priority level */
692         1,                      /* segment descriptor present */
693         1,                      /* long */
694         0,                      /* default 32 vs 16 bit size */
695         1                       /* limit granularity (byte/page units)*/ },
696 /* GUCODE32_SEL 3 32 bit Code Descriptor for user */
697 {       0x0,                    /* segment base address  */
698         0xfffff,                /* length - all address space */
699         SDT_MEMERA,             /* segment type */
700         SEL_UPL,                /* segment descriptor priority level */
701         1,                      /* segment descriptor present */
702         0,                      /* long */
703         1,                      /* default 32 vs 16 bit size */
704         1                       /* limit granularity (byte/page units)*/ },
705 /* GUDATA_SEL   4 32/64 bit Data Descriptor for user */
706 {       0x0,                    /* segment base address  */
707         0xfffff,                /* length - all address space */
708         SDT_MEMRWA,             /* segment type */
709         SEL_UPL,                /* segment descriptor priority level */
710         1,                      /* segment descriptor present */
711         0,                      /* long */
712         1,                      /* default 32 vs 16 bit size */
713         1                       /* limit granularity (byte/page units)*/ },
714 /* GUCODE_SEL   5 64 bit Code Descriptor for user */
715 {       0x0,                    /* segment base address  */
716         0xfffff,                /* length - all address space */
717         SDT_MEMERA,             /* segment type */
718         SEL_UPL,                /* segment descriptor priority level */
719         1,                      /* segment descriptor present */
720         1,                      /* long */
721         0,                      /* default 32 vs 16 bit size */
722         1                       /* limit granularity (byte/page units)*/ },
723 /* GPROC0_SEL   6 Proc 0 Tss Descriptor */
724 {
725         0x0,                    /* segment base address */
726         sizeof(struct amd64tss)-1,/* length - all address space */
727         SDT_SYSTSS,             /* segment type */
728         SEL_KPL,                /* segment descriptor priority level */
729         1,                      /* segment descriptor present */
730         0,                      /* long */
731         0,                      /* unused - default 32 vs 16 bit size */
732         0                       /* limit granularity (byte/page units)*/ },
733 /* Actually, the TSS is a system descriptor which is double size */
734 {       0x0,                    /* segment base address  */
735         0x0,                    /* length */
736         0,                      /* segment type */
737         0,                      /* segment descriptor priority level */
738         0,                      /* segment descriptor present */
739         0,                      /* long */
740         0,                      /* default 32 vs 16 bit size */
741         0                       /* limit granularity (byte/page units)*/ },
742 };
743
744 void
745 setidt(idx, func, typ, dpl, ist)
746         int idx;
747         inthand_t *func;
748         int typ;
749         int dpl;
750         int ist;
751 {
752         struct gate_descriptor *ip;
753
754         ip = idt + idx;
755         ip->gd_looffset = (uintptr_t)func;
756         ip->gd_selector = GSEL(GCODE_SEL, SEL_KPL);
757         ip->gd_ist = ist;
758         ip->gd_xx = 0;
759         ip->gd_type = typ;
760         ip->gd_dpl = dpl;
761         ip->gd_p = 1;
762         ip->gd_hioffset = ((uintptr_t)func)>>16 ;
763 }
764
765 #define IDTVEC(name)    __CONCAT(X,name)
766
767 extern inthand_t
768         IDTVEC(div), IDTVEC(dbg), IDTVEC(nmi), IDTVEC(bpt), IDTVEC(ofl),
769         IDTVEC(bnd), IDTVEC(ill), IDTVEC(dna), IDTVEC(fpusegm),
770         IDTVEC(tss), IDTVEC(missing), IDTVEC(stk), IDTVEC(prot),
771         IDTVEC(page), IDTVEC(mchk), IDTVEC(rsvd), IDTVEC(fpu), IDTVEC(align),
772         IDTVEC(xmm), IDTVEC(dblfault),
773         IDTVEC(fast_syscall), IDTVEC(fast_syscall32);
774
775 void
776 sdtossd(sd, ssd)
777         struct user_segment_descriptor *sd;
778         struct soft_segment_descriptor *ssd;
779 {
780
781         ssd->ssd_base  = (sd->sd_hibase << 24) | sd->sd_lobase;
782         ssd->ssd_limit = (sd->sd_hilimit << 16) | sd->sd_lolimit;
783         ssd->ssd_type  = sd->sd_type;
784         ssd->ssd_dpl   = sd->sd_dpl;
785         ssd->ssd_p     = sd->sd_p;
786         ssd->ssd_long  = sd->sd_long;
787         ssd->ssd_def32 = sd->sd_def32;
788         ssd->ssd_gran  = sd->sd_gran;
789 }
790
791 void
792 ssdtosd(ssd, sd)
793         struct soft_segment_descriptor *ssd;
794         struct user_segment_descriptor *sd;
795 {
796
797         sd->sd_lobase = (ssd->ssd_base) & 0xffffff;
798         sd->sd_hibase = (ssd->ssd_base >> 24) & 0xff;
799         sd->sd_lolimit = (ssd->ssd_limit) & 0xffff;
800         sd->sd_hilimit = (ssd->ssd_limit >> 16) & 0xf;
801         sd->sd_type  = ssd->ssd_type;
802         sd->sd_dpl   = ssd->ssd_dpl;
803         sd->sd_p     = ssd->ssd_p;
804         sd->sd_long  = ssd->ssd_long;
805         sd->sd_def32 = ssd->ssd_def32;
806         sd->sd_gran  = ssd->ssd_gran;
807 }
808
809 void
810 ssdtosyssd(ssd, sd)
811         struct soft_segment_descriptor *ssd;
812         struct system_segment_descriptor *sd;
813 {
814
815         sd->sd_lobase = (ssd->ssd_base) & 0xffffff;
816         sd->sd_hibase = (ssd->ssd_base >> 24) & 0xfffffffffful;
817         sd->sd_lolimit = (ssd->ssd_limit) & 0xffff;
818         sd->sd_hilimit = (ssd->ssd_limit >> 16) & 0xf;
819         sd->sd_type  = ssd->ssd_type;
820         sd->sd_dpl   = ssd->ssd_dpl;
821         sd->sd_p     = ssd->ssd_p;
822         sd->sd_gran  = ssd->ssd_gran;
823 }
824
825 #if !defined(DEV_ATPIC) && defined(DEV_ISA)
826 #include <isa/isavar.h>
827 u_int
828 isa_irq_pending(void)
829 {
830
831         return (0);
832 }
833 #endif
834
835 #define PHYSMAP_SIZE    (2 * 20)
836
837 u_int basemem;
838
839 /*
840  * Populate the (physmap) array with base/bound pairs describing the
841  * available physical memory in the system, then test this memory and
842  * build the phys_avail array describing the actually-available memory.
843  *
844  * If we cannot accurately determine the physical memory map, then use
845  * value from the 0xE801 call, and failing that, the RTC.
846  *
847  * Total memory size may be set by the kernel environment variable
848  * hw.physmem or the compile-time define MAXMEM.
849  *
850  * XXX first should be vm_paddr_t.
851  */
852 static void
853 getmemsize(caddr_t kmdp, u_int64_t first)
854 {
855         int i, physmap_idx, pa_indx, da_indx;
856         vm_paddr_t pa, physmap[PHYSMAP_SIZE];
857         u_long physmem_tunable;
858         pt_entry_t *pte;
859         struct bios_smap *smapbase, *smap, *smapend;
860         u_int32_t smapsize;
861         quad_t dcons_addr, dcons_size;
862
863         bzero(physmap, sizeof(physmap));
864         basemem = 0;
865         physmap_idx = 0;
866
867         /*
868          * get memory map from INT 15:E820, kindly supplied by the loader.
869          *
870          * subr_module.c says:
871          * "Consumer may safely assume that size value precedes data."
872          * ie: an int32_t immediately precedes smap.
873          */
874         smapbase = (struct bios_smap *)preload_search_info(kmdp,
875             MODINFO_METADATA | MODINFOMD_SMAP);
876         if (smapbase == NULL)
877                 panic("No BIOS smap info from loader!");
878
879         smapsize = *((u_int32_t *)smapbase - 1);
880         smapend = (struct bios_smap *)((uintptr_t)smapbase + smapsize);
881
882         for (smap = smapbase; smap < smapend; smap++) {
883                 if (boothowto & RB_VERBOSE)
884                         printf("SMAP type=%02x base=%016lx len=%016lx\n",
885                             smap->type, smap->base, smap->length);
886
887                 if (smap->type != 0x01)
888                         continue;
889
890                 if (smap->length == 0)
891                         continue;
892
893                 for (i = 0; i <= physmap_idx; i += 2) {
894                         if (smap->base < physmap[i + 1]) {
895                                 if (boothowto & RB_VERBOSE)
896                                         printf(
897         "Overlapping or non-montonic memory region, ignoring second region\n");
898                                 continue;
899                         }
900                 }
901
902                 if (smap->base == physmap[physmap_idx + 1]) {
903                         physmap[physmap_idx + 1] += smap->length;
904                         continue;
905                 }
906
907                 physmap_idx += 2;
908                 if (physmap_idx == PHYSMAP_SIZE) {
909                         printf(
910                 "Too many segments in the physical address map, giving up\n");
911                         break;
912                 }
913                 physmap[physmap_idx] = smap->base;
914                 physmap[physmap_idx + 1] = smap->base + smap->length;
915         }
916
917         /*
918          * Find the 'base memory' segment for SMP
919          */
920         basemem = 0;
921         for (i = 0; i <= physmap_idx; i += 2) {
922                 if (physmap[i] == 0x00000000) {
923                         basemem = physmap[i + 1] / 1024;
924                         break;
925                 }
926         }
927         if (basemem == 0)
928                 panic("BIOS smap did not include a basemem segment!");
929
930 #ifdef SMP
931         /* make hole for AP bootstrap code */
932         physmap[1] = mp_bootaddress(physmap[1] / 1024);
933 #endif
934
935         /*
936          * Maxmem isn't the "maximum memory", it's one larger than the
937          * highest page of the physical address space.  It should be
938          * called something like "Maxphyspage".  We may adjust this
939          * based on ``hw.physmem'' and the results of the memory test.
940          */
941         Maxmem = atop(physmap[physmap_idx + 1]);
942
943 #ifdef MAXMEM
944         Maxmem = MAXMEM / 4;
945 #endif
946
947         if (TUNABLE_ULONG_FETCH("hw.physmem", &physmem_tunable))
948                 Maxmem = atop(physmem_tunable);
949
950         if (atop(physmap[physmap_idx + 1]) != Maxmem &&
951             (boothowto & RB_VERBOSE))
952                 printf("Physical memory use set to %ldK\n", Maxmem * 4);
953
954         /*
955          * If Maxmem has been increased beyond what the system has detected,
956          * extend the last memory segment to the new limit.
957          */
958         if (atop(physmap[physmap_idx + 1]) < Maxmem)
959                 physmap[physmap_idx + 1] = ptoa((vm_paddr_t)Maxmem);
960
961         /* call pmap initialization to make new kernel address space */
962         pmap_bootstrap(&first);
963
964         /*
965          * Size up each available chunk of physical memory.
966          */
967         physmap[0] = PAGE_SIZE;         /* mask off page 0 */
968         pa_indx = 0;
969         da_indx = 1;
970         phys_avail[pa_indx++] = physmap[0];
971         phys_avail[pa_indx] = physmap[0];
972         dump_avail[da_indx] = physmap[0];
973         pte = CMAP1;
974
975         /*
976          * Get dcons buffer address
977          */
978         if (getenv_quad("dcons.addr", &dcons_addr) == 0 ||
979             getenv_quad("dcons.size", &dcons_size) == 0)
980                 dcons_addr = 0;
981
982         /*
983          * physmap is in bytes, so when converting to page boundaries,
984          * round up the start address and round down the end address.
985          */
986         for (i = 0; i <= physmap_idx; i += 2) {
987                 vm_paddr_t end;
988
989                 end = ptoa((vm_paddr_t)Maxmem);
990                 if (physmap[i + 1] < end)
991                         end = trunc_page(physmap[i + 1]);
992                 for (pa = round_page(physmap[i]); pa < end; pa += PAGE_SIZE) {
993                         int tmp, page_bad, full;
994                         int *ptr = (int *)CADDR1;
995
996                         full = FALSE;
997                         /*
998                          * block out kernel memory as not available.
999                          */
1000                         if (pa >= 0x100000 && pa < first)
1001                                 goto do_dump_avail;
1002
1003                         /*
1004                          * block out dcons buffer
1005                          */
1006                         if (dcons_addr > 0
1007                             && pa >= trunc_page(dcons_addr)
1008                             && pa < dcons_addr + dcons_size)
1009                                 goto do_dump_avail;
1010
1011                         page_bad = FALSE;
1012
1013                         /*
1014                          * map page into kernel: valid, read/write,non-cacheable
1015                          */
1016                         *pte = pa | PG_V | PG_RW | PG_N;
1017                         invltlb();
1018
1019                         tmp = *(int *)ptr;
1020                         /*
1021                          * Test for alternating 1's and 0's
1022                          */
1023                         *(volatile int *)ptr = 0xaaaaaaaa;
1024                         if (*(volatile int *)ptr != 0xaaaaaaaa)
1025                                 page_bad = TRUE;
1026                         /*
1027                          * Test for alternating 0's and 1's
1028                          */
1029                         *(volatile int *)ptr = 0x55555555;
1030                         if (*(volatile int *)ptr != 0x55555555)
1031                                 page_bad = TRUE;
1032                         /*
1033                          * Test for all 1's
1034                          */
1035                         *(volatile int *)ptr = 0xffffffff;
1036                         if (*(volatile int *)ptr != 0xffffffff)
1037                                 page_bad = TRUE;
1038                         /*
1039                          * Test for all 0's
1040                          */
1041                         *(volatile int *)ptr = 0x0;
1042                         if (*(volatile int *)ptr != 0x0)
1043                                 page_bad = TRUE;
1044                         /*
1045                          * Restore original value.
1046                          */
1047                         *(int *)ptr = tmp;
1048
1049                         /*
1050                          * Adjust array of valid/good pages.
1051                          */
1052                         if (page_bad == TRUE)
1053                                 continue;
1054                         /*
1055                          * If this good page is a continuation of the
1056                          * previous set of good pages, then just increase
1057                          * the end pointer. Otherwise start a new chunk.
1058                          * Note that "end" points one higher than end,
1059                          * making the range >= start and < end.
1060                          * If we're also doing a speculative memory
1061                          * test and we at or past the end, bump up Maxmem
1062                          * so that we keep going. The first bad page
1063                          * will terminate the loop.
1064                          */
1065                         if (phys_avail[pa_indx] == pa) {
1066                                 phys_avail[pa_indx] += PAGE_SIZE;
1067                         } else {
1068                                 pa_indx++;
1069                                 if (pa_indx == PHYS_AVAIL_ARRAY_END) {
1070                                         printf(
1071                 "Too many holes in the physical address space, giving up\n");
1072                                         pa_indx--;
1073                                         full = TRUE;
1074                                         goto do_dump_avail;
1075                                 }
1076                                 phys_avail[pa_indx++] = pa;     /* start */
1077                                 phys_avail[pa_indx] = pa + PAGE_SIZE; /* end */
1078                         }
1079                         physmem++;
1080 do_dump_avail:
1081                         if (dump_avail[da_indx] == pa) {
1082                                 dump_avail[da_indx] += PAGE_SIZE;
1083                         } else {
1084                                 da_indx++;
1085                                 if (da_indx == DUMP_AVAIL_ARRAY_END) {
1086                                         da_indx--;
1087                                         goto do_next;
1088                                 }
1089                                 dump_avail[da_indx++] = pa; /* start */
1090                                 dump_avail[da_indx] = pa + PAGE_SIZE; /* end */
1091                         }
1092 do_next:
1093                         if (full)
1094                                 break;
1095                 }
1096         }
1097         *pte = 0;
1098         invltlb();
1099
1100         /*
1101          * XXX
1102          * The last chunk must contain at least one page plus the message
1103          * buffer to avoid complicating other code (message buffer address
1104          * calculation, etc.).
1105          */
1106         while (phys_avail[pa_indx - 1] + PAGE_SIZE +
1107             round_page(MSGBUF_SIZE) >= phys_avail[pa_indx]) {
1108                 physmem -= atop(phys_avail[pa_indx] - phys_avail[pa_indx - 1]);
1109                 phys_avail[pa_indx--] = 0;
1110                 phys_avail[pa_indx--] = 0;
1111         }
1112
1113         Maxmem = atop(phys_avail[pa_indx]);
1114
1115         /* Trim off space for the message buffer. */
1116         phys_avail[pa_indx] -= round_page(MSGBUF_SIZE);
1117
1118         avail_end = phys_avail[pa_indx];
1119 }
1120
1121 u_int64_t
1122 hammer_time(u_int64_t modulep, u_int64_t physfree)
1123 {
1124         caddr_t kmdp;
1125         int gsel_tss, off, x;
1126         struct pcpu *pc;
1127         u_int64_t msr;
1128         char *env;
1129
1130         thread0.td_kstack = physfree + KERNBASE;
1131         bzero((void *)thread0.td_kstack, KSTACK_PAGES * PAGE_SIZE);
1132         physfree += KSTACK_PAGES * PAGE_SIZE;
1133         thread0.td_pcb = (struct pcb *)
1134            (thread0.td_kstack + KSTACK_PAGES * PAGE_SIZE) - 1;
1135
1136         /*
1137          * This may be done better later if it gets more high level
1138          * components in it. If so just link td->td_proc here.
1139          */
1140         proc_linkup(&proc0, &ksegrp0, &thread0);
1141
1142         preload_metadata = (caddr_t)(uintptr_t)(modulep + KERNBASE);
1143         preload_bootstrap_relocate(KERNBASE);
1144         kmdp = preload_search_by_type("elf kernel");
1145         if (kmdp == NULL)
1146                 kmdp = preload_search_by_type("elf64 kernel");
1147         boothowto = MD_FETCH(kmdp, MODINFOMD_HOWTO, int);
1148         kern_envp = MD_FETCH(kmdp, MODINFOMD_ENVP, char *) + KERNBASE;
1149 #ifdef DDB
1150         ksym_start = MD_FETCH(kmdp, MODINFOMD_SSYM, uintptr_t);
1151         ksym_end = MD_FETCH(kmdp, MODINFOMD_ESYM, uintptr_t);
1152 #endif
1153
1154         /* Init basic tunables, hz etc */
1155         init_param1();
1156
1157         /*
1158          * make gdt memory segments
1159          */
1160         gdt_segs[GPROC0_SEL].ssd_base = (uintptr_t)&common_tss[0];
1161
1162         for (x = 0; x < NGDT; x++) {
1163                 if (x != GPROC0_SEL && x != (GPROC0_SEL + 1))
1164                         ssdtosd(&gdt_segs[x], &gdt[x]);
1165         }
1166         ssdtosyssd(&gdt_segs[GPROC0_SEL],
1167             (struct system_segment_descriptor *)&gdt[GPROC0_SEL]);
1168
1169         r_gdt.rd_limit = NGDT * sizeof(gdt[0]) - 1;
1170         r_gdt.rd_base =  (long) gdt;
1171         lgdt(&r_gdt);
1172         pc = &__pcpu[0];
1173
1174         wrmsr(MSR_FSBASE, 0);           /* User value */
1175         wrmsr(MSR_GSBASE, (u_int64_t)pc);
1176         wrmsr(MSR_KGSBASE, 0);          /* User value while in the kernel */
1177
1178         pcpu_init(pc, 0, sizeof(struct pcpu));
1179         PCPU_SET(prvspace, pc);
1180         PCPU_SET(curthread, &thread0);
1181         PCPU_SET(curpcb, thread0.td_pcb);
1182         PCPU_SET(tssp, &common_tss[0]);
1183
1184         /*
1185          * Initialize mutexes.
1186          *
1187          * icu_lock: in order to allow an interrupt to occur in a critical
1188          *           section, to set pcpu->ipending (etc...) properly, we
1189          *           must be able to get the icu lock, so it can't be
1190          *           under witness.
1191          */
1192         mutex_init();
1193         mtx_init(&clock_lock, "clk", NULL, MTX_SPIN);
1194         mtx_init(&icu_lock, "icu", NULL, MTX_SPIN | MTX_NOWITNESS);
1195
1196         /* exceptions */
1197         for (x = 0; x < NIDT; x++)
1198                 setidt(x, &IDTVEC(rsvd), SDT_SYSIGT, SEL_KPL, 0);
1199         setidt(IDT_DE, &IDTVEC(div),  SDT_SYSIGT, SEL_KPL, 0);
1200         setidt(IDT_DB, &IDTVEC(dbg),  SDT_SYSIGT, SEL_KPL, 0);
1201         setidt(IDT_NMI, &IDTVEC(nmi),  SDT_SYSIGT, SEL_KPL, 0);
1202         setidt(IDT_BP, &IDTVEC(bpt),  SDT_SYSIGT, SEL_UPL, 0);
1203         setidt(IDT_OF, &IDTVEC(ofl),  SDT_SYSIGT, SEL_KPL, 0);
1204         setidt(IDT_BR, &IDTVEC(bnd),  SDT_SYSIGT, SEL_KPL, 0);
1205         setidt(IDT_UD, &IDTVEC(ill),  SDT_SYSIGT, SEL_KPL, 0);
1206         setidt(IDT_NM, &IDTVEC(dna),  SDT_SYSIGT, SEL_KPL, 0);
1207         setidt(IDT_DF, &IDTVEC(dblfault), SDT_SYSIGT, SEL_KPL, 1);
1208         setidt(IDT_FPUGP, &IDTVEC(fpusegm),  SDT_SYSIGT, SEL_KPL, 0);
1209         setidt(IDT_TS, &IDTVEC(tss),  SDT_SYSIGT, SEL_KPL, 0);
1210         setidt(IDT_NP, &IDTVEC(missing),  SDT_SYSIGT, SEL_KPL, 0);
1211         setidt(IDT_SS, &IDTVEC(stk),  SDT_SYSIGT, SEL_KPL, 0);
1212         setidt(IDT_GP, &IDTVEC(prot),  SDT_SYSIGT, SEL_KPL, 0);
1213         setidt(IDT_PF, &IDTVEC(page),  SDT_SYSIGT, SEL_KPL, 0);
1214         setidt(IDT_MF, &IDTVEC(fpu),  SDT_SYSIGT, SEL_KPL, 0);
1215         setidt(IDT_AC, &IDTVEC(align), SDT_SYSIGT, SEL_KPL, 0);
1216         setidt(IDT_MC, &IDTVEC(mchk),  SDT_SYSIGT, SEL_KPL, 0);
1217         setidt(IDT_XF, &IDTVEC(xmm), SDT_SYSIGT, SEL_KPL, 0);
1218
1219         r_idt.rd_limit = sizeof(idt0) - 1;
1220         r_idt.rd_base = (long) idt;
1221         lidt(&r_idt);
1222
1223         /*
1224          * Initialize the console before we print anything out.
1225          */
1226         cninit();
1227
1228 #ifdef DEV_ISA
1229 #ifdef DEV_ATPIC
1230         elcr_probe();
1231         atpic_startup();
1232 #else
1233         /* Reset and mask the atpics and leave them shut down. */
1234         outb(IO_ICU1, ICW1_RESET | ICW1_IC4);
1235         outb(IO_ICU1 + ICU_IMR_OFFSET, IDT_IO_INTS);
1236         outb(IO_ICU1 + ICU_IMR_OFFSET, 1 << 2);
1237         outb(IO_ICU1 + ICU_IMR_OFFSET, ICW4_8086);
1238         outb(IO_ICU1 + ICU_IMR_OFFSET, 0xff);
1239         outb(IO_ICU1, OCW3_SEL | OCW3_RR);
1240
1241         outb(IO_ICU2, ICW1_RESET | ICW1_IC4);
1242         outb(IO_ICU2 + ICU_IMR_OFFSET, IDT_IO_INTS + 8);
1243         outb(IO_ICU2 + ICU_IMR_OFFSET, 2);
1244         outb(IO_ICU2 + ICU_IMR_OFFSET, ICW4_8086);
1245         outb(IO_ICU2 + ICU_IMR_OFFSET, 0xff);
1246         outb(IO_ICU2, OCW3_SEL | OCW3_RR);
1247
1248         /*
1249          * Point the ICU spurious interrupt vectors at the APIC spurious
1250          * interrupt handler.
1251          */
1252         setidt(IDT_IO_INTS + 7, IDTVEC(spuriousint), SDT_SYSIGT, SEL_KPL, 0);
1253         setidt(IDT_IO_INTS + 15, IDTVEC(spuriousint), SDT_SYSIGT, SEL_KPL, 0);
1254 #endif
1255 #else
1256 #error "have you forgotten the isa device?";
1257 #endif
1258
1259         kdb_init();
1260
1261 #ifdef KDB
1262         if (boothowto & RB_KDB)
1263                 kdb_enter("Boot flags requested debugger");
1264 #endif
1265
1266         identify_cpu();         /* Final stage of CPU initialization */
1267         initializecpu();        /* Initialize CPU registers */
1268
1269         /* make an initial tss so cpu can get interrupt stack on syscall! */
1270         common_tss[0].tss_rsp0 = thread0.td_kstack + \
1271             KSTACK_PAGES * PAGE_SIZE - sizeof(struct pcb);
1272         /* Ensure the stack is aligned to 16 bytes */
1273         common_tss[0].tss_rsp0 &= ~0xFul;
1274         PCPU_SET(rsp0, common_tss[0].tss_rsp0);
1275
1276         /* doublefault stack space, runs on ist1 */
1277         common_tss[0].tss_ist1 = (long)&dblfault_stack[sizeof(dblfault_stack)];
1278
1279         /* Set the IO permission bitmap (empty due to tss seg limit) */
1280         common_tss[0].tss_iobase = sizeof(struct amd64tss);
1281
1282         gsel_tss = GSEL(GPROC0_SEL, SEL_KPL);
1283         ltr(gsel_tss);
1284
1285         /* Set up the fast syscall stuff */
1286         msr = rdmsr(MSR_EFER) | EFER_SCE;
1287         wrmsr(MSR_EFER, msr);
1288         wrmsr(MSR_LSTAR, (u_int64_t)IDTVEC(fast_syscall));
1289         wrmsr(MSR_CSTAR, (u_int64_t)IDTVEC(fast_syscall32));
1290         msr = ((u_int64_t)GSEL(GCODE_SEL, SEL_KPL) << 32) |
1291               ((u_int64_t)GSEL(GUCODE32_SEL, SEL_UPL) << 48);
1292         wrmsr(MSR_STAR, msr);
1293         wrmsr(MSR_SF_MASK, PSL_NT|PSL_T|PSL_I|PSL_C|PSL_D);
1294
1295         getmemsize(kmdp, physfree);
1296         init_param2(physmem);
1297
1298         /* now running on new page tables, configured,and u/iom is accessible */
1299
1300         /* Map the message buffer. */
1301         for (off = 0; off < round_page(MSGBUF_SIZE); off += PAGE_SIZE)
1302                 pmap_kenter((vm_offset_t)msgbufp + off, avail_end + off);
1303
1304         msgbufinit(msgbufp, MSGBUF_SIZE);
1305         fpuinit();
1306
1307         /* transfer to user mode */
1308
1309         _ucodesel = GSEL(GUCODE_SEL, SEL_UPL);
1310         _udatasel = GSEL(GUDATA_SEL, SEL_UPL);
1311         _ucode32sel = GSEL(GUCODE32_SEL, SEL_UPL);
1312
1313         /* setup proc 0's pcb */
1314         thread0.td_pcb->pcb_flags = 0; /* XXXKSE */
1315         thread0.td_pcb->pcb_cr3 = KPML4phys;
1316         thread0.td_frame = &proc0_tf;
1317
1318         env = getenv("kernelname");
1319         if (env != NULL)
1320                 strlcpy(kernelname, env, sizeof(kernelname));
1321
1322         /* Location of kernel stack for locore */
1323         return ((u_int64_t)thread0.td_pcb);
1324 }
1325
1326 void
1327 cpu_pcpu_init(struct pcpu *pcpu, int cpuid, size_t size)
1328 {
1329
1330         pcpu->pc_acpi_id = 0xffffffff;
1331 }
1332
1333 void
1334 spinlock_enter(void)
1335 {
1336         struct thread *td;
1337
1338         td = curthread;
1339         if (td->td_md.md_spinlock_count == 0)
1340                 td->td_md.md_saved_flags = intr_disable();
1341         td->td_md.md_spinlock_count++;
1342         critical_enter();
1343 }
1344
1345 void
1346 spinlock_exit(void)
1347 {
1348         struct thread *td;
1349
1350         td = curthread;
1351         critical_exit();
1352         td->td_md.md_spinlock_count--;
1353         if (td->td_md.md_spinlock_count == 0)
1354                 intr_restore(td->td_md.md_saved_flags);
1355 }
1356
1357 /*
1358  * Construct a PCB from a trapframe. This is called from kdb_trap() where
1359  * we want to start a backtrace from the function that caused us to enter
1360  * the debugger. We have the context in the trapframe, but base the trace
1361  * on the PCB. The PCB doesn't have to be perfect, as long as it contains
1362  * enough for a backtrace.
1363  */
1364 void
1365 makectx(struct trapframe *tf, struct pcb *pcb)
1366 {
1367
1368         pcb->pcb_r12 = tf->tf_r12;
1369         pcb->pcb_r13 = tf->tf_r13;
1370         pcb->pcb_r14 = tf->tf_r14;
1371         pcb->pcb_r15 = tf->tf_r15;
1372         pcb->pcb_rbp = tf->tf_rbp;
1373         pcb->pcb_rbx = tf->tf_rbx;
1374         pcb->pcb_rip = tf->tf_rip;
1375         pcb->pcb_rsp = (ISPL(tf->tf_cs)) ? tf->tf_rsp : (long)(tf + 1) - 8;
1376 }
1377
1378 int
1379 ptrace_set_pc(struct thread *td, unsigned long addr)
1380 {
1381         td->td_frame->tf_rip = addr;
1382         return (0);
1383 }
1384
1385 int
1386 ptrace_single_step(struct thread *td)
1387 {
1388         td->td_frame->tf_rflags |= PSL_T;
1389         return (0);
1390 }
1391
1392 int
1393 ptrace_clear_single_step(struct thread *td)
1394 {
1395         td->td_frame->tf_rflags &= ~PSL_T;
1396         return (0);
1397 }
1398
1399 int
1400 fill_regs(struct thread *td, struct reg *regs)
1401 {
1402         struct trapframe *tp;
1403
1404         tp = td->td_frame;
1405         regs->r_r15 = tp->tf_r15;
1406         regs->r_r14 = tp->tf_r14;
1407         regs->r_r13 = tp->tf_r13;
1408         regs->r_r12 = tp->tf_r12;
1409         regs->r_r11 = tp->tf_r11;
1410         regs->r_r10 = tp->tf_r10;
1411         regs->r_r9  = tp->tf_r9;
1412         regs->r_r8  = tp->tf_r8;
1413         regs->r_rdi = tp->tf_rdi;
1414         regs->r_rsi = tp->tf_rsi;
1415         regs->r_rbp = tp->tf_rbp;
1416         regs->r_rbx = tp->tf_rbx;
1417         regs->r_rdx = tp->tf_rdx;
1418         regs->r_rcx = tp->tf_rcx;
1419         regs->r_rax = tp->tf_rax;
1420         regs->r_rip = tp->tf_rip;
1421         regs->r_cs = tp->tf_cs;
1422         regs->r_rflags = tp->tf_rflags;
1423         regs->r_rsp = tp->tf_rsp;
1424         regs->r_ss = tp->tf_ss;
1425         return (0);
1426 }
1427
1428 int
1429 set_regs(struct thread *td, struct reg *regs)
1430 {
1431         struct trapframe *tp;
1432         register_t rflags;
1433
1434         tp = td->td_frame;
1435         rflags = regs->r_rflags & 0xffffffff;
1436         if (!EFL_SECURE(rflags, tp->tf_rflags) || !CS_SECURE(regs->r_cs))
1437                 return (EINVAL);
1438         tp->tf_r15 = regs->r_r15;
1439         tp->tf_r14 = regs->r_r14;
1440         tp->tf_r13 = regs->r_r13;
1441         tp->tf_r12 = regs->r_r12;
1442         tp->tf_r11 = regs->r_r11;
1443         tp->tf_r10 = regs->r_r10;
1444         tp->tf_r9  = regs->r_r9;
1445         tp->tf_r8  = regs->r_r8;
1446         tp->tf_rdi = regs->r_rdi;
1447         tp->tf_rsi = regs->r_rsi;
1448         tp->tf_rbp = regs->r_rbp;
1449         tp->tf_rbx = regs->r_rbx;
1450         tp->tf_rdx = regs->r_rdx;
1451         tp->tf_rcx = regs->r_rcx;
1452         tp->tf_rax = regs->r_rax;
1453         tp->tf_rip = regs->r_rip;
1454         tp->tf_cs = regs->r_cs;
1455         tp->tf_rflags = rflags;
1456         tp->tf_rsp = regs->r_rsp;
1457         tp->tf_ss = regs->r_ss;
1458         td->td_pcb->pcb_flags |= PCB_FULLCTX;
1459         return (0);
1460 }
1461
1462 /* XXX check all this stuff! */
1463 /* externalize from sv_xmm */
1464 static void
1465 fill_fpregs_xmm(struct savefpu *sv_xmm, struct fpreg *fpregs)
1466 {
1467         struct envxmm *penv_fpreg = (struct envxmm *)&fpregs->fpr_env;
1468         struct envxmm *penv_xmm = &sv_xmm->sv_env;
1469         int i;
1470
1471         /* pcb -> fpregs */
1472         bzero(fpregs, sizeof(*fpregs));
1473
1474         /* FPU control/status */
1475         penv_fpreg->en_cw = penv_xmm->en_cw;
1476         penv_fpreg->en_sw = penv_xmm->en_sw;
1477         penv_fpreg->en_tw = penv_xmm->en_tw;
1478         penv_fpreg->en_opcode = penv_xmm->en_opcode;
1479         penv_fpreg->en_rip = penv_xmm->en_rip;
1480         penv_fpreg->en_rdp = penv_xmm->en_rdp;
1481         penv_fpreg->en_mxcsr = penv_xmm->en_mxcsr;
1482         penv_fpreg->en_mxcsr_mask = penv_xmm->en_mxcsr_mask;
1483
1484         /* FPU registers */
1485         for (i = 0; i < 8; ++i)
1486                 bcopy(sv_xmm->sv_fp[i].fp_acc.fp_bytes, fpregs->fpr_acc[i], 10);
1487
1488         /* SSE registers */
1489         for (i = 0; i < 16; ++i)
1490                 bcopy(sv_xmm->sv_xmm[i].xmm_bytes, fpregs->fpr_xacc[i], 16);
1491 }
1492
1493 /* internalize from fpregs into sv_xmm */
1494 static void
1495 set_fpregs_xmm(struct fpreg *fpregs, struct savefpu *sv_xmm)
1496 {
1497         struct envxmm *penv_xmm = &sv_xmm->sv_env;
1498         struct envxmm *penv_fpreg = (struct envxmm *)&fpregs->fpr_env;
1499         int i;
1500
1501         /* fpregs -> pcb */
1502         /* FPU control/status */
1503         penv_xmm->en_cw = penv_fpreg->en_cw;
1504         penv_xmm->en_sw = penv_fpreg->en_sw;
1505         penv_xmm->en_tw = penv_fpreg->en_tw;
1506         penv_xmm->en_opcode = penv_fpreg->en_opcode;
1507         penv_xmm->en_rip = penv_fpreg->en_rip;
1508         penv_xmm->en_rdp = penv_fpreg->en_rdp;
1509         penv_xmm->en_mxcsr = penv_fpreg->en_mxcsr;
1510         penv_xmm->en_mxcsr_mask = penv_fpreg->en_mxcsr_mask & cpu_mxcsr_mask;
1511
1512         /* FPU registers */
1513         for (i = 0; i < 8; ++i)
1514                 bcopy(fpregs->fpr_acc[i], sv_xmm->sv_fp[i].fp_acc.fp_bytes, 10);
1515
1516         /* SSE registers */
1517         for (i = 0; i < 16; ++i)
1518                 bcopy(fpregs->fpr_xacc[i], sv_xmm->sv_xmm[i].xmm_bytes, 16);
1519 }
1520
1521 /* externalize from td->pcb */
1522 int
1523 fill_fpregs(struct thread *td, struct fpreg *fpregs)
1524 {
1525
1526         fill_fpregs_xmm(&td->td_pcb->pcb_save, fpregs);
1527         return (0);
1528 }
1529
1530 /* internalize to td->pcb */
1531 int
1532 set_fpregs(struct thread *td, struct fpreg *fpregs)
1533 {
1534
1535         set_fpregs_xmm(fpregs, &td->td_pcb->pcb_save);
1536         return (0);
1537 }
1538
1539 /*
1540  * Get machine context.
1541  */
1542 int
1543 get_mcontext(struct thread *td, mcontext_t *mcp, int flags)
1544 {
1545         struct trapframe *tp;
1546
1547         tp = td->td_frame;
1548         PROC_LOCK(curthread->td_proc);
1549         mcp->mc_onstack = sigonstack(tp->tf_rsp);
1550         PROC_UNLOCK(curthread->td_proc);
1551         mcp->mc_r15 = tp->tf_r15;
1552         mcp->mc_r14 = tp->tf_r14;
1553         mcp->mc_r13 = tp->tf_r13;
1554         mcp->mc_r12 = tp->tf_r12;
1555         mcp->mc_r11 = tp->tf_r11;
1556         mcp->mc_r10 = tp->tf_r10;
1557         mcp->mc_r9  = tp->tf_r9;
1558         mcp->mc_r8  = tp->tf_r8;
1559         mcp->mc_rdi = tp->tf_rdi;
1560         mcp->mc_rsi = tp->tf_rsi;
1561         mcp->mc_rbp = tp->tf_rbp;
1562         mcp->mc_rbx = tp->tf_rbx;
1563         mcp->mc_rcx = tp->tf_rcx;
1564         mcp->mc_rflags = tp->tf_rflags;
1565         if (flags & GET_MC_CLEAR_RET) {
1566                 mcp->mc_rax = 0;
1567                 mcp->mc_rdx = 0;
1568                 mcp->mc_rflags &= ~PSL_C;
1569         } else {
1570                 mcp->mc_rax = tp->tf_rax;
1571                 mcp->mc_rdx = tp->tf_rdx;
1572         }
1573         mcp->mc_rip = tp->tf_rip;
1574         mcp->mc_cs = tp->tf_cs;
1575         mcp->mc_rsp = tp->tf_rsp;
1576         mcp->mc_ss = tp->tf_ss;
1577         mcp->mc_len = sizeof(*mcp);
1578         get_fpcontext(td, mcp);
1579         return (0);
1580 }
1581
1582 /*
1583  * Set machine context.
1584  *
1585  * However, we don't set any but the user modifiable flags, and we won't
1586  * touch the cs selector.
1587  */
1588 int
1589 set_mcontext(struct thread *td, const mcontext_t *mcp)
1590 {
1591         struct trapframe *tp;
1592         long rflags;
1593         int ret;
1594
1595         tp = td->td_frame;
1596         if (mcp->mc_len != sizeof(*mcp))
1597                 return (EINVAL);
1598         rflags = (mcp->mc_rflags & PSL_USERCHANGE) |
1599             (tp->tf_rflags & ~PSL_USERCHANGE);
1600         ret = set_fpcontext(td, mcp);
1601         if (ret != 0)
1602                 return (ret);
1603         tp->tf_r15 = mcp->mc_r15;
1604         tp->tf_r14 = mcp->mc_r14;
1605         tp->tf_r13 = mcp->mc_r13;
1606         tp->tf_r12 = mcp->mc_r12;
1607         tp->tf_r11 = mcp->mc_r11;
1608         tp->tf_r10 = mcp->mc_r10;
1609         tp->tf_r9  = mcp->mc_r9;
1610         tp->tf_r8  = mcp->mc_r8;
1611         tp->tf_rdi = mcp->mc_rdi;
1612         tp->tf_rsi = mcp->mc_rsi;
1613         tp->tf_rbp = mcp->mc_rbp;
1614         tp->tf_rbx = mcp->mc_rbx;
1615         tp->tf_rdx = mcp->mc_rdx;
1616         tp->tf_rcx = mcp->mc_rcx;
1617         tp->tf_rax = mcp->mc_rax;
1618         tp->tf_rip = mcp->mc_rip;
1619         tp->tf_rflags = rflags;
1620         tp->tf_rsp = mcp->mc_rsp;
1621         tp->tf_ss = mcp->mc_ss;
1622         td->td_pcb->pcb_flags |= PCB_FULLCTX;
1623         return (0);
1624 }
1625
1626 static void
1627 get_fpcontext(struct thread *td, mcontext_t *mcp)
1628 {
1629
1630         mcp->mc_ownedfp = fpugetregs(td, (struct savefpu *)&mcp->mc_fpstate);
1631         mcp->mc_fpformat = fpuformat();
1632 }
1633
1634 static int
1635 set_fpcontext(struct thread *td, const mcontext_t *mcp)
1636 {
1637         struct savefpu *fpstate;
1638
1639         if (mcp->mc_fpformat == _MC_FPFMT_NODEV)
1640                 return (0);
1641         else if (mcp->mc_fpformat != _MC_FPFMT_XMM)
1642                 return (EINVAL);
1643         else if (mcp->mc_ownedfp == _MC_FPOWNED_NONE)
1644                 /* We don't care what state is left in the FPU or PCB. */
1645                 fpstate_drop(td);
1646         else if (mcp->mc_ownedfp == _MC_FPOWNED_FPU ||
1647             mcp->mc_ownedfp == _MC_FPOWNED_PCB) {
1648                 /*
1649                  * XXX we violate the dubious requirement that fpusetregs()
1650                  * be called with interrupts disabled.
1651                  * XXX obsolete on trap-16 systems?
1652                  */
1653                 fpstate = (struct savefpu *)&mcp->mc_fpstate;
1654                 fpstate->sv_env.en_mxcsr &= cpu_mxcsr_mask;
1655                 fpusetregs(td, fpstate);
1656         } else
1657                 return (EINVAL);
1658         return (0);
1659 }
1660
1661 void
1662 fpstate_drop(struct thread *td)
1663 {
1664         register_t s;
1665
1666         s = intr_disable();
1667         if (PCPU_GET(fpcurthread) == td)
1668                 fpudrop();
1669         /*
1670          * XXX force a full drop of the fpu.  The above only drops it if we
1671          * owned it.
1672          *
1673          * XXX I don't much like fpugetregs()'s semantics of doing a full
1674          * drop.  Dropping only to the pcb matches fnsave's behaviour.
1675          * We only need to drop to !PCB_INITDONE in sendsig().  But
1676          * sendsig() is the only caller of fpugetregs()... perhaps we just
1677          * have too many layers.
1678          */
1679         curthread->td_pcb->pcb_flags &= ~PCB_FPUINITDONE;
1680         intr_restore(s);
1681 }
1682
1683 int
1684 fill_dbregs(struct thread *td, struct dbreg *dbregs)
1685 {
1686         struct pcb *pcb;
1687
1688         if (td == NULL) {
1689                 dbregs->dr[0] = rdr0();
1690                 dbregs->dr[1] = rdr1();
1691                 dbregs->dr[2] = rdr2();
1692                 dbregs->dr[3] = rdr3();
1693                 dbregs->dr[6] = rdr6();
1694                 dbregs->dr[7] = rdr7();
1695         } else {
1696                 pcb = td->td_pcb;
1697                 dbregs->dr[0] = pcb->pcb_dr0;
1698                 dbregs->dr[1] = pcb->pcb_dr1;
1699                 dbregs->dr[2] = pcb->pcb_dr2;
1700                 dbregs->dr[3] = pcb->pcb_dr3;
1701                 dbregs->dr[6] = pcb->pcb_dr6;
1702                 dbregs->dr[7] = pcb->pcb_dr7;
1703         }
1704         dbregs->dr[4] = 0;
1705         dbregs->dr[5] = 0;
1706         dbregs->dr[8] = 0;
1707         dbregs->dr[9] = 0;
1708         dbregs->dr[10] = 0;
1709         dbregs->dr[11] = 0;
1710         dbregs->dr[12] = 0;
1711         dbregs->dr[13] = 0;
1712         dbregs->dr[14] = 0;
1713         dbregs->dr[15] = 0;
1714         return (0);
1715 }
1716
1717 int
1718 set_dbregs(struct thread *td, struct dbreg *dbregs)
1719 {
1720         struct pcb *pcb;
1721         int i;
1722         u_int64_t mask1, mask2;
1723
1724         if (td == NULL) {
1725                 load_dr0(dbregs->dr[0]);
1726                 load_dr1(dbregs->dr[1]);
1727                 load_dr2(dbregs->dr[2]);
1728                 load_dr3(dbregs->dr[3]);
1729                 load_dr6(dbregs->dr[6]);
1730                 load_dr7(dbregs->dr[7]);
1731         } else {
1732                 /*
1733                  * Don't let an illegal value for dr7 get set.  Specifically,
1734                  * check for undefined settings.  Setting these bit patterns
1735                  * result in undefined behaviour and can lead to an unexpected
1736                  * TRCTRAP or a general protection fault right here.
1737                  * Upper bits of dr6 and dr7 must not be set
1738                  */
1739                 for (i = 0, mask1 = 0x3<<16, mask2 = 0x2<<16; i < 8;
1740                      i++, mask1 <<= 2, mask2 <<= 2)
1741                         if ((dbregs->dr[7] & mask1) == mask2)
1742                                 return (EINVAL);
1743                 if ((dbregs->dr[6] & 0xffffffff00000000ul) != 0 ||
1744                     (dbregs->dr[7] & 0xffffffff00000000ul) != 0)
1745                         return (EINVAL);
1746
1747                 pcb = td->td_pcb;
1748
1749                 /*
1750                  * Don't let a process set a breakpoint that is not within the
1751                  * process's address space.  If a process could do this, it
1752                  * could halt the system by setting a breakpoint in the kernel
1753                  * (if ddb was enabled).  Thus, we need to check to make sure
1754                  * that no breakpoints are being enabled for addresses outside
1755                  * process's address space.
1756                  *
1757                  * XXX - what about when the watched area of the user's
1758                  * address space is written into from within the kernel
1759                  * ... wouldn't that still cause a breakpoint to be generated
1760                  * from within kernel mode?
1761                  */
1762
1763                 if (dbregs->dr[7] & 0x3) {
1764                         /* dr0 is enabled */
1765                         if (dbregs->dr[0] >= VM_MAXUSER_ADDRESS)
1766                                 return (EINVAL);
1767                 }
1768                 if (dbregs->dr[7] & 0x3<<2) {
1769                         /* dr1 is enabled */
1770                         if (dbregs->dr[1] >= VM_MAXUSER_ADDRESS)
1771                                 return (EINVAL);
1772                 }
1773                 if (dbregs->dr[7] & 0x3<<4) {
1774                         /* dr2 is enabled */
1775                         if (dbregs->dr[2] >= VM_MAXUSER_ADDRESS)
1776                                 return (EINVAL);
1777                 }
1778                 if (dbregs->dr[7] & 0x3<<6) {
1779                         /* dr3 is enabled */
1780                         if (dbregs->dr[3] >= VM_MAXUSER_ADDRESS)
1781                                 return (EINVAL);
1782                 }
1783
1784                 pcb->pcb_dr0 = dbregs->dr[0];
1785                 pcb->pcb_dr1 = dbregs->dr[1];
1786                 pcb->pcb_dr2 = dbregs->dr[2];
1787                 pcb->pcb_dr3 = dbregs->dr[3];
1788                 pcb->pcb_dr6 = dbregs->dr[6];
1789                 pcb->pcb_dr7 = dbregs->dr[7];
1790
1791                 pcb->pcb_flags |= PCB_DBREGS;
1792         }
1793
1794         return (0);
1795 }
1796
1797 void
1798 reset_dbregs(void)
1799 {
1800
1801         load_dr7(0);    /* Turn off the control bits first */
1802         load_dr0(0);
1803         load_dr1(0);
1804         load_dr2(0);
1805         load_dr3(0);
1806         load_dr6(0);
1807 }
1808
1809 /*
1810  * Return > 0 if a hardware breakpoint has been hit, and the
1811  * breakpoint was in user space.  Return 0, otherwise.
1812  */
1813 int
1814 user_dbreg_trap(void)
1815 {
1816         u_int64_t dr7, dr6; /* debug registers dr6 and dr7 */
1817         u_int64_t bp;       /* breakpoint bits extracted from dr6 */
1818         int nbp;            /* number of breakpoints that triggered */
1819         caddr_t addr[4];    /* breakpoint addresses */
1820         int i;
1821         
1822         dr7 = rdr7();
1823         if ((dr7 & 0x000000ff) == 0) {
1824                 /*
1825                  * all GE and LE bits in the dr7 register are zero,
1826                  * thus the trap couldn't have been caused by the
1827                  * hardware debug registers
1828                  */
1829                 return 0;
1830         }
1831
1832         nbp = 0;
1833         dr6 = rdr6();
1834         bp = dr6 & 0x0000000f;
1835
1836         if (!bp) {
1837                 /*
1838                  * None of the breakpoint bits are set meaning this
1839                  * trap was not caused by any of the debug registers
1840                  */
1841                 return 0;
1842         }
1843
1844         /*
1845          * at least one of the breakpoints were hit, check to see
1846          * which ones and if any of them are user space addresses
1847          */
1848
1849         if (bp & 0x01) {
1850                 addr[nbp++] = (caddr_t)rdr0();
1851         }
1852         if (bp & 0x02) {
1853                 addr[nbp++] = (caddr_t)rdr1();
1854         }
1855         if (bp & 0x04) {
1856                 addr[nbp++] = (caddr_t)rdr2();
1857         }
1858         if (bp & 0x08) {
1859                 addr[nbp++] = (caddr_t)rdr3();
1860         }
1861
1862         for (i=0; i<nbp; i++) {
1863                 if (addr[i] <
1864                     (caddr_t)VM_MAXUSER_ADDRESS) {
1865                         /*
1866                          * addr[i] is in user space
1867                          */
1868                         return nbp;
1869                 }
1870         }
1871
1872         /*
1873          * None of the breakpoints are in user space.
1874          */
1875         return 0;
1876 }
1877
1878 #ifdef KDB
1879
1880 /*
1881  * Provide inb() and outb() as functions.  They are normally only
1882  * available as macros calling inlined functions, thus cannot be
1883  * called from the debugger.
1884  *
1885  * The actual code is stolen from <machine/cpufunc.h>, and de-inlined.
1886  */
1887
1888 #undef inb
1889 #undef outb
1890
1891 /* silence compiler warnings */
1892 u_char inb(u_int);
1893 void outb(u_int, u_char);
1894
1895 u_char
1896 inb(u_int port)
1897 {
1898         u_char  data;
1899         /*
1900          * We use %%dx and not %1 here because i/o is done at %dx and not at
1901          * %edx, while gcc generates inferior code (movw instead of movl)
1902          * if we tell it to load (u_short) port.
1903          */
1904         __asm __volatile("inb %%dx,%0" : "=a" (data) : "d" (port));
1905         return (data);
1906 }
1907
1908 void
1909 outb(u_int port, u_char data)
1910 {
1911         u_char  al;
1912         /*
1913          * Use an unnecessary assignment to help gcc's register allocator.
1914          * This make a large difference for gcc-1.40 and a tiny difference
1915          * for gcc-2.6.0.  For gcc-1.40, al had to be ``asm("ax")'' for
1916          * best results.  gcc-2.6.0 can't handle this.
1917          */
1918         al = data;
1919         __asm __volatile("outb %0,%%dx" : : "a" (al), "d" (port));
1920 }
1921
1922 #endif /* KDB */