xref: /illumos-gate/usr/src/uts/i86pc/os/machdep.c (revision aedf2b3bb56b025fcaf87b49ec6c8aeea07f16d7)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 #include <sys/types.h>
28 #include <sys/t_lock.h>
29 #include <sys/param.h>
30 #include <sys/segments.h>
31 #include <sys/sysmacros.h>
32 #include <sys/signal.h>
33 #include <sys/systm.h>
34 #include <sys/user.h>
35 #include <sys/mman.h>
36 #include <sys/vm.h>
37 
38 #include <sys/disp.h>
39 #include <sys/class.h>
40 
41 #include <sys/proc.h>
42 #include <sys/buf.h>
43 #include <sys/kmem.h>
44 
45 #include <sys/reboot.h>
46 #include <sys/uadmin.h>
47 #include <sys/callb.h>
48 
49 #include <sys/cred.h>
50 #include <sys/vnode.h>
51 #include <sys/file.h>
52 
53 #include <sys/procfs.h>
54 #include <sys/acct.h>
55 
56 #include <sys/vfs.h>
57 #include <sys/dnlc.h>
58 #include <sys/var.h>
59 #include <sys/cmn_err.h>
60 #include <sys/utsname.h>
61 #include <sys/debug.h>
62 
63 #include <sys/dumphdr.h>
64 #include <sys/bootconf.h>
65 #include <sys/varargs.h>
66 #include <sys/promif.h>
67 #include <sys/modctl.h>
68 
69 #include <sys/consdev.h>
70 #include <sys/frame.h>
71 
72 #include <sys/sunddi.h>
73 #include <sys/ddidmareq.h>
74 #include <sys/psw.h>
75 #include <sys/regset.h>
76 #include <sys/privregs.h>
77 #include <sys/clock.h>
78 #include <sys/tss.h>
79 #include <sys/cpu.h>
80 #include <sys/stack.h>
81 #include <sys/trap.h>
82 #include <sys/pic.h>
83 #include <vm/hat.h>
84 #include <vm/anon.h>
85 #include <vm/as.h>
86 #include <vm/page.h>
87 #include <vm/seg.h>
88 #include <vm/seg_kmem.h>
89 #include <vm/seg_map.h>
90 #include <vm/seg_vn.h>
91 #include <vm/seg_kp.h>
92 #include <vm/hat_i86.h>
93 #include <sys/swap.h>
94 #include <sys/thread.h>
95 #include <sys/sysconf.h>
96 #include <sys/vm_machparam.h>
97 #include <sys/archsystm.h>
98 #include <sys/machsystm.h>
99 #include <sys/machlock.h>
100 #include <sys/x_call.h>
101 #include <sys/instance.h>
102 
103 #include <sys/time.h>
104 #include <sys/smp_impldefs.h>
105 #include <sys/psm_types.h>
106 #include <sys/atomic.h>
107 #include <sys/panic.h>
108 #include <sys/cpuvar.h>
109 #include <sys/dtrace.h>
110 #include <sys/bl.h>
111 #include <sys/nvpair.h>
112 #include <sys/x86_archext.h>
113 #include <sys/pool_pset.h>
114 #include <sys/autoconf.h>
115 #include <sys/mem.h>
116 #include <sys/dumphdr.h>
117 #include <sys/compress.h>
118 #include <sys/cpu_module.h>
119 #if defined(__xpv)
120 #include <sys/hypervisor.h>
121 #include <sys/xpv_panic.h>
122 #endif
123 
124 #include <sys/fastboot.h>
125 #include <sys/machelf.h>
126 #include <sys/kobj.h>
127 #include <sys/multiboot.h>
128 
129 #ifdef	TRAPTRACE
130 #include <sys/traptrace.h>
131 #endif	/* TRAPTRACE */
132 
133 #include <sys/clock_impl.h>
134 
135 extern void audit_enterprom(int);
136 extern void audit_exitprom(int);
137 
138 /*
139  * Occassionally the kernel knows better whether to power-off or reboot.
140  */
141 int force_shutdown_method = AD_UNKNOWN;
142 
143 /*
144  * The panicbuf array is used to record messages and state:
145  */
146 char panicbuf[PANICBUFSIZE];
147 
148 /*
149  * maxphys - used during physio
150  * klustsize - used for klustering by swapfs and specfs
151  */
152 int maxphys = 56 * 1024;    /* XXX See vm_subr.c - max b_count in physio */
153 int klustsize = 56 * 1024;
154 
155 caddr_t	p0_va;		/* Virtual address for accessing physical page 0 */
156 
157 /*
158  * defined here, though unused on x86,
159  * to make kstat_fr.c happy.
160  */
161 int vac;
162 
163 void debug_enter(char *);
164 
165 extern void pm_cfb_check_and_powerup(void);
166 extern void pm_cfb_rele(void);
167 
168 extern fastboot_info_t newkernel;
169 
170 /*
171  * Machine dependent code to reboot.
172  * "mdep" is interpreted as a character pointer; if non-null, it is a pointer
173  * to a string to be used as the argument string when rebooting.
174  *
175  * "invoke_cb" is a boolean. It is set to true when mdboot() can safely
176  * invoke CB_CL_MDBOOT callbacks before shutting the system down, i.e. when
177  * we are in a normal shutdown sequence (interrupts are not blocked, the
178  * system is not panic'ing or being suspended).
179  */
180 /*ARGSUSED*/
181 void
182 mdboot(int cmd, int fcn, char *mdep, boolean_t invoke_cb)
183 {
184 	processorid_t bootcpuid = 0;
185 	static int is_first_quiesce = 1;
186 	static int is_first_reset = 1;
187 	int reset_status = 0;
188 	static char fallback_str[] = "Falling back to regular reboot.\n";
189 
190 	if (fcn == AD_FASTREBOOT && !newkernel.fi_valid)
191 		fcn = AD_BOOT;
192 
193 	if (!panicstr) {
194 		kpreempt_disable();
195 		if (fcn == AD_FASTREBOOT) {
196 			mutex_enter(&cpu_lock);
197 			if (CPU_ACTIVE(cpu_get(bootcpuid))) {
198 				affinity_set(bootcpuid);
199 			}
200 			mutex_exit(&cpu_lock);
201 		} else {
202 			affinity_set(CPU_CURRENT);
203 		}
204 	}
205 
206 	if (force_shutdown_method != AD_UNKNOWN)
207 		fcn = force_shutdown_method;
208 
209 	/*
210 	 * XXX - rconsvp is set to NULL to ensure that output messages
211 	 * are sent to the underlying "hardware" device using the
212 	 * monitor's printf routine since we are in the process of
213 	 * either rebooting or halting the machine.
214 	 */
215 	rconsvp = NULL;
216 
217 	/*
218 	 * Print the reboot message now, before pausing other cpus.
219 	 * There is a race condition in the printing support that
220 	 * can deadlock multiprocessor machines.
221 	 */
222 	if (!(fcn == AD_HALT || fcn == AD_POWEROFF))
223 		prom_printf("rebooting...\n");
224 
225 	if (IN_XPV_PANIC())
226 		reset();
227 
228 	/*
229 	 * We can't bring up the console from above lock level, so do it now
230 	 */
231 	pm_cfb_check_and_powerup();
232 
233 	/* make sure there are no more changes to the device tree */
234 	devtree_freeze();
235 
236 	if (invoke_cb)
237 		(void) callb_execute_class(CB_CL_MDBOOT, NULL);
238 
239 	/*
240 	 * Clear any unresolved UEs from memory.
241 	 */
242 	page_retire_mdboot();
243 
244 #if defined(__xpv)
245 	/*
246 	 * XXPV	Should probably think some more about how we deal
247 	 *	with panicing before it's really safe to panic.
248 	 *	On hypervisors, we reboot very quickly..  Perhaps panic
249 	 *	should only attempt to recover by rebooting if,
250 	 *	say, we were able to mount the root filesystem,
251 	 *	or if we successfully launched init(1m).
252 	 */
253 	if (panicstr && proc_init == NULL)
254 		(void) HYPERVISOR_shutdown(SHUTDOWN_poweroff);
255 #endif
256 	/*
257 	 * stop other cpus and raise our priority.  since there is only
258 	 * one active cpu after this, and our priority will be too high
259 	 * for us to be preempted, we're essentially single threaded
260 	 * from here on out.
261 	 */
262 	(void) spl6();
263 	if (!panicstr) {
264 		mutex_enter(&cpu_lock);
265 		pause_cpus(NULL);
266 		mutex_exit(&cpu_lock);
267 	}
268 
269 	/*
270 	 * If the system is panicking, the preloaded kernel is valid, and
271 	 * fastreboot_onpanic has been set, and the system has been up for
272 	 * longer than fastreboot_onpanic_uptime (default to 10 minutes),
273 	 * choose Fast Reboot.
274 	 */
275 	if (fcn == AD_BOOT && panicstr && newkernel.fi_valid &&
276 	    fastreboot_onpanic &&
277 	    (panic_lbolt - lbolt_at_boot) > fastreboot_onpanic_uptime) {
278 		fcn = AD_FASTREBOOT;
279 	}
280 
281 	/*
282 	 * Try to quiesce devices.
283 	 */
284 	if (is_first_quiesce) {
285 		/*
286 		 * Clear is_first_quiesce before calling quiesce_devices()
287 		 * so that if quiesce_devices() causes panics, it will not
288 		 * be invoked again.
289 		 */
290 		is_first_quiesce = 0;
291 
292 		quiesce_active = 1;
293 		quiesce_devices(ddi_root_node(), &reset_status);
294 		if (reset_status == -1) {
295 			if (fcn == AD_FASTREBOOT && !force_fastreboot) {
296 				prom_printf("Driver(s) not capable of fast "
297 				    "reboot.\n");
298 				prom_printf(fallback_str);
299 				fastreboot_capable = 0;
300 				fcn = AD_BOOT;
301 			} else if (fcn != AD_FASTREBOOT)
302 				fastreboot_capable = 0;
303 		}
304 		quiesce_active = 0;
305 	}
306 
307 	/*
308 	 * Try to reset devices. reset_leaves() should only be called
309 	 * a) when there are no other threads that could be accessing devices,
310 	 *    and
311 	 * b) on a system that's not capable of fast reboot (fastreboot_capable
312 	 *    being 0), or on a system where quiesce_devices() failed to
313 	 *    complete (quiesce_active being 1).
314 	 */
315 	if (is_first_reset && (!fastreboot_capable || quiesce_active)) {
316 		/*
317 		 * Clear is_first_reset before calling reset_devices()
318 		 * so that if reset_devices() causes panics, it will not
319 		 * be invoked again.
320 		 */
321 		is_first_reset = 0;
322 		reset_leaves();
323 	}
324 
325 	/* Verify newkernel checksum */
326 	if (fastreboot_capable && fcn == AD_FASTREBOOT &&
327 	    fastboot_cksum_verify(&newkernel) != 0) {
328 		fastreboot_capable = 0;
329 		prom_printf("Fast reboot: checksum failed for the new "
330 		    "kernel.\n");
331 		prom_printf(fallback_str);
332 	}
333 
334 	(void) spl8();
335 
336 	if (fastreboot_capable && fcn == AD_FASTREBOOT) {
337 		/*
338 		 * psm_shutdown is called within fast_reboot()
339 		 */
340 		fast_reboot();
341 	} else {
342 		(*psm_shutdownf)(cmd, fcn);
343 
344 		if (fcn == AD_HALT || fcn == AD_POWEROFF)
345 			halt((char *)NULL);
346 		else
347 			prom_reboot("");
348 	}
349 	/*NOTREACHED*/
350 }
351 
352 /* mdpreboot - may be called prior to mdboot while root fs still mounted */
353 /*ARGSUSED*/
354 void
355 mdpreboot(int cmd, int fcn, char *mdep)
356 {
357 	if (fcn == AD_FASTREBOOT && !fastreboot_capable) {
358 		fcn = AD_BOOT;
359 #ifdef	__xpv
360 		cmn_err(CE_WARN, "Fast reboot is not supported on xVM");
361 #else
362 		cmn_err(CE_WARN,
363 		    "Fast reboot is not supported on this platform");
364 #endif
365 	}
366 
367 	if (fcn == AD_FASTREBOOT) {
368 		fastboot_load_kernel(mdep);
369 		if (!newkernel.fi_valid)
370 			fcn = AD_BOOT;
371 	}
372 
373 	(*psm_preshutdownf)(cmd, fcn);
374 }
375 
376 static void
377 stop_other_cpus(void)
378 {
379 	ulong_t s = clear_int_flag(); /* fast way to keep CPU from changing */
380 	cpuset_t xcset;
381 
382 	CPUSET_ALL_BUT(xcset, CPU->cpu_id);
383 	xc_priority(0, 0, 0, CPUSET2BV(xcset), (xc_func_t)mach_cpu_halt);
384 	restore_int_flag(s);
385 }
386 
387 /*
388  *	Machine dependent abort sequence handling
389  */
390 void
391 abort_sequence_enter(char *msg)
392 {
393 	if (abort_enable == 0) {
394 		if (audit_active)
395 			audit_enterprom(0);
396 		return;
397 	}
398 	if (audit_active)
399 		audit_enterprom(1);
400 	debug_enter(msg);
401 	if (audit_active)
402 		audit_exitprom(1);
403 }
404 
405 /*
406  * Enter debugger.  Called when the user types ctrl-alt-d or whenever
407  * code wants to enter the debugger and possibly resume later.
408  */
409 void
410 debug_enter(
411 	char	*msg)		/* message to print, possibly NULL */
412 {
413 	if (dtrace_debugger_init != NULL)
414 		(*dtrace_debugger_init)();
415 
416 	if (msg)
417 		prom_printf("%s\n", msg);
418 
419 	if (boothowto & RB_DEBUG)
420 		kmdb_enter();
421 
422 	if (dtrace_debugger_fini != NULL)
423 		(*dtrace_debugger_fini)();
424 }
425 
426 void
427 reset(void)
428 {
429 	extern	void acpi_reset_system();
430 #if !defined(__xpv)
431 	ushort_t *bios_memchk;
432 
433 	/*
434 	 * Can't use psm_map_phys or acpi_reset_system before the hat is
435 	 * initialized.
436 	 */
437 	if (khat_running) {
438 		bios_memchk = (ushort_t *)psm_map_phys(0x472,
439 		    sizeof (ushort_t), PROT_READ | PROT_WRITE);
440 		if (bios_memchk)
441 			*bios_memchk = 0x1234;	/* bios memory check disable */
442 
443 		if (options_dip != NULL &&
444 		    ddi_prop_exists(DDI_DEV_T_ANY, ddi_root_node(), 0,
445 		    "efi-systab")) {
446 			efi_reset();
447 		}
448 
449 		/*
450 		 * The problem with using stubs is that we can call
451 		 * acpi_reset_system only after the kernel is up and running.
452 		 *
453 		 * We should create a global state to keep track of how far
454 		 * up the kernel is but for the time being we will depend on
455 		 * bootops. bootops cleared in startup_end().
456 		 */
457 		if (bootops == NULL)
458 			acpi_reset_system();
459 	}
460 
461 	pc_reset();
462 #else
463 	if (IN_XPV_PANIC()) {
464 		if (khat_running && bootops == NULL) {
465 			acpi_reset_system();
466 		}
467 
468 		pc_reset();
469 	}
470 
471 	(void) HYPERVISOR_shutdown(SHUTDOWN_reboot);
472 	panic("HYPERVISOR_shutdown() failed");
473 #endif
474 	/*NOTREACHED*/
475 }
476 
477 /*
478  * Halt the machine and return to the monitor
479  */
480 void
481 halt(char *s)
482 {
483 	stop_other_cpus();	/* send stop signal to other CPUs */
484 	if (s)
485 		prom_printf("(%s) \n", s);
486 	prom_exit_to_mon();
487 	/*NOTREACHED*/
488 }
489 
490 /*
491  * Initiate interrupt redistribution.
492  */
493 void
494 i_ddi_intr_redist_all_cpus()
495 {
496 }
497 
498 /*
499  * XXX These probably ought to live somewhere else
500  * XXX They are called from mem.c
501  */
502 
503 /*
504  * Convert page frame number to an OBMEM page frame number
505  * (i.e. put in the type bits -- zero for this implementation)
506  */
507 pfn_t
508 impl_obmem_pfnum(pfn_t pf)
509 {
510 	return (pf);
511 }
512 
513 #ifdef	NM_DEBUG
514 int nmi_test = 0;	/* checked in intentry.s during clock int */
515 int nmtest = -1;
516 nmfunc1(arg, rp)
517 int	arg;
518 struct regs *rp;
519 {
520 	printf("nmi called with arg = %x, regs = %x\n", arg, rp);
521 	nmtest += 50;
522 	if (arg == nmtest) {
523 		printf("ip = %x\n", rp->r_pc);
524 		return (1);
525 	}
526 	return (0);
527 }
528 
529 #endif
530 
531 #include <sys/bootsvcs.h>
532 
533 /* Hacked up initialization for initial kernel check out is HERE. */
534 /* The basic steps are: */
535 /*	kernel bootfuncs definition/initialization for KADB */
536 /*	kadb bootfuncs pointer initialization */
537 /*	putchar/getchar (interrupts disabled) */
538 
539 /* kadb bootfuncs pointer initialization */
540 
541 int
542 sysp_getchar()
543 {
544 	int i;
545 	ulong_t s;
546 
547 	if (cons_polledio == NULL) {
548 		/* Uh oh */
549 		prom_printf("getchar called with no console\n");
550 		for (;;)
551 			/* LOOP FOREVER */;
552 	}
553 
554 	s = clear_int_flag();
555 	i = cons_polledio->cons_polledio_getchar(
556 	    cons_polledio->cons_polledio_argument);
557 	restore_int_flag(s);
558 	return (i);
559 }
560 
561 void
562 sysp_putchar(int c)
563 {
564 	ulong_t s;
565 
566 	/*
567 	 * We have no alternative but to drop the output on the floor.
568 	 */
569 	if (cons_polledio == NULL ||
570 	    cons_polledio->cons_polledio_putchar == NULL)
571 		return;
572 
573 	s = clear_int_flag();
574 	cons_polledio->cons_polledio_putchar(
575 	    cons_polledio->cons_polledio_argument, c);
576 	restore_int_flag(s);
577 }
578 
579 int
580 sysp_ischar()
581 {
582 	int i;
583 	ulong_t s;
584 
585 	if (cons_polledio == NULL ||
586 	    cons_polledio->cons_polledio_ischar == NULL)
587 		return (0);
588 
589 	s = clear_int_flag();
590 	i = cons_polledio->cons_polledio_ischar(
591 	    cons_polledio->cons_polledio_argument);
592 	restore_int_flag(s);
593 	return (i);
594 }
595 
596 int
597 goany(void)
598 {
599 	prom_printf("Type any key to continue ");
600 	(void) prom_getchar();
601 	prom_printf("\n");
602 	return (1);
603 }
604 
605 static struct boot_syscalls kern_sysp = {
606 	sysp_getchar,	/*	unchar	(*getchar)();	7  */
607 	sysp_putchar,	/*	int	(*putchar)();	8  */
608 	sysp_ischar,	/*	int	(*ischar)();	9  */
609 };
610 
611 #if defined(__xpv)
612 int using_kern_polledio;
613 #endif
614 
615 void
616 kadb_uses_kernel()
617 {
618 	/*
619 	 * This routine is now totally misnamed, since it does not in fact
620 	 * control kadb's I/O; it only controls the kernel's prom_* I/O.
621 	 */
622 	sysp = &kern_sysp;
623 #if defined(__xpv)
624 	using_kern_polledio = 1;
625 #endif
626 }
627 
628 /*
629  *	the interface to the outside world
630  */
631 
632 /*
633  * poll_port -- wait for a register to achieve a
634  *		specific state.  Arguments are a mask of bits we care about,
635  *		and two sub-masks.  To return normally, all the bits in the
636  *		first sub-mask must be ON, all the bits in the second sub-
637  *		mask must be OFF.  If about seconds pass without the register
638  *		achieving the desired bit configuration, we return 1, else
639  *		0.
640  */
641 int
642 poll_port(ushort_t port, ushort_t mask, ushort_t onbits, ushort_t offbits)
643 {
644 	int i;
645 	ushort_t maskval;
646 
647 	for (i = 500000; i; i--) {
648 		maskval = inb(port) & mask;
649 		if (((maskval & onbits) == onbits) &&
650 		    ((maskval & offbits) == 0))
651 			return (0);
652 		drv_usecwait(10);
653 	}
654 	return (1);
655 }
656 
657 /*
658  * set_idle_cpu is called from idle() when a CPU becomes idle.
659  */
660 /*LINTED: static unused */
661 static uint_t last_idle_cpu;
662 
663 /*ARGSUSED*/
664 void
665 set_idle_cpu(int cpun)
666 {
667 	last_idle_cpu = cpun;
668 	(*psm_set_idle_cpuf)(cpun);
669 }
670 
671 /*
672  * unset_idle_cpu is called from idle() when a CPU is no longer idle.
673  */
674 /*ARGSUSED*/
675 void
676 unset_idle_cpu(int cpun)
677 {
678 	(*psm_unset_idle_cpuf)(cpun);
679 }
680 
681 /*
682  * This routine is almost correct now, but not quite.  It still needs the
683  * equivalent concept of "hres_last_tick", just like on the sparc side.
684  * The idea is to take a snapshot of the hi-res timer while doing the
685  * hrestime_adj updates under hres_lock in locore, so that the small
686  * interval between interrupt assertion and interrupt processing is
687  * accounted for correctly.  Once we have this, the code below should
688  * be modified to subtract off hres_last_tick rather than hrtime_base.
689  *
690  * I'd have done this myself, but I don't have source to all of the
691  * vendor-specific hi-res timer routines (grrr...).  The generic hook I
692  * need is something like "gethrtime_unlocked()", which would be just like
693  * gethrtime() but would assume that you're already holding CLOCK_LOCK().
694  * This is what the GET_HRTIME() macro is for on sparc (although it also
695  * serves the function of making time available without a function call
696  * so you don't take a register window overflow while traps are disabled).
697  */
698 void
699 pc_gethrestime(timestruc_t *tp)
700 {
701 	int lock_prev;
702 	timestruc_t now;
703 	int nslt;		/* nsec since last tick */
704 	int adj;		/* amount of adjustment to apply */
705 
706 loop:
707 	lock_prev = hres_lock;
708 	now = hrestime;
709 	nslt = (int)(gethrtime() - hres_last_tick);
710 	if (nslt < 0) {
711 		/*
712 		 * nslt < 0 means a tick came between sampling
713 		 * gethrtime() and hres_last_tick; restart the loop
714 		 */
715 
716 		goto loop;
717 	}
718 	now.tv_nsec += nslt;
719 	if (hrestime_adj != 0) {
720 		if (hrestime_adj > 0) {
721 			adj = (nslt >> ADJ_SHIFT);
722 			if (adj > hrestime_adj)
723 				adj = (int)hrestime_adj;
724 		} else {
725 			adj = -(nslt >> ADJ_SHIFT);
726 			if (adj < hrestime_adj)
727 				adj = (int)hrestime_adj;
728 		}
729 		now.tv_nsec += adj;
730 	}
731 	while ((unsigned long)now.tv_nsec >= NANOSEC) {
732 
733 		/*
734 		 * We might have a large adjustment or have been in the
735 		 * debugger for a long time; take care of (at most) four
736 		 * of those missed seconds (tv_nsec is 32 bits, so
737 		 * anything >4s will be wrapping around).  However,
738 		 * anything more than 2 seconds out of sync will trigger
739 		 * timedelta from clock() to go correct the time anyway,
740 		 * so do what we can, and let the big crowbar do the
741 		 * rest.  A similar correction while loop exists inside
742 		 * hres_tick(); in all cases we'd like tv_nsec to
743 		 * satisfy 0 <= tv_nsec < NANOSEC to avoid confusing
744 		 * user processes, but if tv_sec's a little behind for a
745 		 * little while, that's OK; time still monotonically
746 		 * increases.
747 		 */
748 
749 		now.tv_nsec -= NANOSEC;
750 		now.tv_sec++;
751 	}
752 	if ((hres_lock & ~1) != lock_prev)
753 		goto loop;
754 
755 	*tp = now;
756 }
757 
758 void
759 gethrestime_lasttick(timespec_t *tp)
760 {
761 	int s;
762 
763 	s = hr_clock_lock();
764 	*tp = hrestime;
765 	hr_clock_unlock(s);
766 }
767 
768 time_t
769 gethrestime_sec(void)
770 {
771 	timestruc_t now;
772 
773 	gethrestime(&now);
774 	return (now.tv_sec);
775 }
776 
777 /*
778  * Initialize a kernel thread's stack
779  */
780 
781 caddr_t
782 thread_stk_init(caddr_t stk)
783 {
784 	ASSERT(((uintptr_t)stk & (STACK_ALIGN - 1)) == 0);
785 	return (stk - SA(MINFRAME));
786 }
787 
788 /*
789  * Initialize lwp's kernel stack.
790  */
791 
792 #ifdef TRAPTRACE
793 /*
794  * There's a tricky interdependency here between use of sysenter and
795  * TRAPTRACE which needs recording to avoid future confusion (this is
796  * about the third time I've re-figured this out ..)
797  *
798  * Here's how debugging lcall works with TRAPTRACE.
799  *
800  * 1 We're in userland with a breakpoint on the lcall instruction.
801  * 2 We execute the instruction - the instruction pushes the userland
802  *   %ss, %esp, %efl, %cs, %eip on the stack and zips into the kernel
803  *   via the call gate.
804  * 3 The hardware raises a debug trap in kernel mode, the hardware
805  *   pushes %efl, %cs, %eip and gets to dbgtrap via the idt.
806  * 4 dbgtrap pushes the error code and trapno and calls cmntrap
807  * 5 cmntrap finishes building a trap frame
808  * 6 The TRACE_REGS macros in cmntrap copy a REGSIZE worth chunk
809  *   off the stack into the traptrace buffer.
810  *
811  * This means that the traptrace buffer contains the wrong values in
812  * %esp and %ss, but everything else in there is correct.
813  *
814  * Here's how debugging sysenter works with TRAPTRACE.
815  *
816  * a We're in userland with a breakpoint on the sysenter instruction.
817  * b We execute the instruction - the instruction pushes -nothing-
818  *   on the stack, but sets %cs, %eip, %ss, %esp to prearranged
819  *   values to take us to sys_sysenter, at the top of the lwp's
820  *   stack.
821  * c goto 3
822  *
823  * At this point, because we got into the kernel without the requisite
824  * five pushes on the stack, if we didn't make extra room, we'd
825  * end up with the TRACE_REGS macro fetching the saved %ss and %esp
826  * values from negative (unmapped) stack addresses -- which really bites.
827  * That's why we do the '-= 8' below.
828  *
829  * XXX	Note that reading "up" lwp0's stack works because t0 is declared
830  *	right next to t0stack in locore.s
831  */
832 #endif
833 
834 caddr_t
835 lwp_stk_init(klwp_t *lwp, caddr_t stk)
836 {
837 	caddr_t oldstk;
838 	struct pcb *pcb = &lwp->lwp_pcb;
839 
840 	oldstk = stk;
841 	stk -= SA(sizeof (struct regs) + SA(MINFRAME));
842 #ifdef TRAPTRACE
843 	stk -= 2 * sizeof (greg_t); /* space for phony %ss:%sp (see above) */
844 #endif
845 	stk = (caddr_t)((uintptr_t)stk & ~(STACK_ALIGN - 1ul));
846 	bzero(stk, oldstk - stk);
847 	lwp->lwp_regs = (void *)(stk + SA(MINFRAME));
848 
849 	/*
850 	 * Arrange that the virtualized %fs and %gs GDT descriptors
851 	 * have a well-defined initial state (present, ring 3
852 	 * and of type data).
853 	 */
854 #if defined(__amd64)
855 	if (lwp_getdatamodel(lwp) == DATAMODEL_NATIVE)
856 		pcb->pcb_fsdesc = pcb->pcb_gsdesc = zero_udesc;
857 	else
858 		pcb->pcb_fsdesc = pcb->pcb_gsdesc = zero_u32desc;
859 #elif defined(__i386)
860 	pcb->pcb_fsdesc = pcb->pcb_gsdesc = zero_udesc;
861 #endif	/* __i386 */
862 	lwp_installctx(lwp);
863 	return (stk);
864 }
865 
866 /*ARGSUSED*/
867 void
868 lwp_stk_fini(klwp_t *lwp)
869 {}
870 
871 /*
872  * If we're not the panic CPU, we wait in panic_idle for reboot.
873  */
874 void
875 panic_idle(void)
876 {
877 	splx(ipltospl(CLOCK_LEVEL));
878 	(void) setjmp(&curthread->t_pcb);
879 
880 	dumpsys_helper();
881 
882 #ifndef __xpv
883 	for (;;)
884 		i86_halt();
885 #else
886 	for (;;)
887 		;
888 #endif
889 }
890 
891 /*
892  * Stop the other CPUs by cross-calling them and forcing them to enter
893  * the panic_idle() loop above.
894  */
895 /*ARGSUSED*/
896 void
897 panic_stopcpus(cpu_t *cp, kthread_t *t, int spl)
898 {
899 	processorid_t i;
900 	cpuset_t xcset;
901 
902 	/*
903 	 * In the case of a Xen panic, the hypervisor has already stopped
904 	 * all of the CPUs.
905 	 */
906 	if (!IN_XPV_PANIC()) {
907 		(void) splzs();
908 
909 		CPUSET_ALL_BUT(xcset, cp->cpu_id);
910 		xc_priority(0, 0, 0, CPUSET2BV(xcset), (xc_func_t)panic_idle);
911 	}
912 
913 	for (i = 0; i < NCPU; i++) {
914 		if (i != cp->cpu_id && cpu[i] != NULL &&
915 		    (cpu[i]->cpu_flags & CPU_EXISTS))
916 			cpu[i]->cpu_flags |= CPU_QUIESCED;
917 	}
918 }
919 
920 /*
921  * Platform callback following each entry to panicsys().
922  */
923 /*ARGSUSED*/
924 void
925 panic_enter_hw(int spl)
926 {
927 	/* Nothing to do here */
928 }
929 
930 /*
931  * Platform-specific code to execute after panicstr is set: we invoke
932  * the PSM entry point to indicate that a panic has occurred.
933  */
934 /*ARGSUSED*/
935 void
936 panic_quiesce_hw(panic_data_t *pdp)
937 {
938 	psm_notifyf(PSM_PANIC_ENTER);
939 
940 	cmi_panic_callback();
941 
942 #ifdef	TRAPTRACE
943 	/*
944 	 * Turn off TRAPTRACE
945 	 */
946 	TRAPTRACE_FREEZE;
947 #endif	/* TRAPTRACE */
948 }
949 
950 /*
951  * Platform callback prior to writing crash dump.
952  */
953 /*ARGSUSED*/
954 void
955 panic_dump_hw(int spl)
956 {
957 	/* Nothing to do here */
958 }
959 
960 void *
961 plat_traceback(void *fpreg)
962 {
963 #ifdef __xpv
964 	if (IN_XPV_PANIC())
965 		return (xpv_traceback(fpreg));
966 #endif
967 	return (fpreg);
968 }
969 
970 /*ARGSUSED*/
971 void
972 plat_tod_fault(enum tod_fault_type tod_bad)
973 {}
974 
975 /*ARGSUSED*/
976 int
977 blacklist(int cmd, const char *scheme, nvlist_t *fmri, const char *class)
978 {
979 	return (ENOTSUP);
980 }
981 
982 /*
983  * The underlying console output routines are protected by raising IPL in case
984  * we are still calling into the early boot services.  Once we start calling
985  * the kernel console emulator, it will disable interrupts completely during
986  * character rendering (see sysp_putchar, for example).  Refer to the comments
987  * and code in common/os/console.c for more information on these callbacks.
988  */
989 /*ARGSUSED*/
990 int
991 console_enter(int busy)
992 {
993 	return (splzs());
994 }
995 
996 /*ARGSUSED*/
997 void
998 console_exit(int busy, int spl)
999 {
1000 	splx(spl);
1001 }
1002 
1003 /*
1004  * Allocate a region of virtual address space, unmapped.
1005  * Stubbed out except on sparc, at least for now.
1006  */
1007 /*ARGSUSED*/
1008 void *
1009 boot_virt_alloc(void *addr, size_t size)
1010 {
1011 	return (addr);
1012 }
1013 
1014 volatile unsigned long	tenmicrodata;
1015 
1016 void
1017 tenmicrosec(void)
1018 {
1019 	extern int gethrtime_hires;
1020 
1021 	if (gethrtime_hires) {
1022 		hrtime_t start, end;
1023 		start = end =  gethrtime();
1024 		while ((end - start) < (10 * (NANOSEC / MICROSEC))) {
1025 			SMT_PAUSE();
1026 			end = gethrtime();
1027 		}
1028 	} else {
1029 #if defined(__xpv)
1030 		hrtime_t newtime;
1031 
1032 		newtime = xpv_gethrtime() + 10000; /* now + 10 us */
1033 		while (xpv_gethrtime() < newtime)
1034 			SMT_PAUSE();
1035 #else	/* __xpv */
1036 		int i;
1037 
1038 		/*
1039 		 * Artificial loop to induce delay.
1040 		 */
1041 		for (i = 0; i < microdata; i++)
1042 			tenmicrodata = microdata;
1043 #endif	/* __xpv */
1044 	}
1045 }
1046 
1047 /*
1048  * get_cpu_mstate() is passed an array of timestamps, NCMSTATES
1049  * long, and it fills in the array with the time spent on cpu in
1050  * each of the mstates, where time is returned in nsec.
1051  *
1052  * No guarantee is made that the returned values in times[] will
1053  * monotonically increase on sequential calls, although this will
1054  * be true in the long run. Any such guarantee must be handled by
1055  * the caller, if needed. This can happen if we fail to account
1056  * for elapsed time due to a generation counter conflict, yet we
1057  * did account for it on a prior call (see below).
1058  *
1059  * The complication is that the cpu in question may be updating
1060  * its microstate at the same time that we are reading it.
1061  * Because the microstate is only updated when the CPU's state
1062  * changes, the values in cpu_intracct[] can be indefinitely out
1063  * of date. To determine true current values, it is necessary to
1064  * compare the current time with cpu_mstate_start, and add the
1065  * difference to times[cpu_mstate].
1066  *
1067  * This can be a problem if those values are changing out from
1068  * under us. Because the code path in new_cpu_mstate() is
1069  * performance critical, we have not added a lock to it. Instead,
1070  * we have added a generation counter. Before beginning
1071  * modifications, the counter is set to 0. After modifications,
1072  * it is set to the old value plus one.
1073  *
1074  * get_cpu_mstate() will not consider the values of cpu_mstate
1075  * and cpu_mstate_start to be usable unless the value of
1076  * cpu_mstate_gen is both non-zero and unchanged, both before and
1077  * after reading the mstate information. Note that we must
1078  * protect against out-of-order loads around accesses to the
1079  * generation counter. Also, this is a best effort approach in
1080  * that we do not retry should the counter be found to have
1081  * changed.
1082  *
1083  * cpu_intracct[] is used to identify time spent in each CPU
1084  * mstate while handling interrupts. Such time should be reported
1085  * against system time, and so is subtracted out from its
1086  * corresponding cpu_acct[] time and added to
1087  * cpu_acct[CMS_SYSTEM].
1088  */
1089 
1090 void
1091 get_cpu_mstate(cpu_t *cpu, hrtime_t *times)
1092 {
1093 	int i;
1094 	hrtime_t now, start;
1095 	uint16_t gen;
1096 	uint16_t state;
1097 	hrtime_t intracct[NCMSTATES];
1098 
1099 	/*
1100 	 * Load all volatile state under the protection of membar.
1101 	 * cpu_acct[cpu_mstate] must be loaded to avoid double counting
1102 	 * of (now - cpu_mstate_start) by a change in CPU mstate that
1103 	 * arrives after we make our last check of cpu_mstate_gen.
1104 	 */
1105 
1106 	now = gethrtime_unscaled();
1107 	gen = cpu->cpu_mstate_gen;
1108 
1109 	membar_consumer();	/* guarantee load ordering */
1110 	start = cpu->cpu_mstate_start;
1111 	state = cpu->cpu_mstate;
1112 	for (i = 0; i < NCMSTATES; i++) {
1113 		intracct[i] = cpu->cpu_intracct[i];
1114 		times[i] = cpu->cpu_acct[i];
1115 	}
1116 	membar_consumer();	/* guarantee load ordering */
1117 
1118 	if (gen != 0 && gen == cpu->cpu_mstate_gen && now > start)
1119 		times[state] += now - start;
1120 
1121 	for (i = 0; i < NCMSTATES; i++) {
1122 		if (i == CMS_SYSTEM)
1123 			continue;
1124 		times[i] -= intracct[i];
1125 		if (times[i] < 0) {
1126 			intracct[i] += times[i];
1127 			times[i] = 0;
1128 		}
1129 		times[CMS_SYSTEM] += intracct[i];
1130 		scalehrtime(&times[i]);
1131 	}
1132 	scalehrtime(&times[CMS_SYSTEM]);
1133 }
1134 
1135 /*
1136  * This is a version of the rdmsr instruction that allows
1137  * an error code to be returned in the case of failure.
1138  */
1139 int
1140 checked_rdmsr(uint_t msr, uint64_t *value)
1141 {
1142 	if ((x86_feature & X86_MSR) == 0)
1143 		return (ENOTSUP);
1144 	*value = rdmsr(msr);
1145 	return (0);
1146 }
1147 
1148 /*
1149  * This is a version of the wrmsr instruction that allows
1150  * an error code to be returned in the case of failure.
1151  */
1152 int
1153 checked_wrmsr(uint_t msr, uint64_t value)
1154 {
1155 	if ((x86_feature & X86_MSR) == 0)
1156 		return (ENOTSUP);
1157 	wrmsr(msr, value);
1158 	return (0);
1159 }
1160 
1161 /*
1162  * The mem driver's usual method of using hat_devload() to establish a
1163  * temporary mapping will not work for foreign pages mapped into this
1164  * domain or for the special hypervisor-provided pages.  For the foreign
1165  * pages, we often don't know which domain owns them, so we can't ask the
1166  * hypervisor to set up a new mapping.  For the other pages, we don't have
1167  * a pfn, so we can't create a new PTE.  For these special cases, we do a
1168  * direct uiomove() from the existing kernel virtual address.
1169  */
1170 /*ARGSUSED*/
1171 int
1172 plat_mem_do_mmio(struct uio *uio, enum uio_rw rw)
1173 {
1174 #if defined(__xpv)
1175 	void *va = (void *)(uintptr_t)uio->uio_loffset;
1176 	off_t pageoff = uio->uio_loffset & PAGEOFFSET;
1177 	size_t nbytes = MIN((size_t)(PAGESIZE - pageoff),
1178 	    (size_t)uio->uio_iov->iov_len);
1179 
1180 	if ((rw == UIO_READ &&
1181 	    (va == HYPERVISOR_shared_info || va == xen_info)) ||
1182 	    (pfn_is_foreign(hat_getpfnum(kas.a_hat, va))))
1183 		return (uiomove(va, nbytes, rw, uio));
1184 #endif
1185 	return (ENOTSUP);
1186 }
1187 
1188 pgcnt_t
1189 num_phys_pages()
1190 {
1191 	pgcnt_t npages = 0;
1192 	struct memlist *mp;
1193 
1194 #if defined(__xpv)
1195 	if (DOMAIN_IS_INITDOMAIN(xen_info))
1196 		return (xpv_nr_phys_pages());
1197 #endif /* __xpv */
1198 
1199 	for (mp = phys_install; mp != NULL; mp = mp->next)
1200 		npages += mp->size >> PAGESHIFT;
1201 
1202 	return (npages);
1203 }
1204 
1205 /* cpu threshold for compressed dumps */
1206 #ifdef _LP64
1207 uint_t dump_plat_mincpu = DUMP_PLAT_X86_64_MINCPU;
1208 #else
1209 uint_t dump_plat_mincpu = DUMP_PLAT_X86_32_MINCPU;
1210 #endif
1211 
1212 int
1213 dump_plat_addr()
1214 {
1215 #ifdef __xpv
1216 	pfn_t pfn = mmu_btop(xen_info->shared_info) | PFN_IS_FOREIGN_MFN;
1217 	mem_vtop_t mem_vtop;
1218 	int cnt;
1219 
1220 	/*
1221 	 * On the hypervisor, we want to dump the page with shared_info on it.
1222 	 */
1223 	if (!IN_XPV_PANIC()) {
1224 		mem_vtop.m_as = &kas;
1225 		mem_vtop.m_va = HYPERVISOR_shared_info;
1226 		mem_vtop.m_pfn = pfn;
1227 		dumpvp_write(&mem_vtop, sizeof (mem_vtop_t));
1228 		cnt = 1;
1229 	} else {
1230 		cnt = dump_xpv_addr();
1231 	}
1232 	return (cnt);
1233 #else
1234 	return (0);
1235 #endif
1236 }
1237 
1238 void
1239 dump_plat_pfn()
1240 {
1241 #ifdef __xpv
1242 	pfn_t pfn = mmu_btop(xen_info->shared_info) | PFN_IS_FOREIGN_MFN;
1243 
1244 	if (!IN_XPV_PANIC())
1245 		dumpvp_write(&pfn, sizeof (pfn));
1246 	else
1247 		dump_xpv_pfn();
1248 #endif
1249 }
1250 
1251 /*ARGSUSED*/
1252 int
1253 dump_plat_data(void *dump_cbuf)
1254 {
1255 #ifdef __xpv
1256 	uint32_t csize;
1257 	int cnt;
1258 
1259 	if (!IN_XPV_PANIC()) {
1260 		csize = (uint32_t)compress(HYPERVISOR_shared_info, dump_cbuf,
1261 		    PAGESIZE);
1262 		dumpvp_write(&csize, sizeof (uint32_t));
1263 		dumpvp_write(dump_cbuf, csize);
1264 		cnt = 1;
1265 	} else {
1266 		cnt = dump_xpv_data(dump_cbuf);
1267 	}
1268 	return (cnt);
1269 #else
1270 	return (0);
1271 #endif
1272 }
1273 
1274 /*
1275  * Calculates a linear address, given the CS selector and PC values
1276  * by looking up the %cs selector process's LDT or the CPU's GDT.
1277  * proc->p_ldtlock must be held across this call.
1278  */
1279 int
1280 linear_pc(struct regs *rp, proc_t *p, caddr_t *linearp)
1281 {
1282 	user_desc_t	*descrp;
1283 	caddr_t		baseaddr;
1284 	uint16_t	idx = SELTOIDX(rp->r_cs);
1285 
1286 	ASSERT(rp->r_cs <= 0xFFFF);
1287 	ASSERT(MUTEX_HELD(&p->p_ldtlock));
1288 
1289 	if (SELISLDT(rp->r_cs)) {
1290 		/*
1291 		 * Currently 64 bit processes cannot have private LDTs.
1292 		 */
1293 		ASSERT(p->p_model != DATAMODEL_LP64);
1294 
1295 		if (p->p_ldt == NULL)
1296 			return (-1);
1297 
1298 		descrp = &p->p_ldt[idx];
1299 		baseaddr = (caddr_t)(uintptr_t)USEGD_GETBASE(descrp);
1300 
1301 		/*
1302 		 * Calculate the linear address (wraparound is not only ok,
1303 		 * it's expected behavior).  The cast to uint32_t is because
1304 		 * LDT selectors are only allowed in 32-bit processes.
1305 		 */
1306 		*linearp = (caddr_t)(uintptr_t)(uint32_t)((uintptr_t)baseaddr +
1307 		    rp->r_pc);
1308 	} else {
1309 #ifdef DEBUG
1310 		descrp = &CPU->cpu_gdt[idx];
1311 		baseaddr = (caddr_t)(uintptr_t)USEGD_GETBASE(descrp);
1312 		/* GDT-based descriptors' base addresses should always be 0 */
1313 		ASSERT(baseaddr == 0);
1314 #endif
1315 		*linearp = (caddr_t)(uintptr_t)rp->r_pc;
1316 	}
1317 
1318 	return (0);
1319 }
1320 
1321 /*
1322  * The implementation of dtrace_linear_pc is similar to the that of
1323  * linear_pc, above, but here we acquire p_ldtlock before accessing
1324  * p_ldt.  This implementation is used by the pid provider; we prefix
1325  * it with "dtrace_" to avoid inducing spurious tracing events.
1326  */
1327 int
1328 dtrace_linear_pc(struct regs *rp, proc_t *p, caddr_t *linearp)
1329 {
1330 	user_desc_t	*descrp;
1331 	caddr_t		baseaddr;
1332 	uint16_t	idx = SELTOIDX(rp->r_cs);
1333 
1334 	ASSERT(rp->r_cs <= 0xFFFF);
1335 
1336 	if (SELISLDT(rp->r_cs)) {
1337 		/*
1338 		 * Currently 64 bit processes cannot have private LDTs.
1339 		 */
1340 		ASSERT(p->p_model != DATAMODEL_LP64);
1341 
1342 		mutex_enter(&p->p_ldtlock);
1343 		if (p->p_ldt == NULL) {
1344 			mutex_exit(&p->p_ldtlock);
1345 			return (-1);
1346 		}
1347 		descrp = &p->p_ldt[idx];
1348 		baseaddr = (caddr_t)(uintptr_t)USEGD_GETBASE(descrp);
1349 		mutex_exit(&p->p_ldtlock);
1350 
1351 		/*
1352 		 * Calculate the linear address (wraparound is not only ok,
1353 		 * it's expected behavior).  The cast to uint32_t is because
1354 		 * LDT selectors are only allowed in 32-bit processes.
1355 		 */
1356 		*linearp = (caddr_t)(uintptr_t)(uint32_t)((uintptr_t)baseaddr +
1357 		    rp->r_pc);
1358 	} else {
1359 #ifdef DEBUG
1360 		descrp = &CPU->cpu_gdt[idx];
1361 		baseaddr = (caddr_t)(uintptr_t)USEGD_GETBASE(descrp);
1362 		/* GDT-based descriptors' base addresses should always be 0 */
1363 		ASSERT(baseaddr == 0);
1364 #endif
1365 		*linearp = (caddr_t)(uintptr_t)rp->r_pc;
1366 	}
1367 
1368 	return (0);
1369 }
1370 
1371 /*
1372  * We need to post a soft interrupt to reprogram the lbolt cyclic when
1373  * switching from event to cyclic driven lbolt. The following code adds
1374  * and posts the softint for x86.
1375  */
1376 static ddi_softint_hdl_impl_t lbolt_softint_hdl =
1377 	{0, NULL, NULL, NULL, 0, NULL, NULL, NULL};
1378 
1379 void
1380 lbolt_softint_add(void)
1381 {
1382 	(void) add_avsoftintr((void *)&lbolt_softint_hdl, LOCK_LEVEL,
1383 	    (avfunc)lbolt_ev_to_cyclic, "lbolt_ev_to_cyclic", NULL, NULL);
1384 }
1385 
1386 void
1387 lbolt_softint_post(void)
1388 {
1389 	(*setsoftint)(CBE_LOCK_PIL, lbolt_softint_hdl.ih_pending);
1390 }
1391