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