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