source: libcfa/src/concurrency/ready_queue.cfa@ ec43cf9

ADT arm-eh ast-experimental enum forall-pointer-decay jacob/cs343-translation new-ast-unique-expr pthread-emulation qualifiedEnum
Last change on this file since ec43cf9 was 5cb51502, checked in by Thierry Delisle <tdelisle@…>, 4 years ago

Fix stats so they are correctly tallied when called from outside the cluster.

  • Property mode set to 100644
File size: 18.7 KB
Line 
1//
2// Cforall Version 1.0.0 Copyright (C) 2019 University of Waterloo
3//
4// The contents of this file are covered under the licence agreement in the
5// file "LICENCE" distributed with Cforall.
6//
7// ready_queue.cfa --
8//
9// Author : Thierry Delisle
10// Created On : Mon Nov dd 16:29:18 2019
11// Last Modified By :
12// Last Modified On :
13// Update Count :
14//
15
16#define __cforall_thread__
17// #define __CFA_DEBUG_PRINT_READY_QUEUE__
18
19// #define USE_SNZI
20// #define USE_MPSC
21
22#include "bits/defs.hfa"
23#include "kernel_private.hfa"
24
25#define _GNU_SOURCE
26#include "stdlib.hfa"
27#include "math.hfa"
28
29#include <unistd.h>
30
31#include "snzi.hfa"
32#include "ready_subqueue.hfa"
33
34static const size_t cache_line_size = 64;
35
36// No overriden function, no environment variable, no define
37// fall back to a magic number
38#ifndef __CFA_MAX_PROCESSORS__
39 #define __CFA_MAX_PROCESSORS__ 1024
40#endif
41
42#define BIAS 4
43
44// returns the maximum number of processors the RWLock support
45__attribute__((weak)) unsigned __max_processors() {
46 const char * max_cores_s = getenv("CFA_MAX_PROCESSORS");
47 if(!max_cores_s) {
48 __cfadbg_print_nolock(ready_queue, "No CFA_MAX_PROCESSORS in ENV\n");
49 return __CFA_MAX_PROCESSORS__;
50 }
51
52 char * endptr = 0p;
53 long int max_cores_l = strtol(max_cores_s, &endptr, 10);
54 if(max_cores_l < 1 || max_cores_l > 65535) {
55 __cfadbg_print_nolock(ready_queue, "CFA_MAX_PROCESSORS out of range : %ld\n", max_cores_l);
56 return __CFA_MAX_PROCESSORS__;
57 }
58 if('\0' != *endptr) {
59 __cfadbg_print_nolock(ready_queue, "CFA_MAX_PROCESSORS not a decimal number : %s\n", max_cores_s);
60 return __CFA_MAX_PROCESSORS__;
61 }
62
63 return max_cores_l;
64}
65
66//=======================================================================
67// Cluster wide reader-writer lock
68//=======================================================================
69void ?{}(__scheduler_RWLock_t & this) {
70 this.max = __max_processors();
71 this.alloc = 0;
72 this.ready = 0;
73 this.lock = false;
74 this.data = alloc(this.max);
75
76 /*paranoid*/ verify( 0 == (((uintptr_t)(this.data )) % 64) );
77 /*paranoid*/ verify( 0 == (((uintptr_t)(this.data + 1)) % 64) );
78 /*paranoid*/ verify(__atomic_is_lock_free(sizeof(this.alloc), &this.alloc));
79 /*paranoid*/ verify(__atomic_is_lock_free(sizeof(this.ready), &this.ready));
80
81}
82void ^?{}(__scheduler_RWLock_t & this) {
83 free(this.data);
84}
85
86void ?{}( __scheduler_lock_id_t & this, __processor_id_t * proc ) {
87 this.handle = proc;
88 this.lock = false;
89 #ifdef __CFA_WITH_VERIFY__
90 this.owned = false;
91 #endif
92}
93
94//=======================================================================
95// Lock-Free registering/unregistering of threads
96unsigned doregister( struct __processor_id_t * proc ) with(*__scheduler_lock) {
97 __cfadbg_print_safe(ready_queue, "Kernel : Registering proc %p for RW-Lock\n", proc);
98
99 // Step - 1 : check if there is already space in the data
100 uint_fast32_t s = ready;
101
102 // Check among all the ready
103 for(uint_fast32_t i = 0; i < s; i++) {
104 __processor_id_t * null = 0p; // Re-write every loop since compare thrashes it
105 if( __atomic_load_n(&data[i].handle, (int)__ATOMIC_RELAXED) == null
106 && __atomic_compare_exchange_n( &data[i].handle, &null, proc, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) {
107 /*paranoid*/ verify(i < ready);
108 /*paranoid*/ verify(0 == (__alignof__(data[i]) % cache_line_size));
109 /*paranoid*/ verify((((uintptr_t)&data[i]) % cache_line_size) == 0);
110 return i;
111 }
112 }
113
114 if(max <= alloc) abort("Trying to create more than %ud processors", __scheduler_lock->max);
115
116 // Step - 2 : F&A to get a new spot in the array.
117 uint_fast32_t n = __atomic_fetch_add(&alloc, 1, __ATOMIC_SEQ_CST);
118 if(max <= n) abort("Trying to create more than %ud processors", __scheduler_lock->max);
119
120 // Step - 3 : Mark space as used and then publish it.
121 __scheduler_lock_id_t * storage = (__scheduler_lock_id_t *)&data[n];
122 (*storage){ proc };
123 while() {
124 unsigned copy = n;
125 if( __atomic_load_n(&ready, __ATOMIC_RELAXED) == n
126 && __atomic_compare_exchange_n(&ready, &copy, n + 1, true, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST))
127 break;
128 Pause();
129 }
130
131 __cfadbg_print_safe(ready_queue, "Kernel : Registering proc %p done, id %lu\n", proc, n);
132
133 // Return new spot.
134 /*paranoid*/ verify(n < ready);
135 /*paranoid*/ verify(__alignof__(data[n]) == (2 * cache_line_size));
136 /*paranoid*/ verify((((uintptr_t)&data[n]) % cache_line_size) == 0);
137 return n;
138}
139
140void unregister( struct __processor_id_t * proc ) with(*__scheduler_lock) {
141 unsigned id = proc->id;
142 /*paranoid*/ verify(id < ready);
143 /*paranoid*/ verify(proc == __atomic_load_n(&data[id].handle, __ATOMIC_RELAXED));
144 __atomic_store_n(&data[id].handle, 0p, __ATOMIC_RELEASE);
145
146 __cfadbg_print_safe(ready_queue, "Kernel : Unregister proc %p\n", proc);
147}
148
149//-----------------------------------------------------------------------
150// Writer side : acquire when changing the ready queue, e.g. adding more
151// queues or removing them.
152uint_fast32_t ready_mutate_lock( void ) with(*__scheduler_lock) {
153 /* paranoid */ verify( ! __preemption_enabled() );
154
155 // Step 1 : lock global lock
156 // It is needed to avoid processors that register mid Critical-Section
157 // to simply lock their own lock and enter.
158 __atomic_acquire( &lock );
159
160 // Step 2 : lock per-proc lock
161 // Processors that are currently being registered aren't counted
162 // but can't be in read_lock or in the critical section.
163 // All other processors are counted
164 uint_fast32_t s = ready;
165 for(uint_fast32_t i = 0; i < s; i++) {
166 __atomic_acquire( &data[i].lock );
167 }
168
169 /* paranoid */ verify( ! __preemption_enabled() );
170 return s;
171}
172
173void ready_mutate_unlock( uint_fast32_t last_s ) with(*__scheduler_lock) {
174 /* paranoid */ verify( ! __preemption_enabled() );
175
176 // Step 1 : release local locks
177 // This must be done while the global lock is held to avoid
178 // threads that where created mid critical section
179 // to race to lock their local locks and have the writer
180 // immidiately unlock them
181 // Alternative solution : return s in write_lock and pass it to write_unlock
182 for(uint_fast32_t i = 0; i < last_s; i++) {
183 verify(data[i].lock);
184 __atomic_store_n(&data[i].lock, (bool)false, __ATOMIC_RELEASE);
185 }
186
187 // Step 2 : release global lock
188 /*paranoid*/ assert(true == lock);
189 __atomic_store_n(&lock, (bool)false, __ATOMIC_RELEASE);
190
191 /* paranoid */ verify( ! __preemption_enabled() );
192}
193
194//=======================================================================
195// Cforall Reqdy Queue used for scheduling
196//=======================================================================
197void ?{}(__ready_queue_t & this) with (this) {
198 lanes.data = 0p;
199 lanes.count = 0;
200}
201
202void ^?{}(__ready_queue_t & this) with (this) {
203 verify( 1 == lanes.count );
204 #ifdef USE_SNZI
205 verify( !query( snzi ) );
206 #endif
207 free(lanes.data);
208}
209
210//-----------------------------------------------------------------------
211__attribute__((hot)) bool query(struct cluster * cltr) {
212 #ifdef USE_SNZI
213 return query(cltr->ready_queue.snzi);
214 #endif
215 return true;
216}
217
218static inline [unsigned, bool] idx_from_r(unsigned r, unsigned preferred) {
219 unsigned i;
220 bool local;
221 #if defined(BIAS)
222 unsigned rlow = r % BIAS;
223 unsigned rhigh = r / BIAS;
224 if((0 != rlow) && preferred >= 0) {
225 // (BIAS - 1) out of BIAS chances
226 // Use perferred queues
227 i = preferred + (rhigh % 4);
228 local = true;
229 }
230 else {
231 // 1 out of BIAS chances
232 // Use all queues
233 i = rhigh;
234 local = false;
235 }
236 #else
237 i = r;
238 local = false;
239 #endif
240 return [i, local];
241}
242
243//-----------------------------------------------------------------------
244__attribute__((hot)) bool push(struct cluster * cltr, struct $thread * thrd) with (cltr->ready_queue) {
245 __cfadbg_print_safe(ready_queue, "Kernel : Pushing %p on cluster %p\n", thrd, cltr);
246
247 const bool external = (!kernelTLS().this_processor) || (cltr != kernelTLS().this_processor->cltr);
248
249 // write timestamp
250 thrd->link.ts = rdtscl();
251
252 bool first = false;
253 __attribute__((unused)) bool local;
254 __attribute__((unused)) int preferred;
255 #if defined(BIAS)
256 preferred =
257 //*
258 external ? -1 : kernelTLS().this_processor->cltr_id;
259 /*/
260 thrd->link.preferred * 4;
261 //*/
262 #endif
263
264 // Try to pick a lane and lock it
265 unsigned i;
266 do {
267 // Pick the index of a lane
268 // unsigned r = __tls_rand();
269 unsigned r = __tls_rand_fwd();
270 [i, local] = idx_from_r(r, preferred);
271
272 i %= __atomic_load_n( &lanes.count, __ATOMIC_RELAXED );
273
274 #if !defined(__CFA_NO_STATISTICS__)
275 if(external) {
276 if(local) __atomic_fetch_add(&cltr->stats->ready.pick.ext.local, 1, __ATOMIC_RELAXED);
277 __atomic_fetch_add(&cltr->stats->ready.pick.ext.attempt, 1, __ATOMIC_RELAXED);
278 }
279 else {
280 if(local) __tls_stats()->ready.pick.push.local++;
281 __tls_stats()->ready.pick.push.attempt++;
282 }
283 #endif
284
285 #if defined(USE_MPSC)
286 // mpsc always succeeds
287 } while( false );
288 #else
289 // If we can't lock it retry
290 } while( !__atomic_try_acquire( &lanes.data[i].lock ) );
291 #endif
292
293 // Actually push it
294 #ifdef USE_SNZI
295 bool lane_first =
296 #endif
297
298 push(lanes.data[i], thrd);
299
300 #ifdef USE_SNZI
301 // If this lane used to be empty we need to do more
302 if(lane_first) {
303 // Check if the entire queue used to be empty
304 first = !query(snzi);
305
306 // Update the snzi
307 arrive( snzi, i );
308 }
309 #endif
310
311 #if !defined(USE_MPSC)
312 // Unlock and return
313 __atomic_unlock( &lanes.data[i].lock );
314 #endif
315
316 // Mark the current index in the tls rng instance as having an item
317 __tls_rand_advance_bck();
318
319 __cfadbg_print_safe(ready_queue, "Kernel : Pushed %p on cluster %p (idx: %u, mask %llu, first %d)\n", thrd, cltr, i, used.mask[0], lane_first);
320
321 // Update statistics
322 #if !defined(__CFA_NO_STATISTICS__)
323 if(external) {
324 if(local) __atomic_fetch_add(&cltr->stats->ready.pick.ext.lsuccess, 1, __ATOMIC_RELAXED);
325 __atomic_fetch_add(&cltr->stats->ready.pick.ext.success, 1, __ATOMIC_RELAXED);
326 }
327 else {
328 if(local) __tls_stats()->ready.pick.push.lsuccess++;
329 __tls_stats()->ready.pick.push.success++;
330 }
331 #endif
332
333 // return whether or not the list was empty before this push
334 return first;
335}
336
337static struct $thread * try_pop(struct cluster * cltr, unsigned i, unsigned j);
338static struct $thread * try_pop(struct cluster * cltr, unsigned i);
339
340// Pop from the ready queue from a given cluster
341__attribute__((hot)) $thread * pop(struct cluster * cltr) with (cltr->ready_queue) {
342 /* paranoid */ verify( lanes.count > 0 );
343 unsigned count = __atomic_load_n( &lanes.count, __ATOMIC_RELAXED );
344 int preferred;
345 #if defined(BIAS)
346 // Don't bother trying locally too much
347 preferred = kernelTLS().this_processor->cltr_id;
348 #endif
349
350
351 // As long as the list is not empty, try finding a lane that isn't empty and pop from it
352 #ifdef USE_SNZI
353 while( query(snzi) ) {
354 #else
355 for(25) {
356 #endif
357 // Pick two lists at random
358 // unsigned ri = __tls_rand();
359 // unsigned rj = __tls_rand();
360 unsigned ri = __tls_rand_bck();
361 unsigned rj = __tls_rand_bck();
362
363 unsigned i, j;
364 __attribute__((unused)) bool locali, localj;
365 [i, locali] = idx_from_r(ri, preferred);
366 [j, localj] = idx_from_r(rj, preferred);
367
368 #if !defined(__CFA_NO_STATISTICS__)
369 if(locali && localj) {
370 __tls_stats()->ready.pick.pop.local++;
371 }
372 #endif
373
374 i %= count;
375 j %= count;
376
377 // try popping from the 2 picked lists
378 struct $thread * thrd = try_pop(cltr, i, j);
379 if(thrd) {
380 #if defined(BIAS) && !defined(__CFA_NO_STATISTICS__)
381 if( locali || localj ) __tls_stats()->ready.pick.pop.lsuccess++;
382 #endif
383 return thrd;
384 }
385 }
386
387 // All lanes where empty return 0p
388 return 0p;
389}
390
391__attribute__((hot)) struct $thread * pop_slow(struct cluster * cltr) with (cltr->ready_queue) {
392 /* paranoid */ verify( lanes.count > 0 );
393 unsigned count = __atomic_load_n( &lanes.count, __ATOMIC_RELAXED );
394 unsigned offset = __tls_rand();
395 for(i; count) {
396 unsigned idx = (offset + i) % count;
397 struct $thread * thrd = try_pop(cltr, idx);
398 if(thrd) {
399 return thrd;
400 }
401 }
402
403 // All lanes where empty return 0p
404 return 0p;
405}
406
407
408//-----------------------------------------------------------------------
409// Given 2 indexes, pick the list with the oldest push an try to pop from it
410static inline struct $thread * try_pop(struct cluster * cltr, unsigned i, unsigned j) with (cltr->ready_queue) {
411 #if !defined(__CFA_NO_STATISTICS__)
412 __tls_stats()->ready.pick.pop.attempt++;
413 #endif
414
415 // Pick the bet list
416 int w = i;
417 if( __builtin_expect(!is_empty(lanes.data[j]), true) ) {
418 w = (ts(lanes.data[i]) < ts(lanes.data[j])) ? i : j;
419 }
420
421 return try_pop(cltr, w);
422}
423
424static inline struct $thread * try_pop(struct cluster * cltr, unsigned w) with (cltr->ready_queue) {
425 // Get relevant elements locally
426 __intrusive_lane_t & lane = lanes.data[w];
427
428 // If list looks empty retry
429 if( is_empty(lane) ) return 0p;
430
431 // If we can't get the lock retry
432 if( !__atomic_try_acquire(&lane.lock) ) return 0p;
433
434
435 // If list is empty, unlock and retry
436 if( is_empty(lane) ) {
437 __atomic_unlock(&lane.lock);
438 return 0p;
439 }
440
441 // Actually pop the list
442 struct $thread * thrd;
443 thrd = pop(lane);
444
445 /* paranoid */ verify(thrd);
446 /* paranoid */ verify(lane.lock);
447
448 #ifdef USE_SNZI
449 // If this was the last element in the lane
450 if(emptied) {
451 depart( snzi, w );
452 }
453 #endif
454
455 // Unlock and return
456 __atomic_unlock(&lane.lock);
457
458 // Update statistics
459 #if !defined(__CFA_NO_STATISTICS__)
460 __tls_stats()->ready.pick.pop.success++;
461 #endif
462
463 // Update the thread bias
464 thrd->link.preferred = w / 4;
465
466 // return the popped thread
467 return thrd;
468}
469//-----------------------------------------------------------------------
470
471bool remove_head(struct cluster * cltr, struct $thread * thrd) with (cltr->ready_queue) {
472 for(i; lanes.count) {
473 __intrusive_lane_t & lane = lanes.data[i];
474
475 bool removed = false;
476
477 __atomic_acquire(&lane.lock);
478 if(head(lane)->link.next == thrd) {
479 $thread * pthrd;
480 pthrd = pop(lane);
481
482 /* paranoid */ verify( pthrd == thrd );
483
484 removed = true;
485 #ifdef USE_SNZI
486 if(emptied) {
487 depart( snzi, i );
488 }
489 #endif
490 }
491 __atomic_unlock(&lane.lock);
492
493 if( removed ) return true;
494 }
495 return false;
496}
497
498//-----------------------------------------------------------------------
499
500static void check( __ready_queue_t & q ) with (q) {
501 #if defined(__CFA_WITH_VERIFY__) && !defined(USE_MPSC)
502 {
503 for( idx ; lanes.count ) {
504 __intrusive_lane_t & sl = lanes.data[idx];
505 assert(!lanes.data[idx].lock);
506
507 assert(head(sl)->link.prev == 0p );
508 assert(head(sl)->link.next->link.prev == head(sl) );
509 assert(tail(sl)->link.next == 0p );
510 assert(tail(sl)->link.prev->link.next == tail(sl) );
511
512 if(is_empty(sl)) {
513 assert(tail(sl)->link.prev == head(sl));
514 assert(head(sl)->link.next == tail(sl));
515 } else {
516 assert(tail(sl)->link.prev != head(sl));
517 assert(head(sl)->link.next != tail(sl));
518 }
519 }
520 }
521 #endif
522}
523
524// Call this function of the intrusive list was moved using memcpy
525// fixes the list so that the pointers back to anchors aren't left dangling
526static inline void fix(__intrusive_lane_t & ll) {
527 #if !defined(USE_MPSC)
528 // if the list is not empty then follow he pointer and fix its reverse
529 if(!is_empty(ll)) {
530 head(ll)->link.next->link.prev = head(ll);
531 tail(ll)->link.prev->link.next = tail(ll);
532 }
533 // Otherwise just reset the list
534 else {
535 verify(tail(ll)->link.next == 0p);
536 tail(ll)->link.prev = head(ll);
537 head(ll)->link.next = tail(ll);
538 verify(head(ll)->link.prev == 0p);
539 }
540 #endif
541}
542
543// Grow the ready queue
544unsigned ready_queue_grow(struct cluster * cltr, int target) {
545 unsigned preferred;
546 size_t ncount;
547
548 /* paranoid */ verify( ready_mutate_islocked() );
549 __cfadbg_print_safe(ready_queue, "Kernel : Growing ready queue\n");
550
551 // Make sure that everything is consistent
552 /* paranoid */ check( cltr->ready_queue );
553
554 // grow the ready queue
555 with( cltr->ready_queue ) {
556 #ifdef USE_SNZI
557 ^(snzi){};
558 #endif
559
560 // Find new count
561 // Make sure we always have atleast 1 list
562 if(target >= 2) {
563 ncount = target * 4;
564 preferred = ncount - 4;
565 } else {
566 ncount = 1;
567 preferred = 0;
568 }
569
570 // Allocate new array (uses realloc and memcpies the data)
571 lanes.data = alloc( ncount, lanes.data`realloc );
572
573 // Fix the moved data
574 for( idx; (size_t)lanes.count ) {
575 fix(lanes.data[idx]);
576 }
577
578 // Construct new data
579 for( idx; (size_t)lanes.count ~ ncount) {
580 (lanes.data[idx]){};
581 }
582
583 // Update original
584 lanes.count = ncount;
585
586 #ifdef USE_SNZI
587 // Re-create the snzi
588 snzi{ log2( lanes.count / 8 ) };
589 for( idx; (size_t)lanes.count ) {
590 if( !is_empty(lanes.data[idx]) ) {
591 arrive(snzi, idx);
592 }
593 }
594 #endif
595 }
596
597 // Make sure that everything is consistent
598 /* paranoid */ check( cltr->ready_queue );
599
600 __cfadbg_print_safe(ready_queue, "Kernel : Growing ready queue done\n");
601
602 /* paranoid */ verify( ready_mutate_islocked() );
603 return preferred;
604}
605
606// Shrink the ready queue
607void ready_queue_shrink(struct cluster * cltr, int target) {
608 /* paranoid */ verify( ready_mutate_islocked() );
609 __cfadbg_print_safe(ready_queue, "Kernel : Shrinking ready queue\n");
610
611 // Make sure that everything is consistent
612 /* paranoid */ check( cltr->ready_queue );
613
614 with( cltr->ready_queue ) {
615 #ifdef USE_SNZI
616 ^(snzi){};
617 #endif
618
619 // Remember old count
620 size_t ocount = lanes.count;
621
622 // Find new count
623 // Make sure we always have atleast 1 list
624 lanes.count = target >= 2 ? target * 4: 1;
625 /* paranoid */ verify( ocount >= lanes.count );
626 /* paranoid */ verify( lanes.count == target * 4 || target < 2 );
627
628 // for printing count the number of displaced threads
629 #if defined(__CFA_DEBUG_PRINT__) || defined(__CFA_DEBUG_PRINT_READY_QUEUE__)
630 __attribute__((unused)) size_t displaced = 0;
631 #endif
632
633 // redistribute old data
634 for( idx; (size_t)lanes.count ~ ocount) {
635 // Lock is not strictly needed but makes checking invariants much easier
636 __attribute__((unused)) bool locked = __atomic_try_acquire(&lanes.data[idx].lock);
637 verify(locked);
638
639 // As long as we can pop from this lane to push the threads somewhere else in the queue
640 while(!is_empty(lanes.data[idx])) {
641 struct $thread * thrd;
642 thrd = pop(lanes.data[idx]);
643
644 push(cltr, thrd);
645
646 // for printing count the number of displaced threads
647 #if defined(__CFA_DEBUG_PRINT__) || defined(__CFA_DEBUG_PRINT_READY_QUEUE__)
648 displaced++;
649 #endif
650 }
651
652 // Unlock the lane
653 __atomic_unlock(&lanes.data[idx].lock);
654
655 // TODO print the queue statistics here
656
657 ^(lanes.data[idx]){};
658 }
659
660 __cfadbg_print_safe(ready_queue, "Kernel : Shrinking ready queue displaced %zu threads\n", displaced);
661
662 // Allocate new array (uses realloc and memcpies the data)
663 lanes.data = alloc( lanes.count, lanes.data`realloc );
664
665 // Fix the moved data
666 for( idx; (size_t)lanes.count ) {
667 fix(lanes.data[idx]);
668 }
669
670 #ifdef USE_SNZI
671 // Re-create the snzi
672 snzi{ log2( lanes.count / 8 ) };
673 for( idx; (size_t)lanes.count ) {
674 if( !is_empty(lanes.data[idx]) ) {
675 arrive(snzi, idx);
676 }
677 }
678 #endif
679 }
680
681 // Make sure that everything is consistent
682 /* paranoid */ check( cltr->ready_queue );
683
684 __cfadbg_print_safe(ready_queue, "Kernel : Shrinking ready queue done\n");
685 /* paranoid */ verify( ready_mutate_islocked() );
686}
Note: See TracBrowser for help on using the repository browser.