xref: /illumos-gate/usr/src/uts/sun4v/os/mach_cpu_states.c (revision 8fd04b8338ed5093ec2d1e668fa620b7de44c177)
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  * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 #include <sys/types.h>
27 #include <sys/systm.h>
28 #include <sys/archsystm.h>
29 #include <sys/t_lock.h>
30 #include <sys/uadmin.h>
31 #include <sys/panic.h>
32 #include <sys/reboot.h>
33 #include <sys/autoconf.h>
34 #include <sys/machsystm.h>
35 #include <sys/promif.h>
36 #include <sys/membar.h>
37 #include <vm/hat_sfmmu.h>
38 #include <sys/cpu_module.h>
39 #include <sys/cpu_sgnblk_defs.h>
40 #include <sys/intreg.h>
41 #include <sys/consdev.h>
42 #include <sys/kdi_impl.h>
43 #include <sys/traptrace.h>
44 #include <sys/hypervisor_api.h>
45 #include <sys/vmsystm.h>
46 #include <sys/dtrace.h>
47 #include <sys/xc_impl.h>
48 #include <sys/callb.h>
49 #include <sys/mdesc.h>
50 #include <sys/mach_descrip.h>
51 #include <sys/wdt.h>
52 #include <sys/soft_state.h>
53 #include <sys/promimpl.h>
54 #include <sys/hsvc.h>
55 #include <sys/ldoms.h>
56 #include <sys/kldc.h>
57 #include <sys/clock_impl.h>
58 #include <sys/suspend.h>
59 #include <sys/dumphdr.h>
60 
61 /*
62  * hvdump_buf_va is a pointer to the currently-configured hvdump_buf.
63  * A value of NULL indicates that this area is not configured.
64  * hvdump_buf_sz is tunable but will be clamped to HVDUMP_SIZE_MAX.
65  */
66 
67 caddr_t hvdump_buf_va;
68 uint64_t hvdump_buf_sz = HVDUMP_SIZE_DEFAULT;
69 static uint64_t hvdump_buf_pa;
70 
71 u_longlong_t panic_tick;
72 
73 extern u_longlong_t gettick();
74 static void reboot_machine(char *);
75 static void update_hvdump_buffer(void);
76 
77 /*
78  * For xt_sync synchronization.
79  */
80 extern uint64_t xc_tick_limit;
81 extern uint64_t xc_tick_jump_limit;
82 extern uint64_t xc_sync_tick_limit;
83 
84 /*
85  * We keep our own copies, used for cache flushing, because we can be called
86  * before cpu_fiximpl().
87  */
88 static int kdi_dcache_size;
89 static int kdi_dcache_linesize;
90 static int kdi_icache_size;
91 static int kdi_icache_linesize;
92 
93 /*
94  * Assembly support for generic modules in sun4v/ml/mach_xc.s
95  */
96 extern void init_mondo_nocheck(xcfunc_t *func, uint64_t arg1, uint64_t arg2);
97 extern void kdi_flush_idcache(int, int, int, int);
98 extern uint64_t get_cpuaddr(uint64_t, uint64_t);
99 
100 
101 #define	BOOT_CMD_MAX_LEN	256
102 #define	BOOT_CMD_BASE		"boot "
103 
104 /*
105  * In an LDoms system we do not save the user's boot args in NVRAM
106  * as is done on legacy systems.  Instead, we format and send a
107  * 'reboot-command' variable to the variable service.  The contents
108  * of the variable are retrieved by OBP and used verbatim for
109  * the next boot.
110  */
111 static void
112 store_boot_cmd(char *args, boolean_t add_boot_str, boolean_t invoke_cb)
113 {
114 	static char	cmd_buf[BOOT_CMD_MAX_LEN];
115 	size_t		len = 1;
116 	pnode_t		node;
117 	size_t		base_len = 0;
118 	size_t		args_len;
119 	size_t		args_max;
120 	uint64_t	majornum;
121 	uint64_t	minornum;
122 	uint64_t	buf_pa;
123 	uint64_t	status;
124 
125 	status = hsvc_version(HSVC_GROUP_REBOOT_DATA, &majornum, &minornum);
126 
127 	/*
128 	 * invoke_cb is set to true when we are in a normal shutdown sequence
129 	 * (interrupts are not blocked, the system is not panicking or being
130 	 * suspended). In that case, we can use any method to store the boot
131 	 * command. Otherwise storing the boot command can not be done using
132 	 * a domain service because it can not be safely used in that context.
133 	 */
134 	if ((status != H_EOK) && (invoke_cb == B_FALSE))
135 		return;
136 
137 	if (add_boot_str) {
138 		(void) strcpy(cmd_buf, BOOT_CMD_BASE);
139 
140 		base_len = strlen(BOOT_CMD_BASE);
141 		len = base_len + 1;
142 	}
143 
144 	if (args != NULL) {
145 		args_len = strlen(args);
146 		args_max = BOOT_CMD_MAX_LEN - len;
147 
148 		if (args_len > args_max) {
149 			cmn_err(CE_WARN, "Reboot command too long (%ld), "
150 			    "truncating command arguments", len + args_len);
151 
152 			args_len = args_max;
153 		}
154 
155 		len += args_len;
156 		(void) strncpy(&cmd_buf[base_len], args, args_len);
157 	}
158 
159 	/*
160 	 * Save the reboot-command with HV, if reboot data group is
161 	 * negotiated. Else save the reboot-command via vars-config domain
162 	 * services on the SP.
163 	 */
164 	if (status == H_EOK) {
165 		buf_pa = va_to_pa(cmd_buf);
166 		status = hv_reboot_data_set(buf_pa, len);
167 		if (status != H_EOK) {
168 			cmn_err(CE_WARN, "Unable to store boot command for "
169 			    "use on reboot with HV: error = 0x%lx", status);
170 		}
171 	} else {
172 		node = prom_optionsnode();
173 		if ((node == OBP_NONODE) || (node == OBP_BADNODE) ||
174 		    prom_setprop(node, "reboot-command", cmd_buf, len) == -1)
175 			cmn_err(CE_WARN, "Unable to store boot command for "
176 			    "use on reboot");
177 	}
178 }
179 
180 
181 /*
182  * Machine dependent code to reboot.
183  *
184  * "bootstr", when non-null, points to a string to be used as the
185  * argument string when rebooting.
186  *
187  * "invoke_cb" is a boolean. It is set to true when mdboot() can safely
188  * invoke CB_CL_MDBOOT callbacks before shutting the system down, i.e. when
189  * we are in a normal shutdown sequence (interrupts are not blocked, the
190  * system is not panic'ing or being suspended).
191  */
192 /*ARGSUSED*/
193 void
194 mdboot(int cmd, int fcn, char *bootstr, boolean_t invoke_cb)
195 {
196 	extern void pm_cfb_check_and_powerup(void);
197 
198 	/*
199 	 * XXX - rconsvp is set to NULL to ensure that output messages
200 	 * are sent to the underlying "hardware" device using the
201 	 * monitor's printf routine since we are in the process of
202 	 * either rebooting or halting the machine.
203 	 */
204 	rconsvp = NULL;
205 
206 	switch (fcn) {
207 	case AD_HALT:
208 		/*
209 		 * LDoms: By storing a no-op command
210 		 * in the 'reboot-command' variable we cause OBP
211 		 * to ignore the setting of 'auto-boot?' after
212 		 * it completes the reset.  This causes the system
213 		 * to stop at the ok prompt.
214 		 */
215 		if (domaining_enabled())
216 			store_boot_cmd("noop", B_FALSE, invoke_cb);
217 		break;
218 
219 	case AD_POWEROFF:
220 		break;
221 
222 	default:
223 		if (bootstr == NULL) {
224 			switch (fcn) {
225 
226 			case AD_BOOT:
227 				bootstr = "";
228 				break;
229 
230 			case AD_IBOOT:
231 				bootstr = "-a";
232 				break;
233 
234 			case AD_SBOOT:
235 				bootstr = "-s";
236 				break;
237 
238 			case AD_SIBOOT:
239 				bootstr = "-sa";
240 				break;
241 			default:
242 				cmn_err(CE_WARN,
243 				    "mdboot: invalid function %d", fcn);
244 				bootstr = "";
245 				break;
246 			}
247 		}
248 
249 		/*
250 		 * If LDoms is running, we must save the boot string
251 		 * before we enter restricted mode.  This is possible
252 		 * only if we are not being called from panic.
253 		 */
254 		if (domaining_enabled())
255 			store_boot_cmd(bootstr, B_TRUE, invoke_cb);
256 	}
257 
258 	/*
259 	 * At a high interrupt level we can't:
260 	 *	1) bring up the console
261 	 * or
262 	 *	2) wait for pending interrupts prior to redistribution
263 	 *	   to the current CPU
264 	 *
265 	 * so we do them now.
266 	 */
267 	pm_cfb_check_and_powerup();
268 
269 	/* make sure there are no more changes to the device tree */
270 	devtree_freeze();
271 
272 	if (invoke_cb)
273 		(void) callb_execute_class(CB_CL_MDBOOT, NULL);
274 
275 	/*
276 	 * Clear any unresolved UEs from memory.
277 	 */
278 	page_retire_mdboot();
279 
280 	/*
281 	 * stop other cpus which also raise our priority. since there is only
282 	 * one active cpu after this, and our priority will be too high
283 	 * for us to be preempted, we're essentially single threaded
284 	 * from here on out.
285 	 */
286 	stop_other_cpus();
287 
288 	/*
289 	 * try and reset leaf devices.  reset_leaves() should only
290 	 * be called when there are no other threads that could be
291 	 * accessing devices
292 	 */
293 	reset_leaves();
294 
295 	watchdog_clear();
296 
297 	if (fcn == AD_HALT) {
298 		mach_set_soft_state(SIS_TRANSITION,
299 		    &SOLARIS_SOFT_STATE_HALT_MSG);
300 		halt((char *)NULL);
301 	} else if (fcn == AD_POWEROFF) {
302 		mach_set_soft_state(SIS_TRANSITION,
303 		    &SOLARIS_SOFT_STATE_POWER_MSG);
304 		power_down(NULL);
305 	} else {
306 		mach_set_soft_state(SIS_TRANSITION,
307 		    &SOLARIS_SOFT_STATE_REBOOT_MSG);
308 		reboot_machine(bootstr);
309 	}
310 	/* MAYBE REACHED */
311 }
312 
313 /* mdpreboot - may be called prior to mdboot while root fs still mounted */
314 /*ARGSUSED*/
315 void
316 mdpreboot(int cmd, int fcn, char *bootstr)
317 {
318 }
319 
320 /*
321  * Halt the machine and then reboot with the device
322  * and arguments specified in bootstr.
323  */
324 static void
325 reboot_machine(char *bootstr)
326 {
327 	flush_windows();
328 	stop_other_cpus();		/* send stop signal to other CPUs */
329 	prom_printf("rebooting...\n");
330 	/*
331 	 * For platforms that use CPU signatures, we
332 	 * need to set the signature block to OS and
333 	 * the state to exiting for all the processors.
334 	 */
335 	CPU_SIGNATURE(OS_SIG, SIGST_EXIT, SIGSUBST_REBOOT, -1);
336 	prom_reboot(bootstr);
337 	/*NOTREACHED*/
338 }
339 
340 /*
341  * We use the x-trap mechanism and idle_stop_xcall() to stop the other CPUs.
342  * Once in panic_idle() they raise spl, record their location, and spin.
343  */
344 static void
345 panic_idle(void)
346 {
347 	(void) spl7();
348 
349 	debug_flush_windows();
350 	(void) setjmp(&curthread->t_pcb);
351 
352 	CPU->cpu_m.in_prom = 1;
353 	membar_stld();
354 
355 	dumpsys_helper();
356 
357 	for (;;)
358 		;
359 }
360 
361 /*
362  * Force the other CPUs to trap into panic_idle(), and then remove them
363  * from the cpu_ready_set so they will no longer receive cross-calls.
364  */
365 /*ARGSUSED*/
366 void
367 panic_stopcpus(cpu_t *cp, kthread_t *t, int spl)
368 {
369 	cpuset_t cps;
370 	int i;
371 
372 	(void) splzs();
373 	CPUSET_ALL_BUT(cps, cp->cpu_id);
374 	xt_some(cps, (xcfunc_t *)idle_stop_xcall, (uint64_t)&panic_idle, NULL);
375 
376 	for (i = 0; i < NCPU; i++) {
377 		if (i != cp->cpu_id && CPU_XCALL_READY(i)) {
378 			int ntries = 0x10000;
379 
380 			while (!cpu[i]->cpu_m.in_prom && ntries) {
381 				DELAY(50);
382 				ntries--;
383 			}
384 
385 			if (!cpu[i]->cpu_m.in_prom)
386 				printf("panic: failed to stop cpu%d\n", i);
387 
388 			cpu[i]->cpu_flags &= ~CPU_READY;
389 			cpu[i]->cpu_flags |= CPU_QUIESCED;
390 			CPUSET_DEL(cpu_ready_set, cpu[i]->cpu_id);
391 		}
392 	}
393 }
394 
395 /*
396  * Platform callback following each entry to panicsys().  If we've panicked at
397  * level 14, we examine t_panic_trap to see if a fatal trap occurred.  If so,
398  * we disable further %tick_cmpr interrupts.  If not, an explicit call to panic
399  * was made and so we re-enqueue an interrupt request structure to allow
400  * further level 14 interrupts to be processed once we lower PIL.  This allows
401  * us to handle panics from the deadman() CY_HIGH_LEVEL cyclic.
402  */
403 void
404 panic_enter_hw(int spl)
405 {
406 	if (!panic_tick) {
407 		panic_tick = gettick();
408 		if (mach_htraptrace_enable) {
409 			uint64_t prev_freeze;
410 
411 			/*  there are no possible error codes for this hcall */
412 			(void) hv_ttrace_freeze((uint64_t)TRAP_TFREEZE_ALL,
413 			    &prev_freeze);
414 		}
415 #ifdef TRAPTRACE
416 		TRAPTRACE_FREEZE;
417 #endif
418 	}
419 
420 	mach_set_soft_state(SIS_TRANSITION, &SOLARIS_SOFT_STATE_PANIC_MSG);
421 
422 	if (spl == ipltospl(PIL_14)) {
423 		uint_t opstate = disable_vec_intr();
424 
425 		if (curthread->t_panic_trap != NULL) {
426 			tickcmpr_disable();
427 			intr_dequeue_req(PIL_14, cbe_level14_inum);
428 		} else {
429 			if (!tickcmpr_disabled())
430 				intr_enqueue_req(PIL_14, cbe_level14_inum);
431 			/*
432 			 * Clear SOFTINT<14>, SOFTINT<0> (TICK_INT)
433 			 * and SOFTINT<16> (STICK_INT) to indicate
434 			 * that the current level 14 has been serviced.
435 			 */
436 			wr_clr_softint((1 << PIL_14) |
437 			    TICK_INT_MASK | STICK_INT_MASK);
438 		}
439 
440 		enable_vec_intr(opstate);
441 	}
442 }
443 
444 /*
445  * Miscellaneous hardware-specific code to execute after panicstr is set
446  * by the panic code: we also print and record PTL1 panic information here.
447  */
448 /*ARGSUSED*/
449 void
450 panic_quiesce_hw(panic_data_t *pdp)
451 {
452 	extern uint_t getpstate(void);
453 	extern void setpstate(uint_t);
454 
455 	/*
456 	 * Turn off TRAPTRACE and save the current %tick value in panic_tick.
457 	 */
458 	if (!panic_tick) {
459 		panic_tick = gettick();
460 		if (mach_htraptrace_enable) {
461 			uint64_t prev_freeze;
462 
463 			/*  there are no possible error codes for this hcall */
464 			(void) hv_ttrace_freeze((uint64_t)TRAP_TFREEZE_ALL,
465 			    &prev_freeze);
466 		}
467 #ifdef TRAPTRACE
468 		TRAPTRACE_FREEZE;
469 #endif
470 	}
471 	/*
472 	 * For Platforms that use CPU signatures, we
473 	 * need to set the signature block to OS, the state to
474 	 * exiting, and the substate to panic for all the processors.
475 	 */
476 	CPU_SIGNATURE(OS_SIG, SIGST_EXIT, SIGSUBST_PANIC, -1);
477 
478 	update_hvdump_buffer();
479 
480 	/*
481 	 * Disable further ECC errors from the bus nexus.
482 	 */
483 	(void) bus_func_invoke(BF_TYPE_ERRDIS);
484 
485 	/*
486 	 * Redirect all interrupts to the current CPU.
487 	 */
488 	intr_redist_all_cpus_shutdown();
489 
490 	/*
491 	 * This call exists solely to support dumps to network
492 	 * devices after sync from OBP.
493 	 *
494 	 * If we came here via the sync callback, then on some
495 	 * platforms, interrupts may have arrived while we were
496 	 * stopped in OBP.  OBP will arrange for those interrupts to
497 	 * be redelivered if you say "go", but not if you invoke a
498 	 * client callback like 'sync'.	 For some dump devices
499 	 * (network swap devices), we need interrupts to be
500 	 * delivered in order to dump, so we have to call the bus
501 	 * nexus driver to reset the interrupt state machines.
502 	 */
503 	(void) bus_func_invoke(BF_TYPE_RESINTR);
504 
505 	setpstate(getpstate() | PSTATE_IE);
506 }
507 
508 /*
509  * Platforms that use CPU signatures need to set the signature block to OS and
510  * the state to exiting for all CPUs. PANIC_CONT indicates that we're about to
511  * write the crash dump, which tells the SSP/SMS to begin a timeout routine to
512  * reboot the machine if the dump never completes.
513  */
514 /*ARGSUSED*/
515 void
516 panic_dump_hw(int spl)
517 {
518 	CPU_SIGNATURE(OS_SIG, SIGST_EXIT, SIGSUBST_DUMP, -1);
519 }
520 
521 /*
522  * for ptl1_panic
523  */
524 void
525 ptl1_init_cpu(struct cpu *cpu)
526 {
527 	ptl1_state_t *pstate = &cpu->cpu_m.ptl1_state;
528 
529 	/*CONSTCOND*/
530 	if (sizeof (struct cpu) + PTL1_SSIZE > CPU_ALLOC_SIZE) {
531 		panic("ptl1_init_cpu: not enough space left for ptl1_panic "
532 		    "stack, sizeof (struct cpu) = %lu",
533 		    (unsigned long)sizeof (struct cpu));
534 	}
535 
536 	pstate->ptl1_stktop = (uintptr_t)cpu + CPU_ALLOC_SIZE;
537 	cpu_pa[cpu->cpu_id] = va_to_pa(cpu);
538 }
539 
540 void
541 ptl1_panic_handler(ptl1_state_t *pstate)
542 {
543 	static const char *ptl1_reasons[] = {
544 #ifdef	PTL1_PANIC_DEBUG
545 		"trap for debug purpose",	/* PTL1_BAD_DEBUG */
546 #else
547 		"unknown trap",			/* PTL1_BAD_DEBUG */
548 #endif
549 		"register window trap",		/* PTL1_BAD_WTRAP */
550 		"kernel MMU miss",		/* PTL1_BAD_KMISS */
551 		"kernel protection fault",	/* PTL1_BAD_KPROT_FAULT */
552 		"ISM MMU miss",			/* PTL1_BAD_ISM */
553 		"kernel MMU trap",		/* PTL1_BAD_MMUTRAP */
554 		"kernel trap handler state",	/* PTL1_BAD_TRAP */
555 		"floating point trap",		/* PTL1_BAD_FPTRAP */
556 #ifdef	DEBUG
557 		"pointer to intr_vec",		/* PTL1_BAD_INTR_VEC */
558 #else
559 		"unknown trap",			/* PTL1_BAD_INTR_VEC */
560 #endif
561 #ifdef	TRAPTRACE
562 		"TRACE_PTR state",		/* PTL1_BAD_TRACE_PTR */
563 #else
564 		"unknown trap",			/* PTL1_BAD_TRACE_PTR */
565 #endif
566 		"stack overflow",		/* PTL1_BAD_STACK */
567 		"DTrace flags",			/* PTL1_BAD_DTRACE_FLAGS */
568 		"attempt to steal locked ctx",  /* PTL1_BAD_CTX_STEAL */
569 		"CPU ECC error loop",		/* PTL1_BAD_ECC */
570 		"unexpected error from hypervisor call", /* PTL1_BAD_HCALL */
571 		"unexpected global level(%gl)", /* PTL1_BAD_GL */
572 		"Watchdog Reset", 		/* PTL1_BAD_WATCHDOG */
573 		"unexpected RED mode trap", 	/* PTL1_BAD_RED */
574 		"return value EINVAL from hcall: "\
575 		    "UNMAP_PERM_ADDR",	/* PTL1_BAD_HCALL_UNMAP_PERM_EINVAL */
576 		"return value ENOMAP from hcall: "\
577 		    "UNMAP_PERM_ADDR", /* PTL1_BAD_HCALL_UNMAP_PERM_ENOMAP */
578 		"error raising a TSB exception", /* PTL1_BAD_RAISE_TSBEXCP */
579 		"missing shared TSB"	/* PTL1_NO_SCDTSB8K */
580 	};
581 
582 	uint_t reason = pstate->ptl1_regs.ptl1_gregs[0].ptl1_g1;
583 	uint_t tl = pstate->ptl1_regs.ptl1_trap_regs[0].ptl1_tl;
584 	struct panic_trap_info ti = { 0 };
585 
586 	/*
587 	 * Use trap_info for a place holder to call panic_savetrap() and
588 	 * panic_showtrap() to save and print out ptl1_panic information.
589 	 */
590 	if (curthread->t_panic_trap == NULL)
591 		curthread->t_panic_trap = &ti;
592 
593 	if (reason < sizeof (ptl1_reasons) / sizeof (ptl1_reasons[0]))
594 		panic("bad %s at TL %u", ptl1_reasons[reason], tl);
595 	else
596 		panic("ptl1_panic reason 0x%x at TL %u", reason, tl);
597 }
598 
599 void
600 clear_watchdog_on_exit(void)
601 {
602 	if (watchdog_enabled && watchdog_activated) {
603 		prom_printf("Debugging requested; hardware watchdog "
604 		    "suspended.\n");
605 		(void) watchdog_suspend();
606 	}
607 }
608 
609 /*
610  * Restore the watchdog timer when returning from a debugger
611  * after a panic or L1-A and resume watchdog pat.
612  */
613 void
614 restore_watchdog_on_entry()
615 {
616 	watchdog_resume();
617 }
618 
619 int
620 kdi_watchdog_disable(void)
621 {
622 	watchdog_suspend();
623 
624 	return (0);
625 }
626 
627 void
628 kdi_watchdog_restore(void)
629 {
630 	watchdog_resume();
631 }
632 
633 void
634 mach_dump_buffer_init(void)
635 {
636 	uint64_t  ret, minsize = 0;
637 
638 	if (hvdump_buf_sz > HVDUMP_SIZE_MAX)
639 		hvdump_buf_sz = HVDUMP_SIZE_MAX;
640 
641 	hvdump_buf_va = contig_mem_alloc_align(hvdump_buf_sz, PAGESIZE);
642 	if (hvdump_buf_va == NULL)
643 		return;
644 
645 	hvdump_buf_pa = va_to_pa(hvdump_buf_va);
646 
647 	ret = hv_dump_buf_update(hvdump_buf_pa, hvdump_buf_sz,
648 	    &minsize);
649 
650 	if (ret != H_EOK) {
651 		contig_mem_free(hvdump_buf_va, hvdump_buf_sz);
652 		hvdump_buf_va = NULL;
653 		cmn_err(CE_NOTE, "!Error in setting up hvstate"
654 		    "dump buffer. Error = 0x%lx, size = 0x%lx,"
655 		    "buf_pa = 0x%lx", ret, hvdump_buf_sz,
656 		    hvdump_buf_pa);
657 
658 		if (ret == H_EINVAL) {
659 			cmn_err(CE_NOTE, "!Buffer size too small."
660 			    "Available buffer size = 0x%lx,"
661 			    "Minimum buffer size required = 0x%lx",
662 			    hvdump_buf_sz, minsize);
663 		}
664 	}
665 }
666 
667 
668 static void
669 update_hvdump_buffer(void)
670 {
671 	uint64_t ret, dummy_val;
672 
673 	if (hvdump_buf_va == NULL)
674 		return;
675 
676 	ret = hv_dump_buf_update(hvdump_buf_pa, hvdump_buf_sz,
677 	    &dummy_val);
678 	if (ret != H_EOK) {
679 		cmn_err(CE_NOTE, "!Cannot update hvstate dump"
680 		    "buffer. Error = 0x%lx", ret);
681 	}
682 }
683 
684 
685 static int
686 getintprop(pnode_t node, char *name, int deflt)
687 {
688 	int	value;
689 
690 	switch (prom_getproplen(node, name)) {
691 	case 0:
692 		value = 1;	/* boolean properties */
693 		break;
694 
695 	case sizeof (int):
696 		(void) prom_getprop(node, name, (caddr_t)&value);
697 		break;
698 
699 	default:
700 		value = deflt;
701 		break;
702 	}
703 
704 	return (value);
705 }
706 
707 /*
708  * Called by setcpudelay
709  */
710 void
711 cpu_init_tick_freq(void)
712 {
713 	md_t *mdp;
714 	mde_cookie_t rootnode;
715 	int		listsz;
716 	mde_cookie_t	*listp = NULL;
717 	int	num_nodes;
718 	uint64_t stick_prop;
719 
720 	if (broken_md_flag) {
721 		sys_tick_freq = cpunodes[CPU->cpu_id].clock_freq;
722 		return;
723 	}
724 
725 	if ((mdp = md_get_handle()) == NULL)
726 		panic("stick_frequency property not found in MD");
727 
728 	rootnode = md_root_node(mdp);
729 	ASSERT(rootnode != MDE_INVAL_ELEM_COOKIE);
730 
731 	num_nodes = md_node_count(mdp);
732 
733 	ASSERT(num_nodes > 0);
734 	listsz = num_nodes * sizeof (mde_cookie_t);
735 	listp = (mde_cookie_t *)prom_alloc((caddr_t)0, listsz, 0);
736 
737 	if (listp == NULL)
738 		panic("cannot allocate list for MD properties");
739 
740 	num_nodes = md_scan_dag(mdp, rootnode, md_find_name(mdp, "platform"),
741 	    md_find_name(mdp, "fwd"), listp);
742 
743 	ASSERT(num_nodes == 1);
744 
745 	if (md_get_prop_val(mdp, *listp, "stick-frequency", &stick_prop) != 0)
746 		panic("stick_frequency property not found in MD");
747 
748 	sys_tick_freq = stick_prop;
749 
750 	prom_free((caddr_t)listp, listsz);
751 	(void) md_fini_handle(mdp);
752 }
753 
754 int shipit(int n, uint64_t cpu_list_ra);
755 
756 #ifdef DEBUG
757 #define	SEND_MONDO_STATS	1
758 #endif
759 
760 #ifdef SEND_MONDO_STATS
761 uint32_t x_one_stimes[64];
762 uint32_t x_one_ltimes[16];
763 uint32_t x_set_stimes[64];
764 uint32_t x_set_ltimes[16];
765 uint32_t x_set_cpus[NCPU];
766 #endif
767 
768 void
769 send_one_mondo(int cpuid)
770 {
771 	int retries, stat;
772 	uint64_t starttick, endtick, tick, lasttick;
773 	struct machcpu	*mcpup = &(CPU->cpu_m);
774 
775 	CPU_STATS_ADDQ(CPU, sys, xcalls, 1);
776 	starttick = lasttick = gettick();
777 	mcpup->cpu_list[0] = (uint16_t)cpuid;
778 	stat = shipit(1, mcpup->cpu_list_ra);
779 	endtick = starttick + xc_tick_limit;
780 	retries = 0;
781 	while (stat != H_EOK) {
782 		if (stat != H_EWOULDBLOCK) {
783 			if (panic_quiesce)
784 				return;
785 			if (stat == H_ECPUERROR)
786 				cmn_err(CE_PANIC, "send_one_mondo: "
787 				    "cpuid: 0x%x has been marked in "
788 				    "error", cpuid);
789 			else
790 				cmn_err(CE_PANIC, "send_one_mondo: "
791 				    "unexpected hypervisor error 0x%x "
792 				    "while sending a mondo to cpuid: "
793 				    "0x%x", stat, cpuid);
794 		}
795 		tick = gettick();
796 		/*
797 		 * If there is a big jump between the current tick
798 		 * count and lasttick, we have probably hit a break
799 		 * point.  Adjust endtick accordingly to avoid panic.
800 		 */
801 		if (tick > (lasttick + xc_tick_jump_limit))
802 			endtick += (tick - lasttick);
803 		lasttick = tick;
804 		if (tick > endtick) {
805 			if (panic_quiesce)
806 				return;
807 			cmn_err(CE_PANIC, "send mondo timeout "
808 			    "(target 0x%x) [retries: 0x%x hvstat: 0x%x]",
809 			    cpuid, retries, stat);
810 		}
811 		drv_usecwait(1);
812 		stat = shipit(1, mcpup->cpu_list_ra);
813 		retries++;
814 	}
815 #ifdef SEND_MONDO_STATS
816 	{
817 		uint64_t n = gettick() - starttick;
818 		if (n < 8192)
819 			x_one_stimes[n >> 7]++;
820 		else if (n < 15*8192)
821 			x_one_ltimes[n >> 13]++;
822 		else
823 			x_one_ltimes[0xf]++;
824 	}
825 #endif
826 }
827 
828 void
829 send_mondo_set(cpuset_t set)
830 {
831 	uint64_t starttick, endtick, tick, lasttick;
832 	uint_t largestid, smallestid;
833 	int i, j;
834 	int ncpuids = 0;
835 	int shipped = 0;
836 	int retries = 0;
837 	struct machcpu	*mcpup = &(CPU->cpu_m);
838 
839 	ASSERT(!CPUSET_ISNULL(set));
840 	CPUSET_BOUNDS(set, smallestid, largestid);
841 	if (smallestid == CPUSET_NOTINSET) {
842 		return;
843 	}
844 
845 	starttick = lasttick = gettick();
846 	endtick = starttick + xc_tick_limit;
847 
848 	/*
849 	 * Assemble CPU list for HV argument. We already know
850 	 * smallestid and largestid are members of set.
851 	 */
852 	mcpup->cpu_list[ncpuids++] = (uint16_t)smallestid;
853 	if (largestid != smallestid) {
854 		for (i = smallestid+1; i <= largestid-1; i++) {
855 			if (CPU_IN_SET(set, i)) {
856 				mcpup->cpu_list[ncpuids++] = (uint16_t)i;
857 			}
858 		}
859 		mcpup->cpu_list[ncpuids++] = (uint16_t)largestid;
860 	}
861 
862 	do {
863 		int stat;
864 
865 		stat = shipit(ncpuids, mcpup->cpu_list_ra);
866 		if (stat == H_EOK) {
867 			shipped += ncpuids;
868 			break;
869 		}
870 
871 		/*
872 		 * Either not all CPU mondos were sent, or an
873 		 * error occurred. CPUs that were sent mondos
874 		 * have their CPU IDs overwritten in cpu_list.
875 		 * Reset cpu_list so that it only holds those
876 		 * CPU IDs that still need to be sent.
877 		 */
878 		for (i = 0, j = 0; i < ncpuids; i++) {
879 			if (mcpup->cpu_list[i] == HV_SEND_MONDO_ENTRYDONE) {
880 				shipped++;
881 			} else {
882 				mcpup->cpu_list[j++] = mcpup->cpu_list[i];
883 			}
884 		}
885 		ncpuids = j;
886 
887 		/*
888 		 * Now handle possible errors returned
889 		 * from hypervisor.
890 		 */
891 		if (stat == H_ECPUERROR) {
892 			int errorcpus;
893 
894 			if (!panic_quiesce)
895 				cmn_err(CE_CONT, "send_mondo_set: cpuid(s) ");
896 
897 			/*
898 			 * Remove any CPUs in the error state from
899 			 * cpu_list. At this point cpu_list only
900 			 * contains the CPU IDs for mondos not
901 			 * succesfully sent.
902 			 */
903 			for (i = 0, errorcpus = 0; i < ncpuids; i++) {
904 				uint64_t state = CPU_STATE_INVALID;
905 				uint16_t id = mcpup->cpu_list[i];
906 
907 				(void) hv_cpu_state(id, &state);
908 				if (state == CPU_STATE_ERROR) {
909 					if (!panic_quiesce)
910 						cmn_err(CE_CONT, "0x%x ", id);
911 					errorcpus++;
912 				} else if (errorcpus > 0) {
913 					mcpup->cpu_list[i - errorcpus] =
914 					    mcpup->cpu_list[i];
915 				}
916 			}
917 			ncpuids -= errorcpus;
918 
919 			if (!panic_quiesce) {
920 				if (errorcpus == 0) {
921 					cmn_err(CE_CONT, "<none> have been "
922 					    "marked in error\n");
923 					cmn_err(CE_PANIC, "send_mondo_set: "
924 					    "hypervisor returned "
925 					    "H_ECPUERROR but no CPU in "
926 					    "cpu_list in error state");
927 				} else {
928 					cmn_err(CE_CONT, "have been marked in "
929 					    "error\n");
930 					cmn_err(CE_PANIC, "send_mondo_set: "
931 					    "CPU(s) in error state");
932 				}
933 			}
934 		} else if (stat != H_EWOULDBLOCK) {
935 			if (panic_quiesce)
936 				return;
937 			/*
938 			 * For all other errors, panic.
939 			 */
940 			cmn_err(CE_CONT, "send_mondo_set: unexpected "
941 			    "hypervisor error 0x%x while sending a "
942 			    "mondo to cpuid(s):", stat);
943 			for (i = 0; i < ncpuids; i++) {
944 				cmn_err(CE_CONT, " 0x%x", mcpup->cpu_list[i]);
945 			}
946 			cmn_err(CE_CONT, "\n");
947 			cmn_err(CE_PANIC, "send_mondo_set: unexpected "
948 			    "hypervisor error");
949 		}
950 
951 		tick = gettick();
952 		/*
953 		 * If there is a big jump between the current tick
954 		 * count and lasttick, we have probably hit a break
955 		 * point.  Adjust endtick accordingly to avoid panic.
956 		 */
957 		if (tick > (lasttick + xc_tick_jump_limit))
958 			endtick += (tick - lasttick);
959 		lasttick = tick;
960 		if (tick > endtick) {
961 			if (panic_quiesce)
962 				return;
963 			cmn_err(CE_CONT, "send mondo timeout "
964 			    "[retries: 0x%x]  cpuids: ", retries);
965 			for (i = 0; i < ncpuids; i++)
966 				cmn_err(CE_CONT, " 0x%x", mcpup->cpu_list[i]);
967 			cmn_err(CE_CONT, "\n");
968 			cmn_err(CE_PANIC, "send_mondo_set: timeout");
969 		}
970 
971 		while (gettick() < (tick + sys_clock_mhz))
972 			;
973 		retries++;
974 	} while (ncpuids > 0);
975 
976 	CPU_STATS_ADDQ(CPU, sys, xcalls, shipped);
977 
978 #ifdef SEND_MONDO_STATS
979 	{
980 		uint64_t n = gettick() - starttick;
981 		if (n < 8192)
982 			x_set_stimes[n >> 7]++;
983 		else if (n < 15*8192)
984 			x_set_ltimes[n >> 13]++;
985 		else
986 			x_set_ltimes[0xf]++;
987 	}
988 	x_set_cpus[shipped]++;
989 #endif
990 }
991 
992 void
993 syncfpu(void)
994 {
995 }
996 
997 void
998 sticksync_slave(void)
999 {
1000 	suspend_sync_tick_stick_npt();
1001 }
1002 
1003 void
1004 sticksync_master(void)
1005 {}
1006 
1007 void
1008 cpu_init_cache_scrub(void)
1009 {
1010 	mach_set_soft_state(SIS_NORMAL, &SOLARIS_SOFT_STATE_RUN_MSG);
1011 }
1012 
1013 int
1014 dtrace_blksuword32_err(uintptr_t addr, uint32_t *data)
1015 {
1016 	int ret, watched;
1017 
1018 	watched = watch_disable_addr((void *)addr, 4, S_WRITE);
1019 	ret = dtrace_blksuword32(addr, data, 0);
1020 	if (watched)
1021 		watch_enable_addr((void *)addr, 4, S_WRITE);
1022 
1023 	return (ret);
1024 }
1025 
1026 int
1027 dtrace_blksuword32(uintptr_t addr, uint32_t *data, int tryagain)
1028 {
1029 	if (suword32((void *)addr, *data) == -1)
1030 		return (tryagain ? dtrace_blksuword32_err(addr, data) : -1);
1031 	dtrace_flush_sec(addr);
1032 
1033 	return (0);
1034 }
1035 
1036 /*ARGSUSED*/
1037 void
1038 cpu_faulted_enter(struct cpu *cp)
1039 {
1040 }
1041 
1042 /*ARGSUSED*/
1043 void
1044 cpu_faulted_exit(struct cpu *cp)
1045 {
1046 }
1047 
1048 static int
1049 kdi_cpu_ready_iter(int (*cb)(int, void *), void *arg)
1050 {
1051 	int rc, i;
1052 
1053 	for (rc = 0, i = 0; i < NCPU; i++) {
1054 		if (CPU_IN_SET(cpu_ready_set, i))
1055 			rc += cb(i, arg);
1056 	}
1057 
1058 	return (rc);
1059 }
1060 
1061 /*
1062  * Sends a cross-call to a specified processor.  The caller assumes
1063  * responsibility for repetition of cross-calls, as appropriate (MARSA for
1064  * debugging).
1065  */
1066 static int
1067 kdi_xc_one(int cpuid, void (*func)(uintptr_t, uintptr_t), uintptr_t arg1,
1068     uintptr_t arg2)
1069 {
1070 	int stat;
1071 	struct machcpu	*mcpup;
1072 	uint64_t cpuaddr_reg = 0, cpuaddr_scr = 0;
1073 
1074 	mcpup = &(((cpu_t *)get_cpuaddr(cpuaddr_reg, cpuaddr_scr))->cpu_m);
1075 
1076 	/*
1077 	 * if (idsr_busy())
1078 	 *	return (KDI_XC_RES_ERR);
1079 	 */
1080 
1081 	init_mondo_nocheck((xcfunc_t *)func, arg1, arg2);
1082 
1083 	mcpup->cpu_list[0] = (uint16_t)cpuid;
1084 	stat = shipit(1, mcpup->cpu_list_ra);
1085 
1086 	if (stat == 0)
1087 		return (KDI_XC_RES_OK);
1088 	else
1089 		return (KDI_XC_RES_NACK);
1090 }
1091 
1092 static void
1093 kdi_tickwait(clock_t nticks)
1094 {
1095 	clock_t endtick = gettick() + nticks;
1096 
1097 	while (gettick() < endtick)
1098 		;
1099 }
1100 
1101 static void
1102 kdi_cpu_init(int dcache_size, int dcache_linesize, int icache_size,
1103     int icache_linesize)
1104 {
1105 	kdi_dcache_size = dcache_size;
1106 	kdi_dcache_linesize = dcache_linesize;
1107 	kdi_icache_size = icache_size;
1108 	kdi_icache_linesize = icache_linesize;
1109 }
1110 
1111 /* used directly by kdi_read/write_phys */
1112 void
1113 kdi_flush_caches(void)
1114 {
1115 	/* Not required on sun4v architecture. */
1116 }
1117 
1118 /*ARGSUSED*/
1119 int
1120 kdi_get_stick(uint64_t *stickp)
1121 {
1122 	return (-1);
1123 }
1124 
1125 void
1126 cpu_kdi_init(kdi_t *kdi)
1127 {
1128 	kdi->kdi_flush_caches = kdi_flush_caches;
1129 	kdi->mkdi_cpu_init = kdi_cpu_init;
1130 	kdi->mkdi_cpu_ready_iter = kdi_cpu_ready_iter;
1131 	kdi->mkdi_xc_one = kdi_xc_one;
1132 	kdi->mkdi_tickwait = kdi_tickwait;
1133 	kdi->mkdi_get_stick = kdi_get_stick;
1134 }
1135 
1136 uint64_t	soft_state_message_ra[SOLARIS_SOFT_STATE_MSG_CNT];
1137 static uint64_t	soft_state_saved_state = (uint64_t)-1;
1138 static int	soft_state_initialized = 0;
1139 static uint64_t soft_state_sup_minor;		/* Supported minor number */
1140 static hsvc_info_t soft_state_hsvc = {
1141 			HSVC_REV_1, NULL, HSVC_GROUP_SOFT_STATE, 1, 0, NULL };
1142 
1143 
1144 static void
1145 sun4v_system_claim(void)
1146 {
1147 	lbolt_debug_entry();
1148 
1149 	watchdog_suspend();
1150 	kldc_debug_enter();
1151 	/*
1152 	 * For "mdb -K", set soft state to debugging
1153 	 */
1154 	if (soft_state_saved_state == -1) {
1155 		mach_get_soft_state(&soft_state_saved_state,
1156 		    &SOLARIS_SOFT_STATE_SAVED_MSG);
1157 	}
1158 	/*
1159 	 * check again as the read above may or may not have worked and if
1160 	 * it didn't then soft state will still be -1
1161 	 */
1162 	if (soft_state_saved_state != -1) {
1163 		mach_set_soft_state(SIS_TRANSITION,
1164 		    &SOLARIS_SOFT_STATE_DEBUG_MSG);
1165 	}
1166 }
1167 
1168 static void
1169 sun4v_system_release(void)
1170 {
1171 	watchdog_resume();
1172 	/*
1173 	 * For "mdb -K", set soft_state state back to original state on exit
1174 	 */
1175 	if (soft_state_saved_state != -1) {
1176 		mach_set_soft_state(soft_state_saved_state,
1177 		    &SOLARIS_SOFT_STATE_SAVED_MSG);
1178 		soft_state_saved_state = -1;
1179 	}
1180 
1181 	lbolt_debug_return();
1182 }
1183 
1184 void
1185 plat_kdi_init(kdi_t *kdi)
1186 {
1187 	kdi->pkdi_system_claim = sun4v_system_claim;
1188 	kdi->pkdi_system_release = sun4v_system_release;
1189 }
1190 
1191 /*
1192  * Routine to return memory information associated
1193  * with a physical address and syndrome.
1194  */
1195 /* ARGSUSED */
1196 int
1197 cpu_get_mem_info(uint64_t synd, uint64_t afar,
1198     uint64_t *mem_sizep, uint64_t *seg_sizep, uint64_t *bank_sizep,
1199     int *segsp, int *banksp, int *mcidp)
1200 {
1201 	return (ENOTSUP);
1202 }
1203 
1204 /*
1205  * This routine returns the size of the kernel's FRU name buffer.
1206  */
1207 size_t
1208 cpu_get_name_bufsize()
1209 {
1210 	return (UNUM_NAMLEN);
1211 }
1212 
1213 /*
1214  * This routine is a more generic interface to cpu_get_mem_unum(),
1215  * that may be used by other modules (e.g. mm).
1216  */
1217 /* ARGSUSED */
1218 int
1219 cpu_get_mem_name(uint64_t synd, uint64_t *afsr, uint64_t afar,
1220     char *buf, int buflen, int *lenp)
1221 {
1222 	return (ENOTSUP);
1223 }
1224 
1225 /* ARGSUSED */
1226 int
1227 cpu_get_mem_sid(char *unum, char *buf, int buflen, int *lenp)
1228 {
1229 	return (ENOTSUP);
1230 }
1231 
1232 /* ARGSUSED */
1233 int
1234 cpu_get_mem_addr(char *unum, char *sid, uint64_t offset, uint64_t *addrp)
1235 {
1236 	return (ENOTSUP);
1237 }
1238 
1239 /*
1240  * xt_sync - wait for previous x-traps to finish
1241  */
1242 void
1243 xt_sync(cpuset_t cpuset)
1244 {
1245 	union {
1246 		uint8_t volatile byte[NCPU];
1247 		uint64_t volatile xword[NCPU / 8];
1248 	} cpu_sync;
1249 	uint64_t starttick, endtick, tick, lasttick, traptrace_id;
1250 	uint_t largestid, smallestid;
1251 	int i, j;
1252 
1253 	kpreempt_disable();
1254 	CPUSET_DEL(cpuset, CPU->cpu_id);
1255 	CPUSET_AND(cpuset, cpu_ready_set);
1256 
1257 	CPUSET_BOUNDS(cpuset, smallestid, largestid);
1258 	if (smallestid == CPUSET_NOTINSET)
1259 		goto out;
1260 
1261 	/*
1262 	 * Sun4v uses a queue for receiving mondos. Successful
1263 	 * transmission of a mondo only indicates that the mondo
1264 	 * has been written into the queue.
1265 	 *
1266 	 * We use an array of bytes to let each cpu to signal back
1267 	 * to the cross trap sender that the cross trap has been
1268 	 * executed. Set the byte to 1 before sending the cross trap
1269 	 * and wait until other cpus reset it to 0.
1270 	 */
1271 	bzero((void *)&cpu_sync, NCPU);
1272 	cpu_sync.byte[smallestid] = 1;
1273 	if (largestid != smallestid) {
1274 		for (i = (smallestid + 1); i <= (largestid - 1); i++)
1275 			if (CPU_IN_SET(cpuset, i))
1276 				cpu_sync.byte[i] = 1;
1277 		cpu_sync.byte[largestid] = 1;
1278 	}
1279 
1280 	/*
1281 	 * To help debug xt_sync panic, each mondo is uniquely identified
1282 	 * by passing the tick value, traptrace_id as the second mondo
1283 	 * argument to xt_some which is logged in CPU's mondo queue,
1284 	 * traptrace buffer and the panic message.
1285 	 */
1286 	traptrace_id = gettick();
1287 	xt_some(cpuset, (xcfunc_t *)xt_sync_tl1,
1288 	    (uint64_t)cpu_sync.byte, traptrace_id);
1289 
1290 	starttick = lasttick = gettick();
1291 	endtick = starttick + xc_sync_tick_limit;
1292 
1293 	for (i = (smallestid / 8); i <= (largestid / 8); i++) {
1294 		while (cpu_sync.xword[i] != 0) {
1295 			tick = gettick();
1296 			/*
1297 			 * If there is a big jump between the current tick
1298 			 * count and lasttick, we have probably hit a break
1299 			 * point. Adjust endtick accordingly to avoid panic.
1300 			 */
1301 			if (tick > (lasttick + xc_tick_jump_limit)) {
1302 				endtick += (tick - lasttick);
1303 			}
1304 			lasttick = tick;
1305 			if (tick > endtick) {
1306 				if (panic_quiesce)
1307 					goto out;
1308 				cmn_err(CE_CONT, "Cross trap sync timeout:  "
1309 				    "at cpu_sync.xword[%d]: 0x%lx "
1310 				    "cpu_sync.byte: 0x%lx "
1311 				    "starttick: 0x%lx endtick: 0x%lx "
1312 				    "traptrace_id = 0x%lx\n",
1313 				    i, cpu_sync.xword[i],
1314 				    (uint64_t)cpu_sync.byte,
1315 				    starttick, endtick, traptrace_id);
1316 				cmn_err(CE_CONT, "CPUIDs:");
1317 				for (j = (i * 8); j <= largestid; j++) {
1318 					if (cpu_sync.byte[j] != 0)
1319 						cmn_err(CE_CONT, " 0x%x", j);
1320 				}
1321 				cmn_err(CE_PANIC, "xt_sync: timeout");
1322 			}
1323 		}
1324 	}
1325 
1326 out:
1327 	kpreempt_enable();
1328 }
1329 
1330 #define	QFACTOR		200
1331 /*
1332  * Recalculate the values of the cross-call timeout variables based
1333  * on the value of the 'inter-cpu-latency' property of the platform node.
1334  * The property sets the number of nanosec to wait for a cross-call
1335  * to be acknowledged.  Other timeout variables are derived from it.
1336  *
1337  * N.B. This implementation is aware of the internals of xc_init()
1338  * and updates many of the same variables.
1339  */
1340 void
1341 recalc_xc_timeouts(void)
1342 {
1343 	typedef union {
1344 		uint64_t whole;
1345 		struct {
1346 			uint_t high;
1347 			uint_t low;
1348 		} half;
1349 	} u_number;
1350 
1351 	/* See x_call.c for descriptions of these extern variables. */
1352 	extern uint64_t xc_tick_limit_scale;
1353 	extern uint64_t xc_mondo_time_limit;
1354 	extern uint64_t xc_func_time_limit;
1355 	extern uint64_t xc_scale;
1356 	extern uint64_t xc_mondo_multiplier;
1357 	extern uint_t   nsec_shift;
1358 
1359 	/* Temp versions of the target variables */
1360 	uint64_t tick_limit;
1361 	uint64_t tick_jump_limit;
1362 	uint64_t mondo_time_limit;
1363 	uint64_t func_time_limit;
1364 	uint64_t scale;
1365 
1366 	uint64_t latency;	/* nanoseconds */
1367 	uint64_t maxfreq;
1368 	uint64_t tick_limit_save = xc_tick_limit;
1369 	uint64_t sync_tick_limit_save = xc_sync_tick_limit;
1370 	uint_t   tick_scale;
1371 	uint64_t top;
1372 	uint64_t bottom;
1373 	u_number tk;
1374 
1375 	md_t *mdp;
1376 	int nrnode;
1377 	mde_cookie_t *platlist;
1378 
1379 	/*
1380 	 * Look up the 'inter-cpu-latency' (optional) property in the
1381 	 * platform node of the MD.  The units are nanoseconds.
1382 	 */
1383 	if ((mdp = md_get_handle()) == NULL) {
1384 		cmn_err(CE_WARN, "recalc_xc_timeouts: "
1385 		    "Unable to initialize machine description");
1386 		return;
1387 	}
1388 
1389 	nrnode = md_alloc_scan_dag(mdp,
1390 	    md_root_node(mdp), "platform", "fwd", &platlist);
1391 
1392 	ASSERT(nrnode == 1);
1393 	if (nrnode < 1) {
1394 		cmn_err(CE_WARN, "recalc_xc_timeouts: platform node missing");
1395 		goto done;
1396 	}
1397 	if (md_get_prop_val(mdp, platlist[0],
1398 	    "inter-cpu-latency", &latency) == -1)
1399 		goto done;
1400 
1401 	/*
1402 	 * clock.h defines an assembly-language macro
1403 	 * (NATIVE_TIME_TO_NSEC_SCALE) to convert from %stick
1404 	 * units to nanoseconds.  Since the inter-cpu-latency
1405 	 * units are nanoseconds and the xc_* variables require
1406 	 * %stick units, we need the inverse of that function.
1407 	 * The trick is to perform the calculation without
1408 	 * floating point, but also without integer truncation
1409 	 * or overflow.  To understand the calculation below,
1410 	 * please read the discussion of the macro in clock.h.
1411 	 * Since this new code will be invoked infrequently,
1412 	 * we can afford to implement it in C.
1413 	 *
1414 	 * tick_scale is the reciprocal of nsec_scale which is
1415 	 * calculated at startup in setcpudelay().  The calc
1416 	 * of tick_limit parallels that of NATIVE_TIME_TO_NSEC_SCALE
1417 	 * except we use tick_scale instead of nsec_scale and
1418 	 * C instead of assembler.
1419 	 */
1420 	tick_scale = (uint_t)(((u_longlong_t)sys_tick_freq
1421 	    << (32 - nsec_shift)) / NANOSEC);
1422 
1423 	tk.whole = latency;
1424 	top = ((uint64_t)tk.half.high << 4) * tick_scale;
1425 	bottom = (((uint64_t)tk.half.low << 4) * (uint64_t)tick_scale) >> 32;
1426 	tick_limit = top + bottom;
1427 
1428 	/*
1429 	 * xc_init() calculated 'maxfreq' by looking at all the cpus,
1430 	 * and used it to derive some of the timeout variables that we
1431 	 * recalculate below.  We can back into the original value by
1432 	 * using the inverse of one of those calculations.
1433 	 */
1434 	maxfreq = xc_mondo_time_limit / xc_scale;
1435 
1436 	/*
1437 	 * Don't allow the new timeout (xc_tick_limit) to fall below
1438 	 * the system tick frequency (stick).  Allowing the timeout
1439 	 * to be set more tightly than this empirically determined
1440 	 * value may cause panics.
1441 	 */
1442 	tick_limit = tick_limit < sys_tick_freq ? sys_tick_freq : tick_limit;
1443 
1444 	tick_jump_limit = tick_limit / 32;
1445 	tick_limit *= xc_tick_limit_scale;
1446 
1447 	/*
1448 	 * Recalculate xc_scale since it is used in a callback function
1449 	 * (xc_func_timeout_adj) to adjust two of the timeouts dynamically.
1450 	 * Make the change in xc_scale proportional to the change in
1451 	 * xc_tick_limit.
1452 	 */
1453 	scale = (xc_scale * tick_limit + sys_tick_freq / 2) / tick_limit_save;
1454 	if (scale == 0)
1455 		scale = 1;
1456 
1457 	mondo_time_limit = maxfreq * scale;
1458 	func_time_limit = mondo_time_limit * xc_mondo_multiplier;
1459 
1460 	/*
1461 	 * Don't modify the timeouts if nothing has changed.  Else,
1462 	 * stuff the variables with the freshly calculated (temp)
1463 	 * variables.  This minimizes the window where the set of
1464 	 * values could be inconsistent.
1465 	 */
1466 	if (tick_limit != xc_tick_limit) {
1467 		xc_tick_limit = tick_limit;
1468 		xc_tick_jump_limit = tick_jump_limit;
1469 		xc_scale = scale;
1470 		xc_mondo_time_limit = mondo_time_limit;
1471 		xc_func_time_limit = func_time_limit;
1472 	}
1473 
1474 done:
1475 	/*
1476 	 * Increase the timeout limit for xt_sync() cross calls.
1477 	 */
1478 	xc_sync_tick_limit = xc_tick_limit * (cpu_q_entries / QFACTOR);
1479 	xc_sync_tick_limit = xc_sync_tick_limit < xc_tick_limit ?
1480 	    xc_tick_limit : xc_sync_tick_limit;
1481 
1482 	/*
1483 	 * Force the new values to be used for future cross calls.
1484 	 * This is necessary only when we increase the timeouts.
1485 	 */
1486 	if ((xc_tick_limit > tick_limit_save) || (xc_sync_tick_limit >
1487 	    sync_tick_limit_save)) {
1488 		cpuset_t cpuset = cpu_ready_set;
1489 		xt_sync(cpuset);
1490 	}
1491 
1492 	if (nrnode > 0)
1493 		md_free_scan_dag(mdp, &platlist);
1494 	(void) md_fini_handle(mdp);
1495 }
1496 
1497 void
1498 mach_soft_state_init(void)
1499 {
1500 	int		i;
1501 	uint64_t	ra;
1502 
1503 	/*
1504 	 * Try to register soft_state api. If it fails, soft_state api has not
1505 	 * been implemented in the firmware, so do not bother to setup
1506 	 * soft_state in the kernel.
1507 	 */
1508 	if ((i = hsvc_register(&soft_state_hsvc, &soft_state_sup_minor)) != 0) {
1509 		return;
1510 	}
1511 	for (i = 0; i < SOLARIS_SOFT_STATE_MSG_CNT; i++) {
1512 		ASSERT(strlen((const char *)(void *)
1513 		    soft_state_message_strings + i) < SSM_SIZE);
1514 		if ((ra = va_to_pa(
1515 		    (void *)(soft_state_message_strings + i))) == -1ll) {
1516 			return;
1517 		}
1518 		soft_state_message_ra[i] = ra;
1519 	}
1520 	/*
1521 	 * Tell OBP that we are supporting Guest State
1522 	 */
1523 	prom_sun4v_soft_state_supported();
1524 	soft_state_initialized = 1;
1525 }
1526 
1527 void
1528 mach_set_soft_state(uint64_t state, uint64_t *string_ra)
1529 {
1530 	uint64_t	rc;
1531 
1532 	if (soft_state_initialized && *string_ra) {
1533 		rc = hv_soft_state_set(state, *string_ra);
1534 		if (rc != H_EOK) {
1535 			cmn_err(CE_WARN,
1536 			    "hv_soft_state_set returned %ld\n", rc);
1537 		}
1538 	}
1539 }
1540 
1541 void
1542 mach_get_soft_state(uint64_t *state, uint64_t *string_ra)
1543 {
1544 	uint64_t	rc;
1545 
1546 	if (soft_state_initialized && *string_ra) {
1547 		rc = hv_soft_state_get(*string_ra, state);
1548 		if (rc != H_EOK) {
1549 			cmn_err(CE_WARN,
1550 			    "hv_soft_state_get returned %ld\n", rc);
1551 			*state = -1;
1552 		}
1553 	}
1554 }
1555