source: libcfa/src/concurrency/ready_queue.cfa @ 6528d75

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

Added alternative to relaxed-fifo scheduler.
Disabled by default

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