source: libcfa/src/concurrency/kernel/private.hfa @ 8b74fa7

ADTast-experimental
Last change on this file since 8b74fa7 was df6cc9d, checked in by Thierry Delisle <tdelisle@…>, 2 years ago

Merge branch 'master' into pthread-emulation

  • Property mode set to 100644
File size: 14.2 KB
Line 
1//
2// Cforall Version 1.0.0 Copyright (C) 2016 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// kernel/private.hfa --
8//
9// Author           : Thierry Delisle
10// Created On       : Mon Feb 13 12:27:26 2017
11// Last Modified By : Peter A. Buhr
12// Last Modified On : Wed Aug 12 08:21:33 2020
13// Update Count     : 9
14//
15
16#pragma once
17
18#if !defined(__cforall_thread__)
19        #error kernel/private.hfa should only be included in libcfathread source
20#endif
21
22#include <signal.h>
23
24#include "kernel.hfa"
25#include "thread.hfa"
26
27#include "alarm.hfa"
28#include "stats.hfa"
29
30extern "C" {
31#if   defined(CFA_HAVE_LINUX_LIBRSEQ)
32        #include <rseq/rseq.h>
33#elif defined(CFA_HAVE_LINUX_RSEQ_H)
34        #include <linux/rseq.h>
35#else
36        #ifndef _GNU_SOURCE
37        #error kernel/private requires gnu_source
38        #endif
39        #include <sched.h>
40#endif
41}
42
43// Defines whether or not we *want* to use io_uring_enter as the idle_sleep blocking call
44// #define CFA_WANT_IO_URING_IDLE
45
46// Defines whether or not we *can* use io_uring_enter as the idle_sleep blocking call
47#if defined(CFA_WANT_IO_URING_IDLE) && defined(CFA_HAVE_LINUX_IO_URING_H)
48        #if defined(CFA_HAVE_IORING_OP_READ) || (defined(CFA_HAVE_READV) && defined(CFA_HAVE_IORING_OP_READV))
49                #define CFA_WITH_IO_URING_IDLE
50        #endif
51#endif
52// #define READYQ_USE_LINEAR_AVG
53#define READYQ_USE_LOGDBL_AVG
54// #define READYQ_USE_LOGINT_AVG
55
56#if   defined(READYQ_USE_LINEAR_AVG)
57typedef unsigned long long __readyQ_avg_t;
58#elif defined(READYQ_USE_LOGDBL_AVG)
59typedef double __readyQ_avg_t;
60#elif defined(READYQ_USE_LOGDBL_AVG)
61typedef unsigned long long __readyQ_avg_t;
62#else
63#error must pick a scheme for averaging
64#endif
65
66extern "C" {
67        __attribute__((visibility("protected"))) int __cfaabi_pthread_create(pthread_t *_thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg);
68        __attribute__((visibility("protected"))) int __cfaabi_pthread_join(pthread_t _thread, void **retval);
69        __attribute__((visibility("protected"))) pthread_t __cfaabi_pthread_self(void);
70        __attribute__((visibility("protected"))) int __cfaabi_pthread_attr_init(pthread_attr_t *attr);
71        __attribute__((visibility("protected"))) int __cfaabi_pthread_attr_destroy(pthread_attr_t *attr);
72        __attribute__((visibility("protected"))) int __cfaabi_pthread_attr_setstack( pthread_attr_t *attr, void *stackaddr, size_t stacksize );
73        __attribute__((visibility("protected"))) int __cfaabi_pthread_attr_getstacksize( const pthread_attr_t *attr, size_t *stacksize );
74        __attribute__((visibility("protected"))) int __cfaabi_pthread_sigqueue(pthread_t _thread, int sig, const union sigval value);
75        __attribute__((visibility("protected"))) int __cfaabi_pthread_sigmask( int how, const sigset_t *set, sigset_t *oset);
76}
77
78//-----------------------------------------------------------------------------
79// Scheduler
80union __attribute__((aligned(64))) __timestamp_t {
81        struct {
82                volatile unsigned long long tv;
83                volatile __readyQ_avg_t ma;
84        } t;
85        char __padding[192];
86};
87
88extern "C" {
89        void disable_interrupts() OPTIONAL_THREAD;
90        void enable_interrupts( bool poll = true );
91}
92
93void schedule_thread$( thread$ *, unpark_hint hint ) __attribute__((nonnull (1)));
94
95extern bool __preemption_enabled();
96
97enum {
98        PREEMPT_NORMAL    = 0,
99        PREEMPT_TERMINATE = 1,
100        PREEMPT_IO = 2,
101};
102
103static inline void __disable_interrupts_checked() {
104        /* paranoid */ verify( __preemption_enabled() );
105        disable_interrupts();
106        /* paranoid */ verify( ! __preemption_enabled() );
107}
108
109static inline void __enable_interrupts_checked( bool poll = true ) {
110        /* paranoid */ verify( ! __preemption_enabled() );
111        enable_interrupts( poll );
112        /* paranoid */ verify( __preemption_enabled() );
113}
114
115//release/wake-up the following resources
116void __thread_finish( thread$ * thrd );
117
118//-----------------------------------------------------------------------------
119// Hardware
120
121#if   defined(CFA_HAVE_LINUX_LIBRSEQ)
122        // No data needed
123#elif defined(CFA_HAVE_LINUX_RSEQ_H)
124        extern "Cforall" {
125                extern __attribute__((aligned(64))) __thread volatile struct rseq __cfaabi_rseq;
126        }
127#else
128        // No data needed
129#endif
130
131static inline int __kernel_getcpu() {
132        /* paranoid */ verify( ! __preemption_enabled() );
133#if   defined(CFA_HAVE_LINUX_LIBRSEQ)
134        return rseq_current_cpu();
135#elif defined(CFA_HAVE_LINUX_RSEQ_H)
136        int r = __cfaabi_rseq.cpu_id;
137        /* paranoid */ verify( r >= 0 );
138        return r;
139#else
140        return sched_getcpu();
141#endif
142}
143
144//-----------------------------------------------------------------------------
145// Processor
146void main(processorCtx_t &);
147static inline coroutine$* get_coroutine(processorCtx_t & this) { return &this.self; }
148
149void * __create_pthread( pthread_t *, void * (*)(void *), void * );
150void __destroy_pthread( pthread_t pthread, void * stack, void ** retval );
151
152extern cluster * mainCluster;
153
154//-----------------------------------------------------------------------------
155// Threads
156extern "C" {
157      void __cfactx_invoke_thread(void (*main)(void *), void * this);
158}
159
160__cfaabi_dbg_debug_do(
161        extern void __cfaabi_dbg_thread_register  ( thread$ * thrd );
162        extern void __cfaabi_dbg_thread_unregister( thread$ * thrd );
163)
164
165#define TICKET_BLOCKED (-1) // thread is blocked
166#define TICKET_RUNNING ( 0) // thread is running
167#define TICKET_UNBLOCK ( 1) // thread should ignore next block
168
169//-----------------------------------------------------------------------------
170// Utils
171void doregister( struct cluster * cltr, struct thread$ & thrd );
172void unregister( struct cluster * cltr, struct thread$ & thrd );
173
174//-----------------------------------------------------------------------------
175// I/O
176io_arbiter$ * create(void);
177void destroy(io_arbiter$ *);
178
179//=======================================================================
180// Cluster lock API
181//=======================================================================
182// Lock-Free registering/unregistering of threads
183// Register a processor to a given cluster and get its unique id in return
184unsigned register_proc_id( void );
185
186// Unregister a processor from a given cluster using its id, getting back the original pointer
187void unregister_proc_id( unsigned );
188
189//=======================================================================
190// Reader-writer lock implementation
191// Concurrent with doregister/unregister,
192//    i.e., threads can be added at any point during or between the entry/exit
193
194//-----------------------------------------------------------------------
195// simple spinlock underlying the RWLock
196// Blocking acquire
197static inline void __atomic_acquire(volatile bool * ll) {
198        /* paranoid */ verify( ! __preemption_enabled() );
199        /* paranoid */ verify(ll);
200
201        while( __builtin_expect(__atomic_exchange_n(ll, (bool)true, __ATOMIC_SEQ_CST), false) ) {
202                while(__atomic_load_n(ll, (int)__ATOMIC_RELAXED))
203                        Pause();
204        }
205        /* paranoid */ verify(*ll);
206        /* paranoid */ verify( ! __preemption_enabled() );
207}
208
209// Non-Blocking acquire
210static inline bool __atomic_try_acquire(volatile bool * ll) {
211        /* paranoid */ verify( ! __preemption_enabled() );
212        /* paranoid */ verify(ll);
213
214        return !__atomic_exchange_n(ll, (bool)true, __ATOMIC_SEQ_CST);
215}
216
217// Release
218static inline void __atomic_unlock(volatile bool * ll) {
219        /* paranoid */ verify( ! __preemption_enabled() );
220        /* paranoid */ verify(ll);
221        /* paranoid */ verify(*ll);
222        __atomic_store_n(ll, (bool)false, __ATOMIC_RELEASE);
223}
224
225//-----------------------------------------------------------------------
226// Reader-Writer lock protecting the ready-queues
227// while this lock is mostly generic some aspects
228// have been hard-coded to for the ready-queue for
229// simplicity and performance
230union __attribute__((aligned(64))) __scheduler_RWLock_t {
231        struct {
232                __attribute__((aligned(64))) char padding;
233
234                // total cachelines allocated
235                __attribute__((aligned(64))) unsigned int max;
236
237                // cachelines currently in use
238                volatile unsigned int alloc;
239
240                // cachelines ready to itereate over
241                // (!= to alloc when thread is in second half of doregister)
242                volatile unsigned int ready;
243
244                // writer lock
245                volatile bool write_lock;
246
247                // data pointer
248                volatile bool * volatile * data;
249        } lock;
250        char pad[192];
251};
252
253void  ?{}(__scheduler_RWLock_t & this);
254void ^?{}(__scheduler_RWLock_t & this);
255
256extern __scheduler_RWLock_t __scheduler_lock;
257
258//-----------------------------------------------------------------------
259// Reader side : acquire when using the ready queue to schedule but not
260//  creating/destroying queues
261static inline void ready_schedule_lock(void) with(__scheduler_lock.lock) {
262        /* paranoid */ verify( ! __preemption_enabled() );
263        /* paranoid */ verify( ! kernelTLS().in_sched_lock );
264        /* paranoid */ verify( data[kernelTLS().sched_id] == &kernelTLS().sched_lock );
265        /* paranoid */ verify( !kernelTLS().this_processor || kernelTLS().this_processor->unique_id == kernelTLS().sched_id );
266
267        // Step 1 : make sure no writer are in the middle of the critical section
268        while(__atomic_load_n(&write_lock, (int)__ATOMIC_RELAXED))
269                Pause();
270
271        // Fence needed because we don't want to start trying to acquire the lock
272        // before we read a false.
273        // Not needed on x86
274        // std::atomic_thread_fence(std::memory_order_seq_cst);
275
276        // Step 2 : acquire our local lock
277        __atomic_acquire( &kernelTLS().sched_lock );
278        /*paranoid*/ verify(kernelTLS().sched_lock);
279
280        #ifdef __CFA_WITH_VERIFY__
281                // Debug, check if this is owned for reading
282                kernelTLS().in_sched_lock = true;
283        #endif
284}
285
286static inline void ready_schedule_unlock(void) with(__scheduler_lock.lock) {
287        /* paranoid */ verify( ! __preemption_enabled() );
288        /* paranoid */ verify( data[kernelTLS().sched_id] == &kernelTLS().sched_lock );
289        /* paranoid */ verify( !kernelTLS().this_processor || kernelTLS().this_processor->unique_id == kernelTLS().sched_id );
290        /* paranoid */ verify( kernelTLS().sched_lock );
291        /* paranoid */ verify( kernelTLS().in_sched_lock );
292        #ifdef __CFA_WITH_VERIFY__
293                // Debug, check if this is owned for reading
294                kernelTLS().in_sched_lock = false;
295        #endif
296        __atomic_unlock(&kernelTLS().sched_lock);
297}
298
299#ifdef __CFA_WITH_VERIFY__
300        static inline bool ready_schedule_islocked(void) {
301                /* paranoid */ verify( ! __preemption_enabled() );
302                /* paranoid */ verify( (!kernelTLS().in_sched_lock) || kernelTLS().sched_lock );
303                return kernelTLS().sched_lock;
304        }
305
306        static inline bool ready_mutate_islocked() {
307                return __scheduler_lock.lock.write_lock;
308        }
309#endif
310
311//-----------------------------------------------------------------------
312// Writer side : acquire when changing the ready queue, e.g. adding more
313//  queues or removing them.
314uint_fast32_t ready_mutate_lock( void );
315
316void ready_mutate_unlock( uint_fast32_t /* value returned by lock */ );
317
318//-----------------------------------------------------------------------
319// Lock-Free registering/unregistering of threads
320// Register a processor to a given cluster and get its unique id in return
321// For convenience, also acquires the lock
322static inline [unsigned, uint_fast32_t] ready_mutate_register() {
323        unsigned id = register_proc_id();
324        uint_fast32_t last = ready_mutate_lock();
325        return [id, last];
326}
327
328// Unregister a processor from a given cluster using its id, getting back the original pointer
329// assumes the lock is acquired
330static inline void ready_mutate_unregister( unsigned id, uint_fast32_t last_s ) {
331        ready_mutate_unlock( last_s );
332        unregister_proc_id( id );
333}
334
335//-----------------------------------------------------------------------
336// Cluster idle lock/unlock
337static inline void lock(__cluster_proc_list & this) {
338        /* paranoid */ verify( ! __preemption_enabled() );
339
340        // Start by locking the global RWlock so that we know no-one is
341        // adding/removing processors while we mess with the idle lock
342        ready_schedule_lock();
343
344        lock( this.lock __cfaabi_dbg_ctx2 );
345
346        /* paranoid */ verify( ! __preemption_enabled() );
347}
348
349static inline bool try_lock(__cluster_proc_list & this) {
350        /* paranoid */ verify( ! __preemption_enabled() );
351
352        // Start by locking the global RWlock so that we know no-one is
353        // adding/removing processors while we mess with the idle lock
354        ready_schedule_lock();
355
356        if(try_lock( this.lock __cfaabi_dbg_ctx2 )) {
357                // success
358                /* paranoid */ verify( ! __preemption_enabled() );
359                return true;
360        }
361
362        // failed to lock
363        ready_schedule_unlock();
364
365        /* paranoid */ verify( ! __preemption_enabled() );
366        return false;
367}
368
369static inline void unlock(__cluster_proc_list & this) {
370        /* paranoid */ verify( ! __preemption_enabled() );
371
372        unlock(this.lock);
373
374        // Release the global lock, which we acquired when locking
375        ready_schedule_unlock();
376
377        /* paranoid */ verify( ! __preemption_enabled() );
378}
379
380//=======================================================================
381// Ready-Queue API
382//-----------------------------------------------------------------------
383// push thread onto a ready queue for a cluster
384// returns true if the list was previously empty, false otherwise
385__attribute__((hot)) void push(struct cluster * cltr, struct thread$ * thrd, unpark_hint hint);
386
387//-----------------------------------------------------------------------
388// pop thread from the local queues of a cluster
389// returns 0p if empty
390// May return 0p spuriously
391__attribute__((hot)) struct thread$ * pop_fast(struct cluster * cltr);
392
393//-----------------------------------------------------------------------
394// pop thread from any ready queue of a cluster
395// returns 0p if empty
396// May return 0p spuriously
397__attribute__((hot)) struct thread$ * pop_slow(struct cluster * cltr);
398
399//-----------------------------------------------------------------------
400// search all ready queues of a cluster for any thread
401// returns 0p if empty
402// guaranteed to find any threads added before this call
403__attribute__((hot)) struct thread$ * pop_search(struct cluster * cltr);
404
405//-----------------------------------------------------------------------
406// get preferred ready for new thread
407unsigned ready_queue_new_preferred();
408
409//-----------------------------------------------------------------------
410// Increase the width of the ready queue (number of lanes) by 4
411void ready_queue_grow  (struct cluster * cltr);
412
413//-----------------------------------------------------------------------
414// Decrease the width of the ready queue (number of lanes) by 4
415void ready_queue_shrink(struct cluster * cltr);
416
417//-----------------------------------------------------------------------
418// Decrease the width of the ready queue (number of lanes) by 4
419void ready_queue_close(struct cluster * cltr);
420
421// Local Variables: //
422// mode: c //
423// tab-width: 4 //
424// End: //
Note: See TracBrowser for help on using the repository browser.