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