-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquark.c
2703 lines (2548 loc) · 122 KB
/
quark.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
/* **************************************************************************** */
/**
* @file quark.c
*
* QUARK (QUeuing And Runtime for Kernels) provides a runtime
* enviornment for the dynamic execution of precedence-constrained
* tasks.
*
* QUARK is a software package provided by Univ. of Tennessee,
* Univ. of California Berkeley and Univ. of Colorado Denver.
*
* @version 2.5.0
* @author Asim YarKhan
* @date 2010-11-15
*
*/
/* Define a group for Doxygen documentation */
/**
* @defgroup QUARK QUARK: QUeuing And Runtime for Kernels
*
* These functions are available from the QUARK library for the
* scheduling of kernel routines.
*/
/* Define a group for Doxygen documentation */
/**
* @defgroup QUARK_Unsupported QUARK: Unsupported functions
*
* These functions are used by internal QUARK and PLASMA developers to
* obtain very specific behavior, but are unsupported and may have
* unexpected results.
*/
/**
* @defgroup QUARK_Depreciated QUARK: Depreciated Functions
*
* These functions have been depreciated and will be removed in a
* future release.
*/
/* **************************************************************************** */
/*
Summary of environment flags:
Change the window size (default should be checked in the code)
export QUARK_UNROLL_TASKS_PER_THREAD=num
Enable WAR avoidance (false dependency handling) (default=0 off)
export QUARK_WAR_DEPENDENCIES_ENABLE=1
Enable DAG generation (default=0 off)
export QUARK_DOT_DAG_ENABLE=1
*/
/* **************************************************************************** */
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <limits.h>
#include <errno.h>
#ifndef inline
#define inline __inline
#endif
#if defined( _WIN32 ) || defined( _WIN64 )
# define fopen(ppfile, name, mode) fopen_s(ppfile, name, mode)
# define strdup _strdup
# include "quarkwinthread.h"
#else
# define fopen(ppfile, name, mode) *ppfile = fopen(name, mode)
# include <pthread.h>
#endif
#ifdef TRUE
#undef TRUE
#endif
#ifdef FALSE
#undef FALSE
#endif
#include "icl_list.h"
#include "icl_hash.h"
#include "bsd_queue.h"
#include "bsd_tree.h"
#include "quark.h"
#include "quark_unpack_args.h"
#include "quark_trace.h"
#ifdef DBGQUARK
#include <time.h>
#include <sys/time.h>
#endif /* DBGQUARK */
#ifndef ULLONG_MAX
# define ULLONG_MAX 18446744073709551615ULL
#endif
typedef enum { ALLOCATED_ONLY, NOTREADY, QUEUED, RUNNING, DONE, CANCELLED } task_status;
typedef enum { FALSE, TRUE } bool;
typedef enum { WORKER_SLEEPING, WORKER_NOT_SLEEPING } worker_status;
struct quark_s {
pthread_mutex_t quark_mutex;
int low_water_mark;
int high_water_mark;
int num_threads; /* number of threads */
struct worker_s **worker; /* array of workers [num_threads] */
int *coresbind; /* array of indices where to bind workers [num_threads] */
/* volatile */int list_robin; /* round-robin list insertion index */
volatile bool start; /* start flag */
volatile bool all_tasks_queued; /* flag */
volatile long long num_tasks; /* number of tasks queued */
icl_hash_t *task_set;
pthread_mutex_t task_set_mutex;
icl_hash_t *address_set; /* hash table of addresses */
pthread_mutex_t address_set_mutex; /* hash table access mutex */
pthread_attr_t thread_attr; /* threads' attributes */
volatile int num_queued_tasks;
pthread_mutex_t num_queued_tasks_mutex;
pthread_cond_t num_queued_tasks_cond;
int war_dependencies_enable;
int dot_dag_enable;
int dot_dag_was_setup;
int queue_before_computing;
#define tasklevel_width_max_level 5000
int tasklevel_width[tasklevel_width_max_level];
pthread_mutex_t dot_dag_mutex;
pthread_mutex_t completed_tasks_mutex;
struct completed_tasks_head_s *completed_tasks;
volatile int completed_tasks_size;
};
struct Quark_sequence_s {
volatile int status;
pthread_mutex_t sequence_mutex;
struct ll_list_head_s *tasks_in_sequence;
};
typedef struct worker_s {
pthread_mutex_t worker_mutex;
pthread_t thread_id;
int rank;
struct task_priority_tree_head_s *ready_list;
volatile int ready_list_size;
Quark_Task *current_task_ptr;
Quark *quark_ptr;
volatile int finalize; /* termination flag */
volatile int executing_task;
int set_to_manual_scheduling;
pthread_cond_t worker_must_awake_cond;
int status;
} Worker;
typedef struct quark_task_s {
pthread_mutex_t task_mutex;
void (*function) (Quark *); /* task function pointer */
volatile task_status status; /* Status of task; NOTREADY, READY; QUEUED; DONE */
volatile int num_dependencies_remaining; /* number of dependencies remaining to be fulfilled */
icl_list_t *args_list; /* list of arguments (copies of scalar values and pointers) */
icl_list_t *dependency_list; /* list of dependencies */
icl_list_t *scratch_list; /* List of scratch space information and their sizes */
volatile struct dependency_s *locality_preserving_dep; /* Try to run task on core that preserves the locality of this dependency */
unsigned long long taskid; /* An identifier, used only for generating DAGs */
unsigned long long tasklevel; /* An identifier, used only for generating DAGs */
int lock_to_thread;
unsigned char *lock_to_thread_mask;
char *task_label; /* Label for this task, used in dot_dag generation */
char *task_color; /* Color for this task, used in dot_dag generation */
int start_code, stop_code; /* Codes for start/stop event of the function call */
int priority; /* Is this a high priority task */
Quark_Sequence *sequence;
struct ll_list_node_s *ptr_to_task_in_sequence; /* convenience pointer to this task in the sequence */
int task_thread_count; /* Num of threads required by task */
int task_thread_count_outstanding; /* Num of threads required by task */
int thread_set_to_manual_scheduling; /* enable or disable work stealing in the thread that runs this task */
volatile int threadid; /* Index of the thread calling the function GetRankInTask in parallel tasks */
int executed_on_threadid; /* Track which thread executes this task */
} Task;
typedef struct dependency_s {
struct quark_task_s *task; /* pointer to parent task containing this dependency */
void *address; /* address of data */
int size; /* Size of dependency data */
quark_direction_t direction; /* direction of this dependency, INPUT, INOUT, OUTPUT */
bool locality; /* Priority of this dependency; more like data locality */
bool accumulator; /* Tasks depending on this may be reordered, they accumulate results */
int data_region; /* Different regions may be specified for dependencies; uses bitmask of 8 bits */
bool gatherv; /* Tasks depending on this may be run in parallel, assured by the programmer */
struct address_set_node_s *address_set_node_ptr; /* convenience pointer to address_set_node */
icl_list_t *address_set_waiting_deps_node_ptr; /* convenience pointer to address_set_node waiting_deps node */
icl_list_t *task_args_list_node_ptr; /* convenience ptr to the task->args_list [node] to use for WAR address updates */
icl_list_t *task_dependency_list_node_ptr; /* convenience ptr to the task->dependency_list [node] */
/* volatile */ bool ready; /* Data dependency is ready */
} Dependency;
typedef struct scratch_s {
void *ptr; /* address of scratch space */
int size; /* Size of scratch data */
icl_list_t *task_args_list_node_ptr; /* convenience ptr to the task->args_list [node] */
} Scratch;
typedef struct address_set_node_s {
void *address; /* copy of key to the address_set - pointer to the data */
int size; /* data object size */
/* volatile */ int last_thread; /* last thread to use this data - for scheduling/locality */
icl_list_t *waiting_deps; /* list of dependencies waiting for this data */
/* volatile */ bool delete_data_at_address_when_node_is_deleted; /* used when data is copied in order to handle false dependencies */
unsigned long long last_writer_taskid; /* used for generating DOT DAGs */
unsigned long long last_writer_tasklevel; /* used for tracking critical depth */
unsigned long long last_reader_or_writer_taskid; /* used for generating DOT DAGs */
unsigned long long last_reader_or_writer_tasklevel; /* used for tracking critical depth */
pthread_mutex_t asn_mutex;
} Address_Set_Node;
/* Data structure for a list containing long long int values. Used to
* track task ids in sequences of tasks, so that the tasks in a
* sequence can be controlled */
typedef struct ll_list_node_s {
long long int val;
LIST_ENTRY( ll_list_node_s ) ll_entries;
} ll_list_node_t;
LIST_HEAD(ll_list_head_s, ll_list_node_s);
typedef struct ll_list_head_s ll_list_head_t;
typedef struct completed_tasks_node_s {
Task *task;
int workerid;
TAILQ_ENTRY( completed_tasks_node_s ) ctn_entries;
} completed_tasks_node_t;
TAILQ_HEAD( completed_tasks_head_s, completed_tasks_node_s );
typedef struct completed_tasks_head_s completed_tasks_head_t;
/* Tree (red-black) structure for keeping a priority list of
* executable tasks */
typedef struct task_priority_tree_node_s {
int priority;
Task *task;
RB_ENTRY( task_priority_tree_node_s ) n_entry;
} task_priority_tree_node_t;
RB_HEAD( task_priority_tree_head_s, task_priority_tree_node_s );
typedef struct task_priority_tree_head_s task_priority_tree_head_t;
static int compare_task_priority_tree_nodes( task_priority_tree_node_t *n1, task_priority_tree_node_t *n2 )
{
int diff = n2->priority - n1->priority;
return diff;
}
/* Generate red-black tree functions */
RB_PROTOTYPE_STATIC( task_priority_tree_head_s, task_priority_tree_node_s, n_entry, compare_task_priority_tree_nodes )
RB_GENERATE_STATIC( task_priority_tree_head_s, task_priority_tree_node_s, n_entry, compare_task_priority_tree_nodes )
/* **************************************************************************** */
/**
* Local function prototypes, declared static so they are not
* available outside the scope of this file.
*/
static Task *quark_task_new();
static void *quark_task_delete( Quark *quark, Task *task);
static Worker *quark_worker_new(Quark *quark, int rank);
static void quark_worker_delete(Worker *worker);
static inline int quark_worker_find_next_assignable( Quark *quark );
static void quark_insert_task_dependencies(Quark * quark, Task * task);
static void quark_check_and_queue_ready_task( Quark *quark, Task *task, int worker_rank );
static void quark_work_set_affinity_and_call_main_loop(Worker *worker);
static long long quark_work_main_loop(Worker *worker);
static Scratch *quark_scratch_new( void *arg_ptr, int arg_size, icl_list_t *task_args_list_node_ptr);
static void quark_scratch_allocate( Task *task );
static void quark_scratch_deallocate( Task *task );
static void quark_worker_remove_completed_task_enqueue_for_later_processing(Quark *quark, Task *task, int worker_rank);
static void quark_remove_completed_task_and_check_for_ready(Quark *quark, Task *task, int worker_rank);
static void quark_process_completed_tasks(Quark *quark);
static void quark_address_set_node_free( void* data );
static inline void quark_fatal_error(const char *func_name, char* msg_text);
static void quark_address_set_node_wait(Quark *quark, Address_Set_Node *address_set_node);
Task *quark_set_task_flags_in_task_structure( Quark *quark, Task *task, Quark_Task_Flags *task_flags );
static void quark_avoid_war_dependencies( Quark *quark, Address_Set_Node *asn_old, Task *parent_task );
/* **************************************************************************** */
/**
* Mutex wrappers for tracing/timing purposes. Makes it easier to
* profile the costs of these pthreads routines.
*/
inline static int pthread_mutex_lock_address_set(pthread_mutex_t *mtx) { int rv; if ((rv=pthread_mutex_lock( mtx ))!=0) { quark_fatal_error("pthread_mutex_lock_address_set", strerror(rv)); } return rv; }
/* inline static int pthread_mutex_trylock_address_set(pthread_mutex_t *mtx) { int rv; rv=pthread_mutex_trylock( mtx ); return rv; } */
inline static int pthread_mutex_unlock_address_set(pthread_mutex_t *mtx) { int rv; if ((rv=pthread_mutex_unlock( mtx ))!=0) { quark_fatal_error("pthread_mutex_unlock_address_set", strerror(rv)); } return rv; }
inline static int pthread_mutex_lock_ready_list(pthread_mutex_t *mtx) { int rv; if ((rv=pthread_mutex_lock( mtx ))!=0) { quark_fatal_error("pthread_mutex_lock_ready_list", strerror(rv)); } return rv; }
inline static int pthread_mutex_trylock_ready_list(pthread_mutex_t *mtx) { int rv; rv=pthread_mutex_trylock( mtx ); return rv; }
inline static int pthread_mutex_unlock_ready_list(pthread_mutex_t *mtx) { int rv; if ((rv=pthread_mutex_unlock( mtx ))!=0) { quark_fatal_error("pthread_mutex_unlock_ready_list", strerror(rv)); } return rv; }
inline static int pthread_mutex_lock_task(pthread_mutex_t *mtx) { int rv; if ((rv=pthread_mutex_lock( mtx ))!=0) { quark_fatal_error("pthread_mutex_lock_task", strerror(rv)); } return rv; }
inline static int pthread_mutex_unlock_task(pthread_mutex_t *mtx) { int rv; if ((rv=pthread_mutex_unlock( mtx ))!=0) { quark_fatal_error("pthread_mutex_unlock_task", strerror(rv)); } return rv; }
inline static int pthread_mutex_lock_atomic_add(pthread_mutex_t *mtx) { int rv; if ((rv=pthread_mutex_lock( mtx ))!=0) { quark_fatal_error("pthread_mutex_lock_atomic_add", strerror(rv)); } return rv; }
inline static int pthread_mutex_lock_atomic_set(pthread_mutex_t *mtx) { int rv; if ((rv=pthread_mutex_lock( mtx ))!=0) { quark_fatal_error("pthread_mutex_lock_atomic_set", strerror(rv)); } return rv; }
/* inline static int pthread_mutex_lock_atomic_get(pthread_mutex_t *mtx) { int rv; if ((rv=pthread_mutex_lock( mtx ))!=0) { quark_fatal_error("pthread_mutex_lock_atomic_get", strerror(rv)); } return rv; } */
inline static int pthread_mutex_unlock_atomic(pthread_mutex_t *mtx) { int rv; if ((rv=pthread_mutex_unlock( mtx ))!=0) { quark_fatal_error("pthread_mutex_unlock_atomic", strerror(rv)); } return rv; }
inline static int pthread_mutex_lock_wrap(pthread_mutex_t *mtx) { int rv; if ((rv=pthread_mutex_lock( mtx ))!=0) { quark_fatal_error("pthread_mutex_lock_wrap", strerror(rv)); } return rv; }
inline static int pthread_mutex_unlock_wrap(pthread_mutex_t *mtx) { int rv; if ((rv=pthread_mutex_unlock( mtx ))!=0) { quark_fatal_error("pthread_mutex_unlock_wrap", strerror(rv)); } return rv; }
inline static int pthread_mutex_lock_completed_tasks(pthread_mutex_t *mtx) { int rv; if ((rv=pthread_mutex_lock( mtx ))!=0) { quark_fatal_error("pthread_mutex_lock_completed_tasks", strerror(rv)); } return rv; }
inline static int pthread_mutex_trylock_completed_tasks(pthread_mutex_t *mtx) { int rv; rv=pthread_mutex_trylock( mtx ); return rv; }
inline static int pthread_mutex_unlock_completed_tasks(pthread_mutex_t *mtx) { int rv; if ((rv=pthread_mutex_unlock( mtx ))!=0) { quark_fatal_error("pthread_mutex_unlock_completed_tasks", strerror(rv)); } return rv; }
/* inline static int pthread_cond_wait_ready_list( pthread_cond_t *cond, pthread_mutex_t *mtx ) { int rv; if ((rv=pthread_cond_wait( cond, mtx))!=0) { quark_fatal_error("pthread_cond_wait_ready_list", strerror(rv)); } return rv; } */
inline static int pthread_cond_wait_wrap( pthread_cond_t *cond, pthread_mutex_t *mtx ) { int rv; if ((rv=pthread_cond_wait( cond, mtx))!=0) { quark_fatal_error("pthread_cond_wait_wrap", strerror(rv)); } return rv; }
/* **************************************************************************** */
/* If dags are to be generated, setup file name and pointer and
* various macros. This assumes that the fprintf function is thread
* safe. */
static char *quark_task_default_label = " ";
static char *quark_task_default_color = "white";
#define DEPCOLOR "black"
#define DEPCOLOR_R_FIRST "black"
#define DEPCOLOR_W_FIRST "black"
#define DEPCOLOR_RAR "black"
#define DEPCOLOR_WAW "black"
#define DEPCOLOR_RAW "black"
#define DEPCOLOR_WAR "red"
#define DEPCOLOR_GATHERV "green"
#define DOT_DAG_FILENAME "dot_dag_file.dot"
FILE *dot_dag_file = NULL;
#define dot_dag_print_edge( quark, parentid, parent_level, childid, child_level, color) \
if ( quark->dot_dag_enable ) { \
pthread_mutex_lock_wrap( &quark->dot_dag_mutex ); \
if ( parentid>0 ) fprintf(dot_dag_file, "t%llu->t%llu [color=\"%s\"];\n", (parentid), (childid), (color)); \
fflush(dot_dag_file); \
child_level = (parent_level+1 <= child_level ? child_level : parent_level+1 ); \
pthread_mutex_unlock_wrap( &quark->dot_dag_mutex ); \
}
/* **************************************************************************** */
/**
* Define a macro to add to value. Setup to shorten some code by
* locking/unlocking a mutex around the operation.
*/
#define quark_atomic_add( pval, addvalue, pmutex ) { \
pthread_mutex_lock_atomic_add(pmutex); pval += addvalue; pthread_mutex_unlock_atomic(pmutex); \
/* pval += addvalue; */ \
}
/* **************************************************************************** */
/**
* Define a macro to set a value. Setup to shorten some code by
* locking/unlocking a mutex around the operation.
*/
#define quark_atomic_set( pval, setvalue, pmutex ) { \
pthread_mutex_lock_atomic_set(pmutex); pval = setvalue; pthread_mutex_unlock_atomic(pmutex); \
/* pval = setvalue; */ \
}
/* **************************************************************************** */
/**
* Define a macro get a value. Setup to shorten some code by
* locking/unlocking a mutex around the operation. Can disable the
* mutex for performance, since the exact current value of the
* variable is not needed. The variables used here are declared
* volatile, and can lag behind the real value without a loss of
* accuracy.
*/
#define quark_atomic_get( retval, pval, pmutex ) { \
/* pthread_mutex_lock_atomic_get(pmutex); retval = pval; pthread_mutex_unlock_atomic(pmutex); */\
retval = pval; \
}
/***************************************************************************//**
*
* Unrecoverable errors.
* @param[in] func_name
* Function location where warning occurred
* @param[in] msg_text
* Warning message to display.
*
******************************************************************************/
static void quark_fatal_error(const char *func_name, char* msg_text)
{
fprintf(stderr, "QUARK_FATAL_ERROR: %s(): %s\n", func_name, msg_text);
abort();
exit(0);
}
/***************************************************************************//**
*
* Warning messages
* @param[in] func_name
* Function location where warning occurred
* @param[in] msg_text
* Warning message to display.
*
******************************************************************************/
void quark_warning(const char *func_name, char* msg_text)
{
fprintf(stderr, "QUARK_WARNING: %s(): %s\n", func_name, msg_text);
}
/* **************************************************************************** */
/**
* Allocate memory, failing
*/
static inline void *quark_malloc(size_t size)
{
void *mem = malloc(size);
if ( mem == NULL ) quark_fatal_error( "malloc", "memory allocation failed" );
return mem;
}
/* **************************************************************************** */
/**
* Initialize the task data structure
*/
static Task *quark_task_new()
{
static unsigned long long taskid = 1;
Task *task = (Task *)quark_malloc(sizeof(Task));
task->function = NULL;
task->num_dependencies_remaining = 0;
task->args_list = icl_list_new();
if ( task->args_list == NULL) quark_fatal_error( "quark_task_new", "Allocating arg list" );
task->dependency_list = icl_list_new();
if ( task->dependency_list == NULL) quark_fatal_error( "quark_task_new", "Allocating dependency list" );
task->locality_preserving_dep = NULL;
task->scratch_list = icl_list_new();
if ( task->scratch_list == NULL) quark_fatal_error( "quark_task_new", "Allocating scratch list" );
if ( taskid >= ULLONG_MAX) quark_fatal_error( "quark_task_new", "Task id > ULLONG_MAX, too many tasks" );
task->taskid = taskid++;
task->tasklevel = 0;
pthread_mutex_init( &task->task_mutex, NULL );
task->ptr_to_task_in_sequence = NULL;
task->sequence = NULL;
task->priority = QUARK_TASK_MIN_PRIORITY;
task->start_code = QUARK_TASK_DEFAULT_START_CODE;
task->stop_code = QUARK_TASK_DEFAULT_STOP_CODE;
task->task_label = quark_task_default_label;
task->task_color = quark_task_default_color;
task->lock_to_thread = -1;
task->lock_to_thread_mask = NULL;
task->task_thread_count = 1;
task->thread_set_to_manual_scheduling = -1;
task->threadid = 0;
task->status = ALLOCATED_ONLY;
task->executed_on_threadid = -1;
return task;
}
/* **************************************************************************** */
/**
* Remove the task from any quark data structures. Note, this may
* also occur before the task is added to any global data structures,
* if the sequence is deleted.
*/
static void *quark_task_delete(Quark *quark, Task *task)
{
/* task is not just allocated, it has been inserted and may have other references to it */
if ( task->status!=ALLOCATED_ONLY ) {
pthread_mutex_lock_wrap( &quark->task_set_mutex );
icl_hash_delete( quark->task_set, &task->taskid, NULL, NULL );
quark->num_tasks--;
pthread_mutex_lock_task( &task->task_mutex );
pthread_mutex_unlock_wrap( &quark->task_set_mutex );
}
if ( task->task_color!=NULL && task->task_color!=quark_task_default_color ) free(task->task_color);
if ( task->task_label!=NULL && task->task_label!=quark_task_default_label ) free(task->task_label);
if ( task->lock_to_thread_mask!=NULL ) free(task->lock_to_thread_mask);
icl_list_destroy(task->args_list, free);
icl_list_destroy(task->dependency_list, free);
icl_list_destroy(task->scratch_list, free);
if ( task->status!=ALLOCATED_ONLY ) {
if ( task->ptr_to_task_in_sequence != NULL ) {
pthread_mutex_lock_wrap( &task->sequence->sequence_mutex );
LIST_REMOVE( task->ptr_to_task_in_sequence, ll_entries );
pthread_mutex_unlock_wrap( &task->sequence->sequence_mutex );
free( task->ptr_to_task_in_sequence );
}
pthread_mutex_unlock_task( &task->task_mutex );
}
pthread_mutex_destroy( &task->task_mutex );
free( task );
task = NULL;
return task;
}
/* **************************************************************************** */
/**
* Return the rank of a thread.
*
* @param[in] quark
* The scheduler's main data structure.
* @return
* The rank of the calling thread
* @ingroup QUARK
*/
int QUARK_Thread_Rank(Quark *quark)
{
pthread_t self_id = pthread_self();
int i;
for (i=0; i<quark->num_threads; i++)
if (pthread_equal(quark->worker[i]->thread_id, self_id))
return i;
return -1;
}
/* **************************************************************************** */
/**
* Return a pointer to the argument list being processed by the
* current task and worker.
*
* @param[in] quark
* The scheduler's main data structure.
* @return
* Pointer to the current argument list (icl_list_t *)
* @ingroup QUARK
*/
void *QUARK_Args_List(Quark *quark)
{
Task *curr_task = quark->worker[QUARK_Thread_Rank(quark)]->current_task_ptr;
return (void *)curr_task->args_list;
}
/* **************************************************************************** */
/**
* Return the rank of a thread inside a parallel task.
*
* @param[in] quark
* The scheduler's main data structure.
* @return
* Pointer to the current argument list (icl_list_t *)
* @ingroup QUARK
*/
/* FIXME This is working but could be more efficient. Depends on the
* function being called only once by each instance in a
* multi-threaded task */
int QUARK_Get_RankInTask(Quark *quark)
{
int local_rank = 0;
int global_rank = QUARK_Thread_Rank(quark);
Task *curr_task = quark->worker[global_rank]->current_task_ptr;
pthread_mutex_lock_wrap( &curr_task->task_mutex );
local_rank = curr_task->threadid;
curr_task->threadid++;
pthread_mutex_unlock_wrap( &curr_task->task_mutex );
return local_rank;
}
/* **************************************************************************** */
/**
* Return a pointer to the next argument. The variable last_arg
* should be NULL on the first call, then each subsequent call will
* use last_arg to get the the next argument. The argument list is
* not actually popped, it is preserved intact.
*
* @param[in] args_list
* Pointer to the current arguments
* @param[in,out] last_arg
* Pointer to the last argument; should be NULL on the first call
* @return
* Pointer to the next argument
* @ingroup QUARK
*/
void *QUARK_Args_Pop( void *args_list, void **last_arg)
{
icl_list_t *args = (icl_list_t *)args_list;
icl_list_t *node = (icl_list_t *)*last_arg;
void *arg = NULL;
if ( node == NULL ) {
node = icl_list_first( args );
if (node!=NULL) arg = node->data;
} else {
node = icl_list_next( args, node );
if (node!=NULL) arg = node->data;
}
*last_arg = node;
return arg;
}
/* **************************************************************************** */
/**
* Well known hash function: Fowler/Noll/Vo - 32 bit version
*/
static inline unsigned int fnv_hash_function( void *key, int len )
{
unsigned char *p = key;
unsigned int h = 2166136261u;
int i;
for ( i = 0; i < len; i++ )
h = ( h * 16777619 ) ^ p[i];
return h;
}
/* **************************************************************************** */
/**
* Hash function to map addresses, cut into "long" size chunks, then
* XOR. The result will be matched to hash table size using mod in the
* hash table implementation
*/
static inline unsigned int address_hash_function(void *address)
{
int len = sizeof(void *);
unsigned int hashval = fnv_hash_function( &address, len );
return hashval;
}
/* **************************************************************************** */
/**
* Adress compare function for hash table */
static inline int address_key_compare(void *addr1, void *addr2)
{
return (addr1 == addr2);
}
/* **************************************************************************** */
/**
* Hash function for unsigned long longs (used for taskid)
*/
static inline unsigned int ullong_hash_function( void *key )
{
int len = sizeof(unsigned long long);
unsigned int hashval = fnv_hash_function( key, len );
return hashval;
}
/* **************************************************************************** */
/**
* Compare unsigned long longs for hash keys (used for taskid)
*/
static inline int ullong_key_compare( void *key1, void *key2 )
{
return ( *(unsigned long long*)key1 == *(unsigned long long*)key2 );
}
/* **************************************************************************** */
/**
* Find the next worker thread that can have a task assigned to it.
* Need to skip the manually scheduled threads, since the master
* cannot assign work to them. Abort if there is no such thread.
*/
static inline int quark_worker_find_next_assignable( Quark *quark )
{
int id = quark->list_robin;
quark->list_robin = ((quark->list_robin + 1) % quark->num_threads);
return id;
}
/* **************************************************************************** */
/**
* Duplicate the argument, allocating a memory buffer for it
*/
static inline char *arg_dup(char *arg, int size)
{
char *argbuf = (char *) quark_malloc(size);
memcpy(argbuf, arg, size);
return argbuf;
}
/* **************************************************************************** */
/**
* Allocate and initialize a dependency structure
*/
static inline Dependency *dependency_new(void *addr, long long size, quark_direction_t dir, bool loc, Task *task, bool accumulator, bool gatherv, int data_region, icl_list_t *task_args_list_node_ptr)
{
Dependency *dep = (Dependency *) quark_malloc(sizeof(Dependency));
dep->task = task;
dep->address = addr;
dep->size = size;
dep->direction = dir;
dep->locality = loc;
dep->accumulator = accumulator;
dep->data_region = data_region;
dep->gatherv = gatherv;
dep->address_set_node_ptr = NULL; /* convenience ptr, filled later */
dep->address_set_waiting_deps_node_ptr = NULL; /* convenience ptr, filled later */
dep->task_args_list_node_ptr = task_args_list_node_ptr; /* convenience ptr for WAR address updating */
dep->task_dependency_list_node_ptr = NULL; /* convenience ptr */
dep->ready = FALSE;
/* For the task, track the dependency to be used to do locality
* preservation; by default, use first output dependency. */
if ( dep->locality )
task->locality_preserving_dep = dep;
else if ( (task->locality_preserving_dep == NULL) && ( dep->direction==OUTPUT || dep->direction==INOUT) )
task->locality_preserving_dep = dep;
return dep;
}
/* **************************************************************************** */
/**
* Allocate and initialize a worker structure
*/
static Worker *quark_worker_new(Quark *quark, int rank)
{
Worker *worker = (Worker *) quark_malloc(sizeof(Worker));
worker->thread_id = pthread_self();
pthread_mutex_init( &worker->worker_mutex, NULL );
worker->rank = rank;
worker->ready_list = quark_malloc(sizeof(task_priority_tree_head_t));
RB_INIT( worker->ready_list );
worker->ready_list_size = 0;
/* convenience pointer to the real args for the task */
worker->current_task_ptr = NULL;
worker->quark_ptr = quark;
worker->finalize = FALSE;
worker->executing_task = FALSE;
worker->set_to_manual_scheduling = FALSE;
pthread_cond_init( &worker->worker_must_awake_cond, NULL );
worker->status = WORKER_NOT_SLEEPING;
return worker;
}
/* **************************************************************************** */
/**
* Cleanup and free worker data structures.
*/
static void quark_worker_delete(Worker * worker)
{
task_priority_tree_node_t *node, *nxt;
/* Destroy the workers priority queue, if there is still anything there */
for ( node = RB_MIN( task_priority_tree_head_s, worker->ready_list ); node != NULL; node = nxt) {
nxt = RB_NEXT( task_priority_tree_head_s, worker->ready_list, node );
RB_REMOVE( task_priority_tree_head_s, worker->ready_list, node );
free(node);
}
free( worker->ready_list );
pthread_mutex_destroy(&worker->worker_mutex);
free(worker);
}
/* **************************************************************************** */
/**
* The task requires scratch workspace, which will be allocated if
* needed. This records the scratch requirements.
*/
static Scratch *quark_scratch_new( void *arg_ptr, int arg_size, icl_list_t *task_args_list_node_ptr )
{
Scratch *scratch = (Scratch *)quark_malloc(sizeof(Scratch));
scratch->ptr = arg_ptr;
scratch->size = arg_size;
scratch->task_args_list_node_ptr = task_args_list_node_ptr;
return(scratch);
}
/* **************************************************************************** */
/**
* Allocate any needed scratch space;
*/
static void quark_scratch_allocate( Task *task )
{
icl_list_t *scr_node;
for (scr_node = icl_list_first( task->scratch_list );
scr_node != NULL && scr_node->data != NULL;
scr_node = icl_list_next(task->scratch_list, scr_node)) {
Scratch *scratch = (Scratch *)scr_node->data;
if ( scratch->ptr == NULL ) {
/* Since ptr is null, space is to be allocted and attached */
if ( scratch->size <= 0 ) quark_fatal_error( "quark_scratch_allocate", "scratch->size <= 0 " );
void *scratchspace = quark_malloc( scratch->size );
*(void **)scratch->task_args_list_node_ptr->data = scratchspace;
}
}
}
/* **************************************************************************** */
/**
* Deallocate any scratch space.
*/
static void quark_scratch_deallocate( Task *task )
{
icl_list_t *scr_node;
for (scr_node = icl_list_first( task->scratch_list );
scr_node != NULL && scr_node->data!=NULL;
scr_node = icl_list_next(task->scratch_list, scr_node)) {
Scratch *scratch = (Scratch *)scr_node->data;
if ( scratch->ptr == NULL ) {
/* If scratch had to be allocated, free it */
free(*(void **)scratch->task_args_list_node_ptr->data);
}
}
}
/* **************************************************************************** */
/**
* Called by the master thread. This routine does not do thread
* management, so it can be used with a larger libarary. Allocate and
* initialize the scheduler data stuctures for the master and
* num_threads worker threads.
*
* @param[in] num_threads
* Number of threads to be used (1 master and rest compute workers).
* @return
* Pointer to the QUARK scheduler data structure.
* @ingroup QUARK
*/
Quark *QUARK_Setup(int num_threads)
{
int i = 0;
Quark *quark = (Quark *) quark_malloc(sizeof(Quark));
/* Used to tell master when to act as worker */
int quark_unroll_tasks_per_thread = quark_getenv_int("QUARK_UNROLL_TASKS_PER_THREAD", 50);
int quark_unroll_tasks = quark_getenv_int("QUARK_UNROLL_TASKS", quark_unroll_tasks_per_thread * num_threads);
quark->war_dependencies_enable = quark_getenv_int("QUARK_WAR_DEPENDENCIES_ENABLE", 0);
quark->queue_before_computing = quark_getenv_int("QUARK_QUEUE_BEFORE_COMPUTING", 0);
quark->dot_dag_enable = quark_getenv_int("QUARK_DOT_DAG_ENABLE", 0);
//if ( quark->dot_dag_enable ) quark->queue_before_computing = 1;
if ( quark->queue_before_computing==1 || quark_unroll_tasks==0 ) {
quark->high_water_mark = (int)(INT_MAX - 1);
quark->low_water_mark = (int)(quark->high_water_mark);
} else {
quark->low_water_mark = (int)(quark_unroll_tasks);
quark->high_water_mark = (int)(quark->low_water_mark + quark->low_water_mark*0.25);
}
quark->num_queued_tasks = 0;
pthread_mutex_init( &quark->num_queued_tasks_mutex, NULL );
pthread_cond_init( &quark->num_queued_tasks_cond, NULL );
quark->num_threads = num_threads;
quark->list_robin = 0;
pthread_mutex_init( &quark->quark_mutex, NULL );
quark->start = FALSE;
quark->all_tasks_queued = FALSE;
quark->num_tasks = 0;
quark->task_set = icl_hash_create( 0x1<<12, ullong_hash_function, ullong_key_compare );
pthread_mutex_init( &quark->task_set_mutex, NULL );
/* Create hash table to hold addresses */
quark->address_set = icl_hash_create( 0x01<<12, address_hash_function, address_key_compare);
pthread_mutex_init( &quark->address_set_mutex, NULL );
/* To handle completed tasks */
quark->completed_tasks = quark_malloc(sizeof(completed_tasks_head_t));
TAILQ_INIT( quark->completed_tasks );
pthread_mutex_init( &quark->completed_tasks_mutex, NULL );
quark->completed_tasks_size = 0;
/* Setup workers */
quark->worker = (Worker **) quark_malloc(num_threads * sizeof(Worker *));
/* The structure for the 0th worker will be used by the master */
quark->worker[0] = quark_worker_new(quark, 0);
quark->worker[0]->thread_id = pthread_self();
quark->dot_dag_was_setup = 0;
if ( quark->dot_dag_enable ) QUARK_DOT_DAG_Enable( quark, 1 );
/* Launch workers; first create the structures */
for(i = 1; i < num_threads; i++)
quark->worker[i] = quark_worker_new(quark, i);
/* Threads can start as soon as they want */
quark->start = TRUE;
return quark;
}
/* **************************************************************************** */
/**
* Called by the master thread. Allocate and initialize the scheduler
* data stuctures and spawn worker threads. Used when this scheduler
* is to do all the thread management.
*
* @param[in] num_threads
* Number of threads to be used (1 master and rest compute workers).
* If num_threads < 1, first try environment variable QUARK_NUM_THREADS
* or use use num_threads = number of cores
* @return
* Pointer to the QUARK data structure.
* @ingroup QUARK
*/
Quark *QUARK_New(int num_threads)
{
int i, nthrd;
/* Init number of cores and topology */
quark_topology_init();
/* Get number of threads */
if ( num_threads < 1 ) {
nthrd = quark_get_numthreads();
if ( nthrd == -1 ) nthrd = 1;
} else {
nthrd = num_threads;
}
/* Create scheduler data structures for master and workers */
Quark *quark = QUARK_Setup(nthrd);
/* Get binding informations */
quark->coresbind = quark_get_affthreads();
/* Setup thread attributes */
pthread_attr_init(&quark->thread_attr);
/* pthread_setconcurrency(quark->num_threads); */
pthread_attr_setscope(&quark->thread_attr, PTHREAD_SCOPE_SYSTEM);
/* Then start the threads, so that workers can scan the structures easily */
for(i = 1; i < nthrd; i++) {
int rc = pthread_create(&quark->worker[i]->thread_id, &quark->thread_attr, (void *(*)(void *))quark_work_set_affinity_and_call_main_loop, quark->worker[i]);
if ( rc != 0 ) quark_fatal_error ( " QUARK_New", "Could not create threads properly" );
}
quark_setaffinity( quark->coresbind[0] );
return quark;
}
/* **************************************************************************** */
/**
* Called by the master thread. Wait for all the tasks to be
* completed, then return. The worker tasks will NOT exit from their
* work loop.
*
* @param[in,out] quark
* The scheduler's main data structure.
* @ingroup QUARK
*/
void QUARK_Barrier(Quark * quark)
{
long long num_tasks = 1;
/* Force queue_before_computing to be OFF!! */
quark->queue_before_computing = FALSE;
quark->all_tasks_queued = TRUE;
do {
quark_process_completed_tasks(quark);
num_tasks = quark_work_main_loop( quark->worker[0] );
#ifdef QUARK_WITH_VALGRIND
/* Asim: maybe you can have a signal right here ? */
pthread_yield();
#endif
} while ( num_tasks > 0 );
/* FIXME Since address_set_nodes are not cleaned as the code progresses, they are freed here */
if ( quark->dot_dag_enable ) {
/* If dag generation is enabled, reset level counters */
unsigned long long tasklevel = 0;
for ( tasklevel=1; tasklevel<tasklevel_width_max_level; tasklevel++ )
if ( quark->tasklevel_width[tasklevel] == 0 )
break;
tasklevel = tasklevel -1;
int tmpint; icl_entry_t* tmpent; void *kp, *dp;
icl_hash_foreach(quark->address_set, tmpint, tmpent, kp, dp) {
Address_Set_Node *address_set_node = (Address_Set_Node *)dp;
address_set_node->last_writer_tasklevel = tasklevel;
address_set_node->last_reader_or_writer_tasklevel = tasklevel;
}
fprintf(dot_dag_file, "// QUARK_Barrier reached: level=%llu \n", tasklevel );
} else {
/* If NO dag generation, cleanup memory */
icl_hash_destroy( quark->address_set, NULL, quark_address_set_node_free );
quark->address_set = icl_hash_create( 0x01<<12, address_hash_function, address_key_compare);
}
}
/* **************************************************************************** */
/**
* Called by the master thread. Wait for all the
* tasks to be completed, then return. The worker tasks will also
* exit from their work loop at this time.
*
* @param[in,out] quark
* The scheduler's main data structure.
* @ingroup QUARK
*/
void QUARK_Waitall(Quark * quark)
{
int i;
Worker *worker;
QUARK_Barrier( quark );
/* Tell each worker to exit the work_loop; master handles himself */
for (i=1; i<quark->num_threads; i++) {
worker = quark->worker[i];
DBGPRINTF("Wkr %d [ %d ] setting finalize\n", worker->rank, worker->ready_list_size );
quark_atomic_set( worker->finalize, TRUE, &worker->worker_mutex );
}
pthread_mutex_lock_wrap( &quark->num_queued_tasks_mutex );
for (i=0; i<quark->num_threads; i++)
pthread_cond_signal( &quark->worker[i]->worker_must_awake_cond );
pthread_mutex_unlock_wrap( &quark->num_queued_tasks_mutex );
}
/* **************************************************************************** */
/**
* Called by the master thread. Free all QUARK data structures, this
* assumes that all usage of QUARK is completed. This interface does
* not manage, delete or close down the worker threads.
*
* @param[in,out] quark
* The scheduler's main data structure.
* @ingroup QUARK
*/
void QUARK_Free(Quark * quark)
{
int i;
QUARK_Waitall(quark);
/* Write the level matching/forcing information */
QUARK_DOT_DAG_Enable( quark, 0 );
/* Destroy hash tables, workers and other data structures */
for (i = 1; i < quark->num_threads; i++)
quark_worker_delete( quark->worker[i] );
quark_worker_delete( quark->worker[0] );
if (quark->worker) free(quark->worker);
if (quark->completed_tasks) free(quark->completed_tasks);
icl_hash_destroy( quark->address_set, NULL, quark_address_set_node_free );
icl_hash_destroy( quark->task_set, NULL, NULL );
pthread_mutex_destroy(&quark->address_set_mutex);
pthread_mutex_destroy(&quark->quark_mutex);
free(quark);
}
/* **************************************************************************** */
/**
* Called by the master thread. Wait for all tasks to complete, then