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