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