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