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