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