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