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

ADTarm-ehast-experimentalenumforall-pointer-decayjacob/cs343-translationnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since a3effcc was 772411a, checked in by Thierry Delisle <tdelisle@…>, 4 years ago

Moved bias to it's own function.
Fixed minor assertions triggering.

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