-
Notifications
You must be signed in to change notification settings - Fork 59
Expand file tree
/
Copy pathrml_server.cpp
More file actions
3309 lines (2975 loc) · 125 KB
/
rml_server.cpp
File metadata and controls
3309 lines (2975 loc) · 125 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright (c) 2005-2017 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "rml_tbb.h"
#define private public /* Sleazy trick to avoid publishing internal names in public header. */
#include "rml_omp.h"
#undef private
#include "tbb/tbb_allocator.h"
#include "tbb/cache_aligned_allocator.h"
#include "tbb/aligned_space.h"
#include "tbb/atomic.h"
#include "tbb/spin_mutex.h"
#include "tbb/tbb_misc.h" // Get AvailableHwConcurrency() from here.
#if _MSC_VER==1500 && !defined(__INTEL_COMPILER)
// VS2008/VC9 seems to have an issue;
#pragma warning( push )
#pragma warning( disable: 4985 )
#endif
#include "tbb/concurrent_vector.h"
#if _MSC_VER==1500 && !defined(__INTEL_COMPILER)
#pragma warning( pop )
#endif
#if _MSC_VER && defined(_Wp64)
// Workaround for overzealous compiler warnings
#pragma warning (push)
#pragma warning (disable: 4244)
#endif
#include "job_automaton.h"
#include "wait_counter.h"
#include "thread_monitor.h"
#if RML_USE_WCRM
#include <concrt.h>
#include <concrtrm.h>
using namespace Concurrency;
#include <vector>
#include <hash_map>
#define __RML_REMOVE_VIRTUAL_PROCESSORS_DISABLED 0
#endif /* RML_USE_WCRM */
#define STRINGIFY(x) #x
#define TOSTRING(x) STRINGIFY(x)
namespace rml {
namespace internal {
using tbb::internal::rml::tbb_client;
using tbb::internal::rml::tbb_server;
using __kmp::rml::omp_client;
using __kmp::rml::omp_server;
typedef versioned_object::version_type version_type;
#define SERVER_VERSION 2
#define EARLIEST_COMPATIBLE_CLIENT_VERSION 2
static const size_t cache_line_size = tbb::internal::NFS_MaxLineSize;
template<typename Server, typename Client> class generic_connection;
class tbb_connection_v2;
class omp_connection_v2;
#if RML_USE_WCRM
//! State of a server_thread
/** Below are diagrams of legal state transitions.
ts_busy
^ ^
/ \
/ V
ts_done <----- ts_asleep <------> ts_idle
*/
enum thread_state_t {
ts_idle,
ts_asleep,
ts_busy,
ts_done
};
//! Extra state of an omp server thread
enum thread_extra_state_t {
ts_none,
ts_removed,
ts_lent
};
//! Results from try_grab_for()
enum thread_grab_t {
wk_failed,
wk_from_asleep,
wk_from_idle
};
#else /* !RML_USE_WCRM */
//! State of a server_thread
/** Below are diagrams of legal state transitions.
OMP
ts_omp_busy
^ ^
/ \
/ V
ts_asleep <-----------> ts_idle
ts_deactivated
^ ^
/ \
V \
ts_none <--------------> ts_reactivated
TBB
ts_tbb_busy
^ ^
/ \
/ V
ts_asleep <-----------> ts_idle --> ts_done
For TBB only. Extra state transition.
ts_created -> ts_started -> ts_visited
*/
enum thread_state_t {
//! Thread not doing anything useful, but running and looking for work.
ts_idle,
//! Thread not doing anything useful and is asleep */
ts_asleep,
//! Thread is enlisted into OpenMP team
ts_omp_busy,
//! Thread is busy doing TBB work.
ts_tbb_busy,
//! For tbb threads only
ts_done,
ts_created,
ts_started,
ts_visited,
//! For omp threads only
ts_none,
ts_deactivated,
ts_reactivated
};
#endif /* RML_USE_WCRM */
#if TBB_USE_ASSERT
#define PRODUCE_ARG(x) ,x
#else
#define PRODUCE_ARG(x)
#endif /* TBB_USE_ASSERT */
//! Synchronizes dispatch of OpenMP work.
class omp_dispatch_type {
typedef ::rml::job job_type;
omp_client* client;
void* cookie;
omp_client::size_type index;
tbb::atomic<job_type*> job;
#if TBB_USE_ASSERT
omp_connection_v2* server;
#endif /* TBB_USE_ASSERT */
public:
omp_dispatch_type() {job=NULL;}
void consume();
void produce( omp_client& c, job_type* j, void* cookie_, omp_client::size_type index_ PRODUCE_ARG( omp_connection_v2& s )) {
__TBB_ASSERT( j, NULL );
__TBB_ASSERT( !job, "job already set" );
client = &c;
#if TBB_USE_ASSERT
server = &s;
#endif /* TBB_USE_ASSERT */
cookie = cookie_;
index = index_;
// Must be last
job = j;
}
};
//! A reference count.
/** No default constructor, because users of ref_count must be very careful about whether the
initial reference count is 0 or 1. */
class ref_count: no_copy {
friend class thread_map;
tbb::atomic<int> my_ref_count;
public:
ref_count(int k ) {my_ref_count=k;}
~ref_count() {__TBB_ASSERT( !my_ref_count, "premature destruction of refcounted object" );}
//! Add one and return new value.
int add_ref() {
int k = ++my_ref_count;
__TBB_ASSERT(k>=1,"reference count underflowed before add_ref");
return k;
}
//! Subtract one and return new value.
int remove_ref() {
int k = --my_ref_count;
__TBB_ASSERT(k>=0,"reference count underflow");
return k;
}
};
#if RML_USE_WCRM
#if USE_UMS_THREAD
#define RML_THREAD_KIND UmsThreadDefault
#define RML_THREAD_KIND_STRING "UmsThread"
#else
#define RML_THREAD_KIND ThreadScheduler
#define RML_THREAD_KIND_STRING "WinThread"
#endif
// Forward declaration
class thread_map;
static const IExecutionResource* c_remove_prepare = (IExecutionResource*)0;
static const IExecutionResource* c_remove_returned = (IExecutionResource*)1;
//! Server thread representation
class server_thread_rep : no_copy {
friend class thread_map;
friend class omp_connection_v2;
friend class server_thread;
friend class tbb_server_thread;
friend class omp_server_thread;
template<typename Connection> friend void make_job( Connection& c, typename Connection::server_thread_type& t );
typedef int thread_state_rep_t;
public:
//! Ctor
server_thread_rep( bool assigned, IScheduler* s, IExecutionResource* r, thread_map& map, rml::client& cl ) :
uid( GetExecutionContextId() ), my_scheduler(s), my_proxy(NULL),
my_thread_map(map), my_client(cl), my_job(NULL)
{
my_state = assigned ? ts_busy : ts_idle;
my_extra_state = ts_none;
terminate = false;
my_execution_resource = r;
}
//! Dtor
~server_thread_rep() {}
//! Synchronization routine
inline rml::job* wait_for_job() {
if( !my_job ) my_job = my_job_automaton.wait_for_job();
return my_job;
}
// Getters and setters
inline thread_state_t read_state() const { thread_state_rep_t s = my_state; return static_cast<thread_state_t>(s); }
inline void set_state( thread_state_t to ) {my_state = to;}
inline void set_removed() { __TBB_ASSERT( my_extra_state==ts_none, NULL ); my_extra_state = ts_removed; }
inline bool is_removed() const { return my_extra_state==ts_removed; }
inline bool is_lent() const {return my_extra_state==ts_lent;}
inline void set_lent() { my_extra_state=ts_lent; }
inline void set_returned() { my_extra_state=ts_none; }
inline IExecutionResource* get_execution_resource() { return my_execution_resource; }
inline IVirtualProcessorRoot* get_virtual_processor() { return (IVirtualProcessorRoot*)get_execution_resource(); }
//! Enlist the thread for work
inline bool wakeup( thread_state_t to, thread_state_t from ) {
__TBB_ASSERT( from==ts_asleep && (to==ts_idle||to==ts_busy||to==ts_done), NULL );
return my_state.compare_and_swap( to, from )==from;
}
//! Enlist the thread for.
thread_grab_t try_grab_for();
//! Destroy the client job associated with the thread
template<typename Connection> bool destroy_job( Connection* c );
//! Try to re-use the thread
void revive( IScheduler* s, IExecutionResource* r, rml::client& c ) {
// the variables may not have been set before a thread was told to quit
__TBB_ASSERT( my_scheduler==s, "my_scheduler has been altered?\n" );
my_scheduler = s;
__TBB_ASSERT( &my_client==&c, "my_client has been altered?\n" );
if( r ) my_execution_resource = r;
my_client = c;
my_state = ts_idle;
__TBB_ASSERT( my_extra_state==ts_removed, NULL );
my_extra_state = ts_none;
}
protected:
const int uid;
IScheduler* my_scheduler;
IThreadProxy* my_proxy;
tbb::atomic<IExecutionResource*> my_execution_resource; /* for non-masters, it is IVirtualProcessorRoot */
thread_map& my_thread_map;
rml::client& my_client;
job* my_job;
job_automaton my_job_automaton;
tbb::atomic<bool> terminate;
tbb::atomic<thread_state_rep_t> my_state;
tbb::atomic<thread_extra_state_t> my_extra_state;
};
//! Class that implements IExecutionContext
class server_thread : public IExecutionContext, public server_thread_rep {
friend class tbb_connection_v2;
friend class omp_connection_v2;
friend class tbb_server_thread;
friend class omp_server_thread;
friend class thread_map;
template<typename Connection> friend void make_job( Connection& c, typename Connection::server_thread_type& t );
protected:
server_thread( bool is_tbb, bool assigned, IScheduler* s, IExecutionResource* r, thread_map& map, rml::client& cl ) : server_thread_rep(assigned,s,r,map,cl), tbb_thread(is_tbb) {}
~server_thread() {}
unsigned int GetId() const __TBB_override { return uid; }
IScheduler* GetScheduler() __TBB_override { return my_scheduler; }
IThreadProxy* GetProxy() __TBB_override { return my_proxy; }
void SetProxy( IThreadProxy* thr_proxy ) __TBB_override { my_proxy = thr_proxy; }
private:
bool tbb_thread;
};
// Forward declaration
class tbb_connection_v2;
class omp_connection_v2;
//! TBB server thread
class tbb_server_thread : public server_thread {
friend class tbb_connection_v2;
public:
tbb_server_thread( bool assigned, IScheduler* s, IExecutionResource* r, tbb_connection_v2* con, thread_map& map, rml::client& cl ) : server_thread(true,assigned,s,r,map,cl), my_conn(con) {
activation_count = 0;
}
~tbb_server_thread() {}
void Dispatch( DispatchState* ) __TBB_override;
inline bool initiate_termination();
bool sleep_perhaps();
//! Switch out this thread
bool switch_out();
private:
tbb_connection_v2* my_conn;
public:
tbb::atomic<int> activation_count;
};
//! OMP server thread
class omp_server_thread : public server_thread {
friend class omp_connection_v2;
public:
omp_server_thread( bool assigned, IScheduler* s, IExecutionResource* r, omp_connection_v2* con, thread_map& map, rml::client& cl ) :
server_thread(false,assigned,s,r,map,cl), my_conn(con), my_cookie(NULL), my_index(UINT_MAX) {}
~omp_server_thread() {}
void Dispatch( DispatchState* ) __TBB_override;
inline void* get_cookie() {return my_cookie;}
inline ::__kmp::rml::omp_client::size_type get_index() {return my_index;}
inline IExecutionResource* get_execution_resource() { return get_execution_resource(); }
inline bool initiate_termination() { return destroy_job( (omp_connection_v2*) my_conn ); }
void sleep_perhaps();
private:
omp_connection_v2* my_conn;
void* my_cookie;
::__kmp::rml::omp_client::size_type my_index;
omp_dispatch_type omp_data;
};
//! Class that implements IScheduler
template<typename Connection>
class scheduler : no_copy, public IScheduler {
public:
unsigned int GetId() const __TBB_override {return uid;}
void Statistics( unsigned int* /*pTaskCompletionRate*/, unsigned int* /*pTaskArrivalRate*/, unsigned int* /*pNumberOfTaskEnqueued*/) __TBB_override {}
SchedulerPolicy GetPolicy() const __TBB_override { __TBB_ASSERT(my_policy,NULL); return *my_policy; }
void AddVirtualProcessors( IVirtualProcessorRoot** vproots, unsigned int count ) __TBB_override { if( !my_conn.is_closing() ) my_conn.add_virtual_processors( vproots, count); }
void RemoveVirtualProcessors( IVirtualProcessorRoot** vproots, unsigned int count ) __TBB_override;
void NotifyResourcesExternallyIdle( IVirtualProcessorRoot** vproots, unsigned int count ) __TBB_override { __TBB_ASSERT( false, "This call is not allowed for TBB" ); }
void NotifyResourcesExternallyBusy( IVirtualProcessorRoot** vproots, unsigned int count ) __TBB_override { __TBB_ASSERT( false, "This call is not allowed for TBB" ); }
protected:
scheduler( Connection& conn );
virtual ~scheduler() { __TBB_ASSERT( my_policy, NULL ); delete my_policy; }
public:
static scheduler* create( Connection& conn ) {return new scheduler( conn );}
private:
const int uid;
Connection& my_conn;
SchedulerPolicy* my_policy;
};
/*
* --> ts_busy --> ts_done
*/
class thread_scavenger_thread : public IExecutionContext, no_copy {
public:
thread_scavenger_thread( IScheduler* s, IVirtualProcessorRoot* r, thread_map& map ) :
uid( GetExecutionContextId() ), my_scheduler(s), my_virtual_processor_root(r), my_proxy(NULL), my_thread_map(map)
{
my_state = ts_busy;
#if TBB_USE_ASSERT
activation_count = 0;
#endif
}
~thread_scavenger_thread() {}
unsigned int GetId() const __TBB_override { return uid; }
IScheduler* GetScheduler() __TBB_override { return my_scheduler; }
IThreadProxy* GetProxy() __TBB_override { return my_proxy; }
void SetProxy( IThreadProxy* thr_proxy ) __TBB_override { my_proxy = thr_proxy; }
void Dispatch( DispatchState* ) __TBB_override;
inline thread_state_t read_state() { return my_state; }
inline void set_state( thread_state_t s ) { my_state = s; }
inline IVirtualProcessorRoot* get_virtual_processor() { return my_virtual_processor_root; }
private:
const int uid;
IScheduler* my_scheduler;
IVirtualProcessorRoot* my_virtual_processor_root;
IThreadProxy* my_proxy;
thread_map& my_thread_map;
tbb::atomic<thread_state_t> my_state;
#if TBB_USE_ASSERT
public:
tbb::atomic<int> activation_count;
#endif
};
static const thread_scavenger_thread* c_claimed = reinterpret_cast<thread_scavenger_thread*>(1);
struct garbage_connection_queue {
tbb::atomic<uintptr_t> head;
tbb::atomic<uintptr_t> tail;
static const uintptr_t empty = 0; // connection scavenger thread empty list
static const uintptr_t plugged = 1; // end of use of the list
static const uintptr_t plugged_acked = 2; // connection scavenger saw the plugged flag, and it freed all connections
};
//! Connection scavenger
/** It collects closed connection objects, wait for worker threads belonging to the connection to return to ConcRT RM
* then return the object to the memory manager.
*/
class connection_scavenger_thread {
friend void assist_cleanup_connections();
/*
* connection_scavenger_thread's state
* ts_busy <----> ts_asleep <--
*/
tbb::atomic<thread_state_t> state;
/* We steal two bits from a connection pointer to encode
* whether the connection is for TBB or for OMP.
*
* ----------------------------------
* | | | |
* ----------------------------------
* ^ ^
* / |
* 1 : tbb, 0 : omp |
* if set, terminate
*/
// FIXME: pad these?
thread_monitor monitor;
HANDLE thr_handle;
#if TBB_USE_ASSERT
tbb::atomic<int> n_scavenger_threads;
#endif
public:
connection_scavenger_thread() : thr_handle(NULL) {
state = ts_asleep;
#if TBB_USE_ASSERT
n_scavenger_threads = 0;
#endif
}
~connection_scavenger_thread() {}
void wakeup() {
if( state.compare_and_swap( ts_busy, ts_asleep )==ts_asleep )
monitor.notify();
}
void sleep_perhaps();
void process_requests( uintptr_t conn_ex );
static __RML_DECL_THREAD_ROUTINE thread_routine( void* arg );
void launch() {
thread_monitor::launch( connection_scavenger_thread::thread_routine, this, NULL );
}
template<typename Server, typename Client>
void add_request( generic_connection<Server,Client>* conn_to_close );
template<typename Server, typename Client>
uintptr_t grab_and_prepend( generic_connection<Server,Client>* last_conn_to_close );
};
void free_all_connections( uintptr_t );
#endif /* RML_USE_WCRM */
#if !RML_USE_WCRM
class server_thread;
//! thread_map_base; we need to make the iterator type available to server_thread
struct thread_map_base {
//! A value in the map
class value_type {
public:
server_thread& thread() {
__TBB_ASSERT( my_thread, "thread_map::value_type::thread() called when !my_thread" );
return *my_thread;
}
rml::job& job() {
__TBB_ASSERT( my_job, "thread_map::value_type::job() called when !my_job" );
return *my_job;
}
value_type() : my_thread(NULL), my_job(NULL) {}
server_thread& wait_for_thread() const {
for(;;) {
server_thread* ptr=const_cast<server_thread*volatile&>(my_thread);
if( ptr )
return *ptr;
__TBB_Yield();
}
}
/** Shortly after when a connection is established, it is possible for the server
to grab a server_thread that has not yet created a job object for that server. */
rml::job* wait_for_job() const {
if( !my_job ) {
my_job = my_automaton.wait_for_job();
}
return my_job;
}
private:
server_thread* my_thread;
/** Marked mutable because though it is physically modified, conceptually it is a duplicate of
the job held by job_automaton. */
mutable rml::job* my_job;
job_automaton my_automaton;
// FIXME - pad out to cache line, because my_automaton is hit hard by thread()
friend class thread_map;
};
typedef tbb::concurrent_vector<value_type,tbb::zero_allocator<value_type,tbb::cache_aligned_allocator> > array_type;
};
#endif /* !RML_USE_WCRM */
#if _MSC_VER && !defined(__INTEL_COMPILER)
// Suppress overzealous compiler warnings about uninstantiable class
#pragma warning(push)
#pragma warning(disable:4510 4610)
#endif
template<typename T>
class padded: public T {
char pad[cache_line_size - sizeof(T)%cache_line_size];
};
#if _MSC_VER && !defined(__INTEL_COMPILER)
#pragma warning(pop)
#endif
// FIXME - should we pad out memory to avoid false sharing of our global variables?
static unsigned the_default_concurrency;
static tbb::atomic<int> the_balance;
static tbb::atomic<tbb::internal::do_once_state> rml_module_state;
#if !RML_USE_WCRM
//! Per thread information
/** ref_count holds number of clients that are using this,
plus 1 if a host thread owns this instance. */
class server_thread: public ref_count {
friend class thread_map;
template<typename Server, typename Client> friend class generic_connection;
friend class tbb_connection_v2;
friend class omp_connection_v2;
//! Integral type that can hold a thread_state_t
typedef int thread_state_rep_t;
tbb::atomic<thread_state_rep_t> state;
public:
thread_monitor monitor;
private:
bool is_omp_thread;
tbb::atomic<thread_state_rep_t> my_extra_state;
server_thread* link;
thread_map_base::array_type::iterator my_map_pos;
rml::server *my_conn;
rml::job* my_job;
job_automaton* my_ja;
size_t my_index;
tbb::atomic<bool> terminate;
omp_dispatch_type omp_dispatch;
#if TBB_USE_ASSERT
//! Flag used to check if thread is still using *this.
bool has_active_thread;
#endif /* TBB_USE_ASSERT */
//! Volunteer to sleep.
void sleep_perhaps( thread_state_t asleep );
//! Destroy job corresponding to given client
/** Return true if thread must quit. */
template<typename Connection>
bool destroy_job( Connection& c );
//! Do terminate the thread
/** Return true if thread must quit. */
bool do_termination();
void loop();
static __RML_DECL_THREAD_ROUTINE thread_routine( void* arg );
public:
server_thread();
~server_thread();
//! Read the thread state
thread_state_t read_state() const {
thread_state_rep_t s = state;
__TBB_ASSERT( unsigned(s)<=unsigned(ts_done), "corrupted server thread?" );
return thread_state_t(s);
}
//! Read the tbb-specific extra thread state
thread_state_t read_extra_state() const {
thread_state_rep_t s = my_extra_state;
return thread_state_t(s);
}
//! Launch a thread that is bound to *this.
void launch( size_t stack_size );
//! Attempt to wakeup a thread
/** The value "to" is the new state for the thread, if it was woken up.
Returns true if thread was woken up, false otherwise. */
bool wakeup( thread_state_t to, thread_state_t from );
//! Attempt to enslave a thread for OpenMP/TBB.
/** Returns true if state is successfully changed. 's' takes either ts_omp_busy or ts_tbb_busy */
bool try_grab_for( thread_state_t s );
#if _WIN32||_WIN64
//! Send the worker thread to sleep temporarily
void deactivate();
//! Wake the worker thread up
void reactivate();
#endif /* _WIN32||_WIN64 */
};
//! Bag of threads that are private to a client.
class private_thread_bag {
struct list_thread: server_thread {
list_thread* next;
};
//! Root of atomic linked list of list_thread
/** ABA problem is avoided because items are only atomically pushed, never popped. */
tbb::atomic<list_thread*> my_root;
tbb::cache_aligned_allocator<padded<list_thread> > my_allocator;
public:
//! Construct empty bag
private_thread_bag() {my_root=NULL;}
//! Create a fresh server_thread object.
server_thread& add_one_thread() {
list_thread* t = my_allocator.allocate(1);
new( t ) list_thread;
// Atomically add to list
list_thread* old_root;
do {
old_root = my_root;
t->next = old_root;
} while( my_root.compare_and_swap( t, old_root )!=old_root );
return *t;
}
//! Destroy the bag and threads in it.
~private_thread_bag() {
while( my_root ) {
// Unlink thread from list.
list_thread* t = my_root;
my_root = t->next;
// Destroy and deallocate the thread.
t->~list_thread();
my_allocator.deallocate(static_cast<padded<list_thread>*>(t),1);
}
}
};
//! Forward declaration
void wakeup_some_tbb_threads();
//! Type-independent part of class generic_connection.
/** One to one map from server threads to jobs, and associated reference counting. */
class thread_map : public thread_map_base {
public:
typedef rml::client::size_type size_type;
//! ctor
thread_map( wait_counter& fc, ::rml::client& client ) :
all_visited_at_least_once(false), my_min_stack_size(0), my_server_ref_count(1),
my_client_ref_count(1), my_client(client), my_factory_counter(fc)
{ my_unrealized_threads = 0; }
//! dtor
~thread_map() {}
typedef array_type::iterator iterator;
iterator begin() {return my_array.begin();}
iterator end() {return my_array.end();}
void bind();
void unbind();
void assist_cleanup( bool assist_null_only );
/** Returns number of unrealized threads to create. */
size_type wakeup_tbb_threads( size_type n );
bool wakeup_next_thread( iterator i, tbb_connection_v2& conn );
void release_tbb_threads( server_thread* t );
void adjust_balance( int delta );
//! Add a server_thread object to the map, but do not bind it.
/** Return NULL if out of unrealized threads. */
value_type* add_one_thread( bool is_omp_thread_ );
void bind_one_thread( rml::server& server, value_type& x );
void remove_client_ref();
int add_server_ref() {return my_server_ref_count.add_ref();}
int remove_server_ref() {return my_server_ref_count.remove_ref();}
::rml::client& client() const {return my_client;}
size_type get_unrealized_threads() { return my_unrealized_threads; }
private:
private_thread_bag my_private_threads;
bool all_visited_at_least_once;
array_type my_array;
size_t my_min_stack_size;
tbb::atomic<size_type> my_unrealized_threads;
//! Number of threads referencing *this, plus one extra.
/** When it becomes zero, the containing server object can be safely deleted. */
ref_count my_server_ref_count;
//! Number of jobs that need cleanup, plus one extra.
/** When it becomes zero, acknowledge_close_connection is called. */
ref_count my_client_ref_count;
::rml::client& my_client;
//! Counter owned by factory that produced this thread_map.
wait_counter& my_factory_counter;
};
void thread_map::bind_one_thread( rml::server& server, value_type& x ) {
// Add one to account for the thread referencing this map hereforth.
server_thread& t = x.thread();
my_server_ref_count.add_ref();
my_client_ref_count.add_ref();
#if TBB_USE_ASSERT
__TBB_ASSERT( t.add_ref()==1, NULL );
#else
t.add_ref();
#endif
// Have responsibility to start the thread.
t.my_conn = &server;
t.my_ja = &x.my_automaton;
t.launch( my_min_stack_size );
/* Must wake thread up so it can fill in its "my_job" field in *this.
Otherwise deadlock can occur where wait_for_job spins on thread that is sleeping. */
__TBB_ASSERT( t.state!=ts_tbb_busy, NULL );
t.wakeup( ts_idle, ts_asleep );
}
thread_map::value_type* thread_map::add_one_thread( bool is_omp_thread_ ) {
size_type u;
do {
u = my_unrealized_threads;
if( !u ) return NULL;
} while( my_unrealized_threads.compare_and_swap(u-1,u)!=u );
server_thread& t = my_private_threads.add_one_thread();
t.is_omp_thread = is_omp_thread_;
__TBB_ASSERT( u>=1, NULL );
t.my_index = u - 1;
__TBB_ASSERT( t.state!=ts_tbb_busy, NULL );
t.my_extra_state = t.is_omp_thread ? ts_none : ts_created;
iterator i = t.my_map_pos = my_array.grow_by(1);
value_type& v = *i;
v.my_thread = &t;
return &v;
}
void thread_map::bind() {
++my_factory_counter;
my_min_stack_size = my_client.min_stack_size();
__TBB_ASSERT( my_unrealized_threads==0, "already called bind?" );
my_unrealized_threads = my_client.max_job_count();
}
void thread_map::unbind() {
// Ask each server_thread to cleanup its job for this server.
for( iterator i=begin(); i!=end(); ++i ) {
server_thread& t = i->thread();
t.terminate = true;
t.wakeup( ts_idle, ts_asleep );
}
// Remove extra ref to client.
remove_client_ref();
}
void thread_map::assist_cleanup( bool assist_null_only ) {
// To avoid deadlock, the current thread *must* help out with cleanups that have not started,
// because the thread that created the job may be busy for a long time.
for( iterator i = begin(); i!=end(); ++i ) {
rml::job* j=0;
job_automaton& ja = i->my_automaton;
if( assist_null_only ? ja.try_plug_null() : ja.try_plug(j) ) {
if( j ) {
my_client.cleanup(*j);
} else {
// server thread did not get a chance to create a job.
}
remove_client_ref();
}
}
}
thread_map::size_type thread_map::wakeup_tbb_threads( size_type n ) {
__TBB_ASSERT(n>0,"must specify positive number of threads to wake up");
iterator e = end();
for( iterator k=begin(); k!=e; ++k ) {
// If another thread added *k, there is a tiny timing window where thread() is invalid.
server_thread& t = k->wait_for_thread();
thread_state_t thr_s = t.read_state();
if( t.read_extra_state()==ts_created || thr_s==ts_tbb_busy || thr_s==ts_done )
continue;
if( --the_balance>=0 ) { // try to withdraw a coin from the deposit
while( !t.try_grab_for( ts_tbb_busy ) ) {
thr_s = t.read_state();
if( thr_s==ts_tbb_busy || thr_s==ts_done ) {
// we lost; move on to the next.
++the_balance;
goto skip;
}
}
if( --n==0 )
return 0;
} else {
// overdraft.
++the_balance;
break;
}
skip:
;
}
return n<my_unrealized_threads ? n : size_type(my_unrealized_threads);
}
#else /* RML_USE_WCRM */
class thread_map : no_copy {
friend class omp_connection_v2;
typedef ::std::hash_map<uintptr_t,server_thread*> hash_map_type;
size_t my_min_stack_size;
size_t my_unrealized_threads;
::rml::client& my_client;
//! Counter owned by factory that produced this thread_map.
wait_counter& my_factory_counter;
//! Ref counters
ref_count my_server_ref_count;
ref_count my_client_ref_count;
// FIXME: pad this?
hash_map_type my_map;
bool shutdown_in_progress;
std::vector<IExecutionResource*> original_exec_resources;
tbb::cache_aligned_allocator<padded<tbb_server_thread> > my_tbb_allocator;
tbb::cache_aligned_allocator<padded<omp_server_thread> > my_omp_allocator;
tbb::cache_aligned_allocator<padded<thread_scavenger_thread> > my_scavenger_allocator;
IResourceManager* my_concrt_resource_manager;
IScheduler* my_scheduler;
ISchedulerProxy* my_scheduler_proxy;
tbb::atomic<thread_scavenger_thread*> my_thread_scavenger_thread;
#if TBB_USE_ASSERT
tbb::atomic<int> n_add_vp_requests;
tbb::atomic<int> n_thread_scavengers_created;
#endif
public:
thread_map( wait_counter& fc, ::rml::client& client ) :
my_min_stack_size(0), my_client(client), my_factory_counter(fc),
my_server_ref_count(1), my_client_ref_count(1), shutdown_in_progress(false),
my_concrt_resource_manager(NULL), my_scheduler(NULL), my_scheduler_proxy(NULL)
{
my_thread_scavenger_thread = NULL;
#if TBB_USE_ASSERT
n_add_vp_requests = 0;
n_thread_scavengers_created;
#endif
}
~thread_map() {
__TBB_ASSERT( n_thread_scavengers_created<=1, "too many scavenger thread created" );
// if thread_scavenger_thread is launched, wait for it to complete
if( my_thread_scavenger_thread ) {
__TBB_ASSERT( my_thread_scavenger_thread!=c_claimed, NULL );
while( my_thread_scavenger_thread->read_state()==ts_busy )
__TBB_Yield();
thread_scavenger_thread* tst = my_thread_scavenger_thread;
my_scavenger_allocator.deallocate(static_cast<padded<thread_scavenger_thread>*>(tst),1);
}
// deallocate thread contexts
for( hash_map_type::const_iterator hi=my_map.begin(); hi!=my_map.end(); ++hi ) {
server_thread* thr = hi->second;
if( thr->tbb_thread ) {
while( ((tbb_server_thread*)thr)->activation_count>1 )
__TBB_Yield();
((tbb_server_thread*)thr)->~tbb_server_thread();
my_tbb_allocator.deallocate(static_cast<padded<tbb_server_thread>*>(thr),1);
} else {
((omp_server_thread*)thr)->~omp_server_thread();
my_omp_allocator.deallocate(static_cast<padded<omp_server_thread>*>(thr),1);
}
}
if( my_scheduler_proxy ) {
my_scheduler_proxy->Shutdown();
my_concrt_resource_manager->Release();
__TBB_ASSERT( my_scheduler, NULL );
delete my_scheduler;
} else {
__TBB_ASSERT( !my_scheduler, NULL );
}
}
typedef hash_map_type::key_type key_type;
typedef hash_map_type::value_type value_type;
typedef hash_map_type::iterator iterator;
iterator begin() {return my_map.begin();}
iterator end() {return my_map.end();}
iterator find( key_type k ) {return my_map.find( k );}
iterator insert( key_type k, server_thread* v ) {
std::pair<iterator,bool> res = my_map.insert( value_type(k,v) );
return res.first;
}
void bind( IScheduler* s ) {
++my_factory_counter;
if( s ) {
my_unrealized_threads = s->GetPolicy().GetPolicyValue( MaxConcurrency );
__TBB_ASSERT( my_unrealized_threads>0, NULL );
my_scheduler = s;
my_concrt_resource_manager = CreateResourceManager(); // reference count==3 when first created.
my_scheduler_proxy = my_concrt_resource_manager->RegisterScheduler( s, CONCRT_RM_VERSION_1 );
my_scheduler_proxy->RequestInitialVirtualProcessors( false );
}
}
bool is_closing() { return shutdown_in_progress; }
void unbind( rml::server& server, ::tbb::spin_mutex& mtx );
void add_client_ref() { my_server_ref_count.add_ref(); }
void remove_client_ref();
void add_server_ref() {my_server_ref_count.add_ref();}
int remove_server_ref() {return my_server_ref_count.remove_ref();}
int get_server_ref_count() { int k = my_server_ref_count.my_ref_count; return k; }
void assist_cleanup( bool assist_null_only );
void adjust_balance( int delta );
int current_balance() const {int k = the_balance; return k;}
::rml::client& client() const {return my_client;}
void register_as_master( server::execution_resource_t& v ) const { (IExecutionResource*&)v = my_scheduler_proxy ? my_scheduler_proxy->SubscribeCurrentThread() : NULL; }
// Remove() should be called from the same thread that subscribed the current h/w thread (i.e., the one that
// called register_as_master() ).
void unregister( server::execution_resource_t v ) const {if( v ) ((IExecutionResource*)v)->Remove( my_scheduler );}
void add_virtual_processors( IVirtualProcessorRoot** vprocs, unsigned int count, tbb_connection_v2& conn, ::tbb::spin_mutex& mtx );
void add_virtual_processors( IVirtualProcessorRoot** vprocs, unsigned int count, omp_connection_v2& conn, ::tbb::spin_mutex& mtx );
void remove_virtual_processors( IVirtualProcessorRoot** vproots, unsigned count, ::tbb::spin_mutex& mtx );
void mark_virtual_processors_as_lent( IVirtualProcessorRoot** vproots, unsigned count, ::tbb::spin_mutex& mtx );
void create_oversubscribers( unsigned n, std::vector<server_thread*>& thr_vec, omp_connection_v2& conn, ::tbb::spin_mutex& mtx );
void wakeup_tbb_threads( int c, ::tbb::spin_mutex& mtx );
void mark_virtual_processors_as_returned( IVirtualProcessorRoot** vprocs, unsigned int count, tbb::spin_mutex& mtx );
inline void addto_original_exec_resources( IExecutionResource* r, ::tbb::spin_mutex& mtx ) {
::tbb::spin_mutex::scoped_lock lck(mtx);
__TBB_ASSERT( !is_closing(), "trying to register master while connection is being shutdown?" );
original_exec_resources.push_back( r );
}
#if !__RML_REMOVE_VIRTUAL_PROCESSORS_DISABLED
void allocate_thread_scavenger( IExecutionResource* v );
#endif
inline thread_scavenger_thread* get_thread_scavenger() { return my_thread_scavenger_thread; }
};
garbage_connection_queue connections_to_reclaim;