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