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