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