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