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