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