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