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

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

Changed ready-queue to use -1 for empty ts.

  • Property mode set to 100644
File size: 30.4 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 _GNU_SOURCE
18
19// #define __CFA_DEBUG_PRINT_READY_QUEUE__
20
21
22#define USE_RELAXED_FIFO
23// #define USE_WORK_STEALING
24
25#include "bits/defs.hfa"
26#include "device/cpu.hfa"
27#include "kernel_private.hfa"
28
29#include "stdlib.hfa"
30#include "math.hfa"
31
32#include <errno.h>
33#include <unistd.h>
34
35extern "C" {
36 #include <sys/syscall.h> // __NR_xxx
37}
38
39#include "ready_subqueue.hfa"
40
41static const size_t cache_line_size = 64;
42
43#if !defined(__CFA_NO_STATISTICS__)
44 #define __STATS(...) __VA_ARGS__
45#else
46 #define __STATS(...)
47#endif
48
49// No overriden function, no environment variable, no define
50// fall back to a magic number
51#ifndef __CFA_MAX_PROCESSORS__
52 #define __CFA_MAX_PROCESSORS__ 1024
53#endif
54
55#if defined(USE_CPU_WORK_STEALING)
56 #define READYQ_SHARD_FACTOR 2
57#elif defined(USE_RELAXED_FIFO)
58 #define BIAS 4
59 #define READYQ_SHARD_FACTOR 4
60 #define SEQUENTIAL_SHARD 1
61#elif defined(USE_WORK_STEALING)
62 #define READYQ_SHARD_FACTOR 2
63 #define SEQUENTIAL_SHARD 2
64#else
65 #error no scheduling strategy selected
66#endif
67
68static inline struct $thread * try_pop(struct cluster * cltr, unsigned w __STATS(, __stats_readyQ_pop_t & stats));
69static inline struct $thread * try_pop(struct cluster * cltr, unsigned i, unsigned j __STATS(, __stats_readyQ_pop_t & stats));
70static inline struct $thread * search(struct cluster * cltr);
71static inline [unsigned, bool] idx_from_r(unsigned r, unsigned preferred);
72
73
74// returns the maximum number of processors the RWLock support
75__attribute__((weak)) unsigned __max_processors() {
76 const char * max_cores_s = getenv("CFA_MAX_PROCESSORS");
77 if(!max_cores_s) {
78 __cfadbg_print_nolock(ready_queue, "No CFA_MAX_PROCESSORS in ENV\n");
79 return __CFA_MAX_PROCESSORS__;
80 }
81
82 char * endptr = 0p;
83 long int max_cores_l = strtol(max_cores_s, &endptr, 10);
84 if(max_cores_l < 1 || max_cores_l > 65535) {
85 __cfadbg_print_nolock(ready_queue, "CFA_MAX_PROCESSORS out of range : %ld\n", max_cores_l);
86 return __CFA_MAX_PROCESSORS__;
87 }
88 if('\0' != *endptr) {
89 __cfadbg_print_nolock(ready_queue, "CFA_MAX_PROCESSORS not a decimal number : %s\n", max_cores_s);
90 return __CFA_MAX_PROCESSORS__;
91 }
92
93 return max_cores_l;
94}
95
96#if defined(CFA_HAVE_LINUX_LIBRSEQ)
97 // No forward declaration needed
98 #define __kernel_rseq_register rseq_register_current_thread
99 #define __kernel_rseq_unregister rseq_unregister_current_thread
100#elif defined(CFA_HAVE_LINUX_RSEQ_H)
101 void __kernel_raw_rseq_register (void);
102 void __kernel_raw_rseq_unregister(void);
103
104 #define __kernel_rseq_register __kernel_raw_rseq_register
105 #define __kernel_rseq_unregister __kernel_raw_rseq_unregister
106#else
107 // No forward declaration needed
108 // No initialization needed
109 static inline void noop(void) {}
110
111 #define __kernel_rseq_register noop
112 #define __kernel_rseq_unregister noop
113#endif
114
115//=======================================================================
116// Cluster wide reader-writer lock
117//=======================================================================
118void ?{}(__scheduler_RWLock_t & this) {
119 this.max = __max_processors();
120 this.alloc = 0;
121 this.ready = 0;
122 this.data = alloc(this.max);
123 this.write_lock = false;
124
125 /*paranoid*/ verify(__atomic_is_lock_free(sizeof(this.alloc), &this.alloc));
126 /*paranoid*/ verify(__atomic_is_lock_free(sizeof(this.ready), &this.ready));
127
128}
129void ^?{}(__scheduler_RWLock_t & this) {
130 free(this.data);
131}
132
133
134//=======================================================================
135// Lock-Free registering/unregistering of threads
136unsigned register_proc_id( void ) with(*__scheduler_lock) {
137 __kernel_rseq_register();
138
139 __cfadbg_print_safe(ready_queue, "Kernel : Registering proc %p for RW-Lock\n", proc);
140 bool * handle = (bool *)&kernelTLS().sched_lock;
141
142 // Step - 1 : check if there is already space in the data
143 uint_fast32_t s = ready;
144
145 // Check among all the ready
146 for(uint_fast32_t i = 0; i < s; i++) {
147 bool * volatile * cell = (bool * volatile *)&data[i]; // Cforall is bugged and the double volatiles causes problems
148 /* paranoid */ verify( handle != *cell );
149
150 bool * null = 0p; // Re-write every loop since compare thrashes it
151 if( __atomic_load_n(cell, (int)__ATOMIC_RELAXED) == null
152 && __atomic_compare_exchange_n( cell, &null, handle, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) {
153 /* paranoid */ verify(i < ready);
154 /* paranoid */ verify( (kernelTLS().sched_id = i, true) );
155 return i;
156 }
157 }
158
159 if(max <= alloc) abort("Trying to create more than %ud processors", __scheduler_lock->max);
160
161 // Step - 2 : F&A to get a new spot in the array.
162 uint_fast32_t n = __atomic_fetch_add(&alloc, 1, __ATOMIC_SEQ_CST);
163 if(max <= n) abort("Trying to create more than %ud processors", __scheduler_lock->max);
164
165 // Step - 3 : Mark space as used and then publish it.
166 data[n] = handle;
167 while() {
168 unsigned copy = n;
169 if( __atomic_load_n(&ready, __ATOMIC_RELAXED) == n
170 && __atomic_compare_exchange_n(&ready, &copy, n + 1, true, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST))
171 break;
172 Pause();
173 }
174
175 __cfadbg_print_safe(ready_queue, "Kernel : Registering proc %p done, id %lu\n", proc, n);
176
177 // Return new spot.
178 /* paranoid */ verify(n < ready);
179 /* paranoid */ verify( (kernelTLS().sched_id = n, true) );
180 return n;
181}
182
183void unregister_proc_id( unsigned id ) with(*__scheduler_lock) {
184 /* paranoid */ verify(id < ready);
185 /* paranoid */ verify(id == kernelTLS().sched_id);
186 /* paranoid */ verify(data[id] == &kernelTLS().sched_lock);
187
188 bool * volatile * cell = (bool * volatile *)&data[id]; // Cforall is bugged and the double volatiles causes problems
189
190 __atomic_store_n(cell, 0p, __ATOMIC_RELEASE);
191
192 __cfadbg_print_safe(ready_queue, "Kernel : Unregister proc %p\n", proc);
193
194 __kernel_rseq_unregister();
195}
196
197//-----------------------------------------------------------------------
198// Writer side : acquire when changing the ready queue, e.g. adding more
199// queues or removing them.
200uint_fast32_t ready_mutate_lock( void ) with(*__scheduler_lock) {
201 /* paranoid */ verify( ! __preemption_enabled() );
202 /* paranoid */ verify( ! kernelTLS().sched_lock );
203
204 // Step 1 : lock global lock
205 // It is needed to avoid processors that register mid Critical-Section
206 // to simply lock their own lock and enter.
207 __atomic_acquire( &write_lock );
208
209 // Step 2 : lock per-proc lock
210 // Processors that are currently being registered aren't counted
211 // but can't be in read_lock or in the critical section.
212 // All other processors are counted
213 uint_fast32_t s = ready;
214 for(uint_fast32_t i = 0; i < s; i++) {
215 volatile bool * llock = data[i];
216 if(llock) __atomic_acquire( llock );
217 }
218
219 /* paranoid */ verify( ! __preemption_enabled() );
220 return s;
221}
222
223void ready_mutate_unlock( uint_fast32_t last_s ) with(*__scheduler_lock) {
224 /* paranoid */ verify( ! __preemption_enabled() );
225
226 // Step 1 : release local locks
227 // This must be done while the global lock is held to avoid
228 // threads that where created mid critical section
229 // to race to lock their local locks and have the writer
230 // immidiately unlock them
231 // Alternative solution : return s in write_lock and pass it to write_unlock
232 for(uint_fast32_t i = 0; i < last_s; i++) {
233 volatile bool * llock = data[i];
234 if(llock) __atomic_store_n(llock, (bool)false, __ATOMIC_RELEASE);
235 }
236
237 // Step 2 : release global lock
238 /*paranoid*/ assert(true == write_lock);
239 __atomic_store_n(&write_lock, (bool)false, __ATOMIC_RELEASE);
240
241 /* paranoid */ verify( ! __preemption_enabled() );
242}
243
244//=======================================================================
245// Cforall Ready Queue used for scheduling
246//=======================================================================
247void ?{}(__ready_queue_t & this) with (this) {
248 #if defined(USE_CPU_WORK_STEALING)
249 lanes.count = cpu_info.hthrd_count * READYQ_SHARD_FACTOR;
250 lanes.data = alloc( lanes.count );
251 lanes.tscs = alloc( lanes.count );
252
253 for( idx; (size_t)lanes.count ) {
254 (lanes.data[idx]){};
255 lanes.tscs[idx].tv = rdtscl();
256 }
257 #else
258 lanes.data = 0p;
259 lanes.tscs = 0p;
260 lanes.count = 0;
261 #endif
262}
263
264void ^?{}(__ready_queue_t & this) with (this) {
265 #if !defined(USE_CPU_WORK_STEALING)
266 verify( SEQUENTIAL_SHARD == lanes.count );
267 #endif
268
269 free(lanes.data);
270 free(lanes.tscs);
271}
272
273//-----------------------------------------------------------------------
274#if defined(USE_CPU_WORK_STEALING)
275 __attribute__((hot)) void push(struct cluster * cltr, struct $thread * thrd, bool push_local) with (cltr->ready_queue) {
276 __cfadbg_print_safe(ready_queue, "Kernel : Pushing %p on cluster %p\n", thrd, cltr);
277
278 processor * const proc = kernelTLS().this_processor;
279 const bool external = !push_local || (!proc) || (cltr != proc->cltr);
280
281 const int cpu = __kernel_getcpu();
282 /* paranoid */ verify(cpu >= 0);
283 /* paranoid */ verify(cpu < cpu_info.hthrd_count);
284 /* paranoid */ verify(cpu * READYQ_SHARD_FACTOR < lanes.count);
285
286 const cpu_map_entry_t & map = cpu_info.llc_map[cpu];
287 /* paranoid */ verify(map.start * READYQ_SHARD_FACTOR < lanes.count);
288 /* paranoid */ verify(map.self * READYQ_SHARD_FACTOR < lanes.count);
289 /* paranoid */ verifyf((map.start + map.count) * READYQ_SHARD_FACTOR <= lanes.count, "have %u lanes but map can go up to %u", lanes.count, (map.start + map.count) * READYQ_SHARD_FACTOR);
290
291 const int start = map.self * READYQ_SHARD_FACTOR;
292 unsigned i;
293 do {
294 unsigned r;
295 if(unlikely(external)) { r = __tls_rand(); }
296 else { r = proc->rdq.its++; }
297 i = start + (r % READYQ_SHARD_FACTOR);
298 // If we can't lock it retry
299 } while( !__atomic_try_acquire( &lanes.data[i].lock ) );
300
301 // Actually push it
302 push(lanes.data[i], thrd);
303
304 // Unlock and return
305 __atomic_unlock( &lanes.data[i].lock );
306
307 #if !defined(__CFA_NO_STATISTICS__)
308 if(unlikely(external)) __atomic_fetch_add(&cltr->stats->ready.push.extrn.success, 1, __ATOMIC_RELAXED);
309 else __tls_stats()->ready.push.local.success++;
310 #endif
311
312 __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);
313
314 }
315
316 // Pop from the ready queue from a given cluster
317 __attribute__((hot)) $thread * pop_fast(struct cluster * cltr) with (cltr->ready_queue) {
318 /* paranoid */ verify( lanes.count > 0 );
319 /* paranoid */ verify( kernelTLS().this_processor );
320
321 const int cpu = __kernel_getcpu();
322 /* paranoid */ verify(cpu >= 0);
323 /* paranoid */ verify(cpu < cpu_info.hthrd_count);
324 /* paranoid */ verify(cpu * READYQ_SHARD_FACTOR < lanes.count);
325
326 const cpu_map_entry_t & map = cpu_info.llc_map[cpu];
327 /* paranoid */ verify(map.start * READYQ_SHARD_FACTOR < lanes.count);
328 /* paranoid */ verify(map.self * READYQ_SHARD_FACTOR < lanes.count);
329 /* paranoid */ verifyf((map.start + map.count) * READYQ_SHARD_FACTOR <= lanes.count, "have %u lanes but map can go up to %u", lanes.count, (map.start + map.count) * READYQ_SHARD_FACTOR);
330
331 processor * const proc = kernelTLS().this_processor;
332 const int start = map.self * READYQ_SHARD_FACTOR;
333
334 // Did we already have a help target
335 if(proc->rdq.target == -1u) {
336 // if We don't have a
337 unsigned long long min = ts(lanes.data[start]);
338 for(i; READYQ_SHARD_FACTOR) {
339 unsigned long long tsc = ts(lanes.data[start + i]);
340 if(tsc < min) min = tsc;
341 }
342 proc->rdq.cutoff = min;
343 proc->rdq.target = (map.start * READYQ_SHARD_FACTOR) + (__tls_rand() % (map.count* READYQ_SHARD_FACTOR));
344 }
345 else {
346 const unsigned long long bias = 0; //2_500_000_000;
347 const unsigned long long cutoff = proc->rdq.cutoff > bias ? proc->rdq.cutoff - bias : proc->rdq.cutoff;
348 {
349 unsigned target = proc->rdq.target;
350 proc->rdq.target = -1u;
351 if(lanes.tscs[target].tv < cutoff && ts(lanes.data[target]) < cutoff) {
352 $thread * t = try_pop(cltr, target __STATS(, __tls_stats()->ready.pop.help));
353 proc->rdq.last = target;
354 if(t) return t;
355 }
356 }
357
358 unsigned last = proc->rdq.last;
359 if(last != -1u && lanes.tscs[last].tv < cutoff && ts(lanes.data[last]) < cutoff) {
360 $thread * t = try_pop(cltr, last __STATS(, __tls_stats()->ready.pop.help));
361 if(t) return t;
362 }
363 else {
364 proc->rdq.last = -1u;
365 }
366 }
367
368 for(READYQ_SHARD_FACTOR) {
369 unsigned i = start + (proc->rdq.itr++ % READYQ_SHARD_FACTOR);
370 if($thread * t = try_pop(cltr, i __STATS(, __tls_stats()->ready.pop.local))) return t;
371 }
372
373 // All lanes where empty return 0p
374 return 0p;
375 }
376
377 __attribute__((hot)) struct $thread * pop_slow(struct cluster * cltr) with (cltr->ready_queue) {
378 processor * const proc = kernelTLS().this_processor;
379 unsigned last = proc->rdq.last;
380
381 unsigned i = __tls_rand() % lanes.count;
382 return try_pop(cltr, i __STATS(, __tls_stats()->ready.pop.steal));
383 }
384 __attribute__((hot)) struct $thread * pop_search(struct cluster * cltr) {
385 return search(cltr);
386 }
387#endif
388#if defined(USE_RELAXED_FIFO)
389 //-----------------------------------------------------------------------
390 // get index from random number with or without bias towards queues
391 static inline [unsigned, bool] idx_from_r(unsigned r, unsigned preferred) {
392 unsigned i;
393 bool local;
394 unsigned rlow = r % BIAS;
395 unsigned rhigh = r / BIAS;
396 if((0 != rlow) && preferred >= 0) {
397 // (BIAS - 1) out of BIAS chances
398 // Use perferred queues
399 i = preferred + (rhigh % READYQ_SHARD_FACTOR);
400 local = true;
401 }
402 else {
403 // 1 out of BIAS chances
404 // Use all queues
405 i = rhigh;
406 local = false;
407 }
408 return [i, local];
409 }
410
411 __attribute__((hot)) void push(struct cluster * cltr, struct $thread * thrd, bool push_local) with (cltr->ready_queue) {
412 __cfadbg_print_safe(ready_queue, "Kernel : Pushing %p on cluster %p\n", thrd, cltr);
413
414 const bool external = !push_local || (!kernelTLS().this_processor) || (cltr != kernelTLS().this_processor->cltr);
415 /* paranoid */ verify(external || kernelTLS().this_processor->rdq.id < lanes.count );
416
417 bool local;
418 int preferred = external ? -1 : kernelTLS().this_processor->rdq.id;
419
420 // Try to pick a lane and lock it
421 unsigned i;
422 do {
423 // Pick the index of a lane
424 unsigned r = __tls_rand_fwd();
425 [i, local] = idx_from_r(r, preferred);
426
427 i %= __atomic_load_n( &lanes.count, __ATOMIC_RELAXED );
428
429 #if !defined(__CFA_NO_STATISTICS__)
430 if(unlikely(external)) __atomic_fetch_add(&cltr->stats->ready.push.extrn.attempt, 1, __ATOMIC_RELAXED);
431 else if(local) __tls_stats()->ready.push.local.attempt++;
432 else __tls_stats()->ready.push.share.attempt++;
433 #endif
434
435 // If we can't lock it retry
436 } while( !__atomic_try_acquire( &lanes.data[i].lock ) );
437
438 // Actually push it
439 push(lanes.data[i], thrd);
440
441 // Unlock and return
442 __atomic_unlock( &lanes.data[i].lock );
443
444 // Mark the current index in the tls rng instance as having an item
445 __tls_rand_advance_bck();
446
447 __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);
448
449 // Update statistics
450 #if !defined(__CFA_NO_STATISTICS__)
451 if(unlikely(external)) __atomic_fetch_add(&cltr->stats->ready.push.extrn.success, 1, __ATOMIC_RELAXED);
452 else if(local) __tls_stats()->ready.push.local.success++;
453 else __tls_stats()->ready.push.share.success++;
454 #endif
455 }
456
457 // Pop from the ready queue from a given cluster
458 __attribute__((hot)) $thread * pop_fast(struct cluster * cltr) with (cltr->ready_queue) {
459 /* paranoid */ verify( lanes.count > 0 );
460 /* paranoid */ verify( kernelTLS().this_processor );
461 /* paranoid */ verify( kernelTLS().this_processor->rdq.id < lanes.count );
462
463 unsigned count = __atomic_load_n( &lanes.count, __ATOMIC_RELAXED );
464 int preferred = kernelTLS().this_processor->rdq.id;
465
466
467 // As long as the list is not empty, try finding a lane that isn't empty and pop from it
468 for(25) {
469 // Pick two lists at random
470 unsigned ri = __tls_rand_bck();
471 unsigned rj = __tls_rand_bck();
472
473 unsigned i, j;
474 __attribute__((unused)) bool locali, localj;
475 [i, locali] = idx_from_r(ri, preferred);
476 [j, localj] = idx_from_r(rj, preferred);
477
478 i %= count;
479 j %= count;
480
481 // try popping from the 2 picked lists
482 struct $thread * thrd = try_pop(cltr, i, j __STATS(, *(locali || localj ? &__tls_stats()->ready.pop.local : &__tls_stats()->ready.pop.help)));
483 if(thrd) {
484 return thrd;
485 }
486 }
487
488 // All lanes where empty return 0p
489 return 0p;
490 }
491
492 __attribute__((hot)) struct $thread * pop_slow(struct cluster * cltr) { return pop_fast(cltr); }
493 __attribute__((hot)) struct $thread * pop_search(struct cluster * cltr) {
494 return search(cltr);
495 }
496#endif
497#if defined(USE_WORK_STEALING)
498 __attribute__((hot)) void push(struct cluster * cltr, struct $thread * thrd, bool push_local) with (cltr->ready_queue) {
499 __cfadbg_print_safe(ready_queue, "Kernel : Pushing %p on cluster %p\n", thrd, cltr);
500
501 // #define USE_PREFERRED
502 #if !defined(USE_PREFERRED)
503 const bool external = !push_local || (!kernelTLS().this_processor) || (cltr != kernelTLS().this_processor->cltr);
504 /* paranoid */ verify(external || kernelTLS().this_processor->rdq.id < lanes.count );
505 #else
506 unsigned preferred = thrd->preferred;
507 const bool external = push_local || (!kernelTLS().this_processor) || preferred == -1u || thrd->curr_cluster != cltr;
508 /* paranoid */ verifyf(external || preferred < lanes.count, "Invalid preferred queue %u for %u lanes", preferred, lanes.count );
509
510 unsigned r = preferred % READYQ_SHARD_FACTOR;
511 const unsigned start = preferred - r;
512 #endif
513
514 // Try to pick a lane and lock it
515 unsigned i;
516 do {
517 #if !defined(__CFA_NO_STATISTICS__)
518 if(unlikely(external)) __atomic_fetch_add(&cltr->stats->ready.push.extrn.attempt, 1, __ATOMIC_RELAXED);
519 else __tls_stats()->ready.push.local.attempt++;
520 #endif
521
522 if(unlikely(external)) {
523 i = __tls_rand() % lanes.count;
524 }
525 else {
526 #if !defined(USE_PREFERRED)
527 processor * proc = kernelTLS().this_processor;
528 unsigned r = proc->rdq.its++;
529 i = proc->rdq.id + (r % READYQ_SHARD_FACTOR);
530 #else
531 i = start + (r++ % READYQ_SHARD_FACTOR);
532 #endif
533 }
534 // If we can't lock it retry
535 } while( !__atomic_try_acquire( &lanes.data[i].lock ) );
536
537 // Actually push it
538 push(lanes.data[i], thrd);
539
540 // Unlock and return
541 __atomic_unlock( &lanes.data[i].lock );
542
543 #if !defined(__CFA_NO_STATISTICS__)
544 if(unlikely(external)) __atomic_fetch_add(&cltr->stats->ready.push.extrn.success, 1, __ATOMIC_RELAXED);
545 else __tls_stats()->ready.push.local.success++;
546 #endif
547
548 __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);
549 }
550
551 // Pop from the ready queue from a given cluster
552 __attribute__((hot)) $thread * pop_fast(struct cluster * cltr) with (cltr->ready_queue) {
553 /* paranoid */ verify( lanes.count > 0 );
554 /* paranoid */ verify( kernelTLS().this_processor );
555 /* paranoid */ verify( kernelTLS().this_processor->rdq.id < lanes.count );
556
557 processor * proc = kernelTLS().this_processor;
558
559 if(proc->rdq.target == -1u) {
560 unsigned long long min = ts(lanes.data[proc->rdq.id]);
561 for(int i = 0; i < READYQ_SHARD_FACTOR; i++) {
562 unsigned long long tsc = ts(lanes.data[proc->rdq.id + i]);
563 if(tsc < min) min = tsc;
564 }
565 proc->rdq.cutoff = min;
566 proc->rdq.target = __tls_rand() % lanes.count;
567 }
568 else {
569 unsigned target = proc->rdq.target;
570 proc->rdq.target = -1u;
571 const unsigned long long bias = 0; //2_500_000_000;
572 const unsigned long long cutoff = proc->rdq.cutoff > bias ? proc->rdq.cutoff - bias : proc->rdq.cutoff;
573 if(lanes.tscs[target].tv < cutoff && ts(lanes.data[target]) < cutoff) {
574 $thread * t = try_pop(cltr, target __STATS(, __tls_stats()->ready.pop.help));
575 if(t) return t;
576 }
577 }
578
579 for(READYQ_SHARD_FACTOR) {
580 unsigned i = proc->rdq.id + (proc->rdq.itr++ % READYQ_SHARD_FACTOR);
581 if($thread * t = try_pop(cltr, i __STATS(, __tls_stats()->ready.pop.local))) return t;
582 }
583 return 0p;
584 }
585
586 __attribute__((hot)) struct $thread * pop_slow(struct cluster * cltr) with (cltr->ready_queue) {
587 unsigned i = __tls_rand() % lanes.count;
588 return try_pop(cltr, i __STATS(, __tls_stats()->ready.pop.steal));
589 }
590
591 __attribute__((hot)) struct $thread * pop_search(struct cluster * cltr) with (cltr->ready_queue) {
592 return search(cltr);
593 }
594#endif
595
596//=======================================================================
597// Various Ready Queue utilities
598//=======================================================================
599// these function work the same or almost the same
600// whether they are using work-stealing or relaxed fifo scheduling
601
602//-----------------------------------------------------------------------
603// try to pop from a lane given by index w
604static inline struct $thread * try_pop(struct cluster * cltr, unsigned w __STATS(, __stats_readyQ_pop_t & stats)) with (cltr->ready_queue) {
605 __STATS( stats.attempt++; )
606
607 // Get relevant elements locally
608 __intrusive_lane_t & lane = lanes.data[w];
609
610 // If list looks empty retry
611 if( is_empty(lane) ) {
612 return 0p;
613 }
614
615 // If we can't get the lock retry
616 if( !__atomic_try_acquire(&lane.lock) ) {
617 return 0p;
618 }
619
620 // If list is empty, unlock and retry
621 if( is_empty(lane) ) {
622 __atomic_unlock(&lane.lock);
623 return 0p;
624 }
625
626 // Actually pop the list
627 struct $thread * thrd;
628 unsigned long long tsv;
629 [thrd, tsv] = pop(lane);
630
631 /* paranoid */ verify(thrd);
632 /* paranoid */ verify(tsv);
633 /* paranoid */ verify(lane.lock);
634
635 // Unlock and return
636 __atomic_unlock(&lane.lock);
637
638 // Update statistics
639 __STATS( stats.success++; )
640
641 #if defined(USE_WORK_STEALING)
642 lanes.tscs[w].tv = tsv;
643 #endif
644
645 thrd->preferred = w;
646
647 // return the popped thread
648 return thrd;
649}
650
651//-----------------------------------------------------------------------
652// try to pop from any lanes making sure you don't miss any threads push
653// before the start of the function
654static inline struct $thread * search(struct cluster * cltr) with (cltr->ready_queue) {
655 /* paranoid */ verify( lanes.count > 0 );
656 unsigned count = __atomic_load_n( &lanes.count, __ATOMIC_RELAXED );
657 unsigned offset = __tls_rand();
658 for(i; count) {
659 unsigned idx = (offset + i) % count;
660 struct $thread * thrd = try_pop(cltr, idx __STATS(, __tls_stats()->ready.pop.search));
661 if(thrd) {
662 return thrd;
663 }
664 }
665
666 // All lanes where empty return 0p
667 return 0p;
668}
669
670//-----------------------------------------------------------------------
671// Check that all the intrusive queues in the data structure are still consistent
672static void check( __ready_queue_t & q ) with (q) {
673 #if defined(__CFA_WITH_VERIFY__)
674 {
675 for( idx ; lanes.count ) {
676 __intrusive_lane_t & sl = lanes.data[idx];
677 assert(!lanes.data[idx].lock);
678
679 if(is_empty(sl)) {
680 assert( sl.anchor.next == 0p );
681 assert( sl.anchor.ts == -1llu );
682 assert( mock_head(sl) == sl.prev );
683 } else {
684 assert( sl.anchor.next != 0p );
685 assert( sl.anchor.ts != -1llu );
686 assert( mock_head(sl) != sl.prev );
687 }
688 }
689 }
690 #endif
691}
692
693//-----------------------------------------------------------------------
694// Given 2 indexes, pick the list with the oldest push an try to pop from it
695static inline struct $thread * try_pop(struct cluster * cltr, unsigned i, unsigned j __STATS(, __stats_readyQ_pop_t & stats)) with (cltr->ready_queue) {
696 // Pick the bet list
697 int w = i;
698 if( __builtin_expect(!is_empty(lanes.data[j]), true) ) {
699 w = (ts(lanes.data[i]) < ts(lanes.data[j])) ? i : j;
700 }
701
702 return try_pop(cltr, w __STATS(, stats));
703}
704
705// Call this function of the intrusive list was moved using memcpy
706// fixes the list so that the pointers back to anchors aren't left dangling
707static inline void fix(__intrusive_lane_t & ll) {
708 if(is_empty(ll)) {
709 verify(ll.anchor.next == 0p);
710 ll.prev = mock_head(ll);
711 }
712}
713
714static void assign_list(unsigned & value, dlist(processor) & list, unsigned count) {
715 processor * it = &list`first;
716 for(unsigned i = 0; i < count; i++) {
717 /* paranoid */ verifyf( it, "Unexpected null iterator, at index %u of %u\n", i, count);
718 it->rdq.id = value;
719 it->rdq.target = -1u;
720 value += READYQ_SHARD_FACTOR;
721 it = &(*it)`next;
722 }
723}
724
725static void reassign_cltr_id(struct cluster * cltr) {
726 unsigned preferred = 0;
727 assign_list(preferred, cltr->procs.actives, cltr->procs.total - cltr->procs.idle);
728 assign_list(preferred, cltr->procs.idles , cltr->procs.idle );
729}
730
731static void fix_times( struct cluster * cltr ) with( cltr->ready_queue ) {
732 #if defined(USE_WORK_STEALING)
733 lanes.tscs = alloc(lanes.count, lanes.tscs`realloc);
734 for(i; lanes.count) {
735 unsigned long long tsc1 = ts(lanes.data[i]);
736 unsigned long long tsc2 = rdtscl()
737 lanes.tscs[i].tv = min(tsc1, tsc2);
738 }
739 #endif
740}
741
742#if defined(USE_CPU_WORK_STEALING)
743 // ready_queue size is fixed in this case
744 void ready_queue_grow(struct cluster * cltr) {}
745 void ready_queue_shrink(struct cluster * cltr) {}
746#else
747 // Grow the ready queue
748 void ready_queue_grow(struct cluster * cltr) {
749 size_t ncount;
750 int target = cltr->procs.total;
751
752 /* paranoid */ verify( ready_mutate_islocked() );
753 __cfadbg_print_safe(ready_queue, "Kernel : Growing ready queue\n");
754
755 // Make sure that everything is consistent
756 /* paranoid */ check( cltr->ready_queue );
757
758 // grow the ready queue
759 with( cltr->ready_queue ) {
760 // Find new count
761 // Make sure we always have atleast 1 list
762 if(target >= 2) {
763 ncount = target * READYQ_SHARD_FACTOR;
764 } else {
765 ncount = SEQUENTIAL_SHARD;
766 }
767
768 // Allocate new array (uses realloc and memcpies the data)
769 lanes.data = alloc( ncount, lanes.data`realloc );
770
771 // Fix the moved data
772 for( idx; (size_t)lanes.count ) {
773 fix(lanes.data[idx]);
774 }
775
776 // Construct new data
777 for( idx; (size_t)lanes.count ~ ncount) {
778 (lanes.data[idx]){};
779 }
780
781 // Update original
782 lanes.count = ncount;
783 }
784
785 fix_times(cltr);
786
787 reassign_cltr_id(cltr);
788
789 // Make sure that everything is consistent
790 /* paranoid */ check( cltr->ready_queue );
791
792 __cfadbg_print_safe(ready_queue, "Kernel : Growing ready queue done\n");
793
794 /* paranoid */ verify( ready_mutate_islocked() );
795 }
796
797 // Shrink the ready queue
798 void ready_queue_shrink(struct cluster * cltr) {
799 /* paranoid */ verify( ready_mutate_islocked() );
800 __cfadbg_print_safe(ready_queue, "Kernel : Shrinking ready queue\n");
801
802 // Make sure that everything is consistent
803 /* paranoid */ check( cltr->ready_queue );
804
805 int target = cltr->procs.total;
806
807 with( cltr->ready_queue ) {
808 // Remember old count
809 size_t ocount = lanes.count;
810
811 // Find new count
812 // Make sure we always have atleast 1 list
813 lanes.count = target >= 2 ? target * READYQ_SHARD_FACTOR: SEQUENTIAL_SHARD;
814 /* paranoid */ verify( ocount >= lanes.count );
815 /* paranoid */ verify( lanes.count == target * READYQ_SHARD_FACTOR || target < 2 );
816
817 // for printing count the number of displaced threads
818 #if defined(__CFA_DEBUG_PRINT__) || defined(__CFA_DEBUG_PRINT_READY_QUEUE__)
819 __attribute__((unused)) size_t displaced = 0;
820 #endif
821
822 // redistribute old data
823 for( idx; (size_t)lanes.count ~ ocount) {
824 // Lock is not strictly needed but makes checking invariants much easier
825 __attribute__((unused)) bool locked = __atomic_try_acquire(&lanes.data[idx].lock);
826 verify(locked);
827
828 // As long as we can pop from this lane to push the threads somewhere else in the queue
829 while(!is_empty(lanes.data[idx])) {
830 struct $thread * thrd;
831 unsigned long long _;
832 [thrd, _] = pop(lanes.data[idx]);
833
834 push(cltr, thrd, true);
835
836 // for printing count the number of displaced threads
837 #if defined(__CFA_DEBUG_PRINT__) || defined(__CFA_DEBUG_PRINT_READY_QUEUE__)
838 displaced++;
839 #endif
840 }
841
842 // Unlock the lane
843 __atomic_unlock(&lanes.data[idx].lock);
844
845 // TODO print the queue statistics here
846
847 ^(lanes.data[idx]){};
848 }
849
850 __cfadbg_print_safe(ready_queue, "Kernel : Shrinking ready queue displaced %zu threads\n", displaced);
851
852 // Allocate new array (uses realloc and memcpies the data)
853 lanes.data = alloc( lanes.count, lanes.data`realloc );
854
855 // Fix the moved data
856 for( idx; (size_t)lanes.count ) {
857 fix(lanes.data[idx]);
858 }
859 }
860
861 fix_times(cltr);
862
863 reassign_cltr_id(cltr);
864
865 // Make sure that everything is consistent
866 /* paranoid */ check( cltr->ready_queue );
867
868 __cfadbg_print_safe(ready_queue, "Kernel : Shrinking ready queue done\n");
869 /* paranoid */ verify( ready_mutate_islocked() );
870 }
871#endif
872
873#if !defined(__CFA_NO_STATISTICS__)
874 unsigned cnt(const __ready_queue_t & this, unsigned idx) {
875 /* paranoid */ verify(this.lanes.count > idx);
876 return this.lanes.data[idx].cnt;
877 }
878#endif
879
880
881#if defined(CFA_HAVE_LINUX_LIBRSEQ)
882 // No definition needed
883#elif defined(CFA_HAVE_LINUX_RSEQ_H)
884
885 #if defined( __x86_64 ) || defined( __i386 )
886 #define RSEQ_SIG 0x53053053
887 #elif defined( __ARM_ARCH )
888 #ifdef __ARMEB__
889 #define RSEQ_SIG 0xf3def5e7 /* udf #24035 ; 0x5de3 (ARMv6+) */
890 #else
891 #define RSEQ_SIG 0xe7f5def3 /* udf #24035 ; 0x5de3 */
892 #endif
893 #endif
894
895 extern void __disable_interrupts_hard();
896 extern void __enable_interrupts_hard();
897
898 void __kernel_raw_rseq_register (void) {
899 /* paranoid */ verify( __cfaabi_rseq.cpu_id == RSEQ_CPU_ID_UNINITIALIZED );
900
901 // int ret = syscall(__NR_rseq, &__cfaabi_rseq, sizeof(struct rseq), 0, (sigset_t *)0p, _NSIG / 8);
902 int ret = syscall(__NR_rseq, &__cfaabi_rseq, sizeof(struct rseq), 0, RSEQ_SIG);
903 if(ret != 0) {
904 int e = errno;
905 switch(e) {
906 case EINVAL: abort("KERNEL ERROR: rseq register invalid argument");
907 case ENOSYS: abort("KERNEL ERROR: rseq register no supported");
908 case EFAULT: abort("KERNEL ERROR: rseq register with invalid argument");
909 case EBUSY : abort("KERNEL ERROR: rseq register already registered");
910 case EPERM : abort("KERNEL ERROR: rseq register sig argument on unregistration does not match the signature received on registration");
911 default: abort("KERNEL ERROR: rseq register unexpected return %d", e);
912 }
913 }
914 }
915
916 void __kernel_raw_rseq_unregister(void) {
917 /* paranoid */ verify( __cfaabi_rseq.cpu_id >= 0 );
918
919 // int ret = syscall(__NR_rseq, &__cfaabi_rseq, sizeof(struct rseq), RSEQ_FLAG_UNREGISTER, (sigset_t *)0p, _NSIG / 8);
920 int ret = syscall(__NR_rseq, &__cfaabi_rseq, sizeof(struct rseq), RSEQ_FLAG_UNREGISTER, RSEQ_SIG);
921 if(ret != 0) {
922 int e = errno;
923 switch(e) {
924 case EINVAL: abort("KERNEL ERROR: rseq unregister invalid argument");
925 case ENOSYS: abort("KERNEL ERROR: rseq unregister no supported");
926 case EFAULT: abort("KERNEL ERROR: rseq unregister with invalid argument");
927 case EBUSY : abort("KERNEL ERROR: rseq unregister already registered");
928 case EPERM : abort("KERNEL ERROR: rseq unregister sig argument on unregistration does not match the signature received on registration");
929 default: abort("KERNEL ERROR: rseq unregisteunexpected return %d", e);
930 }
931 }
932 }
933#else
934 // No definition needed
935#endif
Note: See TracBrowser for help on using the repository browser.