xref: /titanic_52/usr/src/uts/common/os/cyclic.c (revision bdfc6d18da790deeec2e0eb09c625902defe2498)
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, Version 1.0 only
6  * (the "License").  You may not use this file except in compliance
7  * with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or http://www.opensolaris.org/os/licensing.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 /*
23  * Copyright 2004 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 #pragma ident	"%Z%%M%	%I%	%E% SMI"
28 
29 /*
30  *  The Cyclic Subsystem
31  *  --------------------
32  *
33  *  Prehistory
34  *
35  *  Historically, most computer architectures have specified interval-based
36  *  timer parts (e.g. SPARCstation's counter/timer; Intel's i8254).  While
37  *  these parts deal in relative (i.e. not absolute) time values, they are
38  *  typically used by the operating system to implement the abstraction of
39  *  absolute time.  As a result, these parts cannot typically be reprogrammed
40  *  without introducing error in the system's notion of time.
41  *
42  *  Starting in about 1994, chip architectures began specifying high resolution
43  *  timestamp registers.  As of this writing (1999), all major chip families
44  *  (UltraSPARC, PentiumPro, MIPS, PowerPC, Alpha) have high resolution
45  *  timestamp registers, and two (UltraSPARC and MIPS) have added the capacity
46  *  to interrupt based on timestamp values.  These timestamp-compare registers
47  *  present a time-based interrupt source which can be reprogrammed arbitrarily
48  *  often without introducing error.  Given the low cost of implementing such a
49  *  timestamp-compare register (and the tangible benefit of eliminating
50  *  discrete timer parts), it is reasonable to expect that future chip
51  *  architectures will adopt this feature.
52  *
53  *  The cyclic subsystem has been designed to take advantage of chip
54  *  architectures with the capacity to interrupt based on absolute, high
55  *  resolution values of time.
56  *
57  *  Subsystem Overview
58  *
59  *  The cyclic subsystem is a low-level kernel subsystem designed to provide
60  *  arbitrarily high resolution, per-CPU interval timers (to avoid colliding
61  *  with existing terms, we dub such an interval timer a "cyclic").  Cyclics
62  *  can be specified to fire at high, lock or low interrupt level, and may be
63  *  optionally bound to a CPU or a CPU partition.  A cyclic's CPU or CPU
64  *  partition binding may be changed dynamically; the cyclic will be "juggled"
65  *  to a CPU which satisfies the new binding.  Alternatively, a cyclic may
66  *  be specified to be "omnipresent", denoting firing on all online CPUs.
67  *
68  *  Cyclic Subsystem Interface Overview
69  *  -----------------------------------
70  *
71  *  The cyclic subsystem has interfaces with the kernel at-large, with other
72  *  kernel subsystems (e.g. the processor management subsystem, the checkpoint
73  *  resume subsystem) and with the platform (the cyclic backend).  Each
74  *  of these interfaces is given a brief synopsis here, and is described
75  *  in full above the interface's implementation.
76  *
77  *  The following diagram displays the cyclic subsystem's interfaces to
78  *  other kernel components.  The arrows denote a "calls" relationship, with
79  *  the large arrow indicating the cyclic subsystem's consumer interface.
80  *  Each arrow is labeled with the section in which the corresponding
81  *  interface is described.
82  *
83  *           Kernel at-large consumers
84  *           -----------++------------
85  *                      ||
86  *                      ||
87  *                     _||_
88  *                     \  /
89  *                      \/
90  *            +---------------------+
91  *            |                     |
92  *            |  Cyclic subsystem   |<-----------  Other kernel subsystems
93  *            |                     |
94  *            +---------------------+
95  *                   ^       |
96  *                   |       |
97  *                   |       |
98  *                   |       v
99  *            +---------------------+
100  *            |                     |
101  *            |   Cyclic backend    |
102  *            | (platform specific) |
103  *            |                     |
104  *            +---------------------+
105  *
106  *
107  *  Kernel At-Large Interfaces
108  *
109  *      cyclic_add()         <-- Creates a cyclic
110  *      cyclic_add_omni()    <-- Creates an omnipresent cyclic
111  *      cyclic_remove()      <-- Removes a cyclic
112  *      cyclic_bind()        <-- Change a cyclic's CPU or partition binding
113  *
114  *  Inter-subsystem Interfaces
115  *
116  *      cyclic_juggle()      <-- Juggles cyclics away from a CPU
117  *      cyclic_offline()     <-- Offlines cyclic operation on a CPU
118  *      cyclic_online()      <-- Reenables operation on an offlined CPU
119  *      cyclic_move_in()     <-- Notifies subsystem of change in CPU partition
120  *      cyclic_move_out()    <-- Notifies subsystem of change in CPU partition
121  *      cyclic_suspend()     <-- Suspends the cyclic subsystem on all CPUs
122  *      cyclic_resume()      <-- Resumes the cyclic subsystem on all CPUs
123  *
124  *  Backend Interfaces
125  *
126  *      cyclic_init()        <-- Initializes the cyclic subsystem
127  *      cyclic_fire()        <-- CY_HIGH_LEVEL interrupt entry point
128  *      cyclic_softint()     <-- CY_LOCK/LOW_LEVEL soft interrupt entry point
129  *
130  *  The backend-supplied interfaces (through the cyc_backend structure) are
131  *  documented in detail in <sys/cyclic_impl.h>
132  *
133  *
134  *  Cyclic Subsystem Implementation Overview
135  *  ----------------------------------------
136  *
137  *  The cyclic subsystem is designed to minimize interference between cyclics
138  *  on different CPUs.  Thus, all of the cyclic subsystem's data structures
139  *  hang off of a per-CPU structure, cyc_cpu.
140  *
141  *  Each cyc_cpu has a power-of-two sized array of cyclic structures (the
142  *  cyp_cyclics member of the cyc_cpu structure).  If cyclic_add() is called
143  *  and there does not exist a free slot in the cyp_cyclics array, the size of
144  *  the array will be doubled.  The array will never shrink.  Cyclics are
145  *  referred to by their index in the cyp_cyclics array, which is of type
146  *  cyc_index_t.
147  *
148  *  The cyclics are kept sorted by expiration time in the cyc_cpu's heap.  The
149  *  heap is keyed by cyclic expiration time, with parents expiring earlier
150  *  than their children.
151  *
152  *  Heap Management
153  *
154  *  The heap is managed primarily by cyclic_fire().  Upon entry, cyclic_fire()
155  *  compares the root cyclic's expiration time to the current time.  If the
156  *  expiration time is in the past, cyclic_expire() is called on the root
157  *  cyclic.  Upon return from cyclic_expire(), the cyclic's new expiration time
158  *  is derived by adding its interval to its old expiration time, and a
159  *  downheap operation is performed.  After the downheap, cyclic_fire()
160  *  examines the (potentially changed) root cyclic, repeating the
161  *  cyclic_expire()/add interval/cyclic_downheap() sequence until the root
162  *  cyclic has an expiration time in the future.  This expiration time
163  *  (guaranteed to be the earliest in the heap) is then communicated to the
164  *  backend via cyb_reprogram.  Optimal backends will next call cyclic_fire()
165  *  shortly after the root cyclic's expiration time.
166  *
167  *  To allow efficient, deterministic downheap operations, we implement the
168  *  heap as an array (the cyp_heap member of the cyc_cpu structure), with each
169  *  element containing an index into the CPU's cyp_cyclics array.
170  *
171  *  The heap is laid out in the array according to the following:
172  *
173  *   1.  The root of the heap is always in the 0th element of the heap array
174  *   2.  The left and right children of the nth element are element
175  *       (((n + 1) << 1) - 1) and element ((n + 1) << 1), respectively.
176  *
177  *  This layout is standard (see, e.g., Cormen's "Algorithms"); the proof
178  *  that these constraints correctly lay out a heap (or indeed, any binary
179  *  tree) is trivial and left to the reader.
180  *
181  *  To see the heap by example, assume our cyclics array has the following
182  *  members (at time t):
183  *
184  *            cy_handler            cy_level      cy_expire
185  *            ---------------------------------------------
186  *     [ 0]   clock()                   LOCK     t+10000000
187  *     [ 1]   deadman()                 HIGH   t+1000000000
188  *     [ 2]   clock_highres_fire()       LOW          t+100
189  *     [ 3]   clock_highres_fire()       LOW         t+1000
190  *     [ 4]   clock_highres_fire()       LOW          t+500
191  *     [ 5]   (free)                      --             --
192  *     [ 6]   (free)                      --             --
193  *     [ 7]   (free)                      --             --
194  *
195  *  The heap array could be:
196  *
197  *                [0]   [1]   [2]   [3]   [4]   [5]   [6]   [7]
198  *              +-----+-----+-----+-----+-----+-----+-----+-----+
199  *              |     |     |     |     |     |     |     |     |
200  *              |  2  |  3  |  4  |  0  |  1  |  x  |  x  |  x  |
201  *              |     |     |     |     |     |     |     |     |
202  *              +-----+-----+-----+-----+-----+-----+-----+-----+
203  *
204  *  Graphically, this array corresponds to the following (excuse the ASCII art):
205  *
206  *                                       2
207  *                                       |
208  *                    +------------------+------------------+
209  *                    3                                     4
210  *                    |
211  *          +---------+--------+
212  *          0                  1
213  *
214  *  Note that the heap is laid out by layer:  all nodes at a given depth are
215  *  stored in consecutive elements of the array.  Moreover, layers of
216  *  consecutive depths are in adjacent element ranges.  This property
217  *  guarantees high locality of reference during downheap operations.
218  *  Specifically, we are guaranteed that we can downheap to a depth of
219  *
220  *      lg (cache_line_size / sizeof (cyc_index_t))
221  *
222  *  nodes with at most one cache miss.  On UltraSPARC (64 byte e-cache line
223  *  size), this corresponds to a depth of four nodes.  Thus, if there are
224  *  fewer than sixteen cyclics in the heap, downheaps on UltraSPARC miss at
225  *  most once in the e-cache.
226  *
227  *  Downheaps are required to compare siblings as they proceed down the
228  *  heap.  For downheaps proceeding beyond the one-cache-miss depth, every
229  *  access to a left child could potentially miss in the cache.  However,
230  *  if we assume
231  *
232  *      (cache_line_size / sizeof (cyc_index_t)) > 2,
233  *
234  *  then all siblings are guaranteed to be on the same cache line.  Thus, the
235  *  miss on the left child will guarantee a hit on the right child; downheaps
236  *  will incur at most one cache miss per layer beyond the one-cache-miss
237  *  depth.  The total number of cache misses for heap management during a
238  *  downheap operation is thus bounded by
239  *
240  *      lg (n) - lg (cache_line_size / sizeof (cyc_index_t))
241  *
242  *  Traditional pointer-based heaps are implemented without regard to
243  *  locality.  Downheaps can thus incur two cache misses per layer (one for
244  *  each child), but at most one cache miss at the root.  This yields a bound
245  *  of
246  *
247  *      2 * lg (n) - 1
248  *
249  *  on the total cache misses.
250  *
251  *  This difference may seem theoretically trivial (the difference is, after
252  *  all, constant), but can become substantial in practice -- especially for
253  *  caches with very large cache lines and high miss penalties (e.g. TLBs).
254  *
255  *  Heaps must always be full, balanced trees.  Heap management must therefore
256  *  track the next point-of-insertion into the heap.  In pointer-based heaps,
257  *  recomputing this point takes O(lg (n)).  Given the layout of the
258  *  array-based implementation, however, the next point-of-insertion is
259  *  always:
260  *
261  *      heap[number_of_elements]
262  *
263  *  We exploit this property by implementing the free-list in the usused
264  *  heap elements.  Heap insertion, therefore, consists only of filling in
265  *  the cyclic at cyp_cyclics[cyp_heap[number_of_elements]], incrementing
266  *  the number of elements, and performing an upheap.  Heap deletion consists
267  *  of decrementing the number of elements, swapping the to-be-deleted element
268  *  with the element at cyp_heap[number_of_elements], and downheaping.
269  *
270  *  Filling in more details in our earlier example:
271  *
272  *                                               +--- free list head
273  *                                               |
274  *                                               V
275  *
276  *                [0]   [1]   [2]   [3]   [4]   [5]   [6]   [7]
277  *              +-----+-----+-----+-----+-----+-----+-----+-----+
278  *              |     |     |     |     |     |     |     |     |
279  *              |  2  |  3  |  4  |  0  |  1  |  5  |  6  |  7  |
280  *              |     |     |     |     |     |     |     |     |
281  *              +-----+-----+-----+-----+-----+-----+-----+-----+
282  *
283  *  To insert into this heap, we would just need to fill in the cyclic at
284  *  cyp_cyclics[5], bump the number of elements (from 5 to 6) and perform
285  *  an upheap.
286  *
287  *  If we wanted to remove, say, cyp_cyclics[3], we would first scan for it
288  *  in the cyp_heap, and discover it at cyp_heap[1].  We would then decrement
289  *  the number of elements (from 5 to 4), swap cyp_heap[1] with cyp_heap[4],
290  *  and perform a downheap from cyp_heap[1].  The linear scan is required
291  *  because the cyclic does not keep a backpointer into the heap.  This makes
292  *  heap manipulation (e.g. downheaps) faster at the expense of removal
293  *  operations.
294  *
295  *  Expiry processing
296  *
297  *  As alluded to above, cyclic_expire() is called by cyclic_fire() at
298  *  CY_HIGH_LEVEL to expire a cyclic.  Cyclic subsystem consumers are
299  *  guaranteed that for an arbitrary time t in the future, their cyclic
300  *  handler will have been called (t - cyt_when) / cyt_interval times.  Thus,
301  *  there must be a one-to-one mapping between a cyclic's expiration at
302  *  CY_HIGH_LEVEL and its execution at the desired level (either CY_HIGH_LEVEL,
303  *  CY_LOCK_LEVEL or CY_LOW_LEVEL).
304  *
305  *  For CY_HIGH_LEVEL cyclics, this is trivial; cyclic_expire() simply needs
306  *  to call the handler.
307  *
308  *  For CY_LOCK_LEVEL and CY_LOW_LEVEL cyclics, however, there exists a
309  *  potential disconnect:  if the CPU is at an interrupt level less than
310  *  CY_HIGH_LEVEL but greater than the level of a cyclic for a period of
311  *  time longer than twice the cyclic's interval, the cyclic will be expired
312  *  twice before it can be handled.
313  *
314  *  To maintain the one-to-one mapping, we track the difference between the
315  *  number of times a cyclic has been expired and the number of times it's
316  *  been handled in a "pending count" (the cy_pend field of the cyclic
317  *  structure).  cyclic_expire() thus increments the cy_pend count for the
318  *  expired cyclic and posts a soft interrupt at the desired level.  In the
319  *  cyclic subsystem's soft interrupt handler, cyclic_softint(), we repeatedly
320  *  call the cyclic handler and decrement cy_pend until we have decremented
321  *  cy_pend to zero.
322  *
323  *  The Producer/Consumer Buffer
324  *
325  *  If we wish to avoid a linear scan of the cyclics array at soft interrupt
326  *  level, cyclic_softint() must be able to quickly determine which cyclics
327  *  have a non-zero cy_pend count.  We thus introduce a per-soft interrupt
328  *  level producer/consumer buffer shared with CY_HIGH_LEVEL.  These buffers
329  *  are encapsulated in the cyc_pcbuffer structure, and, like cyp_heap, are
330  *  implemented as cyc_index_t arrays (the cypc_buf member of the cyc_pcbuffer
331  *  structure).
332  *
333  *  The producer (cyclic_expire() running at CY_HIGH_LEVEL) enqueues a cyclic
334  *  by storing the cyclic's index to cypc_buf[cypc_prodndx] and incrementing
335  *  cypc_prodndx.  The consumer (cyclic_softint() running at either
336  *  CY_LOCK_LEVEL or CY_LOW_LEVEL) dequeues a cyclic by loading from
337  *  cypc_buf[cypc_consndx] and bumping cypc_consndx.  The buffer is empty when
338  *  cypc_prodndx == cypc_consndx.
339  *
340  *  To bound the size of the producer/consumer buffer, cyclic_expire() only
341  *  enqueues a cyclic if its cy_pend was zero (if the cyclic's cy_pend is
342  *  non-zero, cyclic_expire() only bumps cy_pend).  Symmetrically,
343  *  cyclic_softint() only consumes a cyclic after it has decremented the
344  *  cy_pend count to zero.
345  *
346  *  Returning to our example, here is what the CY_LOW_LEVEL producer/consumer
347  *  buffer might look like:
348  *
349  *     cypc_consndx ---+                 +--- cypc_prodndx
350  *                     |                 |
351  *                     V                 V
352  *
353  *        [0]   [1]   [2]   [3]   [4]   [5]   [6]   [7]
354  *      +-----+-----+-----+-----+-----+-----+-----+-----+
355  *      |     |     |     |     |     |     |     |     |
356  *      |  x  |  x  |  3  |  2  |  4  |  x  |  x  |  x  |   <== cypc_buf
357  *      |     |     |  .  |  .  |  .  |     |     |     |
358  *      +-----+-----+- | -+- | -+- | -+-----+-----+-----+
359  *                     |     |     |
360  *                     |     |     |              cy_pend  cy_handler
361  *                     |     |     |          -------------------------
362  *                     |     |     |          [ 0]      1  clock()
363  *                     |     |     |          [ 1]      0  deadman()
364  *                     |     +---- | -------> [ 2]      3  clock_highres_fire()
365  *                     +---------- | -------> [ 3]      1  clock_highres_fire()
366  *                                 +--------> [ 4]      1  clock_highres_fire()
367  *                                            [ 5]      -  (free)
368  *                                            [ 6]      -  (free)
369  *                                            [ 7]      -  (free)
370  *
371  *  In particular, note that clock()'s cy_pend is 1 but that it is _not_ in
372  *  this producer/consumer buffer; it would be enqueued in the CY_LOCK_LEVEL
373  *  producer/consumer buffer.
374  *
375  *  Locking
376  *
377  *  Traditionally, access to per-CPU data structures shared between
378  *  interrupt levels is serialized by manipulating programmable interrupt
379  *  level:  readers and writers are required to raise their interrupt level
380  *  to that of the highest level writer.
381  *
382  *  For the producer/consumer buffers (shared between cyclic_fire()/
383  *  cyclic_expire() executing at CY_HIGH_LEVEL and cyclic_softint() executing
384  *  at one of CY_LOCK_LEVEL or CY_LOW_LEVEL), forcing cyclic_softint() to raise
385  *  programmable interrupt level is undesirable:  aside from the additional
386  *  latency incurred by manipulating interrupt level in the hot cy_pend
387  *  processing path, this would create the potential for soft level cy_pend
388  *  processing to delay CY_HIGH_LEVEL firing and expiry processing.
389  *  CY_LOCK/LOW_LEVEL cyclics could thereby induce jitter in CY_HIGH_LEVEL
390  *  cyclics.
391  *
392  *  To minimize jitter, then, we would like the cyclic_fire()/cyclic_expire()
393  *  and cyclic_softint() code paths to be lock-free.
394  *
395  *  For cyclic_fire()/cyclic_expire(), lock-free execution is straightforward:
396  *  because these routines execute at a higher interrupt level than
397  *  cyclic_softint(), their actions on the producer/consumer buffer appear
398  *  atomic.  In particular, the increment of cy_pend appears to occur
399  *  atomically with the increment of cypc_prodndx.
400  *
401  *  For cyclic_softint(), however, lock-free execution requires more delicacy.
402  *  When cyclic_softint() discovers a cyclic in the producer/consumer buffer,
403  *  it calls the cyclic's handler and attempts to atomically decrement the
404  *  cy_pend count with a compare&swap operation.
405  *
406  *  If the compare&swap operation succeeds, cyclic_softint() behaves
407  *  conditionally based on the value it atomically wrote to cy_pend:
408  *
409  *     - If the cy_pend was decremented to 0, the cyclic has been consumed;
410  *       cyclic_softint() increments the cypc_consndx and checks for more
411  *       enqueued work.
412  *
413  *     - If the count was decremented to a non-zero value, there is more work
414  *       to be done on the cyclic; cyclic_softint() calls the cyclic handler
415  *       and repeats the atomic decrement process.
416  *
417  *  If the compare&swap operation fails, cyclic_softint() knows that
418  *  cyclic_expire() has intervened and bumped the cy_pend count (resizes
419  *  and removals complicate this, however -- see the sections on their
420  *  operation, below).  cyclic_softint() thus reloads cy_pend, and re-attempts
421  *  the atomic decrement.
422  *
423  *  Recall that we bound the size of the producer/consumer buffer by
424  *  having cyclic_expire() only enqueue the specified cyclic if its
425  *  cy_pend count is zero; this assures that each cyclic is enqueued at
426  *  most once.  This leads to a critical constraint on cyclic_softint(),
427  *  however:  after the compare&swap operation which successfully decrements
428  *  cy_pend to zero, cyclic_softint() must _not_ re-examine the consumed
429  *  cyclic.  In part to obey this constraint, cyclic_softint() calls the
430  *  cyclic handler before decrementing cy_pend.
431  *
432  *  Resizing
433  *
434  *  All of the discussion thus far has assumed a static number of cyclics.
435  *  Obviously, static limitations are not practical; we need the capacity
436  *  to resize our data structures dynamically.
437  *
438  *  We resize our data structures lazily, and only on a per-CPU basis.
439  *  The size of the data structures always doubles and never shrinks.  We
440  *  serialize adds (and thus resizes) on cpu_lock; we never need to deal
441  *  with concurrent resizes.  Resizes should be rare; they may induce jitter
442  *  on the CPU being resized, but should not affect cyclic operation on other
443  *  CPUs.  Pending cyclics may not be dropped during a resize operation.
444  *
445  *  Three key cyc_cpu data structures need to be resized:  the cyclics array,
446  *  the heap array and the producer/consumer buffers.  Resizing the first two
447  *  is relatively straightforward:
448  *
449  *    1.  The new, larger arrays are allocated in cyclic_expand() (called
450  *        from cyclic_add()).
451  *    2.  cyclic_expand() cross calls cyclic_expand_xcall() on the CPU
452  *        undergoing the resize.
453  *    3.  cyclic_expand_xcall() raises interrupt level to CY_HIGH_LEVEL
454  *    4.  The contents of the old arrays are copied into the new arrays.
455  *    5.  The old cyclics array is bzero()'d
456  *    6.  The pointers are updated.
457  *
458  *  The producer/consumer buffer is dicier:  cyclic_expand_xcall() may have
459  *  interrupted cyclic_softint() in the middle of consumption. To resize the
460  *  producer/consumer buffer, we implement up to two buffers per soft interrupt
461  *  level:  a hard buffer (the buffer being produced into by cyclic_expire())
462  *  and a soft buffer (the buffer from which cyclic_softint() is consuming).
463  *  During normal operation, the hard buffer and soft buffer point to the
464  *  same underlying producer/consumer buffer.
465  *
466  *  During a resize, however, cyclic_expand_xcall() changes the hard buffer
467  *  to point to the new, larger producer/consumer buffer; all future
468  *  cyclic_expire()'s will produce into the new buffer.  cyclic_expand_xcall()
469  *  then posts a CY_LOCK_LEVEL soft interrupt, landing in cyclic_softint().
470  *
471  *  As under normal operation, cyclic_softint() will consume cyclics from
472  *  its soft buffer.  After the soft buffer is drained, however,
473  *  cyclic_softint() will see that the hard buffer has changed.  At that time,
474  *  cyclic_softint() will change its soft buffer to point to the hard buffer,
475  *  and repeat the producer/consumer buffer draining procedure.
476  *
477  *  After the new buffer is drained, cyclic_softint() will determine if both
478  *  soft levels have seen their new producer/consumer buffer.  If both have,
479  *  cyclic_softint() will post on the semaphore cyp_modify_wait.  If not, a
480  *  soft interrupt will be generated for the remaining level.
481  *
482  *  cyclic_expand() blocks on the cyp_modify_wait semaphore (a semaphore is
483  *  used instead of a condition variable because of the race between the
484  *  sema_p() in cyclic_expand() and the sema_v() in cyclic_softint()).  This
485  *  allows cyclic_expand() to know when the resize operation is complete;
486  *  all of the old buffers (the heap, the cyclics array and the producer/
487  *  consumer buffers) can be freed.
488  *
489  *  A final caveat on resizing:  we described step (5) in the
490  *  cyclic_expand_xcall() procedure without providing any motivation.  This
491  *  step addresses the problem of a cyclic_softint() attempting to decrement
492  *  a cy_pend count while interrupted by a cyclic_expand_xcall().  Because
493  *  cyclic_softint() has already called the handler by the time cy_pend is
494  *  decremented, we want to assure that it doesn't decrement a cy_pend
495  *  count in the old cyclics array.  By zeroing the old cyclics array in
496  *  cyclic_expand_xcall(), we are zeroing out every cy_pend count; when
497  *  cyclic_softint() attempts to compare&swap on the cy_pend count, it will
498  *  fail and recognize that the count has been zeroed.  cyclic_softint() will
499  *  update its stale copy of the cyp_cyclics pointer, re-read the cy_pend
500  *  count from the new cyclics array, and re-attempt the compare&swap.
501  *
502  *  Removals
503  *
504  *  Cyclic removals should be rare.  To simplify the implementation (and to
505  *  allow optimization for the cyclic_fire()/cyclic_expire()/cyclic_softint()
506  *  path), we force removals and adds to serialize on cpu_lock.
507  *
508  *  Cyclic removal is complicated by a guarantee made to the consumer of
509  *  the cyclic subsystem:  after cyclic_remove() returns, the cyclic handler
510  *  has returned and will never again be called.
511  *
512  *  Here is the procedure for cyclic removal:
513  *
514  *    1.  cyclic_remove() calls cyclic_remove_xcall() on the CPU undergoing
515  *        the removal.
516  *    2.  cyclic_remove_xcall() raises interrupt level to CY_HIGH_LEVEL
517  *    3.  The current expiration time for the removed cyclic is recorded.
518  *    4.  If the cy_pend count on the removed cyclic is non-zero, it
519  *        is copied into cyp_rpend and subsequently zeroed.
520  *    5.  The cyclic is removed from the heap
521  *    6.  If the root of the heap has changed, the backend is reprogrammed.
522  *    7.  If the cy_pend count was non-zero cyclic_remove() blocks on the
523  *        cyp_modify_wait semaphore.
524  *
525  *  The motivation for step (3) is explained in "Juggling", below.
526  *
527  *  The cy_pend count is decremented in cyclic_softint() after the cyclic
528  *  handler returns.  Thus, if we find a cy_pend count of zero in step
529  *  (4), we know that cyclic_remove() doesn't need to block.
530  *
531  *  If the cy_pend count is non-zero, however, we must block in cyclic_remove()
532  *  until cyclic_softint() has finished calling the cyclic handler.  To let
533  *  cyclic_softint() know that this cyclic has been removed, we zero the
534  *  cy_pend count.  This will cause cyclic_softint()'s compare&swap to fail.
535  *  When cyclic_softint() sees the zero cy_pend count, it knows that it's been
536  *  caught during a resize (see "Resizing", above) or that the cyclic has been
537  *  removed.  In the latter case, it calls cyclic_remove_pend() to call the
538  *  cyclic handler cyp_rpend - 1 times, and posts on cyp_modify_wait.
539  *
540  *  Juggling
541  *
542  *  At first glance, cyclic juggling seems to be a difficult problem.  The
543  *  subsystem must guarantee that a cyclic doesn't execute simultaneously on
544  *  different CPUs, while also assuring that a cyclic fires exactly once
545  *  per interval.  We solve this problem by leveraging a property of the
546  *  platform:  gethrtime() is required to increase in lock-step across
547  *  multiple CPUs.  Therefore, to juggle a cyclic, we remove it from its
548  *  CPU, recording its expiration time in the remove cross call (step (3)
549  *  in "Removing", above).  We then add the cyclic to the new CPU, explicitly
550  *  setting its expiration time to the time recorded in the removal.  This
551  *  leverages the existing cyclic expiry processing, which will compensate
552  *  for any time lost while juggling.
553  *
554  */
555 #include <sys/cyclic_impl.h>
556 #include <sys/sysmacros.h>
557 #include <sys/systm.h>
558 #include <sys/atomic.h>
559 #include <sys/kmem.h>
560 #include <sys/cmn_err.h>
561 #include <sys/ddi.h>
562 
563 #ifdef CYCLIC_TRACE
564 
565 /*
566  * cyc_trace_enabled is for the benefit of kernel debuggers.
567  */
568 int cyc_trace_enabled = 1;
569 static cyc_tracebuf_t cyc_ptrace;
570 static cyc_coverage_t cyc_coverage[CY_NCOVERAGE];
571 
572 /*
573  * Seen this anywhere?
574  */
575 static uint_t
576 cyclic_coverage_hash(char *p)
577 {
578 	unsigned int g;
579 	uint_t hval;
580 
581 	hval = 0;
582 	while (*p) {
583 		hval = (hval << 4) + *p++;
584 		if ((g = (hval & 0xf0000000)) != 0)
585 			hval ^= g >> 24;
586 		hval &= ~g;
587 	}
588 	return (hval);
589 }
590 
591 static void
592 cyclic_coverage(char *why, int level, uint64_t arg0, uint64_t arg1)
593 {
594 	uint_t ndx, orig;
595 
596 	for (ndx = orig = cyclic_coverage_hash(why) % CY_NCOVERAGE; ; ) {
597 		if (cyc_coverage[ndx].cyv_why == why)
598 			break;
599 
600 		if (cyc_coverage[ndx].cyv_why != NULL ||
601 		    casptr(&cyc_coverage[ndx].cyv_why, NULL, why) != NULL) {
602 
603 			if (++ndx == CY_NCOVERAGE)
604 				ndx = 0;
605 
606 			if (ndx == orig)
607 				panic("too many cyclic coverage points");
608 			continue;
609 		}
610 
611 		/*
612 		 * If we're here, we have successfully swung our guy into
613 		 * the position at "ndx".
614 		 */
615 		break;
616 	}
617 
618 	if (level == CY_PASSIVE_LEVEL)
619 		cyc_coverage[ndx].cyv_passive_count++;
620 	else
621 		cyc_coverage[ndx].cyv_count[level]++;
622 
623 	cyc_coverage[ndx].cyv_arg0 = arg0;
624 	cyc_coverage[ndx].cyv_arg1 = arg1;
625 }
626 
627 #define	CYC_TRACE(cpu, level, why, arg0, arg1) \
628 	CYC_TRACE_IMPL(&cpu->cyp_trace[level], level, why, arg0, arg1)
629 
630 #define	CYC_PTRACE(why, arg0, arg1) \
631 	CYC_TRACE_IMPL(&cyc_ptrace, CY_PASSIVE_LEVEL, why, arg0, arg1)
632 
633 #define	CYC_TRACE_IMPL(buf, level, why, a0, a1) { \
634 	if (panicstr == NULL) { \
635 		int _ndx = (buf)->cyt_ndx; \
636 		cyc_tracerec_t *_rec = &(buf)->cyt_buf[_ndx]; \
637 		(buf)->cyt_ndx = (++_ndx == CY_NTRACEREC) ? 0 : _ndx; \
638 		_rec->cyt_tstamp = gethrtime_unscaled(); \
639 		_rec->cyt_why = (why); \
640 		_rec->cyt_arg0 = (uint64_t)(uintptr_t)(a0); \
641 		_rec->cyt_arg1 = (uint64_t)(uintptr_t)(a1); \
642 		cyclic_coverage(why, level,	\
643 		    (uint64_t)(uintptr_t)(a0), (uint64_t)(uintptr_t)(a1)); \
644 	} \
645 }
646 
647 #else
648 
649 static int cyc_trace_enabled = 0;
650 
651 #define	CYC_TRACE(cpu, level, why, arg0, arg1)
652 #define	CYC_PTRACE(why, arg0, arg1)
653 
654 #endif
655 
656 #define	CYC_TRACE0(cpu, level, why) CYC_TRACE(cpu, level, why, 0, 0)
657 #define	CYC_TRACE1(cpu, level, why, arg0) CYC_TRACE(cpu, level, why, arg0, 0)
658 
659 #define	CYC_PTRACE0(why) CYC_PTRACE(why, 0, 0)
660 #define	CYC_PTRACE1(why, arg0) CYC_PTRACE(why, arg0, 0)
661 
662 static kmem_cache_t *cyclic_id_cache;
663 static cyc_id_t *cyclic_id_head;
664 static hrtime_t cyclic_resolution;
665 static cyc_backend_t cyclic_backend;
666 
667 /*
668  * Returns 1 if the upheap propagated to the root, 0 if it did not.  This
669  * allows the caller to reprogram the backend only when the root has been
670  * modified.
671  */
672 static int
673 cyclic_upheap(cyc_cpu_t *cpu, cyc_index_t ndx)
674 {
675 	cyclic_t *cyclics;
676 	cyc_index_t *heap;
677 	cyc_index_t heap_parent, heap_current = ndx;
678 	cyc_index_t parent, current;
679 
680 	if (heap_current == 0)
681 		return (1);
682 
683 	heap = cpu->cyp_heap;
684 	cyclics = cpu->cyp_cyclics;
685 	heap_parent = CYC_HEAP_PARENT(heap_current);
686 
687 	for (;;) {
688 		current = heap[heap_current];
689 		parent = heap[heap_parent];
690 
691 		/*
692 		 * We have an expiration time later than our parent; we're
693 		 * done.
694 		 */
695 		if (cyclics[current].cy_expire >= cyclics[parent].cy_expire)
696 			return (0);
697 
698 		/*
699 		 * We need to swap with our parent, and continue up the heap.
700 		 */
701 		heap[heap_parent] = current;
702 		heap[heap_current] = parent;
703 
704 		/*
705 		 * If we just reached the root, we're done.
706 		 */
707 		if (heap_parent == 0)
708 			return (1);
709 
710 		heap_current = heap_parent;
711 		heap_parent = CYC_HEAP_PARENT(heap_current);
712 	}
713 }
714 
715 static void
716 cyclic_downheap(cyc_cpu_t *cpu, cyc_index_t ndx)
717 {
718 	cyclic_t *cyclics = cpu->cyp_cyclics;
719 	cyc_index_t *heap = cpu->cyp_heap;
720 
721 	cyc_index_t heap_left, heap_right, heap_me = ndx;
722 	cyc_index_t left, right, me;
723 	cyc_index_t nelems = cpu->cyp_nelems;
724 
725 	for (;;) {
726 		/*
727 		 * If we don't have a left child (i.e., we're a leaf), we're
728 		 * done.
729 		 */
730 		if ((heap_left = CYC_HEAP_LEFT(heap_me)) >= nelems)
731 			return;
732 
733 		left = heap[heap_left];
734 		me = heap[heap_me];
735 
736 		heap_right = CYC_HEAP_RIGHT(heap_me);
737 
738 		/*
739 		 * Even if we don't have a right child, we still need to compare
740 		 * our expiration time against that of our left child.
741 		 */
742 		if (heap_right >= nelems)
743 			goto comp_left;
744 
745 		right = heap[heap_right];
746 
747 		/*
748 		 * We have both a left and a right child.  We need to compare
749 		 * the expiration times of the children to determine which
750 		 * expires earlier.
751 		 */
752 		if (cyclics[right].cy_expire < cyclics[left].cy_expire) {
753 			/*
754 			 * Our right child is the earlier of our children.
755 			 * We'll now compare our expiration time to its; if
756 			 * ours is the earlier, we're done.
757 			 */
758 			if (cyclics[me].cy_expire <= cyclics[right].cy_expire)
759 				return;
760 
761 			/*
762 			 * Our right child expires earlier than we do; swap
763 			 * with our right child, and descend right.
764 			 */
765 			heap[heap_right] = me;
766 			heap[heap_me] = right;
767 			heap_me = heap_right;
768 			continue;
769 		}
770 
771 comp_left:
772 		/*
773 		 * Our left child is the earlier of our children (or we have
774 		 * no right child).  We'll now compare our expiration time
775 		 * to its; if ours is the earlier, we're done.
776 		 */
777 		if (cyclics[me].cy_expire <= cyclics[left].cy_expire)
778 			return;
779 
780 		/*
781 		 * Our left child expires earlier than we do; swap with our
782 		 * left child, and descend left.
783 		 */
784 		heap[heap_left] = me;
785 		heap[heap_me] = left;
786 		heap_me = heap_left;
787 	}
788 }
789 
790 static void
791 cyclic_expire(cyc_cpu_t *cpu, cyc_index_t ndx, cyclic_t *cyclic)
792 {
793 	cyc_backend_t *be = cpu->cyp_backend;
794 	cyc_level_t level = cyclic->cy_level;
795 
796 	/*
797 	 * If this is a CY_HIGH_LEVEL cyclic, just call the handler; we don't
798 	 * need to worry about the pend count for CY_HIGH_LEVEL cyclics.
799 	 */
800 	if (level == CY_HIGH_LEVEL) {
801 		cyc_func_t handler = cyclic->cy_handler;
802 		void *arg = cyclic->cy_arg;
803 
804 		CYC_TRACE(cpu, CY_HIGH_LEVEL, "handler-in", handler, arg);
805 		(*handler)(arg);
806 		CYC_TRACE(cpu, CY_HIGH_LEVEL, "handler-out", handler, arg);
807 
808 		return;
809 	}
810 
811 	/*
812 	 * We're at CY_HIGH_LEVEL; this modification to cy_pend need not
813 	 * be atomic (the high interrupt level assures that it will appear
814 	 * atomic to any softint currently running).
815 	 */
816 	if (cyclic->cy_pend++ == 0) {
817 		cyc_softbuf_t *softbuf = &cpu->cyp_softbuf[level];
818 		cyc_pcbuffer_t *pc = &softbuf->cys_buf[softbuf->cys_hard];
819 
820 		/*
821 		 * We need to enqueue this cyclic in the soft buffer.
822 		 */
823 		CYC_TRACE(cpu, CY_HIGH_LEVEL, "expire-enq", cyclic,
824 		    pc->cypc_prodndx);
825 		pc->cypc_buf[pc->cypc_prodndx++ & pc->cypc_sizemask] = ndx;
826 
827 		ASSERT(pc->cypc_prodndx != pc->cypc_consndx);
828 	} else {
829 		/*
830 		 * If the pend count is zero after we incremented it, then
831 		 * we've wrapped (i.e. we had a cy_pend count of over four
832 		 * billion.  In this case, we clamp the pend count at
833 		 * UINT32_MAX.  Yes, cyclics can be lost in this case.
834 		 */
835 		if (cyclic->cy_pend == 0) {
836 			CYC_TRACE1(cpu, CY_HIGH_LEVEL, "expire-wrap", cyclic);
837 			cyclic->cy_pend = UINT32_MAX;
838 		}
839 
840 		CYC_TRACE(cpu, CY_HIGH_LEVEL, "expire-bump", cyclic, 0);
841 	}
842 
843 	be->cyb_softint(be->cyb_arg, cyclic->cy_level);
844 }
845 
846 /*
847  *  cyclic_fire(cpu_t *)
848  *
849  *  Overview
850  *
851  *    cyclic_fire() is the cyclic subsystem's CY_HIGH_LEVEL interrupt handler.
852  *    Called by the cyclic backend.
853  *
854  *  Arguments and notes
855  *
856  *    The only argument is the CPU on which the interrupt is executing;
857  *    backends must call into cyclic_fire() on the specified CPU.
858  *
859  *    cyclic_fire() may be called spuriously without ill effect.  Optimal
860  *    backends will call into cyclic_fire() at or shortly after the time
861  *    requested via cyb_reprogram().  However, calling cyclic_fire()
862  *    arbitrarily late will only manifest latency bubbles; the correctness
863  *    of the cyclic subsystem does not rely on the timeliness of the backend.
864  *
865  *    cyclic_fire() is wait-free; it will not block or spin.
866  *
867  *  Return values
868  *
869  *    None.
870  *
871  *  Caller's context
872  *
873  *    cyclic_fire() must be called from CY_HIGH_LEVEL interrupt context.
874  */
875 void
876 cyclic_fire(cpu_t *c)
877 {
878 	cyc_cpu_t *cpu = c->cpu_cyclic;
879 	cyc_backend_t *be = cpu->cyp_backend;
880 	cyc_index_t *heap = cpu->cyp_heap;
881 	cyclic_t *cyclic, *cyclics = cpu->cyp_cyclics;
882 	void *arg = be->cyb_arg;
883 	hrtime_t now = gethrtime();
884 	hrtime_t exp;
885 
886 	CYC_TRACE(cpu, CY_HIGH_LEVEL, "fire", now, 0);
887 
888 	if (cpu->cyp_nelems == 0) {
889 		/*
890 		 * This is a spurious fire.  Count it as such, and blow
891 		 * out of here.
892 		 */
893 		CYC_TRACE0(cpu, CY_HIGH_LEVEL, "fire-spurious");
894 		return;
895 	}
896 
897 	for (;;) {
898 		cyc_index_t ndx = heap[0];
899 
900 		cyclic = &cyclics[ndx];
901 
902 		ASSERT(!(cyclic->cy_flags & CYF_FREE));
903 
904 		CYC_TRACE(cpu, CY_HIGH_LEVEL, "fire-check", cyclic,
905 		    cyclic->cy_expire);
906 
907 		if ((exp = cyclic->cy_expire) > now)
908 			break;
909 
910 		cyclic_expire(cpu, ndx, cyclic);
911 
912 		/*
913 		 * If this cyclic will be set to next expire in the distant
914 		 * past, we have one of two situations:
915 		 *
916 		 *   a)	This is the first firing of a cyclic which had
917 		 *	cy_expire set to 0.
918 		 *
919 		 *   b)	We are tragically late for a cyclic -- most likely
920 		 *	due to being in the debugger.
921 		 *
922 		 * In either case, we set the new expiration time to be the
923 		 * the next interval boundary.  This assures that the
924 		 * expiration time modulo the interval is invariant.
925 		 *
926 		 * We arbitrarily define "distant" to be one second (one second
927 		 * is chosen because it's shorter than any foray to the
928 		 * debugger while still being longer than any legitimate
929 		 * stretch at CY_HIGH_LEVEL).
930 		 */
931 		exp += cyclic->cy_interval;
932 
933 		if (now - exp > NANOSEC) {
934 			hrtime_t interval = cyclic->cy_interval;
935 
936 			CYC_TRACE(cpu, CY_HIGH_LEVEL, exp == interval ?
937 			    "fire-first" : "fire-swing", now, exp);
938 
939 			exp += ((now - exp) / interval + 1) * interval;
940 		}
941 
942 		cyclic->cy_expire = exp;
943 		cyclic_downheap(cpu, 0);
944 	}
945 
946 	/*
947 	 * Now we have a cyclic in the root slot which isn't in the past;
948 	 * reprogram the interrupt source.
949 	 */
950 	be->cyb_reprogram(arg, exp);
951 }
952 
953 static void
954 cyclic_remove_pend(cyc_cpu_t *cpu, cyc_level_t level, cyclic_t *cyclic)
955 {
956 	cyc_func_t handler = cyclic->cy_handler;
957 	void *arg = cyclic->cy_arg;
958 	uint32_t i, rpend = cpu->cyp_rpend - 1;
959 
960 	ASSERT(cyclic->cy_flags & CYF_FREE);
961 	ASSERT(cyclic->cy_pend == 0);
962 	ASSERT(cpu->cyp_state == CYS_REMOVING);
963 	ASSERT(cpu->cyp_rpend > 0);
964 
965 	CYC_TRACE(cpu, level, "remove-rpend", cyclic, cpu->cyp_rpend);
966 
967 	/*
968 	 * Note that we only call the handler cyp_rpend - 1 times; this is
969 	 * to account for the handler call in cyclic_softint().
970 	 */
971 	for (i = 0; i < rpend; i++) {
972 		CYC_TRACE(cpu, level, "rpend-in", handler, arg);
973 		(*handler)(arg);
974 		CYC_TRACE(cpu, level, "rpend-out", handler, arg);
975 	}
976 
977 	/*
978 	 * We can now let the remove operation complete.
979 	 */
980 	sema_v(&cpu->cyp_modify_wait);
981 }
982 
983 /*
984  *  cyclic_softint(cpu_t *cpu, cyc_level_t level)
985  *
986  *  Overview
987  *
988  *    cyclic_softint() is the cyclic subsystem's CY_LOCK_LEVEL and CY_LOW_LEVEL
989  *    soft interrupt handler.  Called by the cyclic backend.
990  *
991  *  Arguments and notes
992  *
993  *    The first argument to cyclic_softint() is the CPU on which the interrupt
994  *    is executing; backends must call into cyclic_softint() on the specified
995  *    CPU.  The second argument is the level of the soft interrupt; it must
996  *    be one of CY_LOCK_LEVEL or CY_LOW_LEVEL.
997  *
998  *    cyclic_softint() will call the handlers for cyclics pending at the
999  *    specified level.  cyclic_softint() will not return until all pending
1000  *    cyclics at the specified level have been dealt with; intervening
1001  *    CY_HIGH_LEVEL interrupts which enqueue cyclics at the specified level
1002  *    may therefore prolong cyclic_softint().
1003  *
1004  *    cyclic_softint() never disables interrupts, and, if neither a
1005  *    cyclic_add() nor a cyclic_remove() is pending on the specified CPU, is
1006  *    lock-free.  This assures that in the common case, cyclic_softint()
1007  *    completes without blocking, and never starves cyclic_fire().  If either
1008  *    cyclic_add() or cyclic_remove() is pending, cyclic_softint() may grab
1009  *    a dispatcher lock.
1010  *
1011  *    While cyclic_softint() is designed for bounded latency, it is obviously
1012  *    at the mercy of its cyclic handlers.  Because cyclic handlers may block
1013  *    arbitrarily, callers of cyclic_softint() should not rely upon
1014  *    deterministic completion.
1015  *
1016  *    cyclic_softint() may be called spuriously without ill effect.
1017  *
1018  *  Return value
1019  *
1020  *    None.
1021  *
1022  *  Caller's context
1023  *
1024  *    The caller must be executing in soft interrupt context at either
1025  *    CY_LOCK_LEVEL or CY_LOW_LEVEL.  The level passed to cyclic_softint()
1026  *    must match the level at which it is executing.  On optimal backends,
1027  *    the caller will hold no locks.  In any case, the caller may not hold
1028  *    cpu_lock or any lock acquired by any cyclic handler or held across
1029  *    any of cyclic_add(), cyclic_remove(), cyclic_bind() or cyclic_juggle().
1030  */
1031 void
1032 cyclic_softint(cpu_t *c, cyc_level_t level)
1033 {
1034 	cyc_cpu_t *cpu = c->cpu_cyclic;
1035 	cyc_softbuf_t *softbuf;
1036 	int soft, *buf, consndx, resized = 0, intr_resized = 0;
1037 	cyc_pcbuffer_t *pc;
1038 	cyclic_t *cyclics = cpu->cyp_cyclics;
1039 	int sizemask;
1040 
1041 	CYC_TRACE(cpu, level, "softint", cyclics, 0);
1042 
1043 	ASSERT(level < CY_LOW_LEVEL + CY_SOFT_LEVELS);
1044 
1045 	softbuf = &cpu->cyp_softbuf[level];
1046 top:
1047 	soft = softbuf->cys_soft;
1048 	ASSERT(soft == 0 || soft == 1);
1049 
1050 	pc = &softbuf->cys_buf[soft];
1051 	buf = pc->cypc_buf;
1052 	consndx = pc->cypc_consndx;
1053 	sizemask = pc->cypc_sizemask;
1054 
1055 	CYC_TRACE(cpu, level, "softint-top", cyclics, pc);
1056 
1057 	while (consndx != pc->cypc_prodndx) {
1058 		int pend, npend, opend;
1059 		int consmasked = consndx & sizemask;
1060 		cyclic_t *cyclic = &cyclics[buf[consmasked]];
1061 		cyc_func_t handler = cyclic->cy_handler;
1062 		void *arg = cyclic->cy_arg;
1063 
1064 		ASSERT(buf[consmasked] < cpu->cyp_size);
1065 		CYC_TRACE(cpu, level, "consuming", consndx, cyclic);
1066 
1067 		/*
1068 		 * We have found this cyclic in the pcbuffer.  We know that
1069 		 * one of the following is true:
1070 		 *
1071 		 *  (a)	The pend is non-zero.  We need to execute the handler
1072 		 *	at least once.
1073 		 *
1074 		 *  (b)	The pend _was_ non-zero, but it's now zero due to a
1075 		 *	resize.  We will call the handler once, see that we
1076 		 *	are in this case, and read the new cyclics buffer
1077 		 *	(and hence the old non-zero pend).
1078 		 *
1079 		 *  (c)	The pend _was_ non-zero, but it's now zero due to a
1080 		 *	removal.  We will call the handler once, see that we
1081 		 *	are in this case, and call into cyclic_remove_pend()
1082 		 *	to call the cyclic rpend times.  We will take into
1083 		 *	account that we have already called the handler once.
1084 		 *
1085 		 * Point is:  it's safe to call the handler without first
1086 		 * checking the pend.
1087 		 */
1088 		do {
1089 			CYC_TRACE(cpu, level, "handler-in", handler, arg);
1090 			(*handler)(arg);
1091 			CYC_TRACE(cpu, level, "handler-out", handler, arg);
1092 reread:
1093 			pend = cyclic->cy_pend;
1094 			npend = pend - 1;
1095 
1096 			if (pend == 0) {
1097 				if (cpu->cyp_state == CYS_REMOVING) {
1098 					/*
1099 					 * This cyclic has been removed while
1100 					 * it had a non-zero pend count (we
1101 					 * know it was non-zero because we
1102 					 * found this cyclic in the pcbuffer).
1103 					 * There must be a non-zero rpend for
1104 					 * this CPU, and there must be a remove
1105 					 * operation blocking; we'll call into
1106 					 * cyclic_remove_pend() to clean this
1107 					 * up, and break out of the pend loop.
1108 					 */
1109 					cyclic_remove_pend(cpu, level, cyclic);
1110 					break;
1111 				}
1112 
1113 				/*
1114 				 * We must have had a resize interrupt us.
1115 				 */
1116 				CYC_TRACE(cpu, level, "resize-int", cyclics, 0);
1117 				ASSERT(cpu->cyp_state == CYS_EXPANDING);
1118 				ASSERT(cyclics != cpu->cyp_cyclics);
1119 				ASSERT(resized == 0);
1120 				ASSERT(intr_resized == 0);
1121 				intr_resized = 1;
1122 				cyclics = cpu->cyp_cyclics;
1123 				cyclic = &cyclics[buf[consmasked]];
1124 				ASSERT(cyclic->cy_handler == handler);
1125 				ASSERT(cyclic->cy_arg == arg);
1126 				goto reread;
1127 			}
1128 
1129 			if ((opend =
1130 			    cas32(&cyclic->cy_pend, pend, npend)) != pend) {
1131 				/*
1132 				 * Our cas32 can fail for one of several
1133 				 * reasons:
1134 				 *
1135 				 *  (a)	An intervening high level bumped up the
1136 				 *	pend count on this cyclic.  In this
1137 				 *	case, we will see a higher pend.
1138 				 *
1139 				 *  (b)	The cyclics array has been yanked out
1140 				 *	from underneath us by a resize
1141 				 *	operation.  In this case, pend is 0 and
1142 				 *	cyp_state is CYS_EXPANDING.
1143 				 *
1144 				 *  (c)	The cyclic has been removed by an
1145 				 *	intervening remove-xcall.  In this case,
1146 				 *	pend will be 0, the cyp_state will be
1147 				 *	CYS_REMOVING, and the cyclic will be
1148 				 *	marked CYF_FREE.
1149 				 *
1150 				 * The assertion below checks that we are
1151 				 * in one of the above situations.  The
1152 				 * action under all three is to return to
1153 				 * the top of the loop.
1154 				 */
1155 				CYC_TRACE(cpu, level, "cas-fail", opend, pend);
1156 				ASSERT(opend > pend || (opend == 0 &&
1157 				    ((cyclics != cpu->cyp_cyclics &&
1158 				    cpu->cyp_state == CYS_EXPANDING) ||
1159 				    (cpu->cyp_state == CYS_REMOVING &&
1160 				    (cyclic->cy_flags & CYF_FREE)))));
1161 				goto reread;
1162 			}
1163 
1164 			/*
1165 			 * Okay, so we've managed to successfully decrement
1166 			 * pend.  If we just decremented the pend to 0, we're
1167 			 * done.
1168 			 */
1169 		} while (npend > 0);
1170 
1171 		pc->cypc_consndx = ++consndx;
1172 	}
1173 
1174 	/*
1175 	 * If the high level handler is no longer writing to the same
1176 	 * buffer, then we've had a resize.  We need to switch our soft
1177 	 * index, and goto top.
1178 	 */
1179 	if (soft != softbuf->cys_hard) {
1180 		/*
1181 		 * We can assert that the other buffer has grown by exactly
1182 		 * one factor of two.
1183 		 */
1184 		CYC_TRACE(cpu, level, "buffer-grow", 0, 0);
1185 		ASSERT(cpu->cyp_state == CYS_EXPANDING);
1186 		ASSERT(softbuf->cys_buf[softbuf->cys_hard].cypc_sizemask ==
1187 		    (softbuf->cys_buf[soft].cypc_sizemask << 1) + 1 ||
1188 		    softbuf->cys_buf[soft].cypc_sizemask == 0);
1189 		ASSERT(softbuf->cys_hard == (softbuf->cys_soft ^ 1));
1190 
1191 		/*
1192 		 * If our cached cyclics pointer doesn't match cyp_cyclics,
1193 		 * then we took a resize between our last iteration of the
1194 		 * pend loop and the check against softbuf->cys_hard.
1195 		 */
1196 		if (cpu->cyp_cyclics != cyclics) {
1197 			CYC_TRACE1(cpu, level, "resize-int-int", consndx);
1198 			cyclics = cpu->cyp_cyclics;
1199 		}
1200 
1201 		softbuf->cys_soft = softbuf->cys_hard;
1202 
1203 		ASSERT(resized == 0);
1204 		resized = 1;
1205 		goto top;
1206 	}
1207 
1208 	/*
1209 	 * If we were interrupted by a resize operation, then we must have
1210 	 * seen the hard index change.
1211 	 */
1212 	ASSERT(!(intr_resized == 1 && resized == 0));
1213 
1214 	if (resized) {
1215 		uint32_t lev, nlev;
1216 
1217 		ASSERT(cpu->cyp_state == CYS_EXPANDING);
1218 
1219 		do {
1220 			lev = cpu->cyp_modify_levels;
1221 			nlev = lev + 1;
1222 		} while (cas32(&cpu->cyp_modify_levels, lev, nlev) != lev);
1223 
1224 		/*
1225 		 * If we are the last soft level to see the modification,
1226 		 * post on cyp_modify_wait.  Otherwise, (if we're not
1227 		 * already at low level), post down to the next soft level.
1228 		 */
1229 		if (nlev == CY_SOFT_LEVELS) {
1230 			CYC_TRACE0(cpu, level, "resize-kick");
1231 			sema_v(&cpu->cyp_modify_wait);
1232 		} else {
1233 			ASSERT(nlev < CY_SOFT_LEVELS);
1234 			if (level != CY_LOW_LEVEL) {
1235 				cyc_backend_t *be = cpu->cyp_backend;
1236 
1237 				CYC_TRACE0(cpu, level, "resize-post");
1238 				be->cyb_softint(be->cyb_arg, level - 1);
1239 			}
1240 		}
1241 	}
1242 }
1243 
1244 static void
1245 cyclic_expand_xcall(cyc_xcallarg_t *arg)
1246 {
1247 	cyc_cpu_t *cpu = arg->cyx_cpu;
1248 	cyc_backend_t *be = cpu->cyp_backend;
1249 	cyb_arg_t bar = be->cyb_arg;
1250 	cyc_cookie_t cookie;
1251 	cyc_index_t new_size = arg->cyx_size, size = cpu->cyp_size, i;
1252 	cyc_index_t *new_heap = arg->cyx_heap;
1253 	cyclic_t *cyclics = cpu->cyp_cyclics, *new_cyclics = arg->cyx_cyclics;
1254 
1255 	ASSERT(cpu->cyp_state == CYS_EXPANDING);
1256 
1257 	/*
1258 	 * This is a little dicey.  First, we'll raise our interrupt level
1259 	 * to CY_HIGH_LEVEL.  This CPU already has a new heap, cyclic array,
1260 	 * etc.; we just need to bcopy them across.  As for the softint
1261 	 * buffers, we'll switch the active buffers.  The actual softints will
1262 	 * take care of consuming any pending cyclics in the old buffer.
1263 	 */
1264 	cookie = be->cyb_set_level(bar, CY_HIGH_LEVEL);
1265 
1266 	CYC_TRACE(cpu, CY_HIGH_LEVEL, "expand", new_size, 0);
1267 
1268 	/*
1269 	 * Assert that the new size is a power of 2.
1270 	 */
1271 	ASSERT((new_size & new_size - 1) == 0);
1272 	ASSERT(new_size == (size << 1));
1273 	ASSERT(cpu->cyp_heap != NULL && cpu->cyp_cyclics != NULL);
1274 
1275 	bcopy(cpu->cyp_heap, new_heap, sizeof (cyc_index_t) * size);
1276 	bcopy(cyclics, new_cyclics, sizeof (cyclic_t) * size);
1277 
1278 	/*
1279 	 * Now run through the old cyclics array, setting pend to 0.  To
1280 	 * softints (which are executing at a lower priority level), the
1281 	 * pends dropping to 0 will appear atomic with the cyp_cyclics
1282 	 * pointer changing.
1283 	 */
1284 	for (i = 0; i < size; i++)
1285 		cyclics[i].cy_pend = 0;
1286 
1287 	/*
1288 	 * Set up the free list, and set all of the new cyclics to be CYF_FREE.
1289 	 */
1290 	for (i = size; i < new_size; i++) {
1291 		new_heap[i] = i;
1292 		new_cyclics[i].cy_flags = CYF_FREE;
1293 	}
1294 
1295 	/*
1296 	 * We can go ahead and plow the value of cyp_heap and cyp_cyclics;
1297 	 * cyclic_expand() has kept a copy.
1298 	 */
1299 	cpu->cyp_heap = new_heap;
1300 	cpu->cyp_cyclics = new_cyclics;
1301 	cpu->cyp_size = new_size;
1302 
1303 	/*
1304 	 * We've switched over the heap and the cyclics array.  Now we need
1305 	 * to switch over our active softint buffer pointers.
1306 	 */
1307 	for (i = CY_LOW_LEVEL; i < CY_LOW_LEVEL + CY_SOFT_LEVELS; i++) {
1308 		cyc_softbuf_t *softbuf = &cpu->cyp_softbuf[i];
1309 		uchar_t hard = softbuf->cys_hard;
1310 
1311 		/*
1312 		 * Assert that we're not in the middle of a resize operation.
1313 		 */
1314 		ASSERT(hard == softbuf->cys_soft);
1315 		ASSERT(hard == 0 || hard == 1);
1316 		ASSERT(softbuf->cys_buf[hard].cypc_buf != NULL);
1317 
1318 		softbuf->cys_hard = hard ^ 1;
1319 
1320 		/*
1321 		 * The caller (cyclic_expand()) is responsible for setting
1322 		 * up the new producer-consumer buffer; assert that it's
1323 		 * been done correctly.
1324 		 */
1325 		ASSERT(softbuf->cys_buf[hard ^ 1].cypc_buf != NULL);
1326 		ASSERT(softbuf->cys_buf[hard ^ 1].cypc_prodndx == 0);
1327 		ASSERT(softbuf->cys_buf[hard ^ 1].cypc_consndx == 0);
1328 	}
1329 
1330 	/*
1331 	 * That's all there is to it; now we just need to postdown to
1332 	 * get the softint chain going.
1333 	 */
1334 	be->cyb_softint(bar, CY_HIGH_LEVEL - 1);
1335 	be->cyb_restore_level(bar, cookie);
1336 }
1337 
1338 /*
1339  * cyclic_expand() will cross call onto the CPU to perform the actual
1340  * expand operation.
1341  */
1342 static void
1343 cyclic_expand(cyc_cpu_t *cpu)
1344 {
1345 	cyc_index_t new_size, old_size;
1346 	cyc_index_t *new_heap, *old_heap;
1347 	cyclic_t *new_cyclics, *old_cyclics;
1348 	cyc_xcallarg_t arg;
1349 	cyc_backend_t *be = cpu->cyp_backend;
1350 	char old_hard;
1351 	int i;
1352 
1353 	ASSERT(MUTEX_HELD(&cpu_lock));
1354 	ASSERT(cpu->cyp_state == CYS_ONLINE);
1355 
1356 	cpu->cyp_state = CYS_EXPANDING;
1357 
1358 	old_heap = cpu->cyp_heap;
1359 	old_cyclics = cpu->cyp_cyclics;
1360 
1361 	if ((new_size = ((old_size = cpu->cyp_size) << 1)) == 0) {
1362 		new_size = CY_DEFAULT_PERCPU;
1363 		ASSERT(old_heap == NULL && old_cyclics == NULL);
1364 	}
1365 
1366 	/*
1367 	 * Check that the new_size is a power of 2.
1368 	 */
1369 	ASSERT((new_size - 1 & new_size) == 0);
1370 
1371 	new_heap = kmem_alloc(sizeof (cyc_index_t) * new_size, KM_SLEEP);
1372 	new_cyclics = kmem_zalloc(sizeof (cyclic_t) * new_size, KM_SLEEP);
1373 
1374 	/*
1375 	 * We know that no other expansions are in progress (they serialize
1376 	 * on cpu_lock), so we can safely read the softbuf metadata.
1377 	 */
1378 	old_hard = cpu->cyp_softbuf[0].cys_hard;
1379 
1380 	for (i = CY_LOW_LEVEL; i < CY_LOW_LEVEL + CY_SOFT_LEVELS; i++) {
1381 		cyc_softbuf_t *softbuf = &cpu->cyp_softbuf[i];
1382 		char hard = softbuf->cys_hard;
1383 		cyc_pcbuffer_t *pc = &softbuf->cys_buf[hard ^ 1];
1384 
1385 		ASSERT(hard == old_hard);
1386 		ASSERT(hard == softbuf->cys_soft);
1387 		ASSERT(pc->cypc_buf == NULL);
1388 
1389 		pc->cypc_buf =
1390 		    kmem_alloc(sizeof (cyc_index_t) * new_size, KM_SLEEP);
1391 		pc->cypc_prodndx = pc->cypc_consndx = 0;
1392 		pc->cypc_sizemask = new_size - 1;
1393 	}
1394 
1395 	arg.cyx_cpu = cpu;
1396 	arg.cyx_heap = new_heap;
1397 	arg.cyx_cyclics = new_cyclics;
1398 	arg.cyx_size = new_size;
1399 
1400 	cpu->cyp_modify_levels = 0;
1401 
1402 	be->cyb_xcall(be->cyb_arg, cpu->cyp_cpu,
1403 	    (cyc_func_t)cyclic_expand_xcall, &arg);
1404 
1405 	/*
1406 	 * Now block, waiting for the resize operation to complete.
1407 	 */
1408 	sema_p(&cpu->cyp_modify_wait);
1409 	ASSERT(cpu->cyp_modify_levels == CY_SOFT_LEVELS);
1410 
1411 	/*
1412 	 * The operation is complete; we can now free the old buffers.
1413 	 */
1414 	for (i = CY_LOW_LEVEL; i < CY_LOW_LEVEL + CY_SOFT_LEVELS; i++) {
1415 		cyc_softbuf_t *softbuf = &cpu->cyp_softbuf[i];
1416 		char hard = softbuf->cys_hard;
1417 		cyc_pcbuffer_t *pc = &softbuf->cys_buf[hard ^ 1];
1418 
1419 		ASSERT(hard == (old_hard ^ 1));
1420 		ASSERT(hard == softbuf->cys_soft);
1421 
1422 		if (pc->cypc_buf == NULL)
1423 			continue;
1424 
1425 		ASSERT(pc->cypc_sizemask == ((new_size - 1) >> 1));
1426 
1427 		kmem_free(pc->cypc_buf,
1428 		    sizeof (cyc_index_t) * (pc->cypc_sizemask + 1));
1429 		pc->cypc_buf = NULL;
1430 	}
1431 
1432 	if (old_cyclics != NULL) {
1433 		ASSERT(old_heap != NULL);
1434 		ASSERT(old_size != 0);
1435 		kmem_free(old_cyclics, sizeof (cyclic_t) * old_size);
1436 		kmem_free(old_heap, sizeof (cyc_index_t) * old_size);
1437 	}
1438 
1439 	ASSERT(cpu->cyp_state == CYS_EXPANDING);
1440 	cpu->cyp_state = CYS_ONLINE;
1441 }
1442 
1443 /*
1444  * cyclic_pick_cpu will attempt to pick a CPU according to the constraints
1445  * specified by the partition, bound CPU, and flags.  Additionally,
1446  * cyclic_pick_cpu() will not pick the avoid CPU; it will return NULL if
1447  * the avoid CPU is the only CPU which satisfies the constraints.
1448  *
1449  * If CYF_CPU_BOUND is set in flags, the specified CPU must be non-NULL.
1450  * If CYF_PART_BOUND is set in flags, the specified partition must be non-NULL.
1451  * If both CYF_CPU_BOUND and CYF_PART_BOUND are set, the specified CPU must
1452  * be in the specified partition.
1453  */
1454 static cyc_cpu_t *
1455 cyclic_pick_cpu(cpupart_t *part, cpu_t *bound, cpu_t *avoid, uint16_t flags)
1456 {
1457 	cpu_t *c, *start = (part != NULL) ? part->cp_cpulist : CPU;
1458 	cpu_t *online = NULL;
1459 	uintptr_t offset;
1460 
1461 	CYC_PTRACE("pick-cpu", part, bound);
1462 
1463 	ASSERT(!(flags & CYF_CPU_BOUND) || bound != NULL);
1464 	ASSERT(!(flags & CYF_PART_BOUND) || part != NULL);
1465 
1466 	/*
1467 	 * If we're bound to our CPU, there isn't much choice involved.  We
1468 	 * need to check that the CPU passed as bound is in the cpupart, and
1469 	 * that the CPU that we're binding to has been configured.
1470 	 */
1471 	if (flags & CYF_CPU_BOUND) {
1472 		CYC_PTRACE("pick-cpu-bound", bound, avoid);
1473 
1474 		if ((flags & CYF_PART_BOUND) && bound->cpu_part != part)
1475 			panic("cyclic_pick_cpu:  "
1476 			    "CPU binding contradicts partition binding");
1477 
1478 		if (bound == avoid)
1479 			return (NULL);
1480 
1481 		if (bound->cpu_cyclic == NULL)
1482 			panic("cyclic_pick_cpu:  "
1483 			    "attempt to bind to non-configured CPU");
1484 
1485 		return (bound->cpu_cyclic);
1486 	}
1487 
1488 	if (flags & CYF_PART_BOUND) {
1489 		CYC_PTRACE("pick-part-bound", bound, avoid);
1490 		offset = offsetof(cpu_t, cpu_next_part);
1491 	} else {
1492 		offset = offsetof(cpu_t, cpu_next_onln);
1493 	}
1494 
1495 	c = start;
1496 	do {
1497 		if (c->cpu_cyclic == NULL)
1498 			continue;
1499 
1500 		if (c->cpu_cyclic->cyp_state == CYS_OFFLINE)
1501 			continue;
1502 
1503 		if (c == avoid)
1504 			continue;
1505 
1506 		if (c->cpu_flags & CPU_ENABLE)
1507 			goto found;
1508 
1509 		if (online == NULL)
1510 			online = c;
1511 	} while ((c = *(cpu_t **)((uintptr_t)c + offset)) != start);
1512 
1513 	/*
1514 	 * If we're here, we're in one of two situations:
1515 	 *
1516 	 *  (a)	We have a partition-bound cyclic, and there is no CPU in
1517 	 *	our partition which is CPU_ENABLE'd.  If we saw another
1518 	 *	non-CYS_OFFLINE CPU in our partition, we'll go with it.
1519 	 *	If not, the avoid CPU must be the only non-CYS_OFFLINE
1520 	 *	CPU in the partition; we're forced to return NULL.
1521 	 *
1522 	 *  (b)	We have a partition-unbound cyclic, in which case there
1523 	 *	must only be one CPU CPU_ENABLE'd, and it must be the one
1524 	 *	we're trying to avoid.  If cyclic_juggle()/cyclic_offline()
1525 	 *	are called appropriately, this generally shouldn't happen
1526 	 *	(the offline should fail before getting to this code).
1527 	 *	At any rate: we can't avoid the avoid CPU, so we return
1528 	 *	NULL.
1529 	 */
1530 	if (!(flags & CYF_PART_BOUND)) {
1531 		ASSERT(avoid->cpu_flags & CPU_ENABLE);
1532 		return (NULL);
1533 	}
1534 
1535 	CYC_PTRACE("pick-no-intr", part, avoid);
1536 
1537 	if ((c = online) != NULL)
1538 		goto found;
1539 
1540 	CYC_PTRACE("pick-fail", part, avoid);
1541 	ASSERT(avoid->cpu_part == start->cpu_part);
1542 	return (NULL);
1543 
1544 found:
1545 	CYC_PTRACE("pick-cpu-found", c, avoid);
1546 	ASSERT(c != avoid);
1547 	ASSERT(c->cpu_cyclic != NULL);
1548 
1549 	return (c->cpu_cyclic);
1550 }
1551 
1552 static void
1553 cyclic_add_xcall(cyc_xcallarg_t *arg)
1554 {
1555 	cyc_cpu_t *cpu = arg->cyx_cpu;
1556 	cyc_handler_t *hdlr = arg->cyx_hdlr;
1557 	cyc_time_t *when = arg->cyx_when;
1558 	cyc_backend_t *be = cpu->cyp_backend;
1559 	cyc_index_t ndx, nelems;
1560 	cyc_cookie_t cookie;
1561 	cyb_arg_t bar = be->cyb_arg;
1562 	cyclic_t *cyclic;
1563 
1564 	ASSERT(cpu->cyp_nelems < cpu->cyp_size);
1565 
1566 	cookie = be->cyb_set_level(bar, CY_HIGH_LEVEL);
1567 
1568 	CYC_TRACE(cpu, CY_HIGH_LEVEL,
1569 	    "add-xcall", when->cyt_when, when->cyt_interval);
1570 
1571 	nelems = cpu->cyp_nelems++;
1572 
1573 	if (nelems == 0) {
1574 		/*
1575 		 * If this is the first element, we need to enable the
1576 		 * backend on this CPU.
1577 		 */
1578 		CYC_TRACE0(cpu, CY_HIGH_LEVEL, "enabled");
1579 		be->cyb_enable(bar);
1580 	}
1581 
1582 	ndx = cpu->cyp_heap[nelems];
1583 	cyclic = &cpu->cyp_cyclics[ndx];
1584 
1585 	ASSERT(cyclic->cy_flags == CYF_FREE);
1586 	cyclic->cy_interval = when->cyt_interval;
1587 
1588 	if (when->cyt_when == 0) {
1589 		/*
1590 		 * If a start time hasn't been explicitly specified, we'll
1591 		 * start on the next interval boundary.
1592 		 */
1593 		cyclic->cy_expire = (gethrtime() / cyclic->cy_interval + 1) *
1594 		    cyclic->cy_interval;
1595 	} else {
1596 		cyclic->cy_expire = when->cyt_when;
1597 	}
1598 
1599 	cyclic->cy_handler = hdlr->cyh_func;
1600 	cyclic->cy_arg = hdlr->cyh_arg;
1601 	cyclic->cy_level = hdlr->cyh_level;
1602 	cyclic->cy_flags = arg->cyx_flags;
1603 
1604 	if (cyclic_upheap(cpu, nelems)) {
1605 		hrtime_t exp = cyclic->cy_expire;
1606 
1607 		CYC_TRACE(cpu, CY_HIGH_LEVEL, "add-reprog", cyclic, exp);
1608 
1609 		/*
1610 		 * If our upheap propagated to the root, we need to
1611 		 * reprogram the interrupt source.
1612 		 */
1613 		be->cyb_reprogram(bar, exp);
1614 	}
1615 	be->cyb_restore_level(bar, cookie);
1616 
1617 	arg->cyx_ndx = ndx;
1618 }
1619 
1620 static cyc_index_t
1621 cyclic_add_here(cyc_cpu_t *cpu, cyc_handler_t *hdlr,
1622     cyc_time_t *when, uint16_t flags)
1623 {
1624 	cyc_backend_t *be = cpu->cyp_backend;
1625 	cyb_arg_t bar = be->cyb_arg;
1626 	cyc_xcallarg_t arg;
1627 
1628 	CYC_PTRACE("add-cpu", cpu, hdlr->cyh_func);
1629 	ASSERT(MUTEX_HELD(&cpu_lock));
1630 	ASSERT(cpu->cyp_state == CYS_ONLINE);
1631 	ASSERT(!(cpu->cyp_cpu->cpu_flags & CPU_OFFLINE));
1632 	ASSERT(when->cyt_when >= 0 && when->cyt_interval > 0);
1633 
1634 	if (cpu->cyp_nelems == cpu->cyp_size) {
1635 		/*
1636 		 * This is expensive; it will cross call onto the other
1637 		 * CPU to perform the expansion.
1638 		 */
1639 		cyclic_expand(cpu);
1640 		ASSERT(cpu->cyp_nelems < cpu->cyp_size);
1641 	}
1642 
1643 	/*
1644 	 * By now, we know that we're going to be able to successfully
1645 	 * perform the add.  Now cross call over to the CPU of interest to
1646 	 * actually add our cyclic.
1647 	 */
1648 	arg.cyx_cpu = cpu;
1649 	arg.cyx_hdlr = hdlr;
1650 	arg.cyx_when = when;
1651 	arg.cyx_flags = flags;
1652 
1653 	be->cyb_xcall(bar, cpu->cyp_cpu, (cyc_func_t)cyclic_add_xcall, &arg);
1654 
1655 	CYC_PTRACE("add-cpu-done", cpu, arg.cyx_ndx);
1656 
1657 	return (arg.cyx_ndx);
1658 }
1659 
1660 static void
1661 cyclic_remove_xcall(cyc_xcallarg_t *arg)
1662 {
1663 	cyc_cpu_t *cpu = arg->cyx_cpu;
1664 	cyc_backend_t *be = cpu->cyp_backend;
1665 	cyb_arg_t bar = be->cyb_arg;
1666 	cyc_cookie_t cookie;
1667 	cyc_index_t ndx = arg->cyx_ndx, nelems = cpu->cyp_nelems, i;
1668 	cyc_index_t *heap = cpu->cyp_heap, last;
1669 	cyclic_t *cyclic;
1670 #ifdef DEBUG
1671 	cyc_index_t root;
1672 #endif
1673 
1674 	ASSERT(cpu->cyp_state == CYS_REMOVING);
1675 	ASSERT(nelems > 0);
1676 
1677 	cookie = be->cyb_set_level(bar, CY_HIGH_LEVEL);
1678 
1679 	CYC_TRACE1(cpu, CY_HIGH_LEVEL, "remove-xcall", ndx);
1680 
1681 	cyclic = &cpu->cyp_cyclics[ndx];
1682 
1683 	/*
1684 	 * Grab the current expiration time.  If this cyclic is being
1685 	 * removed as part of a juggling operation, the expiration time
1686 	 * will be used when the cyclic is added to the new CPU.
1687 	 */
1688 	if (arg->cyx_when != NULL) {
1689 		arg->cyx_when->cyt_when = cyclic->cy_expire;
1690 		arg->cyx_when->cyt_interval = cyclic->cy_interval;
1691 	}
1692 
1693 	if (cyclic->cy_pend != 0) {
1694 		/*
1695 		 * The pend is non-zero; this cyclic is currently being
1696 		 * executed (or will be executed shortly).  If the caller
1697 		 * refuses to wait, we must return (doing nothing).  Otherwise,
1698 		 * we will stash the pend value * in this CPU's rpend, and
1699 		 * then zero it out.  The softint in the pend loop will see
1700 		 * that we have zeroed out pend, and will call the cyclic
1701 		 * handler rpend times.  The caller will wait until the
1702 		 * softint has completed calling the cyclic handler.
1703 		 */
1704 		if (arg->cyx_wait == CY_NOWAIT) {
1705 			arg->cyx_wait = CY_WAIT;
1706 			goto out;
1707 		}
1708 
1709 		ASSERT(cyclic->cy_level != CY_HIGH_LEVEL);
1710 		CYC_TRACE1(cpu, CY_HIGH_LEVEL, "remove-pend", cyclic->cy_pend);
1711 		cpu->cyp_rpend = cyclic->cy_pend;
1712 		cyclic->cy_pend = 0;
1713 	}
1714 
1715 	/*
1716 	 * Now set the flags to CYF_FREE.  We don't need a membar_enter()
1717 	 * between zeroing pend and setting the flags because we're at
1718 	 * CY_HIGH_LEVEL (that is, the zeroing of pend and the setting
1719 	 * of cy_flags appear atomic to softints).
1720 	 */
1721 	cyclic->cy_flags = CYF_FREE;
1722 
1723 	for (i = 0; i < nelems; i++) {
1724 		if (heap[i] == ndx)
1725 			break;
1726 	}
1727 
1728 	if (i == nelems)
1729 		panic("attempt to remove non-existent cyclic");
1730 
1731 	cpu->cyp_nelems = --nelems;
1732 
1733 	if (nelems == 0) {
1734 		/*
1735 		 * If we just removed the last element, then we need to
1736 		 * disable the backend on this CPU.
1737 		 */
1738 		CYC_TRACE0(cpu, CY_HIGH_LEVEL, "disabled");
1739 		be->cyb_disable(bar);
1740 	}
1741 
1742 	if (i == nelems) {
1743 		/*
1744 		 * If we just removed the last element of the heap, then
1745 		 * we don't have to downheap.
1746 		 */
1747 		CYC_TRACE0(cpu, CY_HIGH_LEVEL, "remove-bottom");
1748 		goto out;
1749 	}
1750 
1751 #ifdef DEBUG
1752 	root = heap[0];
1753 #endif
1754 
1755 	/*
1756 	 * Swap the last element of the heap with the one we want to
1757 	 * remove, and downheap (this has the implicit effect of putting
1758 	 * the newly freed element on the free list).
1759 	 */
1760 	heap[i] = (last = heap[nelems]);
1761 	heap[nelems] = ndx;
1762 
1763 	if (i == 0) {
1764 		CYC_TRACE0(cpu, CY_HIGH_LEVEL, "remove-root");
1765 		cyclic_downheap(cpu, 0);
1766 	} else {
1767 		if (cyclic_upheap(cpu, i) == 0) {
1768 			/*
1769 			 * The upheap didn't propagate to the root; if it
1770 			 * didn't propagate at all, we need to downheap.
1771 			 */
1772 			CYC_TRACE0(cpu, CY_HIGH_LEVEL, "remove-no-root");
1773 			if (heap[i] == last) {
1774 				CYC_TRACE0(cpu, CY_HIGH_LEVEL, "remove-no-up");
1775 				cyclic_downheap(cpu, i);
1776 			}
1777 			ASSERT(heap[0] == root);
1778 			goto out;
1779 		}
1780 	}
1781 
1782 	/*
1783 	 * We're here because we changed the root; we need to reprogram
1784 	 * the clock source.
1785 	 */
1786 	cyclic = &cpu->cyp_cyclics[heap[0]];
1787 
1788 	CYC_TRACE0(cpu, CY_HIGH_LEVEL, "remove-reprog");
1789 
1790 	ASSERT(nelems != 0);
1791 	be->cyb_reprogram(bar, cyclic->cy_expire);
1792 out:
1793 	be->cyb_restore_level(bar, cookie);
1794 }
1795 
1796 static int
1797 cyclic_remove_here(cyc_cpu_t *cpu, cyc_index_t ndx, cyc_time_t *when, int wait)
1798 {
1799 	cyc_backend_t *be = cpu->cyp_backend;
1800 	cyc_xcallarg_t arg;
1801 	cyclic_t *cyclic = &cpu->cyp_cyclics[ndx];
1802 	cyc_level_t level = cyclic->cy_level;
1803 
1804 	ASSERT(MUTEX_HELD(&cpu_lock));
1805 	ASSERT(cpu->cyp_rpend == 0);
1806 	ASSERT(wait == CY_WAIT || wait == CY_NOWAIT);
1807 
1808 	arg.cyx_ndx = ndx;
1809 	arg.cyx_cpu = cpu;
1810 	arg.cyx_when = when;
1811 	arg.cyx_wait = wait;
1812 
1813 	ASSERT(cpu->cyp_state == CYS_ONLINE);
1814 	cpu->cyp_state = CYS_REMOVING;
1815 
1816 	be->cyb_xcall(be->cyb_arg, cpu->cyp_cpu,
1817 	    (cyc_func_t)cyclic_remove_xcall, &arg);
1818 
1819 	/*
1820 	 * If the cyclic we removed wasn't at CY_HIGH_LEVEL, then we need to
1821 	 * check the cyp_rpend.  If it's non-zero, then we need to wait here
1822 	 * for all pending cyclic handlers to run.
1823 	 */
1824 	ASSERT(!(level == CY_HIGH_LEVEL && cpu->cyp_rpend != 0));
1825 	ASSERT(!(wait == CY_NOWAIT && cpu->cyp_rpend != 0));
1826 	ASSERT(!(arg.cyx_wait == CY_NOWAIT && cpu->cyp_rpend != 0));
1827 
1828 	if (wait != arg.cyx_wait) {
1829 		/*
1830 		 * We are being told that we must wait if we want to
1831 		 * remove this cyclic; put the CPU back in the CYS_ONLINE
1832 		 * state and return failure.
1833 		 */
1834 		ASSERT(wait == CY_NOWAIT && arg.cyx_wait == CY_WAIT);
1835 		ASSERT(cpu->cyp_state == CYS_REMOVING);
1836 		cpu->cyp_state = CYS_ONLINE;
1837 
1838 		return (0);
1839 	}
1840 
1841 	if (cpu->cyp_rpend != 0)
1842 		sema_p(&cpu->cyp_modify_wait);
1843 
1844 	ASSERT(cpu->cyp_state == CYS_REMOVING);
1845 
1846 	cpu->cyp_rpend = 0;
1847 	cpu->cyp_state = CYS_ONLINE;
1848 
1849 	return (1);
1850 }
1851 
1852 /*
1853  * cyclic_juggle_one_to() should only be called when the source cyclic
1854  * can be juggled and the destination CPU is known to be able to accept
1855  * it.
1856  */
1857 static void
1858 cyclic_juggle_one_to(cyc_id_t *idp, cyc_cpu_t *dest)
1859 {
1860 	cyc_cpu_t *src = idp->cyi_cpu;
1861 	cyc_index_t ndx = idp->cyi_ndx;
1862 	cyc_time_t when;
1863 	cyc_handler_t hdlr;
1864 	cyclic_t *cyclic;
1865 	uint16_t flags;
1866 	hrtime_t delay;
1867 
1868 	ASSERT(MUTEX_HELD(&cpu_lock));
1869 	ASSERT(src != NULL && idp->cyi_omni_list == NULL);
1870 	ASSERT(!(dest->cyp_cpu->cpu_flags & (CPU_QUIESCED | CPU_OFFLINE)));
1871 	CYC_PTRACE("juggle-one-to", idp, dest);
1872 
1873 	cyclic = &src->cyp_cyclics[ndx];
1874 
1875 	flags = cyclic->cy_flags;
1876 	ASSERT(!(flags & CYF_CPU_BOUND) && !(flags & CYF_FREE));
1877 
1878 	hdlr.cyh_func = cyclic->cy_handler;
1879 	hdlr.cyh_level = cyclic->cy_level;
1880 	hdlr.cyh_arg = cyclic->cy_arg;
1881 
1882 	/*
1883 	 * Before we begin the juggling process, see if the destination
1884 	 * CPU requires an expansion.  If it does, we'll perform the
1885 	 * expansion before removing the cyclic.  This is to prevent us
1886 	 * from blocking while a system-critical cyclic (notably, the clock
1887 	 * cyclic) isn't on a CPU.
1888 	 */
1889 	if (dest->cyp_nelems == dest->cyp_size) {
1890 		CYC_PTRACE("remove-expand", idp, dest);
1891 		cyclic_expand(dest);
1892 		ASSERT(dest->cyp_nelems < dest->cyp_size);
1893 	}
1894 
1895 	/*
1896 	 * Remove the cyclic from the source.  As mentioned above, we cannot
1897 	 * block during this operation; if we cannot remove the cyclic
1898 	 * without waiting, we spin for a time shorter than the interval, and
1899 	 * reattempt the (non-blocking) removal.  If we continue to fail,
1900 	 * we will exponentially back off (up to half of the interval).
1901 	 * Note that the removal will ultimately succeed -- even if the
1902 	 * cyclic handler is blocked on a resource held by a thread which we
1903 	 * have preempted, priority inheritance assures that the preempted
1904 	 * thread will preempt us and continue to progress.
1905 	 */
1906 	for (delay = NANOSEC / MICROSEC; ; delay <<= 1) {
1907 		/*
1908 		 * Before we begin this operation, disable kernel preemption.
1909 		 */
1910 		kpreempt_disable();
1911 		if (cyclic_remove_here(src, ndx, &when, CY_NOWAIT))
1912 			break;
1913 
1914 		/*
1915 		 * The operation failed; enable kernel preemption while
1916 		 * spinning.
1917 		 */
1918 		kpreempt_enable();
1919 
1920 		CYC_PTRACE("remove-retry", idp, src);
1921 
1922 		if (delay > (cyclic->cy_interval >> 1))
1923 			delay = cyclic->cy_interval >> 1;
1924 
1925 		drv_usecwait((clock_t)(delay / (NANOSEC / MICROSEC)));
1926 	}
1927 
1928 	/*
1929 	 * Now add the cyclic to the destination.  This won't block; we
1930 	 * performed any necessary (blocking) expansion of the destination
1931 	 * CPU before removing the cyclic from the source CPU.
1932 	 */
1933 	idp->cyi_ndx = cyclic_add_here(dest, &hdlr, &when, flags);
1934 	idp->cyi_cpu = dest;
1935 	kpreempt_enable();
1936 }
1937 
1938 static int
1939 cyclic_juggle_one(cyc_id_t *idp)
1940 {
1941 	cyc_index_t ndx = idp->cyi_ndx;
1942 	cyc_cpu_t *cpu = idp->cyi_cpu, *dest;
1943 	cyclic_t *cyclic = &cpu->cyp_cyclics[ndx];
1944 	cpu_t *c = cpu->cyp_cpu;
1945 	cpupart_t *part = c->cpu_part;
1946 
1947 	CYC_PTRACE("juggle-one", idp, cpu);
1948 	ASSERT(MUTEX_HELD(&cpu_lock));
1949 	ASSERT(!(c->cpu_flags & CPU_OFFLINE));
1950 	ASSERT(cpu->cyp_state == CYS_ONLINE);
1951 	ASSERT(!(cyclic->cy_flags & CYF_FREE));
1952 
1953 	if ((dest = cyclic_pick_cpu(part, c, c, cyclic->cy_flags)) == NULL) {
1954 		/*
1955 		 * Bad news:  this cyclic can't be juggled.
1956 		 */
1957 		CYC_PTRACE("juggle-fail", idp, cpu)
1958 		return (0);
1959 	}
1960 
1961 	cyclic_juggle_one_to(idp, dest);
1962 
1963 	return (1);
1964 }
1965 
1966 static void
1967 cyclic_unbind_cpu(cyclic_id_t id)
1968 {
1969 	cyc_id_t *idp = (cyc_id_t *)id;
1970 	cyc_cpu_t *cpu = idp->cyi_cpu;
1971 	cpu_t *c = cpu->cyp_cpu;
1972 	cyclic_t *cyclic = &cpu->cyp_cyclics[idp->cyi_ndx];
1973 
1974 	CYC_PTRACE("unbind-cpu", id, cpu);
1975 	ASSERT(MUTEX_HELD(&cpu_lock));
1976 	ASSERT(cpu->cyp_state == CYS_ONLINE);
1977 	ASSERT(!(cyclic->cy_flags & CYF_FREE));
1978 	ASSERT(cyclic->cy_flags & CYF_CPU_BOUND);
1979 
1980 	cyclic->cy_flags &= ~CYF_CPU_BOUND;
1981 
1982 	/*
1983 	 * If we were bound to CPU which has interrupts disabled, we need
1984 	 * to juggle away.  This can only fail if we are bound to a
1985 	 * processor set, and if every CPU in the processor set has
1986 	 * interrupts disabled.
1987 	 */
1988 	if (!(c->cpu_flags & CPU_ENABLE)) {
1989 		int res = cyclic_juggle_one(idp);
1990 
1991 		ASSERT((res && idp->cyi_cpu != cpu) ||
1992 		    (!res && (cyclic->cy_flags & CYF_PART_BOUND)));
1993 	}
1994 }
1995 
1996 static void
1997 cyclic_bind_cpu(cyclic_id_t id, cpu_t *d)
1998 {
1999 	cyc_id_t *idp = (cyc_id_t *)id;
2000 	cyc_cpu_t *dest = d->cpu_cyclic, *cpu = idp->cyi_cpu;
2001 	cpu_t *c = cpu->cyp_cpu;
2002 	cyclic_t *cyclic = &cpu->cyp_cyclics[idp->cyi_ndx];
2003 	cpupart_t *part = c->cpu_part;
2004 
2005 	CYC_PTRACE("bind-cpu", id, dest);
2006 	ASSERT(MUTEX_HELD(&cpu_lock));
2007 	ASSERT(!(d->cpu_flags & CPU_OFFLINE));
2008 	ASSERT(!(c->cpu_flags & CPU_OFFLINE));
2009 	ASSERT(cpu->cyp_state == CYS_ONLINE);
2010 	ASSERT(dest != NULL);
2011 	ASSERT(dest->cyp_state == CYS_ONLINE);
2012 	ASSERT(!(cyclic->cy_flags & CYF_FREE));
2013 	ASSERT(!(cyclic->cy_flags & CYF_CPU_BOUND));
2014 
2015 	dest = cyclic_pick_cpu(part, d, NULL, cyclic->cy_flags | CYF_CPU_BOUND);
2016 
2017 	if (dest != cpu) {
2018 		cyclic_juggle_one_to(idp, dest);
2019 		cyclic = &dest->cyp_cyclics[idp->cyi_ndx];
2020 	}
2021 
2022 	cyclic->cy_flags |= CYF_CPU_BOUND;
2023 }
2024 
2025 static void
2026 cyclic_unbind_cpupart(cyclic_id_t id)
2027 {
2028 	cyc_id_t *idp = (cyc_id_t *)id;
2029 	cyc_cpu_t *cpu = idp->cyi_cpu;
2030 	cpu_t *c = cpu->cyp_cpu;
2031 	cyclic_t *cyc = &cpu->cyp_cyclics[idp->cyi_ndx];
2032 
2033 	CYC_PTRACE("unbind-part", idp, c->cpu_part);
2034 	ASSERT(MUTEX_HELD(&cpu_lock));
2035 	ASSERT(cpu->cyp_state == CYS_ONLINE);
2036 	ASSERT(!(cyc->cy_flags & CYF_FREE));
2037 	ASSERT(cyc->cy_flags & CYF_PART_BOUND);
2038 
2039 	cyc->cy_flags &= ~CYF_PART_BOUND;
2040 
2041 	/*
2042 	 * If we're on a CPU which has interrupts disabled (and if this cyclic
2043 	 * isn't bound to the CPU), we need to juggle away.
2044 	 */
2045 	if (!(c->cpu_flags & CPU_ENABLE) && !(cyc->cy_flags & CYF_CPU_BOUND)) {
2046 		int res = cyclic_juggle_one(idp);
2047 
2048 		ASSERT(res && idp->cyi_cpu != cpu);
2049 	}
2050 }
2051 
2052 static void
2053 cyclic_bind_cpupart(cyclic_id_t id, cpupart_t *part)
2054 {
2055 	cyc_id_t *idp = (cyc_id_t *)id;
2056 	cyc_cpu_t *cpu = idp->cyi_cpu, *dest;
2057 	cpu_t *c = cpu->cyp_cpu;
2058 	cyclic_t *cyc = &cpu->cyp_cyclics[idp->cyi_ndx];
2059 
2060 	CYC_PTRACE("bind-part", idp, part);
2061 	ASSERT(MUTEX_HELD(&cpu_lock));
2062 	ASSERT(!(c->cpu_flags & CPU_OFFLINE));
2063 	ASSERT(cpu->cyp_state == CYS_ONLINE);
2064 	ASSERT(!(cyc->cy_flags & CYF_FREE));
2065 	ASSERT(!(cyc->cy_flags & CYF_PART_BOUND));
2066 	ASSERT(part->cp_ncpus > 0);
2067 
2068 	dest = cyclic_pick_cpu(part, c, NULL, cyc->cy_flags | CYF_PART_BOUND);
2069 
2070 	if (dest != cpu) {
2071 		cyclic_juggle_one_to(idp, dest);
2072 		cyc = &dest->cyp_cyclics[idp->cyi_ndx];
2073 	}
2074 
2075 	cyc->cy_flags |= CYF_PART_BOUND;
2076 }
2077 
2078 static void
2079 cyclic_configure(cpu_t *c)
2080 {
2081 	cyc_cpu_t *cpu = kmem_zalloc(sizeof (cyc_cpu_t), KM_SLEEP);
2082 	cyc_backend_t *nbe = kmem_zalloc(sizeof (cyc_backend_t), KM_SLEEP);
2083 	int i;
2084 
2085 	CYC_PTRACE1("configure", cpu);
2086 	ASSERT(MUTEX_HELD(&cpu_lock));
2087 
2088 	if (cyclic_id_cache == NULL)
2089 		cyclic_id_cache = kmem_cache_create("cyclic_id_cache",
2090 		    sizeof (cyc_id_t), 0, NULL, NULL, NULL, NULL, NULL, 0);
2091 
2092 	cpu->cyp_cpu = c;
2093 
2094 	sema_init(&cpu->cyp_modify_wait, 0, NULL, SEMA_DEFAULT, NULL);
2095 
2096 	cpu->cyp_size = 1;
2097 	cpu->cyp_heap = kmem_zalloc(sizeof (cyc_index_t), KM_SLEEP);
2098 	cpu->cyp_cyclics = kmem_zalloc(sizeof (cyclic_t), KM_SLEEP);
2099 	cpu->cyp_cyclics->cy_flags = CYF_FREE;
2100 
2101 	for (i = CY_LOW_LEVEL; i < CY_LOW_LEVEL + CY_SOFT_LEVELS; i++) {
2102 		/*
2103 		 * We don't need to set the sizemask; it's already zero
2104 		 * (which is the appropriate sizemask for a size of 1).
2105 		 */
2106 		cpu->cyp_softbuf[i].cys_buf[0].cypc_buf =
2107 		    kmem_alloc(sizeof (cyc_index_t), KM_SLEEP);
2108 	}
2109 
2110 	cpu->cyp_state = CYS_OFFLINE;
2111 
2112 	/*
2113 	 * Setup the backend for this CPU.
2114 	 */
2115 	bcopy(&cyclic_backend, nbe, sizeof (cyc_backend_t));
2116 	nbe->cyb_arg = nbe->cyb_configure(c);
2117 	cpu->cyp_backend = nbe;
2118 
2119 	/*
2120 	 * On platforms where stray interrupts may be taken during startup,
2121 	 * the CPU's cpu_cyclic pointer serves as an indicator that the
2122 	 * cyclic subsystem for this CPU is prepared to field interrupts.
2123 	 */
2124 	membar_producer();
2125 
2126 	c->cpu_cyclic = cpu;
2127 }
2128 
2129 static void
2130 cyclic_unconfigure(cpu_t *c)
2131 {
2132 	cyc_cpu_t *cpu = c->cpu_cyclic;
2133 	cyc_backend_t *be = cpu->cyp_backend;
2134 	cyb_arg_t bar = be->cyb_arg;
2135 	int i;
2136 
2137 	CYC_PTRACE1("unconfigure", cpu);
2138 	ASSERT(MUTEX_HELD(&cpu_lock));
2139 	ASSERT(cpu->cyp_state == CYS_OFFLINE);
2140 	ASSERT(cpu->cyp_nelems == 0);
2141 
2142 	/*
2143 	 * Let the backend know that the CPU is being yanked, and free up
2144 	 * the backend structure.
2145 	 */
2146 	be->cyb_unconfigure(bar);
2147 	kmem_free(be, sizeof (cyc_backend_t));
2148 	cpu->cyp_backend = NULL;
2149 
2150 	/*
2151 	 * Free up the producer/consumer buffers at each of the soft levels.
2152 	 */
2153 	for (i = CY_LOW_LEVEL; i < CY_LOW_LEVEL + CY_SOFT_LEVELS; i++) {
2154 		cyc_softbuf_t *softbuf = &cpu->cyp_softbuf[i];
2155 		uchar_t hard = softbuf->cys_hard;
2156 		cyc_pcbuffer_t *pc = &softbuf->cys_buf[hard];
2157 		size_t bufsize = sizeof (cyc_index_t) * (pc->cypc_sizemask + 1);
2158 
2159 		/*
2160 		 * Assert that we're not in the middle of a resize operation.
2161 		 */
2162 		ASSERT(hard == softbuf->cys_soft);
2163 		ASSERT(hard == 0 || hard == 1);
2164 		ASSERT(pc->cypc_buf != NULL);
2165 		ASSERT(softbuf->cys_buf[hard ^ 1].cypc_buf == NULL);
2166 
2167 		kmem_free(pc->cypc_buf, bufsize);
2168 		pc->cypc_buf = NULL;
2169 	}
2170 
2171 	/*
2172 	 * Finally, clean up our remaining dynamic structures and NULL out
2173 	 * the cpu_cyclic pointer.
2174 	 */
2175 	kmem_free(cpu->cyp_cyclics, cpu->cyp_size * sizeof (cyclic_t));
2176 	kmem_free(cpu->cyp_heap, cpu->cyp_size * sizeof (cyc_index_t));
2177 	kmem_free(cpu, sizeof (cyc_cpu_t));
2178 
2179 	c->cpu_cyclic = NULL;
2180 }
2181 
2182 static int
2183 cyclic_cpu_setup(cpu_setup_t what, int id)
2184 {
2185 	/*
2186 	 * We are guaranteed that there is still/already an entry in the
2187 	 * cpu array for this CPU.
2188 	 */
2189 	cpu_t *c = cpu[id];
2190 	cyc_cpu_t *cyp = c->cpu_cyclic;
2191 
2192 	ASSERT(MUTEX_HELD(&cpu_lock));
2193 
2194 	switch (what) {
2195 	case CPU_CONFIG:
2196 		ASSERT(cyp == NULL);
2197 		cyclic_configure(c);
2198 		break;
2199 
2200 	case CPU_UNCONFIG:
2201 		ASSERT(cyp != NULL && cyp->cyp_state == CYS_OFFLINE);
2202 		cyclic_unconfigure(c);
2203 		break;
2204 
2205 	default:
2206 		break;
2207 	}
2208 
2209 	return (0);
2210 }
2211 
2212 static void
2213 cyclic_suspend_xcall(cyc_xcallarg_t *arg)
2214 {
2215 	cyc_cpu_t *cpu = arg->cyx_cpu;
2216 	cyc_backend_t *be = cpu->cyp_backend;
2217 	cyc_cookie_t cookie;
2218 	cyb_arg_t bar = be->cyb_arg;
2219 
2220 	cookie = be->cyb_set_level(bar, CY_HIGH_LEVEL);
2221 
2222 	CYC_TRACE1(cpu, CY_HIGH_LEVEL, "suspend-xcall", cpu->cyp_nelems);
2223 	ASSERT(cpu->cyp_state == CYS_ONLINE || cpu->cyp_state == CYS_OFFLINE);
2224 
2225 	/*
2226 	 * We won't disable this CPU unless it has a non-zero number of
2227 	 * elements (cpu_lock assures that no one else may be attempting
2228 	 * to disable this CPU).
2229 	 */
2230 	if (cpu->cyp_nelems > 0) {
2231 		ASSERT(cpu->cyp_state == CYS_ONLINE);
2232 		be->cyb_disable(bar);
2233 	}
2234 
2235 	if (cpu->cyp_state == CYS_ONLINE)
2236 		cpu->cyp_state = CYS_SUSPENDED;
2237 
2238 	be->cyb_suspend(bar);
2239 	be->cyb_restore_level(bar, cookie);
2240 }
2241 
2242 static void
2243 cyclic_resume_xcall(cyc_xcallarg_t *arg)
2244 {
2245 	cyc_cpu_t *cpu = arg->cyx_cpu;
2246 	cyc_backend_t *be = cpu->cyp_backend;
2247 	cyc_cookie_t cookie;
2248 	cyb_arg_t bar = be->cyb_arg;
2249 	cyc_state_t state = cpu->cyp_state;
2250 
2251 	cookie = be->cyb_set_level(bar, CY_HIGH_LEVEL);
2252 
2253 	CYC_TRACE1(cpu, CY_HIGH_LEVEL, "resume-xcall", cpu->cyp_nelems);
2254 	ASSERT(state == CYS_SUSPENDED || state == CYS_OFFLINE);
2255 
2256 	be->cyb_resume(bar);
2257 
2258 	/*
2259 	 * We won't enable this CPU unless it has a non-zero number of
2260 	 * elements.
2261 	 */
2262 	if (cpu->cyp_nelems > 0) {
2263 		cyclic_t *cyclic = &cpu->cyp_cyclics[cpu->cyp_heap[0]];
2264 		hrtime_t exp = cyclic->cy_expire;
2265 
2266 		CYC_TRACE(cpu, CY_HIGH_LEVEL, "resume-reprog", cyclic, exp);
2267 		ASSERT(state == CYS_SUSPENDED);
2268 		be->cyb_enable(bar);
2269 		be->cyb_reprogram(bar, exp);
2270 	}
2271 
2272 	if (state == CYS_SUSPENDED)
2273 		cpu->cyp_state = CYS_ONLINE;
2274 
2275 	CYC_TRACE1(cpu, CY_HIGH_LEVEL, "resume-done", cpu->cyp_nelems);
2276 	be->cyb_restore_level(bar, cookie);
2277 }
2278 
2279 static void
2280 cyclic_omni_start(cyc_id_t *idp, cyc_cpu_t *cpu)
2281 {
2282 	cyc_omni_handler_t *omni = &idp->cyi_omni_hdlr;
2283 	cyc_omni_cpu_t *ocpu = kmem_alloc(sizeof (cyc_omni_cpu_t), KM_SLEEP);
2284 	cyc_handler_t hdlr;
2285 	cyc_time_t when;
2286 
2287 	CYC_PTRACE("omni-start", cpu, idp);
2288 	ASSERT(MUTEX_HELD(&cpu_lock));
2289 	ASSERT(cpu->cyp_state == CYS_ONLINE);
2290 	ASSERT(idp->cyi_cpu == NULL);
2291 
2292 	hdlr.cyh_func = NULL;
2293 	hdlr.cyh_arg = NULL;
2294 	hdlr.cyh_level = CY_LEVELS;
2295 
2296 	when.cyt_when = 0;
2297 	when.cyt_interval = 0;
2298 
2299 	omni->cyo_online(omni->cyo_arg, cpu->cyp_cpu, &hdlr, &when);
2300 
2301 	ASSERT(hdlr.cyh_func != NULL);
2302 	ASSERT(hdlr.cyh_level < CY_LEVELS);
2303 	ASSERT(when.cyt_when >= 0 && when.cyt_interval > 0);
2304 
2305 	ocpu->cyo_cpu = cpu;
2306 	ocpu->cyo_arg = hdlr.cyh_arg;
2307 	ocpu->cyo_ndx = cyclic_add_here(cpu, &hdlr, &when, 0);
2308 	ocpu->cyo_next = idp->cyi_omni_list;
2309 	idp->cyi_omni_list = ocpu;
2310 }
2311 
2312 static void
2313 cyclic_omni_stop(cyc_id_t *idp, cyc_cpu_t *cpu)
2314 {
2315 	cyc_omni_handler_t *omni = &idp->cyi_omni_hdlr;
2316 	cyc_omni_cpu_t *ocpu = idp->cyi_omni_list, *prev = NULL;
2317 
2318 	CYC_PTRACE("omni-stop", cpu, idp);
2319 	ASSERT(MUTEX_HELD(&cpu_lock));
2320 	ASSERT(cpu->cyp_state == CYS_ONLINE);
2321 	ASSERT(idp->cyi_cpu == NULL);
2322 	ASSERT(ocpu != NULL);
2323 
2324 	while (ocpu != NULL && ocpu->cyo_cpu != cpu) {
2325 		prev = ocpu;
2326 		ocpu = ocpu->cyo_next;
2327 	}
2328 
2329 	/*
2330 	 * We _must_ have found an cyc_omni_cpu which corresponds to this
2331 	 * CPU -- the definition of an omnipresent cyclic is that it runs
2332 	 * on all online CPUs.
2333 	 */
2334 	ASSERT(ocpu != NULL);
2335 
2336 	if (prev == NULL) {
2337 		idp->cyi_omni_list = ocpu->cyo_next;
2338 	} else {
2339 		prev->cyo_next = ocpu->cyo_next;
2340 	}
2341 
2342 	(void) cyclic_remove_here(ocpu->cyo_cpu, ocpu->cyo_ndx, NULL, CY_WAIT);
2343 
2344 	/*
2345 	 * The cyclic has been removed from this CPU; time to call the
2346 	 * omnipresent offline handler.
2347 	 */
2348 	if (omni->cyo_offline != NULL)
2349 		omni->cyo_offline(omni->cyo_arg, cpu->cyp_cpu, ocpu->cyo_arg);
2350 
2351 	kmem_free(ocpu, sizeof (cyc_omni_cpu_t));
2352 }
2353 
2354 static cyc_id_t *
2355 cyclic_new_id()
2356 {
2357 	cyc_id_t *idp;
2358 
2359 	ASSERT(MUTEX_HELD(&cpu_lock));
2360 
2361 	idp = kmem_cache_alloc(cyclic_id_cache, KM_SLEEP);
2362 
2363 	/*
2364 	 * The cyi_cpu field of the cyc_id_t structure tracks the CPU
2365 	 * associated with the cyclic.  If and only if this field is NULL, the
2366 	 * cyc_id_t is an omnipresent cyclic.  Note that cyi_omni_list may be
2367 	 * NULL for an omnipresent cyclic while the cyclic is being created
2368 	 * or destroyed.
2369 	 */
2370 	idp->cyi_cpu = NULL;
2371 	idp->cyi_ndx = 0;
2372 
2373 	idp->cyi_next = cyclic_id_head;
2374 	idp->cyi_prev = NULL;
2375 	idp->cyi_omni_list = NULL;
2376 
2377 	if (cyclic_id_head != NULL) {
2378 		ASSERT(cyclic_id_head->cyi_prev == NULL);
2379 		cyclic_id_head->cyi_prev = idp;
2380 	}
2381 
2382 	cyclic_id_head = idp;
2383 
2384 	return (idp);
2385 }
2386 
2387 /*
2388  *  cyclic_id_t cyclic_add(cyc_handler_t *, cyc_time_t *)
2389  *
2390  *  Overview
2391  *
2392  *    cyclic_add() will create an unbound cyclic with the specified handler and
2393  *    interval.  The cyclic will run on a CPU which both has interrupts enabled
2394  *    and is in the system CPU partition.
2395  *
2396  *  Arguments and notes
2397  *
2398  *    As its first argument, cyclic_add() takes a cyc_handler, which has the
2399  *    following members:
2400  *
2401  *      cyc_func_t cyh_func    <-- Cyclic handler
2402  *      void *cyh_arg          <-- Argument to cyclic handler
2403  *      cyc_level_t cyh_level  <-- Level at which to fire; must be one of
2404  *                                 CY_LOW_LEVEL, CY_LOCK_LEVEL or CY_HIGH_LEVEL
2405  *
2406  *    Note that cyh_level is _not_ an ipl or spl; it must be one the
2407  *    CY_*_LEVELs.  This layer of abstraction allows the platform to define
2408  *    the precise interrupt priority levels, within the following constraints:
2409  *
2410  *       CY_LOCK_LEVEL must map to LOCK_LEVEL
2411  *       CY_HIGH_LEVEL must map to an ipl greater than LOCK_LEVEL
2412  *       CY_LOW_LEVEL must map to an ipl below LOCK_LEVEL
2413  *
2414  *    In addition to a cyc_handler, cyclic_add() takes a cyc_time, which
2415  *    has the following members:
2416  *
2417  *       hrtime_t cyt_when     <-- Absolute time, in nanoseconds since boot, at
2418  *                                 which to start firing
2419  *       hrtime_t cyt_interval <-- Length of interval, in nanoseconds
2420  *
2421  *    gethrtime() is the time source for nanoseconds since boot.  If cyt_when
2422  *    is set to 0, the cyclic will start to fire when cyt_interval next
2423  *    divides the number of nanoseconds since boot.
2424  *
2425  *    The cyt_interval field _must_ be filled in by the caller; one-shots are
2426  *    _not_ explicitly supported by the cyclic subsystem (cyclic_add() will
2427  *    assert that cyt_interval is non-zero).  The maximum value for either
2428  *    field is INT64_MAX; the caller is responsible for assuring that
2429  *    cyt_when + cyt_interval <= INT64_MAX.  Neither field may be negative.
2430  *
2431  *    For an arbitrary time t in the future, the cyclic handler is guaranteed
2432  *    to have been called (t - cyt_when) / cyt_interval times.  This will
2433  *    be true even if interrupts have been disabled for periods greater than
2434  *    cyt_interval nanoseconds.  In order to compensate for such periods,
2435  *    the cyclic handler may be called a finite number of times with an
2436  *    arbitrarily small interval.
2437  *
2438  *    The cyclic subsystem will not enforce any lower bound on the interval;
2439  *    if the interval is less than the time required to process an interrupt,
2440  *    the CPU will wedge.  It's the responsibility of the caller to assure that
2441  *    either the value of the interval is sane, or that its caller has
2442  *    sufficient privilege to deny service (i.e. its caller is root).
2443  *
2444  *    The cyclic handler is guaranteed to be single threaded, even while the
2445  *    cyclic is being juggled between CPUs (see cyclic_juggle(), below).
2446  *    That is, a given cyclic handler will never be executed simultaneously
2447  *    on different CPUs.
2448  *
2449  *  Return value
2450  *
2451  *    cyclic_add() returns a cyclic_id_t, which is guaranteed to be a value
2452  *    other than CYCLIC_NONE.  cyclic_add() cannot fail.
2453  *
2454  *  Caller's context
2455  *
2456  *    cpu_lock must be held by the caller, and the caller must not be in
2457  *    interrupt context.  cyclic_add() will perform a KM_SLEEP kernel
2458  *    memory allocation, so the usual rules (e.g. p_lock cannot be held)
2459  *    apply.  A cyclic may be added even in the presence of CPUs that have
2460  *    not been configured with respect to the cyclic subsystem, but only
2461  *    configured CPUs will be eligible to run the new cyclic.
2462  *
2463  *  Cyclic handler's context
2464  *
2465  *    Cyclic handlers will be executed in the interrupt context corresponding
2466  *    to the specified level (i.e. either high, lock or low level).  The
2467  *    usual context rules apply.
2468  *
2469  *    A cyclic handler may not grab ANY locks held by the caller of any of
2470  *    cyclic_add(), cyclic_remove() or cyclic_bind(); the implementation of
2471  *    these functions may require blocking on cyclic handler completion.
2472  *    Moreover, cyclic handlers may not make any call back into the cyclic
2473  *    subsystem.
2474  */
2475 cyclic_id_t
2476 cyclic_add(cyc_handler_t *hdlr, cyc_time_t *when)
2477 {
2478 	cyc_id_t *idp = cyclic_new_id();
2479 
2480 	ASSERT(MUTEX_HELD(&cpu_lock));
2481 	ASSERT(when->cyt_when >= 0 && when->cyt_interval > 0);
2482 
2483 	idp->cyi_cpu = cyclic_pick_cpu(NULL, NULL, NULL, 0);
2484 	idp->cyi_ndx = cyclic_add_here(idp->cyi_cpu, hdlr, when, 0);
2485 
2486 	return ((uintptr_t)idp);
2487 }
2488 
2489 /*
2490  *  cyclic_id_t cyclic_add_omni(cyc_omni_handler_t *)
2491  *
2492  *  Overview
2493  *
2494  *    cyclic_add_omni() will create an omnipresent cyclic with the specified
2495  *    online and offline handlers.  Omnipresent cyclics run on all online
2496  *    CPUs, including CPUs which have unbound interrupts disabled.
2497  *
2498  *  Arguments
2499  *
2500  *    As its only argument, cyclic_add_omni() takes a cyc_omni_handler, which
2501  *    has the following members:
2502  *
2503  *      void (*cyo_online)()   <-- Online handler
2504  *      void (*cyo_offline)()  <-- Offline handler
2505  *      void *cyo_arg          <-- Argument to be passed to on/offline handlers
2506  *
2507  *  Online handler
2508  *
2509  *    The cyo_online member is a pointer to a function which has the following
2510  *    four arguments:
2511  *
2512  *      void *                 <-- Argument (cyo_arg)
2513  *      cpu_t *                <-- Pointer to CPU about to be onlined
2514  *      cyc_handler_t *        <-- Pointer to cyc_handler_t; must be filled in
2515  *                                 by omni online handler
2516  *      cyc_time_t *           <-- Pointer to cyc_time_t; must be filled in by
2517  *                                 omni online handler
2518  *
2519  *    The omni cyclic online handler is always called _before_ the omni
2520  *    cyclic begins to fire on the specified CPU.  As the above argument
2521  *    description implies, the online handler must fill in the two structures
2522  *    passed to it:  the cyc_handler_t and the cyc_time_t.  These are the
2523  *    same two structures passed to cyclic_add(), outlined above.  This
2524  *    allows the omni cyclic to have maximum flexibility; different CPUs may
2525  *    optionally
2526  *
2527  *      (a)  have different intervals
2528  *      (b)  be explicitly in or out of phase with one another
2529  *      (c)  have different handlers
2530  *      (d)  have different handler arguments
2531  *      (e)  fire at different levels
2532  *
2533  *    Of these, (e) seems somewhat dubious, but is nonetheless allowed.
2534  *
2535  *    The omni online handler is called in the same context as cyclic_add(),
2536  *    and has the same liberties:  omni online handlers may perform KM_SLEEP
2537  *    kernel memory allocations, and may grab locks which are also acquired
2538  *    by cyclic handlers.  However, omni cyclic online handlers may _not_
2539  *    call back into the cyclic subsystem, and should be generally careful
2540  *    about calling into arbitrary kernel subsystems.
2541  *
2542  *  Offline handler
2543  *
2544  *    The cyo_offline member is a pointer to a function which has the following
2545  *    three arguments:
2546  *
2547  *      void *                 <-- Argument (cyo_arg)
2548  *      cpu_t *                <-- Pointer to CPU about to be offlined
2549  *      void *                 <-- CPU's cyclic argument (that is, value
2550  *                                 to which cyh_arg member of the cyc_handler_t
2551  *                                 was set in the omni online handler)
2552  *
2553  *    The omni cyclic offline handler is always called _after_ the omni
2554  *    cyclic has ceased firing on the specified CPU.  Its purpose is to
2555  *    allow cleanup of any resources dynamically allocated in the omni cyclic
2556  *    online handler.  The context of the offline handler is identical to
2557  *    that of the online handler; the same constraints and liberties apply.
2558  *
2559  *    The offline handler is optional; it may be NULL.
2560  *
2561  *  Return value
2562  *
2563  *    cyclic_add_omni() returns a cyclic_id_t, which is guaranteed to be a
2564  *    value other than CYCLIC_NONE.  cyclic_add_omni() cannot fail.
2565  *
2566  *  Caller's context
2567  *
2568  *    The caller's context is identical to that of cyclic_add(), specified
2569  *    above.
2570  */
2571 cyclic_id_t
2572 cyclic_add_omni(cyc_omni_handler_t *omni)
2573 {
2574 	cyc_id_t *idp = cyclic_new_id();
2575 	cyc_cpu_t *cpu;
2576 	cpu_t *c;
2577 
2578 	ASSERT(MUTEX_HELD(&cpu_lock));
2579 	ASSERT(omni != NULL && omni->cyo_online != NULL);
2580 
2581 	idp->cyi_omni_hdlr = *omni;
2582 
2583 	c = cpu_list;
2584 	do {
2585 		if ((cpu = c->cpu_cyclic) == NULL)
2586 			continue;
2587 
2588 		if (cpu->cyp_state != CYS_ONLINE) {
2589 			ASSERT(cpu->cyp_state == CYS_OFFLINE);
2590 			continue;
2591 		}
2592 
2593 		cyclic_omni_start(idp, cpu);
2594 	} while ((c = c->cpu_next) != cpu_list);
2595 
2596 	/*
2597 	 * We must have found at least one online CPU on which to run
2598 	 * this cyclic.
2599 	 */
2600 	ASSERT(idp->cyi_omni_list != NULL);
2601 	ASSERT(idp->cyi_cpu == NULL);
2602 
2603 	return ((uintptr_t)idp);
2604 }
2605 
2606 /*
2607  *  void cyclic_remove(cyclic_id_t)
2608  *
2609  *  Overview
2610  *
2611  *    cyclic_remove() will remove the specified cyclic from the system.
2612  *
2613  *  Arguments and notes
2614  *
2615  *    The only argument is a cyclic_id returned from either cyclic_add() or
2616  *    cyclic_add_omni().
2617  *
2618  *    By the time cyclic_remove() returns, the caller is guaranteed that the
2619  *    removed cyclic handler has completed execution (this is the same
2620  *    semantic that untimeout() provides).  As a result, cyclic_remove() may
2621  *    need to block, waiting for the removed cyclic to complete execution.
2622  *    This leads to an important constraint on the caller:  no lock may be
2623  *    held across cyclic_remove() that also may be acquired by a cyclic
2624  *    handler.
2625  *
2626  *  Return value
2627  *
2628  *    None; cyclic_remove() always succeeds.
2629  *
2630  *  Caller's context
2631  *
2632  *    cpu_lock must be held by the caller, and the caller must not be in
2633  *    interrupt context.  The caller may not hold any locks which are also
2634  *    grabbed by any cyclic handler.  See "Arguments and notes", above.
2635  */
2636 void
2637 cyclic_remove(cyclic_id_t id)
2638 {
2639 	cyc_id_t *idp = (cyc_id_t *)id;
2640 	cyc_id_t *prev = idp->cyi_prev, *next = idp->cyi_next;
2641 	cyc_cpu_t *cpu = idp->cyi_cpu;
2642 
2643 	CYC_PTRACE("remove", idp, idp->cyi_cpu);
2644 	ASSERT(MUTEX_HELD(&cpu_lock));
2645 
2646 	if (cpu != NULL) {
2647 		(void) cyclic_remove_here(cpu, idp->cyi_ndx, NULL, CY_WAIT);
2648 	} else {
2649 		ASSERT(idp->cyi_omni_list != NULL);
2650 		while (idp->cyi_omni_list != NULL)
2651 			cyclic_omni_stop(idp, idp->cyi_omni_list->cyo_cpu);
2652 	}
2653 
2654 	if (prev != NULL) {
2655 		ASSERT(cyclic_id_head != idp);
2656 		prev->cyi_next = next;
2657 	} else {
2658 		ASSERT(cyclic_id_head == idp);
2659 		cyclic_id_head = next;
2660 	}
2661 
2662 	if (next != NULL)
2663 		next->cyi_prev = prev;
2664 
2665 	kmem_cache_free(cyclic_id_cache, idp);
2666 }
2667 
2668 /*
2669  *  void cyclic_bind(cyclic_id_t, cpu_t *, cpupart_t *)
2670  *
2671  *  Overview
2672  *
2673  *    cyclic_bind() atomically changes the CPU and CPU partition bindings
2674  *    of a cyclic.
2675  *
2676  *  Arguments and notes
2677  *
2678  *    The first argument is a cyclic_id retuned from cyclic_add().
2679  *    cyclic_bind() may _not_ be called on a cyclic_id returned from
2680  *    cyclic_add_omni().
2681  *
2682  *    The second argument specifies the CPU to which to bind the specified
2683  *    cyclic.  If the specified cyclic is bound to a CPU other than the one
2684  *    specified, it will be unbound from its bound CPU.  Unbinding the cyclic
2685  *    from its CPU may cause it to be juggled to another CPU.  If the specified
2686  *    CPU is non-NULL, the cyclic will be subsequently rebound to the specified
2687  *    CPU.
2688  *
2689  *    If a CPU with bound cyclics is transitioned into the P_NOINTR state,
2690  *    only cyclics not bound to the CPU can be juggled away; CPU-bound cyclics
2691  *    will continue to fire on the P_NOINTR CPU.  A CPU with bound cyclics
2692  *    cannot be offlined (attempts to offline the CPU will return EBUSY).
2693  *    Likewise, cyclics may not be bound to an offline CPU; if the caller
2694  *    attempts to bind a cyclic to an offline CPU, the cyclic subsystem will
2695  *    panic.
2696  *
2697  *    The third argument specifies the CPU partition to which to bind the
2698  *    specified cyclic.  If the specified cyclic is bound to a CPU partition
2699  *    other than the one specified, it will be unbound from its bound
2700  *    partition.  Unbinding the cyclic from its CPU partition may cause it
2701  *    to be juggled to another CPU.  If the specified CPU partition is
2702  *    non-NULL, the cyclic will be subsequently rebound to the specified CPU
2703  *    partition.
2704  *
2705  *    It is the caller's responsibility to assure that the specified CPU
2706  *    partition contains a CPU.  If it does not, the cyclic subsystem will
2707  *    panic.  A CPU partition with bound cyclics cannot be destroyed (attempts
2708  *    to destroy the partition will return EBUSY).  If a CPU with
2709  *    partition-bound cyclics is transitioned into the P_NOINTR state, cyclics
2710  *    bound to the CPU's partition (but not bound to the CPU) will be juggled
2711  *    away only if there exists another CPU in the partition in the P_ONLINE
2712  *    state.
2713  *
2714  *    It is the caller's responsibility to assure that the specified CPU and
2715  *    CPU partition are self-consistent.  If both parameters are non-NULL,
2716  *    and the specified CPU partition does not contain the specified CPU, the
2717  *    cyclic subsystem will panic.
2718  *
2719  *    It is the caller's responsibility to assure that the specified CPU has
2720  *    been configured with respect to the cyclic subsystem.  Generally, this
2721  *    is always true for valid, on-line CPUs.  The only periods of time during
2722  *    which this may not be true are during MP boot (i.e. after cyclic_init()
2723  *    is called but before cyclic_mp_init() is called) or during dynamic
2724  *    reconfiguration; cyclic_bind() should only be called with great care
2725  *    from these contexts.
2726  *
2727  *  Return value
2728  *
2729  *    None; cyclic_bind() always succeeds.
2730  *
2731  *  Caller's context
2732  *
2733  *    cpu_lock must be held by the caller, and the caller must not be in
2734  *    interrupt context.  The caller may not hold any locks which are also
2735  *    grabbed by any cyclic handler.
2736  */
2737 void
2738 cyclic_bind(cyclic_id_t id, cpu_t *d, cpupart_t *part)
2739 {
2740 	cyc_id_t *idp = (cyc_id_t *)id;
2741 	cyc_cpu_t *cpu = idp->cyi_cpu;
2742 	cpu_t *c;
2743 	uint16_t flags;
2744 
2745 	CYC_PTRACE("bind", d, part);
2746 	ASSERT(MUTEX_HELD(&cpu_lock));
2747 	ASSERT(part == NULL || d == NULL || d->cpu_part == part);
2748 
2749 	if (cpu == NULL) {
2750 		ASSERT(idp->cyi_omni_list != NULL);
2751 		panic("attempt to change binding of omnipresent cyclic");
2752 	}
2753 
2754 	c = cpu->cyp_cpu;
2755 	flags = cpu->cyp_cyclics[idp->cyi_ndx].cy_flags;
2756 
2757 	if (c != d && (flags & CYF_CPU_BOUND))
2758 		cyclic_unbind_cpu(id);
2759 
2760 	/*
2761 	 * Reload our cpu (we may have migrated).  We don't have to reload
2762 	 * the flags field here; if we were CYF_PART_BOUND on entry, we are
2763 	 * CYF_PART_BOUND now.
2764 	 */
2765 	cpu = idp->cyi_cpu;
2766 	c = cpu->cyp_cpu;
2767 
2768 	if (part != c->cpu_part && (flags & CYF_PART_BOUND))
2769 		cyclic_unbind_cpupart(id);
2770 
2771 	/*
2772 	 * Now reload the flags field, asserting that if we are CPU bound,
2773 	 * the CPU was specified (and likewise, if we are partition bound,
2774 	 * the partition was specified).
2775 	 */
2776 	cpu = idp->cyi_cpu;
2777 	c = cpu->cyp_cpu;
2778 	flags = cpu->cyp_cyclics[idp->cyi_ndx].cy_flags;
2779 	ASSERT(!(flags & CYF_CPU_BOUND) || c == d);
2780 	ASSERT(!(flags & CYF_PART_BOUND) || c->cpu_part == part);
2781 
2782 	if (!(flags & CYF_CPU_BOUND) && d != NULL)
2783 		cyclic_bind_cpu(id, d);
2784 
2785 	if (!(flags & CYF_PART_BOUND) && part != NULL)
2786 		cyclic_bind_cpupart(id, part);
2787 }
2788 
2789 hrtime_t
2790 cyclic_getres()
2791 {
2792 	return (cyclic_resolution);
2793 }
2794 
2795 void
2796 cyclic_init(cyc_backend_t *be, hrtime_t resolution)
2797 {
2798 	ASSERT(MUTEX_HELD(&cpu_lock));
2799 
2800 	CYC_PTRACE("init", be, resolution);
2801 	cyclic_resolution = resolution;
2802 
2803 	/*
2804 	 * Copy the passed cyc_backend into the backend template.  This must
2805 	 * be done before the CPU can be configured.
2806 	 */
2807 	bcopy(be, &cyclic_backend, sizeof (cyc_backend_t));
2808 
2809 	/*
2810 	 * It's safe to look at the "CPU" pointer without disabling kernel
2811 	 * preemption; cyclic_init() is called only during startup by the
2812 	 * cyclic backend.
2813 	 */
2814 	cyclic_configure(CPU);
2815 	cyclic_online(CPU);
2816 }
2817 
2818 /*
2819  * It is assumed that cyclic_mp_init() is called some time after cyclic
2820  * init (and therefore, after cpu0 has been initialized).  We grab cpu_lock,
2821  * find the already initialized CPU, and initialize every other CPU with the
2822  * same backend.  Finally, we register a cpu_setup function.
2823  */
2824 void
2825 cyclic_mp_init()
2826 {
2827 	cpu_t *c;
2828 
2829 	mutex_enter(&cpu_lock);
2830 
2831 	c = cpu_list;
2832 	do {
2833 		if (c->cpu_cyclic == NULL) {
2834 			cyclic_configure(c);
2835 			cyclic_online(c);
2836 		}
2837 	} while ((c = c->cpu_next) != cpu_list);
2838 
2839 	register_cpu_setup_func((cpu_setup_func_t *)cyclic_cpu_setup, NULL);
2840 	mutex_exit(&cpu_lock);
2841 }
2842 
2843 /*
2844  *  int cyclic_juggle(cpu_t *)
2845  *
2846  *  Overview
2847  *
2848  *    cyclic_juggle() juggles as many cyclics as possible away from the
2849  *    specified CPU; all remaining cyclics on the CPU will either be CPU-
2850  *    or partition-bound.
2851  *
2852  *  Arguments and notes
2853  *
2854  *    The only argument to cyclic_juggle() is the CPU from which cyclics
2855  *    should be juggled.  CPU-bound cyclics are never juggled; partition-bound
2856  *    cyclics are only juggled if the specified CPU is in the P_NOINTR state
2857  *    and there exists a P_ONLINE CPU in the partition.  The cyclic subsystem
2858  *    assures that a cyclic will never fire late or spuriously, even while
2859  *    being juggled.
2860  *
2861  *  Return value
2862  *
2863  *    cyclic_juggle() returns a non-zero value if all cyclics were able to
2864  *    be juggled away from the CPU, and zero if one or more cyclics could
2865  *    not be juggled away.
2866  *
2867  *  Caller's context
2868  *
2869  *    cpu_lock must be held by the caller, and the caller must not be in
2870  *    interrupt context.  The caller may not hold any locks which are also
2871  *    grabbed by any cyclic handler.  While cyclic_juggle() _may_ be called
2872  *    in any context satisfying these constraints, it _must_ be called
2873  *    immediately after clearing CPU_ENABLE (i.e. before dropping cpu_lock).
2874  *    Failure to do so could result in an assertion failure in the cyclic
2875  *    subsystem.
2876  */
2877 int
2878 cyclic_juggle(cpu_t *c)
2879 {
2880 	cyc_cpu_t *cpu = c->cpu_cyclic;
2881 	cyc_id_t *idp;
2882 	int all_juggled = 1;
2883 
2884 	CYC_PTRACE1("juggle", c);
2885 	ASSERT(MUTEX_HELD(&cpu_lock));
2886 
2887 	/*
2888 	 * We'll go through each cyclic on the CPU, attempting to juggle
2889 	 * each one elsewhere.
2890 	 */
2891 	for (idp = cyclic_id_head; idp != NULL; idp = idp->cyi_next) {
2892 		if (idp->cyi_cpu != cpu)
2893 			continue;
2894 
2895 		if (cyclic_juggle_one(idp) == 0) {
2896 			all_juggled = 0;
2897 			continue;
2898 		}
2899 
2900 		ASSERT(idp->cyi_cpu != cpu);
2901 	}
2902 
2903 	return (all_juggled);
2904 }
2905 
2906 /*
2907  *  int cyclic_offline(cpu_t *)
2908  *
2909  *  Overview
2910  *
2911  *    cyclic_offline() offlines the cyclic subsystem on the specified CPU.
2912  *
2913  *  Arguments and notes
2914  *
2915  *    The only argument to cyclic_offline() is a CPU to offline.
2916  *    cyclic_offline() will attempt to juggle cyclics away from the specified
2917  *    CPU.
2918  *
2919  *  Return value
2920  *
2921  *    cyclic_offline() returns 1 if all cyclics on the CPU were juggled away
2922  *    and the cyclic subsystem on the CPU was successfully offlines.
2923  *    cyclic_offline returns 0 if some cyclics remain, blocking the cyclic
2924  *    offline operation.  All remaining cyclics on the CPU will either be
2925  *    CPU- or partition-bound.
2926  *
2927  *    See the "Arguments and notes" of cyclic_juggle(), below, for more detail
2928  *    on cyclic juggling.
2929  *
2930  *  Caller's context
2931  *
2932  *    The only caller of cyclic_offline() should be the processor management
2933  *    subsystem.  It is expected that the caller of cyclic_offline() will
2934  *    offline the CPU immediately after cyclic_offline() returns success (i.e.
2935  *    before dropping cpu_lock).  Moreover, it is expected that the caller will
2936  *    fail the CPU offline operation if cyclic_offline() returns failure.
2937  */
2938 int
2939 cyclic_offline(cpu_t *c)
2940 {
2941 	cyc_cpu_t *cpu = c->cpu_cyclic;
2942 	cyc_id_t *idp;
2943 
2944 	CYC_PTRACE1("offline", cpu);
2945 	ASSERT(MUTEX_HELD(&cpu_lock));
2946 
2947 	if (!cyclic_juggle(c))
2948 		return (0);
2949 
2950 	/*
2951 	 * This CPU is headed offline; we need to now stop omnipresent
2952 	 * cyclic firing on this CPU.
2953 	 */
2954 	for (idp = cyclic_id_head; idp != NULL; idp = idp->cyi_next) {
2955 		if (idp->cyi_cpu != NULL)
2956 			continue;
2957 
2958 		/*
2959 		 * We cannot possibly be offlining the last CPU; cyi_omni_list
2960 		 * must be non-NULL.
2961 		 */
2962 		ASSERT(idp->cyi_omni_list != NULL);
2963 		cyclic_omni_stop(idp, cpu);
2964 	}
2965 
2966 	ASSERT(cpu->cyp_state == CYS_ONLINE);
2967 	cpu->cyp_state = CYS_OFFLINE;
2968 
2969 	return (1);
2970 }
2971 
2972 /*
2973  *  void cyclic_online(cpu_t *)
2974  *
2975  *  Overview
2976  *
2977  *    cyclic_online() onlines a CPU previously offlined with cyclic_offline().
2978  *
2979  *  Arguments and notes
2980  *
2981  *    cyclic_online()'s only argument is a CPU to online.  The specified
2982  *    CPU must have been previously offlined with cyclic_offline().  After
2983  *    cyclic_online() returns, the specified CPU will be eligible to execute
2984  *    cyclics.
2985  *
2986  *  Return value
2987  *
2988  *    None; cyclic_online() always succeeds.
2989  *
2990  *  Caller's context
2991  *
2992  *    cyclic_online() should only be called by the processor management
2993  *    subsystem; cpu_lock must be held.
2994  */
2995 void
2996 cyclic_online(cpu_t *c)
2997 {
2998 	cyc_cpu_t *cpu = c->cpu_cyclic;
2999 	cyc_id_t *idp;
3000 
3001 	CYC_PTRACE1("online", cpu);
3002 	ASSERT(c->cpu_flags & CPU_ENABLE);
3003 	ASSERT(MUTEX_HELD(&cpu_lock));
3004 	ASSERT(cpu->cyp_state == CYS_OFFLINE);
3005 
3006 	cpu->cyp_state = CYS_ONLINE;
3007 
3008 	/*
3009 	 * Now that this CPU is open for business, we need to start firing
3010 	 * all omnipresent cyclics on it.
3011 	 */
3012 	for (idp = cyclic_id_head; idp != NULL; idp = idp->cyi_next) {
3013 		if (idp->cyi_cpu != NULL)
3014 			continue;
3015 
3016 		cyclic_omni_start(idp, cpu);
3017 	}
3018 }
3019 
3020 /*
3021  *  void cyclic_move_in(cpu_t *)
3022  *
3023  *  Overview
3024  *
3025  *    cyclic_move_in() is called by the CPU partition code immediately after
3026  *    the specified CPU has moved into a new partition.
3027  *
3028  *  Arguments and notes
3029  *
3030  *    The only argument to cyclic_move_in() is a CPU which has moved into a
3031  *    new partition.  If the specified CPU is P_ONLINE, and every other
3032  *    CPU in the specified CPU's new partition is P_NOINTR, cyclic_move_in()
3033  *    will juggle all partition-bound, CPU-unbound cyclics to the specified
3034  *    CPU.
3035  *
3036  *  Return value
3037  *
3038  *    None; cyclic_move_in() always succeeds.
3039  *
3040  *  Caller's context
3041  *
3042  *    cyclic_move_in() should _only_ be called immediately after a CPU has
3043  *    moved into a new partition, with cpu_lock held.  As with other calls
3044  *    into the cyclic subsystem, no lock may be held which is also grabbed
3045  *    by any cyclic handler.
3046  */
3047 void
3048 cyclic_move_in(cpu_t *d)
3049 {
3050 	cyc_id_t *idp;
3051 	cyc_cpu_t *dest = d->cpu_cyclic;
3052 	cyclic_t *cyclic;
3053 	cpupart_t *part = d->cpu_part;
3054 
3055 	CYC_PTRACE("move-in", dest, part);
3056 	ASSERT(MUTEX_HELD(&cpu_lock));
3057 
3058 	/*
3059 	 * Look for CYF_PART_BOUND cyclics in the new partition.  If
3060 	 * we find one, check to see if it is currently on a CPU which has
3061 	 * interrupts disabled.  If it is (and if this CPU currently has
3062 	 * interrupts enabled), we'll juggle those cyclics over here.
3063 	 */
3064 	if (!(d->cpu_flags & CPU_ENABLE)) {
3065 		CYC_PTRACE1("move-in-none", dest);
3066 		return;
3067 	}
3068 
3069 	for (idp = cyclic_id_head; idp != NULL; idp = idp->cyi_next) {
3070 		cyc_cpu_t *cpu = idp->cyi_cpu;
3071 		cpu_t *c;
3072 
3073 		/*
3074 		 * Omnipresent cyclics are exempt from juggling.
3075 		 */
3076 		if (cpu == NULL)
3077 			continue;
3078 
3079 		c = cpu->cyp_cpu;
3080 
3081 		if (c->cpu_part != part || (c->cpu_flags & CPU_ENABLE))
3082 			continue;
3083 
3084 		cyclic = &cpu->cyp_cyclics[idp->cyi_ndx];
3085 
3086 		if (cyclic->cy_flags & CYF_CPU_BOUND)
3087 			continue;
3088 
3089 		/*
3090 		 * We know that this cyclic is bound to its processor set
3091 		 * (otherwise, it would not be on a CPU with interrupts
3092 		 * disabled); juggle it to our CPU.
3093 		 */
3094 		ASSERT(cyclic->cy_flags & CYF_PART_BOUND);
3095 		cyclic_juggle_one_to(idp, dest);
3096 	}
3097 
3098 	CYC_PTRACE1("move-in-done", dest);
3099 }
3100 
3101 /*
3102  *  int cyclic_move_out(cpu_t *)
3103  *
3104  *  Overview
3105  *
3106  *    cyclic_move_out() is called by the CPU partition code immediately before
3107  *    the specified CPU is to move out of its partition.
3108  *
3109  *  Arguments and notes
3110  *
3111  *    The only argument to cyclic_move_out() is a CPU which is to move out of
3112  *    its partition.
3113  *
3114  *    cyclic_move_out() will attempt to juggle away all partition-bound
3115  *    cyclics.  If the specified CPU is the last CPU in a partition with
3116  *    partition-bound cyclics, cyclic_move_out() will fail.  If there exists
3117  *    a partition-bound cyclic which is CPU-bound to the specified CPU,
3118  *    cyclic_move_out() will fail.
3119  *
3120  *    Note that cyclic_move_out() will _only_ attempt to juggle away
3121  *    partition-bound cyclics; CPU-bound cyclics which are not partition-bound
3122  *    and unbound cyclics are not affected by changing the partition
3123  *    affiliation of the CPU.
3124  *
3125  *  Return value
3126  *
3127  *    cyclic_move_out() returns 1 if all partition-bound cyclics on the CPU
3128  *    were juggled away; 0 if some cyclics remain.
3129  *
3130  *  Caller's context
3131  *
3132  *    cyclic_move_out() should _only_ be called immediately before a CPU has
3133  *    moved out of its partition, with cpu_lock held.  It is expected that
3134  *    the caller of cyclic_move_out() will change the processor set affiliation
3135  *    of the specified CPU immediately after cyclic_move_out() returns
3136  *    success (i.e. before dropping cpu_lock).  Moreover, it is expected that
3137  *    the caller will fail the CPU repartitioning operation if cyclic_move_out()
3138  *    returns failure.  As with other calls into the cyclic subsystem, no lock
3139  *    may be held which is also grabbed by any cyclic handler.
3140  */
3141 int
3142 cyclic_move_out(cpu_t *c)
3143 {
3144 	cyc_id_t *idp;
3145 	cyc_cpu_t *cpu = c->cpu_cyclic, *dest;
3146 	cyclic_t *cyclic, *cyclics = cpu->cyp_cyclics;
3147 	cpupart_t *part = c->cpu_part;
3148 
3149 	CYC_PTRACE1("move-out", cpu);
3150 	ASSERT(MUTEX_HELD(&cpu_lock));
3151 
3152 	/*
3153 	 * If there are any CYF_PART_BOUND cyclics on this CPU, we need
3154 	 * to try to juggle them away.
3155 	 */
3156 	for (idp = cyclic_id_head; idp != NULL; idp = idp->cyi_next) {
3157 
3158 		if (idp->cyi_cpu != cpu)
3159 			continue;
3160 
3161 		cyclic = &cyclics[idp->cyi_ndx];
3162 
3163 		if (!(cyclic->cy_flags & CYF_PART_BOUND))
3164 			continue;
3165 
3166 		dest = cyclic_pick_cpu(part, c, c, cyclic->cy_flags);
3167 
3168 		if (dest == NULL) {
3169 			/*
3170 			 * We can't juggle this cyclic; we need to return
3171 			 * failure (we won't bother trying to juggle away
3172 			 * other cyclics).
3173 			 */
3174 			CYC_PTRACE("move-out-fail", cpu, idp);
3175 			return (0);
3176 		}
3177 		cyclic_juggle_one_to(idp, dest);
3178 	}
3179 
3180 	CYC_PTRACE1("move-out-done", cpu);
3181 	return (1);
3182 }
3183 
3184 /*
3185  *  void cyclic_suspend()
3186  *
3187  *  Overview
3188  *
3189  *    cyclic_suspend() suspends all cyclic activity throughout the cyclic
3190  *    subsystem.  It should be called only by subsystems which are attempting
3191  *    to suspend the entire system (e.g. checkpoint/resume, dynamic
3192  *    reconfiguration).
3193  *
3194  *  Arguments and notes
3195  *
3196  *    cyclic_suspend() takes no arguments.  Each CPU with an active cyclic
3197  *    disables its backend (offline CPUs disable their backends as part of
3198  *    the cyclic_offline() operation), thereby disabling future CY_HIGH_LEVEL
3199  *    interrupts.
3200  *
3201  *    Note that disabling CY_HIGH_LEVEL interrupts does not completely preclude
3202  *    cyclic handlers from being called after cyclic_suspend() returns:  if a
3203  *    CY_LOCK_LEVEL or CY_LOW_LEVEL interrupt thread was blocked at the time
3204  *    of cyclic_suspend(), cyclic handlers at its level may continue to be
3205  *    called after the interrupt thread becomes unblocked.  The
3206  *    post-cyclic_suspend() activity is bounded by the pend count on all
3207  *    cyclics at the time of cyclic_suspend().  Callers concerned with more
3208  *    than simply disabling future CY_HIGH_LEVEL interrupts must check for
3209  *    this condition.
3210  *
3211  *    On most platforms, timestamps from gethrtime() and gethrestime() are not
3212  *    guaranteed to monotonically increase between cyclic_suspend() and
3213  *    cyclic_resume().  However, timestamps are guaranteed to monotonically
3214  *    increase across the entire cyclic_suspend()/cyclic_resume() operation.
3215  *    That is, every timestamp obtained before cyclic_suspend() will be less
3216  *    than every timestamp obtained after cyclic_resume().
3217  *
3218  *  Return value
3219  *
3220  *    None; cyclic_suspend() always succeeds.
3221  *
3222  *  Caller's context
3223  *
3224  *    The cyclic subsystem must be configured on every valid CPU;
3225  *    cyclic_suspend() may not be called during boot or during dynamic
3226  *    reconfiguration.  Additionally, cpu_lock must be held, and the caller
3227  *    cannot be in high-level interrupt context.  However, unlike most other
3228  *    cyclic entry points, cyclic_suspend() may be called with locks held
3229  *    which are also acquired by CY_LOCK_LEVEL or CY_LOW_LEVEL cyclic
3230  *    handlers.
3231  */
3232 void
3233 cyclic_suspend()
3234 {
3235 	cpu_t *c;
3236 	cyc_cpu_t *cpu;
3237 	cyc_xcallarg_t arg;
3238 	cyc_backend_t *be;
3239 
3240 	CYC_PTRACE0("suspend");
3241 	ASSERT(MUTEX_HELD(&cpu_lock));
3242 	c = cpu_list;
3243 
3244 	do {
3245 		cpu = c->cpu_cyclic;
3246 		be = cpu->cyp_backend;
3247 		arg.cyx_cpu = cpu;
3248 
3249 		be->cyb_xcall(be->cyb_arg, c,
3250 		    (cyc_func_t)cyclic_suspend_xcall, &arg);
3251 	} while ((c = c->cpu_next) != cpu_list);
3252 }
3253 
3254 /*
3255  *  void cyclic_resume()
3256  *
3257  *    cyclic_resume() resumes all cyclic activity throughout the cyclic
3258  *    subsystem.  It should be called only by system-suspending subsystems.
3259  *
3260  *  Arguments and notes
3261  *
3262  *    cyclic_resume() takes no arguments.  Each CPU with an active cyclic
3263  *    reenables and reprograms its backend (offline CPUs are not reenabled).
3264  *    On most platforms, timestamps from gethrtime() and gethrestime() are not
3265  *    guaranteed to monotonically increase between cyclic_suspend() and
3266  *    cyclic_resume().  However, timestamps are guaranteed to monotonically
3267  *    increase across the entire cyclic_suspend()/cyclic_resume() operation.
3268  *    That is, every timestamp obtained before cyclic_suspend() will be less
3269  *    than every timestamp obtained after cyclic_resume().
3270  *
3271  *  Return value
3272  *
3273  *    None; cyclic_resume() always succeeds.
3274  *
3275  *  Caller's context
3276  *
3277  *    The cyclic subsystem must be configured on every valid CPU;
3278  *    cyclic_resume() may not be called during boot or during dynamic
3279  *    reconfiguration.  Additionally, cpu_lock must be held, and the caller
3280  *    cannot be in high-level interrupt context.  However, unlike most other
3281  *    cyclic entry points, cyclic_resume() may be called with locks held which
3282  *    are also acquired by CY_LOCK_LEVEL or CY_LOW_LEVEL cyclic handlers.
3283  */
3284 void
3285 cyclic_resume()
3286 {
3287 	cpu_t *c;
3288 	cyc_cpu_t *cpu;
3289 	cyc_xcallarg_t arg;
3290 	cyc_backend_t *be;
3291 
3292 	CYC_PTRACE0("resume");
3293 	ASSERT(MUTEX_HELD(&cpu_lock));
3294 
3295 	c = cpu_list;
3296 
3297 	do {
3298 		cpu = c->cpu_cyclic;
3299 		be = cpu->cyp_backend;
3300 		arg.cyx_cpu = cpu;
3301 
3302 		be->cyb_xcall(be->cyb_arg, c,
3303 		    (cyc_func_t)cyclic_resume_xcall, &arg);
3304 	} while ((c = c->cpu_next) != cpu_list);
3305 }
3306