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