forked from gcc-mirror/gcc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscheduler.c
3940 lines (3367 loc) · 135 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
/* scheduler.c -*-C-*-
*
*************************************************************************
*
* @copyright
* Copyright (C) 2007-2013, Intel Corporation
* All rights reserved.
*
* @copyright
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Intel Corporation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* @copyright
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY
* WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
**************************************************************************/
/*
* Cilk scheduler
*/
#include "scheduler.h"
#include "bug.h"
#include "os.h"
#include "os_mutex.h"
#include "local_state.h"
#include "signal_node.h"
#include "full_frame.h"
#include "sysdep.h"
#include "except.h"
#include "cilk_malloc.h"
#include "pedigrees.h"
#include "record-replay.h"
#include <limits.h>
#include <string.h> /* memcpy */
#include <stdio.h> // sprintf
#include <stdlib.h> // malloc, free, abort
#ifdef _WIN32
# pragma warning(disable:1786) // disable warning: sprintf is deprecated
# include "sysdep-win.h"
# include "except-win32.h"
#endif // _WIN32
// ICL: Don't complain about conversion from pointer to same-sized integral
// type in __cilkrts_put_stack. That's why we're using ptrdiff_t
#ifdef _WIN32
# pragma warning(disable: 1684)
#endif
#include "cilk/cilk_api.h"
#include "frame_malloc.h"
#include "metacall_impl.h"
#include "reducer_impl.h"
#include "cilk-tbb-interop.h"
#include "cilk-ittnotify.h"
#include "stats.h"
// ICL: Don't complain about loss of precision in myrand
// I tried restoring the warning after the function, but it didn't
// suppress it
#ifdef _WIN32
# pragma warning(disable: 2259)
#endif
#ifndef _WIN32
# include <unistd.h>
#endif
#ifdef __VXWORKS__
// redeclare longjmp() with noreturn to stop warnings
extern __attribute__((noreturn))
void longjmp(jmp_buf, int);
#endif
//#define DEBUG_LOCKS 1
#ifdef DEBUG_LOCKS
// The currently executing worker must own this worker's lock
# define ASSERT_WORKER_LOCK_OWNED(w) \
{ \
__cilkrts_worker *tls_worker = __cilkrts_get_tls_worker(); \
CILK_ASSERT((w)->l->lock.owner == tls_worker); \
}
#else
# define ASSERT_WORKER_LOCK_OWNED(w)
#endif // DEBUG_LOCKS
// Options for the scheduler.
enum schedule_t { SCHEDULE_RUN,
SCHEDULE_WAIT,
SCHEDULE_EXIT };
// Return values for provably_good_steal()
enum provably_good_steal_t
{
ABANDON_EXECUTION, // Not the last child to the sync - attempt to steal work
CONTINUE_EXECUTION, // Last child to the sync - continue executing on this worker
WAIT_FOR_CONTINUE // The replay log indicates that this was the worker
// which continued. Loop until we are the last worker
// to the sync.
};
// Verify that "w" is the worker we are currently executing on.
// Because this check is expensive, this method is usually a no-op.
static inline void verify_current_wkr(__cilkrts_worker *w)
{
#if ((REDPAR_DEBUG >= 3) || (FIBER_DEBUG >= 1))
// Lookup the worker from TLS and compare to w.
__cilkrts_worker* tmp = __cilkrts_get_tls_worker();
if (w != tmp) {
fprintf(stderr, "Error. W=%d, actual worker =%d...\n",
w->self,
tmp->self);
}
CILK_ASSERT(w == tmp);
#endif
}
static enum schedule_t worker_runnable(__cilkrts_worker *w);
// Scheduling-fiber functions:
static void do_return_from_spawn (__cilkrts_worker *w,
full_frame *ff,
__cilkrts_stack_frame *sf);
static void do_sync (__cilkrts_worker *w,
full_frame *ff,
__cilkrts_stack_frame *sf);
// max is defined on Windows and VxWorks
#if (! defined(_WIN32)) && (! defined(__VXWORKS__))
// TBD: definition of max() for Linux.
# define max(a, b) ((a) < (b) ? (b) : (a))
#endif
void __cilkrts_dump_stats_to_stderr(global_state_t *g)
{
#ifdef CILK_PROFILE
int i;
for (i = 0; i < g->total_workers; ++i) {
// Print out statistics for each worker. We collected them,
// so why not print them out?
fprintf(stderr, "Stats for worker %d\n", i);
dump_stats_to_file(stderr, g->workers[i]->l->stats);
__cilkrts_accum_stats(&g->stats, g->workers[i]->l->stats);
}
// Also print out aggregate statistics.
dump_stats_to_file(stderr, &g->stats);
#endif
fprintf(stderr,
"CILK PLUS Thread Info: P=%d, Q=%d\n",
g->P,
g->Q);
fprintf(stderr,
"CILK PLUS RUNTIME MEMORY USAGE: %lld bytes",
(long long)g->frame_malloc.allocated_from_os);
#ifdef CILK_PROFILE
if (g->stats.stack_hwm)
fprintf(stderr, ", %ld stacks", g->stats.stack_hwm);
#endif
fputc('\n', stderr);
}
static void validate_worker(__cilkrts_worker *w)
{
/* check the magic numbers, for debugging purposes */
if (w->l->worker_magic_0 != WORKER_MAGIC_0 ||
w->l->worker_magic_1 != WORKER_MAGIC_1)
abort_because_rts_is_corrupted();
}
static void double_link(full_frame *left_ff, full_frame *right_ff)
{
if (left_ff)
left_ff->right_sibling = right_ff;
if (right_ff)
right_ff->left_sibling = left_ff;
}
/* add CHILD to the right of all children of PARENT */
static void push_child(full_frame *parent_ff, full_frame *child_ff)
{
double_link(parent_ff->rightmost_child, child_ff);
double_link(child_ff, 0);
parent_ff->rightmost_child = child_ff;
}
/* unlink CHILD from the list of all children of PARENT */
static void unlink_child(full_frame *parent_ff, full_frame *child_ff)
{
double_link(child_ff->left_sibling, child_ff->right_sibling);
if (!child_ff->right_sibling) {
/* this is the rightmost child -- update parent link */
CILK_ASSERT(parent_ff->rightmost_child == child_ff);
parent_ff->rightmost_child = child_ff->left_sibling;
}
child_ff->left_sibling = child_ff->right_sibling = 0; /* paranoia */
}
static void incjoin(full_frame *ff)
{
++ff->join_counter;
}
static int decjoin(full_frame *ff)
{
CILK_ASSERT(ff->join_counter > 0);
return (--ff->join_counter);
}
static int simulate_decjoin(full_frame *ff)
{
CILK_ASSERT(ff->join_counter > 0);
return (ff->join_counter - 1);
}
/*
* Pseudo-random generator defined by the congruence S' = 69070 * S
* mod (2^32 - 5). Marsaglia (CACM July 1993) says on page 107 that
* this is a ``good one''. There you go.
*
* The literature makes a big fuss about avoiding the division, but
* for us it is not worth the hassle.
*/
static const unsigned RNGMOD = ((1ULL << 32) - 5);
static const unsigned RNGMUL = 69070U;
static unsigned myrand(__cilkrts_worker *w)
{
unsigned state = w->l->rand_seed;
state = (unsigned)((RNGMUL * (unsigned long long)state) % RNGMOD);
w->l->rand_seed = state;
return state;
}
static void mysrand(__cilkrts_worker *w, unsigned seed)
{
seed %= RNGMOD;
seed += (seed == 0); /* 0 does not belong to the multiplicative
group. Use 1 instead */
w->l->rand_seed = seed;
}
/* W grabs its own lock */
void __cilkrts_worker_lock(__cilkrts_worker *w)
{
validate_worker(w);
CILK_ASSERT(w->l->do_not_steal == 0);
/* tell thieves to stay out of the way */
w->l->do_not_steal = 1;
__cilkrts_fence(); /* probably redundant */
__cilkrts_mutex_lock(w, &w->l->lock);
}
void __cilkrts_worker_unlock(__cilkrts_worker *w)
{
__cilkrts_mutex_unlock(w, &w->l->lock);
CILK_ASSERT(w->l->do_not_steal == 1);
/* The fence is probably redundant. Use a release
operation when supported (gcc and compatibile);
that is faster on x86 which serializes normal stores. */
#if defined __GNUC__ && (__GNUC__ * 10 + __GNUC_MINOR__ > 43 || __ICC >= 1110)
__sync_lock_release(&w->l->do_not_steal);
#else
w->l->do_not_steal = 0;
__cilkrts_fence(); /* store-store barrier, redundant on x86 */
#endif
}
/* try to acquire the lock of some *other* worker */
static int worker_trylock_other(__cilkrts_worker *w,
__cilkrts_worker *other)
{
int status = 0;
validate_worker(other);
/* This protocol guarantees that, after setting the DO_NOT_STEAL
flag, worker W can enter its critical section after waiting for
the thief currently in the critical section (if any) and at
most one other thief.
This requirement is overly paranoid, but it should protect us
against future nonsense from OS implementors.
*/
/* compete for the right to disturb OTHER */
if (__cilkrts_mutex_trylock(w, &other->l->steal_lock)) {
if (other->l->do_not_steal) {
/* leave it alone */
} else {
status = __cilkrts_mutex_trylock(w, &other->l->lock);
}
__cilkrts_mutex_unlock(w, &other->l->steal_lock);
}
return status;
}
static void worker_unlock_other(__cilkrts_worker *w,
__cilkrts_worker *other)
{
__cilkrts_mutex_unlock(w, &other->l->lock);
}
/* Lock macro Usage:
BEGIN_WITH_WORKER_LOCK(w) {
statement;
statement;
BEGIN_WITH_FRAME_LOCK(w, ff) {
statement;
statement;
} END_WITH_FRAME_LOCK(w, ff);
} END_WITH_WORKER_LOCK(w);
*/
#define BEGIN_WITH_WORKER_LOCK(w) __cilkrts_worker_lock(w); do
#define END_WITH_WORKER_LOCK(w) while (__cilkrts_worker_unlock(w), 0)
// TBD(jsukha): These are worker lock acquistions on
// a worker whose deque is empty. My conjecture is that we
// do not need to hold the worker lock at these points.
// I have left them in for now, however.
//
// #define REMOVE_POSSIBLY_OPTIONAL_LOCKS
#ifdef REMOVE_POSSIBLY_OPTIONAL_LOCKS
#define BEGIN_WITH_WORKER_LOCK_OPTIONAL(w) do
#define END_WITH_WORKER_LOCK_OPTIONAL(w) while (0)
#else
#define BEGIN_WITH_WORKER_LOCK_OPTIONAL(w) __cilkrts_worker_lock(w); do
#define END_WITH_WORKER_LOCK_OPTIONAL(w) while (__cilkrts_worker_unlock(w), 0)
#endif
#define BEGIN_WITH_FRAME_LOCK(w, ff) \
do { full_frame *_locked_ff = ff; __cilkrts_frame_lock(w, _locked_ff); do
#define END_WITH_FRAME_LOCK(w, ff) \
while (__cilkrts_frame_unlock(w, _locked_ff), 0); } while (0)
/* W becomes the owner of F and F can be stolen from W */
static void make_runnable(__cilkrts_worker *w, full_frame *ff)
{
w->l->frame_ff = ff;
/* CALL_STACK is invalid (the information is stored implicitly in W) */
ff->call_stack = 0;
}
/*
* The worker parameter is unused, except for print-debugging purposes.
*/
static void make_unrunnable(__cilkrts_worker *w,
full_frame *ff,
__cilkrts_stack_frame *sf,
int is_loot,
const char *why)
{
/* CALL_STACK becomes valid again */
ff->call_stack = sf;
if (sf) {
#if CILK_LIB_DEBUG
if (__builtin_expect(sf->flags & CILK_FRAME_EXITING, 0))
__cilkrts_bug("W%d suspending exiting frame %p/%p\n", w->self, ff, sf);
#endif
sf->flags |= CILK_FRAME_STOLEN | CILK_FRAME_SUSPENDED;
sf->worker = 0;
if (is_loot)
__cilkrts_put_stack(ff, sf);
/* perform any system-dependent action, such as saving the
state of the stack */
__cilkrts_make_unrunnable_sysdep(w, ff, sf, is_loot, why);
}
}
/* Push the next full frame to be made active in this worker and increment its
* join counter. __cilkrts_push_next_frame and pop_next_frame work on a
* one-element queue. This queue is used to communicate across the runtime
* from the code that wants to activate a frame to the code that can actually
* begin execution on that frame. They are asymetrical in that push
* increments the join counter but pop does not decrement it. Rather, a
* single push/pop combination makes a frame active and increments its join
* counter once. */
void __cilkrts_push_next_frame(__cilkrts_worker *w, full_frame *ff)
{
CILK_ASSERT(ff);
CILK_ASSERT(!w->l->next_frame_ff);
incjoin(ff);
w->l->next_frame_ff = ff;
}
/* Get the next full-frame to be made active in this worker. The join count
* of the full frame will have been incremented by the corresponding push
* event. See __cilkrts_push_next_frame, above.
*/
static full_frame *pop_next_frame(__cilkrts_worker *w)
{
full_frame *ff;
ff = w->l->next_frame_ff;
// Remove the frame from the next_frame field.
//
// If this is a user worker, then there is a chance that another worker
// from our team could push work into our next_frame (if it is the last
// worker doing work for this team). The other worker's setting of the
// next_frame could race with our setting of next_frame to NULL. This is
// the only possible race condition on next_frame. However, if next_frame
// has a non-NULL value, then it means the team still has work to do, and
// there is no chance of another team member populating next_frame. Thus,
// it is safe to set next_frame to NULL, if it was populated. There is no
// need for an atomic op.
if (NULL != ff) {
w->l->next_frame_ff = NULL;
}
return ff;
}
/*
* Identify the single worker that is allowed to cross a sync in this frame. A
* thief should call this function when it is the first to steal work from a
* user worker. "First to steal work" may mean that there has been parallelism
* in the user worker before, but the whole team sync'd, and this is the first
* steal after that.
*
* This should happen while holding the worker and frame lock.
*/
static void set_sync_master(__cilkrts_worker *w, full_frame *ff)
{
w->l->last_full_frame = ff;
ff->sync_master = w;
}
/*
* The sync that ends all parallelism for a particular user worker is about to
* be crossed. Decouple the worker and frame.
*
* No locks need to be held since the user worker isn't doing anything, and none
* of the system workers can steal from it. But unset_sync_master() should be
* called before the user worker knows about this work (i.e., before it is
* inserted into the w->l->next_frame_ff is set).
*/
static void unset_sync_master(__cilkrts_worker *w, full_frame *ff)
{
CILK_ASSERT(WORKER_USER == w->l->type);
CILK_ASSERT(ff->sync_master == w);
ff->sync_master = NULL;
w->l->last_full_frame = NULL;
}
/********************************************************************
* THE protocol:
********************************************************************/
/*
* This is a protocol for work stealing that minimizes the overhead on
* the victim.
*
* The protocol uses three shared pointers into the worker's deque:
* - T - the "tail"
* - H - the "head"
* - E - the "exception" NB: In this case, "exception" has nothing to do
* with C++ throw-catch exceptions -- it refers only to a non-normal return,
* i.e., a steal or similar scheduling exception.
*
* with H <= E, H <= T.
*
* Stack frames SF, where H <= E < T, are available for stealing.
*
* The worker operates on the T end of the stack. The frame being
* worked on is not on the stack. To make a continuation available for
* stealing the worker pushes a from onto the stack: stores *T++ = SF.
* To return, it pops the frame off the stack: obtains SF = *--T.
*
* After decrementing T, the condition E > T signals to the victim that
* it should invoke the runtime system's "THE" exception handler. The
* pointer E can become INFINITY, in which case the victim must invoke
* the THE exception handler as soon as possible.
*
* See "The implementation of the Cilk-5 multithreaded language", PLDI 1998,
* http://portal.acm.org/citation.cfm?doid=277652.277725, for more information
* on the THE protocol.
*/
/* the infinity value of E */
#define EXC_INFINITY ((__cilkrts_stack_frame **) (-1))
static void increment_E(__cilkrts_worker *victim)
{
__cilkrts_stack_frame *volatile *tmp;
// The currently executing worker must own the worker lock to touch
// victim->exc
ASSERT_WORKER_LOCK_OWNED(victim);
tmp = victim->exc;
if (tmp != EXC_INFINITY) {
/* On most x86 this pair of operations would be slightly faster
as an atomic exchange due to the implicit memory barrier in
an atomic instruction. */
victim->exc = tmp + 1;
__cilkrts_fence();
}
}
static void decrement_E(__cilkrts_worker *victim)
{
__cilkrts_stack_frame *volatile *tmp;
// The currently executing worker must own the worker lock to touch
// victim->exc
ASSERT_WORKER_LOCK_OWNED(victim);
tmp = victim->exc;
if (tmp != EXC_INFINITY) {
/* On most x86 this pair of operations would be slightly faster
as an atomic exchange due to the implicit memory barrier in
an atomic instruction. */
victim->exc = tmp - 1;
__cilkrts_fence(); /* memory fence not really necessary */
}
}
#if 0
/* for now unused, will be necessary if we implement abort */
static void signal_THE_exception(__cilkrts_worker *wparent)
{
wparent->exc = EXC_INFINITY;
__cilkrts_fence();
}
#endif
static void reset_THE_exception(__cilkrts_worker *w)
{
// The currently executing worker must own the worker lock to touch
// w->exc
ASSERT_WORKER_LOCK_OWNED(w);
w->exc = w->head;
__cilkrts_fence();
}
/* conditions under which victim->head can be stolen: */
static int can_steal_from(__cilkrts_worker *victim)
{
return ((victim->head < victim->tail) &&
(victim->head < victim->protected_tail));
}
/* Return TRUE if the frame can be stolen, false otherwise */
static int dekker_protocol(__cilkrts_worker *victim)
{
// increment_E and decrement_E are going to touch victim->exc. The
// currently executing worker must own victim's lock before they can
// modify it
ASSERT_WORKER_LOCK_OWNED(victim);
/* ASSERT(E >= H); */
increment_E(victim);
/* ASSERT(E >= H + 1); */
if (can_steal_from(victim)) {
/* success, we can steal victim->head and set H <- H + 1
in detach() */
return 1;
} else {
/* failure, restore previous state */
decrement_E(victim);
return 0;
}
}
/* Link PARENT and CHILD in the spawn tree */
static full_frame *make_child(__cilkrts_worker *w,
full_frame *parent_ff,
__cilkrts_stack_frame *child_sf,
cilk_fiber *fiber)
{
full_frame *child_ff = __cilkrts_make_full_frame(w, child_sf);
child_ff->parent = parent_ff;
push_child(parent_ff, child_ff);
//DBGPRINTF("%d- make_child - child_frame: %p, parent_frame: %p, child_sf: %p\n"
// " parent - parent: %p, left_sibling: %p, right_sibling: %p, rightmost_child: %p\n"
// " child - parent: %p, left_sibling: %p, right_sibling: %p, rightmost_child: %p\n",
// w->self, child, parent, child_sf,
// parent->parent, parent->left_sibling, parent->right_sibling, parent->rightmost_child,
// child->parent, child->left_sibling, child->right_sibling, child->rightmost_child);
CILK_ASSERT(parent_ff->call_stack);
child_ff->is_call_child = (fiber == NULL);
/* PLACEHOLDER_FIBER is used as non-null marker indicating that
child should be treated as a spawn child even though we have not
yet assigned a real fiber to its parent. */
if (fiber == PLACEHOLDER_FIBER)
fiber = NULL; /* Parent actually gets a null fiber, for now */
/* perform any system-dependent actions, such as capturing
parameter passing information */
/*__cilkrts_make_child_sysdep(child, parent);*/
/* Child gets reducer map and stack of parent.
Parent gets a new map and new stack. */
child_ff->fiber_self = parent_ff->fiber_self;
child_ff->sync_master = NULL;
if (child_ff->is_call_child) {
/* Cause segfault on any attempted access. The parent gets
the child map and stack when the child completes. */
parent_ff->fiber_self = 0;
} else {
parent_ff->fiber_self = fiber;
}
incjoin(parent_ff);
return child_ff;
}
static inline __cilkrts_stack_frame *__cilkrts_advance_frame(__cilkrts_stack_frame *sf)
{
__cilkrts_stack_frame *p = sf->call_parent;
sf->call_parent = 0;
return p;
}
/* w should be the currently executing worker.
* loot_sf is the youngest stack frame in the call stack being
* unrolled (i.e., the most deeply nested stack frame.)
*
* When this method is called for a steal, loot_sf should be on a
* victim worker which is different from w.
* For CILK_FORCE_REDUCE, the victim worker will equal w.
*
* Before execution, the __cilkrts_stack_frame's have pointers from
* older to younger, i.e., a __cilkrts_stack_frame points to parent.
*
* This method creates a full frame for each __cilkrts_stack_frame in
* the call stack, with each full frame also pointing to its parent.
*
* The method returns the full frame created for loot_sf, i.e., the
* youngest full frame.
*/
static full_frame *unroll_call_stack(__cilkrts_worker *w,
full_frame *ff,
__cilkrts_stack_frame *const loot_sf)
{
__cilkrts_stack_frame *sf = loot_sf;
__cilkrts_stack_frame *rev_sf = 0;
__cilkrts_stack_frame *t_sf;
CILK_ASSERT(sf);
/*CILK_ASSERT(sf->call_parent != sf);*/
/* The leafmost frame is unsynched. */
if (sf->worker != w)
sf->flags |= CILK_FRAME_UNSYNCHED;
/* Reverse the call stack to make a linked list ordered from parent
to child. sf->call_parent points to the child of SF instead of
the parent. */
do {
t_sf = (sf->flags & (CILK_FRAME_DETACHED|CILK_FRAME_STOLEN|CILK_FRAME_LAST))? 0 : sf->call_parent;
sf->call_parent = rev_sf;
rev_sf = sf;
sf = t_sf;
} while (sf);
sf = rev_sf;
/* Promote each stack frame to a full frame in order from parent
to child, following the reversed list we just built. */
make_unrunnable(w, ff, sf, sf == loot_sf, "steal 1");
/* T is the *child* of SF, because we have reversed the list */
for (t_sf = __cilkrts_advance_frame(sf); t_sf;
sf = t_sf, t_sf = __cilkrts_advance_frame(sf)) {
ff = make_child(w, ff, t_sf, NULL);
make_unrunnable(w, ff, t_sf, t_sf == loot_sf, "steal 2");
}
/* XXX What if the leafmost frame does not contain a sync
and this steal is from promote own deque? */
/*sf->flags |= CILK_FRAME_UNSYNCHED;*/
CILK_ASSERT(!sf->call_parent);
return ff;
}
/* detach the top of the deque frame from the VICTIM and install a new
CHILD frame in its place */
static void detach_for_steal(__cilkrts_worker *w,
__cilkrts_worker *victim,
cilk_fiber* fiber)
{
/* ASSERT: we own victim->lock */
full_frame *parent_ff, *child_ff, *loot_ff;
__cilkrts_stack_frame *volatile *h;
__cilkrts_stack_frame *sf;
w->l->team = victim->l->team;
CILK_ASSERT(w->l->frame_ff == 0 || w == victim);
h = victim->head;
CILK_ASSERT(*h);
victim->head = h + 1;
parent_ff = victim->l->frame_ff;
BEGIN_WITH_FRAME_LOCK(w, parent_ff) {
/* parent no longer referenced by victim */
decjoin(parent_ff);
/* obtain the victim call stack */
sf = *h;
/* perform system-dependent normalizations */
/*__cilkrts_normalize_call_stack_on_steal(sf);*/
/* unroll PARENT_FF with call stack SF, adopt the youngest
frame LOOT. If loot_ff == parent_ff, then we hold loot_ff->lock,
otherwise, loot_ff is newly created and we can modify it without
holding its lock. */
loot_ff = unroll_call_stack(w, parent_ff, sf);
#if REDPAR_DEBUG >= 3
fprintf(stderr, "[W=%d, victim=%d, desc=detach, parent_ff=%p, loot=%p]\n",
w->self, victim->self,
parent_ff, loot_ff);
#endif
if (WORKER_USER == victim->l->type &&
NULL == victim->l->last_full_frame) {
// Mark this looted frame as special: only the original user worker
// may cross the sync.
//
// This call is a shared access to
// victim->l->last_full_frame.
set_sync_master(victim, loot_ff);
}
/* LOOT is the next frame that the thief W is supposed to
run, unless the thief is stealing from itself, in which
case the thief W == VICTIM executes CHILD and nobody
executes LOOT. */
if (w == victim) {
/* Pretend that frame has been stolen */
loot_ff->call_stack->flags |= CILK_FRAME_UNSYNCHED;
loot_ff->simulated_stolen = 1;
}
else
__cilkrts_push_next_frame(w, loot_ff);
// After this "push_next_frame" call, w now owns loot_ff.
child_ff = make_child(w, loot_ff, 0, fiber);
BEGIN_WITH_FRAME_LOCK(w, child_ff) {
/* install child in the victim's work queue, taking
the parent_ff's place */
/* child is referenced by victim */
incjoin(child_ff);
// With this call, w is bestowing ownership of the newly
// created frame child_ff to the victim, and victim is
// giving up ownership of parent_ff.
//
// Worker w will either take ownership of parent_ff
// if parent_ff == loot_ff, or parent_ff will be
// suspended.
//
// Note that this call changes the victim->frame_ff
// while the victim may be executing.
make_runnable(victim, child_ff);
} END_WITH_FRAME_LOCK(w, child_ff);
} END_WITH_FRAME_LOCK(w, parent_ff);
}
/**
* @brief cilk_fiber_proc that resumes user code after a successful
* random steal.
* This function longjmps back into the user code whose state is
* stored in cilk_fiber_get_data(fiber)->resume_sf. The stack pointer
* is adjusted so that the code resumes on the specified fiber stack
* instead of its original stack.
*
* This method gets executed only on a fiber freshly allocated from a
* pool.
*
* @param fiber The fiber being used to resume user code.
* @param arg Unused.
*/
static
void fiber_proc_to_resume_user_code_for_random_steal(cilk_fiber *fiber)
{
cilk_fiber_data *data = cilk_fiber_get_data(fiber);
__cilkrts_stack_frame* sf = data->resume_sf;
full_frame *ff;
CILK_ASSERT(sf);
// When we pull the resume_sf out of the fiber to resume it, clear
// the old value.
data->resume_sf = NULL;
CILK_ASSERT(sf->worker == data->owner);
ff = sf->worker->l->frame_ff;
// For Win32, we need to overwrite the default exception handler
// in this function, so that when the OS exception handling code
// walks off the top of the current Cilk stack, it reaches our stub
// handler.
// Also, this function needs to be wrapped into a try-catch block
// so the compiler generates the appropriate exception information
// in this frame.
// TBD: IS THIS HANDLER IN THE WRONG PLACE? Can we longjmp out of
// this function (and does it matter?)
#if defined(_WIN32) && !defined(_WIN64)
install_exception_stub_handler();
__try
#endif
{
char* new_sp = sysdep_reset_jump_buffers_for_resume(fiber, ff, sf);
// Notify the Intel tools that we're stealing code
ITT_SYNC_ACQUIRED(sf->worker);
NOTIFY_ZC_INTRINSIC("cilk_continue", sf);
// TBD: We'd like to move TBB-interop methods into the fiber
// eventually.
cilk_fiber_invoke_tbb_stack_op(fiber, CILK_TBB_STACK_ADOPT);
sf->flags &= ~CILK_FRAME_SUSPENDED;
// longjmp to user code. Don't process exceptions here,
// because we are resuming a stolen frame.
sysdep_longjmp_to_sf(new_sp, sf, NULL);
/*NOTREACHED*/
// Intel's C compiler respects the preceding lint pragma
}
#if defined(_WIN32) && !defined(_WIN64)
__except (CILK_ASSERT(!"should not execute the the stub filter"),
EXCEPTION_EXECUTE_HANDLER)
{
// If we are here, that means something very wrong
// has happened in our exception processing...
CILK_ASSERT(! "should not be here!");
}
#endif
}
static void random_steal(__cilkrts_worker *w)
{
__cilkrts_worker *victim = NULL;
cilk_fiber *fiber = NULL;
int n;
int success = 0;
int32_t victim_id;
// Nothing's been stolen yet. When true, this will flag
// setup_for_execution_pedigree to increment the pedigree
w->l->work_stolen = 0;
/* If the user has disabled stealing (using the debugger) we fail */
if (__builtin_expect(w->g->stealing_disabled, 0))
return;
CILK_ASSERT(w->l->type == WORKER_SYSTEM || w->l->team == w);
/* If there is only one processor work can still be stolen.
There must be only one worker to prevent stealing. */
CILK_ASSERT(w->g->total_workers > 1);
/* pick random *other* victim */
n = myrand(w) % (w->g->total_workers - 1);
if (n >= w->self)
++n;
// If we're replaying a log, override the victim. -1 indicates that
// we've exhausted the list of things this worker stole when we recorded
// the log so just return. If we're not replaying a log,
// replay_get_next_recorded_victim() just returns the victim ID passed in.
n = replay_get_next_recorded_victim(w, n);
if (-1 == n)
return;
victim = w->g->workers[n];
START_INTERVAL(w, INTERVAL_FIBER_ALLOCATE) {
/* Verify that we can get a stack. If not, no need to continue. */
fiber = cilk_fiber_allocate(&w->l->fiber_pool);
} STOP_INTERVAL(w, INTERVAL_FIBER_ALLOCATE);
if (NULL == fiber) {
#if FIBER_DEBUG >= 2
fprintf(stderr, "w=%d: failed steal because we could not get a fiber\n",
w->self);
#endif
return;
}
/* do not steal from self */
CILK_ASSERT (victim != w);
/* Execute a quick check before engaging in the THE protocol.
Avoid grabbing locks if there is nothing to steal. */
if (!can_steal_from(victim)) {
NOTE_INTERVAL(w, INTERVAL_STEAL_FAIL_EMPTYQ);
START_INTERVAL(w, INTERVAL_FIBER_DEALLOCATE) {
int ref_count = cilk_fiber_remove_reference(fiber, &w->l->fiber_pool);
// Fibers we use when trying to steal should not be active,
// and thus should not have any other references.
CILK_ASSERT(0 == ref_count);
} STOP_INTERVAL(w, INTERVAL_FIBER_DEALLOCATE);
return;
}
/* Attempt to steal work from the victim */
if (worker_trylock_other(w, victim)) {
if (w->l->type == WORKER_USER && victim->l->team != w) {
// Fail to steal if this is a user worker and the victim is not
// on this team. If a user worker were allowed to steal work
// descended from another user worker, the former might not be
// done with its work by the time it was needed to resume and
// unbind. Therefore, user workers are not permitted to change
// teams.
// There is no race on the victim's team because the victim cannot
// change its team until it runs out of work to do, at which point
// it will try to take out its own lock, and this worker already
// holds it.
NOTE_INTERVAL(w, INTERVAL_STEAL_FAIL_USER_WORKER);
} else if (victim->l->frame_ff) {
// A successful steal will change victim->frame_ff, even
// though the victim may be executing. Thus, the lock on
// the victim's deque is also protecting victim->frame_ff.
if (dekker_protocol(victim)) {
int proceed_with_steal = 1; // optimistic
// If we're replaying a log, verify that this the correct frame
// to steal from the victim
if (! replay_match_victim_pedigree(w, victim))
{
// Abort the steal attempt. decrement_E(victim) to
// counter the increment_E(victim) done by the
// dekker protocol
decrement_E(victim);
proceed_with_steal = 0;
}
if (proceed_with_steal)
{
START_INTERVAL(w, INTERVAL_STEAL_SUCCESS) {
success = 1;
detach_for_steal(w, victim, fiber);
victim_id = victim->self;
#if REDPAR_DEBUG >= 1
fprintf(stderr, "Wkr %d stole from victim %d, fiber = %p\n",
w->self, victim->self, fiber);
#endif
// The use of victim->self contradicts our
// classification of the "self" field as