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