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