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