xref: /titanic_50/usr/src/uts/common/os/cpu.c (revision ae115bc77f6fcde83175c75b4206dc2e50747966)
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 		pause_cpus(NULL);
1169 		cpu_add_active_internal(cp);
1170 		if (cp->cpu_flags & CPU_FAULTED) {
1171 			cp->cpu_flags &= ~CPU_FAULTED;
1172 			mp_cpu_faulted_exit(cp);
1173 		}
1174 		cp->cpu_flags &= ~(CPU_QUIESCED | CPU_OFFLINE | CPU_FROZEN |
1175 		    CPU_SPARE);
1176 		start_cpus();
1177 		cpu_stats_kstat_create(cp);
1178 		cpu_create_intrstat(cp);
1179 		lgrp_kstat_create(cp);
1180 		cpu_state_change_notify(cp->cpu_id, CPU_ON);
1181 		cpu_intr_enable(cp);	/* arch-dep hook */
1182 		cpu_set_state(cp);
1183 		cyclic_online(cp);
1184 		poke_cpu(cp->cpu_id);
1185 	}
1186 
1187 	return (error);
1188 }
1189 
1190 /*
1191  * Take the indicated CPU offline.
1192  */
1193 int
1194 cpu_offline(cpu_t *cp, int flags)
1195 {
1196 	cpupart_t *pp;
1197 	int	error = 0;
1198 	cpu_t	*ncp;
1199 	int	intr_enable;
1200 	int	cyclic_off = 0;
1201 	int	loop_count;
1202 	int	no_quiesce = 0;
1203 	int	(*bound_func)(struct cpu *, int);
1204 	kthread_t *t;
1205 	lpl_t	*cpu_lpl;
1206 	proc_t	*p;
1207 	int	lgrp_diff_lpl;
1208 
1209 	ASSERT(MUTEX_HELD(&cpu_lock));
1210 
1211 	/*
1212 	 * If we're going from faulted or spare to offline, just
1213 	 * clear these flags and update CPU state.
1214 	 */
1215 	if (cp->cpu_flags & (CPU_FAULTED | CPU_SPARE)) {
1216 		if (cp->cpu_flags & CPU_FAULTED) {
1217 			cp->cpu_flags &= ~CPU_FAULTED;
1218 			mp_cpu_faulted_exit(cp);
1219 		}
1220 		cp->cpu_flags &= ~CPU_SPARE;
1221 		cpu_set_state(cp);
1222 		return (0);
1223 	}
1224 
1225 	/*
1226 	 * Handle off-line request.
1227 	 */
1228 	pp = cp->cpu_part;
1229 	/*
1230 	 * Don't offline last online CPU in partition
1231 	 */
1232 	if (ncpus_online <= 1 || pp->cp_ncpus <= 1 || cpu_intr_count(cp) < 2)
1233 		return (EBUSY);
1234 	/*
1235 	 * Unbind all thread bound to our CPU if we were asked to.
1236 	 */
1237 	if (flags & CPU_FORCED && (error = cpu_unbind(cp->cpu_id)) != 0)
1238 		return (error);
1239 	/*
1240 	 * We shouldn't be bound to this CPU ourselves.
1241 	 */
1242 	if (curthread->t_bound_cpu == cp)
1243 		return (EBUSY);
1244 
1245 	/*
1246 	 * Tell interested parties that this CPU is going offline.
1247 	 */
1248 	cpu_state_change_notify(cp->cpu_id, CPU_OFF);
1249 
1250 	/*
1251 	 * Tell the PG subsystem that the CPU is leaving the partition
1252 	 */
1253 	pg_cpupart_out(cp, pp);
1254 
1255 	/*
1256 	 * Take the CPU out of interrupt participation so we won't find
1257 	 * bound kernel threads.  If the architecture cannot completely
1258 	 * shut off interrupts on the CPU, don't quiesce it, but don't
1259 	 * run anything but interrupt thread... this is indicated by
1260 	 * the CPU_OFFLINE flag being on but the CPU_QUIESCE flag being
1261 	 * off.
1262 	 */
1263 	intr_enable = cp->cpu_flags & CPU_ENABLE;
1264 	if (intr_enable)
1265 		no_quiesce = cpu_intr_disable(cp);
1266 
1267 	/*
1268 	 * Record that we are aiming to offline this cpu.  This acts as
1269 	 * a barrier to further weak binding requests in thread_nomigrate
1270 	 * and also causes cpu_choose, disp_lowpri_cpu and setfrontdq to
1271 	 * lean away from this cpu.  Further strong bindings are already
1272 	 * avoided since we hold cpu_lock.  Since threads that are set
1273 	 * runnable around now and others coming off the target cpu are
1274 	 * directed away from the target, existing strong and weak bindings
1275 	 * (especially the latter) to the target cpu stand maximum chance of
1276 	 * being able to unbind during the short delay loop below (if other
1277 	 * unbound threads compete they may not see cpu in time to unbind
1278 	 * even if they would do so immediately.
1279 	 */
1280 	cpu_inmotion = cp;
1281 	membar_enter();
1282 
1283 	/*
1284 	 * Check for kernel threads (strong or weak) bound to that CPU.
1285 	 * Strongly bound threads may not unbind, and we'll have to return
1286 	 * EBUSY.  Weakly bound threads should always disappear - we've
1287 	 * stopped more weak binding with cpu_inmotion and existing
1288 	 * bindings will drain imminently (they may not block).  Nonetheless
1289 	 * we will wait for a fixed period for all bound threads to disappear.
1290 	 * Inactive interrupt threads are OK (they'll be in TS_FREE
1291 	 * state).  If test finds some bound threads, wait a few ticks
1292 	 * to give short-lived threads (such as interrupts) chance to
1293 	 * complete.  Note that if no_quiesce is set, i.e. this cpu
1294 	 * is required to service interrupts, then we take the route
1295 	 * that permits interrupt threads to be active (or bypassed).
1296 	 */
1297 	bound_func = no_quiesce ? disp_bound_threads : disp_bound_anythreads;
1298 
1299 again:	for (loop_count = 0; (*bound_func)(cp, 0); loop_count++) {
1300 		if (loop_count >= 5) {
1301 			error = EBUSY;	/* some threads still bound */
1302 			break;
1303 		}
1304 
1305 		/*
1306 		 * If some threads were assigned, give them
1307 		 * a chance to complete or move.
1308 		 *
1309 		 * This assumes that the clock_thread is not bound
1310 		 * to any CPU, because the clock_thread is needed to
1311 		 * do the delay(hz/100).
1312 		 *
1313 		 * Note: we still hold the cpu_lock while waiting for
1314 		 * the next clock tick.  This is OK since it isn't
1315 		 * needed for anything else except processor_bind(2),
1316 		 * and system initialization.  If we drop the lock,
1317 		 * we would risk another p_online disabling the last
1318 		 * processor.
1319 		 */
1320 		delay(hz/100);
1321 	}
1322 
1323 	if (error == 0 && cyclic_off == 0) {
1324 		if (!cyclic_offline(cp)) {
1325 			/*
1326 			 * We must have bound cyclics...
1327 			 */
1328 			error = EBUSY;
1329 			goto out;
1330 		}
1331 		cyclic_off = 1;
1332 	}
1333 
1334 	/*
1335 	 * Call mp_cpu_stop() to perform any special operations
1336 	 * needed for this machine architecture to offline a CPU.
1337 	 */
1338 	if (error == 0)
1339 		error = mp_cpu_stop(cp);	/* arch-dep hook */
1340 
1341 	/*
1342 	 * If that all worked, take the CPU offline and decrement
1343 	 * ncpus_online.
1344 	 */
1345 	if (error == 0) {
1346 		/*
1347 		 * Put all the cpus into a known safe place.
1348 		 * No mutexes can be entered while CPUs are paused.
1349 		 */
1350 		pause_cpus(cp);
1351 		/*
1352 		 * Repeat the operation, if necessary, to make sure that
1353 		 * all outstanding low-level interrupts run to completion
1354 		 * before we set the CPU_QUIESCED flag.  It's also possible
1355 		 * that a thread has weak bound to the cpu despite our raising
1356 		 * cpu_inmotion above since it may have loaded that
1357 		 * value before the barrier became visible (this would have
1358 		 * to be the thread that was on the target cpu at the time
1359 		 * we raised the barrier).
1360 		 */
1361 		if ((!no_quiesce && cp->cpu_intr_actv != 0) ||
1362 		    (*bound_func)(cp, 1)) {
1363 			start_cpus();
1364 			(void) mp_cpu_start(cp);
1365 			goto again;
1366 		}
1367 		ncp = cp->cpu_next_part;
1368 		cpu_lpl = cp->cpu_lpl;
1369 		ASSERT(cpu_lpl != NULL);
1370 
1371 		/*
1372 		 * Remove the CPU from the list of active CPUs.
1373 		 */
1374 		cpu_remove_active(cp);
1375 
1376 		/*
1377 		 * Walk the active process list and look for threads
1378 		 * whose home lgroup needs to be updated, or
1379 		 * the last CPU they run on is the one being offlined now.
1380 		 */
1381 
1382 		ASSERT(curthread->t_cpu != cp);
1383 		for (p = practive; p != NULL; p = p->p_next) {
1384 
1385 			t = p->p_tlist;
1386 
1387 			if (t == NULL)
1388 				continue;
1389 
1390 			lgrp_diff_lpl = 0;
1391 
1392 			do {
1393 				ASSERT(t->t_lpl != NULL);
1394 				/*
1395 				 * Taking last CPU in lpl offline
1396 				 * Rehome thread if it is in this lpl
1397 				 * Otherwise, update the count of how many
1398 				 * threads are in this CPU's lgroup but have
1399 				 * a different lpl.
1400 				 */
1401 
1402 				if (cpu_lpl->lpl_ncpu == 0) {
1403 					if (t->t_lpl == cpu_lpl)
1404 						lgrp_move_thread(t,
1405 						    lgrp_choose(t,
1406 						    t->t_cpupart), 0);
1407 					else if (t->t_lpl->lpl_lgrpid ==
1408 					    cpu_lpl->lpl_lgrpid)
1409 						lgrp_diff_lpl++;
1410 				}
1411 				ASSERT(t->t_lpl->lpl_ncpu > 0);
1412 
1413 				/*
1414 				 * Update CPU last ran on if it was this CPU
1415 				 */
1416 				if (t->t_cpu == cp && t->t_bound_cpu != cp)
1417 				    t->t_cpu = disp_lowpri_cpu(ncp, t->t_lpl,
1418 					t->t_pri, NULL);
1419 				ASSERT(t->t_cpu != cp || t->t_bound_cpu == cp ||
1420 				    t->t_weakbound_cpu == cp);
1421 
1422 				t = t->t_forw;
1423 			} while (t != p->p_tlist);
1424 
1425 			/*
1426 			 * Didn't find any threads in the same lgroup as this
1427 			 * CPU with a different lpl, so remove the lgroup from
1428 			 * the process lgroup bitmask.
1429 			 */
1430 
1431 			if (lgrp_diff_lpl == 0)
1432 				klgrpset_del(p->p_lgrpset, cpu_lpl->lpl_lgrpid);
1433 		}
1434 
1435 		/*
1436 		 * Walk thread list looking for threads that need to be
1437 		 * rehomed, since there are some threads that are not in
1438 		 * their process's p_tlist.
1439 		 */
1440 
1441 		t = curthread;
1442 		do {
1443 			ASSERT(t != NULL && t->t_lpl != NULL);
1444 
1445 			/*
1446 			 * Rehome threads with same lpl as this CPU when this
1447 			 * is the last CPU in the lpl.
1448 			 */
1449 
1450 			if ((cpu_lpl->lpl_ncpu == 0) && (t->t_lpl == cpu_lpl))
1451 				lgrp_move_thread(t,
1452 				    lgrp_choose(t, t->t_cpupart), 1);
1453 
1454 			ASSERT(t->t_lpl->lpl_ncpu > 0);
1455 
1456 			/*
1457 			 * Update CPU last ran on if it was this CPU
1458 			 */
1459 
1460 			if (t->t_cpu == cp && t->t_bound_cpu != cp) {
1461 				t->t_cpu = disp_lowpri_cpu(ncp,
1462 				    t->t_lpl, t->t_pri, NULL);
1463 			}
1464 			ASSERT(t->t_cpu != cp || t->t_bound_cpu == cp ||
1465 			    t->t_weakbound_cpu == cp);
1466 			t = t->t_next;
1467 
1468 		} while (t != curthread);
1469 		ASSERT((cp->cpu_flags & (CPU_FAULTED | CPU_SPARE)) == 0);
1470 		cp->cpu_flags |= CPU_OFFLINE;
1471 		disp_cpu_inactive(cp);
1472 		if (!no_quiesce)
1473 			cp->cpu_flags |= CPU_QUIESCED;
1474 		ncpus_online--;
1475 		cpu_set_state(cp);
1476 		cpu_inmotion = NULL;
1477 		start_cpus();
1478 		cpu_stats_kstat_destroy(cp);
1479 		cpu_delete_intrstat(cp);
1480 		lgrp_kstat_destroy(cp);
1481 	}
1482 
1483 out:
1484 	cpu_inmotion = NULL;
1485 
1486 	/*
1487 	 * If we failed, re-enable interrupts.
1488 	 * Do this even if cpu_intr_disable returned an error, because
1489 	 * it may have partially disabled interrupts.
1490 	 */
1491 	if (error && intr_enable)
1492 		cpu_intr_enable(cp);
1493 
1494 	/*
1495 	 * If we failed, but managed to offline the cyclic subsystem on this
1496 	 * CPU, bring it back online.
1497 	 */
1498 	if (error && cyclic_off)
1499 		cyclic_online(cp);
1500 
1501 	/*
1502 	 * If we failed, tell the PG subsystem that the CPU is back
1503 	 */
1504 	pg_cpupart_in(cp, pp);
1505 
1506 	/*
1507 	 * If we failed, we need to notify everyone that this CPU is back on.
1508 	 */
1509 	if (error != 0)
1510 		cpu_state_change_notify(cp->cpu_id, CPU_ON);
1511 
1512 	return (error);
1513 }
1514 
1515 /*
1516  * Mark the indicated CPU as faulted, taking it offline.
1517  */
1518 int
1519 cpu_faulted(cpu_t *cp, int flags)
1520 {
1521 	int	error = 0;
1522 
1523 	ASSERT(MUTEX_HELD(&cpu_lock));
1524 	ASSERT(!cpu_is_poweredoff(cp));
1525 
1526 	if (cpu_is_offline(cp)) {
1527 		cp->cpu_flags &= ~CPU_SPARE;
1528 		cp->cpu_flags |= CPU_FAULTED;
1529 		mp_cpu_faulted_enter(cp);
1530 		cpu_set_state(cp);
1531 		return (0);
1532 	}
1533 
1534 	if ((error = cpu_offline(cp, flags)) == 0) {
1535 		cp->cpu_flags |= CPU_FAULTED;
1536 		mp_cpu_faulted_enter(cp);
1537 		cpu_set_state(cp);
1538 	}
1539 
1540 	return (error);
1541 }
1542 
1543 /*
1544  * Mark the indicated CPU as a spare, taking it offline.
1545  */
1546 int
1547 cpu_spare(cpu_t *cp, int flags)
1548 {
1549 	int	error = 0;
1550 
1551 	ASSERT(MUTEX_HELD(&cpu_lock));
1552 	ASSERT(!cpu_is_poweredoff(cp));
1553 
1554 	if (cpu_is_offline(cp)) {
1555 		if (cp->cpu_flags & CPU_FAULTED) {
1556 			cp->cpu_flags &= ~CPU_FAULTED;
1557 			mp_cpu_faulted_exit(cp);
1558 		}
1559 		cp->cpu_flags |= CPU_SPARE;
1560 		cpu_set_state(cp);
1561 		return (0);
1562 	}
1563 
1564 	if ((error = cpu_offline(cp, flags)) == 0) {
1565 		cp->cpu_flags |= CPU_SPARE;
1566 		cpu_set_state(cp);
1567 	}
1568 
1569 	return (error);
1570 }
1571 
1572 /*
1573  * Take the indicated CPU from poweroff to offline.
1574  */
1575 int
1576 cpu_poweron(cpu_t *cp)
1577 {
1578 	int	error = ENOTSUP;
1579 
1580 	ASSERT(MUTEX_HELD(&cpu_lock));
1581 	ASSERT(cpu_is_poweredoff(cp));
1582 
1583 	error = mp_cpu_poweron(cp);	/* arch-dep hook */
1584 	if (error == 0)
1585 		cpu_set_state(cp);
1586 
1587 	return (error);
1588 }
1589 
1590 /*
1591  * Take the indicated CPU from any inactive state to powered off.
1592  */
1593 int
1594 cpu_poweroff(cpu_t *cp)
1595 {
1596 	int	error = ENOTSUP;
1597 
1598 	ASSERT(MUTEX_HELD(&cpu_lock));
1599 	ASSERT(cpu_is_offline(cp));
1600 
1601 	if (!(cp->cpu_flags & CPU_QUIESCED))
1602 		return (EBUSY);		/* not completely idle */
1603 
1604 	error = mp_cpu_poweroff(cp);	/* arch-dep hook */
1605 	if (error == 0)
1606 		cpu_set_state(cp);
1607 
1608 	return (error);
1609 }
1610 
1611 /*
1612  * Initialize the CPU lists for the first CPU.
1613  */
1614 void
1615 cpu_list_init(cpu_t *cp)
1616 {
1617 	cp->cpu_next = cp;
1618 	cp->cpu_prev = cp;
1619 	cpu_list = cp;
1620 
1621 	cp->cpu_next_onln = cp;
1622 	cp->cpu_prev_onln = cp;
1623 	cpu_active = cp;
1624 
1625 	cp->cpu_seqid = 0;
1626 	CPUSET_ADD(cpu_seqid_inuse, 0);
1627 	cp->cpu_cache_offset = KMEM_CACHE_SIZE(cp->cpu_seqid);
1628 	cp_default.cp_mach = &cp_default_mach;
1629 	cp_default.cp_cpulist = cp;
1630 	cp_default.cp_ncpus = 1;
1631 	cp->cpu_next_part = cp;
1632 	cp->cpu_prev_part = cp;
1633 	cp->cpu_part = &cp_default;
1634 
1635 	CPUSET_ADD(cpu_available, cp->cpu_id);
1636 }
1637 
1638 /*
1639  * Insert a CPU into the list of available CPUs.
1640  */
1641 void
1642 cpu_add_unit(cpu_t *cp)
1643 {
1644 	int seqid;
1645 
1646 	ASSERT(MUTEX_HELD(&cpu_lock));
1647 	ASSERT(cpu_list != NULL);	/* list started in cpu_list_init */
1648 
1649 	lgrp_config(LGRP_CONFIG_CPU_ADD, (uintptr_t)cp, 0);
1650 
1651 	/*
1652 	 * Note: most users of the cpu_list will grab the
1653 	 * cpu_lock to insure that it isn't modified.  However,
1654 	 * certain users can't or won't do that.  To allow this
1655 	 * we pause the other cpus.  Users who walk the list
1656 	 * without cpu_lock, must disable kernel preemption
1657 	 * to insure that the list isn't modified underneath
1658 	 * them.  Also, any cached pointers to cpu structures
1659 	 * must be revalidated by checking to see if the
1660 	 * cpu_next pointer points to itself.  This check must
1661 	 * be done with the cpu_lock held or kernel preemption
1662 	 * disabled.  This check relies upon the fact that
1663 	 * old cpu structures are not free'ed or cleared after
1664 	 * then are removed from the cpu_list.
1665 	 *
1666 	 * Note that the clock code walks the cpu list dereferencing
1667 	 * the cpu_part pointer, so we need to initialize it before
1668 	 * adding the cpu to the list.
1669 	 */
1670 	cp->cpu_part = &cp_default;
1671 	(void) pause_cpus(NULL);
1672 	cp->cpu_next = cpu_list;
1673 	cp->cpu_prev = cpu_list->cpu_prev;
1674 	cpu_list->cpu_prev->cpu_next = cp;
1675 	cpu_list->cpu_prev = cp;
1676 	start_cpus();
1677 
1678 	for (seqid = 0; CPU_IN_SET(cpu_seqid_inuse, seqid); seqid++)
1679 		continue;
1680 	CPUSET_ADD(cpu_seqid_inuse, seqid);
1681 	cp->cpu_seqid = seqid;
1682 	ASSERT(ncpus < max_ncpus);
1683 	ncpus++;
1684 	cp->cpu_cache_offset = KMEM_CACHE_SIZE(cp->cpu_seqid);
1685 	cpu[cp->cpu_id] = cp;
1686 	CPUSET_ADD(cpu_available, cp->cpu_id);
1687 
1688 	/*
1689 	 * allocate a pause thread for this CPU.
1690 	 */
1691 	cpu_pause_alloc(cp);
1692 
1693 	/*
1694 	 * So that new CPUs won't have NULL prev_onln and next_onln pointers,
1695 	 * link them into a list of just that CPU.
1696 	 * This is so that disp_lowpri_cpu will work for thread_create in
1697 	 * pause_cpus() when called from the startup thread in a new CPU.
1698 	 */
1699 	cp->cpu_next_onln = cp;
1700 	cp->cpu_prev_onln = cp;
1701 	cpu_info_kstat_create(cp);
1702 	cp->cpu_next_part = cp;
1703 	cp->cpu_prev_part = cp;
1704 
1705 	init_cpu_mstate(cp, CMS_SYSTEM);
1706 
1707 	pool_pset_mod = gethrtime();
1708 }
1709 
1710 /*
1711  * Do the opposite of cpu_add_unit().
1712  */
1713 void
1714 cpu_del_unit(int cpuid)
1715 {
1716 	struct cpu	*cp, *cpnext;
1717 
1718 	ASSERT(MUTEX_HELD(&cpu_lock));
1719 	cp = cpu[cpuid];
1720 	ASSERT(cp != NULL);
1721 
1722 	ASSERT(cp->cpu_next_onln == cp);
1723 	ASSERT(cp->cpu_prev_onln == cp);
1724 	ASSERT(cp->cpu_next_part == cp);
1725 	ASSERT(cp->cpu_prev_part == cp);
1726 
1727 	/*
1728 	 * Tear down the CPU's physical ID cache, and update any
1729 	 * processor groups
1730 	 */
1731 	pg_cpu_fini(cp);
1732 	pghw_physid_destroy(cp);
1733 
1734 	/*
1735 	 * Destroy kstat stuff.
1736 	 */
1737 	cpu_info_kstat_destroy(cp);
1738 	term_cpu_mstate(cp);
1739 	/*
1740 	 * Free up pause thread.
1741 	 */
1742 	cpu_pause_free(cp);
1743 	CPUSET_DEL(cpu_available, cp->cpu_id);
1744 	cpu[cp->cpu_id] = NULL;
1745 	/*
1746 	 * The clock thread and mutex_vector_enter cannot hold the
1747 	 * cpu_lock while traversing the cpu list, therefore we pause
1748 	 * all other threads by pausing the other cpus. These, and any
1749 	 * other routines holding cpu pointers while possibly sleeping
1750 	 * must be sure to call kpreempt_disable before processing the
1751 	 * list and be sure to check that the cpu has not been deleted
1752 	 * after any sleeps (check cp->cpu_next != NULL). We guarantee
1753 	 * to keep the deleted cpu structure around.
1754 	 *
1755 	 * Note that this MUST be done AFTER cpu_available
1756 	 * has been updated so that we don't waste time
1757 	 * trying to pause the cpu we're trying to delete.
1758 	 */
1759 	(void) pause_cpus(NULL);
1760 
1761 	cpnext = cp->cpu_next;
1762 	cp->cpu_prev->cpu_next = cp->cpu_next;
1763 	cp->cpu_next->cpu_prev = cp->cpu_prev;
1764 	if (cp == cpu_list)
1765 	    cpu_list = cpnext;
1766 
1767 	/*
1768 	 * Signals that the cpu has been deleted (see above).
1769 	 */
1770 	cp->cpu_next = NULL;
1771 	cp->cpu_prev = NULL;
1772 
1773 	start_cpus();
1774 
1775 	CPUSET_DEL(cpu_seqid_inuse, cp->cpu_seqid);
1776 	ncpus--;
1777 	lgrp_config(LGRP_CONFIG_CPU_DEL, (uintptr_t)cp, 0);
1778 
1779 	pool_pset_mod = gethrtime();
1780 }
1781 
1782 /*
1783  * Add a CPU to the list of active CPUs.
1784  *	This routine must not get any locks, because other CPUs are paused.
1785  */
1786 static void
1787 cpu_add_active_internal(cpu_t *cp)
1788 {
1789 	cpupart_t	*pp = cp->cpu_part;
1790 
1791 	ASSERT(MUTEX_HELD(&cpu_lock));
1792 	ASSERT(cpu_list != NULL);	/* list started in cpu_list_init */
1793 
1794 	ncpus_online++;
1795 	cpu_set_state(cp);
1796 	cp->cpu_next_onln = cpu_active;
1797 	cp->cpu_prev_onln = cpu_active->cpu_prev_onln;
1798 	cpu_active->cpu_prev_onln->cpu_next_onln = cp;
1799 	cpu_active->cpu_prev_onln = cp;
1800 
1801 	if (pp->cp_cpulist) {
1802 		cp->cpu_next_part = pp->cp_cpulist;
1803 		cp->cpu_prev_part = pp->cp_cpulist->cpu_prev_part;
1804 		pp->cp_cpulist->cpu_prev_part->cpu_next_part = cp;
1805 		pp->cp_cpulist->cpu_prev_part = cp;
1806 	} else {
1807 		ASSERT(pp->cp_ncpus == 0);
1808 		pp->cp_cpulist = cp->cpu_next_part = cp->cpu_prev_part = cp;
1809 	}
1810 	pp->cp_ncpus++;
1811 	if (pp->cp_ncpus == 1) {
1812 		cp_numparts_nonempty++;
1813 		ASSERT(cp_numparts_nonempty != 0);
1814 	}
1815 
1816 	pg_cpu_active(cp);
1817 	lgrp_config(LGRP_CONFIG_CPU_ONLINE, (uintptr_t)cp, 0);
1818 
1819 	bzero(&cp->cpu_loadavg, sizeof (cp->cpu_loadavg));
1820 }
1821 
1822 /*
1823  * Add a CPU to the list of active CPUs.
1824  *	This is called from machine-dependent layers when a new CPU is started.
1825  */
1826 void
1827 cpu_add_active(cpu_t *cp)
1828 {
1829 	pg_cpupart_in(cp, cp->cpu_part);
1830 
1831 	pause_cpus(NULL);
1832 	cpu_add_active_internal(cp);
1833 	start_cpus();
1834 
1835 	cpu_stats_kstat_create(cp);
1836 	cpu_create_intrstat(cp);
1837 	lgrp_kstat_create(cp);
1838 	cpu_state_change_notify(cp->cpu_id, CPU_INIT);
1839 }
1840 
1841 
1842 /*
1843  * Remove a CPU from the list of active CPUs.
1844  *	This routine must not get any locks, because other CPUs are paused.
1845  */
1846 /* ARGSUSED */
1847 static void
1848 cpu_remove_active(cpu_t *cp)
1849 {
1850 	cpupart_t	*pp = cp->cpu_part;
1851 
1852 	ASSERT(MUTEX_HELD(&cpu_lock));
1853 	ASSERT(cp->cpu_next_onln != cp);	/* not the last one */
1854 	ASSERT(cp->cpu_prev_onln != cp);	/* not the last one */
1855 
1856 	pg_cpu_inactive(cp);
1857 
1858 	lgrp_config(LGRP_CONFIG_CPU_OFFLINE, (uintptr_t)cp, 0);
1859 
1860 	cp->cpu_prev_onln->cpu_next_onln = cp->cpu_next_onln;
1861 	cp->cpu_next_onln->cpu_prev_onln = cp->cpu_prev_onln;
1862 	if (cpu_active == cp) {
1863 		cpu_active = cp->cpu_next_onln;
1864 	}
1865 	cp->cpu_next_onln = cp;
1866 	cp->cpu_prev_onln = cp;
1867 
1868 	cp->cpu_prev_part->cpu_next_part = cp->cpu_next_part;
1869 	cp->cpu_next_part->cpu_prev_part = cp->cpu_prev_part;
1870 	if (pp->cp_cpulist == cp) {
1871 		pp->cp_cpulist = cp->cpu_next_part;
1872 		ASSERT(pp->cp_cpulist != cp);
1873 	}
1874 	cp->cpu_next_part = cp;
1875 	cp->cpu_prev_part = cp;
1876 	pp->cp_ncpus--;
1877 	if (pp->cp_ncpus == 0) {
1878 		cp_numparts_nonempty--;
1879 		ASSERT(cp_numparts_nonempty != 0);
1880 	}
1881 }
1882 
1883 /*
1884  * Routine used to setup a newly inserted CPU in preparation for starting
1885  * it running code.
1886  */
1887 int
1888 cpu_configure(int cpuid)
1889 {
1890 	int retval = 0;
1891 
1892 	ASSERT(MUTEX_HELD(&cpu_lock));
1893 
1894 	/*
1895 	 * Some structures are statically allocated based upon
1896 	 * the maximum number of cpus the system supports.  Do not
1897 	 * try to add anything beyond this limit.
1898 	 */
1899 	if (cpuid < 0 || cpuid >= NCPU) {
1900 		return (EINVAL);
1901 	}
1902 
1903 	if ((cpu[cpuid] != NULL) && (cpu[cpuid]->cpu_flags != 0)) {
1904 		return (EALREADY);
1905 	}
1906 
1907 	if ((retval = mp_cpu_configure(cpuid)) != 0) {
1908 		return (retval);
1909 	}
1910 
1911 	cpu[cpuid]->cpu_flags = CPU_QUIESCED | CPU_OFFLINE | CPU_POWEROFF;
1912 	cpu_set_state(cpu[cpuid]);
1913 	retval = cpu_state_change_hooks(cpuid, CPU_CONFIG, CPU_UNCONFIG);
1914 	if (retval != 0)
1915 		(void) mp_cpu_unconfigure(cpuid);
1916 
1917 	return (retval);
1918 }
1919 
1920 /*
1921  * Routine used to cleanup a CPU that has been powered off.  This will
1922  * destroy all per-cpu information related to this cpu.
1923  */
1924 int
1925 cpu_unconfigure(int cpuid)
1926 {
1927 	int error;
1928 
1929 	ASSERT(MUTEX_HELD(&cpu_lock));
1930 
1931 	if (cpu[cpuid] == NULL) {
1932 		return (ENODEV);
1933 	}
1934 
1935 	if (cpu[cpuid]->cpu_flags == 0) {
1936 		return (EALREADY);
1937 	}
1938 
1939 	if ((cpu[cpuid]->cpu_flags & CPU_POWEROFF) == 0) {
1940 		return (EBUSY);
1941 	}
1942 
1943 	if (cpu[cpuid]->cpu_props != NULL) {
1944 		(void) nvlist_free(cpu[cpuid]->cpu_props);
1945 		cpu[cpuid]->cpu_props = NULL;
1946 	}
1947 
1948 	error = cpu_state_change_hooks(cpuid, CPU_UNCONFIG, CPU_CONFIG);
1949 
1950 	if (error != 0)
1951 		return (error);
1952 
1953 	return (mp_cpu_unconfigure(cpuid));
1954 }
1955 
1956 /*
1957  * Routines for registering and de-registering cpu_setup callback functions.
1958  *
1959  * Caller's context
1960  *	These routines must not be called from a driver's attach(9E) or
1961  *	detach(9E) entry point.
1962  *
1963  * NOTE: CPU callbacks should not block. They are called with cpu_lock held.
1964  */
1965 
1966 /*
1967  * Ideally, these would be dynamically allocated and put into a linked
1968  * list; however that is not feasible because the registration routine
1969  * has to be available before the kmem allocator is working (in fact,
1970  * it is called by the kmem allocator init code).  In any case, there
1971  * are quite a few extra entries for future users.
1972  */
1973 #define	NCPU_SETUPS	20
1974 
1975 struct cpu_setup {
1976 	cpu_setup_func_t *func;
1977 	void *arg;
1978 } cpu_setups[NCPU_SETUPS];
1979 
1980 void
1981 register_cpu_setup_func(cpu_setup_func_t *func, void *arg)
1982 {
1983 	int i;
1984 
1985 	ASSERT(MUTEX_HELD(&cpu_lock));
1986 
1987 	for (i = 0; i < NCPU_SETUPS; i++)
1988 		if (cpu_setups[i].func == NULL)
1989 		    break;
1990 	if (i >= NCPU_SETUPS)
1991 		cmn_err(CE_PANIC, "Ran out of cpu_setup callback entries");
1992 
1993 	cpu_setups[i].func = func;
1994 	cpu_setups[i].arg = arg;
1995 }
1996 
1997 void
1998 unregister_cpu_setup_func(cpu_setup_func_t *func, void *arg)
1999 {
2000 	int i;
2001 
2002 	ASSERT(MUTEX_HELD(&cpu_lock));
2003 
2004 	for (i = 0; i < NCPU_SETUPS; i++)
2005 		if ((cpu_setups[i].func == func) &&
2006 		    (cpu_setups[i].arg == arg))
2007 		    break;
2008 	if (i >= NCPU_SETUPS)
2009 		cmn_err(CE_PANIC, "Could not find cpu_setup callback to "
2010 		    "deregister");
2011 
2012 	cpu_setups[i].func = NULL;
2013 	cpu_setups[i].arg = 0;
2014 }
2015 
2016 /*
2017  * Call any state change hooks for this CPU, ignore any errors.
2018  */
2019 void
2020 cpu_state_change_notify(int id, cpu_setup_t what)
2021 {
2022 	int i;
2023 
2024 	ASSERT(MUTEX_HELD(&cpu_lock));
2025 
2026 	for (i = 0; i < NCPU_SETUPS; i++) {
2027 		if (cpu_setups[i].func != NULL) {
2028 			cpu_setups[i].func(what, id, cpu_setups[i].arg);
2029 		}
2030 	}
2031 }
2032 
2033 /*
2034  * Call any state change hooks for this CPU, undo it if error found.
2035  */
2036 static int
2037 cpu_state_change_hooks(int id, cpu_setup_t what, cpu_setup_t undo)
2038 {
2039 	int i;
2040 	int retval = 0;
2041 
2042 	ASSERT(MUTEX_HELD(&cpu_lock));
2043 
2044 	for (i = 0; i < NCPU_SETUPS; i++) {
2045 		if (cpu_setups[i].func != NULL) {
2046 			retval = cpu_setups[i].func(what, id,
2047 			    cpu_setups[i].arg);
2048 			if (retval) {
2049 				for (i--; i >= 0; i--) {
2050 					if (cpu_setups[i].func != NULL)
2051 						cpu_setups[i].func(undo,
2052 						    id, cpu_setups[i].arg);
2053 				}
2054 				break;
2055 			}
2056 		}
2057 	}
2058 	return (retval);
2059 }
2060 
2061 /*
2062  * Export information about this CPU via the kstat mechanism.
2063  */
2064 static struct {
2065 	kstat_named_t ci_state;
2066 	kstat_named_t ci_state_begin;
2067 	kstat_named_t ci_cpu_type;
2068 	kstat_named_t ci_fpu_type;
2069 	kstat_named_t ci_clock_MHz;
2070 	kstat_named_t ci_chip_id;
2071 	kstat_named_t ci_implementation;
2072 	kstat_named_t ci_brandstr;
2073 	kstat_named_t ci_core_id;
2074 #if defined(__sparcv9)
2075 	kstat_named_t ci_device_ID;
2076 	kstat_named_t ci_cpu_fru;
2077 #endif
2078 #if defined(__x86)
2079 	kstat_named_t ci_vendorstr;
2080 	kstat_named_t ci_family;
2081 	kstat_named_t ci_model;
2082 	kstat_named_t ci_step;
2083 	kstat_named_t ci_clogid;
2084 #endif
2085 } cpu_info_template = {
2086 	{ "state",		KSTAT_DATA_CHAR },
2087 	{ "state_begin",	KSTAT_DATA_LONG },
2088 	{ "cpu_type",		KSTAT_DATA_CHAR },
2089 	{ "fpu_type",		KSTAT_DATA_CHAR },
2090 	{ "clock_MHz",		KSTAT_DATA_LONG },
2091 	{ "chip_id",		KSTAT_DATA_LONG },
2092 	{ "implementation",	KSTAT_DATA_STRING },
2093 	{ "brand",		KSTAT_DATA_STRING },
2094 	{ "core_id",		KSTAT_DATA_LONG },
2095 #if defined(__sparcv9)
2096 	{ "device_ID",		KSTAT_DATA_UINT64 },
2097 	{ "cpu_fru",		KSTAT_DATA_STRING },
2098 #endif
2099 #if defined(__x86)
2100 	{ "vendor_id",		KSTAT_DATA_STRING },
2101 	{ "family",		KSTAT_DATA_INT32 },
2102 	{ "model",		KSTAT_DATA_INT32 },
2103 	{ "stepping",		KSTAT_DATA_INT32 },
2104 	{ "clog_id",		KSTAT_DATA_INT32 },
2105 #endif
2106 };
2107 
2108 static kmutex_t cpu_info_template_lock;
2109 
2110 static int
2111 cpu_info_kstat_update(kstat_t *ksp, int rw)
2112 {
2113 	cpu_t	*cp = ksp->ks_private;
2114 	const char *pi_state;
2115 
2116 	if (rw == KSTAT_WRITE)
2117 		return (EACCES);
2118 
2119 	switch (cp->cpu_type_info.pi_state) {
2120 	case P_ONLINE:
2121 		pi_state = PS_ONLINE;
2122 		break;
2123 	case P_POWEROFF:
2124 		pi_state = PS_POWEROFF;
2125 		break;
2126 	case P_NOINTR:
2127 		pi_state = PS_NOINTR;
2128 		break;
2129 	case P_FAULTED:
2130 		pi_state = PS_FAULTED;
2131 		break;
2132 	case P_SPARE:
2133 		pi_state = PS_SPARE;
2134 		break;
2135 	case P_OFFLINE:
2136 		pi_state = PS_OFFLINE;
2137 		break;
2138 	default:
2139 		pi_state = "unknown";
2140 	}
2141 	(void) strcpy(cpu_info_template.ci_state.value.c, pi_state);
2142 	cpu_info_template.ci_state_begin.value.l = cp->cpu_state_begin;
2143 	(void) strncpy(cpu_info_template.ci_cpu_type.value.c,
2144 	    cp->cpu_type_info.pi_processor_type, 15);
2145 	(void) strncpy(cpu_info_template.ci_fpu_type.value.c,
2146 	    cp->cpu_type_info.pi_fputypes, 15);
2147 	cpu_info_template.ci_clock_MHz.value.l = cp->cpu_type_info.pi_clock;
2148 	cpu_info_template.ci_chip_id.value.l =
2149 	    pg_plat_hw_instance_id(cp, PGHW_CHIP);
2150 	kstat_named_setstr(&cpu_info_template.ci_implementation,
2151 	    cp->cpu_idstr);
2152 	kstat_named_setstr(&cpu_info_template.ci_brandstr, cp->cpu_brandstr);
2153 	cpu_info_template.ci_core_id.value.l = pg_plat_get_core_id(cp);
2154 
2155 #if defined(__sparcv9)
2156 	cpu_info_template.ci_device_ID.value.ui64 =
2157 	    cpunodes[cp->cpu_id].device_id;
2158 	kstat_named_setstr(&cpu_info_template.ci_cpu_fru, cpu_fru_fmri(cp));
2159 #endif
2160 #if defined(__x86)
2161 	kstat_named_setstr(&cpu_info_template.ci_vendorstr,
2162 	    cpuid_getvendorstr(cp));
2163 	cpu_info_template.ci_family.value.l = cpuid_getfamily(cp);
2164 	cpu_info_template.ci_model.value.l = cpuid_getmodel(cp);
2165 	cpu_info_template.ci_step.value.l = cpuid_getstep(cp);
2166 	cpu_info_template.ci_clogid.value.l = cpuid_get_clogid(cp);
2167 #endif
2168 
2169 	return (0);
2170 }
2171 
2172 static void
2173 cpu_info_kstat_create(cpu_t *cp)
2174 {
2175 	zoneid_t zoneid;
2176 
2177 	ASSERT(MUTEX_HELD(&cpu_lock));
2178 
2179 	if (pool_pset_enabled())
2180 		zoneid = GLOBAL_ZONEID;
2181 	else
2182 		zoneid = ALL_ZONES;
2183 	if ((cp->cpu_info_kstat = kstat_create_zone("cpu_info", cp->cpu_id,
2184 	    NULL, "misc", KSTAT_TYPE_NAMED,
2185 		    sizeof (cpu_info_template) / sizeof (kstat_named_t),
2186 		    KSTAT_FLAG_VIRTUAL, zoneid)) != NULL) {
2187 		cp->cpu_info_kstat->ks_data_size += 2 * CPU_IDSTRLEN;
2188 #if defined(__sparcv9)
2189 		cp->cpu_info_kstat->ks_data_size +=
2190 		    strlen(cpu_fru_fmri(cp)) + 1;
2191 #endif
2192 #if defined(__x86)
2193 		cp->cpu_info_kstat->ks_data_size += X86_VENDOR_STRLEN;
2194 #endif
2195 		cp->cpu_info_kstat->ks_lock = &cpu_info_template_lock;
2196 		cp->cpu_info_kstat->ks_data = &cpu_info_template;
2197 		cp->cpu_info_kstat->ks_private = cp;
2198 		cp->cpu_info_kstat->ks_update = cpu_info_kstat_update;
2199 		kstat_install(cp->cpu_info_kstat);
2200 	}
2201 }
2202 
2203 static void
2204 cpu_info_kstat_destroy(cpu_t *cp)
2205 {
2206 	ASSERT(MUTEX_HELD(&cpu_lock));
2207 
2208 	kstat_delete(cp->cpu_info_kstat);
2209 	cp->cpu_info_kstat = NULL;
2210 }
2211 
2212 /*
2213  * Create and install kstats for the boot CPU.
2214  */
2215 void
2216 cpu_kstat_init(cpu_t *cp)
2217 {
2218 	/*
2219 	 * XXX need pg kstats for boot CPU
2220 	 */
2221 	mutex_enter(&cpu_lock);
2222 	cpu_info_kstat_create(cp);
2223 	cpu_stats_kstat_create(cp);
2224 	cpu_create_intrstat(cp);
2225 	cpu_set_state(cp);
2226 	mutex_exit(&cpu_lock);
2227 }
2228 
2229 /*
2230  * Make visible to the zone that subset of the cpu information that would be
2231  * initialized when a cpu is configured (but still offline).
2232  */
2233 void
2234 cpu_visibility_configure(cpu_t *cp, zone_t *zone)
2235 {
2236 	zoneid_t zoneid = zone ? zone->zone_id : ALL_ZONES;
2237 
2238 	ASSERT(MUTEX_HELD(&cpu_lock));
2239 	ASSERT(pool_pset_enabled());
2240 	ASSERT(cp != NULL);
2241 
2242 	if (zoneid != ALL_ZONES && zoneid != GLOBAL_ZONEID) {
2243 		zone->zone_ncpus++;
2244 		ASSERT(zone->zone_ncpus <= ncpus);
2245 	}
2246 	if (cp->cpu_info_kstat != NULL)
2247 		kstat_zone_add(cp->cpu_info_kstat, zoneid);
2248 }
2249 
2250 /*
2251  * Make visible to the zone that subset of the cpu information that would be
2252  * initialized when a previously configured cpu is onlined.
2253  */
2254 void
2255 cpu_visibility_online(cpu_t *cp, zone_t *zone)
2256 {
2257 	kstat_t *ksp;
2258 	char name[sizeof ("cpu_stat") + 10];	/* enough for 32-bit cpuids */
2259 	zoneid_t zoneid = zone ? zone->zone_id : ALL_ZONES;
2260 	processorid_t cpun;
2261 
2262 	ASSERT(MUTEX_HELD(&cpu_lock));
2263 	ASSERT(pool_pset_enabled());
2264 	ASSERT(cp != NULL);
2265 	ASSERT(cpu_is_active(cp));
2266 
2267 	cpun = cp->cpu_id;
2268 	if (zoneid != ALL_ZONES && zoneid != GLOBAL_ZONEID) {
2269 		zone->zone_ncpus_online++;
2270 		ASSERT(zone->zone_ncpus_online <= ncpus_online);
2271 	}
2272 	(void) snprintf(name, sizeof (name), "cpu_stat%d", cpun);
2273 	if ((ksp = kstat_hold_byname("cpu_stat", cpun, name, ALL_ZONES))
2274 	    != NULL) {
2275 		kstat_zone_add(ksp, zoneid);
2276 		kstat_rele(ksp);
2277 	}
2278 	if ((ksp = kstat_hold_byname("cpu", cpun, "sys", ALL_ZONES)) != NULL) {
2279 		kstat_zone_add(ksp, zoneid);
2280 		kstat_rele(ksp);
2281 	}
2282 	if ((ksp = kstat_hold_byname("cpu", cpun, "vm", ALL_ZONES)) != NULL) {
2283 		kstat_zone_add(ksp, zoneid);
2284 		kstat_rele(ksp);
2285 	}
2286 	if ((ksp = kstat_hold_byname("cpu", cpun, "intrstat", ALL_ZONES)) !=
2287 	    NULL) {
2288 		kstat_zone_add(ksp, zoneid);
2289 		kstat_rele(ksp);
2290 	}
2291 }
2292 
2293 /*
2294  * Update relevant kstats such that cpu is now visible to processes
2295  * executing in specified zone.
2296  */
2297 void
2298 cpu_visibility_add(cpu_t *cp, zone_t *zone)
2299 {
2300 	cpu_visibility_configure(cp, zone);
2301 	if (cpu_is_active(cp))
2302 		cpu_visibility_online(cp, zone);
2303 }
2304 
2305 /*
2306  * Make invisible to the zone that subset of the cpu information that would be
2307  * torn down when a previously offlined cpu is unconfigured.
2308  */
2309 void
2310 cpu_visibility_unconfigure(cpu_t *cp, zone_t *zone)
2311 {
2312 	zoneid_t zoneid = zone ? zone->zone_id : ALL_ZONES;
2313 
2314 	ASSERT(MUTEX_HELD(&cpu_lock));
2315 	ASSERT(pool_pset_enabled());
2316 	ASSERT(cp != NULL);
2317 
2318 	if (zoneid != ALL_ZONES && zoneid != GLOBAL_ZONEID) {
2319 		ASSERT(zone->zone_ncpus != 0);
2320 		zone->zone_ncpus--;
2321 	}
2322 	if (cp->cpu_info_kstat)
2323 		kstat_zone_remove(cp->cpu_info_kstat, zoneid);
2324 }
2325 
2326 /*
2327  * Make invisible to the zone that subset of the cpu information that would be
2328  * torn down when a cpu is offlined (but still configured).
2329  */
2330 void
2331 cpu_visibility_offline(cpu_t *cp, zone_t *zone)
2332 {
2333 	kstat_t *ksp;
2334 	char name[sizeof ("cpu_stat") + 10];	/* enough for 32-bit cpuids */
2335 	zoneid_t zoneid = zone ? zone->zone_id : ALL_ZONES;
2336 	processorid_t cpun;
2337 
2338 	ASSERT(MUTEX_HELD(&cpu_lock));
2339 	ASSERT(pool_pset_enabled());
2340 	ASSERT(cp != NULL);
2341 	ASSERT(cpu_is_active(cp));
2342 
2343 	cpun = cp->cpu_id;
2344 	if (zoneid != ALL_ZONES && zoneid != GLOBAL_ZONEID) {
2345 		ASSERT(zone->zone_ncpus_online != 0);
2346 		zone->zone_ncpus_online--;
2347 	}
2348 
2349 	if ((ksp = kstat_hold_byname("cpu", cpun, "intrstat", ALL_ZONES)) !=
2350 	    NULL) {
2351 		kstat_zone_remove(ksp, zoneid);
2352 		kstat_rele(ksp);
2353 	}
2354 	if ((ksp = kstat_hold_byname("cpu", cpun, "vm", ALL_ZONES)) != NULL) {
2355 		kstat_zone_remove(ksp, zoneid);
2356 		kstat_rele(ksp);
2357 	}
2358 	if ((ksp = kstat_hold_byname("cpu", cpun, "sys", ALL_ZONES)) != NULL) {
2359 		kstat_zone_remove(ksp, zoneid);
2360 		kstat_rele(ksp);
2361 	}
2362 	(void) snprintf(name, sizeof (name), "cpu_stat%d", cpun);
2363 	if ((ksp = kstat_hold_byname("cpu_stat", cpun, name, ALL_ZONES))
2364 	    != NULL) {
2365 		kstat_zone_remove(ksp, zoneid);
2366 		kstat_rele(ksp);
2367 	}
2368 }
2369 
2370 /*
2371  * Update relevant kstats such that cpu is no longer visible to processes
2372  * executing in specified zone.
2373  */
2374 void
2375 cpu_visibility_remove(cpu_t *cp, zone_t *zone)
2376 {
2377 	if (cpu_is_active(cp))
2378 		cpu_visibility_offline(cp, zone);
2379 	cpu_visibility_unconfigure(cp, zone);
2380 }
2381 
2382 /*
2383  * Bind a thread to a CPU as requested.
2384  */
2385 int
2386 cpu_bind_thread(kthread_id_t tp, processorid_t bind, processorid_t *obind,
2387     int *error)
2388 {
2389 	processorid_t	binding;
2390 	cpu_t		*cp;
2391 
2392 	ASSERT(MUTEX_HELD(&cpu_lock));
2393 	ASSERT(MUTEX_HELD(&ttoproc(tp)->p_lock));
2394 
2395 	thread_lock(tp);
2396 
2397 	/*
2398 	 * Record old binding, but change the obind, which was initialized
2399 	 * to PBIND_NONE, only if this thread has a binding.  This avoids
2400 	 * reporting PBIND_NONE for a process when some LWPs are bound.
2401 	 */
2402 	binding = tp->t_bind_cpu;
2403 	if (binding != PBIND_NONE)
2404 		*obind = binding;	/* record old binding */
2405 
2406 	if (bind == PBIND_QUERY) {
2407 		thread_unlock(tp);
2408 		return (0);
2409 	}
2410 
2411 	/*
2412 	 * If this thread/LWP cannot be bound because of permission
2413 	 * problems, just note that and return success so that the
2414 	 * other threads/LWPs will be bound.  This is the way
2415 	 * processor_bind() is defined to work.
2416 	 *
2417 	 * Binding will get EPERM if the thread is of system class
2418 	 * or hasprocperm() fails.
2419 	 */
2420 	if (tp->t_cid == 0 || !hasprocperm(tp->t_cred, CRED())) {
2421 		*error = EPERM;
2422 		thread_unlock(tp);
2423 		return (0);
2424 	}
2425 
2426 	binding = bind;
2427 	if (binding != PBIND_NONE) {
2428 		cp = cpu[binding];
2429 		/*
2430 		 * Make sure binding is in right partition.
2431 		 */
2432 		if (tp->t_cpupart != cp->cpu_part) {
2433 			*error = EINVAL;
2434 			thread_unlock(tp);
2435 			return (0);
2436 		}
2437 	}
2438 	tp->t_bind_cpu = binding;	/* set new binding */
2439 
2440 	/*
2441 	 * If there is no system-set reason for affinity, set
2442 	 * the t_bound_cpu field to reflect the binding.
2443 	 */
2444 	if (tp->t_affinitycnt == 0) {
2445 		if (binding == PBIND_NONE) {
2446 			/*
2447 			 * We may need to adjust disp_max_unbound_pri
2448 			 * since we're becoming unbound.
2449 			 */
2450 			disp_adjust_unbound_pri(tp);
2451 
2452 			tp->t_bound_cpu = NULL;	/* set new binding */
2453 
2454 			/*
2455 			 * Move thread to lgroup with strongest affinity
2456 			 * after unbinding
2457 			 */
2458 			if (tp->t_lgrp_affinity)
2459 				lgrp_move_thread(tp,
2460 				    lgrp_choose(tp, tp->t_cpupart), 1);
2461 
2462 			if (tp->t_state == TS_ONPROC &&
2463 			    tp->t_cpu->cpu_part != tp->t_cpupart)
2464 				cpu_surrender(tp);
2465 		} else {
2466 			lpl_t	*lpl;
2467 
2468 			tp->t_bound_cpu = cp;
2469 			ASSERT(cp->cpu_lpl != NULL);
2470 
2471 			/*
2472 			 * Set home to lgroup with most affinity containing CPU
2473 			 * that thread is being bound or minimum bounding
2474 			 * lgroup if no affinities set
2475 			 */
2476 			if (tp->t_lgrp_affinity)
2477 				lpl = lgrp_affinity_best(tp, tp->t_cpupart,
2478 				    LGRP_NONE, B_FALSE);
2479 			else
2480 				lpl = cp->cpu_lpl;
2481 
2482 			if (tp->t_lpl != lpl) {
2483 				/* can't grab cpu_lock */
2484 				lgrp_move_thread(tp, lpl, 1);
2485 			}
2486 
2487 			/*
2488 			 * Make the thread switch to the bound CPU.
2489 			 * If the thread is runnable, we need to
2490 			 * requeue it even if t_cpu is already set
2491 			 * to the right CPU, since it may be on a
2492 			 * kpreempt queue and need to move to a local
2493 			 * queue.  We could check t_disp_queue to
2494 			 * avoid unnecessary overhead if it's already
2495 			 * on the right queue, but since this isn't
2496 			 * a performance-critical operation it doesn't
2497 			 * seem worth the extra code and complexity.
2498 			 *
2499 			 * If the thread is weakbound to the cpu then it will
2500 			 * resist the new binding request until the weak
2501 			 * binding drops.  The cpu_surrender or requeueing
2502 			 * below could be skipped in such cases (since it
2503 			 * will have no effect), but that would require
2504 			 * thread_allowmigrate to acquire thread_lock so
2505 			 * we'll take the very occasional hit here instead.
2506 			 */
2507 			if (tp->t_state == TS_ONPROC) {
2508 				cpu_surrender(tp);
2509 			} else if (tp->t_state == TS_RUN) {
2510 				cpu_t *ocp = tp->t_cpu;
2511 
2512 				(void) dispdeq(tp);
2513 				setbackdq(tp);
2514 				/*
2515 				 * Either on the bound CPU's disp queue now,
2516 				 * or swapped out or on the swap queue.
2517 				 */
2518 				ASSERT(tp->t_disp_queue == cp->cpu_disp ||
2519 				    tp->t_weakbound_cpu == ocp ||
2520 				    (tp->t_schedflag & (TS_LOAD | TS_ON_SWAPQ))
2521 				    != TS_LOAD);
2522 			}
2523 		}
2524 	}
2525 
2526 	/*
2527 	 * Our binding has changed; set TP_CHANGEBIND.
2528 	 */
2529 	tp->t_proc_flag |= TP_CHANGEBIND;
2530 	aston(tp);
2531 
2532 	thread_unlock(tp);
2533 
2534 	return (0);
2535 }
2536 
2537 #if CPUSET_WORDS > 1
2538 
2539 /*
2540  * Functions for implementing cpuset operations when a cpuset is more
2541  * than one word.  On platforms where a cpuset is a single word these
2542  * are implemented as macros in cpuvar.h.
2543  */
2544 
2545 void
2546 cpuset_all(cpuset_t *s)
2547 {
2548 	int i;
2549 
2550 	for (i = 0; i < CPUSET_WORDS; i++)
2551 		s->cpub[i] = ~0UL;
2552 }
2553 
2554 void
2555 cpuset_all_but(cpuset_t *s, uint_t cpu)
2556 {
2557 	cpuset_all(s);
2558 	CPUSET_DEL(*s, cpu);
2559 }
2560 
2561 void
2562 cpuset_only(cpuset_t *s, uint_t cpu)
2563 {
2564 	CPUSET_ZERO(*s);
2565 	CPUSET_ADD(*s, cpu);
2566 }
2567 
2568 int
2569 cpuset_isnull(cpuset_t *s)
2570 {
2571 	int i;
2572 
2573 	for (i = 0; i < CPUSET_WORDS; i++)
2574 		if (s->cpub[i] != 0)
2575 			return (0);
2576 	return (1);
2577 }
2578 
2579 int
2580 cpuset_cmp(cpuset_t *s1, cpuset_t *s2)
2581 {
2582 	int i;
2583 
2584 	for (i = 0; i < CPUSET_WORDS; i++)
2585 		if (s1->cpub[i] != s2->cpub[i])
2586 			return (0);
2587 	return (1);
2588 }
2589 
2590 uint_t
2591 cpuset_find(cpuset_t *s)
2592 {
2593 
2594 	uint_t	i;
2595 	uint_t	cpu = (uint_t)-1;
2596 
2597 	/*
2598 	 * Find a cpu in the cpuset
2599 	 */
2600 	for (i = 0; i < CPUSET_WORDS; i++) {
2601 		cpu = (uint_t)(lowbit(s->cpub[i]) - 1);
2602 		if (cpu != (uint_t)-1) {
2603 			cpu += i * BT_NBIPUL;
2604 			break;
2605 		}
2606 	}
2607 	return (cpu);
2608 }
2609 
2610 void
2611 cpuset_bounds(cpuset_t *s, uint_t *smallestid, uint_t *largestid)
2612 {
2613 	int	i, j;
2614 	uint_t	bit;
2615 
2616 	/*
2617 	 * First, find the smallest cpu id in the set.
2618 	 */
2619 	for (i = 0; i < CPUSET_WORDS; i++) {
2620 		if (s->cpub[i] != 0) {
2621 			bit = (uint_t)(lowbit(s->cpub[i]) - 1);
2622 			ASSERT(bit != (uint_t)-1);
2623 			*smallestid = bit + (i * BT_NBIPUL);
2624 
2625 			/*
2626 			 * Now find the largest cpu id in
2627 			 * the set and return immediately.
2628 			 * Done in an inner loop to avoid
2629 			 * having to break out of the first
2630 			 * loop.
2631 			 */
2632 			for (j = CPUSET_WORDS - 1; j >= i; j--) {
2633 				if (s->cpub[j] != 0) {
2634 					bit = (uint_t)(highbit(s->cpub[j]) - 1);
2635 					ASSERT(bit != (uint_t)-1);
2636 					*largestid = bit + (j * BT_NBIPUL);
2637 					ASSERT(*largestid >= *smallestid);
2638 					return;
2639 				}
2640 			}
2641 
2642 			/*
2643 			 * If this code is reached, a
2644 			 * smallestid was found, but not a
2645 			 * largestid. The cpuset must have
2646 			 * been changed during the course
2647 			 * of this function call.
2648 			 */
2649 			ASSERT(0);
2650 		}
2651 	}
2652 	*smallestid = *largestid = CPUSET_NOTINSET;
2653 }
2654 
2655 #endif	/* CPUSET_WORDS */
2656 
2657 /*
2658  * Unbind all user threads bound to a given CPU.
2659  */
2660 int
2661 cpu_unbind(processorid_t cpu)
2662 {
2663 	processorid_t obind;
2664 	kthread_t *tp;
2665 	int ret = 0;
2666 	proc_t *pp;
2667 	int err, berr = 0;
2668 
2669 	ASSERT(MUTEX_HELD(&cpu_lock));
2670 
2671 	mutex_enter(&pidlock);
2672 	for (pp = practive; pp != NULL; pp = pp->p_next) {
2673 		mutex_enter(&pp->p_lock);
2674 		tp = pp->p_tlist;
2675 		/*
2676 		 * Skip zombies, kernel processes, and processes in
2677 		 * other zones, if called from a non-global zone.
2678 		 */
2679 		if (tp == NULL || (pp->p_flag & SSYS) ||
2680 		    !HASZONEACCESS(curproc, pp->p_zone->zone_id)) {
2681 			mutex_exit(&pp->p_lock);
2682 			continue;
2683 		}
2684 		do {
2685 			if (tp->t_bind_cpu != cpu)
2686 				continue;
2687 			err = cpu_bind_thread(tp, PBIND_NONE, &obind, &berr);
2688 			if (ret == 0)
2689 				ret = err;
2690 		} while ((tp = tp->t_forw) != pp->p_tlist);
2691 		mutex_exit(&pp->p_lock);
2692 	}
2693 	mutex_exit(&pidlock);
2694 	if (ret == 0)
2695 		ret = berr;
2696 	return (ret);
2697 }
2698 
2699 
2700 /*
2701  * Destroy all remaining bound threads on a cpu.
2702  */
2703 void
2704 cpu_destroy_bound_threads(cpu_t *cp)
2705 {
2706 	extern id_t syscid;
2707 	register kthread_id_t	t, tlist, tnext;
2708 
2709 	/*
2710 	 * Destroy all remaining bound threads on the cpu.  This
2711 	 * should include both the interrupt threads and the idle thread.
2712 	 * This requires some care, since we need to traverse the
2713 	 * thread list with the pidlock mutex locked, but thread_free
2714 	 * also locks the pidlock mutex.  So, we collect the threads
2715 	 * we're going to reap in a list headed by "tlist", then we
2716 	 * unlock the pidlock mutex and traverse the tlist list,
2717 	 * doing thread_free's on the thread's.	 Simple, n'est pas?
2718 	 * Also, this depends on thread_free not mucking with the
2719 	 * t_next and t_prev links of the thread.
2720 	 */
2721 
2722 	if ((t = curthread) != NULL) {
2723 
2724 		tlist = NULL;
2725 		mutex_enter(&pidlock);
2726 		do {
2727 			tnext = t->t_next;
2728 			if (t->t_bound_cpu == cp) {
2729 
2730 				/*
2731 				 * We've found a bound thread, carefully unlink
2732 				 * it out of the thread list, and add it to
2733 				 * our "tlist".	 We "know" we don't have to
2734 				 * worry about unlinking curthread (the thread
2735 				 * that is executing this code).
2736 				 */
2737 				t->t_next->t_prev = t->t_prev;
2738 				t->t_prev->t_next = t->t_next;
2739 				t->t_next = tlist;
2740 				tlist = t;
2741 				ASSERT(t->t_cid == syscid);
2742 				/* wake up anyone blocked in thread_join */
2743 				cv_broadcast(&t->t_joincv);
2744 				/*
2745 				 * t_lwp set by interrupt threads and not
2746 				 * cleared.
2747 				 */
2748 				t->t_lwp = NULL;
2749 				/*
2750 				 * Pause and idle threads always have
2751 				 * t_state set to TS_ONPROC.
2752 				 */
2753 				t->t_state = TS_FREE;
2754 				t->t_prev = NULL;	/* Just in case */
2755 			}
2756 
2757 		} while ((t = tnext) != curthread);
2758 
2759 		mutex_exit(&pidlock);
2760 
2761 
2762 		for (t = tlist; t != NULL; t = tnext) {
2763 			tnext = t->t_next;
2764 			thread_free(t);
2765 		}
2766 	}
2767 }
2768 
2769 /*
2770  * processor_info(2) and p_online(2) status support functions
2771  *   The constants returned by the cpu_get_state() and cpu_get_state_str() are
2772  *   for use in communicating processor state information to userland.  Kernel
2773  *   subsystems should only be using the cpu_flags value directly.  Subsystems
2774  *   modifying cpu_flags should record the state change via a call to the
2775  *   cpu_set_state().
2776  */
2777 
2778 /*
2779  * Update the pi_state of this CPU.  This function provides the CPU status for
2780  * the information returned by processor_info(2).
2781  */
2782 void
2783 cpu_set_state(cpu_t *cpu)
2784 {
2785 	ASSERT(MUTEX_HELD(&cpu_lock));
2786 	cpu->cpu_type_info.pi_state = cpu_get_state(cpu);
2787 	cpu->cpu_state_begin = gethrestime_sec();
2788 	pool_cpu_mod = gethrtime();
2789 }
2790 
2791 /*
2792  * Return offline/online/other status for the indicated CPU.  Use only for
2793  * communication with user applications; cpu_flags provides the in-kernel
2794  * interface.
2795  */
2796 int
2797 cpu_get_state(cpu_t *cpu)
2798 {
2799 	ASSERT(MUTEX_HELD(&cpu_lock));
2800 	if (cpu->cpu_flags & CPU_POWEROFF)
2801 		return (P_POWEROFF);
2802 	else if (cpu->cpu_flags & CPU_FAULTED)
2803 		return (P_FAULTED);
2804 	else if (cpu->cpu_flags & CPU_SPARE)
2805 		return (P_SPARE);
2806 	else if ((cpu->cpu_flags & (CPU_READY | CPU_OFFLINE)) != CPU_READY)
2807 		return (P_OFFLINE);
2808 	else if (cpu->cpu_flags & CPU_ENABLE)
2809 		return (P_ONLINE);
2810 	else
2811 		return (P_NOINTR);
2812 }
2813 
2814 /*
2815  * Return processor_info(2) state as a string.
2816  */
2817 const char *
2818 cpu_get_state_str(cpu_t *cpu)
2819 {
2820 	const char *string;
2821 
2822 	switch (cpu_get_state(cpu)) {
2823 	case P_ONLINE:
2824 		string = PS_ONLINE;
2825 		break;
2826 	case P_POWEROFF:
2827 		string = PS_POWEROFF;
2828 		break;
2829 	case P_NOINTR:
2830 		string = PS_NOINTR;
2831 		break;
2832 	case P_SPARE:
2833 		string = PS_SPARE;
2834 		break;
2835 	case P_FAULTED:
2836 		string = PS_FAULTED;
2837 		break;
2838 	case P_OFFLINE:
2839 		string = PS_OFFLINE;
2840 		break;
2841 	default:
2842 		string = "unknown";
2843 		break;
2844 	}
2845 	return (string);
2846 }
2847 
2848 /*
2849  * Export this CPU's statistics (cpu_stat_t and cpu_stats_t) as raw and named
2850  * kstats, respectively.  This is done when a CPU is initialized or placed
2851  * online via p_online(2).
2852  */
2853 static void
2854 cpu_stats_kstat_create(cpu_t *cp)
2855 {
2856 	int 	instance = cp->cpu_id;
2857 	char 	*module = "cpu";
2858 	char 	*class = "misc";
2859 	kstat_t	*ksp;
2860 	zoneid_t zoneid;
2861 
2862 	ASSERT(MUTEX_HELD(&cpu_lock));
2863 
2864 	if (pool_pset_enabled())
2865 		zoneid = GLOBAL_ZONEID;
2866 	else
2867 		zoneid = ALL_ZONES;
2868 	/*
2869 	 * Create named kstats
2870 	 */
2871 #define	CPU_STATS_KS_CREATE(name, tsize, update_func)                    \
2872 	ksp = kstat_create_zone(module, instance, (name), class,         \
2873 	    KSTAT_TYPE_NAMED, (tsize) / sizeof (kstat_named_t), 0,       \
2874 	    zoneid);                                                     \
2875 	if (ksp != NULL) {                                               \
2876 		ksp->ks_private = cp;                                    \
2877 		ksp->ks_update = (update_func);                          \
2878 		kstat_install(ksp);                                      \
2879 	} else                                                           \
2880 		cmn_err(CE_WARN, "cpu: unable to create %s:%d:%s kstat", \
2881 		    module, instance, (name));
2882 
2883 	CPU_STATS_KS_CREATE("sys", sizeof (cpu_sys_stats_ks_data_template),
2884 	    cpu_sys_stats_ks_update);
2885 	CPU_STATS_KS_CREATE("vm", sizeof (cpu_vm_stats_ks_data_template),
2886 	    cpu_vm_stats_ks_update);
2887 
2888 	/*
2889 	 * Export the familiar cpu_stat_t KSTAT_TYPE_RAW kstat.
2890 	 */
2891 	ksp = kstat_create_zone("cpu_stat", cp->cpu_id, NULL,
2892 	    "misc", KSTAT_TYPE_RAW, sizeof (cpu_stat_t), 0, zoneid);
2893 	if (ksp != NULL) {
2894 		ksp->ks_update = cpu_stat_ks_update;
2895 		ksp->ks_private = cp;
2896 		kstat_install(ksp);
2897 	}
2898 }
2899 
2900 static void
2901 cpu_stats_kstat_destroy(cpu_t *cp)
2902 {
2903 	char ks_name[KSTAT_STRLEN];
2904 
2905 	(void) sprintf(ks_name, "cpu_stat%d", cp->cpu_id);
2906 	kstat_delete_byname("cpu_stat", cp->cpu_id, ks_name);
2907 
2908 	kstat_delete_byname("cpu", cp->cpu_id, "sys");
2909 	kstat_delete_byname("cpu", cp->cpu_id, "vm");
2910 }
2911 
2912 static int
2913 cpu_sys_stats_ks_update(kstat_t *ksp, int rw)
2914 {
2915 	cpu_t *cp = (cpu_t *)ksp->ks_private;
2916 	struct cpu_sys_stats_ks_data *csskd;
2917 	cpu_sys_stats_t *css;
2918 	hrtime_t msnsecs[NCMSTATES];
2919 	int	i;
2920 
2921 	if (rw == KSTAT_WRITE)
2922 		return (EACCES);
2923 
2924 	csskd = ksp->ks_data;
2925 	css = &cp->cpu_stats.sys;
2926 
2927 	/*
2928 	 * Read CPU mstate, but compare with the last values we
2929 	 * received to make sure that the returned kstats never
2930 	 * decrease.
2931 	 */
2932 
2933 	get_cpu_mstate(cp, msnsecs);
2934 	if (csskd->cpu_nsec_idle.value.ui64 > msnsecs[CMS_IDLE])
2935 		msnsecs[CMS_IDLE] = csskd->cpu_nsec_idle.value.ui64;
2936 	if (csskd->cpu_nsec_user.value.ui64 > msnsecs[CMS_USER])
2937 		msnsecs[CMS_USER] = csskd->cpu_nsec_user.value.ui64;
2938 	if (csskd->cpu_nsec_kernel.value.ui64 > msnsecs[CMS_SYSTEM])
2939 		msnsecs[CMS_SYSTEM] = csskd->cpu_nsec_kernel.value.ui64;
2940 
2941 	bcopy(&cpu_sys_stats_ks_data_template, ksp->ks_data,
2942 	    sizeof (cpu_sys_stats_ks_data_template));
2943 
2944 	csskd->cpu_ticks_wait.value.ui64 = 0;
2945 	csskd->wait_ticks_io.value.ui64 = 0;
2946 
2947 	csskd->cpu_nsec_idle.value.ui64 = msnsecs[CMS_IDLE];
2948 	csskd->cpu_nsec_user.value.ui64 = msnsecs[CMS_USER];
2949 	csskd->cpu_nsec_kernel.value.ui64 = msnsecs[CMS_SYSTEM];
2950 	csskd->cpu_ticks_idle.value.ui64 =
2951 	    NSEC_TO_TICK(csskd->cpu_nsec_idle.value.ui64);
2952 	csskd->cpu_ticks_user.value.ui64 =
2953 	    NSEC_TO_TICK(csskd->cpu_nsec_user.value.ui64);
2954 	csskd->cpu_ticks_kernel.value.ui64 =
2955 	    NSEC_TO_TICK(csskd->cpu_nsec_kernel.value.ui64);
2956 	csskd->bread.value.ui64 = css->bread;
2957 	csskd->bwrite.value.ui64 = css->bwrite;
2958 	csskd->lread.value.ui64 = css->lread;
2959 	csskd->lwrite.value.ui64 = css->lwrite;
2960 	csskd->phread.value.ui64 = css->phread;
2961 	csskd->phwrite.value.ui64 = css->phwrite;
2962 	csskd->pswitch.value.ui64 = css->pswitch;
2963 	csskd->trap.value.ui64 = css->trap;
2964 	csskd->intr.value.ui64 = 0;
2965 	for (i = 0; i < PIL_MAX; i++)
2966 		csskd->intr.value.ui64 += css->intr[i];
2967 	csskd->syscall.value.ui64 = css->syscall;
2968 	csskd->sysread.value.ui64 = css->sysread;
2969 	csskd->syswrite.value.ui64 = css->syswrite;
2970 	csskd->sysfork.value.ui64 = css->sysfork;
2971 	csskd->sysvfork.value.ui64 = css->sysvfork;
2972 	csskd->sysexec.value.ui64 = css->sysexec;
2973 	csskd->readch.value.ui64 = css->readch;
2974 	csskd->writech.value.ui64 = css->writech;
2975 	csskd->rcvint.value.ui64 = css->rcvint;
2976 	csskd->xmtint.value.ui64 = css->xmtint;
2977 	csskd->mdmint.value.ui64 = css->mdmint;
2978 	csskd->rawch.value.ui64 = css->rawch;
2979 	csskd->canch.value.ui64 = css->canch;
2980 	csskd->outch.value.ui64 = css->outch;
2981 	csskd->msg.value.ui64 = css->msg;
2982 	csskd->sema.value.ui64 = css->sema;
2983 	csskd->namei.value.ui64 = css->namei;
2984 	csskd->ufsiget.value.ui64 = css->ufsiget;
2985 	csskd->ufsdirblk.value.ui64 = css->ufsdirblk;
2986 	csskd->ufsipage.value.ui64 = css->ufsipage;
2987 	csskd->ufsinopage.value.ui64 = css->ufsinopage;
2988 	csskd->procovf.value.ui64 = css->procovf;
2989 	csskd->intrthread.value.ui64 = 0;
2990 	for (i = 0; i < LOCK_LEVEL; i++)
2991 		csskd->intrthread.value.ui64 += css->intr[i];
2992 	csskd->intrblk.value.ui64 = css->intrblk;
2993 	csskd->intrunpin.value.ui64 = css->intrunpin;
2994 	csskd->idlethread.value.ui64 = css->idlethread;
2995 	csskd->inv_swtch.value.ui64 = css->inv_swtch;
2996 	csskd->nthreads.value.ui64 = css->nthreads;
2997 	csskd->cpumigrate.value.ui64 = css->cpumigrate;
2998 	csskd->xcalls.value.ui64 = css->xcalls;
2999 	csskd->mutex_adenters.value.ui64 = css->mutex_adenters;
3000 	csskd->rw_rdfails.value.ui64 = css->rw_rdfails;
3001 	csskd->rw_wrfails.value.ui64 = css->rw_wrfails;
3002 	csskd->modload.value.ui64 = css->modload;
3003 	csskd->modunload.value.ui64 = css->modunload;
3004 	csskd->bawrite.value.ui64 = css->bawrite;
3005 	csskd->iowait.value.ui64 = css->iowait;
3006 
3007 	return (0);
3008 }
3009 
3010 static int
3011 cpu_vm_stats_ks_update(kstat_t *ksp, int rw)
3012 {
3013 	cpu_t *cp = (cpu_t *)ksp->ks_private;
3014 	struct cpu_vm_stats_ks_data *cvskd;
3015 	cpu_vm_stats_t *cvs;
3016 
3017 	if (rw == KSTAT_WRITE)
3018 		return (EACCES);
3019 
3020 	cvs = &cp->cpu_stats.vm;
3021 	cvskd = ksp->ks_data;
3022 
3023 	bcopy(&cpu_vm_stats_ks_data_template, ksp->ks_data,
3024 	    sizeof (cpu_vm_stats_ks_data_template));
3025 	cvskd->pgrec.value.ui64 = cvs->pgrec;
3026 	cvskd->pgfrec.value.ui64 = cvs->pgfrec;
3027 	cvskd->pgin.value.ui64 = cvs->pgin;
3028 	cvskd->pgpgin.value.ui64 = cvs->pgpgin;
3029 	cvskd->pgout.value.ui64 = cvs->pgout;
3030 	cvskd->pgpgout.value.ui64 = cvs->pgpgout;
3031 	cvskd->swapin.value.ui64 = cvs->swapin;
3032 	cvskd->pgswapin.value.ui64 = cvs->pgswapin;
3033 	cvskd->swapout.value.ui64 = cvs->swapout;
3034 	cvskd->pgswapout.value.ui64 = cvs->pgswapout;
3035 	cvskd->zfod.value.ui64 = cvs->zfod;
3036 	cvskd->dfree.value.ui64 = cvs->dfree;
3037 	cvskd->scan.value.ui64 = cvs->scan;
3038 	cvskd->rev.value.ui64 = cvs->rev;
3039 	cvskd->hat_fault.value.ui64 = cvs->hat_fault;
3040 	cvskd->as_fault.value.ui64 = cvs->as_fault;
3041 	cvskd->maj_fault.value.ui64 = cvs->maj_fault;
3042 	cvskd->cow_fault.value.ui64 = cvs->cow_fault;
3043 	cvskd->prot_fault.value.ui64 = cvs->prot_fault;
3044 	cvskd->softlock.value.ui64 = cvs->softlock;
3045 	cvskd->kernel_asflt.value.ui64 = cvs->kernel_asflt;
3046 	cvskd->pgrrun.value.ui64 = cvs->pgrrun;
3047 	cvskd->execpgin.value.ui64 = cvs->execpgin;
3048 	cvskd->execpgout.value.ui64 = cvs->execpgout;
3049 	cvskd->execfree.value.ui64 = cvs->execfree;
3050 	cvskd->anonpgin.value.ui64 = cvs->anonpgin;
3051 	cvskd->anonpgout.value.ui64 = cvs->anonpgout;
3052 	cvskd->anonfree.value.ui64 = cvs->anonfree;
3053 	cvskd->fspgin.value.ui64 = cvs->fspgin;
3054 	cvskd->fspgout.value.ui64 = cvs->fspgout;
3055 	cvskd->fsfree.value.ui64 = cvs->fsfree;
3056 
3057 	return (0);
3058 }
3059 
3060 static int
3061 cpu_stat_ks_update(kstat_t *ksp, int rw)
3062 {
3063 	cpu_stat_t *cso;
3064 	cpu_t *cp;
3065 	int i;
3066 	hrtime_t msnsecs[NCMSTATES];
3067 
3068 	cso = (cpu_stat_t *)ksp->ks_data;
3069 	cp = (cpu_t *)ksp->ks_private;
3070 
3071 	if (rw == KSTAT_WRITE)
3072 		return (EACCES);
3073 
3074 	/*
3075 	 * Read CPU mstate, but compare with the last values we
3076 	 * received to make sure that the returned kstats never
3077 	 * decrease.
3078 	 */
3079 
3080 	get_cpu_mstate(cp, msnsecs);
3081 	msnsecs[CMS_IDLE] = NSEC_TO_TICK(msnsecs[CMS_IDLE]);
3082 	msnsecs[CMS_USER] = NSEC_TO_TICK(msnsecs[CMS_USER]);
3083 	msnsecs[CMS_SYSTEM] = NSEC_TO_TICK(msnsecs[CMS_SYSTEM]);
3084 	if (cso->cpu_sysinfo.cpu[CPU_IDLE] < msnsecs[CMS_IDLE])
3085 		cso->cpu_sysinfo.cpu[CPU_IDLE] = msnsecs[CMS_IDLE];
3086 	if (cso->cpu_sysinfo.cpu[CPU_USER] < msnsecs[CMS_USER])
3087 		cso->cpu_sysinfo.cpu[CPU_USER] = msnsecs[CMS_USER];
3088 	if (cso->cpu_sysinfo.cpu[CPU_KERNEL] < msnsecs[CMS_SYSTEM])
3089 		cso->cpu_sysinfo.cpu[CPU_KERNEL] = msnsecs[CMS_SYSTEM];
3090 	cso->cpu_sysinfo.cpu[CPU_WAIT] 	= 0;
3091 	cso->cpu_sysinfo.wait[W_IO] 	= 0;
3092 	cso->cpu_sysinfo.wait[W_SWAP]	= 0;
3093 	cso->cpu_sysinfo.wait[W_PIO]	= 0;
3094 	cso->cpu_sysinfo.bread 		= CPU_STATS(cp, sys.bread);
3095 	cso->cpu_sysinfo.bwrite 	= CPU_STATS(cp, sys.bwrite);
3096 	cso->cpu_sysinfo.lread 		= CPU_STATS(cp, sys.lread);
3097 	cso->cpu_sysinfo.lwrite 	= CPU_STATS(cp, sys.lwrite);
3098 	cso->cpu_sysinfo.phread 	= CPU_STATS(cp, sys.phread);
3099 	cso->cpu_sysinfo.phwrite 	= CPU_STATS(cp, sys.phwrite);
3100 	cso->cpu_sysinfo.pswitch 	= CPU_STATS(cp, sys.pswitch);
3101 	cso->cpu_sysinfo.trap 		= CPU_STATS(cp, sys.trap);
3102 	cso->cpu_sysinfo.intr		= 0;
3103 	for (i = 0; i < PIL_MAX; i++)
3104 		cso->cpu_sysinfo.intr += CPU_STATS(cp, sys.intr[i]);
3105 	cso->cpu_sysinfo.syscall	= CPU_STATS(cp, sys.syscall);
3106 	cso->cpu_sysinfo.sysread	= CPU_STATS(cp, sys.sysread);
3107 	cso->cpu_sysinfo.syswrite	= CPU_STATS(cp, sys.syswrite);
3108 	cso->cpu_sysinfo.sysfork	= CPU_STATS(cp, sys.sysfork);
3109 	cso->cpu_sysinfo.sysvfork	= CPU_STATS(cp, sys.sysvfork);
3110 	cso->cpu_sysinfo.sysexec	= CPU_STATS(cp, sys.sysexec);
3111 	cso->cpu_sysinfo.readch		= CPU_STATS(cp, sys.readch);
3112 	cso->cpu_sysinfo.writech	= CPU_STATS(cp, sys.writech);
3113 	cso->cpu_sysinfo.rcvint		= CPU_STATS(cp, sys.rcvint);
3114 	cso->cpu_sysinfo.xmtint		= CPU_STATS(cp, sys.xmtint);
3115 	cso->cpu_sysinfo.mdmint		= CPU_STATS(cp, sys.mdmint);
3116 	cso->cpu_sysinfo.rawch		= CPU_STATS(cp, sys.rawch);
3117 	cso->cpu_sysinfo.canch		= CPU_STATS(cp, sys.canch);
3118 	cso->cpu_sysinfo.outch		= CPU_STATS(cp, sys.outch);
3119 	cso->cpu_sysinfo.msg		= CPU_STATS(cp, sys.msg);
3120 	cso->cpu_sysinfo.sema		= CPU_STATS(cp, sys.sema);
3121 	cso->cpu_sysinfo.namei		= CPU_STATS(cp, sys.namei);
3122 	cso->cpu_sysinfo.ufsiget	= CPU_STATS(cp, sys.ufsiget);
3123 	cso->cpu_sysinfo.ufsdirblk	= CPU_STATS(cp, sys.ufsdirblk);
3124 	cso->cpu_sysinfo.ufsipage	= CPU_STATS(cp, sys.ufsipage);
3125 	cso->cpu_sysinfo.ufsinopage	= CPU_STATS(cp, sys.ufsinopage);
3126 	cso->cpu_sysinfo.inodeovf	= 0;
3127 	cso->cpu_sysinfo.fileovf	= 0;
3128 	cso->cpu_sysinfo.procovf	= CPU_STATS(cp, sys.procovf);
3129 	cso->cpu_sysinfo.intrthread	= 0;
3130 	for (i = 0; i < LOCK_LEVEL; i++)
3131 		cso->cpu_sysinfo.intrthread += CPU_STATS(cp, sys.intr[i]);
3132 	cso->cpu_sysinfo.intrblk	= CPU_STATS(cp, sys.intrblk);
3133 	cso->cpu_sysinfo.idlethread	= CPU_STATS(cp, sys.idlethread);
3134 	cso->cpu_sysinfo.inv_swtch	= CPU_STATS(cp, sys.inv_swtch);
3135 	cso->cpu_sysinfo.nthreads	= CPU_STATS(cp, sys.nthreads);
3136 	cso->cpu_sysinfo.cpumigrate	= CPU_STATS(cp, sys.cpumigrate);
3137 	cso->cpu_sysinfo.xcalls		= CPU_STATS(cp, sys.xcalls);
3138 	cso->cpu_sysinfo.mutex_adenters	= CPU_STATS(cp, sys.mutex_adenters);
3139 	cso->cpu_sysinfo.rw_rdfails	= CPU_STATS(cp, sys.rw_rdfails);
3140 	cso->cpu_sysinfo.rw_wrfails	= CPU_STATS(cp, sys.rw_wrfails);
3141 	cso->cpu_sysinfo.modload	= CPU_STATS(cp, sys.modload);
3142 	cso->cpu_sysinfo.modunload	= CPU_STATS(cp, sys.modunload);
3143 	cso->cpu_sysinfo.bawrite	= CPU_STATS(cp, sys.bawrite);
3144 	cso->cpu_sysinfo.rw_enters	= 0;
3145 	cso->cpu_sysinfo.win_uo_cnt	= 0;
3146 	cso->cpu_sysinfo.win_uu_cnt	= 0;
3147 	cso->cpu_sysinfo.win_so_cnt	= 0;
3148 	cso->cpu_sysinfo.win_su_cnt	= 0;
3149 	cso->cpu_sysinfo.win_suo_cnt	= 0;
3150 
3151 	cso->cpu_syswait.iowait		= CPU_STATS(cp, sys.iowait);
3152 	cso->cpu_syswait.swap		= 0;
3153 	cso->cpu_syswait.physio		= 0;
3154 
3155 	cso->cpu_vminfo.pgrec		= CPU_STATS(cp, vm.pgrec);
3156 	cso->cpu_vminfo.pgfrec		= CPU_STATS(cp, vm.pgfrec);
3157 	cso->cpu_vminfo.pgin		= CPU_STATS(cp, vm.pgin);
3158 	cso->cpu_vminfo.pgpgin		= CPU_STATS(cp, vm.pgpgin);
3159 	cso->cpu_vminfo.pgout		= CPU_STATS(cp, vm.pgout);
3160 	cso->cpu_vminfo.pgpgout		= CPU_STATS(cp, vm.pgpgout);
3161 	cso->cpu_vminfo.swapin		= CPU_STATS(cp, vm.swapin);
3162 	cso->cpu_vminfo.pgswapin	= CPU_STATS(cp, vm.pgswapin);
3163 	cso->cpu_vminfo.swapout		= CPU_STATS(cp, vm.swapout);
3164 	cso->cpu_vminfo.pgswapout	= CPU_STATS(cp, vm.pgswapout);
3165 	cso->cpu_vminfo.zfod		= CPU_STATS(cp, vm.zfod);
3166 	cso->cpu_vminfo.dfree		= CPU_STATS(cp, vm.dfree);
3167 	cso->cpu_vminfo.scan		= CPU_STATS(cp, vm.scan);
3168 	cso->cpu_vminfo.rev		= CPU_STATS(cp, vm.rev);
3169 	cso->cpu_vminfo.hat_fault	= CPU_STATS(cp, vm.hat_fault);
3170 	cso->cpu_vminfo.as_fault	= CPU_STATS(cp, vm.as_fault);
3171 	cso->cpu_vminfo.maj_fault	= CPU_STATS(cp, vm.maj_fault);
3172 	cso->cpu_vminfo.cow_fault	= CPU_STATS(cp, vm.cow_fault);
3173 	cso->cpu_vminfo.prot_fault	= CPU_STATS(cp, vm.prot_fault);
3174 	cso->cpu_vminfo.softlock	= CPU_STATS(cp, vm.softlock);
3175 	cso->cpu_vminfo.kernel_asflt	= CPU_STATS(cp, vm.kernel_asflt);
3176 	cso->cpu_vminfo.pgrrun		= CPU_STATS(cp, vm.pgrrun);
3177 	cso->cpu_vminfo.execpgin	= CPU_STATS(cp, vm.execpgin);
3178 	cso->cpu_vminfo.execpgout	= CPU_STATS(cp, vm.execpgout);
3179 	cso->cpu_vminfo.execfree	= CPU_STATS(cp, vm.execfree);
3180 	cso->cpu_vminfo.anonpgin	= CPU_STATS(cp, vm.anonpgin);
3181 	cso->cpu_vminfo.anonpgout	= CPU_STATS(cp, vm.anonpgout);
3182 	cso->cpu_vminfo.anonfree	= CPU_STATS(cp, vm.anonfree);
3183 	cso->cpu_vminfo.fspgin		= CPU_STATS(cp, vm.fspgin);
3184 	cso->cpu_vminfo.fspgout		= CPU_STATS(cp, vm.fspgout);
3185 	cso->cpu_vminfo.fsfree		= CPU_STATS(cp, vm.fsfree);
3186 
3187 	return (0);
3188 }
3189