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