source: libcfa/src/concurrency/ready_queue.cfa @ 78d6c803

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

Removed snzi from ready queue.
It hasn't been used in a while and I don't expect to ever use it again.
Left the files in incase it's useful for something else.

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