-
Notifications
You must be signed in to change notification settings - Fork 225
Expand file tree
/
Copy pathcyclic.c
More file actions
3345 lines (2954 loc) · 106 KB
/
cyclic.c
File metadata and controls
3345 lines (2954 loc) · 106 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License, Version 1.0 only
* (the "License"). You may not use this file except in compliance
* with the License.
*
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
* or http://www.opensolaris.org/os/licensing.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright 2004 Sun Microsystems, Inc. All rights reserved.
* Use is subject to license terms.
*/
//#pragma ident "@(#)cyclic.c 1.8 05/06/08 SMI"
/*
* The Cyclic Subsystem
* --------------------
*
* Prehistory
*
* Historically, most computer architectures have specified interval-based
* timer parts (e.g. SPARCstation's counter/timer; Intel's i8254). While
* these parts deal in relative (i.e. not absolute) time values, they are
* typically used by the operating system to implement the abstraction of
* absolute time. As a result, these parts cannot typically be reprogrammed
* without introducing error in the system's notion of time.
*
* Starting in about 1994, chip architectures began specifying high resolution
* timestamp registers. As of this writing (1999), all major chip families
* (UltraSPARC, PentiumPro, MIPS, PowerPC, Alpha) have high resolution
* timestamp registers, and two (UltraSPARC and MIPS) have added the capacity
* to interrupt based on timestamp values. These timestamp-compare registers
* present a time-based interrupt source which can be reprogrammed arbitrarily
* often without introducing error. Given the low cost of implementing such a
* timestamp-compare register (and the tangible benefit of eliminating
* discrete timer parts), it is reasonable to expect that future chip
* architectures will adopt this feature.
*
* The cyclic subsystem has been designed to take advantage of chip
* architectures with the capacity to interrupt based on absolute, high
* resolution values of time.
*
* Subsystem Overview
*
* The cyclic subsystem is a low-level kernel subsystem designed to provide
* arbitrarily high resolution, per-CPU interval timers (to avoid colliding
* with existing terms, we dub such an interval timer a "cyclic"). Cyclics
* can be specified to fire at high, lock or low interrupt level, and may be
* optionally bound to a CPU or a CPU partition. A cyclic's CPU or CPU
* partition binding may be changed dynamically; the cyclic will be "juggled"
* to a CPU which satisfies the new binding. Alternatively, a cyclic may
* be specified to be "omnipresent", denoting firing on all online CPUs.
*
* Cyclic Subsystem Interface Overview
* -----------------------------------
*
* The cyclic subsystem has interfaces with the kernel at-large, with other
* kernel subsystems (e.g. the processor management subsystem, the checkpoint
* resume subsystem) and with the platform (the cyclic backend). Each
* of these interfaces is given a brief synopsis here, and is described
* in full above the interface's implementation.
*
* The following diagram displays the cyclic subsystem's interfaces to
* other kernel components. The arrows denote a "calls" relationship, with
* the large arrow indicating the cyclic subsystem's consumer interface.
* Each arrow is labeled with the section in which the corresponding
* interface is described.
*
* Kernel at-large consumers
* -----------++------------
* ||
* ||
* _||_
* \ /
* \/
* +---------------------+
* | |
* | Cyclic subsystem |<----------- Other kernel subsystems
* | |
* +---------------------+
* ^ |
* | |
* | |
* | v
* +---------------------+
* | |
* | Cyclic backend |
* | (platform specific) |
* | |
* +---------------------+
*
*
* Kernel At-Large Interfaces
*
* cyclic_add() <-- Creates a cyclic
* cyclic_add_omni() <-- Creates an omnipresent cyclic
* cyclic_remove() <-- Removes a cyclic
* cyclic_bind() <-- Change a cyclic's CPU or partition binding
*
* Inter-subsystem Interfaces
*
* cyclic_juggle() <-- Juggles cyclics away from a CPU
* cyclic_offline() <-- Offlines cyclic operation on a CPU
* cyclic_online() <-- Reenables operation on an offlined CPU
* cyclic_move_in() <-- Notifies subsystem of change in CPU partition
* cyclic_move_out() <-- Notifies subsystem of change in CPU partition
* cyclic_suspend() <-- Suspends the cyclic subsystem on all CPUs
* cyclic_resume() <-- Resumes the cyclic subsystem on all CPUs
*
* Backend Interfaces
*
* cyclic_init() <-- Initializes the cyclic subsystem
* cyclic_fire() <-- CY_HIGH_LEVEL interrupt entry point
* cyclic_softint() <-- CY_LOCK/LOW_LEVEL soft interrupt entry point
*
* The backend-supplied interfaces (through the cyc_backend structure) are
* documented in detail in <sys/cyclic_impl.h>
*
*
* Cyclic Subsystem Implementation Overview
* ----------------------------------------
*
* The cyclic subsystem is designed to minimize interference between cyclics
* on different CPUs. Thus, all of the cyclic subsystem's data structures
* hang off of a per-CPU structure, cyc_cpu.
*
* Each cyc_cpu has a power-of-two sized array of cyclic structures (the
* cyp_cyclics member of the cyc_cpu structure). If cyclic_add() is called
* and there does not exist a free slot in the cyp_cyclics array, the size of
* the array will be doubled. The array will never shrink. Cyclics are
* referred to by their index in the cyp_cyclics array, which is of type
* cyc_index_t.
*
* The cyclics are kept sorted by expiration time in the cyc_cpu's heap. The
* heap is keyed by cyclic expiration time, with parents expiring earlier
* than their children.
*
* Heap Management
*
* The heap is managed primarily by cyclic_fire(). Upon entry, cyclic_fire()
* compares the root cyclic's expiration time to the current time. If the
* expiration time is in the past, cyclic_expire() is called on the root
* cyclic. Upon return from cyclic_expire(), the cyclic's new expiration time
* is derived by adding its interval to its old expiration time, and a
* downheap operation is performed. After the downheap, cyclic_fire()
* examines the (potentially changed) root cyclic, repeating the
* cyclic_expire()/add interval/cyclic_downheap() sequence until the root
* cyclic has an expiration time in the future. This expiration time
* (guaranteed to be the earliest in the heap) is then communicated to the
* backend via cyb_reprogram. Optimal backends will next call cyclic_fire()
* shortly after the root cyclic's expiration time.
*
* To allow efficient, deterministic downheap operations, we implement the
* heap as an array (the cyp_heap member of the cyc_cpu structure), with each
* element containing an index into the CPU's cyp_cyclics array.
*
* The heap is laid out in the array according to the following:
*
* 1. The root of the heap is always in the 0th element of the heap array
* 2. The left and right children of the nth element are element
* (((n + 1) << 1) - 1) and element ((n + 1) << 1), respectively.
*
* This layout is standard (see, e.g., Cormen's "Algorithms"); the proof
* that these constraints correctly lay out a heap (or indeed, any binary
* tree) is trivial and left to the reader.
*
* To see the heap by example, assume our cyclics array has the following
* members (at time t):
*
* cy_handler cy_level cy_expire
* ---------------------------------------------
* [ 0] clock() LOCK t+10000000
* [ 1] deadman() HIGH t+1000000000
* [ 2] clock_highres_fire() LOW t+100
* [ 3] clock_highres_fire() LOW t+1000
* [ 4] clock_highres_fire() LOW t+500
* [ 5] (free) -- --
* [ 6] (free) -- --
* [ 7] (free) -- --
*
* The heap array could be:
*
* [0] [1] [2] [3] [4] [5] [6] [7]
* +-----+-----+-----+-----+-----+-----+-----+-----+
* | | | | | | | | |
* | 2 | 3 | 4 | 0 | 1 | x | x | x |
* | | | | | | | | |
* +-----+-----+-----+-----+-----+-----+-----+-----+
*
* Graphically, this array corresponds to the following (excuse the ASCII art):
*
* 2
* |
* +------------------+------------------+
* 3 4
* |
* +---------+--------+
* 0 1
*
* Note that the heap is laid out by layer: all nodes at a given depth are
* stored in consecutive elements of the array. Moreover, layers of
* consecutive depths are in adjacent element ranges. This property
* guarantees high locality of reference during downheap operations.
* Specifically, we are guaranteed that we can downheap to a depth of
*
* lg (cache_line_size / sizeof (cyc_index_t))
*
* nodes with at most one cache miss. On UltraSPARC (64 byte e-cache line
* size), this corresponds to a depth of four nodes. Thus, if there are
* fewer than sixteen cyclics in the heap, downheaps on UltraSPARC miss at
* most once in the e-cache.
*
* Downheaps are required to compare siblings as they proceed down the
* heap. For downheaps proceeding beyond the one-cache-miss depth, every
* access to a left child could potentially miss in the cache. However,
* if we assume
*
* (cache_line_size / sizeof (cyc_index_t)) > 2,
*
* then all siblings are guaranteed to be on the same cache line. Thus, the
* miss on the left child will guarantee a hit on the right child; downheaps
* will incur at most one cache miss per layer beyond the one-cache-miss
* depth. The total number of cache misses for heap management during a
* downheap operation is thus bounded by
*
* lg (n) - lg (cache_line_size / sizeof (cyc_index_t))
*
* Traditional pointer-based heaps are implemented without regard to
* locality. Downheaps can thus incur two cache misses per layer (one for
* each child), but at most one cache miss at the root. This yields a bound
* of
*
* 2 * lg (n) - 1
*
* on the total cache misses.
*
* This difference may seem theoretically trivial (the difference is, after
* all, constant), but can become substantial in practice -- especially for
* caches with very large cache lines and high miss penalties (e.g. TLBs).
*
* Heaps must always be full, balanced trees. Heap management must therefore
* track the next point-of-insertion into the heap. In pointer-based heaps,
* recomputing this point takes O(lg (n)). Given the layout of the
* array-based implementation, however, the next point-of-insertion is
* always:
*
* heap[number_of_elements]
*
* We exploit this property by implementing the free-list in the usused
* heap elements. Heap insertion, therefore, consists only of filling in
* the cyclic at cyp_cyclics[cyp_heap[number_of_elements]], incrementing
* the number of elements, and performing an upheap. Heap deletion consists
* of decrementing the number of elements, swapping the to-be-deleted element
* with the element at cyp_heap[number_of_elements], and downheaping.
*
* Filling in more details in our earlier example:
*
* +--- free list head
* |
* V
*
* [0] [1] [2] [3] [4] [5] [6] [7]
* +-----+-----+-----+-----+-----+-----+-----+-----+
* | | | | | | | | |
* | 2 | 3 | 4 | 0 | 1 | 5 | 6 | 7 |
* | | | | | | | | |
* +-----+-----+-----+-----+-----+-----+-----+-----+
*
* To insert into this heap, we would just need to fill in the cyclic at
* cyp_cyclics[5], bump the number of elements (from 5 to 6) and perform
* an upheap.
*
* If we wanted to remove, say, cyp_cyclics[3], we would first scan for it
* in the cyp_heap, and discover it at cyp_heap[1]. We would then decrement
* the number of elements (from 5 to 4), swap cyp_heap[1] with cyp_heap[4],
* and perform a downheap from cyp_heap[1]. The linear scan is required
* because the cyclic does not keep a backpointer into the heap. This makes
* heap manipulation (e.g. downheaps) faster at the expense of removal
* operations.
*
* Expiry processing
*
* As alluded to above, cyclic_expire() is called by cyclic_fire() at
* CY_HIGH_LEVEL to expire a cyclic. Cyclic subsystem consumers are
* guaranteed that for an arbitrary time t in the future, their cyclic
* handler will have been called (t - cyt_when) / cyt_interval times. Thus,
* there must be a one-to-one mapping between a cyclic's expiration at
* CY_HIGH_LEVEL and its execution at the desired level (either CY_HIGH_LEVEL,
* CY_LOCK_LEVEL or CY_LOW_LEVEL).
*
* For CY_HIGH_LEVEL cyclics, this is trivial; cyclic_expire() simply needs
* to call the handler.
*
* For CY_LOCK_LEVEL and CY_LOW_LEVEL cyclics, however, there exists a
* potential disconnect: if the CPU is at an interrupt level less than
* CY_HIGH_LEVEL but greater than the level of a cyclic for a period of
* time longer than twice the cyclic's interval, the cyclic will be expired
* twice before it can be handled.
*
* To maintain the one-to-one mapping, we track the difference between the
* number of times a cyclic has been expired and the number of times it's
* been handled in a "pending count" (the cy_pend field of the cyclic
* structure). cyclic_expire() thus increments the cy_pend count for the
* expired cyclic and posts a soft interrupt at the desired level. In the
* cyclic subsystem's soft interrupt handler, cyclic_softint(), we repeatedly
* call the cyclic handler and decrement cy_pend until we have decremented
* cy_pend to zero.
*
* The Producer/Consumer Buffer
*
* If we wish to avoid a linear scan of the cyclics array at soft interrupt
* level, cyclic_softint() must be able to quickly determine which cyclics
* have a non-zero cy_pend count. We thus introduce a per-soft interrupt
* level producer/consumer buffer shared with CY_HIGH_LEVEL. These buffers
* are encapsulated in the cyc_pcbuffer structure, and, like cyp_heap, are
* implemented as cyc_index_t arrays (the cypc_buf member of the cyc_pcbuffer
* structure).
*
* The producer (cyclic_expire() running at CY_HIGH_LEVEL) enqueues a cyclic
* by storing the cyclic's index to cypc_buf[cypc_prodndx] and incrementing
* cypc_prodndx. The consumer (cyclic_softint() running at either
* CY_LOCK_LEVEL or CY_LOW_LEVEL) dequeues a cyclic by loading from
* cypc_buf[cypc_consndx] and bumping cypc_consndx. The buffer is empty when
* cypc_prodndx == cypc_consndx.
*
* To bound the size of the producer/consumer buffer, cyclic_expire() only
* enqueues a cyclic if its cy_pend was zero (if the cyclic's cy_pend is
* non-zero, cyclic_expire() only bumps cy_pend). Symmetrically,
* cyclic_softint() only consumes a cyclic after it has decremented the
* cy_pend count to zero.
*
* Returning to our example, here is what the CY_LOW_LEVEL producer/consumer
* buffer might look like:
*
* cypc_consndx ---+ +--- cypc_prodndx
* | |
* V V
*
* [0] [1] [2] [3] [4] [5] [6] [7]
* +-----+-----+-----+-----+-----+-----+-----+-----+
* | | | | | | | | |
* | x | x | 3 | 2 | 4 | x | x | x | <== cypc_buf
* | | | . | . | . | | | |
* +-----+-----+- | -+- | -+- | -+-----+-----+-----+
* | | |
* | | | cy_pend cy_handler
* | | | -------------------------
* | | | [ 0] 1 clock()
* | | | [ 1] 0 deadman()
* | +---- | -------> [ 2] 3 clock_highres_fire()
* +---------- | -------> [ 3] 1 clock_highres_fire()
* +--------> [ 4] 1 clock_highres_fire()
* [ 5] - (free)
* [ 6] - (free)
* [ 7] - (free)
*
* In particular, note that clock()'s cy_pend is 1 but that it is _not_ in
* this producer/consumer buffer; it would be enqueued in the CY_LOCK_LEVEL
* producer/consumer buffer.
*
* Locking
*
* Traditionally, access to per-CPU data structures shared between
* interrupt levels is serialized by manipulating programmable interrupt
* level: readers and writers are required to raise their interrupt level
* to that of the highest level writer.
*
* For the producer/consumer buffers (shared between cyclic_fire()/
* cyclic_expire() executing at CY_HIGH_LEVEL and cyclic_softint() executing
* at one of CY_LOCK_LEVEL or CY_LOW_LEVEL), forcing cyclic_softint() to raise
* programmable interrupt level is undesirable: aside from the additional
* latency incurred by manipulating interrupt level in the hot cy_pend
* processing path, this would create the potential for soft level cy_pend
* processing to delay CY_HIGH_LEVEL firing and expiry processing.
* CY_LOCK/LOW_LEVEL cyclics could thereby induce jitter in CY_HIGH_LEVEL
* cyclics.
*
* To minimize jitter, then, we would like the cyclic_fire()/cyclic_expire()
* and cyclic_softint() code paths to be lock-free.
*
* For cyclic_fire()/cyclic_expire(), lock-free execution is straightforward:
* because these routines execute at a higher interrupt level than
* cyclic_softint(), their actions on the producer/consumer buffer appear
* atomic. In particular, the increment of cy_pend appears to occur
* atomically with the increment of cypc_prodndx.
*
* For cyclic_softint(), however, lock-free execution requires more delicacy.
* When cyclic_softint() discovers a cyclic in the producer/consumer buffer,
* it calls the cyclic's handler and attempts to atomically decrement the
* cy_pend count with a compare&swap operation.
*
* If the compare&swap operation succeeds, cyclic_softint() behaves
* conditionally based on the value it atomically wrote to cy_pend:
*
* - If the cy_pend was decremented to 0, the cyclic has been consumed;
* cyclic_softint() increments the cypc_consndx and checks for more
* enqueued work.
*
* - If the count was decremented to a non-zero value, there is more work
* to be done on the cyclic; cyclic_softint() calls the cyclic handler
* and repeats the atomic decrement process.
*
* If the compare&swap operation fails, cyclic_softint() knows that
* cyclic_expire() has intervened and bumped the cy_pend count (resizes
* and removals complicate this, however -- see the sections on their
* operation, below). cyclic_softint() thus reloads cy_pend, and re-attempts
* the atomic decrement.
*
* Recall that we bound the size of the producer/consumer buffer by
* having cyclic_expire() only enqueue the specified cyclic if its
* cy_pend count is zero; this assures that each cyclic is enqueued at
* most once. This leads to a critical constraint on cyclic_softint(),
* however: after the compare&swap operation which successfully decrements
* cy_pend to zero, cyclic_softint() must _not_ re-examine the consumed
* cyclic. In part to obey this constraint, cyclic_softint() calls the
* cyclic handler before decrementing cy_pend.
*
* Resizing
*
* All of the discussion thus far has assumed a static number of cyclics.
* Obviously, static limitations are not practical; we need the capacity
* to resize our data structures dynamically.
*
* We resize our data structures lazily, and only on a per-CPU basis.
* The size of the data structures always doubles and never shrinks. We
* serialize adds (and thus resizes) on cpu_lock; we never need to deal
* with concurrent resizes. Resizes should be rare; they may induce jitter
* on the CPU being resized, but should not affect cyclic operation on other
* CPUs. Pending cyclics may not be dropped during a resize operation.
*
* Three key cyc_cpu data structures need to be resized: the cyclics array,
* the heap array and the producer/consumer buffers. Resizing the first two
* is relatively straightforward:
*
* 1. The new, larger arrays are allocated in cyclic_expand() (called
* from cyclic_add()).
* 2. cyclic_expand() cross calls cyclic_expand_xcall() on the CPU
* undergoing the resize.
* 3. cyclic_expand_xcall() raises interrupt level to CY_HIGH_LEVEL
* 4. The contents of the old arrays are copied into the new arrays.
* 5. The old cyclics array is bzero()'d
* 6. The pointers are updated.
*
* The producer/consumer buffer is dicier: cyclic_expand_xcall() may have
* interrupted cyclic_softint() in the middle of consumption. To resize the
* producer/consumer buffer, we implement up to two buffers per soft interrupt
* level: a hard buffer (the buffer being produced into by cyclic_expire())
* and a soft buffer (the buffer from which cyclic_softint() is consuming).
* During normal operation, the hard buffer and soft buffer point to the
* same underlying producer/consumer buffer.
*
* During a resize, however, cyclic_expand_xcall() changes the hard buffer
* to point to the new, larger producer/consumer buffer; all future
* cyclic_expire()'s will produce into the new buffer. cyclic_expand_xcall()
* then posts a CY_LOCK_LEVEL soft interrupt, landing in cyclic_softint().
*
* As under normal operation, cyclic_softint() will consume cyclics from
* its soft buffer. After the soft buffer is drained, however,
* cyclic_softint() will see that the hard buffer has changed. At that time,
* cyclic_softint() will change its soft buffer to point to the hard buffer,
* and repeat the producer/consumer buffer draining procedure.
*
* After the new buffer is drained, cyclic_softint() will determine if both
* soft levels have seen their new producer/consumer buffer. If both have,
* cyclic_softint() will post on the semaphore cyp_modify_wait. If not, a
* soft interrupt will be generated for the remaining level.
*
* cyclic_expand() blocks on the cyp_modify_wait semaphore (a semaphore is
* used instead of a condition variable because of the race between the
* sema_p() in cyclic_expand() and the sema_v() in cyclic_softint()). This
* allows cyclic_expand() to know when the resize operation is complete;
* all of the old buffers (the heap, the cyclics array and the producer/
* consumer buffers) can be freed.
*
* A final caveat on resizing: we described step (5) in the
* cyclic_expand_xcall() procedure without providing any motivation. This
* step addresses the problem of a cyclic_softint() attempting to decrement
* a cy_pend count while interrupted by a cyclic_expand_xcall(). Because
* cyclic_softint() has already called the handler by the time cy_pend is
* decremented, we want to assure that it doesn't decrement a cy_pend
* count in the old cyclics array. By zeroing the old cyclics array in
* cyclic_expand_xcall(), we are zeroing out every cy_pend count; when
* cyclic_softint() attempts to compare&swap on the cy_pend count, it will
* fail and recognize that the count has been zeroed. cyclic_softint() will
* update its stale copy of the cyp_cyclics pointer, re-read the cy_pend
* count from the new cyclics array, and re-attempt the compare&swap.
*
* Removals
*
* Cyclic removals should be rare. To simplify the implementation (and to
* allow optimization for the cyclic_fire()/cyclic_expire()/cyclic_softint()
* path), we force removals and adds to serialize on cpu_lock.
*
* Cyclic removal is complicated by a guarantee made to the consumer of
* the cyclic subsystem: after cyclic_remove() returns, the cyclic handler
* has returned and will never again be called.
*
* Here is the procedure for cyclic removal:
*
* 1. cyclic_remove() calls cyclic_remove_xcall() on the CPU undergoing
* the removal.
* 2. cyclic_remove_xcall() raises interrupt level to CY_HIGH_LEVEL
* 3. The current expiration time for the removed cyclic is recorded.
* 4. If the cy_pend count on the removed cyclic is non-zero, it
* is copied into cyp_rpend and subsequently zeroed.
* 5. The cyclic is removed from the heap
* 6. If the root of the heap has changed, the backend is reprogrammed.
* 7. If the cy_pend count was non-zero cyclic_remove() blocks on the
* cyp_modify_wait semaphore.
*
* The motivation for step (3) is explained in "Juggling", below.
*
* The cy_pend count is decremented in cyclic_softint() after the cyclic
* handler returns. Thus, if we find a cy_pend count of zero in step
* (4), we know that cyclic_remove() doesn't need to block.
*
* If the cy_pend count is non-zero, however, we must block in cyclic_remove()
* until cyclic_softint() has finished calling the cyclic handler. To let
* cyclic_softint() know that this cyclic has been removed, we zero the
* cy_pend count. This will cause cyclic_softint()'s compare&swap to fail.
* When cyclic_softint() sees the zero cy_pend count, it knows that it's been
* caught during a resize (see "Resizing", above) or that the cyclic has been
* removed. In the latter case, it calls cyclic_remove_pend() to call the
* cyclic handler cyp_rpend - 1 times, and posts on cyp_modify_wait.
*
* Juggling
*
* At first glance, cyclic juggling seems to be a difficult problem. The
* subsystem must guarantee that a cyclic doesn't execute simultaneously on
* different CPUs, while also assuring that a cyclic fires exactly once
* per interval. We solve this problem by leveraging a property of the
* platform: gethrtime() is required to increase in lock-step across
* multiple CPUs. Therefore, to juggle a cyclic, we remove it from its
* CPU, recording its expiration time in the remove cross call (step (3)
* in "Removing", above). We then add the cyclic to the new CPU, explicitly
* setting its expiration time to the time recorded in the removal. This
* leverages the existing cyclic expiry processing, which will compensate
* for any time lost while juggling.
*
*/
# if linux
#include "dtrace_linux.h"
# undef current
#define CPU_OFFLINE 0x020 /* CPU offline via p_online */
#define gethrtime() dtrace_gethrtime()
hrtime_t dtrace_gethrtime(void);
# define sema_p(x)
# define drv_usecwait udelay
# endif
#include <sys/cyclic_impl.h>
# if defined(sun)
#include <sys/sysmacros.h>
#include <sys/systm.h>
#include <sys/atomic.h>
#include <sys/kmem.h>
#include <sys/cmn_err.h>
#include <sys/ddi.h>
# endif
#ifdef CYCLIC_TRACE
/*
* cyc_trace_enabled is for the benefit of kernel debuggers.
*/
int cyc_trace_enabled = 1;
static cyc_tracebuf_t cyc_ptrace;
static cyc_coverage_t cyc_coverage[CY_NCOVERAGE];
/*
* Seen this anywhere?
*/
static uint_t
cyclic_coverage_hash(char *p)
{
unsigned int g;
uint_t hval;
hval = 0;
while (*p) {
hval = (hval << 4) + *p++;
if ((g = (hval & 0xf0000000)) != 0)
hval ^= g >> 24;
hval &= ~g;
}
return (hval);
}
static void
cyclic_coverage(char *why, int level, uint64_t arg0, uint64_t arg1)
{
uint_t ndx, orig;
for (ndx = orig = cyclic_coverage_hash(why) % CY_NCOVERAGE; ; ) {
if (cyc_coverage[ndx].cyv_why == why)
break;
if (cyc_coverage[ndx].cyv_why != NULL ||
casptr(&cyc_coverage[ndx].cyv_why, NULL, why) != NULL) {
if (++ndx == CY_NCOVERAGE)
ndx = 0;
if (ndx == orig)
panic("too many cyclic coverage points");
continue;
}
/*
* If we're here, we have successfully swung our guy into
* the position at "ndx".
*/
break;
}
if (level == CY_PASSIVE_LEVEL)
cyc_coverage[ndx].cyv_passive_count++;
else
cyc_coverage[ndx].cyv_count[level]++;
cyc_coverage[ndx].cyv_arg0 = arg0;
cyc_coverage[ndx].cyv_arg1 = arg1;
}
#define CYC_TRACE(cpu, level, why, arg0, arg1) \
CYC_TRACE_IMPL(&cpu->cyp_trace[level], level, why, arg0, arg1)
#define CYC_PTRACE(why, arg0, arg1) \
CYC_TRACE_IMPL(&cyc_ptrace, CY_PASSIVE_LEVEL, why, arg0, arg1)
#define CYC_TRACE_IMPL(buf, level, why, a0, a1) { \
if (panicstr == NULL) { \
int _ndx = (buf)->cyt_ndx; \
cyc_tracerec_t *_rec = &(buf)->cyt_buf[_ndx]; \
(buf)->cyt_ndx = (++_ndx == CY_NTRACEREC) ? 0 : _ndx; \
_rec->cyt_tstamp = gethrtime_unscaled(); \
_rec->cyt_why = (why); \
_rec->cyt_arg0 = (uint64_t)(uintptr_t)(a0); \
_rec->cyt_arg1 = (uint64_t)(uintptr_t)(a1); \
cyclic_coverage(why, level, \
(uint64_t)(uintptr_t)(a0), (uint64_t)(uintptr_t)(a1)); \
} \
}
#else
static int cyc_trace_enabled = 0;
#define CYC_TRACE(cpu, level, why, arg0, arg1)
#define CYC_PTRACE(why, arg0, arg1)
#endif
#define CYC_TRACE0(cpu, level, why) CYC_TRACE(cpu, level, why, 0, 0)
#define CYC_TRACE1(cpu, level, why, arg0) CYC_TRACE(cpu, level, why, arg0, 0)
#define CYC_PTRACE0(why) CYC_PTRACE(why, 0, 0)
#define CYC_PTRACE1(why, arg0) CYC_PTRACE(why, arg0, 0)
static kmem_cache_t *cyclic_id_cache;
static cyc_id_t *cyclic_id_head;
static hrtime_t cyclic_resolution;
static cyc_backend_t cyclic_backend;
/*
* Returns 1 if the upheap propagated to the root, 0 if it did not. This
* allows the caller to reprogram the backend only when the root has been
* modified.
*/
static int
cyclic_upheap(cyc_cpu_t *cpu, cyc_index_t ndx)
{
cyclic_t *cyclics;
cyc_index_t *heap;
cyc_index_t heap_parent, heap_current = ndx;
cyc_index_t parent, current;
if (heap_current == 0)
return (1);
heap = cpu->cyp_heap;
cyclics = cpu->cyp_cyclics;
heap_parent = CYC_HEAP_PARENT(heap_current);
for (;;) {
current = heap[heap_current];
parent = heap[heap_parent];
/*
* We have an expiration time later than our parent; we're
* done.
*/
if (cyclics[current].cy_expire >= cyclics[parent].cy_expire)
return (0);
/*
* We need to swap with our parent, and continue up the heap.
*/
heap[heap_parent] = current;
heap[heap_current] = parent;
/*
* If we just reached the root, we're done.
*/
if (heap_parent == 0)
return (1);
heap_current = heap_parent;
heap_parent = CYC_HEAP_PARENT(heap_current);
}
}
static void
cyclic_downheap(cyc_cpu_t *cpu, cyc_index_t ndx)
{
cyclic_t *cyclics = cpu->cyp_cyclics;
cyc_index_t *heap = cpu->cyp_heap;
cyc_index_t heap_left, heap_right, heap_me = ndx;
cyc_index_t left, right, me;
cyc_index_t nelems = cpu->cyp_nelems;
for (;;) {
/*
* If we don't have a left child (i.e., we're a leaf), we're
* done.
*/
if ((heap_left = CYC_HEAP_LEFT(heap_me)) >= nelems)
return;
left = heap[heap_left];
me = heap[heap_me];
heap_right = CYC_HEAP_RIGHT(heap_me);
/*
* Even if we don't have a right child, we still need to compare
* our expiration time against that of our left child.
*/
if (heap_right >= nelems)
goto comp_left;
right = heap[heap_right];
/*
* We have both a left and a right child. We need to compare
* the expiration times of the children to determine which
* expires earlier.
*/
if (cyclics[right].cy_expire < cyclics[left].cy_expire) {
/*
* Our right child is the earlier of our children.
* We'll now compare our expiration time to its; if
* ours is the earlier, we're done.
*/
if (cyclics[me].cy_expire <= cyclics[right].cy_expire)
return;
/*
* Our right child expires earlier than we do; swap
* with our right child, and descend right.
*/
heap[heap_right] = me;
heap[heap_me] = right;
heap_me = heap_right;
continue;
}
comp_left:
/*
* Our left child is the earlier of our children (or we have
* no right child). We'll now compare our expiration time
* to its; if ours is the earlier, we're done.
*/
if (cyclics[me].cy_expire <= cyclics[left].cy_expire)
return;
/*
* Our left child expires earlier than we do; swap with our
* left child, and descend left.
*/
heap[heap_left] = me;
heap[heap_me] = left;
heap_me = heap_left;
}
}
static void
cyclic_expire(cyc_cpu_t *cpu, cyc_index_t ndx, cyclic_t *cyclic)
{
cyc_backend_t *be = cpu->cyp_backend;
cyc_level_t level = cyclic->cy_level;
/*
* If this is a CY_HIGH_LEVEL cyclic, just call the handler; we don't
* need to worry about the pend count for CY_HIGH_LEVEL cyclics.
*/
if (level == CY_HIGH_LEVEL) {
cyc_func_t handler = cyclic->cy_handler;
void *arg = cyclic->cy_arg;
CYC_TRACE(cpu, CY_HIGH_LEVEL, "handler-in", handler, arg);
(*handler)(arg);
CYC_TRACE(cpu, CY_HIGH_LEVEL, "handler-out", handler, arg);
return;
}
/*
* We're at CY_HIGH_LEVEL; this modification to cy_pend need not
* be atomic (the high interrupt level assures that it will appear
* atomic to any softint currently running).
*/
if (cyclic->cy_pend++ == 0) {
cyc_softbuf_t *softbuf = &cpu->cyp_softbuf[level];
cyc_pcbuffer_t *pc = &softbuf->cys_buf[softbuf->cys_hard];
/*
* We need to enqueue this cyclic in the soft buffer.
*/
CYC_TRACE(cpu, CY_HIGH_LEVEL, "expire-enq", cyclic,
pc->cypc_prodndx);
pc->cypc_buf[pc->cypc_prodndx++ & pc->cypc_sizemask] = ndx;
ASSERT(pc->cypc_prodndx != pc->cypc_consndx);
} else {
/*
* If the pend count is zero after we incremented it, then
* we've wrapped (i.e. we had a cy_pend count of over four
* billion. In this case, we clamp the pend count at
* UINT32_MAX. Yes, cyclics can be lost in this case.
*/
if (cyclic->cy_pend == 0) {
CYC_TRACE1(cpu, CY_HIGH_LEVEL, "expire-wrap", cyclic);
cyclic->cy_pend = UINT32_MAX;
}
CYC_TRACE(cpu, CY_HIGH_LEVEL, "expire-bump", cyclic, 0);
}
be->cyb_softint(be->cyb_arg, cyclic->cy_level);
}
# if defined(sun)
/*
* cyclic_fire(cpu_t *)
*
* Overview
*
* cyclic_fire() is the cyclic subsystem's CY_HIGH_LEVEL interrupt handler.
* Called by the cyclic backend.
*
* Arguments and notes
*
* The only argument is the CPU on which the interrupt is executing;
* backends must call into cyclic_fire() on the specified CPU.
*
* cyclic_fire() may be called spuriously without ill effect. Optimal
* backends will call into cyclic_fire() at or shortly after the time
* requested via cyb_reprogram(). However, calling cyclic_fire()
* arbitrarily late will only manifest latency bubbles; the correctness
* of the cyclic subsystem does not rely on the timeliness of the backend.
*
* cyclic_fire() is wait-free; it will not block or spin.
*
* Return values
*
* None.
*
* Caller's context
*
* cyclic_fire() must be called from CY_HIGH_LEVEL interrupt context.
*/
void
cyclic_fire(cpu_t *c)
{
cyc_cpu_t *cpu = c->cpu_cyclic;
cyc_backend_t *be = cpu->cyp_backend;
cyc_index_t *heap = cpu->cyp_heap;
cyclic_t *cyclic, *cyclics = cpu->cyp_cyclics;
void *arg = be->cyb_arg;
hrtime_t now = gethrtime();
hrtime_t exp;
CYC_TRACE(cpu, CY_HIGH_LEVEL, "fire", now, 0);
if (cpu->cyp_nelems == 0) {
/*
* This is a spurious fire. Count it as such, and blow
* out of here.
*/
CYC_TRACE0(cpu, CY_HIGH_LEVEL, "fire-spurious");
return;
}
for (;;) {
cyc_index_t ndx = heap[0];
cyclic = &cyclics[ndx];
ASSERT(!(cyclic->cy_flags & CYF_FREE));
CYC_TRACE(cpu, CY_HIGH_LEVEL, "fire-check", cyclic,
cyclic->cy_expire);
if ((exp = cyclic->cy_expire) > now)
break;
cyclic_expire(cpu, ndx, cyclic);
/*
* If this cyclic will be set to next expire in the distant
* past, we have one of two situations:
*
* a) This is the first firing of a cyclic which had
* cy_expire set to 0.
*
* b) We are tragically late for a cyclic -- most likely
* due to being in the debugger.
*
* In either case, we set the new expiration time to be the
* the next interval boundary. This assures that the
* expiration time modulo the interval is invariant.
*
* We arbitrarily define "distant" to be one second (one second
* is chosen because it's shorter than any foray to the
* debugger while still being longer than any legitimate
* stretch at CY_HIGH_LEVEL).
*/
exp += cyclic->cy_interval;
if (now - exp > NANOSEC) {
hrtime_t interval = cyclic->cy_interval;
CYC_TRACE(cpu, CY_HIGH_LEVEL, exp == interval ?
"fire-first" : "fire-swing", now, exp);
exp += ((now - exp) / interval + 1) * interval;
}
cyclic->cy_expire = exp;
cyclic_downheap(cpu, 0);
}
/*
* Now we have a cyclic in the root slot which isn't in the past;
* reprogram the interrupt source.
*/
be->cyb_reprogram(arg, exp);
}
static void
cyclic_remove_pend(cyc_cpu_t *cpu, cyc_level_t level, cyclic_t *cyclic)
{
cyc_func_t handler = cyclic->cy_handler;
void *arg = cyclic->cy_arg;
uint32_t i, rpend = cpu->cyp_rpend - 1;
ASSERT(cyclic->cy_flags & CYF_FREE);
ASSERT(cyclic->cy_pend == 0);
ASSERT(cpu->cyp_state == CYS_REMOVING);
ASSERT(cpu->cyp_rpend > 0);
CYC_TRACE(cpu, level, "remove-rpend", cyclic, cpu->cyp_rpend);
/*
* Note that we only call the handler cyp_rpend - 1 times; this is
* to account for the handler call in cyclic_softint().
*/
for (i = 0; i < rpend; i++) {
CYC_TRACE(cpu, level, "rpend-in", handler, arg);
(*handler)(arg);
CYC_TRACE(cpu, level, "rpend-out", handler, arg);
}
/*
* We can now let the remove operation complete.
*/
sema_v(&cpu->cyp_modify_wait);
}
/*
* cyclic_softint(cpu_t *cpu, cyc_level_t level)
*
* Overview