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