x86_64: Allow UP kernel to use LAPIC timer and I/O APIC
[dragonfly.git] / sys / platform / pc64 / x86_64 / machdep.c
1 /*-
2  * Copyright (c) 1982, 1987, 1990 The Regents of the University of California.
3  * Copyright (c) 1992 Terrence R. Lambert.
4  * Copyright (c) 2003 Peter Wemm.
5  * Copyright (c) 2008 The DragonFly Project.
6  * All rights reserved.
7  *
8  * This code is derived from software contributed to Berkeley by
9  * William Jolitz.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  * 3. All advertising materials mentioning features or use of this software
20  *    must display the following acknowledgement:
21  *      This product includes software developed by the University of
22  *      California, Berkeley and its contributors.
23  * 4. Neither the name of the University nor the names of its contributors
24  *    may be used to endorse or promote products derived from this software
25  *    without specific prior written permission.
26  *
27  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
28  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
29  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
30  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
31  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
32  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
33  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
34  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
35  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
36  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
37  * SUCH DAMAGE.
38  *
39  * from: @(#)machdep.c  7.4 (Berkeley) 6/3/91
40  * $FreeBSD: src/sys/i386/i386/machdep.c,v 1.385.2.30 2003/05/31 08:48:05 alc Exp $
41  */
42
43 //#include "use_npx.h"
44 #include "use_isa.h"
45 #include "opt_atalk.h"
46 #include "opt_compat.h"
47 #include "opt_cpu.h"
48 #include "opt_ddb.h"
49 #include "opt_directio.h"
50 #include "opt_inet.h"
51 #include "opt_ipx.h"
52 #include "opt_msgbuf.h"
53 #include "opt_swap.h"
54
55 #include <sys/param.h>
56 #include <sys/systm.h>
57 #include <sys/sysproto.h>
58 #include <sys/signalvar.h>
59 #include <sys/kernel.h>
60 #include <sys/linker.h>
61 #include <sys/malloc.h>
62 #include <sys/proc.h>
63 #include <sys/priv.h>
64 #include <sys/buf.h>
65 #include <sys/reboot.h>
66 #include <sys/mbuf.h>
67 #include <sys/msgbuf.h>
68 #include <sys/sysent.h>
69 #include <sys/sysctl.h>
70 #include <sys/vmmeter.h>
71 #include <sys/bus.h>
72 #include <sys/upcall.h>
73 #include <sys/usched.h>
74 #include <sys/reg.h>
75
76 #include <vm/vm.h>
77 #include <vm/vm_param.h>
78 #include <sys/lock.h>
79 #include <vm/vm_kern.h>
80 #include <vm/vm_object.h>
81 #include <vm/vm_page.h>
82 #include <vm/vm_map.h>
83 #include <vm/vm_pager.h>
84 #include <vm/vm_extern.h>
85
86 #include <sys/thread2.h>
87 #include <sys/mplock2.h>
88
89 #include <sys/user.h>
90 #include <sys/exec.h>
91 #include <sys/cons.h>
92
93 #include <ddb/ddb.h>
94
95 #include <machine/cpu.h>
96 #include <machine/clock.h>
97 #include <machine/specialreg.h>
98 #if JG
99 #include <machine/bootinfo.h>
100 #endif
101 #include <machine/md_var.h>
102 #include <machine/metadata.h>
103 #include <machine/pc/bios.h>
104 #include <machine/pcb_ext.h>            /* pcb.h included via sys/user.h */
105 #include <machine/globaldata.h>         /* CPU_prvspace */
106 #include <machine/smp.h>
107 #ifdef PERFMON
108 #include <machine/perfmon.h>
109 #endif
110 #include <machine/cputypes.h>
111 #include <machine/intr_machdep.h>
112
113 #ifdef OLD_BUS_ARCH
114 #include <bus/isa/isa_device.h>
115 #endif
116 #include <machine_base/isa/isa_intr.h>
117 #include <bus/isa/rtc.h>
118 #include <sys/random.h>
119 #include <sys/ptrace.h>
120 #include <machine/sigframe.h>
121
122 #include <sys/machintr.h>
123 #include <machine_base/icu/icu_abi.h>
124 #include <machine_base/icu/elcr_var.h>
125 #include <machine_base/apic/lapic.h>
126 #include <machine_base/apic/ioapic.h>
127 #include <machine_base/apic/ioapic_abi.h>
128
129 #define PHYSMAP_ENTRIES         10
130
131 extern u_int64_t hammer_time(u_int64_t, u_int64_t);
132
133 extern void printcpuinfo(void); /* XXX header file */
134 extern void identify_cpu(void);
135 #if JG
136 extern void finishidentcpu(void);
137 #endif
138 extern void panicifcpuunsupported(void);
139
140 static void cpu_startup(void *);
141 static void pic_finish(void *);
142 static void cpu_finish(void *);
143
144 #ifndef CPU_DISABLE_SSE
145 static void set_fpregs_xmm(struct save87 *, struct savexmm *);
146 static void fill_fpregs_xmm(struct savexmm *, struct save87 *);
147 #endif /* CPU_DISABLE_SSE */
148 #ifdef DIRECTIO
149 extern void ffs_rawread_setup(void);
150 #endif /* DIRECTIO */
151 static void init_locks(void);
152
153 SYSINIT(cpu, SI_BOOT2_START_CPU, SI_ORDER_FIRST, cpu_startup, NULL)
154 SYSINIT(pic_finish, SI_BOOT2_FINISH_PIC, SI_ORDER_FIRST, pic_finish, NULL)
155 SYSINIT(cpu_finish, SI_BOOT2_FINISH_CPU, SI_ORDER_FIRST, cpu_finish, NULL)
156
157 #ifdef DDB
158 extern vm_offset_t ksym_start, ksym_end;
159 #endif
160
161 struct privatespace CPU_prvspace[MAXCPU] __aligned(4096); /* XXX */
162
163 int     _udatasel, _ucodesel, _ucode32sel;
164 u_long  atdevbase;
165 #ifdef SMP
166 int64_t tsc_offsets[MAXCPU];
167 #else
168 int64_t tsc_offsets[1];
169 #endif
170
171 #if defined(SWTCH_OPTIM_STATS)
172 extern int swtch_optim_stats;
173 SYSCTL_INT(_debug, OID_AUTO, swtch_optim_stats,
174         CTLFLAG_RD, &swtch_optim_stats, 0, "");
175 SYSCTL_INT(_debug, OID_AUTO, tlb_flush_count,
176         CTLFLAG_RD, &tlb_flush_count, 0, "");
177 #endif
178
179 long physmem = 0;
180
181 u_long ebda_addr = 0;
182
183 int imcr_present = 0;
184
185 int naps = 0; /* # of Applications processors */
186
187 u_int base_memory;
188
189 static int
190 sysctl_hw_physmem(SYSCTL_HANDLER_ARGS)
191 {
192         u_long pmem = ctob(physmem);
193
194         int error = sysctl_handle_long(oidp, &pmem, 0, req);
195         return (error);
196 }
197
198 SYSCTL_PROC(_hw, HW_PHYSMEM, physmem, CTLTYPE_ULONG|CTLFLAG_RD,
199         0, 0, sysctl_hw_physmem, "LU", "Total system memory in bytes (number of pages * page size)");
200
201 static int
202 sysctl_hw_usermem(SYSCTL_HANDLER_ARGS)
203 {
204         int error = sysctl_handle_int(oidp, 0,
205                 ctob(physmem - vmstats.v_wire_count), req);
206         return (error);
207 }
208
209 SYSCTL_PROC(_hw, HW_USERMEM, usermem, CTLTYPE_INT|CTLFLAG_RD,
210         0, 0, sysctl_hw_usermem, "IU", "");
211
212 static int
213 sysctl_hw_availpages(SYSCTL_HANDLER_ARGS)
214 {
215         int error = sysctl_handle_int(oidp, 0,
216                 x86_64_btop(avail_end - avail_start), req);
217         return (error);
218 }
219
220 SYSCTL_PROC(_hw, OID_AUTO, availpages, CTLTYPE_INT|CTLFLAG_RD,
221         0, 0, sysctl_hw_availpages, "I", "");
222
223 vm_paddr_t Maxmem;
224 vm_paddr_t Realmem;
225
226 /*
227  * The number of PHYSMAP entries must be one less than the number of
228  * PHYSSEG entries because the PHYSMAP entry that spans the largest
229  * physical address that is accessible by ISA DMA is split into two
230  * PHYSSEG entries.
231  */
232 #define PHYSMAP_SIZE    (2 * (VM_PHYSSEG_MAX - 1))
233
234 vm_paddr_t phys_avail[PHYSMAP_SIZE + 2];
235 vm_paddr_t dump_avail[PHYSMAP_SIZE + 2];
236
237 /* must be 2 less so 0 0 can signal end of chunks */
238 #define PHYS_AVAIL_ARRAY_END (NELEM(phys_avail) - 2)
239 #define DUMP_AVAIL_ARRAY_END (NELEM(dump_avail) - 2)
240
241 static vm_offset_t buffer_sva, buffer_eva;
242 vm_offset_t clean_sva, clean_eva;
243 static vm_offset_t pager_sva, pager_eva;
244 static struct trapframe proc0_tf;
245
246 static void
247 cpu_startup(void *dummy)
248 {
249         caddr_t v;
250         vm_size_t size = 0;
251         vm_offset_t firstaddr;
252
253         /*
254          * Good {morning,afternoon,evening,night}.
255          */
256         kprintf("%s", version);
257         startrtclock();
258         printcpuinfo();
259         panicifcpuunsupported();
260 #ifdef PERFMON
261         perfmon_init();
262 #endif
263         kprintf("real memory  = %ju (%ju MB)\n",
264                 (intmax_t)Realmem,
265                 (intmax_t)Realmem / 1024 / 1024);
266         /*
267          * Display any holes after the first chunk of extended memory.
268          */
269         if (bootverbose) {
270                 int indx;
271
272                 kprintf("Physical memory chunk(s):\n");
273                 for (indx = 0; phys_avail[indx + 1] != 0; indx += 2) {
274                         vm_paddr_t size1 = phys_avail[indx + 1] - phys_avail[indx];
275
276                         kprintf("0x%08jx - 0x%08jx, %ju bytes (%ju pages)\n",
277                                 (intmax_t)phys_avail[indx],
278                                 (intmax_t)phys_avail[indx + 1] - 1,
279                                 (intmax_t)size1,
280                                 (intmax_t)(size1 / PAGE_SIZE));
281                 }
282         }
283
284         /*
285          * Allocate space for system data structures.
286          * The first available kernel virtual address is in "v".
287          * As pages of kernel virtual memory are allocated, "v" is incremented.
288          * As pages of memory are allocated and cleared,
289          * "firstaddr" is incremented.
290          * An index into the kernel page table corresponding to the
291          * virtual memory address maintained in "v" is kept in "mapaddr".
292          */
293
294         /*
295          * Make two passes.  The first pass calculates how much memory is
296          * needed and allocates it.  The second pass assigns virtual
297          * addresses to the various data structures.
298          */
299         firstaddr = 0;
300 again:
301         v = (caddr_t)firstaddr;
302
303 #define valloc(name, type, num) \
304             (name) = (type *)v; v = (caddr_t)((name)+(num))
305 #define valloclim(name, type, num, lim) \
306             (name) = (type *)v; v = (caddr_t)((lim) = ((name)+(num)))
307
308         /*
309          * The nominal buffer size (and minimum KVA allocation) is BKVASIZE.
310          * For the first 64MB of ram nominally allocate sufficient buffers to
311          * cover 1/4 of our ram.  Beyond the first 64MB allocate additional
312          * buffers to cover 1/20 of our ram over 64MB.  When auto-sizing
313          * the buffer cache we limit the eventual kva reservation to
314          * maxbcache bytes.
315          *
316          * factor represents the 1/4 x ram conversion.
317          */
318         if (nbuf == 0) {
319                 int factor = 4 * BKVASIZE / 1024;
320                 int kbytes = physmem * (PAGE_SIZE / 1024);
321
322                 nbuf = 50;
323                 if (kbytes > 4096)
324                         nbuf += min((kbytes - 4096) / factor, 65536 / factor);
325                 if (kbytes > 65536)
326                         nbuf += (kbytes - 65536) * 2 / (factor * 5);
327                 if (maxbcache && nbuf > maxbcache / BKVASIZE)
328                         nbuf = maxbcache / BKVASIZE;
329         }
330
331         /*
332          * Do not allow the buffer_map to be more then 1/2 the size of the
333          * kernel_map.
334          */
335         if (nbuf > (virtual_end - virtual_start) / (BKVASIZE * 2)) {
336                 nbuf = (virtual_end - virtual_start) / (BKVASIZE * 2);
337                 kprintf("Warning: nbufs capped at %d\n", nbuf);
338         }
339
340         nswbuf = max(min(nbuf/4, 256), 16);
341 #ifdef NSWBUF_MIN
342         if (nswbuf < NSWBUF_MIN)
343                 nswbuf = NSWBUF_MIN;
344 #endif
345 #ifdef DIRECTIO
346         ffs_rawread_setup();
347 #endif
348
349         valloc(swbuf, struct buf, nswbuf);
350         valloc(buf, struct buf, nbuf);
351
352         /*
353          * End of first pass, size has been calculated so allocate memory
354          */
355         if (firstaddr == 0) {
356                 size = (vm_size_t)(v - firstaddr);
357                 firstaddr = kmem_alloc(&kernel_map, round_page(size));
358                 if (firstaddr == 0)
359                         panic("startup: no room for tables");
360                 goto again;
361         }
362
363         /*
364          * End of second pass, addresses have been assigned
365          */
366         if ((vm_size_t)(v - firstaddr) != size)
367                 panic("startup: table size inconsistency");
368
369         kmem_suballoc(&kernel_map, &clean_map, &clean_sva, &clean_eva,
370                       (nbuf*BKVASIZE) + (nswbuf*MAXPHYS) + pager_map_size);
371         kmem_suballoc(&clean_map, &buffer_map, &buffer_sva, &buffer_eva,
372                       (nbuf*BKVASIZE));
373         buffer_map.system_map = 1;
374         kmem_suballoc(&clean_map, &pager_map, &pager_sva, &pager_eva,
375                       (nswbuf*MAXPHYS) + pager_map_size);
376         pager_map.system_map = 1;
377
378 #if defined(USERCONFIG)
379         userconfig();
380         cninit();               /* the preferred console may have changed */
381 #endif
382
383         kprintf("avail memory = %ju (%ju MB)\n",
384                 (uintmax_t)ptoa(vmstats.v_free_count),
385                 (uintmax_t)ptoa(vmstats.v_free_count) / 1024 / 1024);
386
387         /*
388          * Set up buffers, so they can be used to read disk labels.
389          */
390         bufinit();
391         vm_pager_bufferinit();
392 }
393
394 static void
395 cpu_finish(void *dummy __unused)
396 {
397         cpu_setregs();
398 }
399
400 static void
401 pic_finish(void *dummy __unused)
402 {
403         /* Log ELCR information */
404         elcr_dump();
405
406         /* Finalize PCI */
407         MachIntrABI.finalize();
408 }
409
410 /*
411  * Send an interrupt to process.
412  *
413  * Stack is set up to allow sigcode stored
414  * at top to call routine, followed by kcall
415  * to sigreturn routine below.  After sigreturn
416  * resets the signal mask, the stack, and the
417  * frame pointer, it returns to the user
418  * specified pc, psl.
419  */
420 void
421 sendsig(sig_t catcher, int sig, sigset_t *mask, u_long code)
422 {
423         struct lwp *lp = curthread->td_lwp;
424         struct proc *p = lp->lwp_proc;
425         struct trapframe *regs;
426         struct sigacts *psp = p->p_sigacts;
427         struct sigframe sf, *sfp;
428         int oonstack;
429         char *sp;
430
431         regs = lp->lwp_md.md_regs;
432         oonstack = (lp->lwp_sigstk.ss_flags & SS_ONSTACK) ? 1 : 0;
433
434         /* Save user context */
435         bzero(&sf, sizeof(struct sigframe));
436         sf.sf_uc.uc_sigmask = *mask;
437         sf.sf_uc.uc_stack = lp->lwp_sigstk;
438         sf.sf_uc.uc_mcontext.mc_onstack = oonstack;
439         KKASSERT(__offsetof(struct trapframe, tf_rdi) == 0);
440         bcopy(regs, &sf.sf_uc.uc_mcontext.mc_rdi, sizeof(struct trapframe));
441
442         /* Make the size of the saved context visible to userland */
443         sf.sf_uc.uc_mcontext.mc_len = sizeof(sf.sf_uc.uc_mcontext);
444
445         /* Save mailbox pending state for syscall interlock semantics */
446         if (p->p_flag & P_MAILBOX)
447                 sf.sf_uc.uc_mcontext.mc_xflags |= PGEX_MAILBOX;
448
449         /* Allocate and validate space for the signal handler context. */
450         if ((lp->lwp_flag & LWP_ALTSTACK) != 0 && !oonstack &&
451             SIGISMEMBER(psp->ps_sigonstack, sig)) {
452                 sp = (char *)(lp->lwp_sigstk.ss_sp + lp->lwp_sigstk.ss_size -
453                               sizeof(struct sigframe));
454                 lp->lwp_sigstk.ss_flags |= SS_ONSTACK;
455         } else {
456                 /* We take red zone into account */
457                 sp = (char *)regs->tf_rsp - sizeof(struct sigframe) - 128;
458         }
459
460         /* Align to 16 bytes */
461         sfp = (struct sigframe *)((intptr_t)sp & ~(intptr_t)0xF);
462
463         /* Translate the signal is appropriate */
464         if (p->p_sysent->sv_sigtbl) {
465                 if (sig <= p->p_sysent->sv_sigsize)
466                         sig = p->p_sysent->sv_sigtbl[_SIG_IDX(sig)];
467         }
468
469         /*
470          * Build the argument list for the signal handler.
471          *
472          * Arguments are in registers (%rdi, %rsi, %rdx, %rcx)
473          */
474         regs->tf_rdi = sig;                             /* argument 1 */
475         regs->tf_rdx = (register_t)&sfp->sf_uc;         /* argument 3 */
476
477         if (SIGISMEMBER(psp->ps_siginfo, sig)) {
478                 /*
479                  * Signal handler installed with SA_SIGINFO.
480                  *
481                  * action(signo, siginfo, ucontext)
482                  */
483                 regs->tf_rsi = (register_t)&sfp->sf_si; /* argument 2 */
484                 regs->tf_rcx = (register_t)regs->tf_addr; /* argument 4 */
485                 sf.sf_ahu.sf_action = (__siginfohandler_t *)catcher;
486
487                 /* fill siginfo structure */
488                 sf.sf_si.si_signo = sig;
489                 sf.sf_si.si_code = code;
490                 sf.sf_si.si_addr = (void *)regs->tf_addr;
491         } else {
492                 /*
493                  * Old FreeBSD-style arguments.
494                  *
495                  * handler (signo, code, [uc], addr)
496                  */
497                 regs->tf_rsi = (register_t)code;        /* argument 2 */
498                 regs->tf_rcx = (register_t)regs->tf_addr; /* argument 4 */
499                 sf.sf_ahu.sf_handler = catcher;
500         }
501
502         /*
503          * If we're a vm86 process, we want to save the segment registers.
504          * We also change eflags to be our emulated eflags, not the actual
505          * eflags.
506          */
507 #if JG
508         if (regs->tf_eflags & PSL_VM) {
509                 struct trapframe_vm86 *tf = (struct trapframe_vm86 *)regs;
510                 struct vm86_kernel *vm86 = &lp->lwp_thread->td_pcb->pcb_ext->ext_vm86;
511
512                 sf.sf_uc.uc_mcontext.mc_gs = tf->tf_vm86_gs;
513                 sf.sf_uc.uc_mcontext.mc_fs = tf->tf_vm86_fs;
514                 sf.sf_uc.uc_mcontext.mc_es = tf->tf_vm86_es;
515                 sf.sf_uc.uc_mcontext.mc_ds = tf->tf_vm86_ds;
516
517                 if (vm86->vm86_has_vme == 0)
518                         sf.sf_uc.uc_mcontext.mc_eflags =
519                             (tf->tf_eflags & ~(PSL_VIF | PSL_VIP)) |
520                             (vm86->vm86_eflags & (PSL_VIF | PSL_VIP));
521
522                 /*
523                  * Clear PSL_NT to inhibit T_TSSFLT faults on return from
524                  * syscalls made by the signal handler.  This just avoids
525                  * wasting time for our lazy fixup of such faults.  PSL_NT
526                  * does nothing in vm86 mode, but vm86 programs can set it
527                  * almost legitimately in probes for old cpu types.
528                  */
529                 tf->tf_eflags &= ~(PSL_VM | PSL_NT | PSL_VIF | PSL_VIP);
530         }
531 #endif
532
533         /*
534          * Save the FPU state and reinit the FP unit
535          */
536         npxpush(&sf.sf_uc.uc_mcontext);
537
538         /*
539          * Copy the sigframe out to the user's stack.
540          */
541         if (copyout(&sf, sfp, sizeof(struct sigframe)) != 0) {
542                 /*
543                  * Something is wrong with the stack pointer.
544                  * ...Kill the process.
545                  */
546                 sigexit(lp, SIGILL);
547         }
548
549         regs->tf_rsp = (register_t)sfp;
550         regs->tf_rip = PS_STRINGS - *(p->p_sysent->sv_szsigcode);
551
552         /*
553          * i386 abi specifies that the direction flag must be cleared
554          * on function entry
555          */
556         regs->tf_rflags &= ~(PSL_T|PSL_D);
557
558         /*
559          * 64 bit mode has a code and stack selector but
560          * no data or extra selector.  %fs and %gs are not
561          * stored in-context.
562          */
563         regs->tf_cs = _ucodesel;
564         regs->tf_ss = _udatasel;
565 }
566
567 /*
568  * Sanitize the trapframe for a virtual kernel passing control to a custom
569  * VM context.  Remove any items that would otherwise create a privilage
570  * issue.
571  *
572  * XXX at the moment we allow userland to set the resume flag.  Is this a
573  * bad idea?
574  */
575 int
576 cpu_sanitize_frame(struct trapframe *frame)
577 {
578         frame->tf_cs = _ucodesel;
579         frame->tf_ss = _udatasel;
580         /* XXX VM (8086) mode not supported? */
581         frame->tf_rflags &= (PSL_RF | PSL_USERCHANGE | PSL_VM_UNSUPP);
582         frame->tf_rflags |= PSL_RESERVED_DEFAULT | PSL_I;
583
584         return(0);
585 }
586
587 /*
588  * Sanitize the tls so loading the descriptor does not blow up
589  * on us.  For x86_64 we don't have to do anything.
590  */
591 int
592 cpu_sanitize_tls(struct savetls *tls)
593 {
594         return(0);
595 }
596
597 /*
598  * sigreturn(ucontext_t *sigcntxp)
599  *
600  * System call to cleanup state after a signal
601  * has been taken.  Reset signal mask and
602  * stack state from context left by sendsig (above).
603  * Return to previous pc and psl as specified by
604  * context left by sendsig. Check carefully to
605  * make sure that the user has not modified the
606  * state to gain improper privileges.
607  *
608  * MPSAFE
609  */
610 #define EFL_SECURE(ef, oef)     ((((ef) ^ (oef)) & ~PSL_USERCHANGE) == 0)
611 #define CS_SECURE(cs)           (ISPL(cs) == SEL_UPL)
612
613 int
614 sys_sigreturn(struct sigreturn_args *uap)
615 {
616         struct lwp *lp = curthread->td_lwp;
617         struct proc *p = lp->lwp_proc;
618         struct trapframe *regs;
619         ucontext_t uc;
620         ucontext_t *ucp;
621         register_t rflags;
622         int cs;
623         int error;
624
625         /*
626          * We have to copy the information into kernel space so userland
627          * can't modify it while we are sniffing it.
628          */
629         regs = lp->lwp_md.md_regs;
630         error = copyin(uap->sigcntxp, &uc, sizeof(uc));
631         if (error)
632                 return (error);
633         ucp = &uc;
634         rflags = ucp->uc_mcontext.mc_rflags;
635
636         /* VM (8086) mode not supported */
637         rflags &= ~PSL_VM_UNSUPP;
638
639 #if JG
640         if (eflags & PSL_VM) {
641                 struct trapframe_vm86 *tf = (struct trapframe_vm86 *)regs;
642                 struct vm86_kernel *vm86;
643
644                 /*
645                  * if pcb_ext == 0 or vm86_inited == 0, the user hasn't
646                  * set up the vm86 area, and we can't enter vm86 mode.
647                  */
648                 if (lp->lwp_thread->td_pcb->pcb_ext == 0)
649                         return (EINVAL);
650                 vm86 = &lp->lwp_thread->td_pcb->pcb_ext->ext_vm86;
651                 if (vm86->vm86_inited == 0)
652                         return (EINVAL);
653
654                 /* go back to user mode if both flags are set */
655                 if ((eflags & PSL_VIP) && (eflags & PSL_VIF))
656                         trapsignal(lp, SIGBUS, 0);
657
658                 if (vm86->vm86_has_vme) {
659                         eflags = (tf->tf_eflags & ~VME_USERCHANGE) |
660                             (eflags & VME_USERCHANGE) | PSL_VM;
661                 } else {
662                         vm86->vm86_eflags = eflags;     /* save VIF, VIP */
663                         eflags = (tf->tf_eflags & ~VM_USERCHANGE) |
664                             (eflags & VM_USERCHANGE) | PSL_VM;
665                 }
666                 bcopy(&ucp->uc_mcontext.mc_gs, tf, sizeof(struct trapframe));
667                 tf->tf_eflags = eflags;
668                 tf->tf_vm86_ds = tf->tf_ds;
669                 tf->tf_vm86_es = tf->tf_es;
670                 tf->tf_vm86_fs = tf->tf_fs;
671                 tf->tf_vm86_gs = tf->tf_gs;
672                 tf->tf_ds = _udatasel;
673                 tf->tf_es = _udatasel;
674                 tf->tf_fs = _udatasel;
675                 tf->tf_gs = _udatasel;
676         } else
677 #endif
678         {
679                 /*
680                  * Don't allow users to change privileged or reserved flags.
681                  */
682                 /*
683                  * XXX do allow users to change the privileged flag PSL_RF.
684                  * The cpu sets PSL_RF in tf_eflags for faults.  Debuggers
685                  * should sometimes set it there too.  tf_eflags is kept in
686                  * the signal context during signal handling and there is no
687                  * other place to remember it, so the PSL_RF bit may be
688                  * corrupted by the signal handler without us knowing.
689                  * Corruption of the PSL_RF bit at worst causes one more or
690                  * one less debugger trap, so allowing it is fairly harmless.
691                  */
692                 if (!EFL_SECURE(rflags & ~PSL_RF, regs->tf_rflags & ~PSL_RF)) {
693                         kprintf("sigreturn: rflags = 0x%lx\n", (long)rflags);
694                         return(EINVAL);
695                 }
696
697                 /*
698                  * Don't allow users to load a valid privileged %cs.  Let the
699                  * hardware check for invalid selectors, excess privilege in
700                  * other selectors, invalid %eip's and invalid %esp's.
701                  */
702                 cs = ucp->uc_mcontext.mc_cs;
703                 if (!CS_SECURE(cs)) {
704                         kprintf("sigreturn: cs = 0x%x\n", cs);
705                         trapsignal(lp, SIGBUS, T_PROTFLT);
706                         return(EINVAL);
707                 }
708                 bcopy(&ucp->uc_mcontext.mc_rdi, regs, sizeof(struct trapframe));
709         }
710
711         /*
712          * Restore the FPU state from the frame
713          */
714         crit_enter();
715         npxpop(&ucp->uc_mcontext);
716
717         /*
718          * Merge saved signal mailbox pending flag to maintain interlock
719          * semantics against system calls.
720          */
721         if (ucp->uc_mcontext.mc_xflags & PGEX_MAILBOX)
722                 p->p_flag |= P_MAILBOX;
723
724         if (ucp->uc_mcontext.mc_onstack & 1)
725                 lp->lwp_sigstk.ss_flags |= SS_ONSTACK;
726         else
727                 lp->lwp_sigstk.ss_flags &= ~SS_ONSTACK;
728
729         lp->lwp_sigmask = ucp->uc_sigmask;
730         SIG_CANTMASK(lp->lwp_sigmask);
731         crit_exit();
732         return(EJUSTRETURN);
733 }
734
735 /*
736  * Stack frame on entry to function.  %rax will contain the function vector,
737  * %rcx will contain the function data.  flags, rcx, and rax will have
738  * already been pushed on the stack.
739  */
740 struct upc_frame {
741         register_t      rax;
742         register_t      rcx;
743         register_t      rdx;
744         register_t      flags;
745         register_t      oldip;
746 };
747
748 void
749 sendupcall(struct vmupcall *vu, int morepending)
750 {
751         struct lwp *lp = curthread->td_lwp;
752         struct trapframe *regs;
753         struct upcall upcall;
754         struct upc_frame upc_frame;
755         int     crit_count = 0;
756
757         /*
758          * If we are a virtual kernel running an emulated user process
759          * context, switch back to the virtual kernel context before
760          * trying to post the signal.
761          */
762         if (lp->lwp_vkernel && lp->lwp_vkernel->ve) {
763                 lp->lwp_md.md_regs->tf_trapno = 0;
764                 vkernel_trap(lp, lp->lwp_md.md_regs);
765         }
766
767         /*
768          * Get the upcall data structure
769          */
770         if (copyin(lp->lwp_upcall, &upcall, sizeof(upcall)) ||
771             copyin((char *)upcall.upc_uthread + upcall.upc_critoff, &crit_count, sizeof(int))
772         ) {
773                 vu->vu_pending = 0;
774                 kprintf("bad upcall address\n");
775                 return;
776         }
777
778         /*
779          * If the data structure is already marked pending or has a critical
780          * section count, mark the data structure as pending and return 
781          * without doing an upcall.  vu_pending is left set.
782          */
783         if (upcall.upc_pending || crit_count >= vu->vu_pending) {
784                 if (upcall.upc_pending < vu->vu_pending) {
785                         upcall.upc_pending = vu->vu_pending;
786                         copyout(&upcall.upc_pending, &lp->lwp_upcall->upc_pending,
787                                 sizeof(upcall.upc_pending));
788                 }
789                 return;
790         }
791
792         /*
793          * We can run this upcall now, clear vu_pending.
794          *
795          * Bump our critical section count and set or clear the
796          * user pending flag depending on whether more upcalls are
797          * pending.  The user will be responsible for calling 
798          * upc_dispatch(-1) to process remaining upcalls.
799          */
800         vu->vu_pending = 0;
801         upcall.upc_pending = morepending;
802         ++crit_count;
803         copyout(&upcall.upc_pending, &lp->lwp_upcall->upc_pending, 
804                 sizeof(upcall.upc_pending));
805         copyout(&crit_count, (char *)upcall.upc_uthread + upcall.upc_critoff,
806                 sizeof(int));
807
808         /*
809          * Construct a stack frame and issue the upcall
810          */
811         regs = lp->lwp_md.md_regs;
812         upc_frame.rax = regs->tf_rax;
813         upc_frame.rcx = regs->tf_rcx;
814         upc_frame.rdx = regs->tf_rdx;
815         upc_frame.flags = regs->tf_rflags;
816         upc_frame.oldip = regs->tf_rip;
817         if (copyout(&upc_frame, (void *)(regs->tf_rsp - sizeof(upc_frame)),
818             sizeof(upc_frame)) != 0) {
819                 kprintf("bad stack on upcall\n");
820         } else {
821                 regs->tf_rax = (register_t)vu->vu_func;
822                 regs->tf_rcx = (register_t)vu->vu_data;
823                 regs->tf_rdx = (register_t)lp->lwp_upcall;
824                 regs->tf_rip = (register_t)vu->vu_ctx;
825                 regs->tf_rsp -= sizeof(upc_frame);
826         }
827 }
828
829 /*
830  * fetchupcall occurs in the context of a system call, which means that
831  * we have to return EJUSTRETURN in order to prevent eax and edx from
832  * being overwritten by the syscall return value.
833  *
834  * if vu is not NULL we return the new context in %edx, the new data in %ecx,
835  * and the function pointer in %eax.  
836  */
837 int
838 fetchupcall(struct vmupcall *vu, int morepending, void *rsp)
839 {
840         struct upc_frame upc_frame;
841         struct lwp *lp = curthread->td_lwp;
842         struct trapframe *regs;
843         int error;
844         struct upcall upcall;
845         int crit_count;
846
847         regs = lp->lwp_md.md_regs;
848
849         error = copyout(&morepending, &lp->lwp_upcall->upc_pending, sizeof(int));
850         if (error == 0) {
851             if (vu) {
852                 /*
853                  * This jumps us to the next ready context.
854                  */
855                 vu->vu_pending = 0;
856                 error = copyin(lp->lwp_upcall, &upcall, sizeof(upcall));
857                 crit_count = 0;
858                 if (error == 0)
859                         error = copyin((char *)upcall.upc_uthread + upcall.upc_critoff, &crit_count, sizeof(int));
860                 ++crit_count;
861                 if (error == 0)
862                         error = copyout(&crit_count, (char *)upcall.upc_uthread + upcall.upc_critoff, sizeof(int));
863                 regs->tf_rax = (register_t)vu->vu_func;
864                 regs->tf_rcx = (register_t)vu->vu_data;
865                 regs->tf_rdx = (register_t)lp->lwp_upcall;
866                 regs->tf_rip = (register_t)vu->vu_ctx;
867                 regs->tf_rsp = (register_t)rsp;
868             } else {
869                 /*
870                  * This returns us to the originally interrupted code.
871                  */
872                 error = copyin(rsp, &upc_frame, sizeof(upc_frame));
873                 regs->tf_rax = upc_frame.rax;
874                 regs->tf_rcx = upc_frame.rcx;
875                 regs->tf_rdx = upc_frame.rdx;
876                 regs->tf_rflags = (regs->tf_rflags & ~PSL_USERCHANGE) |
877                                 (upc_frame.flags & PSL_USERCHANGE);
878                 regs->tf_rip = upc_frame.oldip;
879                 regs->tf_rsp = (register_t)((char *)rsp + sizeof(upc_frame));
880             }
881         }
882         if (error == 0)
883                 error = EJUSTRETURN;
884         return(error);
885 }
886
887 /*
888  * Machine dependent boot() routine
889  *
890  * I haven't seen anything to put here yet
891  * Possibly some stuff might be grafted back here from boot()
892  */
893 void
894 cpu_boot(int howto)
895 {
896 }
897
898 /*
899  * Shutdown the CPU as much as possible
900  */
901 void
902 cpu_halt(void)
903 {
904         for (;;)
905                 __asm__ __volatile("hlt");
906 }
907
908 /*
909  * cpu_idle() represents the idle LWKT.  You cannot return from this function
910  * (unless you want to blow things up!).  Instead we look for runnable threads
911  * and loop or halt as appropriate.  Giant is not held on entry to the thread.
912  *
913  * The main loop is entered with a critical section held, we must release
914  * the critical section before doing anything else.  lwkt_switch() will
915  * check for pending interrupts due to entering and exiting its own 
916  * critical section.
917  *
918  * NOTE: On an SMP system we rely on a scheduler IPI to wake a HLTed cpu up.
919  *       However, there are cases where the idlethread will be entered with
920  *       the possibility that no IPI will occur and in such cases
921  *       lwkt_switch() sets TDF_IDLE_NOHLT.
922  *
923  * NOTE: cpu_idle_hlt again defaults to 2 (use ACPI sleep states).  Set to
924  *       1 to just use hlt and for debugging purposes.
925  *
926  * NOTE: cpu_idle_repeat determines how many entries into the idle thread
927  *       must occur before it starts using ACPI halt.
928  */
929 static int      cpu_idle_hlt = 2;
930 static int      cpu_idle_hltcnt;
931 static int      cpu_idle_spincnt;
932 static u_int    cpu_idle_repeat = 4;
933 SYSCTL_INT(_machdep, OID_AUTO, cpu_idle_hlt, CTLFLAG_RW,
934     &cpu_idle_hlt, 0, "Idle loop HLT enable");
935 SYSCTL_INT(_machdep, OID_AUTO, cpu_idle_hltcnt, CTLFLAG_RW,
936     &cpu_idle_hltcnt, 0, "Idle loop entry halts");
937 SYSCTL_INT(_machdep, OID_AUTO, cpu_idle_spincnt, CTLFLAG_RW,
938     &cpu_idle_spincnt, 0, "Idle loop entry spins");
939 SYSCTL_INT(_machdep, OID_AUTO, cpu_idle_repeat, CTLFLAG_RW,
940     &cpu_idle_repeat, 0, "Idle entries before acpi hlt");
941
942 static void
943 cpu_idle_default_hook(void)
944 {
945         /*
946          * We must guarentee that hlt is exactly the instruction
947          * following the sti.
948          */
949         __asm __volatile("sti; hlt");
950 }
951
952 /* Other subsystems (e.g., ACPI) can hook this later. */
953 void (*cpu_idle_hook)(void) = cpu_idle_default_hook;
954
955 void
956 cpu_idle(void)
957 {
958         globaldata_t gd = mycpu;
959         struct thread *td __debugvar = gd->gd_curthread;
960         int reqflags;
961         int quick;
962
963         crit_exit();
964         KKASSERT(td->td_critcount == 0);
965         for (;;) {
966                 /*
967                  * See if there are any LWKTs ready to go.
968                  */
969                 lwkt_switch();
970
971                 /*
972                  * When halting inside a cli we must check for reqflags
973                  * races, particularly [re]schedule requests.  Running
974                  * splz() does the job.
975                  *
976                  * cpu_idle_hlt:
977                  *      0       Never halt, just spin
978                  *
979                  *      1       Always use HLT (or MONITOR/MWAIT if avail).
980                  *              This typically eats more power than the
981                  *              ACPI halt.
982                  *
983                  *      2       Use HLT/MONITOR/MWAIT up to a point and then
984                  *              use the ACPI halt (default).  This is a hybrid
985                  *              approach.  See machdep.cpu_idle_repeat.
986                  *
987                  *      3       Always use the ACPI halt.  This typically
988                  *              eats the least amount of power but the cpu
989                  *              will be slow waking up.  Slows down e.g.
990                  *              compiles and other pipe/event oriented stuff.
991                  *
992                  * NOTE: Interrupts are enabled and we are not in a critical
993                  *       section.
994                  *
995                  * NOTE: Preemptions do not reset gd_idle_repeat.   Also we
996                  *       don't bother capping gd_idle_repeat, it is ok if
997                  *       it overflows.
998                  */
999                 ++gd->gd_idle_repeat;
1000                 reqflags = gd->gd_reqflags;
1001                 quick = (cpu_idle_hlt == 1) ||
1002                         (cpu_idle_hlt < 3 &&
1003                          gd->gd_idle_repeat < cpu_idle_repeat);
1004
1005                 if (quick && (cpu_mi_feature & CPU_MI_MONITOR) &&
1006                     (reqflags & RQF_IDLECHECK_WK_MASK) == 0) {
1007                         cpu_mmw_pause_int(&gd->gd_reqflags, reqflags);
1008                         ++cpu_idle_hltcnt;
1009                 } else if (cpu_idle_hlt) {
1010                         __asm __volatile("cli");
1011                         splz();
1012                         if ((gd->gd_reqflags & RQF_IDLECHECK_WK_MASK) == 0) {
1013                                 if (quick)
1014                                         cpu_idle_default_hook();
1015                                 else
1016                                         cpu_idle_hook();
1017                         }
1018                         __asm __volatile("sti");
1019                         ++cpu_idle_hltcnt;
1020                 } else {
1021                         splz();
1022                         __asm __volatile("sti");
1023                         ++cpu_idle_spincnt;
1024                 }
1025         }
1026 }
1027
1028 #ifdef SMP
1029
1030 /*
1031  * This routine is called if a spinlock has been held through the
1032  * exponential backoff period and is seriously contested.  On a real cpu
1033  * we let it spin.
1034  */
1035 void
1036 cpu_spinlock_contested(void)
1037 {
1038         cpu_pause();
1039 }
1040
1041 #endif
1042
1043 /*
1044  * Clear registers on exec
1045  */
1046 void
1047 exec_setregs(u_long entry, u_long stack, u_long ps_strings)
1048 {
1049         struct thread *td = curthread;
1050         struct lwp *lp = td->td_lwp;
1051         struct pcb *pcb = td->td_pcb;
1052         struct trapframe *regs = lp->lwp_md.md_regs;
1053
1054         /* was i386_user_cleanup() in NetBSD */
1055         user_ldt_free(pcb);
1056   
1057         bzero((char *)regs, sizeof(struct trapframe));
1058         regs->tf_rip = entry;
1059         regs->tf_rsp = ((stack - 8) & ~0xFul) + 8; /* align the stack */
1060         regs->tf_rdi = stack;           /* argv */
1061         regs->tf_rflags = PSL_USER | (regs->tf_rflags & PSL_T);
1062         regs->tf_ss = _udatasel;
1063         regs->tf_cs = _ucodesel;
1064         regs->tf_rbx = ps_strings;
1065
1066         /*
1067          * Reset the hardware debug registers if they were in use.
1068          * They won't have any meaning for the newly exec'd process.
1069          */
1070         if (pcb->pcb_flags & PCB_DBREGS) {
1071                 pcb->pcb_dr0 = 0;
1072                 pcb->pcb_dr1 = 0;
1073                 pcb->pcb_dr2 = 0;
1074                 pcb->pcb_dr3 = 0;
1075                 pcb->pcb_dr6 = 0;
1076                 pcb->pcb_dr7 = 0; /* JG set bit 10? */
1077                 if (pcb == td->td_pcb) {
1078                         /*
1079                          * Clear the debug registers on the running
1080                          * CPU, otherwise they will end up affecting
1081                          * the next process we switch to.
1082                          */
1083                         reset_dbregs();
1084                 }
1085                 pcb->pcb_flags &= ~PCB_DBREGS;
1086         }
1087
1088         /*
1089          * Initialize the math emulator (if any) for the current process.
1090          * Actually, just clear the bit that says that the emulator has
1091          * been initialized.  Initialization is delayed until the process
1092          * traps to the emulator (if it is done at all) mainly because
1093          * emulators don't provide an entry point for initialization.
1094          */
1095         pcb->pcb_flags &= ~FP_SOFTFP;
1096
1097         /*
1098          * NOTE: do not set CR0_TS here.  npxinit() must do it after clearing
1099          *       gd_npxthread.  Otherwise a preemptive interrupt thread
1100          *       may panic in npxdna().
1101          */
1102         crit_enter();
1103         load_cr0(rcr0() | CR0_MP);
1104
1105         /*
1106          * NOTE: The MSR values must be correct so we can return to
1107          *       userland.  gd_user_fs/gs must be correct so the switch
1108          *       code knows what the current MSR values are.
1109          */
1110         pcb->pcb_fsbase = 0;    /* Values loaded from PCB on switch */
1111         pcb->pcb_gsbase = 0;
1112         mdcpu->gd_user_fs = 0;  /* Cache of current MSR values */
1113         mdcpu->gd_user_gs = 0;
1114         wrmsr(MSR_FSBASE, 0);   /* Set MSR values for return to userland */
1115         wrmsr(MSR_KGSBASE, 0);
1116
1117         /* Initialize the npx (if any) for the current process. */
1118         npxinit(__INITIAL_NPXCW__);
1119         crit_exit();
1120
1121         pcb->pcb_ds = _udatasel;
1122         pcb->pcb_es = _udatasel;
1123         pcb->pcb_fs = _udatasel;
1124         pcb->pcb_gs = _udatasel;
1125 }
1126
1127 void
1128 cpu_setregs(void)
1129 {
1130         register_t cr0;
1131
1132         cr0 = rcr0();
1133         cr0 |= CR0_NE;                  /* Done by npxinit() */
1134         cr0 |= CR0_MP | CR0_TS;         /* Done at every execve() too. */
1135         cr0 |= CR0_WP | CR0_AM;
1136         load_cr0(cr0);
1137         load_gs(_udatasel);
1138 }
1139
1140 static int
1141 sysctl_machdep_adjkerntz(SYSCTL_HANDLER_ARGS)
1142 {
1143         int error;
1144         error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2,
1145                 req);
1146         if (!error && req->newptr)
1147                 resettodr();
1148         return (error);
1149 }
1150
1151 SYSCTL_PROC(_machdep, CPU_ADJKERNTZ, adjkerntz, CTLTYPE_INT|CTLFLAG_RW,
1152         &adjkerntz, 0, sysctl_machdep_adjkerntz, "I", "");
1153
1154 SYSCTL_INT(_machdep, CPU_DISRTCSET, disable_rtc_set,
1155         CTLFLAG_RW, &disable_rtc_set, 0, "");
1156
1157 #if JG
1158 SYSCTL_STRUCT(_machdep, CPU_BOOTINFO, bootinfo, 
1159         CTLFLAG_RD, &bootinfo, bootinfo, "");
1160 #endif
1161
1162 SYSCTL_INT(_machdep, CPU_WALLCLOCK, wall_cmos_clock,
1163         CTLFLAG_RW, &wall_cmos_clock, 0, "");
1164
1165 extern u_long bootdev;          /* not a cdev_t - encoding is different */
1166 SYSCTL_ULONG(_machdep, OID_AUTO, guessed_bootdev,
1167         CTLFLAG_RD, &bootdev, 0, "Boot device (not in cdev_t format)");
1168
1169 /*
1170  * Initialize 386 and configure to run kernel
1171  */
1172
1173 /*
1174  * Initialize segments & interrupt table
1175  */
1176
1177 int _default_ldt;
1178 struct user_segment_descriptor gdt[NGDT * MAXCPU];      /* global descriptor table */
1179 static struct gate_descriptor idt0[NIDT];
1180 struct gate_descriptor *idt = &idt0[0]; /* interrupt descriptor table */
1181 #if JG
1182 union descriptor ldt[NLDT];             /* local descriptor table */
1183 #endif
1184
1185 /* table descriptors - used to load tables by cpu */
1186 struct region_descriptor r_gdt, r_idt;
1187
1188 /* JG proc0paddr is a virtual address */
1189 void *proc0paddr;
1190 /* JG alignment? */
1191 char proc0paddr_buff[LWKT_THREAD_STACK];
1192
1193
1194 /* software prototypes -- in more palatable form */
1195 struct soft_segment_descriptor gdt_segs[] = {
1196 /* GNULL_SEL    0 Null Descriptor */
1197 {       0x0,                    /* segment base address  */
1198         0x0,                    /* length */
1199         0,                      /* segment type */
1200         0,                      /* segment descriptor priority level */
1201         0,                      /* segment descriptor present */
1202         0,                      /* long */
1203         0,                      /* default 32 vs 16 bit size */
1204         0                       /* limit granularity (byte/page units)*/ },
1205 /* GCODE_SEL    1 Code Descriptor for kernel */
1206 {       0x0,                    /* segment base address  */
1207         0xfffff,                /* length - all address space */
1208         SDT_MEMERA,             /* segment type */
1209         SEL_KPL,                /* segment descriptor priority level */
1210         1,                      /* segment descriptor present */
1211         1,                      /* long */
1212         0,                      /* default 32 vs 16 bit size */
1213         1                       /* limit granularity (byte/page units)*/ },
1214 /* GDATA_SEL    2 Data Descriptor for kernel */
1215 {       0x0,                    /* segment base address  */
1216         0xfffff,                /* length - all address space */
1217         SDT_MEMRWA,             /* segment type */
1218         SEL_KPL,                /* segment descriptor priority level */
1219         1,                      /* segment descriptor present */
1220         1,                      /* long */
1221         0,                      /* default 32 vs 16 bit size */
1222         1                       /* limit granularity (byte/page units)*/ },
1223 /* GUCODE32_SEL 3 32 bit Code Descriptor for user */
1224 {       0x0,                    /* segment base address  */
1225         0xfffff,                /* length - all address space */
1226         SDT_MEMERA,             /* segment type */
1227         SEL_UPL,                /* segment descriptor priority level */
1228         1,                      /* segment descriptor present */
1229         0,                      /* long */
1230         1,                      /* default 32 vs 16 bit size */
1231         1                       /* limit granularity (byte/page units)*/ },
1232 /* GUDATA_SEL   4 32/64 bit Data Descriptor for user */
1233 {       0x0,                    /* segment base address  */
1234         0xfffff,                /* length - all address space */
1235         SDT_MEMRWA,             /* segment type */
1236         SEL_UPL,                /* segment descriptor priority level */
1237         1,                      /* segment descriptor present */
1238         0,                      /* long */
1239         1,                      /* default 32 vs 16 bit size */
1240         1                       /* limit granularity (byte/page units)*/ },
1241 /* GUCODE_SEL   5 64 bit Code Descriptor for user */
1242 {       0x0,                    /* segment base address  */
1243         0xfffff,                /* length - all address space */
1244         SDT_MEMERA,             /* segment type */
1245         SEL_UPL,                /* segment descriptor priority level */
1246         1,                      /* segment descriptor present */
1247         1,                      /* long */
1248         0,                      /* default 32 vs 16 bit size */
1249         1                       /* limit granularity (byte/page units)*/ },
1250 /* GPROC0_SEL   6 Proc 0 Tss Descriptor */
1251 {
1252         0x0,                    /* segment base address */
1253         sizeof(struct x86_64tss)-1,/* length - all address space */
1254         SDT_SYSTSS,             /* segment type */
1255         SEL_KPL,                /* segment descriptor priority level */
1256         1,                      /* segment descriptor present */
1257         0,                      /* long */
1258         0,                      /* unused - default 32 vs 16 bit size */
1259         0                       /* limit granularity (byte/page units)*/ },
1260 /* Actually, the TSS is a system descriptor which is double size */
1261 {       0x0,                    /* segment base address  */
1262         0x0,                    /* length */
1263         0,                      /* segment type */
1264         0,                      /* segment descriptor priority level */
1265         0,                      /* segment descriptor present */
1266         0,                      /* long */
1267         0,                      /* default 32 vs 16 bit size */
1268         0                       /* limit granularity (byte/page units)*/ },
1269 /* GUGS32_SEL   8 32 bit GS Descriptor for user */
1270 {       0x0,                    /* segment base address  */
1271         0xfffff,                /* length - all address space */
1272         SDT_MEMRWA,             /* segment type */
1273         SEL_UPL,                /* segment descriptor priority level */
1274         1,                      /* segment descriptor present */
1275         0,                      /* long */
1276         1,                      /* default 32 vs 16 bit size */
1277         1                       /* limit granularity (byte/page units)*/ },
1278 };
1279
1280 void
1281 setidt(int idx, inthand_t *func, int typ, int dpl, int ist)
1282 {
1283         struct gate_descriptor *ip;
1284
1285         ip = idt + idx;
1286         ip->gd_looffset = (uintptr_t)func;
1287         ip->gd_selector = GSEL(GCODE_SEL, SEL_KPL);
1288         ip->gd_ist = ist;
1289         ip->gd_xx = 0;
1290         ip->gd_type = typ;
1291         ip->gd_dpl = dpl;
1292         ip->gd_p = 1;
1293         ip->gd_hioffset = ((uintptr_t)func)>>16 ;
1294 }
1295
1296 #define IDTVEC(name)    __CONCAT(X,name)
1297
1298 extern inthand_t
1299         IDTVEC(div), IDTVEC(dbg), IDTVEC(nmi), IDTVEC(bpt), IDTVEC(ofl),
1300         IDTVEC(bnd), IDTVEC(ill), IDTVEC(dna), IDTVEC(fpusegm),
1301         IDTVEC(tss), IDTVEC(missing), IDTVEC(stk), IDTVEC(prot),
1302         IDTVEC(page), IDTVEC(mchk), IDTVEC(rsvd), IDTVEC(fpu), IDTVEC(align),
1303         IDTVEC(xmm), IDTVEC(dblfault),
1304         IDTVEC(fast_syscall), IDTVEC(fast_syscall32);
1305
1306 #ifdef DEBUG_INTERRUPTS
1307 extern inthand_t *Xrsvdary[256];
1308 #endif
1309
1310 void
1311 sdtossd(struct user_segment_descriptor *sd, struct soft_segment_descriptor *ssd)
1312 {
1313         ssd->ssd_base  = (sd->sd_hibase << 24) | sd->sd_lobase;
1314         ssd->ssd_limit = (sd->sd_hilimit << 16) | sd->sd_lolimit;
1315         ssd->ssd_type  = sd->sd_type;
1316         ssd->ssd_dpl   = sd->sd_dpl;
1317         ssd->ssd_p     = sd->sd_p;
1318         ssd->ssd_def32 = sd->sd_def32;
1319         ssd->ssd_gran  = sd->sd_gran;
1320 }
1321
1322 void
1323 ssdtosd(struct soft_segment_descriptor *ssd, struct user_segment_descriptor *sd)
1324 {
1325
1326         sd->sd_lobase = (ssd->ssd_base) & 0xffffff;
1327         sd->sd_hibase = (ssd->ssd_base >> 24) & 0xff;
1328         sd->sd_lolimit = (ssd->ssd_limit) & 0xffff;
1329         sd->sd_hilimit = (ssd->ssd_limit >> 16) & 0xf;
1330         sd->sd_type  = ssd->ssd_type;
1331         sd->sd_dpl   = ssd->ssd_dpl;
1332         sd->sd_p     = ssd->ssd_p;
1333         sd->sd_long  = ssd->ssd_long;
1334         sd->sd_def32 = ssd->ssd_def32;
1335         sd->sd_gran  = ssd->ssd_gran;
1336 }
1337
1338 void
1339 ssdtosyssd(struct soft_segment_descriptor *ssd,
1340     struct system_segment_descriptor *sd)
1341 {
1342
1343         sd->sd_lobase = (ssd->ssd_base) & 0xffffff;
1344         sd->sd_hibase = (ssd->ssd_base >> 24) & 0xfffffffffful;
1345         sd->sd_lolimit = (ssd->ssd_limit) & 0xffff;
1346         sd->sd_hilimit = (ssd->ssd_limit >> 16) & 0xf;
1347         sd->sd_type  = ssd->ssd_type;
1348         sd->sd_dpl   = ssd->ssd_dpl;
1349         sd->sd_p     = ssd->ssd_p;
1350         sd->sd_gran  = ssd->ssd_gran;
1351 }
1352
1353 /*
1354  * Populate the (physmap) array with base/bound pairs describing the
1355  * available physical memory in the system, then test this memory and
1356  * build the phys_avail array describing the actually-available memory.
1357  *
1358  * If we cannot accurately determine the physical memory map, then use
1359  * value from the 0xE801 call, and failing that, the RTC.
1360  *
1361  * Total memory size may be set by the kernel environment variable
1362  * hw.physmem or the compile-time define MAXMEM.
1363  *
1364  * Memory is aligned to PHYSMAP_ALIGN which must be a multiple
1365  * of PAGE_SIZE.  This also greatly reduces the memory test time
1366  * which would otherwise be excessive on machines with > 8G of ram.
1367  *
1368  * XXX first should be vm_paddr_t.
1369  */
1370
1371 #define PHYSMAP_ALIGN           (vm_paddr_t)(128 * 1024)
1372 #define PHYSMAP_ALIGN_MASK      (vm_paddr_t)(PHYSMAP_ALIGN - 1)
1373
1374 static void
1375 getmemsize(caddr_t kmdp, u_int64_t first)
1376 {
1377         int off, physmap_idx, pa_indx, da_indx;
1378         int i, j;
1379         vm_paddr_t physmap[PHYSMAP_SIZE];
1380         vm_paddr_t pa;
1381         vm_paddr_t msgbuf_size;
1382         u_long physmem_tunable;
1383         pt_entry_t *pte;
1384         struct bios_smap *smapbase, *smap, *smapend;
1385         u_int32_t smapsize;
1386         quad_t dcons_addr, dcons_size;
1387
1388         bzero(physmap, sizeof(physmap));
1389         physmap_idx = 0;
1390
1391         /*
1392          * get memory map from INT 15:E820, kindly supplied by the loader.
1393          *
1394          * subr_module.c says:
1395          * "Consumer may safely assume that size value precedes data."
1396          * ie: an int32_t immediately precedes smap.
1397          */
1398         smapbase = (struct bios_smap *)preload_search_info(kmdp,
1399             MODINFO_METADATA | MODINFOMD_SMAP);
1400         if (smapbase == NULL)
1401                 panic("No BIOS smap info from loader!");
1402
1403         smapsize = *((u_int32_t *)smapbase - 1);
1404         smapend = (struct bios_smap *)((uintptr_t)smapbase + smapsize);
1405
1406         for (smap = smapbase; smap < smapend; smap++) {
1407                 if (boothowto & RB_VERBOSE)
1408                         kprintf("SMAP type=%02x base=%016lx len=%016lx\n",
1409                             smap->type, smap->base, smap->length);
1410
1411                 if (smap->type != SMAP_TYPE_MEMORY)
1412                         continue;
1413
1414                 if (smap->length == 0)
1415                         continue;
1416
1417                 for (i = 0; i <= physmap_idx; i += 2) {
1418                         if (smap->base < physmap[i + 1]) {
1419                                 if (boothowto & RB_VERBOSE) {
1420                                         kprintf("Overlapping or non-monotonic "
1421                                                 "memory region, ignoring "
1422                                                 "second region\n");
1423                                 }
1424                                 continue;
1425                         }
1426                 }
1427                 Realmem += smap->length;
1428
1429                 if (smap->base == physmap[physmap_idx + 1]) {
1430                         physmap[physmap_idx + 1] += smap->length;
1431                         continue;
1432                 }
1433
1434                 physmap_idx += 2;
1435                 if (physmap_idx == PHYSMAP_SIZE) {
1436                         kprintf("Too many segments in the physical "
1437                                 "address map, giving up\n");
1438                         break;
1439                 }
1440                 physmap[physmap_idx] = smap->base;
1441                 physmap[physmap_idx + 1] = smap->base + smap->length;
1442         }
1443
1444         base_memory = physmap[1] / 1024;
1445 #ifdef SMP
1446         /* make hole for AP bootstrap code */
1447         physmap[1] = mp_bootaddress(base_memory);
1448 #endif
1449
1450         /* Save EBDA address, if any */
1451         ebda_addr = (u_long)(*(u_short *)(KERNBASE + 0x40e));
1452         ebda_addr <<= 4;
1453
1454         /*
1455          * Maxmem isn't the "maximum memory", it's one larger than the
1456          * highest page of the physical address space.  It should be
1457          * called something like "Maxphyspage".  We may adjust this
1458          * based on ``hw.physmem'' and the results of the memory test.
1459          */
1460         Maxmem = atop(physmap[physmap_idx + 1]);
1461
1462 #ifdef MAXMEM
1463         Maxmem = MAXMEM / 4;
1464 #endif
1465
1466         if (TUNABLE_ULONG_FETCH("hw.physmem", &physmem_tunable))
1467                 Maxmem = atop(physmem_tunable);
1468
1469         /*
1470          * Don't allow MAXMEM or hw.physmem to extend the amount of memory
1471          * in the system.
1472          */
1473         if (Maxmem > atop(physmap[physmap_idx + 1]))
1474                 Maxmem = atop(physmap[physmap_idx + 1]);
1475
1476         /*
1477          * Blowing out the DMAP will blow up the system.
1478          */
1479         if (Maxmem > atop(DMAP_MAX_ADDRESS - DMAP_MIN_ADDRESS)) {
1480                 kprintf("Limiting Maxmem due to DMAP size\n");
1481                 Maxmem = atop(DMAP_MAX_ADDRESS - DMAP_MIN_ADDRESS);
1482         }
1483
1484         if (atop(physmap[physmap_idx + 1]) != Maxmem &&
1485             (boothowto & RB_VERBOSE)) {
1486                 kprintf("Physical memory use set to %ldK\n", Maxmem * 4);
1487         }
1488
1489         /*
1490          * Call pmap initialization to make new kernel address space
1491          *
1492          * Mask off page 0.
1493          */
1494         pmap_bootstrap(&first);
1495         physmap[0] = PAGE_SIZE;
1496
1497         /*
1498          * Align the physmap to PHYSMAP_ALIGN and cut out anything
1499          * exceeding Maxmem.
1500          */
1501         for (i = j = 0; i <= physmap_idx; i += 2) {
1502                 if (physmap[i+1] > ptoa((vm_paddr_t)Maxmem))
1503                         physmap[i+1] = ptoa((vm_paddr_t)Maxmem);
1504                 physmap[i] = (physmap[i] + PHYSMAP_ALIGN_MASK) &
1505                              ~PHYSMAP_ALIGN_MASK;
1506                 physmap[i+1] = physmap[i+1] & ~PHYSMAP_ALIGN_MASK;
1507
1508                 physmap[j] = physmap[i];
1509                 physmap[j+1] = physmap[i+1];
1510
1511                 if (physmap[i] < physmap[i+1])
1512                         j += 2;
1513         }
1514         physmap_idx = j - 2;
1515
1516         /*
1517          * Align anything else used in the validation loop.
1518          */
1519         first = (first + PHYSMAP_ALIGN_MASK) & ~PHYSMAP_ALIGN_MASK;
1520
1521         /*
1522          * Size up each available chunk of physical memory.
1523          */
1524         pa_indx = 0;
1525         da_indx = 1;
1526         phys_avail[pa_indx++] = physmap[0];
1527         phys_avail[pa_indx] = physmap[0];
1528         dump_avail[da_indx] = physmap[0];
1529         pte = CMAP1;
1530
1531         /*
1532          * Get dcons buffer address
1533          */
1534         if (kgetenv_quad("dcons.addr", &dcons_addr) == 0 ||
1535             kgetenv_quad("dcons.size", &dcons_size) == 0)
1536                 dcons_addr = 0;
1537
1538         /*
1539          * Validate the physical memory.  The physical memory segments
1540          * have already been aligned to PHYSMAP_ALIGN which is a multiple
1541          * of PAGE_SIZE.
1542          */
1543         for (i = 0; i <= physmap_idx; i += 2) {
1544                 vm_paddr_t end;
1545
1546                 end = physmap[i + 1];
1547
1548                 for (pa = physmap[i]; pa < end; pa += PHYSMAP_ALIGN) {
1549                         int tmp, page_bad, full;
1550                         int *ptr = (int *)CADDR1;
1551
1552                         full = FALSE;
1553                         /*
1554                          * block out kernel memory as not available.
1555                          */
1556                         if (pa >= 0x100000 && pa < first)
1557                                 goto do_dump_avail;
1558
1559                         /*
1560                          * block out dcons buffer
1561                          */
1562                         if (dcons_addr > 0
1563                             && pa >= trunc_page(dcons_addr)
1564                             && pa < dcons_addr + dcons_size) {
1565                                 goto do_dump_avail;
1566                         }
1567
1568                         page_bad = FALSE;
1569
1570                         /*
1571                          * map page into kernel: valid, read/write,non-cacheable
1572                          */
1573                         *pte = pa | PG_V | PG_RW | PG_N;
1574                         cpu_invltlb();
1575
1576                         tmp = *(int *)ptr;
1577                         /*
1578                          * Test for alternating 1's and 0's
1579                          */
1580                         *(volatile int *)ptr = 0xaaaaaaaa;
1581                         cpu_mfence();
1582                         if (*(volatile int *)ptr != 0xaaaaaaaa)
1583                                 page_bad = TRUE;
1584                         /*
1585                          * Test for alternating 0's and 1's
1586                          */
1587                         *(volatile int *)ptr = 0x55555555;
1588                         cpu_mfence();
1589                         if (*(volatile int *)ptr != 0x55555555)
1590                                 page_bad = TRUE;
1591                         /*
1592                          * Test for all 1's
1593                          */
1594                         *(volatile int *)ptr = 0xffffffff;
1595                         cpu_mfence();
1596                         if (*(volatile int *)ptr != 0xffffffff)
1597                                 page_bad = TRUE;
1598                         /*
1599                          * Test for all 0's
1600                          */
1601                         *(volatile int *)ptr = 0x0;
1602                         cpu_mfence();
1603                         if (*(volatile int *)ptr != 0x0)
1604                                 page_bad = TRUE;
1605                         /*
1606                          * Restore original value.
1607                          */
1608                         *(int *)ptr = tmp;
1609
1610                         /*
1611                          * Adjust array of valid/good pages.
1612                          */
1613                         if (page_bad == TRUE)
1614                                 continue;
1615                         /*
1616                          * If this good page is a continuation of the
1617                          * previous set of good pages, then just increase
1618                          * the end pointer. Otherwise start a new chunk.
1619                          * Note that "end" points one higher than end,
1620                          * making the range >= start and < end.
1621                          * If we're also doing a speculative memory
1622                          * test and we at or past the end, bump up Maxmem
1623                          * so that we keep going. The first bad page
1624                          * will terminate the loop.
1625                          */
1626                         if (phys_avail[pa_indx] == pa) {
1627                                 phys_avail[pa_indx] += PHYSMAP_ALIGN;
1628                         } else {
1629                                 pa_indx++;
1630                                 if (pa_indx == PHYS_AVAIL_ARRAY_END) {
1631                                         kprintf(
1632                 "Too many holes in the physical address space, giving up\n");
1633                                         pa_indx--;
1634                                         full = TRUE;
1635                                         goto do_dump_avail;
1636                                 }
1637                                 phys_avail[pa_indx++] = pa;
1638                                 phys_avail[pa_indx] = pa + PHYSMAP_ALIGN;
1639                         }
1640                         physmem += PHYSMAP_ALIGN / PAGE_SIZE;
1641 do_dump_avail:
1642                         if (dump_avail[da_indx] == pa) {
1643                                 dump_avail[da_indx] += PHYSMAP_ALIGN;
1644                         } else {
1645                                 da_indx++;
1646                                 if (da_indx == DUMP_AVAIL_ARRAY_END) {
1647                                         da_indx--;
1648                                         goto do_next;
1649                                 }
1650                                 dump_avail[da_indx++] = pa;
1651                                 dump_avail[da_indx] = pa + PHYSMAP_ALIGN;
1652                         }
1653 do_next:
1654                         if (full)
1655                                 break;
1656                 }
1657         }
1658         *pte = 0;
1659         cpu_invltlb();
1660
1661         /*
1662          * The last chunk must contain at least one page plus the message
1663          * buffer to avoid complicating other code (message buffer address
1664          * calculation, etc.).
1665          */
1666         msgbuf_size = (MSGBUF_SIZE + PHYSMAP_ALIGN_MASK) & ~PHYSMAP_ALIGN_MASK;
1667
1668         while (phys_avail[pa_indx - 1] + PHYSMAP_ALIGN +
1669                msgbuf_size >= phys_avail[pa_indx]) {
1670                 physmem -= atop(phys_avail[pa_indx] - phys_avail[pa_indx - 1]);
1671                 phys_avail[pa_indx--] = 0;
1672                 phys_avail[pa_indx--] = 0;
1673         }
1674
1675         Maxmem = atop(phys_avail[pa_indx]);
1676
1677         /* Trim off space for the message buffer. */
1678         phys_avail[pa_indx] -= msgbuf_size;
1679
1680         avail_end = phys_avail[pa_indx];
1681
1682         /* Map the message buffer. */
1683         for (off = 0; off < msgbuf_size; off += PAGE_SIZE) {
1684                 pmap_kenter((vm_offset_t)msgbufp + off,
1685                             phys_avail[pa_indx] + off);
1686         }
1687 }
1688
1689 struct machintr_abi MachIntrABI;
1690
1691 /*
1692  * IDT VECTORS:
1693  *      0       Divide by zero
1694  *      1       Debug
1695  *      2       NMI
1696  *      3       BreakPoint
1697  *      4       OverFlow
1698  *      5       Bound-Range
1699  *      6       Invalid OpCode
1700  *      7       Device Not Available (x87)
1701  *      8       Double-Fault
1702  *      9       Coprocessor Segment overrun (unsupported, reserved)
1703  *      10      Invalid-TSS
1704  *      11      Segment not present
1705  *      12      Stack
1706  *      13      General Protection
1707  *      14      Page Fault
1708  *      15      Reserved
1709  *      16      x87 FP Exception pending
1710  *      17      Alignment Check
1711  *      18      Machine Check
1712  *      19      SIMD floating point
1713  *      20-31   reserved
1714  *      32-255  INTn/external sources
1715  */
1716 u_int64_t
1717 hammer_time(u_int64_t modulep, u_int64_t physfree)
1718 {
1719         caddr_t kmdp;
1720         int gsel_tss, x;
1721 #if JG
1722         int metadata_missing, off;
1723 #endif
1724         struct mdglobaldata *gd;
1725         u_int64_t msr;
1726
1727         /*
1728          * Prevent lowering of the ipl if we call tsleep() early.
1729          */
1730         gd = &CPU_prvspace[0].mdglobaldata;
1731         bzero(gd, sizeof(*gd));
1732
1733         /*
1734          * Note: on both UP and SMP curthread must be set non-NULL
1735          * early in the boot sequence because the system assumes
1736          * that 'curthread' is never NULL.
1737          */
1738
1739         gd->mi.gd_curthread = &thread0;
1740         thread0.td_gd = &gd->mi;
1741
1742         atdevbase = ISA_HOLE_START + PTOV_OFFSET;
1743
1744 #if JG
1745         metadata_missing = 0;
1746         if (bootinfo.bi_modulep) {
1747                 preload_metadata = (caddr_t)bootinfo.bi_modulep + KERNBASE;
1748                 preload_bootstrap_relocate(KERNBASE);
1749         } else {
1750                 metadata_missing = 1;
1751         }
1752         if (bootinfo.bi_envp)
1753                 kern_envp = (caddr_t)bootinfo.bi_envp + KERNBASE;
1754 #endif
1755
1756         preload_metadata = (caddr_t)(uintptr_t)(modulep + PTOV_OFFSET);
1757         preload_bootstrap_relocate(PTOV_OFFSET);
1758         kmdp = preload_search_by_type("elf kernel");
1759         if (kmdp == NULL)
1760                 kmdp = preload_search_by_type("elf64 kernel");
1761         boothowto = MD_FETCH(kmdp, MODINFOMD_HOWTO, int);
1762         kern_envp = MD_FETCH(kmdp, MODINFOMD_ENVP, char *) + PTOV_OFFSET;
1763 #ifdef DDB
1764         ksym_start = MD_FETCH(kmdp, MODINFOMD_SSYM, uintptr_t);
1765         ksym_end = MD_FETCH(kmdp, MODINFOMD_ESYM, uintptr_t);
1766 #endif
1767
1768         if (boothowto & RB_VERBOSE)
1769                 bootverbose++;
1770
1771         /*
1772          * Default MachIntrABI to ICU
1773          */
1774         MachIntrABI = MachIntrABI_ICU;
1775
1776         TUNABLE_INT_FETCH("hw.apic_io_enable", &ioapic_enable); /* for compat */
1777         TUNABLE_INT_FETCH("hw.ioapic_enable", &ioapic_enable);
1778         TUNABLE_INT_FETCH("hw.lapic_enable", &lapic_enable);
1779
1780         /*
1781          * start with one cpu.  Note: with one cpu, ncpus2_shift, ncpus2_mask,
1782          * and ncpus_fit_mask remain 0.
1783          */
1784         ncpus = 1;
1785         ncpus2 = 1;
1786         ncpus_fit = 1;
1787         /* Init basic tunables, hz etc */
1788         init_param1();
1789
1790         /*
1791          * make gdt memory segments
1792          */
1793         gdt_segs[GPROC0_SEL].ssd_base =
1794                 (uintptr_t) &CPU_prvspace[0].mdglobaldata.gd_common_tss;
1795
1796         gd->mi.gd_prvspace = &CPU_prvspace[0];
1797
1798         for (x = 0; x < NGDT; x++) {
1799                 if (x != GPROC0_SEL && x != (GPROC0_SEL + 1))
1800                         ssdtosd(&gdt_segs[x], &gdt[x]);
1801         }
1802         ssdtosyssd(&gdt_segs[GPROC0_SEL],
1803             (struct system_segment_descriptor *)&gdt[GPROC0_SEL]);
1804
1805         r_gdt.rd_limit = NGDT * sizeof(gdt[0]) - 1;
1806         r_gdt.rd_base =  (long) gdt;
1807         lgdt(&r_gdt);
1808
1809         wrmsr(MSR_FSBASE, 0);           /* User value */
1810         wrmsr(MSR_GSBASE, (u_int64_t)&gd->mi);
1811         wrmsr(MSR_KGSBASE, 0);          /* User value while in the kernel */
1812
1813         mi_gdinit(&gd->mi, 0);
1814         cpu_gdinit(gd, 0);
1815         proc0paddr = proc0paddr_buff;
1816         mi_proc0init(&gd->mi, proc0paddr);
1817         safepri = TDPRI_MAX;
1818
1819         /* spinlocks and the BGL */
1820         init_locks();
1821
1822         /* exceptions */
1823         for (x = 0; x < NIDT; x++)
1824                 setidt(x, &IDTVEC(rsvd), SDT_SYSIGT, SEL_KPL, 0);
1825         setidt(IDT_DE, &IDTVEC(div),  SDT_SYSIGT, SEL_KPL, 0);
1826         setidt(IDT_DB, &IDTVEC(dbg),  SDT_SYSIGT, SEL_KPL, 0);
1827         setidt(IDT_NMI, &IDTVEC(nmi),  SDT_SYSIGT, SEL_KPL, 1);
1828         setidt(IDT_BP, &IDTVEC(bpt),  SDT_SYSIGT, SEL_UPL, 0);
1829         setidt(IDT_OF, &IDTVEC(ofl),  SDT_SYSIGT, SEL_KPL, 0);
1830         setidt(IDT_BR, &IDTVEC(bnd),  SDT_SYSIGT, SEL_KPL, 0);
1831         setidt(IDT_UD, &IDTVEC(ill),  SDT_SYSIGT, SEL_KPL, 0);
1832         setidt(IDT_NM, &IDTVEC(dna),  SDT_SYSIGT, SEL_KPL, 0);
1833         setidt(IDT_DF, &IDTVEC(dblfault), SDT_SYSIGT, SEL_KPL, 1);
1834         setidt(IDT_FPUGP, &IDTVEC(fpusegm),  SDT_SYSIGT, SEL_KPL, 0);
1835         setidt(IDT_TS, &IDTVEC(tss),  SDT_SYSIGT, SEL_KPL, 0);
1836         setidt(IDT_NP, &IDTVEC(missing),  SDT_SYSIGT, SEL_KPL, 0);
1837         setidt(IDT_SS, &IDTVEC(stk),  SDT_SYSIGT, SEL_KPL, 0);
1838         setidt(IDT_GP, &IDTVEC(prot),  SDT_SYSIGT, SEL_KPL, 0);
1839         setidt(IDT_PF, &IDTVEC(page),  SDT_SYSIGT, SEL_KPL, 0);
1840         setidt(IDT_MF, &IDTVEC(fpu),  SDT_SYSIGT, SEL_KPL, 0);
1841         setidt(IDT_AC, &IDTVEC(align), SDT_SYSIGT, SEL_KPL, 0);
1842         setidt(IDT_MC, &IDTVEC(mchk),  SDT_SYSIGT, SEL_KPL, 0);
1843         setidt(IDT_XF, &IDTVEC(xmm), SDT_SYSIGT, SEL_KPL, 0);
1844
1845         r_idt.rd_limit = sizeof(idt0) - 1;
1846         r_idt.rd_base = (long) idt;
1847         lidt(&r_idt);
1848
1849         /*
1850          * Initialize the console before we print anything out.
1851          */
1852         cninit();
1853
1854 #if JG
1855         if (metadata_missing)
1856                 kprintf("WARNING: loader(8) metadata is missing!\n");
1857 #endif
1858
1859 #if     NISA >0
1860         elcr_probe();
1861         isa_defaultirq();
1862 #endif
1863         rand_initialize();
1864
1865         /*
1866          * Initialize IRQ mapping
1867          *
1868          * NOTE:
1869          * SHOULD be after elcr_probe()
1870          */
1871         MachIntrABI_ICU.initmap();
1872 #ifdef SMP
1873         MachIntrABI_IOAPIC.initmap();
1874 #endif
1875
1876 #ifdef DDB
1877         kdb_init();
1878         if (boothowto & RB_KDB)
1879                 Debugger("Boot flags requested debugger");
1880 #endif
1881
1882 #if JG
1883         finishidentcpu();       /* Final stage of CPU initialization */
1884         setidt(6, &IDTVEC(ill),  SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1885         setidt(13, &IDTVEC(prot),  SDT_SYS386IGT, SEL_KPL, GSEL(GCODE_SEL, SEL_KPL));
1886 #endif
1887         identify_cpu();         /* Final stage of CPU initialization */
1888         initializecpu();        /* Initialize CPU registers */
1889
1890         /* make an initial tss so cpu can get interrupt stack on syscall! */
1891         gd->gd_common_tss.tss_rsp0 =
1892                 (register_t)(thread0.td_kstack +
1893                              KSTACK_PAGES * PAGE_SIZE - sizeof(struct pcb));
1894         /* Ensure the stack is aligned to 16 bytes */
1895         gd->gd_common_tss.tss_rsp0 &= ~(register_t)0xF;
1896
1897         /* double fault stack */
1898         gd->gd_common_tss.tss_ist1 =
1899                 (long)&gd->mi.gd_prvspace->idlestack[
1900                         sizeof(gd->mi.gd_prvspace->idlestack)];
1901
1902         /* Set the IO permission bitmap (empty due to tss seg limit) */
1903         gd->gd_common_tss.tss_iobase = sizeof(struct x86_64tss);
1904
1905         gsel_tss = GSEL(GPROC0_SEL, SEL_KPL);
1906         gd->gd_tss_gdt = &gdt[GPROC0_SEL];
1907         gd->gd_common_tssd = *gd->gd_tss_gdt;
1908         ltr(gsel_tss);
1909
1910         /* Set up the fast syscall stuff */
1911         msr = rdmsr(MSR_EFER) | EFER_SCE;
1912         wrmsr(MSR_EFER, msr);
1913         wrmsr(MSR_LSTAR, (u_int64_t)IDTVEC(fast_syscall));
1914         wrmsr(MSR_CSTAR, (u_int64_t)IDTVEC(fast_syscall32));
1915         msr = ((u_int64_t)GSEL(GCODE_SEL, SEL_KPL) << 32) |
1916               ((u_int64_t)GSEL(GUCODE32_SEL, SEL_UPL) << 48);
1917         wrmsr(MSR_STAR, msr);
1918         wrmsr(MSR_SF_MASK, PSL_NT|PSL_T|PSL_I|PSL_C|PSL_D);
1919
1920         getmemsize(kmdp, physfree);
1921         init_param2(physmem);
1922
1923         /* now running on new page tables, configured,and u/iom is accessible */
1924
1925         /* Map the message buffer. */
1926 #if JG
1927         for (off = 0; off < round_page(MSGBUF_SIZE); off += PAGE_SIZE)
1928                 pmap_kenter((vm_offset_t)msgbufp + off, avail_end + off);
1929 #endif
1930
1931         msgbufinit(msgbufp, MSGBUF_SIZE);
1932
1933
1934         /* transfer to user mode */
1935
1936         _ucodesel = GSEL(GUCODE_SEL, SEL_UPL);
1937         _udatasel = GSEL(GUDATA_SEL, SEL_UPL);
1938         _ucode32sel = GSEL(GUCODE32_SEL, SEL_UPL);
1939
1940         load_ds(_udatasel);
1941         load_es(_udatasel);
1942         load_fs(_udatasel);
1943
1944         /* setup proc 0's pcb */
1945         thread0.td_pcb->pcb_flags = 0;
1946         thread0.td_pcb->pcb_cr3 = KPML4phys;
1947         thread0.td_pcb->pcb_ext = 0;
1948         lwp0.lwp_md.md_regs = &proc0_tf;        /* XXX needed? */
1949
1950         /* Location of kernel stack for locore */
1951         return ((u_int64_t)thread0.td_pcb);
1952 }
1953
1954 /*
1955  * Initialize machine-dependant portions of the global data structure.
1956  * Note that the global data area and cpu0's idlestack in the private
1957  * data space were allocated in locore.
1958  *
1959  * Note: the idlethread's cpl is 0
1960  *
1961  * WARNING!  Called from early boot, 'mycpu' may not work yet.
1962  */
1963 void
1964 cpu_gdinit(struct mdglobaldata *gd, int cpu)
1965 {
1966         if (cpu)
1967                 gd->mi.gd_curthread = &gd->mi.gd_idlethread;
1968
1969         lwkt_init_thread(&gd->mi.gd_idlethread, 
1970                         gd->mi.gd_prvspace->idlestack, 
1971                         sizeof(gd->mi.gd_prvspace->idlestack), 
1972                         0, &gd->mi);
1973         lwkt_set_comm(&gd->mi.gd_idlethread, "idle_%d", cpu);
1974         gd->mi.gd_idlethread.td_switch = cpu_lwkt_switch;
1975         gd->mi.gd_idlethread.td_sp -= sizeof(void *);
1976         *(void **)gd->mi.gd_idlethread.td_sp = cpu_idle_restore;
1977 }
1978
1979 int
1980 is_globaldata_space(vm_offset_t saddr, vm_offset_t eaddr)
1981 {
1982         if (saddr >= (vm_offset_t)&CPU_prvspace[0] &&
1983             eaddr <= (vm_offset_t)&CPU_prvspace[MAXCPU]) {
1984                 return (TRUE);
1985         }
1986         return (FALSE);
1987 }
1988
1989 struct globaldata *
1990 globaldata_find(int cpu)
1991 {
1992         KKASSERT(cpu >= 0 && cpu < ncpus);
1993         return(&CPU_prvspace[cpu].mdglobaldata.mi);
1994 }
1995
1996 int
1997 ptrace_set_pc(struct lwp *lp, unsigned long addr)
1998 {
1999         lp->lwp_md.md_regs->tf_rip = addr;
2000         return (0);
2001 }
2002
2003 int
2004 ptrace_single_step(struct lwp *lp)
2005 {
2006         lp->lwp_md.md_regs->tf_rflags |= PSL_T;
2007         return (0);
2008 }
2009
2010 int
2011 fill_regs(struct lwp *lp, struct reg *regs)
2012 {
2013         struct trapframe *tp;
2014
2015         tp = lp->lwp_md.md_regs;
2016         bcopy(&tp->tf_rdi, &regs->r_rdi, sizeof(*regs));
2017         return (0);
2018 }
2019
2020 int
2021 set_regs(struct lwp *lp, struct reg *regs)
2022 {
2023         struct trapframe *tp;
2024
2025         tp = lp->lwp_md.md_regs;
2026         if (!EFL_SECURE(regs->r_rflags, tp->tf_rflags) ||
2027             !CS_SECURE(regs->r_cs))
2028                 return (EINVAL);
2029         bcopy(&regs->r_rdi, &tp->tf_rdi, sizeof(*regs));
2030         return (0);
2031 }
2032
2033 #ifndef CPU_DISABLE_SSE
2034 static void
2035 fill_fpregs_xmm(struct savexmm *sv_xmm, struct save87 *sv_87)
2036 {
2037         struct env87 *penv_87 = &sv_87->sv_env;
2038         struct envxmm *penv_xmm = &sv_xmm->sv_env;
2039         int i;
2040
2041         /* FPU control/status */
2042         penv_87->en_cw = penv_xmm->en_cw;
2043         penv_87->en_sw = penv_xmm->en_sw;
2044         penv_87->en_tw = penv_xmm->en_tw;
2045         penv_87->en_fip = penv_xmm->en_fip;
2046         penv_87->en_fcs = penv_xmm->en_fcs;
2047         penv_87->en_opcode = penv_xmm->en_opcode;
2048         penv_87->en_foo = penv_xmm->en_foo;
2049         penv_87->en_fos = penv_xmm->en_fos;
2050
2051         /* FPU registers */
2052         for (i = 0; i < 8; ++i)
2053                 sv_87->sv_ac[i] = sv_xmm->sv_fp[i].fp_acc;
2054 }
2055
2056 static void
2057 set_fpregs_xmm(struct save87 *sv_87, struct savexmm *sv_xmm)
2058 {
2059         struct env87 *penv_87 = &sv_87->sv_env;
2060         struct envxmm *penv_xmm = &sv_xmm->sv_env;
2061         int i;
2062
2063         /* FPU control/status */
2064         penv_xmm->en_cw = penv_87->en_cw;
2065         penv_xmm->en_sw = penv_87->en_sw;
2066         penv_xmm->en_tw = penv_87->en_tw;
2067         penv_xmm->en_fip = penv_87->en_fip;
2068         penv_xmm->en_fcs = penv_87->en_fcs;
2069         penv_xmm->en_opcode = penv_87->en_opcode;
2070         penv_xmm->en_foo = penv_87->en_foo;
2071         penv_xmm->en_fos = penv_87->en_fos;
2072
2073         /* FPU registers */
2074         for (i = 0; i < 8; ++i)
2075                 sv_xmm->sv_fp[i].fp_acc = sv_87->sv_ac[i];
2076 }
2077 #endif /* CPU_DISABLE_SSE */
2078
2079 int
2080 fill_fpregs(struct lwp *lp, struct fpreg *fpregs)
2081 {
2082 #ifndef CPU_DISABLE_SSE
2083         if (cpu_fxsr) {
2084                 fill_fpregs_xmm(&lp->lwp_thread->td_pcb->pcb_save.sv_xmm,
2085                                 (struct save87 *)fpregs);
2086                 return (0);
2087         }
2088 #endif /* CPU_DISABLE_SSE */
2089         bcopy(&lp->lwp_thread->td_pcb->pcb_save.sv_87, fpregs, sizeof *fpregs);
2090         return (0);
2091 }
2092
2093 int
2094 set_fpregs(struct lwp *lp, struct fpreg *fpregs)
2095 {
2096 #ifndef CPU_DISABLE_SSE
2097         if (cpu_fxsr) {
2098                 set_fpregs_xmm((struct save87 *)fpregs,
2099                                &lp->lwp_thread->td_pcb->pcb_save.sv_xmm);
2100                 return (0);
2101         }
2102 #endif /* CPU_DISABLE_SSE */
2103         bcopy(fpregs, &lp->lwp_thread->td_pcb->pcb_save.sv_87, sizeof *fpregs);
2104         return (0);
2105 }
2106
2107 int
2108 fill_dbregs(struct lwp *lp, struct dbreg *dbregs)
2109 {
2110         if (lp == NULL) {
2111                 dbregs->dr[0] = rdr0();
2112                 dbregs->dr[1] = rdr1();
2113                 dbregs->dr[2] = rdr2();
2114                 dbregs->dr[3] = rdr3();
2115                 dbregs->dr[4] = rdr4();
2116                 dbregs->dr[5] = rdr5();
2117                 dbregs->dr[6] = rdr6();
2118                 dbregs->dr[7] = rdr7();
2119         } else {
2120                 struct pcb *pcb;
2121
2122                 pcb = lp->lwp_thread->td_pcb;
2123                 dbregs->dr[0] = pcb->pcb_dr0;
2124                 dbregs->dr[1] = pcb->pcb_dr1;
2125                 dbregs->dr[2] = pcb->pcb_dr2;
2126                 dbregs->dr[3] = pcb->pcb_dr3;
2127                 dbregs->dr[4] = 0;
2128                 dbregs->dr[5] = 0;
2129                 dbregs->dr[6] = pcb->pcb_dr6;
2130                 dbregs->dr[7] = pcb->pcb_dr7;
2131         }
2132         return (0);
2133 }
2134
2135 int
2136 set_dbregs(struct lwp *lp, struct dbreg *dbregs)
2137 {
2138         if (lp == NULL) {
2139                 load_dr0(dbregs->dr[0]);
2140                 load_dr1(dbregs->dr[1]);
2141                 load_dr2(dbregs->dr[2]);
2142                 load_dr3(dbregs->dr[3]);
2143                 load_dr4(dbregs->dr[4]);
2144                 load_dr5(dbregs->dr[5]);
2145                 load_dr6(dbregs->dr[6]);
2146                 load_dr7(dbregs->dr[7]);
2147         } else {
2148                 struct pcb *pcb;
2149                 struct ucred *ucred;
2150                 int i;
2151                 uint64_t mask1, mask2;
2152
2153                 /*
2154                  * Don't let an illegal value for dr7 get set.  Specifically,
2155                  * check for undefined settings.  Setting these bit patterns
2156                  * result in undefined behaviour and can lead to an unexpected
2157                  * TRCTRAP.
2158                  */
2159                 /* JG this loop looks unreadable */
2160                 /* Check 4 2-bit fields for invalid patterns.
2161                  * These fields are R/Wi, for i = 0..3
2162                  */
2163                 /* Is 10 in LENi allowed when running in compatibility mode? */
2164                 /* Pattern 10 in R/Wi might be used to indicate
2165                  * breakpoint on I/O. Further analysis should be
2166                  * carried to decide if it is safe and useful to
2167                  * provide access to that capability
2168                  */
2169                 for (i = 0, mask1 = 0x3<<16, mask2 = 0x2<<16; i < 4; 
2170                      i++, mask1 <<= 4, mask2 <<= 4)
2171                         if ((dbregs->dr[7] & mask1) == mask2)
2172                                 return (EINVAL);
2173                 
2174                 pcb = lp->lwp_thread->td_pcb;
2175                 ucred = lp->lwp_proc->p_ucred;
2176
2177                 /*
2178                  * Don't let a process set a breakpoint that is not within the
2179                  * process's address space.  If a process could do this, it
2180                  * could halt the system by setting a breakpoint in the kernel
2181                  * (if ddb was enabled).  Thus, we need to check to make sure
2182                  * that no breakpoints are being enabled for addresses outside
2183                  * process's address space, unless, perhaps, we were called by
2184                  * uid 0.
2185                  *
2186                  * XXX - what about when the watched area of the user's
2187                  * address space is written into from within the kernel
2188                  * ... wouldn't that still cause a breakpoint to be generated
2189                  * from within kernel mode?
2190                  */
2191
2192                 if (priv_check_cred(ucred, PRIV_ROOT, 0) != 0) {
2193                         if (dbregs->dr[7] & 0x3) {
2194                                 /* dr0 is enabled */
2195                                 if (dbregs->dr[0] >= VM_MAX_USER_ADDRESS)
2196                                         return (EINVAL);
2197                         }
2198
2199                         if (dbregs->dr[7] & (0x3<<2)) {
2200                                 /* dr1 is enabled */
2201                                 if (dbregs->dr[1] >= VM_MAX_USER_ADDRESS)
2202                                         return (EINVAL);
2203                         }
2204
2205                         if (dbregs->dr[7] & (0x3<<4)) {
2206                                 /* dr2 is enabled */
2207                                 if (dbregs->dr[2] >= VM_MAX_USER_ADDRESS)
2208                                         return (EINVAL);
2209                         }
2210
2211                         if (dbregs->dr[7] & (0x3<<6)) {
2212                                 /* dr3 is enabled */
2213                                 if (dbregs->dr[3] >= VM_MAX_USER_ADDRESS)
2214                                         return (EINVAL);
2215                         }
2216                 }
2217
2218                 pcb->pcb_dr0 = dbregs->dr[0];
2219                 pcb->pcb_dr1 = dbregs->dr[1];
2220                 pcb->pcb_dr2 = dbregs->dr[2];
2221                 pcb->pcb_dr3 = dbregs->dr[3];
2222                 pcb->pcb_dr6 = dbregs->dr[6];
2223                 pcb->pcb_dr7 = dbregs->dr[7];
2224
2225                 pcb->pcb_flags |= PCB_DBREGS;
2226         }
2227
2228         return (0);
2229 }
2230
2231 /*
2232  * Return > 0 if a hardware breakpoint has been hit, and the
2233  * breakpoint was in user space.  Return 0, otherwise.
2234  */
2235 int
2236 user_dbreg_trap(void)
2237 {
2238         u_int64_t dr7, dr6; /* debug registers dr6 and dr7 */
2239         u_int64_t bp;       /* breakpoint bits extracted from dr6 */
2240         int nbp;            /* number of breakpoints that triggered */
2241         caddr_t addr[4];    /* breakpoint addresses */
2242         int i;
2243         
2244         dr7 = rdr7();
2245         if ((dr7 & 0xff) == 0) {
2246                 /*
2247                  * all GE and LE bits in the dr7 register are zero,
2248                  * thus the trap couldn't have been caused by the
2249                  * hardware debug registers
2250                  */
2251                 return 0;
2252         }
2253
2254         nbp = 0;
2255         dr6 = rdr6();
2256         bp = dr6 & 0xf;
2257
2258         if (bp == 0) {
2259                 /*
2260                  * None of the breakpoint bits are set meaning this
2261                  * trap was not caused by any of the debug registers
2262                  */
2263                 return 0;
2264         }
2265
2266         /*
2267          * at least one of the breakpoints were hit, check to see
2268          * which ones and if any of them are user space addresses
2269          */
2270
2271         if (bp & 0x01) {
2272                 addr[nbp++] = (caddr_t)rdr0();
2273         }
2274         if (bp & 0x02) {
2275                 addr[nbp++] = (caddr_t)rdr1();
2276         }
2277         if (bp & 0x04) {
2278                 addr[nbp++] = (caddr_t)rdr2();
2279         }
2280         if (bp & 0x08) {
2281                 addr[nbp++] = (caddr_t)rdr3();
2282         }
2283
2284         for (i=0; i<nbp; i++) {
2285                 if (addr[i] <
2286                     (caddr_t)VM_MAX_USER_ADDRESS) {
2287                         /*
2288                          * addr[i] is in user space
2289                          */
2290                         return nbp;
2291                 }
2292         }
2293
2294         /*
2295          * None of the breakpoints are in user space.
2296          */
2297         return 0;
2298 }
2299
2300
2301 #ifndef DDB
2302 void
2303 Debugger(const char *msg)
2304 {
2305         kprintf("Debugger(\"%s\") called.\n", msg);
2306 }
2307 #endif /* no DDB */
2308
2309 #ifdef DDB
2310
2311 /*
2312  * Provide inb() and outb() as functions.  They are normally only
2313  * available as macros calling inlined functions, thus cannot be
2314  * called inside DDB.
2315  *
2316  * The actual code is stolen from <machine/cpufunc.h>, and de-inlined.
2317  */
2318
2319 #undef inb
2320 #undef outb
2321
2322 /* silence compiler warnings */
2323 u_char inb(u_int);
2324 void outb(u_int, u_char);
2325
2326 u_char
2327 inb(u_int port)
2328 {
2329         u_char  data;
2330         /*
2331          * We use %%dx and not %1 here because i/o is done at %dx and not at
2332          * %edx, while gcc generates inferior code (movw instead of movl)
2333          * if we tell it to load (u_short) port.
2334          */
2335         __asm __volatile("inb %%dx,%0" : "=a" (data) : "d" (port));
2336         return (data);
2337 }
2338
2339 void
2340 outb(u_int port, u_char data)
2341 {
2342         u_char  al;
2343         /*
2344          * Use an unnecessary assignment to help gcc's register allocator.
2345          * This make a large difference for gcc-1.40 and a tiny difference
2346          * for gcc-2.6.0.  For gcc-1.40, al had to be ``asm("ax")'' for
2347          * best results.  gcc-2.6.0 can't handle this.
2348          */
2349         al = data;
2350         __asm __volatile("outb %0,%%dx" : : "a" (al), "d" (port));
2351 }
2352
2353 #endif /* DDB */
2354
2355
2356
2357 #include "opt_cpu.h"
2358
2359
2360 /*
2361  * initialize all the SMP locks
2362  */
2363
2364 /* critical region when masking or unmasking interupts */
2365 struct spinlock_deprecated imen_spinlock;
2366
2367 /* critical region for old style disable_intr/enable_intr */
2368 struct spinlock_deprecated mpintr_spinlock;
2369
2370 /* critical region around INTR() routines */
2371 struct spinlock_deprecated intr_spinlock;
2372
2373 /* lock region used by kernel profiling */
2374 struct spinlock_deprecated mcount_spinlock;
2375
2376 /* locks com (tty) data/hardware accesses: a FASTINTR() */
2377 struct spinlock_deprecated com_spinlock;
2378
2379 /* lock regions around the clock hardware */
2380 struct spinlock_deprecated clock_spinlock;
2381
2382 static void
2383 init_locks(void)
2384 {
2385 #ifdef SMP
2386         /*
2387          * Get the initial mplock with a count of 1 for the BSP.
2388          * This uses a LOGICAL cpu ID, ie BSP == 0.
2389          */
2390         cpu_get_initial_mplock();
2391 #endif
2392         /* DEPRECATED */
2393         spin_lock_init(&mcount_spinlock);
2394         spin_lock_init(&intr_spinlock);
2395         spin_lock_init(&mpintr_spinlock);
2396         spin_lock_init(&imen_spinlock);
2397         spin_lock_init(&com_spinlock);
2398         spin_lock_init(&clock_spinlock);
2399
2400         /* our token pool needs to work early */
2401         lwkt_token_pool_init();
2402 }
2403