-
Notifications
You must be signed in to change notification settings - Fork 392
Expand file tree
/
Copy pathsmr.c
More file actions
3258 lines (2773 loc) · 84.8 KB
/
Copy pathsmr.c
File metadata and controls
3258 lines (2773 loc) · 84.8 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
/*
* Copyright (c) 2021 Apple Inc. All rights reserved.
*
* @APPLE_OSREFERENCE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. The rights granted to you under the License
* may not be used to create, or enable the creation or redistribution of,
* unlawful or unlicensed copies of an Apple operating system, or to
* circumvent, violate, or enable the circumvention or violation of, any
* terms of an Apple operating system software license agreement.
*
* Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_OSREFERENCE_LICENSE_HEADER_END@
*/
#include <kern/locks_internal.h>
#include <kern/lock_ptr.h>
#include <kern/cpu_data.h>
#include <kern/machine.h>
#include <kern/mpsc_queue.h>
#include <kern/percpu.h>
#include <kern/sched.h>
#include <kern/smr.h>
#include <kern/smr_hash.h>
#include <kern/thread.h>
#include <kern/zalloc.h>
#include <machine/commpage.h>
#include <os/hash.h>
#pragma mark - SMR domains
/*
* This SMR scheme is directly FreeBSD's "Global Unbounded Sequences".
*
* Major differences are:
*
* - only eager clocks are implemented (no lazy, no implicit)
*
*
* SMR clocks have 3 state machines interacting at any given time:
*
* 1. reader critical sections
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~
*
* Each CPU can disable preemption and do this sequence:
*
* CPU::c_rd_seq = GLOBAL::c_wr_seq;
*
* < unfortunate place to receive a long IRQ > [I]
*
* os_atomic_thread_fence(seq_cst); [R1]
*
* {
* // critical section
* }
*
* os_atomic_store(&CPU::c_rd_seq, INVALID, release); [R2]
*
*
*
* 2. writer sequence advances
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~
*
* Each writer can increment the global write sequence
* at any given time:
*
* os_atomic_add(&GLOBAL::c_wr_seq, SMR_SEQ_INC, release); [W]
*
*
*
* 3. synchronization sequence: poll/wait/scan
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*
* This state machine synchronizes with the other two in order to decide
* if a given "goal" is in the past. Only the cases when the call
* is successful is interresting for barrier purposes, and we will focus
* on cases that do not take an early return for failures.
*
* a. __smr_poll:
*
* rd_seq = os_atomic_load(&GLOBAL::c_rd_seq, acquire); [S1]
* if (goal < rd_seq) SUCCESS.
* wr_seq = os_atomic_load(&GLOBAL::c_rd_seq, relaxed);
*
* b. __smr_scan
*
* os_atomic_thread_fence(seq_cst) [S2]
*
* observe the minimum CPU::c_rd_seq "min_rd_seq"
* value possible or rw_seq if no CPU was in a critical section.
* (possibly spinning until it satisfies "goal")
*
* c. __smr_rd_advance
*
* cur_rd_seq = load_exclusive(&GLOBAL::c_rd_seq);
* os_atomic_thread_fence(seq_cst); [S3]
* if (min_rd_seq > cur_rd_seq) {
* store_exlusive(&GLOBAL::c_rd_seq, min_rd_seq);
* }
*
*
* One sentence summary
* ~~~~~~~~~~~~~~~~~~~~
*
* A simplistic one-sentence summary of the algorithm is that __smr_scan()
* works really hard to insert itself in the timeline of write sequences and
* observe a reasonnable bound for first safe-to-reclaim sequence, and
* issues [S3] to sequence everything around "c_rd_seq" (via [S3] -> [S1]):
*
* GLOBAL::c_rd_seq GLOBAL::c_wr_seq
* v v
* ──────────────────────┬────────────────┬─────────────────────
* ... safe to reclaim │ deferred │ future ...
* ──────────────────────┴────────────────┴─────────────────────
*
*
* Detailed explanation
* ~~~~~~~~~~~~~~~~~~~~
*
* [W] -> [R1] establishes a "happens before" relationship between a given
* writer and this critical section. The loaded GLOBAL::c_wr_seq might
* however be stale with respect to the one [R1] really synchronizes with
* (see [I] explanation below).
*
*
* [R1] -> [S2] establishes a "happens before" relationship between all the
* active critical sections and the scanner.
* It lets us compute the oldest possible sequence pinned by an active
* critical section.
*
*
* [R2] -> [S3] establishes a "happens before" relationship between all the
* inactive critical sections and the scanner.
*
*
* [S3] -> [S1] is the typical expected fastpath: when the caller can decide
* that its goal is older than the last update an __smr_rd_advance() did.
* Note that [S3] doubles as an "[S1]" when two __smr_scan() race each other
* and one of them finishes last but observed a "worse" read sequence.
*
*
* [W], [S3] -> [S1] is the last crucial property: all updates to the global
* clock are totally ordered because they update the entire 128bit state
* every time with an RMW. This guarantees that __smr_poll() can't load
* an `rd_seq` that is younger than the `wr_seq` it loads next.
*
*
* [I] __smr_enter() also can be unfortunately delayed after observing
* a given write sequence and right before [R1] at [I].
*
* However for a read sequence to have move past what __smr_enter() observed,
* it means another __smr_scan() didn't observe the store to CPU::c_rd_seq
* made by __smr_enter() and thought the section was inactive.
*
* This can only happen if the scan's [S2] was issued before the delayed
* __smr_enter() [R1] (during the [I] window).
*
* As a consequence the outcome of that scan can be accepted as the "real"
* write sequence __smr_enter() should have observed.
*
*
* Litmus tests
* ~~~~~~~~~~~~
*
* This is the proof of [W] -> [R1] -> [S2] being established properly:
* - P0 sets a global and calls smr_synchronize()
* - P1 does smr_enter() and loads the global
*
* AArch64 MP
* {
* global = 0;
* wr_seq = 123;
* p1_rd_seq = 0;
*
* 0:x0 = global; 0:x1 = wr_seq; 0:x2 = p1_rd_seq;
* 1:x0 = global; 1:x1 = wr_seq; 1:x2 = p1_rd_seq;
* }
* P0 | P1 ;
* MOV X8, #2 | LDR X8, [X1] ;
* STR X8, [X0] | STR X8, [X2] ;
* LDADDL X8, X9, [X1] | DMB SY ;
* DMB SY | LDR X10, [X0] ;
* LDR X10, [X2] | ;
* exists (0:X10 = 0 /\ 1:X8 = 123 /\ 1:X10 = 0)
*
*
* This is the proof that deferred advances are also correct:
* - P0 sets a global and does a smr_deferred_advance()
* - P1 does an smr_synchronize() and reads the global
*
* AArch64 MP
* {
* global = 0;
* wr_seq = 123;
*
* 0:x0 = global; 0:x1 = wr_seq; 0:x2 = 2;
* 1:x0 = global; 1:x1 = wr_seq; 1:x2 = 2;
* }
* P0 | P1 ;
* STR X2, [X0] | LDADDL X2, X9, [X1] ;
* DMB SY | DMB SY ;
* LDR X9, [X1] | LDR X10, [X0] ;
* ADD X9, X9, X2 | ;
* exists (0:X9 = 125 /\ 1:X9 = 123 /\ 1:X10 = 0)
*
*/
/*!
* @struct smr_worker
*
* @brief
* Structure tracking the per-cpu SMR workers state.
*
* @discussion
* This structure is system wide and global and is used to track
* the various active SMR domains at the granularity of a CPU.
*
* Each structure has an associated thread which is responsible
* for the forward progress the @c smr_call() and @c smr_barrier()
* interfaces.
*
* It also tracks all the active, non stalled, sleepable SMR sections.
*/
struct smr_worker {
/*
* The thread for this worker,
* and conveniency pointer to the processor it is bound to.
*/
struct thread *thread;
struct processor *processor;
/*
* Thread binding/locking logic:
*
* If the worker thread is running on its canonical CPU,
* then locking to access the various SMR per-cpu data
* structures it is draining is just preemption disablement.
*
* However, if it is currently not bound to its canonical
* CPU because the CPU has been offlined or de-recommended,
* then a lock which serializes with the CPU going online
* again is being used.
*/
struct waitq waitq;
smr_cpu_reason_t detach_reason;
#if CONFIG_QUIESCE_COUNTER
/*
* Currently active quiescent generation for this processor,
* and the last timestamp when a scan of all cores was performed.
*/
smr_seq_t rd_quiesce_seq;
#endif
/*
* List of all the active sleepable sections that haven't
* been stalled.
*/
struct smrq_list_head sect_queue;
struct thread *sect_waiter;
/*
* Queue of SMR domains with pending smr_call()
* callouts to drain.
*
* This uses an ageing strategy in order to amortize
* SMR clock updates:
*
* - the "old" queue have domains whose callbacks have
* a committed and aged sequence,
* - the "age" queue have domains whose callbacks have
* a commited but fresh sequence and need ageing,
* - the "cur" queue have domains whose callbacks have
* a sequence in the future and need for it to be committed.
*/
struct smr_pcpu *whead;
struct smr_pcpu **wold_tail;
struct smr_pcpu **wage_tail;
struct smr_pcpu **wcur_tail;
uint64_t drain_ctime;
/*
* Queue of smr_barrier() calls in flight,
* that will be picked up by the worker thread
* to enqueue as smr_call() entries in their
* respective per-CPU data structures.
*/
struct mpsc_queue_head barrier_queue;
} __attribute__((aligned(64)));
typedef struct smr_pcpu {
/*
* CPU private cacheline.
*
* Nothing else than the CPU this state is made for,
* ever writes to this cacheline.
*
* It holds the epoch activity witness (rd_seq), and
* the local smr_call() queue, which is structured this way:
*
* head -> n1 -> n2 -> n3 -> n4 -> ... -> ni -> ... -> nN -> NULL
* ^ ^ ^
* qold_tail -------------' | |
* qage_tail --------------------------' |
* qcur_tail ---------------------------------------------'
*
* - the "old" queue can be reclaimed once qold_seq is past,
* qold_seq is always a commited sequence.
* - the "age" queue can be reclaimed once qage_seq is past,
* qage_seq might not be commited yet.
* - the "cur" queue has an approximate size of qcur_size bytes,
* and a length of qcur_cnt callbacks.
*/
smr_seq_t c_rd_seq; /* might have SMR_SEQ_SLEEPABLE set */
smr_node_t qhead;
smr_seq_t qold_seq;
smr_node_t *qold_tail;
smr_seq_t qage_seq;
smr_node_t *qage_tail;
uint32_t qcur_size;
uint32_t qcur_cnt;
smr_node_t *qcur_tail;
uint8_t __cacheline_sep[0];
/*
* Drain queue.
*
* This is used to drive smr_call() via the smr worker threads.
* If the SMR domain is not using smr_call() or smr_barrier(),
* this isn't used.
*/
struct smr *drain_smr;
struct smr_pcpu *drain_next;
uint16_t __check_cpu;
uint8_t __check_reason;
uint8_t __check_list;
/*
* Stalled queue.
*
* Stalled sections are enqueued onto this queue by the scheduler
* when their thread blocks (see smr_mark_active_trackers_stalled()).
*
* If the SMR domain is not sleepable, then this isn't used.
*
* This list is protected by a lock.
*
* When there are stalled sections, stall_rd_seq contains
* the oldest active stalled sequence number.
*
* When threads want to expedite a stalled section, they set
* stall_waiter_goal to the sequence number they are waiting
* for and block via turnstile on the oldest stalled section.
*/
hw_lck_ticket_t stall_lock;
smr_seq_t stall_rd_seq;
smr_seq_t stall_waiter_goal;
struct smrq_tailq_head stall_queue;
struct turnstile *stall_ts;
} __attribute__((aligned(128))) * smr_pcpu_t;
static_assert(offsetof(struct smr_pcpu, __cacheline_sep) == 64);
static_assert(sizeof(struct smr_pcpu) == 128);
#define CPU_CHECKIN_MIN_INTERVAL_US 5000 /* 5ms */
#define CPU_CHECKIN_MIN_INTERVAL_MAX_US USEC_PER_SEC /* 1s */
static uint64_t cpu_checkin_min_interval;
static uint32_t cpu_checkin_min_interval_us;
/*! the amount of memory pending retiring that causes a foreceful flush */
#if XNU_TARGET_OS_OSX
static TUNABLE(vm_size_t, smr_call_size_cap, "smr_call_size_cap", 256 << 10);
static TUNABLE(vm_size_t, smr_call_cnt_cap, "smr_call_cnt_cap", 128);
#else
static TUNABLE(vm_size_t, smr_call_size_cap, "smr_call_size_cap", 64 << 10);
static TUNABLE(vm_size_t, smr_call_cnt_cap, "smr_call_cnt_cap", 32);
#endif
/* time __smr_wait_for_oncore busy spins before going the expensive route */
static TUNABLE(uint32_t, smr_wait_spin_us, "smr_wait_spin_us", 20);
static LCK_GRP_DECLARE(smr_lock_grp, "smr");
static struct smr_worker PERCPU_DATA(smr_worker);
static struct smrq_tailq_head smr_domains = SMRQ_TAILQ_INITIALIZER(smr_domains);
SMR_DEFINE_FLAGS(smr_system, "system", SMR_NONE);
SMR_DEFINE_FLAGS(smr_system_sleepable, "system (sleepable)", SMR_SLEEPABLE);
#pragma mark SMR domains: init & helpers
#define SMR_PCPU_NOT_QUEUED ((struct smr_pcpu *)-1)
__attribute__((always_inline, overloadable))
static inline smr_pcpu_t
__smr_pcpu(smr_t smr, int cpu)
{
return &smr->smr_pcpu[cpu];
}
__attribute__((always_inline, overloadable))
static inline smr_pcpu_t
__smr_pcpu(smr_t smr)
{
return __smr_pcpu(smr, cpu_number());
}
static inline bool
__smr_pcpu_queued(smr_pcpu_t pcpu)
{
return pcpu->drain_next != SMR_PCPU_NOT_QUEUED;
}
static inline void
__smr_pcpu_set_not_queued(smr_pcpu_t pcpu)
{
pcpu->drain_next = SMR_PCPU_NOT_QUEUED;
}
static inline void
__smr_pcpu_associate(smr_t smr, smr_pcpu_t pcpu)
{
zpercpu_foreach_cpu(cpu) {
pcpu[cpu].qold_tail = &pcpu[cpu].qhead;
pcpu[cpu].qage_tail = &pcpu[cpu].qhead;
pcpu[cpu].qcur_tail = &pcpu[cpu].qhead;
pcpu[cpu].drain_smr = smr;
__smr_pcpu_set_not_queued(&pcpu[cpu]);
hw_lck_ticket_init(&pcpu[cpu].stall_lock, &smr_lock_grp);
smrq_init(&pcpu[cpu].stall_queue);
}
os_atomic_store(&smr->smr_pcpu, pcpu, release);
}
static inline event64_t
__smrw_oncore_event(struct smr_worker *smrw)
{
return CAST_EVENT64_T(&smrw->sect_queue);
}
static inline event64_t
__smrw_drain_event(struct smr_worker *smrw)
{
return CAST_EVENT64_T(&smrw->whead);
}
static inline processor_t
__smrw_drain_bind_target(struct smr_worker *smrw)
{
return smrw->detach_reason ? PROCESSOR_NULL : smrw->processor;
}
static inline void
__smrw_lock(struct smr_worker *smrw)
{
waitq_lock(&smrw->waitq);
}
static inline void
__smrw_unlock(struct smr_worker *smrw)
{
waitq_unlock(&smrw->waitq);
}
/*!
* @function __smrw_wakeup_and_unlock()
*
* @brief
* Wakes up (with binding) the SMR worker.
*
* @discussion
* Wakeup the worker thread and bind it to the proper processor
* as a side effect.
*
* This function must be called with interrupts disabled.
*/
static bool
__smrw_wakeup_and_unlock(struct smr_worker *smrw)
{
thread_t thread;
assert(!ml_get_interrupts_enabled());
thread = waitq_wakeup64_identify_locked(&smrw->waitq,
__smrw_drain_event(smrw), THREAD_AWAKENED, WAITQ_UNLOCK);
if (thread != THREAD_NULL) {
assert(thread == smrw->thread);
waitq_resume_and_bind_identified_thread(&smrw->waitq,
thread, __smrw_drain_bind_target(smrw),
THREAD_AWAKENED, WAITQ_WAKEUP_DEFAULT);
}
return thread != THREAD_NULL;
}
static void
__smr_call_drain(smr_node_t head)
{
smr_node_t node;
while ((node = head) != NULL) {
head = node->smrn_next;
node->smrn_next = NULL;
node->smrn_cb(node);
}
}
__startup_func
void
__smr_domain_init(smr_t smr)
{
smr_pcpu_t pcpu;
vm_size_t size;
if (startup_phase < STARTUP_SUB_TUNABLES) {
smr_seq_t *rd_seqp = &smr->smr_early;
/*
* This is a big cheat, but before the EARLY_BOOT phase,
* all smr_* APIs that would access past the rd_seq
* will early return.
*/
pcpu = __container_of(rd_seqp, struct smr_pcpu, c_rd_seq);
smr->smr_pcpu = pcpu - cpu_number();
assert(&__smr_pcpu(smr)->c_rd_seq == &smr->smr_early);
} else {
size = zpercpu_count() * sizeof(struct smr_pcpu);
pcpu = zalloc_permanent(size, ZALIGN(struct smr_pcpu));
__smr_pcpu_associate(smr, pcpu);
}
}
smr_t
smr_domain_create(smr_flags_t flags, const char *name)
{
smr_pcpu_t pcpu;
smr_t smr;
smr = kalloc_type(struct smr, Z_WAITOK | Z_ZERO | Z_NOFAIL);
pcpu = kalloc_type(struct smr_pcpu, zpercpu_count(),
Z_WAITOK | Z_ZERO | Z_NOFAIL);
smr->smr_clock.s_rd_seq = SMR_SEQ_INIT;
smr->smr_clock.s_wr_seq = SMR_SEQ_INIT;
smr->smr_flags = flags;
static_assert(sizeof(struct smr) ==
offsetof(struct smr, smr_name) + SMR_NAME_MAX);
strlcpy(smr->smr_name, name, sizeof(smr->smr_name));
__smr_pcpu_associate(smr, pcpu);
return smr;
}
void
smr_domain_free(smr_t smr)
{
smr_barrier(smr);
zpercpu_foreach_cpu(cpu) {
smr_pcpu_t pcpu = __smr_pcpu(smr, cpu);
assert(pcpu->qhead == NULL);
hw_lck_ticket_destroy(&pcpu->stall_lock, &smr_lock_grp);
}
kfree_type(struct smr_pcpu, zpercpu_count(), smr->smr_pcpu);
kfree_type(struct smr, smr);
}
#pragma mark SMR domains: enter / leave
bool
smr_entered(smr_t smr)
{
thread_t self = current_thread();
smr_tracker_t t;
if (lock_preemption_level_for_thread(self) &&
__smr_pcpu(smr)->c_rd_seq != SMR_SEQ_INVALID) {
return true;
}
if (smr->smr_flags & SMR_SLEEPABLE) {
smrq_serialized_foreach(t, &self->smr_stack, smrt_stack) {
if (t->smrt_domain == smr) {
return true;
}
}
}
return false;
}
__attribute__((always_inline))
bool
smr_entered_cpu_noblock(smr_t smr, int cpu)
{
assert((smr->smr_flags & SMR_SLEEPABLE) == 0);
return __smr_pcpu(smr, cpu)->c_rd_seq != SMR_SEQ_INVALID;
}
__attribute__((always_inline))
static smr_seq_t
__smr_enter(smr_t smr, smr_pcpu_t pcpu, smr_seq_t sleepable)
{
smr_seq_t s_wr_seq;
smr_seq_t old_seq;
assert(!ml_at_interrupt_context());
/*
* It is possible to have a long delay between loading the s_wr_seq
* and storing it to the percpu copy of it.
*
* It is unlikely but possible by that time the s_rd_seq advances
* ahead of what we will store. This however is still safe
* and handled in __smr_scan().
*
* On Intel, to achieve the ordering we want, we could use a store
* followed by an mfence, or any RMW (XCHG, XADD, CMPXCHG, ...).
* XADD is just the fastest instruction of the alternatives,
* but it will only ever add to '0'.
*/
s_wr_seq = os_atomic_load(&smr->smr_clock.s_wr_seq, relaxed);
#if __x86_64__
/* [R1] */
old_seq = os_atomic_add_orig(&pcpu->c_rd_seq, s_wr_seq | sleepable, seq_cst);
#else
old_seq = pcpu->c_rd_seq;
os_atomic_store(&pcpu->c_rd_seq, s_wr_seq | sleepable, relaxed);
os_atomic_thread_fence(seq_cst); /* [R1] */
#endif
assert(old_seq == SMR_SEQ_INVALID);
return s_wr_seq;
}
__attribute__((always_inline))
static void
__smr_leave(smr_pcpu_t pcpu)
{
assert(!ml_at_interrupt_context());
/* [R2] */
os_atomic_store(&pcpu->c_rd_seq, SMR_SEQ_INVALID, release);
}
__attribute__((always_inline))
void
smr_enter(smr_t smr)
{
disable_preemption();
__smr_enter(smr, __smr_pcpu(smr), 0);
}
__attribute__((always_inline))
void
smr_leave(smr_t smr)
{
__smr_leave(__smr_pcpu(smr));
enable_preemption();
}
void
smr_enter_sleepable(smr_t smr, smr_tracker_t tracker)
{
thread_t self = current_thread();
struct smr_worker *smrw;
smr_pcpu_t pcpu;
assert(smr->smr_flags & SMR_SLEEPABLE);
lock_disable_preemption_for_thread(self);
lck_rw_lock_count_inc(self, smr);
pcpu = __smr_pcpu(smr);
smrw = PERCPU_GET(smr_worker);
tracker->smrt_domain = smr;
tracker->smrt_seq = __smr_enter(smr, pcpu, SMR_SEQ_SLEEPABLE);
smrq_serialized_insert_head_relaxed(&smrw->sect_queue, &tracker->smrt_link);
smrq_serialized_insert_head_relaxed(&self->smr_stack, &tracker->smrt_stack);
tracker->smrt_ctid = 0;
tracker->smrt_cpu = -1;
lock_enable_preemption();
}
__attribute__((always_inline))
static void
__smr_wake_oncore_sleepers(struct smr_worker *smrw)
{
/*
* prevent reordering of making the list empty and checking for waiters.
*/
if (__improbable(os_atomic_load(&smrw->sect_waiter, compiler_acq_rel))) {
if (smrq_empty(&smrw->sect_queue)) {
os_atomic_store(&smrw->sect_waiter, NULL, relaxed);
waitq_wakeup64_all(&smrw->waitq,
__smrw_oncore_event(smrw), THREAD_AWAKENED,
WAITQ_WAKEUP_DEFAULT);
}
}
}
void
smr_ack_ipi(void)
{
/*
* see __smr_wait_for_oncore(): if at the time of the IPI ack
* the list is empty and there is still a waiter, wake it up.
*
* If the queue is not empty, then when smr_leave_sleepable()
* runs it can't possibly fail to observe smrw->sect_waiter
* being non NULL and will do the wakeup then.
*/
__smr_wake_oncore_sleepers(PERCPU_GET(smr_worker));
}
void
smr_mark_active_trackers_stalled(thread_t self)
{
struct smr_worker *smrw = PERCPU_GET(smr_worker);
int cpu = cpu_number();
smr_tracker_t t;
/* called at splsched */
smrq_serialized_foreach_safe(t, &smrw->sect_queue, smrt_link) {
smr_t smr = t->smrt_domain;
smr_pcpu_t pcpu;
pcpu = __smr_pcpu(smr, cpu);
t->smrt_ctid = self->ctid;
t->smrt_cpu = cpu;
hw_lck_ticket_lock_nopreempt(&pcpu->stall_lock, &smr_lock_grp);
/*
* Transfer the section to the stalled queue,
* and _then_ leave the regular one.
*
* A store-release is sufficient to order these stores,
* and guarantee that __smr_scan() can't fail to observe
* both the @c rd_seq and @c stall_rd_seq during a transfer
* of a stalled section that was active when it started.
*/
if (smrq_empty(&pcpu->stall_queue)) {
os_atomic_store(&pcpu->stall_rd_seq, t->smrt_seq, relaxed);
}
os_atomic_store(&pcpu->c_rd_seq, SMR_SEQ_INVALID, release);
smrq_serialized_insert_tail_relaxed(&pcpu->stall_queue, &t->smrt_link);
hw_lck_ticket_unlock_nopreempt(&pcpu->stall_lock);
}
smrq_init(&smrw->sect_queue);
__smr_wake_oncore_sleepers(smrw);
}
__attribute__((noinline))
static void
__smr_leave_stalled(smr_t smr, smr_tracker_t tracker, thread_t self)
{
smr_seq_t new_stall_seq = SMR_SEQ_INVALID;
smr_tracker_t first = NULL;
smr_pcpu_t pcpu;
bool progress;
pcpu = __smr_pcpu(smr, tracker->smrt_cpu);
hw_lck_ticket_lock_nopreempt(&pcpu->stall_lock, &smr_lock_grp);
progress = smrq_serialized_first(&pcpu->stall_queue,
struct smr_tracker, smrt_link) == tracker;
smrq_serialized_remove(&self->smr_stack, &tracker->smrt_stack);
smrq_serialized_remove(&pcpu->stall_queue, &tracker->smrt_link);
bzero(tracker, sizeof(*tracker));
if (progress) {
if (!smrq_empty(&pcpu->stall_queue)) {
first = smrq_serialized_first(&pcpu->stall_queue,
struct smr_tracker, smrt_link);
new_stall_seq = first->smrt_seq;
__builtin_assume(new_stall_seq != SMR_SEQ_INVALID);
assert(SMR_SEQ_CMP(pcpu->stall_rd_seq, <=, new_stall_seq));
}
os_atomic_store(&pcpu->stall_rd_seq, new_stall_seq, release);
progress = pcpu->stall_waiter_goal != SMR_SEQ_INVALID;
}
if (progress) {
struct turnstile *ts;
ts = turnstile_prepare((uintptr_t)pcpu, &pcpu->stall_ts,
TURNSTILE_NULL, TURNSTILE_KERNEL_MUTEX);
if (new_stall_seq == SMR_SEQ_INVALID ||
SMR_SEQ_CMP(pcpu->stall_waiter_goal, <=, new_stall_seq)) {
pcpu->stall_waiter_goal = SMR_SEQ_INVALID;
waitq_wakeup64_all(&ts->ts_waitq, CAST_EVENT64_T(pcpu),
THREAD_AWAKENED, WAITQ_UPDATE_INHERITOR);
} else {
turnstile_update_inheritor(ts, ctid_get_thread(first->smrt_ctid),
TURNSTILE_IMMEDIATE_UPDATE | TURNSTILE_INHERITOR_THREAD);
}
turnstile_update_inheritor_complete(ts, TURNSTILE_INTERLOCK_HELD);
turnstile_complete((uintptr_t)pcpu, &pcpu->stall_ts,
NULL, TURNSTILE_KERNEL_MUTEX);
}
/* reenables preemption disabled in smr_leave_sleepable() */
hw_lck_ticket_unlock(&pcpu->stall_lock);
turnstile_cleanup();
}
void
smr_leave_sleepable(smr_t smr, smr_tracker_t tracker)
{
struct smr_worker *smrw;
thread_t self = current_thread();
assert(tracker->smrt_seq != SMR_SEQ_INVALID);
assert(smr->smr_flags & SMR_SLEEPABLE);
lock_disable_preemption_for_thread(self);
lck_rw_lock_count_dec(self, smr);
if (__improbable(tracker->smrt_cpu != -1)) {
return __smr_leave_stalled(smr, tracker, self);
}
__smr_leave(__smr_pcpu(smr));
smrw = PERCPU_GET(smr_worker);
smrq_serialized_remove(&self->smr_stack, &tracker->smrt_stack);
smrq_serialized_remove(&smrw->sect_queue, &tracker->smrt_link);
bzero(tracker, sizeof(*tracker));
__smr_wake_oncore_sleepers(PERCPU_GET(smr_worker));
lock_enable_preemption();
}
#pragma mark SMR domains: advance, wait, poll, synchronize
static inline smr_seq_t
__smr_wr_advance(smr_t smr)
{
/* [W] */
return os_atomic_add(&smr->smr_clock.s_wr_seq, SMR_SEQ_INC, release);
}
static inline bool
__smr_rd_advance(smr_t smr, smr_seq_t goal, smr_seq_t rd_seq)
{
smr_seq_t o_seq;
os_atomic_thread_fence(seq_cst); /* [S3] */
os_atomic_rmw_loop(&smr->smr_clock.s_rd_seq, o_seq, rd_seq, relaxed, {
if (SMR_SEQ_CMP(rd_seq, <=, o_seq)) {
rd_seq = o_seq;
os_atomic_rmw_loop_give_up(break);
}
});
return SMR_SEQ_CMP(goal, <=, rd_seq);
}
__attribute__((noinline))
static smr_seq_t
__smr_wait_for_stalled(smr_pcpu_t pcpu, smr_seq_t goal)
{
struct turnstile *ts;
thread_t inheritor;
wait_result_t wr;
smr_seq_t stall_rd_seq;
hw_lck_ticket_lock(&pcpu->stall_lock, &smr_lock_grp);
stall_rd_seq = pcpu->stall_rd_seq;
if (stall_rd_seq == SMR_SEQ_INVALID ||
SMR_SEQ_CMP(goal, <=, stall_rd_seq)) {
hw_lck_ticket_unlock(&pcpu->stall_lock);
return stall_rd_seq;
}
if (pcpu->stall_waiter_goal == SMR_SEQ_INVALID ||
SMR_SEQ_CMP(goal, <, pcpu->stall_waiter_goal)) {
pcpu->stall_waiter_goal = goal;
}
inheritor = ctid_get_thread(smrq_serialized_first(&pcpu->stall_queue,
struct smr_tracker, smrt_link)->smrt_ctid);
ts = turnstile_prepare((uintptr_t)pcpu, &pcpu->stall_ts,
TURNSTILE_NULL, TURNSTILE_KERNEL_MUTEX);
turnstile_update_inheritor(ts, inheritor,
TURNSTILE_DELAYED_UPDATE | TURNSTILE_INHERITOR_THREAD);
wr = waitq_assert_wait64(&ts->ts_waitq, CAST_EVENT64_T(pcpu),
THREAD_UNINT, TIMEOUT_WAIT_FOREVER);
turnstile_update_inheritor_complete(ts, TURNSTILE_INTERLOCK_HELD);
if (wr == THREAD_WAITING) {
hw_lck_ticket_unlock(&pcpu->stall_lock);
thread_block(THREAD_CONTINUE_NULL);
hw_lck_ticket_lock(&pcpu->stall_lock, &smr_lock_grp);
}
turnstile_complete((uintptr_t)pcpu, &pcpu->stall_ts,
NULL, TURNSTILE_KERNEL_MUTEX);
stall_rd_seq = pcpu->stall_rd_seq;
hw_lck_ticket_unlock(&pcpu->stall_lock);
turnstile_cleanup();
return stall_rd_seq;
}
__attribute__((noinline))
static smr_seq_t
__smr_wait_for_oncore(smr_pcpu_t pcpu, smr_seq_t goal, uint32_t cpu)
{
thread_t self = current_thread();
struct smr_worker *smrw;
uint64_t deadline = 0;
vm_offset_t base;
smr_seq_t rd_seq;
/*
* We are waiting for a currently active SMR section.
* Start spin-waiting for it for a bit.
*/
for (;;) {
if (hw_spin_wait_until(&pcpu->c_rd_seq, rd_seq,
rd_seq == SMR_SEQ_INVALID || SMR_SEQ_CMP(goal, <=, rd_seq))) {
return rd_seq;
}
if (deadline == 0) {
clock_interval_to_deadline(smr_wait_spin_us,
NSEC_PER_USEC, &deadline);
} else if (mach_absolute_time() > deadline) {
break;
}
}
/*
* This section is being active for a while,
* we need to move to a more passive way of waiting.
*
* We post ourselves on the remote processor tracking head,
* to denote we need a thread_wakeup() when the tracker head clears,
* then send an IPI which will have 2 possible outcomes:
*
* 1. when smr_ack_ipi() runs, the queue is already cleared,
* and we will be woken up immediately.
*
* 2. when smr_ack_ipi() runs, the queue isn't cleared,