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