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