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