xref: /illumos-gate/usr/src/uts/common/os/cpu.c (revision 628e3cbed6489fa1db545d8524a06cd6535af456)
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 2008 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 #pragma ident	"%Z%%M%	%I%	%E% SMI"
27 
28 /*
29  * Architecture-independent CPU control functions.
30  */
31 
32 #include <sys/types.h>
33 #include <sys/param.h>
34 #include <sys/var.h>
35 #include <sys/thread.h>
36 #include <sys/cpuvar.h>
37 #include <sys/kstat.h>
38 #include <sys/uadmin.h>
39 #include <sys/systm.h>
40 #include <sys/errno.h>
41 #include <sys/cmn_err.h>
42 #include <sys/procset.h>
43 #include <sys/processor.h>
44 #include <sys/debug.h>
45 #include <sys/cpupart.h>
46 #include <sys/lgrp.h>
47 #include <sys/pset.h>
48 #include <sys/pghw.h>
49 #include <sys/kmem.h>
50 #include <sys/kmem_impl.h>	/* to set per-cpu kmem_cache offset */
51 #include <sys/atomic.h>
52 #include <sys/callb.h>
53 #include <sys/vtrace.h>
54 #include <sys/cyclic.h>
55 #include <sys/bitmap.h>
56 #include <sys/nvpair.h>
57 #include <sys/pool_pset.h>
58 #include <sys/msacct.h>
59 #include <sys/time.h>
60 #include <sys/archsystm.h>
61 #if defined(__x86) || defined(__amd64)
62 #include <sys/x86_archext.h>
63 #endif
64 
65 extern int	mp_cpu_start(cpu_t *);
66 extern int	mp_cpu_stop(cpu_t *);
67 extern int	mp_cpu_poweron(cpu_t *);
68 extern int	mp_cpu_poweroff(cpu_t *);
69 extern int	mp_cpu_configure(int);
70 extern int	mp_cpu_unconfigure(int);
71 extern void	mp_cpu_faulted_enter(cpu_t *);
72 extern void	mp_cpu_faulted_exit(cpu_t *);
73 
74 extern int cmp_cpu_to_chip(processorid_t cpuid);
75 #ifdef __sparcv9
76 extern char *cpu_fru_fmri(cpu_t *cp);
77 #endif
78 
79 static void cpu_add_active_internal(cpu_t *cp);
80 static void cpu_remove_active(cpu_t *cp);
81 static void cpu_info_kstat_create(cpu_t *cp);
82 static void cpu_info_kstat_destroy(cpu_t *cp);
83 static void cpu_stats_kstat_create(cpu_t *cp);
84 static void cpu_stats_kstat_destroy(cpu_t *cp);
85 
86 static int cpu_sys_stats_ks_update(kstat_t *ksp, int rw);
87 static int cpu_vm_stats_ks_update(kstat_t *ksp, int rw);
88 static int cpu_stat_ks_update(kstat_t *ksp, int rw);
89 static int cpu_state_change_hooks(int, cpu_setup_t, cpu_setup_t);
90 
91 /*
92  * cpu_lock protects ncpus, ncpus_online, cpu_flag, cpu_list, cpu_active,
93  * and dispatch queue reallocations.  The lock ordering with respect to
94  * related locks is:
95  *
96  *	cpu_lock --> thread_free_lock  --->  p_lock  --->  thread_lock()
97  *
98  * Warning:  Certain sections of code do not use the cpu_lock when
99  * traversing the cpu_list (e.g. mutex_vector_enter(), clock()).  Since
100  * all cpus are paused during modifications to this list, a solution
101  * to protect the list is too either disable kernel preemption while
102  * walking the list, *or* recheck the cpu_next pointer at each
103  * iteration in the loop.  Note that in no cases can any cached
104  * copies of the cpu pointers be kept as they may become invalid.
105  */
106 kmutex_t	cpu_lock;
107 cpu_t		*cpu_list;		/* list of all CPUs */
108 cpu_t		*clock_cpu_list;	/* used by clock to walk CPUs */
109 cpu_t		*cpu_active;		/* list of active CPUs */
110 static cpuset_t	cpu_available;		/* set of available CPUs */
111 cpuset_t	cpu_seqid_inuse;	/* which cpu_seqids are in use */
112 
113 /*
114  * max_ncpus keeps the max cpus the system can have. Initially
115  * it's NCPU, but since most archs scan the devtree for cpus
116  * fairly early on during boot, the real max can be known before
117  * ncpus is set (useful for early NCPU based allocations).
118  */
119 int max_ncpus = NCPU;
120 /*
121  * platforms that set max_ncpus to maxiumum number of cpus that can be
122  * dynamically added will set boot_max_ncpus to the number of cpus found
123  * at device tree scan time during boot.
124  */
125 int boot_max_ncpus = -1;
126 int boot_ncpus = -1;
127 /*
128  * Maximum possible CPU id.  This can never be >= NCPU since NCPU is
129  * used to size arrays that are indexed by CPU id.
130  */
131 processorid_t max_cpuid = NCPU - 1;
132 
133 int ncpus = 1;
134 int ncpus_online = 1;
135 
136 /*
137  * CPU that we're trying to offline.  Protected by cpu_lock.
138  */
139 cpu_t *cpu_inmotion;
140 
141 /*
142  * Can be raised to suppress further weakbinding, which are instead
143  * satisfied by disabling preemption.  Must be raised/lowered under cpu_lock,
144  * while individual thread weakbinding synchronisation is done under thread
145  * lock.
146  */
147 int weakbindingbarrier;
148 
149 /*
150  * Variables used in pause_cpus().
151  */
152 static volatile char safe_list[NCPU];
153 
154 static struct _cpu_pause_info {
155 	int		cp_spl;		/* spl saved in pause_cpus() */
156 	volatile int	cp_go;		/* Go signal sent after all ready */
157 	int		cp_count;	/* # of CPUs to pause */
158 	ksema_t		cp_sem;		/* synch pause_cpus & cpu_pause */
159 	kthread_id_t	cp_paused;
160 } cpu_pause_info;
161 
162 static kmutex_t pause_free_mutex;
163 static kcondvar_t pause_free_cv;
164 
165 void *(*cpu_pause_func)(void *) = NULL;
166 
167 
168 static struct cpu_sys_stats_ks_data {
169 	kstat_named_t cpu_ticks_idle;
170 	kstat_named_t cpu_ticks_user;
171 	kstat_named_t cpu_ticks_kernel;
172 	kstat_named_t cpu_ticks_wait;
173 	kstat_named_t cpu_nsec_idle;
174 	kstat_named_t cpu_nsec_user;
175 	kstat_named_t cpu_nsec_kernel;
176 	kstat_named_t cpu_nsec_intr;
177 	kstat_named_t cpu_load_intr;
178 	kstat_named_t wait_ticks_io;
179 	kstat_named_t bread;
180 	kstat_named_t bwrite;
181 	kstat_named_t lread;
182 	kstat_named_t lwrite;
183 	kstat_named_t phread;
184 	kstat_named_t phwrite;
185 	kstat_named_t pswitch;
186 	kstat_named_t trap;
187 	kstat_named_t intr;
188 	kstat_named_t syscall;
189 	kstat_named_t sysread;
190 	kstat_named_t syswrite;
191 	kstat_named_t sysfork;
192 	kstat_named_t sysvfork;
193 	kstat_named_t sysexec;
194 	kstat_named_t readch;
195 	kstat_named_t writech;
196 	kstat_named_t rcvint;
197 	kstat_named_t xmtint;
198 	kstat_named_t mdmint;
199 	kstat_named_t rawch;
200 	kstat_named_t canch;
201 	kstat_named_t outch;
202 	kstat_named_t msg;
203 	kstat_named_t sema;
204 	kstat_named_t namei;
205 	kstat_named_t ufsiget;
206 	kstat_named_t ufsdirblk;
207 	kstat_named_t ufsipage;
208 	kstat_named_t ufsinopage;
209 	kstat_named_t procovf;
210 	kstat_named_t intrthread;
211 	kstat_named_t intrblk;
212 	kstat_named_t intrunpin;
213 	kstat_named_t idlethread;
214 	kstat_named_t inv_swtch;
215 	kstat_named_t nthreads;
216 	kstat_named_t cpumigrate;
217 	kstat_named_t xcalls;
218 	kstat_named_t mutex_adenters;
219 	kstat_named_t rw_rdfails;
220 	kstat_named_t rw_wrfails;
221 	kstat_named_t modload;
222 	kstat_named_t modunload;
223 	kstat_named_t bawrite;
224 	kstat_named_t iowait;
225 } cpu_sys_stats_ks_data_template = {
226 	{ "cpu_ticks_idle", 	KSTAT_DATA_UINT64 },
227 	{ "cpu_ticks_user", 	KSTAT_DATA_UINT64 },
228 	{ "cpu_ticks_kernel", 	KSTAT_DATA_UINT64 },
229 	{ "cpu_ticks_wait", 	KSTAT_DATA_UINT64 },
230 	{ "cpu_nsec_idle",	KSTAT_DATA_UINT64 },
231 	{ "cpu_nsec_user",	KSTAT_DATA_UINT64 },
232 	{ "cpu_nsec_kernel",	KSTAT_DATA_UINT64 },
233 	{ "cpu_nsec_intr",	KSTAT_DATA_UINT64 },
234 	{ "cpu_load_intr",	KSTAT_DATA_UINT64 },
235 	{ "wait_ticks_io", 	KSTAT_DATA_UINT64 },
236 	{ "bread", 		KSTAT_DATA_UINT64 },
237 	{ "bwrite", 		KSTAT_DATA_UINT64 },
238 	{ "lread", 		KSTAT_DATA_UINT64 },
239 	{ "lwrite", 		KSTAT_DATA_UINT64 },
240 	{ "phread", 		KSTAT_DATA_UINT64 },
241 	{ "phwrite", 		KSTAT_DATA_UINT64 },
242 	{ "pswitch", 		KSTAT_DATA_UINT64 },
243 	{ "trap", 		KSTAT_DATA_UINT64 },
244 	{ "intr", 		KSTAT_DATA_UINT64 },
245 	{ "syscall", 		KSTAT_DATA_UINT64 },
246 	{ "sysread", 		KSTAT_DATA_UINT64 },
247 	{ "syswrite", 		KSTAT_DATA_UINT64 },
248 	{ "sysfork", 		KSTAT_DATA_UINT64 },
249 	{ "sysvfork", 		KSTAT_DATA_UINT64 },
250 	{ "sysexec", 		KSTAT_DATA_UINT64 },
251 	{ "readch", 		KSTAT_DATA_UINT64 },
252 	{ "writech", 		KSTAT_DATA_UINT64 },
253 	{ "rcvint", 		KSTAT_DATA_UINT64 },
254 	{ "xmtint", 		KSTAT_DATA_UINT64 },
255 	{ "mdmint", 		KSTAT_DATA_UINT64 },
256 	{ "rawch", 		KSTAT_DATA_UINT64 },
257 	{ "canch", 		KSTAT_DATA_UINT64 },
258 	{ "outch", 		KSTAT_DATA_UINT64 },
259 	{ "msg", 		KSTAT_DATA_UINT64 },
260 	{ "sema", 		KSTAT_DATA_UINT64 },
261 	{ "namei", 		KSTAT_DATA_UINT64 },
262 	{ "ufsiget", 		KSTAT_DATA_UINT64 },
263 	{ "ufsdirblk", 		KSTAT_DATA_UINT64 },
264 	{ "ufsipage", 		KSTAT_DATA_UINT64 },
265 	{ "ufsinopage", 	KSTAT_DATA_UINT64 },
266 	{ "procovf", 		KSTAT_DATA_UINT64 },
267 	{ "intrthread", 	KSTAT_DATA_UINT64 },
268 	{ "intrblk", 		KSTAT_DATA_UINT64 },
269 	{ "intrunpin",		KSTAT_DATA_UINT64 },
270 	{ "idlethread", 	KSTAT_DATA_UINT64 },
271 	{ "inv_swtch", 		KSTAT_DATA_UINT64 },
272 	{ "nthreads", 		KSTAT_DATA_UINT64 },
273 	{ "cpumigrate", 	KSTAT_DATA_UINT64 },
274 	{ "xcalls", 		KSTAT_DATA_UINT64 },
275 	{ "mutex_adenters", 	KSTAT_DATA_UINT64 },
276 	{ "rw_rdfails", 	KSTAT_DATA_UINT64 },
277 	{ "rw_wrfails", 	KSTAT_DATA_UINT64 },
278 	{ "modload", 		KSTAT_DATA_UINT64 },
279 	{ "modunload", 		KSTAT_DATA_UINT64 },
280 	{ "bawrite", 		KSTAT_DATA_UINT64 },
281 	{ "iowait",		KSTAT_DATA_UINT64 },
282 };
283 
284 static struct cpu_vm_stats_ks_data {
285 	kstat_named_t pgrec;
286 	kstat_named_t pgfrec;
287 	kstat_named_t pgin;
288 	kstat_named_t pgpgin;
289 	kstat_named_t pgout;
290 	kstat_named_t pgpgout;
291 	kstat_named_t swapin;
292 	kstat_named_t pgswapin;
293 	kstat_named_t swapout;
294 	kstat_named_t pgswapout;
295 	kstat_named_t zfod;
296 	kstat_named_t dfree;
297 	kstat_named_t scan;
298 	kstat_named_t rev;
299 	kstat_named_t hat_fault;
300 	kstat_named_t as_fault;
301 	kstat_named_t maj_fault;
302 	kstat_named_t cow_fault;
303 	kstat_named_t prot_fault;
304 	kstat_named_t softlock;
305 	kstat_named_t kernel_asflt;
306 	kstat_named_t pgrrun;
307 	kstat_named_t execpgin;
308 	kstat_named_t execpgout;
309 	kstat_named_t execfree;
310 	kstat_named_t anonpgin;
311 	kstat_named_t anonpgout;
312 	kstat_named_t anonfree;
313 	kstat_named_t fspgin;
314 	kstat_named_t fspgout;
315 	kstat_named_t fsfree;
316 } cpu_vm_stats_ks_data_template = {
317 	{ "pgrec",		KSTAT_DATA_UINT64 },
318 	{ "pgfrec",		KSTAT_DATA_UINT64 },
319 	{ "pgin",		KSTAT_DATA_UINT64 },
320 	{ "pgpgin",		KSTAT_DATA_UINT64 },
321 	{ "pgout",		KSTAT_DATA_UINT64 },
322 	{ "pgpgout",		KSTAT_DATA_UINT64 },
323 	{ "swapin",		KSTAT_DATA_UINT64 },
324 	{ "pgswapin",		KSTAT_DATA_UINT64 },
325 	{ "swapout",		KSTAT_DATA_UINT64 },
326 	{ "pgswapout",		KSTAT_DATA_UINT64 },
327 	{ "zfod",		KSTAT_DATA_UINT64 },
328 	{ "dfree",		KSTAT_DATA_UINT64 },
329 	{ "scan",		KSTAT_DATA_UINT64 },
330 	{ "rev",		KSTAT_DATA_UINT64 },
331 	{ "hat_fault",		KSTAT_DATA_UINT64 },
332 	{ "as_fault",		KSTAT_DATA_UINT64 },
333 	{ "maj_fault",		KSTAT_DATA_UINT64 },
334 	{ "cow_fault",		KSTAT_DATA_UINT64 },
335 	{ "prot_fault",		KSTAT_DATA_UINT64 },
336 	{ "softlock",		KSTAT_DATA_UINT64 },
337 	{ "kernel_asflt",	KSTAT_DATA_UINT64 },
338 	{ "pgrrun",		KSTAT_DATA_UINT64 },
339 	{ "execpgin",		KSTAT_DATA_UINT64 },
340 	{ "execpgout",		KSTAT_DATA_UINT64 },
341 	{ "execfree",		KSTAT_DATA_UINT64 },
342 	{ "anonpgin",		KSTAT_DATA_UINT64 },
343 	{ "anonpgout",		KSTAT_DATA_UINT64 },
344 	{ "anonfree",		KSTAT_DATA_UINT64 },
345 	{ "fspgin",		KSTAT_DATA_UINT64 },
346 	{ "fspgout",		KSTAT_DATA_UINT64 },
347 	{ "fsfree",		KSTAT_DATA_UINT64 },
348 };
349 
350 /*
351  * Force the specified thread to migrate to the appropriate processor.
352  * Called with thread lock held, returns with it dropped.
353  */
354 static void
355 force_thread_migrate(kthread_id_t tp)
356 {
357 	ASSERT(THREAD_LOCK_HELD(tp));
358 	if (tp == curthread) {
359 		THREAD_TRANSITION(tp);
360 		CL_SETRUN(tp);
361 		thread_unlock_nopreempt(tp);
362 		swtch();
363 	} else {
364 		if (tp->t_state == TS_ONPROC) {
365 			cpu_surrender(tp);
366 		} else if (tp->t_state == TS_RUN) {
367 			(void) dispdeq(tp);
368 			setbackdq(tp);
369 		}
370 		thread_unlock(tp);
371 	}
372 }
373 
374 /*
375  * Set affinity for a specified CPU.
376  * A reference count is incremented and the affinity is held until the
377  * reference count is decremented to zero by thread_affinity_clear().
378  * This is so regions of code requiring affinity can be nested.
379  * Caller needs to ensure that cpu_id remains valid, which can be
380  * done by holding cpu_lock across this call, unless the caller
381  * specifies CPU_CURRENT in which case the cpu_lock will be acquired
382  * by thread_affinity_set and CPU->cpu_id will be the target CPU.
383  */
384 void
385 thread_affinity_set(kthread_id_t t, int cpu_id)
386 {
387 	cpu_t		*cp;
388 	int		c;
389 
390 	ASSERT(!(t == curthread && t->t_weakbound_cpu != NULL));
391 
392 	if ((c = cpu_id) == CPU_CURRENT) {
393 		mutex_enter(&cpu_lock);
394 		cpu_id = CPU->cpu_id;
395 	}
396 	/*
397 	 * We should be asserting that cpu_lock is held here, but
398 	 * the NCA code doesn't acquire it.  The following assert
399 	 * should be uncommented when the NCA code is fixed.
400 	 *
401 	 * ASSERT(MUTEX_HELD(&cpu_lock));
402 	 */
403 	ASSERT((cpu_id >= 0) && (cpu_id < NCPU));
404 	cp = cpu[cpu_id];
405 	ASSERT(cp != NULL);		/* user must provide a good cpu_id */
406 	/*
407 	 * If there is already a hard affinity requested, and this affinity
408 	 * conflicts with that, panic.
409 	 */
410 	thread_lock(t);
411 	if (t->t_affinitycnt > 0 && t->t_bound_cpu != cp) {
412 		panic("affinity_set: setting %p but already bound to %p",
413 		    (void *)cp, (void *)t->t_bound_cpu);
414 	}
415 	t->t_affinitycnt++;
416 	t->t_bound_cpu = cp;
417 
418 	/*
419 	 * Make sure we're running on the right CPU.
420 	 */
421 	if (cp != t->t_cpu || t != curthread) {
422 		force_thread_migrate(t);	/* drops thread lock */
423 	} else {
424 		thread_unlock(t);
425 	}
426 
427 	if (c == CPU_CURRENT)
428 		mutex_exit(&cpu_lock);
429 }
430 
431 /*
432  *	Wrapper for backward compatibility.
433  */
434 void
435 affinity_set(int cpu_id)
436 {
437 	thread_affinity_set(curthread, cpu_id);
438 }
439 
440 /*
441  * Decrement the affinity reservation count and if it becomes zero,
442  * clear the CPU affinity for the current thread, or set it to the user's
443  * software binding request.
444  */
445 void
446 thread_affinity_clear(kthread_id_t t)
447 {
448 	register processorid_t binding;
449 
450 	thread_lock(t);
451 	if (--t->t_affinitycnt == 0) {
452 		if ((binding = t->t_bind_cpu) == PBIND_NONE) {
453 			/*
454 			 * Adjust disp_max_unbound_pri if necessary.
455 			 */
456 			disp_adjust_unbound_pri(t);
457 			t->t_bound_cpu = NULL;
458 			if (t->t_cpu->cpu_part != t->t_cpupart) {
459 				force_thread_migrate(t);
460 				return;
461 			}
462 		} else {
463 			t->t_bound_cpu = cpu[binding];
464 			/*
465 			 * Make sure the thread is running on the bound CPU.
466 			 */
467 			if (t->t_cpu != t->t_bound_cpu) {
468 				force_thread_migrate(t);
469 				return;		/* already dropped lock */
470 			}
471 		}
472 	}
473 	thread_unlock(t);
474 }
475 
476 /*
477  * Wrapper for backward compatibility.
478  */
479 void
480 affinity_clear(void)
481 {
482 	thread_affinity_clear(curthread);
483 }
484 
485 /*
486  * Weak cpu affinity.  Bind to the "current" cpu for short periods
487  * of time during which the thread must not block (but may be preempted).
488  * Use this instead of kpreempt_disable() when it is only "no migration"
489  * rather than "no preemption" semantics that are required - disabling
490  * preemption holds higher priority threads off of cpu and if the
491  * operation that is protected is more than momentary this is not good
492  * for realtime etc.
493  *
494  * Weakly bound threads will not prevent a cpu from being offlined -
495  * we'll only run them on the cpu to which they are weakly bound but
496  * (because they do not block) we'll always be able to move them on to
497  * another cpu at offline time if we give them just a short moment to
498  * run during which they will unbind.  To give a cpu a chance of offlining,
499  * however, we require a barrier to weak bindings that may be raised for a
500  * given cpu (offline/move code may set this and then wait a short time for
501  * existing weak bindings to drop); the cpu_inmotion pointer is that barrier.
502  *
503  * There are few restrictions on the calling context of thread_nomigrate.
504  * The caller must not hold the thread lock.  Calls may be nested.
505  *
506  * After weakbinding a thread must not perform actions that may block.
507  * In particular it must not call thread_affinity_set; calling that when
508  * already weakbound is nonsensical anyway.
509  *
510  * If curthread is prevented from migrating for other reasons
511  * (kernel preemption disabled; high pil; strongly bound; interrupt thread)
512  * then the weak binding will succeed even if this cpu is the target of an
513  * offline/move request.
514  */
515 void
516 thread_nomigrate(void)
517 {
518 	cpu_t *cp;
519 	kthread_id_t t = curthread;
520 
521 again:
522 	kpreempt_disable();
523 	cp = CPU;
524 
525 	/*
526 	 * A highlevel interrupt must not modify t_nomigrate or
527 	 * t_weakbound_cpu of the thread it has interrupted.  A lowlevel
528 	 * interrupt thread cannot migrate and we can avoid the
529 	 * thread_lock call below by short-circuiting here.  In either
530 	 * case we can just return since no migration is possible and
531 	 * the condition will persist (ie, when we test for these again
532 	 * in thread_allowmigrate they can't have changed).   Migration
533 	 * is also impossible if we're at or above DISP_LEVEL pil.
534 	 */
535 	if (CPU_ON_INTR(cp) || t->t_flag & T_INTR_THREAD ||
536 	    getpil() >= DISP_LEVEL) {
537 		kpreempt_enable();
538 		return;
539 	}
540 
541 	/*
542 	 * We must be consistent with existing weak bindings.  Since we
543 	 * may be interrupted between the increment of t_nomigrate and
544 	 * the store to t_weakbound_cpu below we cannot assume that
545 	 * t_weakbound_cpu will be set if t_nomigrate is.  Note that we
546 	 * cannot assert t_weakbound_cpu == t_bind_cpu since that is not
547 	 * always the case.
548 	 */
549 	if (t->t_nomigrate && t->t_weakbound_cpu && t->t_weakbound_cpu != cp) {
550 		if (!panicstr)
551 			panic("thread_nomigrate: binding to %p but already "
552 			    "bound to %p", (void *)cp,
553 			    (void *)t->t_weakbound_cpu);
554 	}
555 
556 	/*
557 	 * At this point we have preemption disabled and we don't yet hold
558 	 * the thread lock.  So it's possible that somebody else could
559 	 * set t_bind_cpu here and not be able to force us across to the
560 	 * new cpu (since we have preemption disabled).
561 	 */
562 	thread_lock(curthread);
563 
564 	/*
565 	 * If further weak bindings are being (temporarily) suppressed then
566 	 * we'll settle for disabling kernel preemption (which assures
567 	 * no migration provided the thread does not block which it is
568 	 * not allowed to if using thread_nomigrate).  We must remember
569 	 * this disposition so we can take appropriate action in
570 	 * thread_allowmigrate.  If this is a nested call and the
571 	 * thread is already weakbound then fall through as normal.
572 	 * We remember the decision to settle for kpreempt_disable through
573 	 * negative nesting counting in t_nomigrate.  Once a thread has had one
574 	 * weakbinding request satisfied in this way any further (nested)
575 	 * requests will continue to be satisfied in the same way,
576 	 * even if weak bindings have recommenced.
577 	 */
578 	if (t->t_nomigrate < 0 || weakbindingbarrier && t->t_nomigrate == 0) {
579 		--t->t_nomigrate;
580 		thread_unlock(curthread);
581 		return;		/* with kpreempt_disable still active */
582 	}
583 
584 	/*
585 	 * We hold thread_lock so t_bind_cpu cannot change.  We could,
586 	 * however, be running on a different cpu to which we are t_bound_cpu
587 	 * to (as explained above).  If we grant the weak binding request
588 	 * in that case then the dispatcher must favour our weak binding
589 	 * over our strong (in which case, just as when preemption is
590 	 * disabled, we can continue to run on a cpu other than the one to
591 	 * which we are strongbound; the difference in this case is that
592 	 * this thread can be preempted and so can appear on the dispatch
593 	 * queues of a cpu other than the one it is strongbound to).
594 	 *
595 	 * If the cpu we are running on does not appear to be a current
596 	 * offline target (we check cpu_inmotion to determine this - since
597 	 * we don't hold cpu_lock we may not see a recent store to that,
598 	 * so it's possible that we at times can grant a weak binding to a
599 	 * cpu that is an offline target, but that one request will not
600 	 * prevent the offline from succeeding) then we will always grant
601 	 * the weak binding request.  This includes the case above where
602 	 * we grant a weakbinding not commensurate with our strong binding.
603 	 *
604 	 * If our cpu does appear to be an offline target then we're inclined
605 	 * not to grant the weakbinding request just yet - we'd prefer to
606 	 * migrate to another cpu and grant the request there.  The
607 	 * exceptions are those cases where going through preemption code
608 	 * will not result in us changing cpu:
609 	 *
610 	 *	. interrupts have already bypassed this case (see above)
611 	 *	. we are already weakbound to this cpu (dispatcher code will
612 	 *	  always return us to the weakbound cpu)
613 	 *	. preemption was disabled even before we disabled it above
614 	 *	. we are strongbound to this cpu (if we're strongbound to
615 	 *	another and not yet running there the trip through the
616 	 *	dispatcher will move us to the strongbound cpu and we
617 	 *	will grant the weak binding there)
618 	 */
619 	if (cp != cpu_inmotion || t->t_nomigrate > 0 || t->t_preempt > 1 ||
620 	    t->t_bound_cpu == cp) {
621 		/*
622 		 * Don't be tempted to store to t_weakbound_cpu only on
623 		 * the first nested bind request - if we're interrupted
624 		 * after the increment of t_nomigrate and before the
625 		 * store to t_weakbound_cpu and the interrupt calls
626 		 * thread_nomigrate then the assertion in thread_allowmigrate
627 		 * would fail.
628 		 */
629 		t->t_nomigrate++;
630 		t->t_weakbound_cpu = cp;
631 		membar_producer();
632 		thread_unlock(curthread);
633 		/*
634 		 * Now that we have dropped the thread_lock another thread
635 		 * can set our t_weakbound_cpu, and will try to migrate us
636 		 * to the strongbound cpu (which will not be prevented by
637 		 * preemption being disabled since we're about to enable
638 		 * preemption).  We have granted the weakbinding to the current
639 		 * cpu, so again we are in the position that is is is possible
640 		 * that our weak and strong bindings differ.  Again this
641 		 * is catered for by dispatcher code which will favour our
642 		 * weak binding.
643 		 */
644 		kpreempt_enable();
645 	} else {
646 		/*
647 		 * Move to another cpu before granting the request by
648 		 * forcing this thread through preemption code.  When we
649 		 * get to set{front,back}dq called from CL_PREEMPT()
650 		 * cpu_choose() will be used to select a cpu to queue
651 		 * us on - that will see cpu_inmotion and take
652 		 * steps to avoid returning us to this cpu.
653 		 */
654 		cp->cpu_kprunrun = 1;
655 		thread_unlock(curthread);
656 		kpreempt_enable();	/* will call preempt() */
657 		goto again;
658 	}
659 }
660 
661 void
662 thread_allowmigrate(void)
663 {
664 	kthread_id_t t = curthread;
665 
666 	ASSERT(t->t_weakbound_cpu == CPU ||
667 	    (t->t_nomigrate < 0 && t->t_preempt > 0) ||
668 	    CPU_ON_INTR(CPU) || t->t_flag & T_INTR_THREAD ||
669 	    getpil() >= DISP_LEVEL);
670 
671 	if (CPU_ON_INTR(CPU) || (t->t_flag & T_INTR_THREAD) ||
672 	    getpil() >= DISP_LEVEL)
673 		return;
674 
675 	if (t->t_nomigrate < 0) {
676 		/*
677 		 * This thread was granted "weak binding" in the
678 		 * stronger form of kernel preemption disabling.
679 		 * Undo a level of nesting for both t_nomigrate
680 		 * and t_preempt.
681 		 */
682 		++t->t_nomigrate;
683 		kpreempt_enable();
684 	} else if (--t->t_nomigrate == 0) {
685 		/*
686 		 * Time to drop the weak binding.  We need to cater
687 		 * for the case where we're weakbound to a different
688 		 * cpu than that to which we're strongbound (a very
689 		 * temporary arrangement that must only persist until
690 		 * weak binding drops).  We don't acquire thread_lock
691 		 * here so even as this code executes t_bound_cpu
692 		 * may be changing.  So we disable preemption and
693 		 * a) in the case that t_bound_cpu changes while we
694 		 * have preemption disabled kprunrun will be set
695 		 * asynchronously, and b) if before disabling
696 		 * preemption we were already on a different cpu to
697 		 * our t_bound_cpu then we set kprunrun ourselves
698 		 * to force a trip through the dispatcher when
699 		 * preemption is enabled.
700 		 */
701 		kpreempt_disable();
702 		if (t->t_bound_cpu &&
703 		    t->t_weakbound_cpu != t->t_bound_cpu)
704 			CPU->cpu_kprunrun = 1;
705 		t->t_weakbound_cpu = NULL;
706 		membar_producer();
707 		kpreempt_enable();
708 	}
709 }
710 
711 /*
712  * weakbinding_stop can be used to temporarily cause weakbindings made
713  * with thread_nomigrate to be satisfied through the stronger action of
714  * kpreempt_disable.  weakbinding_start recommences normal weakbinding.
715  */
716 
717 void
718 weakbinding_stop(void)
719 {
720 	ASSERT(MUTEX_HELD(&cpu_lock));
721 	weakbindingbarrier = 1;
722 	membar_producer();	/* make visible before subsequent thread_lock */
723 }
724 
725 void
726 weakbinding_start(void)
727 {
728 	ASSERT(MUTEX_HELD(&cpu_lock));
729 	weakbindingbarrier = 0;
730 }
731 
732 void
733 null_xcall(void)
734 {
735 }
736 
737 /*
738  * This routine is called to place the CPUs in a safe place so that
739  * one of them can be taken off line or placed on line.  What we are
740  * trying to do here is prevent a thread from traversing the list
741  * of active CPUs while we are changing it or from getting placed on
742  * the run queue of a CPU that has just gone off line.  We do this by
743  * creating a thread with the highest possible prio for each CPU and
744  * having it call this routine.  The advantage of this method is that
745  * we can eliminate all checks for CPU_ACTIVE in the disp routines.
746  * This makes disp faster at the expense of making p_online() slower
747  * which is a good trade off.
748  */
749 static void
750 cpu_pause(int index)
751 {
752 	int s;
753 	struct _cpu_pause_info *cpi = &cpu_pause_info;
754 	volatile char *safe = &safe_list[index];
755 	long    lindex = index;
756 
757 	ASSERT((curthread->t_bound_cpu != NULL) || (*safe == PAUSE_DIE));
758 
759 	while (*safe != PAUSE_DIE) {
760 		*safe = PAUSE_READY;
761 		membar_enter();		/* make sure stores are flushed */
762 		sema_v(&cpi->cp_sem);	/* signal requesting thread */
763 
764 		/*
765 		 * Wait here until all pause threads are running.  That
766 		 * indicates that it's safe to do the spl.  Until
767 		 * cpu_pause_info.cp_go is set, we don't want to spl
768 		 * because that might block clock interrupts needed
769 		 * to preempt threads on other CPUs.
770 		 */
771 		while (cpi->cp_go == 0)
772 			;
773 		/*
774 		 * Even though we are at the highest disp prio, we need
775 		 * to block out all interrupts below LOCK_LEVEL so that
776 		 * an intr doesn't come in, wake up a thread, and call
777 		 * setbackdq/setfrontdq.
778 		 */
779 		s = splhigh();
780 		/*
781 		 * if cpu_pause_func() has been set then call it using
782 		 * index as the argument, currently only used by
783 		 * cpr_suspend_cpus().  This function is used as the
784 		 * code to execute on the "paused" cpu's when a machine
785 		 * comes out of a sleep state and CPU's were powered off.
786 		 * (could also be used for hotplugging CPU's).
787 		 */
788 		if (cpu_pause_func != NULL)
789 			(*cpu_pause_func)((void *)lindex);
790 
791 		mach_cpu_pause(safe);
792 
793 		splx(s);
794 		/*
795 		 * Waiting is at an end. Switch out of cpu_pause
796 		 * loop and resume useful work.
797 		 */
798 		swtch();
799 	}
800 
801 	mutex_enter(&pause_free_mutex);
802 	*safe = PAUSE_DEAD;
803 	cv_broadcast(&pause_free_cv);
804 	mutex_exit(&pause_free_mutex);
805 }
806 
807 /*
808  * Allow the cpus to start running again.
809  */
810 void
811 start_cpus()
812 {
813 	int i;
814 
815 	ASSERT(MUTEX_HELD(&cpu_lock));
816 	ASSERT(cpu_pause_info.cp_paused);
817 	cpu_pause_info.cp_paused = NULL;
818 	for (i = 0; i < NCPU; i++)
819 		safe_list[i] = PAUSE_IDLE;
820 	membar_enter();			/* make sure stores are flushed */
821 	affinity_clear();
822 	splx(cpu_pause_info.cp_spl);
823 	kpreempt_enable();
824 }
825 
826 /*
827  * Allocate a pause thread for a CPU.
828  */
829 static void
830 cpu_pause_alloc(cpu_t *cp)
831 {
832 	kthread_id_t	t;
833 	long		cpun = cp->cpu_id;
834 
835 	/*
836 	 * Note, v.v_nglobpris will not change value as long as I hold
837 	 * cpu_lock.
838 	 */
839 	t = thread_create(NULL, 0, cpu_pause, (void *)cpun,
840 	    0, &p0, TS_STOPPED, v.v_nglobpris - 1);
841 	thread_lock(t);
842 	t->t_bound_cpu = cp;
843 	t->t_disp_queue = cp->cpu_disp;
844 	t->t_affinitycnt = 1;
845 	t->t_preempt = 1;
846 	thread_unlock(t);
847 	cp->cpu_pause_thread = t;
848 	/*
849 	 * Registering a thread in the callback table is usually done
850 	 * in the initialization code of the thread.  In this
851 	 * case, we do it right after thread creation because the
852 	 * thread itself may never run, and we need to register the
853 	 * fact that it is safe for cpr suspend.
854 	 */
855 	CALLB_CPR_INIT_SAFE(t, "cpu_pause");
856 }
857 
858 /*
859  * Free a pause thread for a CPU.
860  */
861 static void
862 cpu_pause_free(cpu_t *cp)
863 {
864 	kthread_id_t	t;
865 	int		cpun = cp->cpu_id;
866 
867 	ASSERT(MUTEX_HELD(&cpu_lock));
868 	/*
869 	 * We have to get the thread and tell him to die.
870 	 */
871 	if ((t = cp->cpu_pause_thread) == NULL) {
872 		ASSERT(safe_list[cpun] == PAUSE_IDLE);
873 		return;
874 	}
875 	thread_lock(t);
876 	t->t_cpu = CPU;		/* disp gets upset if last cpu is quiesced. */
877 	t->t_bound_cpu = NULL;	/* Must un-bind; cpu may not be running. */
878 	t->t_pri = v.v_nglobpris - 1;
879 	ASSERT(safe_list[cpun] == PAUSE_IDLE);
880 	safe_list[cpun] = PAUSE_DIE;
881 	THREAD_TRANSITION(t);
882 	setbackdq(t);
883 	thread_unlock_nopreempt(t);
884 
885 	/*
886 	 * If we don't wait for the thread to actually die, it may try to
887 	 * run on the wrong cpu as part of an actual call to pause_cpus().
888 	 */
889 	mutex_enter(&pause_free_mutex);
890 	while (safe_list[cpun] != PAUSE_DEAD) {
891 		cv_wait(&pause_free_cv, &pause_free_mutex);
892 	}
893 	mutex_exit(&pause_free_mutex);
894 	safe_list[cpun] = PAUSE_IDLE;
895 
896 	cp->cpu_pause_thread = NULL;
897 }
898 
899 /*
900  * Initialize basic structures for pausing CPUs.
901  */
902 void
903 cpu_pause_init()
904 {
905 	sema_init(&cpu_pause_info.cp_sem, 0, NULL, SEMA_DEFAULT, NULL);
906 	/*
907 	 * Create initial CPU pause thread.
908 	 */
909 	cpu_pause_alloc(CPU);
910 }
911 
912 /*
913  * Start the threads used to pause another CPU.
914  */
915 static int
916 cpu_pause_start(processorid_t cpu_id)
917 {
918 	int	i;
919 	int	cpu_count = 0;
920 
921 	for (i = 0; i < NCPU; i++) {
922 		cpu_t		*cp;
923 		kthread_id_t	t;
924 
925 		cp = cpu[i];
926 		if (!CPU_IN_SET(cpu_available, i) || (i == cpu_id)) {
927 			safe_list[i] = PAUSE_WAIT;
928 			continue;
929 		}
930 
931 		/*
932 		 * Skip CPU if it is quiesced or not yet started.
933 		 */
934 		if ((cp->cpu_flags & (CPU_QUIESCED | CPU_READY)) != CPU_READY) {
935 			safe_list[i] = PAUSE_WAIT;
936 			continue;
937 		}
938 
939 		/*
940 		 * Start this CPU's pause thread.
941 		 */
942 		t = cp->cpu_pause_thread;
943 		thread_lock(t);
944 		/*
945 		 * Reset the priority, since nglobpris may have
946 		 * changed since the thread was created, if someone
947 		 * has loaded the RT (or some other) scheduling
948 		 * class.
949 		 */
950 		t->t_pri = v.v_nglobpris - 1;
951 		THREAD_TRANSITION(t);
952 		setbackdq(t);
953 		thread_unlock_nopreempt(t);
954 		++cpu_count;
955 	}
956 	return (cpu_count);
957 }
958 
959 
960 /*
961  * Pause all of the CPUs except the one we are on by creating a high
962  * priority thread bound to those CPUs.
963  *
964  * Note that one must be extremely careful regarding code
965  * executed while CPUs are paused.  Since a CPU may be paused
966  * while a thread scheduling on that CPU is holding an adaptive
967  * lock, code executed with CPUs paused must not acquire adaptive
968  * (or low-level spin) locks.  Also, such code must not block,
969  * since the thread that is supposed to initiate the wakeup may
970  * never run.
971  *
972  * With a few exceptions, the restrictions on code executed with CPUs
973  * paused match those for code executed at high-level interrupt
974  * context.
975  */
976 void
977 pause_cpus(cpu_t *off_cp)
978 {
979 	processorid_t	cpu_id;
980 	int		i;
981 	struct _cpu_pause_info	*cpi = &cpu_pause_info;
982 
983 	ASSERT(MUTEX_HELD(&cpu_lock));
984 	ASSERT(cpi->cp_paused == NULL);
985 	cpi->cp_count = 0;
986 	cpi->cp_go = 0;
987 	for (i = 0; i < NCPU; i++)
988 		safe_list[i] = PAUSE_IDLE;
989 	kpreempt_disable();
990 
991 	/*
992 	 * If running on the cpu that is going offline, get off it.
993 	 * This is so that it won't be necessary to rechoose a CPU
994 	 * when done.
995 	 */
996 	if (CPU == off_cp)
997 		cpu_id = off_cp->cpu_next_part->cpu_id;
998 	else
999 		cpu_id = CPU->cpu_id;
1000 	affinity_set(cpu_id);
1001 
1002 	/*
1003 	 * Start the pause threads and record how many were started
1004 	 */
1005 	cpi->cp_count = cpu_pause_start(cpu_id);
1006 
1007 	/*
1008 	 * Now wait for all CPUs to be running the pause thread.
1009 	 */
1010 	while (cpi->cp_count > 0) {
1011 		/*
1012 		 * Spin reading the count without grabbing the disp
1013 		 * lock to make sure we don't prevent the pause
1014 		 * threads from getting the lock.
1015 		 */
1016 		while (sema_held(&cpi->cp_sem))
1017 			;
1018 		if (sema_tryp(&cpi->cp_sem))
1019 			--cpi->cp_count;
1020 	}
1021 	cpi->cp_go = 1;			/* all have reached cpu_pause */
1022 
1023 	/*
1024 	 * Now wait for all CPUs to spl. (Transition from PAUSE_READY
1025 	 * to PAUSE_WAIT.)
1026 	 */
1027 	for (i = 0; i < NCPU; i++) {
1028 		while (safe_list[i] != PAUSE_WAIT)
1029 			;
1030 	}
1031 	cpi->cp_spl = splhigh();	/* block dispatcher on this CPU */
1032 	cpi->cp_paused = curthread;
1033 }
1034 
1035 /*
1036  * Check whether the current thread has CPUs paused
1037  */
1038 int
1039 cpus_paused(void)
1040 {
1041 	if (cpu_pause_info.cp_paused != NULL) {
1042 		ASSERT(cpu_pause_info.cp_paused == curthread);
1043 		return (1);
1044 	}
1045 	return (0);
1046 }
1047 
1048 static cpu_t *
1049 cpu_get_all(processorid_t cpun)
1050 {
1051 	ASSERT(MUTEX_HELD(&cpu_lock));
1052 
1053 	if (cpun >= NCPU || cpun < 0 || !CPU_IN_SET(cpu_available, cpun))
1054 		return (NULL);
1055 	return (cpu[cpun]);
1056 }
1057 
1058 /*
1059  * Check whether cpun is a valid processor id and whether it should be
1060  * visible from the current zone. If it is, return a pointer to the
1061  * associated CPU structure.
1062  */
1063 cpu_t *
1064 cpu_get(processorid_t cpun)
1065 {
1066 	cpu_t *c;
1067 
1068 	ASSERT(MUTEX_HELD(&cpu_lock));
1069 	c = cpu_get_all(cpun);
1070 	if (c != NULL && !INGLOBALZONE(curproc) && pool_pset_enabled() &&
1071 	    zone_pset_get(curproc->p_zone) != cpupart_query_cpu(c))
1072 		return (NULL);
1073 	return (c);
1074 }
1075 
1076 /*
1077  * The following functions should be used to check CPU states in the kernel.
1078  * They should be invoked with cpu_lock held.  Kernel subsystems interested
1079  * in CPU states should *not* use cpu_get_state() and various P_ONLINE/etc
1080  * states.  Those are for user-land (and system call) use only.
1081  */
1082 
1083 /*
1084  * Determine whether the CPU is online and handling interrupts.
1085  */
1086 int
1087 cpu_is_online(cpu_t *cpu)
1088 {
1089 	ASSERT(MUTEX_HELD(&cpu_lock));
1090 	return (cpu_flagged_online(cpu->cpu_flags));
1091 }
1092 
1093 /*
1094  * Determine whether the CPU is offline (this includes spare and faulted).
1095  */
1096 int
1097 cpu_is_offline(cpu_t *cpu)
1098 {
1099 	ASSERT(MUTEX_HELD(&cpu_lock));
1100 	return (cpu_flagged_offline(cpu->cpu_flags));
1101 }
1102 
1103 /*
1104  * Determine whether the CPU is powered off.
1105  */
1106 int
1107 cpu_is_poweredoff(cpu_t *cpu)
1108 {
1109 	ASSERT(MUTEX_HELD(&cpu_lock));
1110 	return (cpu_flagged_poweredoff(cpu->cpu_flags));
1111 }
1112 
1113 /*
1114  * Determine whether the CPU is handling interrupts.
1115  */
1116 int
1117 cpu_is_nointr(cpu_t *cpu)
1118 {
1119 	ASSERT(MUTEX_HELD(&cpu_lock));
1120 	return (cpu_flagged_nointr(cpu->cpu_flags));
1121 }
1122 
1123 /*
1124  * Determine whether the CPU is active (scheduling threads).
1125  */
1126 int
1127 cpu_is_active(cpu_t *cpu)
1128 {
1129 	ASSERT(MUTEX_HELD(&cpu_lock));
1130 	return (cpu_flagged_active(cpu->cpu_flags));
1131 }
1132 
1133 /*
1134  * Same as above, but these require cpu_flags instead of cpu_t pointers.
1135  */
1136 int
1137 cpu_flagged_online(cpu_flag_t cpu_flags)
1138 {
1139 	return (cpu_flagged_active(cpu_flags) &&
1140 	    (cpu_flags & CPU_ENABLE));
1141 }
1142 
1143 int
1144 cpu_flagged_offline(cpu_flag_t cpu_flags)
1145 {
1146 	return (((cpu_flags & CPU_POWEROFF) == 0) &&
1147 	    ((cpu_flags & (CPU_READY | CPU_OFFLINE)) != CPU_READY));
1148 }
1149 
1150 int
1151 cpu_flagged_poweredoff(cpu_flag_t cpu_flags)
1152 {
1153 	return ((cpu_flags & CPU_POWEROFF) == CPU_POWEROFF);
1154 }
1155 
1156 int
1157 cpu_flagged_nointr(cpu_flag_t cpu_flags)
1158 {
1159 	return (cpu_flagged_active(cpu_flags) &&
1160 	    (cpu_flags & CPU_ENABLE) == 0);
1161 }
1162 
1163 int
1164 cpu_flagged_active(cpu_flag_t cpu_flags)
1165 {
1166 	return (((cpu_flags & (CPU_POWEROFF | CPU_FAULTED | CPU_SPARE)) == 0) &&
1167 	    ((cpu_flags & (CPU_READY | CPU_OFFLINE)) == CPU_READY));
1168 }
1169 
1170 /*
1171  * Bring the indicated CPU online.
1172  */
1173 int
1174 cpu_online(cpu_t *cp)
1175 {
1176 	int	error = 0;
1177 
1178 	/*
1179 	 * Handle on-line request.
1180 	 *	This code must put the new CPU on the active list before
1181 	 *	starting it because it will not be paused, and will start
1182 	 * 	using the active list immediately.  The real start occurs
1183 	 *	when the CPU_QUIESCED flag is turned off.
1184 	 */
1185 
1186 	ASSERT(MUTEX_HELD(&cpu_lock));
1187 
1188 	/*
1189 	 * Put all the cpus into a known safe place.
1190 	 * No mutexes can be entered while CPUs are paused.
1191 	 */
1192 	error = mp_cpu_start(cp);	/* arch-dep hook */
1193 	if (error == 0) {
1194 		pg_cpupart_in(cp, cp->cpu_part);
1195 		pause_cpus(NULL);
1196 		cpu_add_active_internal(cp);
1197 		if (cp->cpu_flags & CPU_FAULTED) {
1198 			cp->cpu_flags &= ~CPU_FAULTED;
1199 			mp_cpu_faulted_exit(cp);
1200 		}
1201 		cp->cpu_flags &= ~(CPU_QUIESCED | CPU_OFFLINE | CPU_FROZEN |
1202 		    CPU_SPARE);
1203 		start_cpus();
1204 		cpu_stats_kstat_create(cp);
1205 		cpu_create_intrstat(cp);
1206 		lgrp_kstat_create(cp);
1207 		cpu_state_change_notify(cp->cpu_id, CPU_ON);
1208 		cpu_intr_enable(cp);	/* arch-dep hook */
1209 		cpu_set_state(cp);
1210 		cyclic_online(cp);
1211 		poke_cpu(cp->cpu_id);
1212 	}
1213 
1214 	return (error);
1215 }
1216 
1217 /*
1218  * Take the indicated CPU offline.
1219  */
1220 int
1221 cpu_offline(cpu_t *cp, int flags)
1222 {
1223 	cpupart_t *pp;
1224 	int	error = 0;
1225 	cpu_t	*ncp;
1226 	int	intr_enable;
1227 	int	cyclic_off = 0;
1228 	int	loop_count;
1229 	int	no_quiesce = 0;
1230 	int	(*bound_func)(struct cpu *, int);
1231 	kthread_t *t;
1232 	lpl_t	*cpu_lpl;
1233 	proc_t	*p;
1234 	int	lgrp_diff_lpl;
1235 	boolean_t unbind_all_threads = (flags & CPU_FORCED) != 0;
1236 
1237 	ASSERT(MUTEX_HELD(&cpu_lock));
1238 
1239 	/*
1240 	 * If we're going from faulted or spare to offline, just
1241 	 * clear these flags and update CPU state.
1242 	 */
1243 	if (cp->cpu_flags & (CPU_FAULTED | CPU_SPARE)) {
1244 		if (cp->cpu_flags & CPU_FAULTED) {
1245 			cp->cpu_flags &= ~CPU_FAULTED;
1246 			mp_cpu_faulted_exit(cp);
1247 		}
1248 		cp->cpu_flags &= ~CPU_SPARE;
1249 		cpu_set_state(cp);
1250 		return (0);
1251 	}
1252 
1253 	/*
1254 	 * Handle off-line request.
1255 	 */
1256 	pp = cp->cpu_part;
1257 	/*
1258 	 * Don't offline last online CPU in partition
1259 	 */
1260 	if (ncpus_online <= 1 || pp->cp_ncpus <= 1 || cpu_intr_count(cp) < 2)
1261 		return (EBUSY);
1262 	/*
1263 	 * Unbind all soft-bound threads bound to our CPU and hard bound threads
1264 	 * if we were asked to.
1265 	 */
1266 	error = cpu_unbind(cp->cpu_id, unbind_all_threads);
1267 	if (error != 0)
1268 		return (error);
1269 	/*
1270 	 * We shouldn't be bound to this CPU ourselves.
1271 	 */
1272 	if (curthread->t_bound_cpu == cp)
1273 		return (EBUSY);
1274 
1275 	/*
1276 	 * Tell interested parties that this CPU is going offline.
1277 	 */
1278 	cpu_state_change_notify(cp->cpu_id, CPU_OFF);
1279 
1280 	/*
1281 	 * Tell the PG subsystem that the CPU is leaving the partition
1282 	 */
1283 	pg_cpupart_out(cp, pp);
1284 
1285 	/*
1286 	 * Take the CPU out of interrupt participation so we won't find
1287 	 * bound kernel threads.  If the architecture cannot completely
1288 	 * shut off interrupts on the CPU, don't quiesce it, but don't
1289 	 * run anything but interrupt thread... this is indicated by
1290 	 * the CPU_OFFLINE flag being on but the CPU_QUIESCE flag being
1291 	 * off.
1292 	 */
1293 	intr_enable = cp->cpu_flags & CPU_ENABLE;
1294 	if (intr_enable)
1295 		no_quiesce = cpu_intr_disable(cp);
1296 
1297 	/*
1298 	 * Record that we are aiming to offline this cpu.  This acts as
1299 	 * a barrier to further weak binding requests in thread_nomigrate
1300 	 * and also causes cpu_choose, disp_lowpri_cpu and setfrontdq to
1301 	 * lean away from this cpu.  Further strong bindings are already
1302 	 * avoided since we hold cpu_lock.  Since threads that are set
1303 	 * runnable around now and others coming off the target cpu are
1304 	 * directed away from the target, existing strong and weak bindings
1305 	 * (especially the latter) to the target cpu stand maximum chance of
1306 	 * being able to unbind during the short delay loop below (if other
1307 	 * unbound threads compete they may not see cpu in time to unbind
1308 	 * even if they would do so immediately.
1309 	 */
1310 	cpu_inmotion = cp;
1311 	membar_enter();
1312 
1313 	/*
1314 	 * Check for kernel threads (strong or weak) bound to that CPU.
1315 	 * Strongly bound threads may not unbind, and we'll have to return
1316 	 * EBUSY.  Weakly bound threads should always disappear - we've
1317 	 * stopped more weak binding with cpu_inmotion and existing
1318 	 * bindings will drain imminently (they may not block).  Nonetheless
1319 	 * we will wait for a fixed period for all bound threads to disappear.
1320 	 * Inactive interrupt threads are OK (they'll be in TS_FREE
1321 	 * state).  If test finds some bound threads, wait a few ticks
1322 	 * to give short-lived threads (such as interrupts) chance to
1323 	 * complete.  Note that if no_quiesce is set, i.e. this cpu
1324 	 * is required to service interrupts, then we take the route
1325 	 * that permits interrupt threads to be active (or bypassed).
1326 	 */
1327 	bound_func = no_quiesce ? disp_bound_threads : disp_bound_anythreads;
1328 
1329 again:	for (loop_count = 0; (*bound_func)(cp, 0); loop_count++) {
1330 		if (loop_count >= 5) {
1331 			error = EBUSY;	/* some threads still bound */
1332 			break;
1333 		}
1334 
1335 		/*
1336 		 * If some threads were assigned, give them
1337 		 * a chance to complete or move.
1338 		 *
1339 		 * This assumes that the clock_thread is not bound
1340 		 * to any CPU, because the clock_thread is needed to
1341 		 * do the delay(hz/100).
1342 		 *
1343 		 * Note: we still hold the cpu_lock while waiting for
1344 		 * the next clock tick.  This is OK since it isn't
1345 		 * needed for anything else except processor_bind(2),
1346 		 * and system initialization.  If we drop the lock,
1347 		 * we would risk another p_online disabling the last
1348 		 * processor.
1349 		 */
1350 		delay(hz/100);
1351 	}
1352 
1353 	if (error == 0 && cyclic_off == 0) {
1354 		if (!cyclic_offline(cp)) {
1355 			/*
1356 			 * We must have bound cyclics...
1357 			 */
1358 			error = EBUSY;
1359 			goto out;
1360 		}
1361 		cyclic_off = 1;
1362 	}
1363 
1364 	/*
1365 	 * Call mp_cpu_stop() to perform any special operations
1366 	 * needed for this machine architecture to offline a CPU.
1367 	 */
1368 	if (error == 0)
1369 		error = mp_cpu_stop(cp);	/* arch-dep hook */
1370 
1371 	/*
1372 	 * If that all worked, take the CPU offline and decrement
1373 	 * ncpus_online.
1374 	 */
1375 	if (error == 0) {
1376 		/*
1377 		 * Put all the cpus into a known safe place.
1378 		 * No mutexes can be entered while CPUs are paused.
1379 		 */
1380 		pause_cpus(cp);
1381 		/*
1382 		 * Repeat the operation, if necessary, to make sure that
1383 		 * all outstanding low-level interrupts run to completion
1384 		 * before we set the CPU_QUIESCED flag.  It's also possible
1385 		 * that a thread has weak bound to the cpu despite our raising
1386 		 * cpu_inmotion above since it may have loaded that
1387 		 * value before the barrier became visible (this would have
1388 		 * to be the thread that was on the target cpu at the time
1389 		 * we raised the barrier).
1390 		 */
1391 		if ((!no_quiesce && cp->cpu_intr_actv != 0) ||
1392 		    (*bound_func)(cp, 1)) {
1393 			start_cpus();
1394 			(void) mp_cpu_start(cp);
1395 			goto again;
1396 		}
1397 		ncp = cp->cpu_next_part;
1398 		cpu_lpl = cp->cpu_lpl;
1399 		ASSERT(cpu_lpl != NULL);
1400 
1401 		/*
1402 		 * Remove the CPU from the list of active CPUs.
1403 		 */
1404 		cpu_remove_active(cp);
1405 
1406 		/*
1407 		 * Walk the active process list and look for threads
1408 		 * whose home lgroup needs to be updated, or
1409 		 * the last CPU they run on is the one being offlined now.
1410 		 */
1411 
1412 		ASSERT(curthread->t_cpu != cp);
1413 		for (p = practive; p != NULL; p = p->p_next) {
1414 
1415 			t = p->p_tlist;
1416 
1417 			if (t == NULL)
1418 				continue;
1419 
1420 			lgrp_diff_lpl = 0;
1421 
1422 			do {
1423 				ASSERT(t->t_lpl != NULL);
1424 				/*
1425 				 * Taking last CPU in lpl offline
1426 				 * Rehome thread if it is in this lpl
1427 				 * Otherwise, update the count of how many
1428 				 * threads are in this CPU's lgroup but have
1429 				 * a different lpl.
1430 				 */
1431 
1432 				if (cpu_lpl->lpl_ncpu == 0) {
1433 					if (t->t_lpl == cpu_lpl)
1434 						lgrp_move_thread(t,
1435 						    lgrp_choose(t,
1436 						    t->t_cpupart), 0);
1437 					else if (t->t_lpl->lpl_lgrpid ==
1438 					    cpu_lpl->lpl_lgrpid)
1439 						lgrp_diff_lpl++;
1440 				}
1441 				ASSERT(t->t_lpl->lpl_ncpu > 0);
1442 
1443 				/*
1444 				 * Update CPU last ran on if it was this CPU
1445 				 */
1446 				if (t->t_cpu == cp && t->t_bound_cpu != cp)
1447 					t->t_cpu = disp_lowpri_cpu(ncp,
1448 					    t->t_lpl, t->t_pri, NULL);
1449 				ASSERT(t->t_cpu != cp || t->t_bound_cpu == cp ||
1450 				    t->t_weakbound_cpu == cp);
1451 
1452 				t = t->t_forw;
1453 			} while (t != p->p_tlist);
1454 
1455 			/*
1456 			 * Didn't find any threads in the same lgroup as this
1457 			 * CPU with a different lpl, so remove the lgroup from
1458 			 * the process lgroup bitmask.
1459 			 */
1460 
1461 			if (lgrp_diff_lpl == 0)
1462 				klgrpset_del(p->p_lgrpset, cpu_lpl->lpl_lgrpid);
1463 		}
1464 
1465 		/*
1466 		 * Walk thread list looking for threads that need to be
1467 		 * rehomed, since there are some threads that are not in
1468 		 * their process's p_tlist.
1469 		 */
1470 
1471 		t = curthread;
1472 		do {
1473 			ASSERT(t != NULL && t->t_lpl != NULL);
1474 
1475 			/*
1476 			 * Rehome threads with same lpl as this CPU when this
1477 			 * is the last CPU in the lpl.
1478 			 */
1479 
1480 			if ((cpu_lpl->lpl_ncpu == 0) && (t->t_lpl == cpu_lpl))
1481 				lgrp_move_thread(t,
1482 				    lgrp_choose(t, t->t_cpupart), 1);
1483 
1484 			ASSERT(t->t_lpl->lpl_ncpu > 0);
1485 
1486 			/*
1487 			 * Update CPU last ran on if it was this CPU
1488 			 */
1489 
1490 			if (t->t_cpu == cp && t->t_bound_cpu != cp) {
1491 				t->t_cpu = disp_lowpri_cpu(ncp,
1492 				    t->t_lpl, t->t_pri, NULL);
1493 			}
1494 			ASSERT(t->t_cpu != cp || t->t_bound_cpu == cp ||
1495 			    t->t_weakbound_cpu == cp);
1496 			t = t->t_next;
1497 
1498 		} while (t != curthread);
1499 		ASSERT((cp->cpu_flags & (CPU_FAULTED | CPU_SPARE)) == 0);
1500 		cp->cpu_flags |= CPU_OFFLINE;
1501 		disp_cpu_inactive(cp);
1502 		if (!no_quiesce)
1503 			cp->cpu_flags |= CPU_QUIESCED;
1504 		ncpus_online--;
1505 		cpu_set_state(cp);
1506 		cpu_inmotion = NULL;
1507 		start_cpus();
1508 		cpu_stats_kstat_destroy(cp);
1509 		cpu_delete_intrstat(cp);
1510 		lgrp_kstat_destroy(cp);
1511 	}
1512 
1513 out:
1514 	cpu_inmotion = NULL;
1515 
1516 	/*
1517 	 * If we failed, re-enable interrupts.
1518 	 * Do this even if cpu_intr_disable returned an error, because
1519 	 * it may have partially disabled interrupts.
1520 	 */
1521 	if (error && intr_enable)
1522 		cpu_intr_enable(cp);
1523 
1524 	/*
1525 	 * If we failed, but managed to offline the cyclic subsystem on this
1526 	 * CPU, bring it back online.
1527 	 */
1528 	if (error && cyclic_off)
1529 		cyclic_online(cp);
1530 
1531 	/*
1532 	 * If we failed, tell the PG subsystem that the CPU is back
1533 	 */
1534 	pg_cpupart_in(cp, pp);
1535 
1536 	/*
1537 	 * If we failed, we need to notify everyone that this CPU is back on.
1538 	 */
1539 	if (error != 0)
1540 		cpu_state_change_notify(cp->cpu_id, CPU_ON);
1541 
1542 	return (error);
1543 }
1544 
1545 /*
1546  * Mark the indicated CPU as faulted, taking it offline.
1547  */
1548 int
1549 cpu_faulted(cpu_t *cp, int flags)
1550 {
1551 	int	error = 0;
1552 
1553 	ASSERT(MUTEX_HELD(&cpu_lock));
1554 	ASSERT(!cpu_is_poweredoff(cp));
1555 
1556 	if (cpu_is_offline(cp)) {
1557 		cp->cpu_flags &= ~CPU_SPARE;
1558 		cp->cpu_flags |= CPU_FAULTED;
1559 		mp_cpu_faulted_enter(cp);
1560 		cpu_set_state(cp);
1561 		return (0);
1562 	}
1563 
1564 	if ((error = cpu_offline(cp, flags)) == 0) {
1565 		cp->cpu_flags |= CPU_FAULTED;
1566 		mp_cpu_faulted_enter(cp);
1567 		cpu_set_state(cp);
1568 	}
1569 
1570 	return (error);
1571 }
1572 
1573 /*
1574  * Mark the indicated CPU as a spare, taking it offline.
1575  */
1576 int
1577 cpu_spare(cpu_t *cp, int flags)
1578 {
1579 	int	error = 0;
1580 
1581 	ASSERT(MUTEX_HELD(&cpu_lock));
1582 	ASSERT(!cpu_is_poweredoff(cp));
1583 
1584 	if (cpu_is_offline(cp)) {
1585 		if (cp->cpu_flags & CPU_FAULTED) {
1586 			cp->cpu_flags &= ~CPU_FAULTED;
1587 			mp_cpu_faulted_exit(cp);
1588 		}
1589 		cp->cpu_flags |= CPU_SPARE;
1590 		cpu_set_state(cp);
1591 		return (0);
1592 	}
1593 
1594 	if ((error = cpu_offline(cp, flags)) == 0) {
1595 		cp->cpu_flags |= CPU_SPARE;
1596 		cpu_set_state(cp);
1597 	}
1598 
1599 	return (error);
1600 }
1601 
1602 /*
1603  * Take the indicated CPU from poweroff to offline.
1604  */
1605 int
1606 cpu_poweron(cpu_t *cp)
1607 {
1608 	int	error = ENOTSUP;
1609 
1610 	ASSERT(MUTEX_HELD(&cpu_lock));
1611 	ASSERT(cpu_is_poweredoff(cp));
1612 
1613 	error = mp_cpu_poweron(cp);	/* arch-dep hook */
1614 	if (error == 0)
1615 		cpu_set_state(cp);
1616 
1617 	return (error);
1618 }
1619 
1620 /*
1621  * Take the indicated CPU from any inactive state to powered off.
1622  */
1623 int
1624 cpu_poweroff(cpu_t *cp)
1625 {
1626 	int	error = ENOTSUP;
1627 
1628 	ASSERT(MUTEX_HELD(&cpu_lock));
1629 	ASSERT(cpu_is_offline(cp));
1630 
1631 	if (!(cp->cpu_flags & CPU_QUIESCED))
1632 		return (EBUSY);		/* not completely idle */
1633 
1634 	error = mp_cpu_poweroff(cp);	/* arch-dep hook */
1635 	if (error == 0)
1636 		cpu_set_state(cp);
1637 
1638 	return (error);
1639 }
1640 
1641 /*
1642  * Initialize the CPU lists for the first CPU.
1643  */
1644 void
1645 cpu_list_init(cpu_t *cp)
1646 {
1647 	cp->cpu_next = cp;
1648 	cp->cpu_prev = cp;
1649 	cpu_list = cp;
1650 	clock_cpu_list = cp;
1651 
1652 	cp->cpu_next_onln = cp;
1653 	cp->cpu_prev_onln = cp;
1654 	cpu_active = cp;
1655 
1656 	cp->cpu_seqid = 0;
1657 	CPUSET_ADD(cpu_seqid_inuse, 0);
1658 	cp->cpu_cache_offset = KMEM_CACHE_SIZE(cp->cpu_seqid);
1659 	cp_default.cp_mach = &cp_default_mach;
1660 	cp_default.cp_cpulist = cp;
1661 	cp_default.cp_ncpus = 1;
1662 	cp->cpu_next_part = cp;
1663 	cp->cpu_prev_part = cp;
1664 	cp->cpu_part = &cp_default;
1665 
1666 	CPUSET_ADD(cpu_available, cp->cpu_id);
1667 }
1668 
1669 /*
1670  * Insert a CPU into the list of available CPUs.
1671  */
1672 void
1673 cpu_add_unit(cpu_t *cp)
1674 {
1675 	int seqid;
1676 
1677 	ASSERT(MUTEX_HELD(&cpu_lock));
1678 	ASSERT(cpu_list != NULL);	/* list started in cpu_list_init */
1679 
1680 	lgrp_config(LGRP_CONFIG_CPU_ADD, (uintptr_t)cp, 0);
1681 
1682 	/*
1683 	 * Note: most users of the cpu_list will grab the
1684 	 * cpu_lock to insure that it isn't modified.  However,
1685 	 * certain users can't or won't do that.  To allow this
1686 	 * we pause the other cpus.  Users who walk the list
1687 	 * without cpu_lock, must disable kernel preemption
1688 	 * to insure that the list isn't modified underneath
1689 	 * them.  Also, any cached pointers to cpu structures
1690 	 * must be revalidated by checking to see if the
1691 	 * cpu_next pointer points to itself.  This check must
1692 	 * be done with the cpu_lock held or kernel preemption
1693 	 * disabled.  This check relies upon the fact that
1694 	 * old cpu structures are not free'ed or cleared after
1695 	 * then are removed from the cpu_list.
1696 	 *
1697 	 * Note that the clock code walks the cpu list dereferencing
1698 	 * the cpu_part pointer, so we need to initialize it before
1699 	 * adding the cpu to the list.
1700 	 */
1701 	cp->cpu_part = &cp_default;
1702 	(void) pause_cpus(NULL);
1703 	cp->cpu_next = cpu_list;
1704 	cp->cpu_prev = cpu_list->cpu_prev;
1705 	cpu_list->cpu_prev->cpu_next = cp;
1706 	cpu_list->cpu_prev = cp;
1707 	start_cpus();
1708 
1709 	for (seqid = 0; CPU_IN_SET(cpu_seqid_inuse, seqid); seqid++)
1710 		continue;
1711 	CPUSET_ADD(cpu_seqid_inuse, seqid);
1712 	cp->cpu_seqid = seqid;
1713 	ASSERT(ncpus < max_ncpus);
1714 	ncpus++;
1715 	cp->cpu_cache_offset = KMEM_CACHE_SIZE(cp->cpu_seqid);
1716 	cpu[cp->cpu_id] = cp;
1717 	CPUSET_ADD(cpu_available, cp->cpu_id);
1718 
1719 	/*
1720 	 * allocate a pause thread for this CPU.
1721 	 */
1722 	cpu_pause_alloc(cp);
1723 
1724 	/*
1725 	 * So that new CPUs won't have NULL prev_onln and next_onln pointers,
1726 	 * link them into a list of just that CPU.
1727 	 * This is so that disp_lowpri_cpu will work for thread_create in
1728 	 * pause_cpus() when called from the startup thread in a new CPU.
1729 	 */
1730 	cp->cpu_next_onln = cp;
1731 	cp->cpu_prev_onln = cp;
1732 	cpu_info_kstat_create(cp);
1733 	cp->cpu_next_part = cp;
1734 	cp->cpu_prev_part = cp;
1735 
1736 	init_cpu_mstate(cp, CMS_SYSTEM);
1737 
1738 	pool_pset_mod = gethrtime();
1739 }
1740 
1741 /*
1742  * Do the opposite of cpu_add_unit().
1743  */
1744 void
1745 cpu_del_unit(int cpuid)
1746 {
1747 	struct cpu	*cp, *cpnext;
1748 
1749 	ASSERT(MUTEX_HELD(&cpu_lock));
1750 	cp = cpu[cpuid];
1751 	ASSERT(cp != NULL);
1752 
1753 	ASSERT(cp->cpu_next_onln == cp);
1754 	ASSERT(cp->cpu_prev_onln == cp);
1755 	ASSERT(cp->cpu_next_part == cp);
1756 	ASSERT(cp->cpu_prev_part == cp);
1757 
1758 	/*
1759 	 * Tear down the CPU's physical ID cache, and update any
1760 	 * processor groups
1761 	 */
1762 	pg_cpu_fini(cp);
1763 	pghw_physid_destroy(cp);
1764 
1765 	/*
1766 	 * Destroy kstat stuff.
1767 	 */
1768 	cpu_info_kstat_destroy(cp);
1769 	term_cpu_mstate(cp);
1770 	/*
1771 	 * Free up pause thread.
1772 	 */
1773 	cpu_pause_free(cp);
1774 	CPUSET_DEL(cpu_available, cp->cpu_id);
1775 	cpu[cp->cpu_id] = NULL;
1776 	/*
1777 	 * The clock thread and mutex_vector_enter cannot hold the
1778 	 * cpu_lock while traversing the cpu list, therefore we pause
1779 	 * all other threads by pausing the other cpus. These, and any
1780 	 * other routines holding cpu pointers while possibly sleeping
1781 	 * must be sure to call kpreempt_disable before processing the
1782 	 * list and be sure to check that the cpu has not been deleted
1783 	 * after any sleeps (check cp->cpu_next != NULL). We guarantee
1784 	 * to keep the deleted cpu structure around.
1785 	 *
1786 	 * Note that this MUST be done AFTER cpu_available
1787 	 * has been updated so that we don't waste time
1788 	 * trying to pause the cpu we're trying to delete.
1789 	 */
1790 	(void) pause_cpus(NULL);
1791 
1792 	cpnext = cp->cpu_next;
1793 	cp->cpu_prev->cpu_next = cp->cpu_next;
1794 	cp->cpu_next->cpu_prev = cp->cpu_prev;
1795 	if (cp == cpu_list)
1796 		cpu_list = cpnext;
1797 
1798 	/*
1799 	 * Signals that the cpu has been deleted (see above).
1800 	 */
1801 	cp->cpu_next = NULL;
1802 	cp->cpu_prev = NULL;
1803 
1804 	start_cpus();
1805 
1806 	CPUSET_DEL(cpu_seqid_inuse, cp->cpu_seqid);
1807 	ncpus--;
1808 	lgrp_config(LGRP_CONFIG_CPU_DEL, (uintptr_t)cp, 0);
1809 
1810 	pool_pset_mod = gethrtime();
1811 }
1812 
1813 /*
1814  * Add a CPU to the list of active CPUs.
1815  *	This routine must not get any locks, because other CPUs are paused.
1816  */
1817 static void
1818 cpu_add_active_internal(cpu_t *cp)
1819 {
1820 	cpupart_t	*pp = cp->cpu_part;
1821 
1822 	ASSERT(MUTEX_HELD(&cpu_lock));
1823 	ASSERT(cpu_list != NULL);	/* list started in cpu_list_init */
1824 
1825 	ncpus_online++;
1826 	cpu_set_state(cp);
1827 	cp->cpu_next_onln = cpu_active;
1828 	cp->cpu_prev_onln = cpu_active->cpu_prev_onln;
1829 	cpu_active->cpu_prev_onln->cpu_next_onln = cp;
1830 	cpu_active->cpu_prev_onln = cp;
1831 
1832 	if (pp->cp_cpulist) {
1833 		cp->cpu_next_part = pp->cp_cpulist;
1834 		cp->cpu_prev_part = pp->cp_cpulist->cpu_prev_part;
1835 		pp->cp_cpulist->cpu_prev_part->cpu_next_part = cp;
1836 		pp->cp_cpulist->cpu_prev_part = cp;
1837 	} else {
1838 		ASSERT(pp->cp_ncpus == 0);
1839 		pp->cp_cpulist = cp->cpu_next_part = cp->cpu_prev_part = cp;
1840 	}
1841 	pp->cp_ncpus++;
1842 	if (pp->cp_ncpus == 1) {
1843 		cp_numparts_nonempty++;
1844 		ASSERT(cp_numparts_nonempty != 0);
1845 	}
1846 
1847 	pg_cpu_active(cp);
1848 	lgrp_config(LGRP_CONFIG_CPU_ONLINE, (uintptr_t)cp, 0);
1849 
1850 	bzero(&cp->cpu_loadavg, sizeof (cp->cpu_loadavg));
1851 }
1852 
1853 /*
1854  * Add a CPU to the list of active CPUs.
1855  *	This is called from machine-dependent layers when a new CPU is started.
1856  */
1857 void
1858 cpu_add_active(cpu_t *cp)
1859 {
1860 	pg_cpupart_in(cp, cp->cpu_part);
1861 
1862 	pause_cpus(NULL);
1863 	cpu_add_active_internal(cp);
1864 	start_cpus();
1865 
1866 	cpu_stats_kstat_create(cp);
1867 	cpu_create_intrstat(cp);
1868 	lgrp_kstat_create(cp);
1869 	cpu_state_change_notify(cp->cpu_id, CPU_INIT);
1870 }
1871 
1872 
1873 /*
1874  * Remove a CPU from the list of active CPUs.
1875  *	This routine must not get any locks, because other CPUs are paused.
1876  */
1877 /* ARGSUSED */
1878 static void
1879 cpu_remove_active(cpu_t *cp)
1880 {
1881 	cpupart_t	*pp = cp->cpu_part;
1882 
1883 	ASSERT(MUTEX_HELD(&cpu_lock));
1884 	ASSERT(cp->cpu_next_onln != cp);	/* not the last one */
1885 	ASSERT(cp->cpu_prev_onln != cp);	/* not the last one */
1886 
1887 	pg_cpu_inactive(cp);
1888 
1889 	lgrp_config(LGRP_CONFIG_CPU_OFFLINE, (uintptr_t)cp, 0);
1890 
1891 	if (cp == clock_cpu_list)
1892 		clock_cpu_list = cp->cpu_next_onln;
1893 
1894 	cp->cpu_prev_onln->cpu_next_onln = cp->cpu_next_onln;
1895 	cp->cpu_next_onln->cpu_prev_onln = cp->cpu_prev_onln;
1896 	if (cpu_active == cp) {
1897 		cpu_active = cp->cpu_next_onln;
1898 	}
1899 	cp->cpu_next_onln = cp;
1900 	cp->cpu_prev_onln = cp;
1901 
1902 	cp->cpu_prev_part->cpu_next_part = cp->cpu_next_part;
1903 	cp->cpu_next_part->cpu_prev_part = cp->cpu_prev_part;
1904 	if (pp->cp_cpulist == cp) {
1905 		pp->cp_cpulist = cp->cpu_next_part;
1906 		ASSERT(pp->cp_cpulist != cp);
1907 	}
1908 	cp->cpu_next_part = cp;
1909 	cp->cpu_prev_part = cp;
1910 	pp->cp_ncpus--;
1911 	if (pp->cp_ncpus == 0) {
1912 		cp_numparts_nonempty--;
1913 		ASSERT(cp_numparts_nonempty != 0);
1914 	}
1915 }
1916 
1917 /*
1918  * Routine used to setup a newly inserted CPU in preparation for starting
1919  * it running code.
1920  */
1921 int
1922 cpu_configure(int cpuid)
1923 {
1924 	int retval = 0;
1925 
1926 	ASSERT(MUTEX_HELD(&cpu_lock));
1927 
1928 	/*
1929 	 * Some structures are statically allocated based upon
1930 	 * the maximum number of cpus the system supports.  Do not
1931 	 * try to add anything beyond this limit.
1932 	 */
1933 	if (cpuid < 0 || cpuid >= NCPU) {
1934 		return (EINVAL);
1935 	}
1936 
1937 	if ((cpu[cpuid] != NULL) && (cpu[cpuid]->cpu_flags != 0)) {
1938 		return (EALREADY);
1939 	}
1940 
1941 	if ((retval = mp_cpu_configure(cpuid)) != 0) {
1942 		return (retval);
1943 	}
1944 
1945 	cpu[cpuid]->cpu_flags = CPU_QUIESCED | CPU_OFFLINE | CPU_POWEROFF;
1946 	cpu_set_state(cpu[cpuid]);
1947 	retval = cpu_state_change_hooks(cpuid, CPU_CONFIG, CPU_UNCONFIG);
1948 	if (retval != 0)
1949 		(void) mp_cpu_unconfigure(cpuid);
1950 
1951 	return (retval);
1952 }
1953 
1954 /*
1955  * Routine used to cleanup a CPU that has been powered off.  This will
1956  * destroy all per-cpu information related to this cpu.
1957  */
1958 int
1959 cpu_unconfigure(int cpuid)
1960 {
1961 	int error;
1962 
1963 	ASSERT(MUTEX_HELD(&cpu_lock));
1964 
1965 	if (cpu[cpuid] == NULL) {
1966 		return (ENODEV);
1967 	}
1968 
1969 	if (cpu[cpuid]->cpu_flags == 0) {
1970 		return (EALREADY);
1971 	}
1972 
1973 	if ((cpu[cpuid]->cpu_flags & CPU_POWEROFF) == 0) {
1974 		return (EBUSY);
1975 	}
1976 
1977 	if (cpu[cpuid]->cpu_props != NULL) {
1978 		(void) nvlist_free(cpu[cpuid]->cpu_props);
1979 		cpu[cpuid]->cpu_props = NULL;
1980 	}
1981 
1982 	error = cpu_state_change_hooks(cpuid, CPU_UNCONFIG, CPU_CONFIG);
1983 
1984 	if (error != 0)
1985 		return (error);
1986 
1987 	return (mp_cpu_unconfigure(cpuid));
1988 }
1989 
1990 /*
1991  * Routines for registering and de-registering cpu_setup callback functions.
1992  *
1993  * Caller's context
1994  *	These routines must not be called from a driver's attach(9E) or
1995  *	detach(9E) entry point.
1996  *
1997  * NOTE: CPU callbacks should not block. They are called with cpu_lock held.
1998  */
1999 
2000 /*
2001  * Ideally, these would be dynamically allocated and put into a linked
2002  * list; however that is not feasible because the registration routine
2003  * has to be available before the kmem allocator is working (in fact,
2004  * it is called by the kmem allocator init code).  In any case, there
2005  * are quite a few extra entries for future users.
2006  */
2007 #define	NCPU_SETUPS	20
2008 
2009 struct cpu_setup {
2010 	cpu_setup_func_t *func;
2011 	void *arg;
2012 } cpu_setups[NCPU_SETUPS];
2013 
2014 void
2015 register_cpu_setup_func(cpu_setup_func_t *func, void *arg)
2016 {
2017 	int i;
2018 
2019 	ASSERT(MUTEX_HELD(&cpu_lock));
2020 
2021 	for (i = 0; i < NCPU_SETUPS; i++)
2022 		if (cpu_setups[i].func == NULL)
2023 			break;
2024 	if (i >= NCPU_SETUPS)
2025 		cmn_err(CE_PANIC, "Ran out of cpu_setup callback entries");
2026 
2027 	cpu_setups[i].func = func;
2028 	cpu_setups[i].arg = arg;
2029 }
2030 
2031 void
2032 unregister_cpu_setup_func(cpu_setup_func_t *func, void *arg)
2033 {
2034 	int i;
2035 
2036 	ASSERT(MUTEX_HELD(&cpu_lock));
2037 
2038 	for (i = 0; i < NCPU_SETUPS; i++)
2039 		if ((cpu_setups[i].func == func) &&
2040 		    (cpu_setups[i].arg == arg))
2041 			break;
2042 	if (i >= NCPU_SETUPS)
2043 		cmn_err(CE_PANIC, "Could not find cpu_setup callback to "
2044 		    "deregister");
2045 
2046 	cpu_setups[i].func = NULL;
2047 	cpu_setups[i].arg = 0;
2048 }
2049 
2050 /*
2051  * Call any state change hooks for this CPU, ignore any errors.
2052  */
2053 void
2054 cpu_state_change_notify(int id, cpu_setup_t what)
2055 {
2056 	int i;
2057 
2058 	ASSERT(MUTEX_HELD(&cpu_lock));
2059 
2060 	for (i = 0; i < NCPU_SETUPS; i++) {
2061 		if (cpu_setups[i].func != NULL) {
2062 			cpu_setups[i].func(what, id, cpu_setups[i].arg);
2063 		}
2064 	}
2065 }
2066 
2067 /*
2068  * Call any state change hooks for this CPU, undo it if error found.
2069  */
2070 static int
2071 cpu_state_change_hooks(int id, cpu_setup_t what, cpu_setup_t undo)
2072 {
2073 	int i;
2074 	int retval = 0;
2075 
2076 	ASSERT(MUTEX_HELD(&cpu_lock));
2077 
2078 	for (i = 0; i < NCPU_SETUPS; i++) {
2079 		if (cpu_setups[i].func != NULL) {
2080 			retval = cpu_setups[i].func(what, id,
2081 			    cpu_setups[i].arg);
2082 			if (retval) {
2083 				for (i--; i >= 0; i--) {
2084 					if (cpu_setups[i].func != NULL)
2085 						cpu_setups[i].func(undo,
2086 						    id, cpu_setups[i].arg);
2087 				}
2088 				break;
2089 			}
2090 		}
2091 	}
2092 	return (retval);
2093 }
2094 
2095 /*
2096  * Export information about this CPU via the kstat mechanism.
2097  */
2098 static struct {
2099 	kstat_named_t ci_state;
2100 	kstat_named_t ci_state_begin;
2101 	kstat_named_t ci_cpu_type;
2102 	kstat_named_t ci_fpu_type;
2103 	kstat_named_t ci_clock_MHz;
2104 	kstat_named_t ci_chip_id;
2105 	kstat_named_t ci_implementation;
2106 	kstat_named_t ci_brandstr;
2107 	kstat_named_t ci_core_id;
2108 	kstat_named_t ci_curr_clock_Hz;
2109 	kstat_named_t ci_supp_freq_Hz;
2110 #if defined(__sparcv9)
2111 	kstat_named_t ci_device_ID;
2112 	kstat_named_t ci_cpu_fru;
2113 #endif
2114 #if defined(__x86)
2115 	kstat_named_t ci_vendorstr;
2116 	kstat_named_t ci_family;
2117 	kstat_named_t ci_model;
2118 	kstat_named_t ci_step;
2119 	kstat_named_t ci_clogid;
2120 	kstat_named_t ci_pkg_core_id;
2121 	kstat_named_t ci_ncpuperchip;
2122 	kstat_named_t ci_ncoreperchip;
2123 #endif
2124 } cpu_info_template = {
2125 	{ "state",			KSTAT_DATA_CHAR },
2126 	{ "state_begin",		KSTAT_DATA_LONG },
2127 	{ "cpu_type",			KSTAT_DATA_CHAR },
2128 	{ "fpu_type",			KSTAT_DATA_CHAR },
2129 	{ "clock_MHz",			KSTAT_DATA_LONG },
2130 	{ "chip_id",			KSTAT_DATA_LONG },
2131 	{ "implementation",		KSTAT_DATA_STRING },
2132 	{ "brand",			KSTAT_DATA_STRING },
2133 	{ "core_id",			KSTAT_DATA_LONG },
2134 	{ "current_clock_Hz",		KSTAT_DATA_UINT64 },
2135 	{ "supported_frequencies_Hz",	KSTAT_DATA_STRING },
2136 #if defined(__sparcv9)
2137 	{ "device_ID",			KSTAT_DATA_UINT64 },
2138 	{ "cpu_fru",			KSTAT_DATA_STRING },
2139 #endif
2140 #if defined(__x86)
2141 	{ "vendor_id",			KSTAT_DATA_STRING },
2142 	{ "family",			KSTAT_DATA_INT32 },
2143 	{ "model",			KSTAT_DATA_INT32 },
2144 	{ "stepping",			KSTAT_DATA_INT32 },
2145 	{ "clog_id",			KSTAT_DATA_INT32 },
2146 	{ "pkg_core_id",		KSTAT_DATA_LONG },
2147 	{ "ncpu_per_chip",		KSTAT_DATA_INT32 },
2148 	{ "ncore_per_chip",		KSTAT_DATA_INT32 },
2149 #endif
2150 };
2151 
2152 static kmutex_t cpu_info_template_lock;
2153 
2154 static int
2155 cpu_info_kstat_update(kstat_t *ksp, int rw)
2156 {
2157 	cpu_t	*cp = ksp->ks_private;
2158 	const char *pi_state;
2159 
2160 	if (rw == KSTAT_WRITE)
2161 		return (EACCES);
2162 
2163 	switch (cp->cpu_type_info.pi_state) {
2164 	case P_ONLINE:
2165 		pi_state = PS_ONLINE;
2166 		break;
2167 	case P_POWEROFF:
2168 		pi_state = PS_POWEROFF;
2169 		break;
2170 	case P_NOINTR:
2171 		pi_state = PS_NOINTR;
2172 		break;
2173 	case P_FAULTED:
2174 		pi_state = PS_FAULTED;
2175 		break;
2176 	case P_SPARE:
2177 		pi_state = PS_SPARE;
2178 		break;
2179 	case P_OFFLINE:
2180 		pi_state = PS_OFFLINE;
2181 		break;
2182 	default:
2183 		pi_state = "unknown";
2184 	}
2185 	(void) strcpy(cpu_info_template.ci_state.value.c, pi_state);
2186 	cpu_info_template.ci_state_begin.value.l = cp->cpu_state_begin;
2187 	(void) strncpy(cpu_info_template.ci_cpu_type.value.c,
2188 	    cp->cpu_type_info.pi_processor_type, 15);
2189 	(void) strncpy(cpu_info_template.ci_fpu_type.value.c,
2190 	    cp->cpu_type_info.pi_fputypes, 15);
2191 	cpu_info_template.ci_clock_MHz.value.l = cp->cpu_type_info.pi_clock;
2192 	cpu_info_template.ci_chip_id.value.l =
2193 	    pg_plat_hw_instance_id(cp, PGHW_CHIP);
2194 	kstat_named_setstr(&cpu_info_template.ci_implementation,
2195 	    cp->cpu_idstr);
2196 	kstat_named_setstr(&cpu_info_template.ci_brandstr, cp->cpu_brandstr);
2197 	cpu_info_template.ci_core_id.value.l = pg_plat_get_core_id(cp);
2198 	cpu_info_template.ci_curr_clock_Hz.value.ui64 =
2199 	    cp->cpu_curr_clock;
2200 	kstat_named_setstr(&cpu_info_template.ci_supp_freq_Hz,
2201 	    cp->cpu_supp_freqs);
2202 #if defined(__sparcv9)
2203 	cpu_info_template.ci_device_ID.value.ui64 =
2204 	    cpunodes[cp->cpu_id].device_id;
2205 	kstat_named_setstr(&cpu_info_template.ci_cpu_fru, cpu_fru_fmri(cp));
2206 #endif
2207 #if defined(__x86)
2208 	kstat_named_setstr(&cpu_info_template.ci_vendorstr,
2209 	    cpuid_getvendorstr(cp));
2210 	cpu_info_template.ci_family.value.l = cpuid_getfamily(cp);
2211 	cpu_info_template.ci_model.value.l = cpuid_getmodel(cp);
2212 	cpu_info_template.ci_step.value.l = cpuid_getstep(cp);
2213 	cpu_info_template.ci_clogid.value.l = cpuid_get_clogid(cp);
2214 	cpu_info_template.ci_ncpuperchip.value.l = cpuid_get_ncpu_per_chip(cp);
2215 	cpu_info_template.ci_ncoreperchip.value.l =
2216 	    cpuid_get_ncore_per_chip(cp);
2217 	cpu_info_template.ci_pkg_core_id.value.l = cpuid_get_pkgcoreid(cp);
2218 #endif
2219 
2220 	return (0);
2221 }
2222 
2223 static void
2224 cpu_info_kstat_create(cpu_t *cp)
2225 {
2226 	zoneid_t zoneid;
2227 
2228 	ASSERT(MUTEX_HELD(&cpu_lock));
2229 
2230 	if (pool_pset_enabled())
2231 		zoneid = GLOBAL_ZONEID;
2232 	else
2233 		zoneid = ALL_ZONES;
2234 	if ((cp->cpu_info_kstat = kstat_create_zone("cpu_info", cp->cpu_id,
2235 	    NULL, "misc", KSTAT_TYPE_NAMED,
2236 	    sizeof (cpu_info_template) / sizeof (kstat_named_t),
2237 	    KSTAT_FLAG_VIRTUAL, zoneid)) != NULL) {
2238 		cp->cpu_info_kstat->ks_data_size += 2 * CPU_IDSTRLEN;
2239 #if defined(__sparcv9)
2240 		cp->cpu_info_kstat->ks_data_size +=
2241 		    strlen(cpu_fru_fmri(cp)) + 1;
2242 #endif
2243 #if defined(__x86)
2244 		cp->cpu_info_kstat->ks_data_size += X86_VENDOR_STRLEN;
2245 #endif
2246 		if (cp->cpu_supp_freqs != NULL)
2247 			cp->cpu_info_kstat->ks_data_size +=
2248 			    strlen(cp->cpu_supp_freqs) + 1;
2249 		cp->cpu_info_kstat->ks_lock = &cpu_info_template_lock;
2250 		cp->cpu_info_kstat->ks_data = &cpu_info_template;
2251 		cp->cpu_info_kstat->ks_private = cp;
2252 		cp->cpu_info_kstat->ks_update = cpu_info_kstat_update;
2253 		kstat_install(cp->cpu_info_kstat);
2254 	}
2255 }
2256 
2257 static void
2258 cpu_info_kstat_destroy(cpu_t *cp)
2259 {
2260 	ASSERT(MUTEX_HELD(&cpu_lock));
2261 
2262 	kstat_delete(cp->cpu_info_kstat);
2263 	cp->cpu_info_kstat = NULL;
2264 }
2265 
2266 /*
2267  * Create and install kstats for the boot CPU.
2268  */
2269 void
2270 cpu_kstat_init(cpu_t *cp)
2271 {
2272 	mutex_enter(&cpu_lock);
2273 	cpu_info_kstat_create(cp);
2274 	cpu_stats_kstat_create(cp);
2275 	cpu_create_intrstat(cp);
2276 	cpu_set_state(cp);
2277 	mutex_exit(&cpu_lock);
2278 }
2279 
2280 /*
2281  * Make visible to the zone that subset of the cpu information that would be
2282  * initialized when a cpu is configured (but still offline).
2283  */
2284 void
2285 cpu_visibility_configure(cpu_t *cp, zone_t *zone)
2286 {
2287 	zoneid_t zoneid = zone ? zone->zone_id : ALL_ZONES;
2288 
2289 	ASSERT(MUTEX_HELD(&cpu_lock));
2290 	ASSERT(pool_pset_enabled());
2291 	ASSERT(cp != NULL);
2292 
2293 	if (zoneid != ALL_ZONES && zoneid != GLOBAL_ZONEID) {
2294 		zone->zone_ncpus++;
2295 		ASSERT(zone->zone_ncpus <= ncpus);
2296 	}
2297 	if (cp->cpu_info_kstat != NULL)
2298 		kstat_zone_add(cp->cpu_info_kstat, zoneid);
2299 }
2300 
2301 /*
2302  * Make visible to the zone that subset of the cpu information that would be
2303  * initialized when a previously configured cpu is onlined.
2304  */
2305 void
2306 cpu_visibility_online(cpu_t *cp, zone_t *zone)
2307 {
2308 	kstat_t *ksp;
2309 	char name[sizeof ("cpu_stat") + 10];	/* enough for 32-bit cpuids */
2310 	zoneid_t zoneid = zone ? zone->zone_id : ALL_ZONES;
2311 	processorid_t cpun;
2312 
2313 	ASSERT(MUTEX_HELD(&cpu_lock));
2314 	ASSERT(pool_pset_enabled());
2315 	ASSERT(cp != NULL);
2316 	ASSERT(cpu_is_active(cp));
2317 
2318 	cpun = cp->cpu_id;
2319 	if (zoneid != ALL_ZONES && zoneid != GLOBAL_ZONEID) {
2320 		zone->zone_ncpus_online++;
2321 		ASSERT(zone->zone_ncpus_online <= ncpus_online);
2322 	}
2323 	(void) snprintf(name, sizeof (name), "cpu_stat%d", cpun);
2324 	if ((ksp = kstat_hold_byname("cpu_stat", cpun, name, ALL_ZONES))
2325 	    != NULL) {
2326 		kstat_zone_add(ksp, zoneid);
2327 		kstat_rele(ksp);
2328 	}
2329 	if ((ksp = kstat_hold_byname("cpu", cpun, "sys", ALL_ZONES)) != NULL) {
2330 		kstat_zone_add(ksp, zoneid);
2331 		kstat_rele(ksp);
2332 	}
2333 	if ((ksp = kstat_hold_byname("cpu", cpun, "vm", ALL_ZONES)) != NULL) {
2334 		kstat_zone_add(ksp, zoneid);
2335 		kstat_rele(ksp);
2336 	}
2337 	if ((ksp = kstat_hold_byname("cpu", cpun, "intrstat", ALL_ZONES)) !=
2338 	    NULL) {
2339 		kstat_zone_add(ksp, zoneid);
2340 		kstat_rele(ksp);
2341 	}
2342 }
2343 
2344 /*
2345  * Update relevant kstats such that cpu is now visible to processes
2346  * executing in specified zone.
2347  */
2348 void
2349 cpu_visibility_add(cpu_t *cp, zone_t *zone)
2350 {
2351 	cpu_visibility_configure(cp, zone);
2352 	if (cpu_is_active(cp))
2353 		cpu_visibility_online(cp, zone);
2354 }
2355 
2356 /*
2357  * Make invisible to the zone that subset of the cpu information that would be
2358  * torn down when a previously offlined cpu is unconfigured.
2359  */
2360 void
2361 cpu_visibility_unconfigure(cpu_t *cp, zone_t *zone)
2362 {
2363 	zoneid_t zoneid = zone ? zone->zone_id : ALL_ZONES;
2364 
2365 	ASSERT(MUTEX_HELD(&cpu_lock));
2366 	ASSERT(pool_pset_enabled());
2367 	ASSERT(cp != NULL);
2368 
2369 	if (zoneid != ALL_ZONES && zoneid != GLOBAL_ZONEID) {
2370 		ASSERT(zone->zone_ncpus != 0);
2371 		zone->zone_ncpus--;
2372 	}
2373 	if (cp->cpu_info_kstat)
2374 		kstat_zone_remove(cp->cpu_info_kstat, zoneid);
2375 }
2376 
2377 /*
2378  * Make invisible to the zone that subset of the cpu information that would be
2379  * torn down when a cpu is offlined (but still configured).
2380  */
2381 void
2382 cpu_visibility_offline(cpu_t *cp, zone_t *zone)
2383 {
2384 	kstat_t *ksp;
2385 	char name[sizeof ("cpu_stat") + 10];	/* enough for 32-bit cpuids */
2386 	zoneid_t zoneid = zone ? zone->zone_id : ALL_ZONES;
2387 	processorid_t cpun;
2388 
2389 	ASSERT(MUTEX_HELD(&cpu_lock));
2390 	ASSERT(pool_pset_enabled());
2391 	ASSERT(cp != NULL);
2392 	ASSERT(cpu_is_active(cp));
2393 
2394 	cpun = cp->cpu_id;
2395 	if (zoneid != ALL_ZONES && zoneid != GLOBAL_ZONEID) {
2396 		ASSERT(zone->zone_ncpus_online != 0);
2397 		zone->zone_ncpus_online--;
2398 	}
2399 
2400 	if ((ksp = kstat_hold_byname("cpu", cpun, "intrstat", ALL_ZONES)) !=
2401 	    NULL) {
2402 		kstat_zone_remove(ksp, zoneid);
2403 		kstat_rele(ksp);
2404 	}
2405 	if ((ksp = kstat_hold_byname("cpu", cpun, "vm", ALL_ZONES)) != NULL) {
2406 		kstat_zone_remove(ksp, zoneid);
2407 		kstat_rele(ksp);
2408 	}
2409 	if ((ksp = kstat_hold_byname("cpu", cpun, "sys", ALL_ZONES)) != NULL) {
2410 		kstat_zone_remove(ksp, zoneid);
2411 		kstat_rele(ksp);
2412 	}
2413 	(void) snprintf(name, sizeof (name), "cpu_stat%d", cpun);
2414 	if ((ksp = kstat_hold_byname("cpu_stat", cpun, name, ALL_ZONES))
2415 	    != NULL) {
2416 		kstat_zone_remove(ksp, zoneid);
2417 		kstat_rele(ksp);
2418 	}
2419 }
2420 
2421 /*
2422  * Update relevant kstats such that cpu is no longer visible to processes
2423  * executing in specified zone.
2424  */
2425 void
2426 cpu_visibility_remove(cpu_t *cp, zone_t *zone)
2427 {
2428 	if (cpu_is_active(cp))
2429 		cpu_visibility_offline(cp, zone);
2430 	cpu_visibility_unconfigure(cp, zone);
2431 }
2432 
2433 /*
2434  * Bind a thread to a CPU as requested.
2435  */
2436 int
2437 cpu_bind_thread(kthread_id_t tp, processorid_t bind, processorid_t *obind,
2438     int *error)
2439 {
2440 	processorid_t	binding;
2441 	cpu_t		*cp = NULL;
2442 
2443 	ASSERT(MUTEX_HELD(&cpu_lock));
2444 	ASSERT(MUTEX_HELD(&ttoproc(tp)->p_lock));
2445 
2446 	thread_lock(tp);
2447 
2448 	/*
2449 	 * Record old binding, but change the obind, which was initialized
2450 	 * to PBIND_NONE, only if this thread has a binding.  This avoids
2451 	 * reporting PBIND_NONE for a process when some LWPs are bound.
2452 	 */
2453 	binding = tp->t_bind_cpu;
2454 
2455 	switch (bind) {
2456 	case PBIND_QUERY:
2457 		/* Just return the old binding */
2458 		*obind = binding;
2459 		thread_unlock(tp);
2460 		return (0);
2461 
2462 	case PBIND_QUERY_TYPE:
2463 		/* Return the binding type */
2464 		*obind = TB_CPU_IS_SOFT(tp) ? PBIND_SOFT : PBIND_HARD;
2465 		thread_unlock(tp);
2466 		return (0);
2467 
2468 	case PBIND_SOFT:
2469 		/*
2470 		 *  Set soft binding for this thread and return the actual
2471 		 *  binding
2472 		 */
2473 		TB_CPU_SOFT_SET(tp);
2474 		*obind = binding;
2475 		thread_unlock(tp);
2476 		return (0);
2477 
2478 	case PBIND_HARD:
2479 		/*
2480 		 *  Set hard binding for this thread and return the actual
2481 		 *  binding
2482 		 */
2483 		TB_CPU_HARD_SET(tp);
2484 		*obind = binding;
2485 		thread_unlock(tp);
2486 		return (0);
2487 
2488 	case PBIND_NONE:
2489 		break;
2490 
2491 	default:
2492 		/* record old binding */
2493 		*obind = binding;
2494 		break;
2495 	}
2496 
2497 	/*
2498 	 * If this thread/LWP cannot be bound because of permission
2499 	 * problems, just note that and return success so that the
2500 	 * other threads/LWPs will be bound.  This is the way
2501 	 * processor_bind() is defined to work.
2502 	 *
2503 	 * Binding will get EPERM if the thread is of system class
2504 	 * or hasprocperm() fails.
2505 	 */
2506 	if (tp->t_cid == 0 || !hasprocperm(tp->t_cred, CRED())) {
2507 		*error = EPERM;
2508 		thread_unlock(tp);
2509 		return (0);
2510 	}
2511 
2512 	binding = bind;
2513 	if (binding != PBIND_NONE) {
2514 		cp = cpu_get((processorid_t)binding);
2515 		/*
2516 		 * Make sure binding is valid and is in right partition.
2517 		 */
2518 		if (cp == NULL || tp->t_cpupart != cp->cpu_part) {
2519 			*error = EINVAL;
2520 			thread_unlock(tp);
2521 			return (0);
2522 		}
2523 	}
2524 	tp->t_bind_cpu = binding;	/* set new binding */
2525 
2526 	/*
2527 	 * If there is no system-set reason for affinity, set
2528 	 * the t_bound_cpu field to reflect the binding.
2529 	 */
2530 	if (tp->t_affinitycnt == 0) {
2531 		if (binding == PBIND_NONE) {
2532 			/*
2533 			 * We may need to adjust disp_max_unbound_pri
2534 			 * since we're becoming unbound.
2535 			 */
2536 			disp_adjust_unbound_pri(tp);
2537 
2538 			tp->t_bound_cpu = NULL;	/* set new binding */
2539 
2540 			/*
2541 			 * Move thread to lgroup with strongest affinity
2542 			 * after unbinding
2543 			 */
2544 			if (tp->t_lgrp_affinity)
2545 				lgrp_move_thread(tp,
2546 				    lgrp_choose(tp, tp->t_cpupart), 1);
2547 
2548 			if (tp->t_state == TS_ONPROC &&
2549 			    tp->t_cpu->cpu_part != tp->t_cpupart)
2550 				cpu_surrender(tp);
2551 		} else {
2552 			lpl_t	*lpl;
2553 
2554 			tp->t_bound_cpu = cp;
2555 			ASSERT(cp->cpu_lpl != NULL);
2556 
2557 			/*
2558 			 * Set home to lgroup with most affinity containing CPU
2559 			 * that thread is being bound or minimum bounding
2560 			 * lgroup if no affinities set
2561 			 */
2562 			if (tp->t_lgrp_affinity)
2563 				lpl = lgrp_affinity_best(tp, tp->t_cpupart,
2564 				    LGRP_NONE, B_FALSE);
2565 			else
2566 				lpl = cp->cpu_lpl;
2567 
2568 			if (tp->t_lpl != lpl) {
2569 				/* can't grab cpu_lock */
2570 				lgrp_move_thread(tp, lpl, 1);
2571 			}
2572 
2573 			/*
2574 			 * Make the thread switch to the bound CPU.
2575 			 * If the thread is runnable, we need to
2576 			 * requeue it even if t_cpu is already set
2577 			 * to the right CPU, since it may be on a
2578 			 * kpreempt queue and need to move to a local
2579 			 * queue.  We could check t_disp_queue to
2580 			 * avoid unnecessary overhead if it's already
2581 			 * on the right queue, but since this isn't
2582 			 * a performance-critical operation it doesn't
2583 			 * seem worth the extra code and complexity.
2584 			 *
2585 			 * If the thread is weakbound to the cpu then it will
2586 			 * resist the new binding request until the weak
2587 			 * binding drops.  The cpu_surrender or requeueing
2588 			 * below could be skipped in such cases (since it
2589 			 * will have no effect), but that would require
2590 			 * thread_allowmigrate to acquire thread_lock so
2591 			 * we'll take the very occasional hit here instead.
2592 			 */
2593 			if (tp->t_state == TS_ONPROC) {
2594 				cpu_surrender(tp);
2595 			} else if (tp->t_state == TS_RUN) {
2596 				cpu_t *ocp = tp->t_cpu;
2597 
2598 				(void) dispdeq(tp);
2599 				setbackdq(tp);
2600 				/*
2601 				 * Either on the bound CPU's disp queue now,
2602 				 * or swapped out or on the swap queue.
2603 				 */
2604 				ASSERT(tp->t_disp_queue == cp->cpu_disp ||
2605 				    tp->t_weakbound_cpu == ocp ||
2606 				    (tp->t_schedflag & (TS_LOAD | TS_ON_SWAPQ))
2607 				    != TS_LOAD);
2608 			}
2609 		}
2610 	}
2611 
2612 	/*
2613 	 * Our binding has changed; set TP_CHANGEBIND.
2614 	 */
2615 	tp->t_proc_flag |= TP_CHANGEBIND;
2616 	aston(tp);
2617 
2618 	thread_unlock(tp);
2619 
2620 	return (0);
2621 }
2622 
2623 #if CPUSET_WORDS > 1
2624 
2625 /*
2626  * Functions for implementing cpuset operations when a cpuset is more
2627  * than one word.  On platforms where a cpuset is a single word these
2628  * are implemented as macros in cpuvar.h.
2629  */
2630 
2631 void
2632 cpuset_all(cpuset_t *s)
2633 {
2634 	int i;
2635 
2636 	for (i = 0; i < CPUSET_WORDS; i++)
2637 		s->cpub[i] = ~0UL;
2638 }
2639 
2640 void
2641 cpuset_all_but(cpuset_t *s, uint_t cpu)
2642 {
2643 	cpuset_all(s);
2644 	CPUSET_DEL(*s, cpu);
2645 }
2646 
2647 void
2648 cpuset_only(cpuset_t *s, uint_t cpu)
2649 {
2650 	CPUSET_ZERO(*s);
2651 	CPUSET_ADD(*s, cpu);
2652 }
2653 
2654 int
2655 cpuset_isnull(cpuset_t *s)
2656 {
2657 	int i;
2658 
2659 	for (i = 0; i < CPUSET_WORDS; i++)
2660 		if (s->cpub[i] != 0)
2661 			return (0);
2662 	return (1);
2663 }
2664 
2665 int
2666 cpuset_cmp(cpuset_t *s1, cpuset_t *s2)
2667 {
2668 	int i;
2669 
2670 	for (i = 0; i < CPUSET_WORDS; i++)
2671 		if (s1->cpub[i] != s2->cpub[i])
2672 			return (0);
2673 	return (1);
2674 }
2675 
2676 uint_t
2677 cpuset_find(cpuset_t *s)
2678 {
2679 
2680 	uint_t	i;
2681 	uint_t	cpu = (uint_t)-1;
2682 
2683 	/*
2684 	 * Find a cpu in the cpuset
2685 	 */
2686 	for (i = 0; i < CPUSET_WORDS; i++) {
2687 		cpu = (uint_t)(lowbit(s->cpub[i]) - 1);
2688 		if (cpu != (uint_t)-1) {
2689 			cpu += i * BT_NBIPUL;
2690 			break;
2691 		}
2692 	}
2693 	return (cpu);
2694 }
2695 
2696 void
2697 cpuset_bounds(cpuset_t *s, uint_t *smallestid, uint_t *largestid)
2698 {
2699 	int	i, j;
2700 	uint_t	bit;
2701 
2702 	/*
2703 	 * First, find the smallest cpu id in the set.
2704 	 */
2705 	for (i = 0; i < CPUSET_WORDS; i++) {
2706 		if (s->cpub[i] != 0) {
2707 			bit = (uint_t)(lowbit(s->cpub[i]) - 1);
2708 			ASSERT(bit != (uint_t)-1);
2709 			*smallestid = bit + (i * BT_NBIPUL);
2710 
2711 			/*
2712 			 * Now find the largest cpu id in
2713 			 * the set and return immediately.
2714 			 * Done in an inner loop to avoid
2715 			 * having to break out of the first
2716 			 * loop.
2717 			 */
2718 			for (j = CPUSET_WORDS - 1; j >= i; j--) {
2719 				if (s->cpub[j] != 0) {
2720 					bit = (uint_t)(highbit(s->cpub[j]) - 1);
2721 					ASSERT(bit != (uint_t)-1);
2722 					*largestid = bit + (j * BT_NBIPUL);
2723 					ASSERT(*largestid >= *smallestid);
2724 					return;
2725 				}
2726 			}
2727 
2728 			/*
2729 			 * If this code is reached, a
2730 			 * smallestid was found, but not a
2731 			 * largestid. The cpuset must have
2732 			 * been changed during the course
2733 			 * of this function call.
2734 			 */
2735 			ASSERT(0);
2736 		}
2737 	}
2738 	*smallestid = *largestid = CPUSET_NOTINSET;
2739 }
2740 
2741 #endif	/* CPUSET_WORDS */
2742 
2743 /*
2744  * Unbind threads bound to specified CPU.
2745  *
2746  * If `unbind_all_threads' is true, unbind all user threads bound to a given
2747  * CPU. Otherwise unbind all soft-bound user threads.
2748  */
2749 int
2750 cpu_unbind(processorid_t cpu, boolean_t unbind_all_threads)
2751 {
2752 	processorid_t obind;
2753 	kthread_t *tp;
2754 	int ret = 0;
2755 	proc_t *pp;
2756 	int err, berr = 0;
2757 
2758 	ASSERT(MUTEX_HELD(&cpu_lock));
2759 
2760 	mutex_enter(&pidlock);
2761 	for (pp = practive; pp != NULL; pp = pp->p_next) {
2762 		mutex_enter(&pp->p_lock);
2763 		tp = pp->p_tlist;
2764 		/*
2765 		 * Skip zombies, kernel processes, and processes in
2766 		 * other zones, if called from a non-global zone.
2767 		 */
2768 		if (tp == NULL || (pp->p_flag & SSYS) ||
2769 		    !HASZONEACCESS(curproc, pp->p_zone->zone_id)) {
2770 			mutex_exit(&pp->p_lock);
2771 			continue;
2772 		}
2773 		do {
2774 			if (tp->t_bind_cpu != cpu)
2775 				continue;
2776 			/*
2777 			 * Skip threads with hard binding when
2778 			 * `unbind_all_threads' is not specified.
2779 			 */
2780 			if (!unbind_all_threads && TB_CPU_IS_HARD(tp))
2781 				continue;
2782 			err = cpu_bind_thread(tp, PBIND_NONE, &obind, &berr);
2783 			if (ret == 0)
2784 				ret = err;
2785 		} while ((tp = tp->t_forw) != pp->p_tlist);
2786 		mutex_exit(&pp->p_lock);
2787 	}
2788 	mutex_exit(&pidlock);
2789 	if (ret == 0)
2790 		ret = berr;
2791 	return (ret);
2792 }
2793 
2794 
2795 /*
2796  * Destroy all remaining bound threads on a cpu.
2797  */
2798 void
2799 cpu_destroy_bound_threads(cpu_t *cp)
2800 {
2801 	extern id_t syscid;
2802 	register kthread_id_t	t, tlist, tnext;
2803 
2804 	/*
2805 	 * Destroy all remaining bound threads on the cpu.  This
2806 	 * should include both the interrupt threads and the idle thread.
2807 	 * This requires some care, since we need to traverse the
2808 	 * thread list with the pidlock mutex locked, but thread_free
2809 	 * also locks the pidlock mutex.  So, we collect the threads
2810 	 * we're going to reap in a list headed by "tlist", then we
2811 	 * unlock the pidlock mutex and traverse the tlist list,
2812 	 * doing thread_free's on the thread's.	 Simple, n'est pas?
2813 	 * Also, this depends on thread_free not mucking with the
2814 	 * t_next and t_prev links of the thread.
2815 	 */
2816 
2817 	if ((t = curthread) != NULL) {
2818 
2819 		tlist = NULL;
2820 		mutex_enter(&pidlock);
2821 		do {
2822 			tnext = t->t_next;
2823 			if (t->t_bound_cpu == cp) {
2824 
2825 				/*
2826 				 * We've found a bound thread, carefully unlink
2827 				 * it out of the thread list, and add it to
2828 				 * our "tlist".	 We "know" we don't have to
2829 				 * worry about unlinking curthread (the thread
2830 				 * that is executing this code).
2831 				 */
2832 				t->t_next->t_prev = t->t_prev;
2833 				t->t_prev->t_next = t->t_next;
2834 				t->t_next = tlist;
2835 				tlist = t;
2836 				ASSERT(t->t_cid == syscid);
2837 				/* wake up anyone blocked in thread_join */
2838 				cv_broadcast(&t->t_joincv);
2839 				/*
2840 				 * t_lwp set by interrupt threads and not
2841 				 * cleared.
2842 				 */
2843 				t->t_lwp = NULL;
2844 				/*
2845 				 * Pause and idle threads always have
2846 				 * t_state set to TS_ONPROC.
2847 				 */
2848 				t->t_state = TS_FREE;
2849 				t->t_prev = NULL;	/* Just in case */
2850 			}
2851 
2852 		} while ((t = tnext) != curthread);
2853 
2854 		mutex_exit(&pidlock);
2855 
2856 		mutex_sync();
2857 		for (t = tlist; t != NULL; t = tnext) {
2858 			tnext = t->t_next;
2859 			thread_free(t);
2860 		}
2861 	}
2862 }
2863 
2864 /*
2865  * Update the cpu_supp_freqs of this cpu. This information is returned
2866  * as part of cpu_info kstats. If the cpu_info_kstat exists already, then
2867  * maintain the kstat data size.
2868  */
2869 void
2870 cpu_set_supp_freqs(cpu_t *cp, const char *freqs)
2871 {
2872 	char clkstr[sizeof ("18446744073709551615") + 1]; /* ui64 MAX */
2873 	const char *lfreqs = clkstr;
2874 	boolean_t kstat_exists = B_FALSE;
2875 	kstat_t *ksp;
2876 	size_t len;
2877 
2878 	/*
2879 	 * A NULL pointer means we only support one speed.
2880 	 */
2881 	if (freqs == NULL)
2882 		(void) snprintf(clkstr, sizeof (clkstr), "%"PRIu64,
2883 		    cp->cpu_curr_clock);
2884 	else
2885 		lfreqs = freqs;
2886 
2887 	/*
2888 	 * Make sure the frequency doesn't change while a snapshot is
2889 	 * going on. Of course, we only need to worry about this if
2890 	 * the kstat exists.
2891 	 */
2892 	if ((ksp = cp->cpu_info_kstat) != NULL) {
2893 		mutex_enter(ksp->ks_lock);
2894 		kstat_exists = B_TRUE;
2895 	}
2896 
2897 	/*
2898 	 * Free any previously allocated string and if the kstat
2899 	 * already exists, then update its data size.
2900 	 */
2901 	if (cp->cpu_supp_freqs != NULL) {
2902 		len = strlen(cp->cpu_supp_freqs) + 1;
2903 		kmem_free(cp->cpu_supp_freqs, len);
2904 		if (kstat_exists)
2905 			ksp->ks_data_size -= len;
2906 	}
2907 
2908 	/*
2909 	 * Allocate the new string and set the pointer.
2910 	 */
2911 	len = strlen(lfreqs) + 1;
2912 	cp->cpu_supp_freqs = kmem_alloc(len, KM_SLEEP);
2913 	(void) strcpy(cp->cpu_supp_freqs, lfreqs);
2914 
2915 	/*
2916 	 * If the kstat already exists then update the data size and
2917 	 * free the lock.
2918 	 */
2919 	if (kstat_exists) {
2920 		ksp->ks_data_size += len;
2921 		mutex_exit(ksp->ks_lock);
2922 	}
2923 }
2924 
2925 /*
2926  * processor_info(2) and p_online(2) status support functions
2927  *   The constants returned by the cpu_get_state() and cpu_get_state_str() are
2928  *   for use in communicating processor state information to userland.  Kernel
2929  *   subsystems should only be using the cpu_flags value directly.  Subsystems
2930  *   modifying cpu_flags should record the state change via a call to the
2931  *   cpu_set_state().
2932  */
2933 
2934 /*
2935  * Update the pi_state of this CPU.  This function provides the CPU status for
2936  * the information returned by processor_info(2).
2937  */
2938 void
2939 cpu_set_state(cpu_t *cpu)
2940 {
2941 	ASSERT(MUTEX_HELD(&cpu_lock));
2942 	cpu->cpu_type_info.pi_state = cpu_get_state(cpu);
2943 	cpu->cpu_state_begin = gethrestime_sec();
2944 	pool_cpu_mod = gethrtime();
2945 }
2946 
2947 /*
2948  * Return offline/online/other status for the indicated CPU.  Use only for
2949  * communication with user applications; cpu_flags provides the in-kernel
2950  * interface.
2951  */
2952 int
2953 cpu_get_state(cpu_t *cpu)
2954 {
2955 	ASSERT(MUTEX_HELD(&cpu_lock));
2956 	if (cpu->cpu_flags & CPU_POWEROFF)
2957 		return (P_POWEROFF);
2958 	else if (cpu->cpu_flags & CPU_FAULTED)
2959 		return (P_FAULTED);
2960 	else if (cpu->cpu_flags & CPU_SPARE)
2961 		return (P_SPARE);
2962 	else if ((cpu->cpu_flags & (CPU_READY | CPU_OFFLINE)) != CPU_READY)
2963 		return (P_OFFLINE);
2964 	else if (cpu->cpu_flags & CPU_ENABLE)
2965 		return (P_ONLINE);
2966 	else
2967 		return (P_NOINTR);
2968 }
2969 
2970 /*
2971  * Return processor_info(2) state as a string.
2972  */
2973 const char *
2974 cpu_get_state_str(cpu_t *cpu)
2975 {
2976 	const char *string;
2977 
2978 	switch (cpu_get_state(cpu)) {
2979 	case P_ONLINE:
2980 		string = PS_ONLINE;
2981 		break;
2982 	case P_POWEROFF:
2983 		string = PS_POWEROFF;
2984 		break;
2985 	case P_NOINTR:
2986 		string = PS_NOINTR;
2987 		break;
2988 	case P_SPARE:
2989 		string = PS_SPARE;
2990 		break;
2991 	case P_FAULTED:
2992 		string = PS_FAULTED;
2993 		break;
2994 	case P_OFFLINE:
2995 		string = PS_OFFLINE;
2996 		break;
2997 	default:
2998 		string = "unknown";
2999 		break;
3000 	}
3001 	return (string);
3002 }
3003 
3004 /*
3005  * Export this CPU's statistics (cpu_stat_t and cpu_stats_t) as raw and named
3006  * kstats, respectively.  This is done when a CPU is initialized or placed
3007  * online via p_online(2).
3008  */
3009 static void
3010 cpu_stats_kstat_create(cpu_t *cp)
3011 {
3012 	int 	instance = cp->cpu_id;
3013 	char 	*module = "cpu";
3014 	char 	*class = "misc";
3015 	kstat_t	*ksp;
3016 	zoneid_t zoneid;
3017 
3018 	ASSERT(MUTEX_HELD(&cpu_lock));
3019 
3020 	if (pool_pset_enabled())
3021 		zoneid = GLOBAL_ZONEID;
3022 	else
3023 		zoneid = ALL_ZONES;
3024 	/*
3025 	 * Create named kstats
3026 	 */
3027 #define	CPU_STATS_KS_CREATE(name, tsize, update_func)                    \
3028 	ksp = kstat_create_zone(module, instance, (name), class,         \
3029 	    KSTAT_TYPE_NAMED, (tsize) / sizeof (kstat_named_t), 0,       \
3030 	    zoneid);                                                     \
3031 	if (ksp != NULL) {                                               \
3032 		ksp->ks_private = cp;                                    \
3033 		ksp->ks_update = (update_func);                          \
3034 		kstat_install(ksp);                                      \
3035 	} else                                                           \
3036 		cmn_err(CE_WARN, "cpu: unable to create %s:%d:%s kstat", \
3037 		    module, instance, (name));
3038 
3039 	CPU_STATS_KS_CREATE("sys", sizeof (cpu_sys_stats_ks_data_template),
3040 	    cpu_sys_stats_ks_update);
3041 	CPU_STATS_KS_CREATE("vm", sizeof (cpu_vm_stats_ks_data_template),
3042 	    cpu_vm_stats_ks_update);
3043 
3044 	/*
3045 	 * Export the familiar cpu_stat_t KSTAT_TYPE_RAW kstat.
3046 	 */
3047 	ksp = kstat_create_zone("cpu_stat", cp->cpu_id, NULL,
3048 	    "misc", KSTAT_TYPE_RAW, sizeof (cpu_stat_t), 0, zoneid);
3049 	if (ksp != NULL) {
3050 		ksp->ks_update = cpu_stat_ks_update;
3051 		ksp->ks_private = cp;
3052 		kstat_install(ksp);
3053 	}
3054 }
3055 
3056 static void
3057 cpu_stats_kstat_destroy(cpu_t *cp)
3058 {
3059 	char ks_name[KSTAT_STRLEN];
3060 
3061 	(void) sprintf(ks_name, "cpu_stat%d", cp->cpu_id);
3062 	kstat_delete_byname("cpu_stat", cp->cpu_id, ks_name);
3063 
3064 	kstat_delete_byname("cpu", cp->cpu_id, "sys");
3065 	kstat_delete_byname("cpu", cp->cpu_id, "vm");
3066 }
3067 
3068 static int
3069 cpu_sys_stats_ks_update(kstat_t *ksp, int rw)
3070 {
3071 	cpu_t *cp = (cpu_t *)ksp->ks_private;
3072 	struct cpu_sys_stats_ks_data *csskd;
3073 	cpu_sys_stats_t *css;
3074 	hrtime_t msnsecs[NCMSTATES];
3075 	int	i;
3076 
3077 	if (rw == KSTAT_WRITE)
3078 		return (EACCES);
3079 
3080 	csskd = ksp->ks_data;
3081 	css = &cp->cpu_stats.sys;
3082 
3083 	/*
3084 	 * Read CPU mstate, but compare with the last values we
3085 	 * received to make sure that the returned kstats never
3086 	 * decrease.
3087 	 */
3088 
3089 	get_cpu_mstate(cp, msnsecs);
3090 	if (csskd->cpu_nsec_idle.value.ui64 > msnsecs[CMS_IDLE])
3091 		msnsecs[CMS_IDLE] = csskd->cpu_nsec_idle.value.ui64;
3092 	if (csskd->cpu_nsec_user.value.ui64 > msnsecs[CMS_USER])
3093 		msnsecs[CMS_USER] = csskd->cpu_nsec_user.value.ui64;
3094 	if (csskd->cpu_nsec_kernel.value.ui64 > msnsecs[CMS_SYSTEM])
3095 		msnsecs[CMS_SYSTEM] = csskd->cpu_nsec_kernel.value.ui64;
3096 
3097 	bcopy(&cpu_sys_stats_ks_data_template, ksp->ks_data,
3098 	    sizeof (cpu_sys_stats_ks_data_template));
3099 
3100 	csskd->cpu_ticks_wait.value.ui64 = 0;
3101 	csskd->wait_ticks_io.value.ui64 = 0;
3102 
3103 	csskd->cpu_nsec_idle.value.ui64 = msnsecs[CMS_IDLE];
3104 	csskd->cpu_nsec_user.value.ui64 = msnsecs[CMS_USER];
3105 	csskd->cpu_nsec_kernel.value.ui64 = msnsecs[CMS_SYSTEM];
3106 	csskd->cpu_ticks_idle.value.ui64 =
3107 	    NSEC_TO_TICK(csskd->cpu_nsec_idle.value.ui64);
3108 	csskd->cpu_ticks_user.value.ui64 =
3109 	    NSEC_TO_TICK(csskd->cpu_nsec_user.value.ui64);
3110 	csskd->cpu_ticks_kernel.value.ui64 =
3111 	    NSEC_TO_TICK(csskd->cpu_nsec_kernel.value.ui64);
3112 	csskd->cpu_nsec_intr.value.ui64 = cp->cpu_intrlast;
3113 	csskd->cpu_load_intr.value.ui64 = cp->cpu_intrload;
3114 	csskd->bread.value.ui64 = css->bread;
3115 	csskd->bwrite.value.ui64 = css->bwrite;
3116 	csskd->lread.value.ui64 = css->lread;
3117 	csskd->lwrite.value.ui64 = css->lwrite;
3118 	csskd->phread.value.ui64 = css->phread;
3119 	csskd->phwrite.value.ui64 = css->phwrite;
3120 	csskd->pswitch.value.ui64 = css->pswitch;
3121 	csskd->trap.value.ui64 = css->trap;
3122 	csskd->intr.value.ui64 = 0;
3123 	for (i = 0; i < PIL_MAX; i++)
3124 		csskd->intr.value.ui64 += css->intr[i];
3125 	csskd->syscall.value.ui64 = css->syscall;
3126 	csskd->sysread.value.ui64 = css->sysread;
3127 	csskd->syswrite.value.ui64 = css->syswrite;
3128 	csskd->sysfork.value.ui64 = css->sysfork;
3129 	csskd->sysvfork.value.ui64 = css->sysvfork;
3130 	csskd->sysexec.value.ui64 = css->sysexec;
3131 	csskd->readch.value.ui64 = css->readch;
3132 	csskd->writech.value.ui64 = css->writech;
3133 	csskd->rcvint.value.ui64 = css->rcvint;
3134 	csskd->xmtint.value.ui64 = css->xmtint;
3135 	csskd->mdmint.value.ui64 = css->mdmint;
3136 	csskd->rawch.value.ui64 = css->rawch;
3137 	csskd->canch.value.ui64 = css->canch;
3138 	csskd->outch.value.ui64 = css->outch;
3139 	csskd->msg.value.ui64 = css->msg;
3140 	csskd->sema.value.ui64 = css->sema;
3141 	csskd->namei.value.ui64 = css->namei;
3142 	csskd->ufsiget.value.ui64 = css->ufsiget;
3143 	csskd->ufsdirblk.value.ui64 = css->ufsdirblk;
3144 	csskd->ufsipage.value.ui64 = css->ufsipage;
3145 	csskd->ufsinopage.value.ui64 = css->ufsinopage;
3146 	csskd->procovf.value.ui64 = css->procovf;
3147 	csskd->intrthread.value.ui64 = 0;
3148 	for (i = 0; i < LOCK_LEVEL - 1; i++)
3149 		csskd->intrthread.value.ui64 += css->intr[i];
3150 	csskd->intrblk.value.ui64 = css->intrblk;
3151 	csskd->intrunpin.value.ui64 = css->intrunpin;
3152 	csskd->idlethread.value.ui64 = css->idlethread;
3153 	csskd->inv_swtch.value.ui64 = css->inv_swtch;
3154 	csskd->nthreads.value.ui64 = css->nthreads;
3155 	csskd->cpumigrate.value.ui64 = css->cpumigrate;
3156 	csskd->xcalls.value.ui64 = css->xcalls;
3157 	csskd->mutex_adenters.value.ui64 = css->mutex_adenters;
3158 	csskd->rw_rdfails.value.ui64 = css->rw_rdfails;
3159 	csskd->rw_wrfails.value.ui64 = css->rw_wrfails;
3160 	csskd->modload.value.ui64 = css->modload;
3161 	csskd->modunload.value.ui64 = css->modunload;
3162 	csskd->bawrite.value.ui64 = css->bawrite;
3163 	csskd->iowait.value.ui64 = css->iowait;
3164 
3165 	return (0);
3166 }
3167 
3168 static int
3169 cpu_vm_stats_ks_update(kstat_t *ksp, int rw)
3170 {
3171 	cpu_t *cp = (cpu_t *)ksp->ks_private;
3172 	struct cpu_vm_stats_ks_data *cvskd;
3173 	cpu_vm_stats_t *cvs;
3174 
3175 	if (rw == KSTAT_WRITE)
3176 		return (EACCES);
3177 
3178 	cvs = &cp->cpu_stats.vm;
3179 	cvskd = ksp->ks_data;
3180 
3181 	bcopy(&cpu_vm_stats_ks_data_template, ksp->ks_data,
3182 	    sizeof (cpu_vm_stats_ks_data_template));
3183 	cvskd->pgrec.value.ui64 = cvs->pgrec;
3184 	cvskd->pgfrec.value.ui64 = cvs->pgfrec;
3185 	cvskd->pgin.value.ui64 = cvs->pgin;
3186 	cvskd->pgpgin.value.ui64 = cvs->pgpgin;
3187 	cvskd->pgout.value.ui64 = cvs->pgout;
3188 	cvskd->pgpgout.value.ui64 = cvs->pgpgout;
3189 	cvskd->swapin.value.ui64 = cvs->swapin;
3190 	cvskd->pgswapin.value.ui64 = cvs->pgswapin;
3191 	cvskd->swapout.value.ui64 = cvs->swapout;
3192 	cvskd->pgswapout.value.ui64 = cvs->pgswapout;
3193 	cvskd->zfod.value.ui64 = cvs->zfod;
3194 	cvskd->dfree.value.ui64 = cvs->dfree;
3195 	cvskd->scan.value.ui64 = cvs->scan;
3196 	cvskd->rev.value.ui64 = cvs->rev;
3197 	cvskd->hat_fault.value.ui64 = cvs->hat_fault;
3198 	cvskd->as_fault.value.ui64 = cvs->as_fault;
3199 	cvskd->maj_fault.value.ui64 = cvs->maj_fault;
3200 	cvskd->cow_fault.value.ui64 = cvs->cow_fault;
3201 	cvskd->prot_fault.value.ui64 = cvs->prot_fault;
3202 	cvskd->softlock.value.ui64 = cvs->softlock;
3203 	cvskd->kernel_asflt.value.ui64 = cvs->kernel_asflt;
3204 	cvskd->pgrrun.value.ui64 = cvs->pgrrun;
3205 	cvskd->execpgin.value.ui64 = cvs->execpgin;
3206 	cvskd->execpgout.value.ui64 = cvs->execpgout;
3207 	cvskd->execfree.value.ui64 = cvs->execfree;
3208 	cvskd->anonpgin.value.ui64 = cvs->anonpgin;
3209 	cvskd->anonpgout.value.ui64 = cvs->anonpgout;
3210 	cvskd->anonfree.value.ui64 = cvs->anonfree;
3211 	cvskd->fspgin.value.ui64 = cvs->fspgin;
3212 	cvskd->fspgout.value.ui64 = cvs->fspgout;
3213 	cvskd->fsfree.value.ui64 = cvs->fsfree;
3214 
3215 	return (0);
3216 }
3217 
3218 static int
3219 cpu_stat_ks_update(kstat_t *ksp, int rw)
3220 {
3221 	cpu_stat_t *cso;
3222 	cpu_t *cp;
3223 	int i;
3224 	hrtime_t msnsecs[NCMSTATES];
3225 
3226 	cso = (cpu_stat_t *)ksp->ks_data;
3227 	cp = (cpu_t *)ksp->ks_private;
3228 
3229 	if (rw == KSTAT_WRITE)
3230 		return (EACCES);
3231 
3232 	/*
3233 	 * Read CPU mstate, but compare with the last values we
3234 	 * received to make sure that the returned kstats never
3235 	 * decrease.
3236 	 */
3237 
3238 	get_cpu_mstate(cp, msnsecs);
3239 	msnsecs[CMS_IDLE] = NSEC_TO_TICK(msnsecs[CMS_IDLE]);
3240 	msnsecs[CMS_USER] = NSEC_TO_TICK(msnsecs[CMS_USER]);
3241 	msnsecs[CMS_SYSTEM] = NSEC_TO_TICK(msnsecs[CMS_SYSTEM]);
3242 	if (cso->cpu_sysinfo.cpu[CPU_IDLE] < msnsecs[CMS_IDLE])
3243 		cso->cpu_sysinfo.cpu[CPU_IDLE] = msnsecs[CMS_IDLE];
3244 	if (cso->cpu_sysinfo.cpu[CPU_USER] < msnsecs[CMS_USER])
3245 		cso->cpu_sysinfo.cpu[CPU_USER] = msnsecs[CMS_USER];
3246 	if (cso->cpu_sysinfo.cpu[CPU_KERNEL] < msnsecs[CMS_SYSTEM])
3247 		cso->cpu_sysinfo.cpu[CPU_KERNEL] = msnsecs[CMS_SYSTEM];
3248 	cso->cpu_sysinfo.cpu[CPU_WAIT] 	= 0;
3249 	cso->cpu_sysinfo.wait[W_IO] 	= 0;
3250 	cso->cpu_sysinfo.wait[W_SWAP]	= 0;
3251 	cso->cpu_sysinfo.wait[W_PIO]	= 0;
3252 	cso->cpu_sysinfo.bread 		= CPU_STATS(cp, sys.bread);
3253 	cso->cpu_sysinfo.bwrite 	= CPU_STATS(cp, sys.bwrite);
3254 	cso->cpu_sysinfo.lread 		= CPU_STATS(cp, sys.lread);
3255 	cso->cpu_sysinfo.lwrite 	= CPU_STATS(cp, sys.lwrite);
3256 	cso->cpu_sysinfo.phread 	= CPU_STATS(cp, sys.phread);
3257 	cso->cpu_sysinfo.phwrite 	= CPU_STATS(cp, sys.phwrite);
3258 	cso->cpu_sysinfo.pswitch 	= CPU_STATS(cp, sys.pswitch);
3259 	cso->cpu_sysinfo.trap 		= CPU_STATS(cp, sys.trap);
3260 	cso->cpu_sysinfo.intr		= 0;
3261 	for (i = 0; i < PIL_MAX; i++)
3262 		cso->cpu_sysinfo.intr += CPU_STATS(cp, sys.intr[i]);
3263 	cso->cpu_sysinfo.syscall	= CPU_STATS(cp, sys.syscall);
3264 	cso->cpu_sysinfo.sysread	= CPU_STATS(cp, sys.sysread);
3265 	cso->cpu_sysinfo.syswrite	= CPU_STATS(cp, sys.syswrite);
3266 	cso->cpu_sysinfo.sysfork	= CPU_STATS(cp, sys.sysfork);
3267 	cso->cpu_sysinfo.sysvfork	= CPU_STATS(cp, sys.sysvfork);
3268 	cso->cpu_sysinfo.sysexec	= CPU_STATS(cp, sys.sysexec);
3269 	cso->cpu_sysinfo.readch		= CPU_STATS(cp, sys.readch);
3270 	cso->cpu_sysinfo.writech	= CPU_STATS(cp, sys.writech);
3271 	cso->cpu_sysinfo.rcvint		= CPU_STATS(cp, sys.rcvint);
3272 	cso->cpu_sysinfo.xmtint		= CPU_STATS(cp, sys.xmtint);
3273 	cso->cpu_sysinfo.mdmint		= CPU_STATS(cp, sys.mdmint);
3274 	cso->cpu_sysinfo.rawch		= CPU_STATS(cp, sys.rawch);
3275 	cso->cpu_sysinfo.canch		= CPU_STATS(cp, sys.canch);
3276 	cso->cpu_sysinfo.outch		= CPU_STATS(cp, sys.outch);
3277 	cso->cpu_sysinfo.msg		= CPU_STATS(cp, sys.msg);
3278 	cso->cpu_sysinfo.sema		= CPU_STATS(cp, sys.sema);
3279 	cso->cpu_sysinfo.namei		= CPU_STATS(cp, sys.namei);
3280 	cso->cpu_sysinfo.ufsiget	= CPU_STATS(cp, sys.ufsiget);
3281 	cso->cpu_sysinfo.ufsdirblk	= CPU_STATS(cp, sys.ufsdirblk);
3282 	cso->cpu_sysinfo.ufsipage	= CPU_STATS(cp, sys.ufsipage);
3283 	cso->cpu_sysinfo.ufsinopage	= CPU_STATS(cp, sys.ufsinopage);
3284 	cso->cpu_sysinfo.inodeovf	= 0;
3285 	cso->cpu_sysinfo.fileovf	= 0;
3286 	cso->cpu_sysinfo.procovf	= CPU_STATS(cp, sys.procovf);
3287 	cso->cpu_sysinfo.intrthread	= 0;
3288 	for (i = 0; i < LOCK_LEVEL - 1; i++)
3289 		cso->cpu_sysinfo.intrthread += CPU_STATS(cp, sys.intr[i]);
3290 	cso->cpu_sysinfo.intrblk	= CPU_STATS(cp, sys.intrblk);
3291 	cso->cpu_sysinfo.idlethread	= CPU_STATS(cp, sys.idlethread);
3292 	cso->cpu_sysinfo.inv_swtch	= CPU_STATS(cp, sys.inv_swtch);
3293 	cso->cpu_sysinfo.nthreads	= CPU_STATS(cp, sys.nthreads);
3294 	cso->cpu_sysinfo.cpumigrate	= CPU_STATS(cp, sys.cpumigrate);
3295 	cso->cpu_sysinfo.xcalls		= CPU_STATS(cp, sys.xcalls);
3296 	cso->cpu_sysinfo.mutex_adenters	= CPU_STATS(cp, sys.mutex_adenters);
3297 	cso->cpu_sysinfo.rw_rdfails	= CPU_STATS(cp, sys.rw_rdfails);
3298 	cso->cpu_sysinfo.rw_wrfails	= CPU_STATS(cp, sys.rw_wrfails);
3299 	cso->cpu_sysinfo.modload	= CPU_STATS(cp, sys.modload);
3300 	cso->cpu_sysinfo.modunload	= CPU_STATS(cp, sys.modunload);
3301 	cso->cpu_sysinfo.bawrite	= CPU_STATS(cp, sys.bawrite);
3302 	cso->cpu_sysinfo.rw_enters	= 0;
3303 	cso->cpu_sysinfo.win_uo_cnt	= 0;
3304 	cso->cpu_sysinfo.win_uu_cnt	= 0;
3305 	cso->cpu_sysinfo.win_so_cnt	= 0;
3306 	cso->cpu_sysinfo.win_su_cnt	= 0;
3307 	cso->cpu_sysinfo.win_suo_cnt	= 0;
3308 
3309 	cso->cpu_syswait.iowait		= CPU_STATS(cp, sys.iowait);
3310 	cso->cpu_syswait.swap		= 0;
3311 	cso->cpu_syswait.physio		= 0;
3312 
3313 	cso->cpu_vminfo.pgrec		= CPU_STATS(cp, vm.pgrec);
3314 	cso->cpu_vminfo.pgfrec		= CPU_STATS(cp, vm.pgfrec);
3315 	cso->cpu_vminfo.pgin		= CPU_STATS(cp, vm.pgin);
3316 	cso->cpu_vminfo.pgpgin		= CPU_STATS(cp, vm.pgpgin);
3317 	cso->cpu_vminfo.pgout		= CPU_STATS(cp, vm.pgout);
3318 	cso->cpu_vminfo.pgpgout		= CPU_STATS(cp, vm.pgpgout);
3319 	cso->cpu_vminfo.swapin		= CPU_STATS(cp, vm.swapin);
3320 	cso->cpu_vminfo.pgswapin	= CPU_STATS(cp, vm.pgswapin);
3321 	cso->cpu_vminfo.swapout		= CPU_STATS(cp, vm.swapout);
3322 	cso->cpu_vminfo.pgswapout	= CPU_STATS(cp, vm.pgswapout);
3323 	cso->cpu_vminfo.zfod		= CPU_STATS(cp, vm.zfod);
3324 	cso->cpu_vminfo.dfree		= CPU_STATS(cp, vm.dfree);
3325 	cso->cpu_vminfo.scan		= CPU_STATS(cp, vm.scan);
3326 	cso->cpu_vminfo.rev		= CPU_STATS(cp, vm.rev);
3327 	cso->cpu_vminfo.hat_fault	= CPU_STATS(cp, vm.hat_fault);
3328 	cso->cpu_vminfo.as_fault	= CPU_STATS(cp, vm.as_fault);
3329 	cso->cpu_vminfo.maj_fault	= CPU_STATS(cp, vm.maj_fault);
3330 	cso->cpu_vminfo.cow_fault	= CPU_STATS(cp, vm.cow_fault);
3331 	cso->cpu_vminfo.prot_fault	= CPU_STATS(cp, vm.prot_fault);
3332 	cso->cpu_vminfo.softlock	= CPU_STATS(cp, vm.softlock);
3333 	cso->cpu_vminfo.kernel_asflt	= CPU_STATS(cp, vm.kernel_asflt);
3334 	cso->cpu_vminfo.pgrrun		= CPU_STATS(cp, vm.pgrrun);
3335 	cso->cpu_vminfo.execpgin	= CPU_STATS(cp, vm.execpgin);
3336 	cso->cpu_vminfo.execpgout	= CPU_STATS(cp, vm.execpgout);
3337 	cso->cpu_vminfo.execfree	= CPU_STATS(cp, vm.execfree);
3338 	cso->cpu_vminfo.anonpgin	= CPU_STATS(cp, vm.anonpgin);
3339 	cso->cpu_vminfo.anonpgout	= CPU_STATS(cp, vm.anonpgout);
3340 	cso->cpu_vminfo.anonfree	= CPU_STATS(cp, vm.anonfree);
3341 	cso->cpu_vminfo.fspgin		= CPU_STATS(cp, vm.fspgin);
3342 	cso->cpu_vminfo.fspgout		= CPU_STATS(cp, vm.fspgout);
3343 	cso->cpu_vminfo.fsfree		= CPU_STATS(cp, vm.fsfree);
3344 
3345 	return (0);
3346 }
3347