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