/
scheduler.c
1674 lines (1448 loc) · 51.3 KB
/
scheduler.c
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
#define PONY_WANT_ATOMIC_DEFS
#include "scheduler.h"
#include "systematic_testing.h"
#include "cpu.h"
#include "mpmcq.h"
#include "../actor/actor.h"
#include "../gc/cycle.h"
#include "../asio/asio.h"
#include "../mem/pagemap.h"
#include "../mem/pool.h"
#include "ponyassert.h"
#include <dtrace.h>
#include <string.h>
#include "mutemap.h"
#ifdef USE_RUNTIMESTATS
#include <stdio.h>
#endif
#define PONY_SCHED_BLOCK_THRESHOLD 1000000
static DECLARE_THREAD_FN(run_thread);
typedef enum
{
SCHED_BLOCK = 20,
SCHED_UNBLOCK = 21,
SCHED_CNF = 30,
SCHED_ACK,
SCHED_TERMINATE = 40,
SCHED_SUSPEND = 41,
SCHED_UNMUTE_ACTOR = 50,
SCHED_NOISY_ASIO = 51,
SCHED_UNNOISY_ASIO = 52
} sched_msg_t;
// Scheduler global data.
static bool pause_cycle_detection;
static uint64_t last_cd_tsc;
static uint32_t scheduler_count;
static uint32_t min_scheduler_count;
static uint64_t scheduler_suspend_threshold;
static PONY_ATOMIC(uint32_t) active_scheduler_count;
static PONY_ATOMIC(uint32_t) active_scheduler_count_check;
static scheduler_t* scheduler;
static pony_ctx_t* inject_context;
static PONY_ATOMIC(bool) detect_quiescence;
static bool use_yield;
static mpmcq_t inject;
static __pony_thread_local scheduler_t* this_scheduler;
#if defined(USE_SCHEDULER_SCALING_PTHREADS)
static pthread_mutex_t sched_mut;
static pthread_once_t sched_mut_once = PTHREAD_ONCE_INIT;
void sched_mut_init()
{
pthread_mutex_init(&sched_mut, NULL);
}
#else
static PONY_ATOMIC(bool) scheduler_count_changing;
#endif
#ifdef USE_RUNTIMESTATS
// holds only size of pthread_cond variables and scheduler_t array
static size_t mem_allocated;
static size_t mem_used;
static bool print_stats;
static size_t print_stats_interval;
void print_scheduler_stats(scheduler_t* sched)
{
printf("Scheduler stats for index: %d, "
"total memory allocated: %ld, "
"total memory used: %ld, "
"created actors counter: %lu, "
"destroyed actors counter: %lu, "
"actors app cpu: %lu, "
"actors gc marking cpu: %lu, "
"actors gc sweeping cpu: %lu, "
"actors system cpu: %lu, "
"scheduler msgs cpu: %lu, "
"scheduler misc cpu: %lu, "
"memory used inflight messages: %ld, "
"memory allocated inflight messages: %ld, "
"number of inflight messages: %ld\n",
sched->index,
sched->ctx.schedulerstats.mem_used + sched->ctx.schedulerstats.mem_used_actors,
sched->ctx.schedulerstats.mem_allocated + sched->ctx.schedulerstats.mem_allocated_actors,
sched->ctx.schedulerstats.created_actors_counter,
sched->ctx.schedulerstats.destroyed_actors_counter,
sched->ctx.schedulerstats.actor_app_cpu,
sched->ctx.schedulerstats.actor_gc_mark_cpu,
sched->ctx.schedulerstats.actor_gc_sweep_cpu,
sched->ctx.schedulerstats.actor_system_cpu,
sched->ctx.schedulerstats.msg_cpu,
sched->ctx.schedulerstats.misc_cpu,
#ifdef USE_RUNTIMESTATS_MESSAGES
sched->ctx.schedulerstats.mem_used_inflight_messages,
sched->ctx.schedulerstats.mem_allocated_inflight_messages,
sched->ctx.schedulerstats.num_inflight_messages
#else
(int64_t)0,
(int64_t)0,
(int64_t)0
#endif
);
}
/** Get the static memory used by the scheduler subsystem.
*/
size_t ponyint_sched_static_mem_size()
{
return mem_used;
}
/** Get the static memory allocated by the scheduler subsystem.
*/
size_t ponyint_sched_static_alloc_size()
{
return mem_allocated;
}
size_t ponyint_sched_total_mem_size(pony_ctx_t* ctx)
{
return
// memory used for each actor struct
// + memory used for actormaps for gc acquire/release messages
ctx->schedulerstats.mem_used_actors
// memory used for mutemap
+ ctx->schedulerstats.mem_used;
}
size_t ponyint_sched_total_alloc_size(pony_ctx_t* ctx)
{
return
// memory allocated for each actor struct
// + memory allocated for actormaps for gc acquire/release messages
ctx->schedulerstats.mem_allocated_actors
// memory allocated for mutemap
+ ctx->schedulerstats.mem_allocated;
}
#endif
/**
* Gets the current active scheduler count
*/
static uint32_t get_active_scheduler_count()
{
return atomic_load_explicit(&active_scheduler_count, memory_order_relaxed);
}
/**
* Gets the current active scheduler count check
*/
static uint32_t get_active_scheduler_count_check()
{
return atomic_load_explicit(&active_scheduler_count_check, memory_order_relaxed);
}
/**
* Gets the next actor from the scheduler queue.
*/
static pony_actor_t* pop(scheduler_t* sched)
{
return (pony_actor_t*)ponyint_mpmcq_pop(&sched->q);
}
/**
* Puts an actor on the scheduler queue.
*/
static void push(scheduler_t* sched, pony_actor_t* actor)
{
ponyint_mpmcq_push_single(&sched->q, actor);
}
/**
* Handles the global queue and then pops from the local queue
*/
static pony_actor_t* pop_global(scheduler_t* sched)
{
pony_actor_t* actor = (pony_actor_t*)ponyint_mpmcq_pop(&inject);
if(actor != NULL)
return actor;
if (sched == NULL)
return NULL;
else
return pop(sched);
}
/**
* Sends a message to a thread.
*/
static void send_msg(uint32_t from, uint32_t to, sched_msg_t msg, intptr_t arg)
{
pony_msgi_t* m = (pony_msgi_t*)pony_alloc_msg(
POOL_INDEX(sizeof(pony_msgi_t)), msg);
#ifdef USE_RUNTIMESTATS_MESSAGES
this_scheduler->ctx.schedulerstats.num_inflight_messages--;
this_scheduler->ctx.schedulerstats.mem_used_inflight_messages += sizeof(pony_msgi_t);
this_scheduler->ctx.schedulerstats.mem_used_inflight_messages -= POOL_ALLOC_SIZE(pony_msgi_t);
#endif
m->i = arg;
ponyint_thread_messageq_push(&scheduler[to].mq, &m->msg, &m->msg
#ifdef USE_DYNAMIC_TRACE
, from, to
#endif
);
(void)from;
}
static void send_msg_all_active(uint32_t from, sched_msg_t msg, intptr_t arg)
{
uint32_t current_active_scheduler_count = get_active_scheduler_count();
for(uint32_t i = 0; i < current_active_scheduler_count; i++)
send_msg(from, i, msg, arg);
}
static void send_msg_all(uint32_t from, sched_msg_t msg, intptr_t arg)
{
for(uint32_t i = 0; i < scheduler_count; i++)
send_msg(from, i, msg, arg);
}
static void signal_suspended_threads(uint32_t sched_count, int32_t curr_sched_id)
{
for(uint32_t i = 0; i < sched_count; i++)
{
if((int32_t)i != curr_sched_id)
#if defined(USE_SYSTEMATIC_TESTING)
SYSTEMATIC_TESTING_YIELD();
#else
ponyint_thread_wake(scheduler[i].tid, scheduler[i].sleep_object);
#endif
}
}
static void wake_suspended_threads(int32_t current_scheduler_id)
{
uint32_t current_active_scheduler_count = get_active_scheduler_count();
// wake up any sleeping threads
while ((current_active_scheduler_count = get_active_scheduler_count()) < scheduler_count)
{
#if defined(USE_SCHEDULER_SCALING_PTHREADS)
// acquire mutex if using pthreads
if(!pthread_mutex_lock(&sched_mut))
#else
// get the bool that controls modifying the active scheduler count variable
// if using signals
if(!atomic_load_explicit(&scheduler_count_changing, memory_order_relaxed)
&& !atomic_exchange_explicit(&scheduler_count_changing, true,
memory_order_acquire))
#endif
{
// in case the count changed between the while check and now
current_active_scheduler_count = get_active_scheduler_count();
if(current_active_scheduler_count < scheduler_count)
{
// set active_scheduler_count to wake all schedulers
current_active_scheduler_count = scheduler_count;
atomic_store_explicit(&active_scheduler_count, current_active_scheduler_count,
memory_order_relaxed);
}
#if !defined(USE_SCHEDULER_SCALING_PTHREADS)
// unlock the bool that controls modifying the active scheduler count
// variable if using signals.
atomic_store_explicit(&scheduler_count_changing, false,
memory_order_release);
#endif
#if defined(USE_SCHEDULER_SCALING_PTHREADS)
// unlock mutex if using pthreads
pthread_mutex_unlock(&sched_mut);
#endif
// send signals to all scheduler threads that should be awake
// this is somewhat wasteful if a scheduler thread is already awake
// NOTE: this intentionally allows for the case where some scheduler
// threads might miss the signal and not wake up. That is handled in
// the following while loop
signal_suspended_threads(current_active_scheduler_count, current_scheduler_id);
}
// wait for sleeping threads to wake and update check variable
while (get_active_scheduler_count() != get_active_scheduler_count_check())
{
// send signals to all scheduler threads that should be awake
// this is somewhat wasteful if a scheduler thread is already awake
// but is necessary in case the signal to wake a thread was missed
// NOTE: this intentionally allows for the case where some scheduler
// threads might miss the signal and not wake up. That is handled in
// by a combination of the check variable and this while loop
signal_suspended_threads(current_active_scheduler_count, current_scheduler_id);
}
}
}
// start cnf/ack cycle for quiescence if block count >= active_scheduler_count
static void maybe_start_cnf_ack_cycle(scheduler_t* sched)
{
if(atomic_load_explicit(&detect_quiescence, memory_order_relaxed) &&
(sched->block_count >= get_active_scheduler_count()))
{
// reset ack token count to 0 because dynamic scheduler scaling means
// that a new thread can wake up changing active_scheduler_count and
// then block causing block_count >= active_scheduler_count for a
// second time and if we don't reset, we can think we've received
// enough acks when we really haven't
sched->ack_token++;
sched->ack_count = 0;
// If we think all threads are blocked, send CNF(token) to everyone.
send_msg_all_active(sched->index, SCHED_CNF, sched->ack_token);
}
}
// handle SCHED_BLOCK message
static void handle_sched_block(scheduler_t* sched)
{
sched->block_count++;
maybe_start_cnf_ack_cycle(sched);
}
// handle SCHED_UNBLOCK message
static void handle_sched_unblock(scheduler_t* sched)
{
// Cancel all acks and increment the ack token, so that any pending
// acks in the queue will be dropped when they are received.
sched->block_count--;
sched->ack_token++;
sched->ack_count = 0;
}
static bool read_msg(scheduler_t* sched)
{
#ifdef USE_RUNTIMESTATS
uint64_t used_cpu = ponyint_sched_cpu_used(&sched->ctx);
sched->ctx.schedulerstats.misc_cpu += used_cpu;
#endif
pony_msgi_t* m;
bool run_queue_changed = false;
while((m = (pony_msgi_t*)ponyint_thread_messageq_pop(&sched->mq
#ifdef USE_DYNAMIC_TRACE
, sched->index
#endif
)) != NULL)
{
#ifdef USE_RUNTIMESTATS_MESSAGES
sched->ctx.schedulerstats.num_inflight_messages--;
sched->ctx.schedulerstats.mem_used_inflight_messages -= sizeof(pony_msgi_t);
sched->ctx.schedulerstats.mem_allocated_inflight_messages -= POOL_ALLOC_SIZE(pony_msgi_t);
#endif
switch(m->msg.id)
{
case SCHED_SUSPEND:
{
maybe_start_cnf_ack_cycle(sched);
break;
}
case SCHED_BLOCK:
{
handle_sched_block(sched);
break;
}
case SCHED_UNBLOCK:
{
handle_sched_unblock(sched);
break;
}
case SCHED_CNF:
{
// Echo the token back as ACK(token).
send_msg(sched->index, 0, SCHED_ACK, m->i);
break;
}
case SCHED_ACK:
{
// If it's the current token, increment the ack count.
if(m->i == sched->ack_token)
sched->ack_count++;
break;
}
case SCHED_TERMINATE:
{
sched->terminate = true;
break;
}
case SCHED_UNMUTE_ACTOR:
{
if (ponyint_sched_unmute_senders(&sched->ctx, (pony_actor_t*)m->i))
run_queue_changed = true;
break;
}
case SCHED_NOISY_ASIO:
{
// mark asio as being noisy
sched->asio_noisy = true;
break;
}
case SCHED_UNNOISY_ASIO:
{
// mark asio as not being noisy
sched->asio_noisy = false;
break;
}
default: {}
}
}
#ifdef USE_RUNTIMESTATS
used_cpu = ponyint_sched_cpu_used(&sched->ctx);
sched->ctx.schedulerstats.msg_cpu += used_cpu;
#endif
return run_queue_changed;
}
/**
* If we can terminate, return true. If all schedulers are waiting, one of
* them will stop the ASIO back end and tell the cycle detector to try to
* terminate.
*/
static bool quiescent(scheduler_t* sched, uint64_t tsc, uint64_t tsc2)
{
if(sched->terminate)
return true;
uint32_t current_active_scheduler_count = get_active_scheduler_count();
if(sched->ack_count >= current_active_scheduler_count)
{
// mark cycle_detector to pause
// this is required to ensure scheduler queues are empty
// upon termination
pause_cycle_detection = true;
if(sched->asio_stoppable && ponyint_asio_stop())
{
// successfully stopped ASIO thread
// tell all scheduler threads to terminate
send_msg_all(sched->index, SCHED_TERMINATE, 0);
wake_suspended_threads(sched->index);
sched->ack_token++;
sched->ack_count = 0;
} else if(ponyint_asio_stoppable()) {
sched->asio_stoppable = true;
sched->ack_token++;
sched->ack_count = 0;
// Run another CNF/ACK cycle.
send_msg_all_active(sched->index, SCHED_CNF, sched->ack_token);
// re-enable cycle detector triggering
pause_cycle_detection = false;
} else {
// ASIO is not stoppable
sched->asio_stoppable = false;
// re-enable cycle detector triggering
pause_cycle_detection = false;
}
}
#if defined(USE_SYSTEMATIC_TESTING)
(void)tsc;
(void)tsc2;
SYSTEMATIC_TESTING_YIELD();
#else
ponyint_cpu_core_pause(tsc, tsc2, use_yield);
#endif
return false;
}
static scheduler_t* choose_victim(scheduler_t* sched)
{
scheduler_t* victim = sched->last_victim;
while(true)
{
// Schedulers are laid out sequentially in memory
// Back up one.
victim--;
uint32_t current_active_scheduler_count = get_active_scheduler_count();
if(victim < scheduler)
// victim is before the first scheduler location
// wrap around to the end.
victim = &scheduler[current_active_scheduler_count - 1];
if((victim == sched->last_victim) || (current_active_scheduler_count == 1))
{
// If we have tried all possible victims, return no victim. Set our last
// victim to ourself to indicate we've started over.
sched->last_victim = sched;
break;
}
// Don't try to steal from ourself.
if(victim == sched)
continue;
// Record that this is our victim and return it.
sched->last_victim = victim;
return victim;
}
return NULL;
}
/**
* Suspend this thread for some time, including no sleep at all if
* pop_global() can give us an actor immediately.
*
* WARNING: suspend_scheduler must be called in critical section
* protected by sched_mut/scheduler_count_changing,
* and we return with that mechanism:
* * Pthreads: locked, because pthread_thread_suspend() does
* not permit a choice to avoid reacquiring the mutex.
* * Non-Pthreads: unlocked, because after the suspend,
* we only need to reacquire in special case of
* sched->index==0.
*/
static pony_actor_t* suspend_scheduler(scheduler_t* sched,
uint32_t current_active_scheduler_count)
{
pony_actor_t* actor = NULL;
// decrement active_scheduler_count so other schedulers know we're
// sleeping
uint32_t sched_count = get_active_scheduler_count();
// make sure the scheduler count didn't change
// if it did, then another thread resumed and it may not be
// appropriate for us to suspend any longer, so don't suspend
if(sched_count != current_active_scheduler_count) {
#if !defined(USE_SCHEDULER_SCALING_PTHREADS)
atomic_store_explicit(&scheduler_count_changing, false,
memory_order_release);
#endif
return actor;
}
atomic_store_explicit(&active_scheduler_count, sched_count - 1,
memory_order_relaxed);
// decrement active_scheduler_count_check
uint32_t sched_count_check = get_active_scheduler_count_check();
atomic_store_explicit(&active_scheduler_count_check, sched_count_check - 1,
memory_order_relaxed);
// ensure main active scheduler count and check variable match
pony_assert(sched_count == sched_count_check);
#if !defined(USE_SCHEDULER_SCALING_PTHREADS)
// unlock the bool that controls modifying the active scheduler count
// variable if using signals
atomic_store_explicit(&scheduler_count_changing, false,
memory_order_release);
#endif
// let sched 0 know we're suspending only after decrementing
// active_scheduler_count to avoid a race condition between
// when we update active_scheduler_count and scheduler 0 processes
// the SCHED_SUSPEND message we send it. If we don't do this,
// and scheduler 0 processes the SCHED_SUSPEND message before we
// decrement active_scheduler_count, it could think that
// active_scheduler_count > block_count and not start the CNF/ACK
// process for termination and potentially hang the runtime instead
// of allowing it to reach quiescence.
if(sched->index != 0)
send_msg(sched->index, 0, SCHED_SUSPEND, 0);
// dtrace suspend notification
DTRACE1(THREAD_SUSPEND, (uintptr_t)sched);
while(get_active_scheduler_count() <= (uint32_t)sched->index)
{
// if we're scheduler 0 with noisy actors check to make
// sure inject queue is empty to avoid race condition
// between thread 0 sleeping and the ASIO thread getting a
// new event
if(sched->index == 0)
{
actor = pop_global(NULL);
if(actor != NULL)
break;
if(read_msg(sched))
{
// An actor was unmuted and added to our run queue. Pop it and return.
// Effectively, we are "stealing" from ourselves. We need to verify that
// popping succeeded (actor != NULL) as some other scheduler might have
// stolen the newly scheduled actor from us already. Schedulers, what a
// bunch of thieving bastards!
actor = pop_global(sched);
if(actor != NULL)
break;
}
// if ASIO is no longer noisy due to reading a message from the ASIO
// thread
if(!sched->asio_noisy)
break;
}
// sleep waiting for signal to wake up again
#if defined(USE_SYSTEMATIC_TESTING)
#if defined(USE_SCHEDULER_SCALING_PTHREADS)
SYSTEMATIC_TESTING_SUSPEND(&sched_mut);
#else
SYSTEMATIC_TESTING_SUSPEND();
#endif
#else
#if defined(USE_SCHEDULER_SCALING_PTHREADS)
ponyint_thread_suspend(sched->sleep_object, &sched_mut);
#else
ponyint_thread_suspend(sched->sleep_object);
#endif
#endif
}
// dtrace resume notification
DTRACE1(THREAD_RESUME, (uintptr_t)sched);
#if !defined(USE_SCHEDULER_SCALING_PTHREADS)
// When using signals, need to acquire sched count changing variable
while (true)
{
// get the bool that controls modifying the active scheduler
// count variable if using signals
if(!atomic_load_explicit(&scheduler_count_changing, memory_order_relaxed)
&& !atomic_exchange_explicit(&scheduler_count_changing, true,
memory_order_acquire))
{
#endif
// get active_scheduler_count
sched_count = get_active_scheduler_count();
// make sure active_scheduler_count == 1 if it is 0
// and we're scheduler 0 with noisy actors
// and we just pulled an actor off the inject queue
// or the ASIO is no longer noisy
// and we broke out of the earlier loop before suspending
// to return the actor
if(sched_count == 0)
{
// set active_scheduler_count to 1
sched_count = 1;
atomic_store_explicit(&active_scheduler_count,
sched_count, memory_order_relaxed);
}
// increment active_scheduler_count_check
sched_count_check = get_active_scheduler_count_check();
atomic_store_explicit(&active_scheduler_count_check,
sched_count_check + 1, memory_order_relaxed);
// ensure main active scheduler count and check variable match
// pony_assert(sched_count == sched_count_check);
#if !defined(USE_SCHEDULER_SCALING_PTHREADS)
// unlock the bool that controls modifying the active scheduler count
// variable if using signals
atomic_store_explicit(&scheduler_count_changing, false,
memory_order_release);
// break while loop
break;
}
}
#endif
return actor;
}
static pony_actor_t* perhaps_suspend_scheduler(
scheduler_t* sched, uint32_t current_active_scheduler_count,
bool* block_sent, uint32_t* steal_attempts, bool sched_is_blocked)
{
// if we're the highest active scheduler thread
// and there are more active schedulers than the minimum requested
// and we're not terminating
// and active scheduler count matchs the check variable indicating all
// threads that should be awake are awake
if ((current_active_scheduler_count > min_scheduler_count)
&& (sched == &scheduler[current_active_scheduler_count - 1])
&& (!sched->terminate)
&& (current_active_scheduler_count == get_active_scheduler_count_check())
#if defined(USE_SCHEDULER_SCALING_PTHREADS)
// try to acquire mutex if using pthreads
&& !pthread_mutex_trylock(&sched_mut)
#else
// try and get the bool that controls modifying the active scheduler count
// variable if using signals
&& (!atomic_load_explicit(&scheduler_count_changing, memory_order_relaxed)
&& !atomic_exchange_explicit(&scheduler_count_changing, true,
memory_order_acquire))
#endif
)
{
pony_actor_t* actor = NULL;
// can only sleep if we're scheduler > 0 or if we're scheduler 0 and
// there is at least one noisy actor registered
if((sched->index > 0) || ((sched->index == 0) && sched->asio_noisy))
{
if (!sched_is_blocked)
{
// unblock before suspending to ensure cnf/ack cycle works as expected
if(sched->index == 0)
handle_sched_unblock(sched);
else
send_msg(sched->index, 0, SCHED_UNBLOCK, 0);
*block_sent = false;
}
actor = suspend_scheduler(sched, current_active_scheduler_count);
// reset steal_attempts so we try to steal from all other schedulers
// prior to suspending again
*steal_attempts = 0;
}
else
{
pony_assert(sched->index == 0);
pony_assert(!sched->asio_noisy);
#if !defined(USE_SCHEDULER_SCALING_PTHREADS)
// suspend_scheduler() would have unlocked for us,
// but we didn't call it, so unlock now.
atomic_store_explicit(&scheduler_count_changing, false,
memory_order_release);
#endif
if (sched_is_blocked)
{
// send block message if there are no noisy actors registered
// with the ASIO thread and this is scheduler 0
handle_sched_block(sched);
*block_sent = true;
}
}
#if defined(USE_SCHEDULER_SCALING_PTHREADS)
// unlock mutex if using pthreads
pthread_mutex_unlock(&sched_mut);
#endif
if(actor != NULL)
return actor;
}
return NULL;
}
/**
* Use mpmcqs to allow stealing directly from a victim, without waiting for a
* response.
*/
static pony_actor_t* steal(scheduler_t* sched)
{
bool block_sent = false;
uint32_t steal_attempts = 0;
uint64_t tsc = ponyint_cpu_tick();
pony_actor_t* actor;
scheduler_t* victim = NULL;
while(true)
{
victim = choose_victim(sched);
actor = pop_global(victim);
if(actor != NULL)
break;
uint64_t tsc2 = ponyint_cpu_tick();
if(read_msg(sched))
{
// An actor was unmuted and added to our run queue. Pop it and return.
// Effectively, we are "stealing" from ourselves. We need to verify that
// popping succeeded (actor != NULL) as some other scheduler might have
// stolen the newly scheduled actor from us already. Schedulers, what a
// bunch of thieving bastards!
actor = pop_global(sched);
if(actor != NULL)
break;
}
if(quiescent(sched, tsc, tsc2))
{
DTRACE2(WORK_STEAL_FAILURE, (uintptr_t)sched, (uintptr_t)victim);
return NULL;
}
// Determine if we are blocked.
//
// Note, "blocked" means we have no more work to do and we believe that we
// should check to see if we can terminate the program.
//
// To be blocked, we have to:
//
// 1. Not have any noisy actors registered with the ASIO thread/subsystem.
// If we have any noisy actors then, while we might not have any work
// to do, we aren't blocked. Blocked means we can't make forward
// progress and the program might be ready to terminate. Noisy actors
// means that no, the program isn't ready to terminate becuase one of
// noisy actors could receive a message from an external source (timer,
// network, etc).
// 2. Not have any muted actors. If we are holding any muted actors then,
// while we might not have any work to do, we aren't blocked. Blocked
// means we can't make forward progress and the program might be ready
// to terminate. Muted actors means that no, the program isn't ready
// to terminate.
// 3. We have attempted to steal from every other scheduler and failed to
// get any work. In the process of stealing from every other scheduler,
// we will have also tried getting work off the ASIO inject queue
// multiple times
// 4. We've been trying to steal for at least PONY_SCHED_BLOCK_THRESHOLD
// cycles (currently 1000000).
// In many work stealing scenarios, we immediately get steal an actor.
// Sending a block/unblock pair in that scenario is very wasteful.
// Same applies to other "quick" steal scenarios.
// 1 million cycles is roughly 1 millisecond, depending on clock speed.
// By waiting 1 millisecond before sending a block message, we are going to
// delay quiescence by a small amount of time but also optimize work
// stealing for generating far fewer block/unblock messages.
uint32_t current_active_scheduler_count = get_active_scheduler_count();
uint64_t clocks_elapsed = tsc2 - tsc;
if (!block_sent)
{
// make sure thread scaling order is still valid. we should never be
// active if the active_scheduler_count isn't larger than our index.
pony_assert(current_active_scheduler_count > (uint32_t)sched->index);
if (steal_attempts < current_active_scheduler_count)
{
steal_attempts++;
}
else if ((clocks_elapsed > PONY_SCHED_BLOCK_THRESHOLD) &&
(ponyint_mutemap_size(&sched->mute_mapping) == 0))
{
// only try and suspend if enough time has passed
if(clocks_elapsed > scheduler_suspend_threshold)
{
// in case active scheduler count changed
current_active_scheduler_count = get_active_scheduler_count();
actor = perhaps_suspend_scheduler(sched, current_active_scheduler_count,
&block_sent, &steal_attempts, true);
if (actor != NULL)
break;
}
if(!sched->asio_noisy)
{
// Only send block messages if there are no noisy actors registered
// with the ASIO thread
if(sched->index == 0)
handle_sched_block(sched);
else
send_msg(sched->index, 0, SCHED_BLOCK, 0);
block_sent = true;
}
}
}
else
{
// block sent and no work to do. We should try and suspend if we can now
// if we do suspend, we'll send a unblock message first to ensure cnf/ack
// cycle works as expected
// make sure thread scaling order is still valid. we should never be
// active if the active_scheduler_count isn't larger than our index.
pony_assert(current_active_scheduler_count > (uint32_t)sched->index);
// only try and suspend if enough time has passed
if(clocks_elapsed > scheduler_suspend_threshold)
{
actor = perhaps_suspend_scheduler(sched, current_active_scheduler_count,
&block_sent, &steal_attempts, false);
if (actor != NULL)
break;
}
}
// if we're scheduler 0 and cycle detection is enabled
if(!ponyint_actor_getnoblock() && (sched->index == 0)
&& (!pause_cycle_detection))
{
// trigger cycle detector by sending it a message if it is time
uint64_t current_tsc = ponyint_cpu_tick();
if(ponyint_cycle_check_blocked(last_cd_tsc, current_tsc))
{
last_cd_tsc = current_tsc;
// cycle detector should now be on the queue
actor = pop_global(sched);
if(actor != NULL)
break;
}
}
}
if(block_sent)
{
// Only send unblock message if a corresponding block message was sent
if(sched->index == 0)
handle_sched_unblock(sched);
else
send_msg(sched->index, 0, SCHED_UNBLOCK, 0);
}
DTRACE3(WORK_STEAL_SUCCESSFUL, (uintptr_t)sched, (uintptr_t)victim, (uintptr_t)actor);
return actor;
}
#ifdef USE_RUNTIMESTATS
uint64_t ponyint_sched_cpu_used(pony_ctx_t* ctx)
{
uint64_t last_tsc = ctx->last_tsc;
uint64_t current_tsc = ponyint_cpu_tick();
ctx->last_tsc = current_tsc;
return current_tsc - last_tsc;
}
#endif
/**
* Run a scheduler thread until termination.
*/
static void run(scheduler_t* sched)
{
#ifdef USE_RUNTIMESTATS
uint64_t last_stats_print_tsc = ponyint_cpu_tick();
sched->ctx.last_tsc = ponyint_cpu_tick();
#endif
// sleep thread until we're ready to start processing
SYSTEMATIC_TESTING_WAIT_START(sched->tid, sched->sleep_object);
if(sched->index == 0) {
pause_cycle_detection = false;
last_cd_tsc = 0;
}
pony_actor_t* actor = pop_global(sched);
if (DTRACE_ENABLED(ACTOR_SCHEDULED) && actor != NULL) {
DTRACE2(ACTOR_SCHEDULED, (uintptr_t)sched, (uintptr_t)actor);
}
while(true)
{
#ifdef USE_RUNTIMESTATS
if(print_stats)
{
// convert to cycles for use with ponyint_cpu_tick()
// 1 second = 2000000000 cycles (approx.)
// based on same scale as ponyint_cpu_core_pause() uses
uint64_t new_tsc = ponyint_cpu_tick();
if((new_tsc - last_stats_print_tsc) > print_stats_interval)
{
last_stats_print_tsc = new_tsc;
print_scheduler_stats(sched);
}
}
#endif
// if we're scheduler 0
if(sched->index == 0)