source: libcfa/src/concurrency/monitor.cfa @ 09bdf2d

Last change on this file since 09bdf2d was ed52dd5, checked in by Peter A. Buhr <pabuhr@…>, 21 months ago

remove comment about _GNU_SOURCE

  • Property mode set to 100644
File size: 36.1 KB
RevLine 
[f07e037]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//
[e84ab3d]7// monitor.cfa --
[f07e037]8//
9// Author           : Thierry Delisle
10// Created On       : Thd Feb 23 12:27:26 2017
[6b0b624]11// Last Modified By : Peter A. Buhr
[ed52dd5]12// Last Modified On : Sun Feb 19 17:00:59 2023
13// Update Count     : 12
[f07e037]14//
15
[2026bb6]16#define __cforall_thread__
17
[58b6d1b]18#include "monitor.hfa"
[f07e037]19
[73abe95]20#include <stdlib.hfa>
[2f6a7e93]21#include <inttypes.h>
[a933dcf4]22
[708ae38]23#include "kernel/private.hfa"
[f07e037]24
[58b6d1b]25#include "bits/algorithm.hfa"
[de737c8]26
[0c78741]27//-----------------------------------------------------------------------------
28// Forward declarations
[e84ab3d]29static inline void __set_owner ( monitor$ * this, thread$ * owner );
30static inline void __set_owner ( monitor$ * storage [], __lock_size_t count, thread$ * owner );
31static inline void set_mask  ( monitor$ * storage [], __lock_size_t count, const __waitfor_mask_t & mask );
32static inline void reset_mask( monitor$ * this );
[6ff4507]33
[e84ab3d]34static inline thread$ * next_thread( monitor$ * this );
35static inline bool is_accepted( monitor$ * this, const __monitor_group_t & monitors );
[0c78741]36
[ea7d2b0]37static inline void lock_all  ( __spinlock_t * locks [], __lock_size_t count );
[e84ab3d]38static inline void lock_all  ( monitor$ * source [], __spinlock_t * /*out*/ locks [], __lock_size_t count );
[ea7d2b0]39static inline void unlock_all( __spinlock_t * locks [], __lock_size_t count );
[e84ab3d]40static inline void unlock_all( monitor$ * locks [], __lock_size_t count );
[0c78741]41
[e84ab3d]42static inline void save   ( monitor$ * ctx [], __lock_size_t count, __spinlock_t * locks [], unsigned int /*out*/ recursions [], __waitfor_mask_t /*out*/ masks [] );
43static inline void restore( monitor$ * ctx [], __lock_size_t count, __spinlock_t * locks [], unsigned int /*in */ recursions [], __waitfor_mask_t /*in */ masks [] );
[0c78741]44
[c18bf9e]45static inline void ?{}(__condition_node_t & this, thread$ * waiting_thread, __lock_size_t count, uintptr_t user_info );
46static inline void ?{}(__condition_criterion_t & this );
47static inline void ?{}(__condition_criterion_t & this, monitor$ * target, __condition_node_t * owner );
48
[e84ab3d]49static inline void init     ( __lock_size_t count, monitor$ * monitors [], __condition_node_t & waiter, __condition_criterion_t criteria [] );
50static inline void init_push( __lock_size_t count, monitor$ * monitors [], __condition_node_t & waiter, __condition_criterion_t criteria [] );
[97e3296]51
[e84ab3d]52static inline thread$ *        check_condition   ( __condition_criterion_t * );
[4cedd9f]53static inline void                 brand_condition   ( condition & );
[e84ab3d]54static inline [thread$ *, int] search_entry_queue( const __waitfor_mask_t &, monitor$ * monitors [], __lock_size_t count );
[b18830e]55
[fd54fef]56forall(T & | sized( T ))
[59a0bde]57static inline __lock_size_t insert_unique( T * array [], __lock_size_t & size, T * val );
58static inline __lock_size_t count_max    ( const __waitfor_mask_t & mask );
[e84ab3d]59static inline __lock_size_t aggregate    ( monitor$ * storage [], const __waitfor_mask_t & mask );
[97e3296]60
61//-----------------------------------------------------------------------------
62// Useful defines
[6ff4507]63#define wait_ctx(thrd, user_info)                               /* Create the necessary information to use the signaller stack                         */ \
64        __condition_node_t waiter = { thrd, count, user_info };   /* Create the node specific to this wait operation                                     */ \
65        __condition_criterion_t criteria[count];                  /* Create the creteria this wait operation needs to wake up                            */ \
[8fc45b7]66        init( count, monitors, waiter, criteria );                /* Link everything together                                                            */ \
[6ff4507]67
68#define wait_ctx_primed(thrd, user_info)                        /* Create the necessary information to use the signaller stack                         */ \
69        __condition_node_t waiter = { thrd, count, user_info };   /* Create the node specific to this wait operation                                     */ \
70        __condition_criterion_t criteria[count];                  /* Create the creteria this wait operation needs to wake up                            */ \
[8fc45b7]71        init_push( count, monitors, waiter, criteria );           /* Link everything together and push it to the AS-Stack                                */ \
[6ff4507]72
73#define monitor_ctx( mons, cnt )                                /* Define that create the necessary struct for internal/external scheduling operations */ \
[e84ab3d]74        monitor$ ** monitors = mons;                          /* Save the targeted monitors                                                          */ \
[59a0bde]75        __lock_size_t count = cnt;                                /* Save the count to a local variable                                                  */ \
[6ff4507]76        unsigned int recursions[ count ];                         /* Save the current recursion levels to restore them later                             */ \
[4cedd9f]77        __waitfor_mask_t masks [ count ];                         /* Save the current waitfor masks to restore them later                                */ \
[ea7d2b0]78        __spinlock_t *   locks [ count ];                         /* We need to pass-in an array of locks to BlockInternal                               */ \
[6ff4507]79
80#define monitor_save    save   ( monitors, count, locks, recursions, masks )
81#define monitor_restore restore( monitors, count, locks, recursions, masks )
82
[97e3296]83
[0c78741]84//-----------------------------------------------------------------------------
85// Enter/Leave routines
[c7a900a]86// Enter single monitor
[e84ab3d]87static void __enter( monitor$ * this, const __monitor_group_t & group ) {
88        thread$ * thrd = active_thread();
[8fc652e0]89
[c7a900a]90        // Lock the monitor spinlock
91        lock( this->lock __cfaabi_dbg_ctx2 );
[690f13c]92
[c7a900a]93        __cfaabi_dbg_print_safe( "Kernel : %10p Entering mon %p (%p)\n", thrd, this, this->owner);
[690f13c]94
[77a2994]95        if( unlikely(0 != (0x1 & (uintptr_t)this->owner)) ) {
96                abort( "Attempt by thread \"%.256s\" (%p) to access joined monitor %p.", thrd->self_cor.name, thrd, this );
97        }
98        else if( !this->owner ) {
[c7a900a]99                // No one has the monitor, just take it
100                __set_owner( this, thrd );
[f07e037]101
[c7a900a]102                __cfaabi_dbg_print_safe( "Kernel :  mon is free \n" );
103        }
104        else if( this->owner == thrd) {
105                // We already have the monitor, just note how many times we took it
106                this->recursion += 1;
[90c4df0]107
[c7a900a]108                __cfaabi_dbg_print_safe( "Kernel :  mon already owned \n" );
109        }
110        else if( is_accepted( this, group) ) {
111                // Some one was waiting for us, enter
112                __set_owner( this, thrd );
[90c4df0]113
[c7a900a]114                // Reset mask
115                reset_mask( this );
[90c4df0]116
[c7a900a]117                __cfaabi_dbg_print_safe( "Kernel :  mon accepts \n" );
118        }
119        else {
120                __cfaabi_dbg_print_safe( "Kernel :  blocking \n" );
[90c4df0]121
[c7a900a]122                // Some one else has the monitor, wait in line for it
[be5f0a5]123                /* paranoid */ verify( thrd->user_link.next == 0p );
[c7a900a]124                append( this->entry_queue, thrd );
[be5f0a5]125                /* paranoid */ verify( thrd->user_link.next == 1p );
[daacf82]126
[c7a900a]127                unlock( this->lock );
[e235429]128                park();
[90c4df0]129
[169d944]130                __cfaabi_dbg_print_safe( "Kernel : %10p Entered  mon %p\n", thrd, this);
[2e9aed4]131
[8fc652e0]132                /* paranoid */ verifyf( active_thread() == this->owner, "Expected owner to be %p, got %p (r: %i, m: %p)", active_thread(), this->owner, this->recursion, this );
[5ea06d6]133                return;
[cb0e6de]134        }
[cc7f4b1]135
[c7a900a]136        __cfaabi_dbg_print_safe( "Kernel : %10p Entered  mon %p\n", thrd, this);
[90c4df0]137
[8fc652e0]138        /* paranoid */ verifyf( active_thread() == this->owner, "Expected owner to be %p, got %p (r: %i, m: %p)", active_thread(), this->owner, this->recursion, this );
[c7a900a]139        /* paranoid */ verify( this->lock.lock );
[f07e037]140
[c7a900a]141        // Release the lock and leave
142        unlock( this->lock );
143        return;
144}
[90c4df0]145
[e84ab3d]146static void __dtor_enter( monitor$ * this, fptr_t func, bool join ) {
147        thread$ * thrd = active_thread();
[3ea8ad1]148        #if defined( __CFA_WITH_VERIFY__ )
149                bool is_thrd = this == &thrd->self_mon;
150        #endif
[8fc652e0]151
[c7a900a]152        // Lock the monitor spinlock
153        lock( this->lock __cfaabi_dbg_ctx2 );
[f07e037]154
[c7a900a]155        __cfaabi_dbg_print_safe( "Kernel : %10p Entering dtor for mon %p (%p)\n", thrd, this, this->owner);
[549c006]156
157
[c7a900a]158        if( !this->owner ) {
159                __cfaabi_dbg_print_safe( "Kernel : Destroying free mon %p\n", this);
[549c006]160
[c7a900a]161                // No one has the monitor, just take it
162                __set_owner( this, thrd );
[549c006]163
[3ea8ad1]164                /* paranoid */ verifyf( active_thread() == this->owner, "Expected owner to be %p, got %p (r: %i, m: %p)", active_thread(), this->owner, this->recursion, this );
165                /* paranoid */ verify( !is_thrd || thrd->state == Halted || thrd->state == Cancelled );
[549c006]166
[c7a900a]167                unlock( this->lock );
168                return;
169        }
[77a2994]170        else if( this->owner == thrd && !join) {
[c7a900a]171                // We already have the monitor... but where about to destroy it so the nesting will fail
172                // Abort!
173                abort( "Attempt to destroy monitor %p by thread \"%.256s\" (%p) in nested mutex.", this, thrd->self_cor.name, thrd );
174        }
[77a2994]175        // SKULLDUGGERY: join will act as a dtor so it would normally trigger to above check
[9d6e1b8a]176        // because join will not release the monitor after it executed.
[77a2994]177        // to avoid that it sets the owner to the special value thrd | 1p before exiting
[e84ab3d]178        else if( this->owner == (thread$*)(1 | (uintptr_t)thrd) ) {
[77a2994]179                // restore the owner and just return
180                __cfaabi_dbg_print_safe( "Kernel : Destroying free mon %p\n", this);
181
182                // No one has the monitor, just take it
[9d6e1b8a]183                __set_owner( this, thrd );
[77a2994]184
[3ea8ad1]185                /* paranoid */ verifyf( active_thread() == this->owner, "Expected owner to be %p, got %p (r: %i, m: %p)", active_thread(), this->owner, this->recursion, this );
186                /* paranoid */ verify( !is_thrd || thrd->state == Halted || thrd->state == Cancelled );
[77a2994]187
188                unlock( this->lock );
189                return;
190        }
[549c006]191
[3ea8ad1]192        // The monitor is busy, if this is a thread and the thread owns itself, it better be active
193        /* paranoid */ verify( !is_thrd || this->owner != thrd || (thrd->state != Halted && thrd->state != Cancelled) );
194
[c7a900a]195        __lock_size_t count = 1;
[e84ab3d]196        monitor$ ** monitors = &this;
[c7a900a]197        __monitor_group_t group = { &this, 1, func };
198        if( is_accepted( this, group) ) {
199                __cfaabi_dbg_print_safe( "Kernel :  mon accepts dtor, block and signal it \n" );
[549c006]200
[c7a900a]201                // Wake the thread that is waiting for this
202                __condition_criterion_t * urgent = pop( this->signal_stack );
203                /* paranoid */ verify( urgent );
[b8116cd]204
[c7a900a]205                // Reset mask
206                reset_mask( this );
[549c006]207
[c7a900a]208                // Create the node specific to this wait operation
209                wait_ctx_primed( thrd, 0 )
[549c006]210
[c7a900a]211                // Some one else has the monitor, wait for him to finish and then run
212                unlock( this->lock );
[549c006]213
[c7a900a]214                // Release the next thread
[8fc652e0]215                /* paranoid */ verifyf( urgent->owner->waiting_thread == this->owner, "Expected owner to be %p, got %p (r: %i, m: %p)", active_thread(), this->owner, this->recursion, this );
[e235429]216                unpark( urgent->owner->waiting_thread );
[549c006]217
[c7a900a]218                // Park current thread waiting
[e235429]219                park();
[549c006]220
[c7a900a]221                // Some one was waiting for us, enter
[8fc652e0]222                /* paranoid */ verifyf( active_thread() == this->owner, "Expected owner to be %p, got %p (r: %i, m: %p)", active_thread(), this->owner, this->recursion, this );
[3ea8ad1]223
224                __cfaabi_dbg_print_safe( "Kernel : Destroying %p\n", this);
225                return;
[c7a900a]226        }
227        else {
228                __cfaabi_dbg_print_safe( "Kernel :  blocking \n" );
[549c006]229
[c7a900a]230                wait_ctx( thrd, 0 )
231                this->dtor_node = &waiter;
[549c006]232
[c7a900a]233                // Some one else has the monitor, wait in line for it
[be5f0a5]234                /* paranoid */ verify( thrd->user_link.next == 0p );
[c7a900a]235                append( this->entry_queue, thrd );
[be5f0a5]236                /* paranoid */ verify( thrd->user_link.next == 1p );
[c7a900a]237                unlock( this->lock );
[549c006]238
[c7a900a]239                // Park current thread waiting
[e235429]240                park();
[549c006]241
[8fc652e0]242                /* paranoid */ verifyf( active_thread() == this->owner, "Expected owner to be %p, got %p (r: %i, m: %p)", active_thread(), this->owner, this->recursion, this );
[c7a900a]243                return;
[549c006]244        }
[c7a900a]245}
[a843067]246
[c7a900a]247// Leave single monitor
[c18bf9e]248static void __leave( monitor$ * this ) {
[c7a900a]249        // Lock the monitor spinlock
250        lock( this->lock __cfaabi_dbg_ctx2 );
[cc7f4b1]251
[8fc652e0]252        __cfaabi_dbg_print_safe( "Kernel : %10p Leaving mon %p (%p)\n", active_thread(), this, this->owner);
[f07e037]253
[8fc652e0]254        /* paranoid */ verifyf( active_thread() == this->owner, "Expected owner to be %p, got %p (r: %i, m: %p)", active_thread(), this->owner, this->recursion, this );
[f07e037]255
[c7a900a]256        // Leaving a recursion level, decrement the counter
257        this->recursion -= 1;
[5ea06d6]258
[c7a900a]259        // If we haven't left the last level of recursion
260        // it means we don't need to do anything
261        if( this->recursion != 0) {
262                __cfaabi_dbg_print_safe( "Kernel :  recursion still %d\n", this->recursion);
[ea7d2b0]263                unlock( this->lock );
[c7a900a]264                return;
[1c273d0]265        }
266
[c7a900a]267        // Get the next thread, will be null on low contention monitor
[e84ab3d]268        thread$ * new_owner = next_thread( this );
[c7a900a]269
270        // Check the new owner is consistent with who we wake-up
271        // new_owner might be null even if someone owns the monitor when the owner is still waiting for another monitor
272        /* paranoid */ verifyf( !new_owner || new_owner == this->owner, "Expected owner to be %p, got %p (m: %p)", new_owner, this->owner, this );
273
274        // We can now let other threads in safely
275        unlock( this->lock );
[549c006]276
[c7a900a]277        //We need to wake-up the thread
278        /* paranoid */ verifyf( !new_owner || new_owner == this->owner, "Expected owner to be %p, got %p (m: %p)", new_owner, this->owner, this );
[e235429]279        unpark( new_owner );
[c7a900a]280}
281
282// Leave single monitor for the last time
[c18bf9e]283static void __dtor_leave( monitor$ * this, bool join ) {
[c7a900a]284        __cfaabi_dbg_debug_do(
[8fc652e0]285                if( active_thread() != this->owner ) {
286                        abort( "Destroyed monitor %p has inconsistent owner, expected %p got %p.\n", this, active_thread(), this->owner);
[c7a900a]287                }
[77a2994]288                if( this->recursion != 1  && !join ) {
[c7a900a]289                        abort( "Destroyed monitor %p has %d outstanding nested calls.\n", this, this->recursion - 1);
290                }
291        )
[77a2994]292
[e84ab3d]293        this->owner = (thread$*)(1 | (uintptr_t)this->owner);
[c7a900a]294}
[549c006]295
[e84ab3d]296void __thread_finish( thread$ * thrd ) {
297        monitor$ * this = &thrd->self_mon;
[97e3296]298
[5afb49a]299        // Lock the monitor now
[9d6e1b8a]300        /* paranoid */ verify( 0x0D15EA5E0D15EA5Ep == thrd->canary );
[5afb49a]301        /* paranoid */ verify( this->lock.lock );
[9d6e1b8a]302        /* paranoid */ verify( thrd->context.SP );
[e84ab3d]303        /* paranoid */ verifyf( ((uintptr_t)thrd->context.SP) > ((uintptr_t)__get_stack(thrd->curr_cor)->limit), "ERROR : thread$ %p has been corrupted.\n StackPointer too large.\n", thrd );
304        /* paranoid */ verifyf( ((uintptr_t)thrd->context.SP) < ((uintptr_t)__get_stack(thrd->curr_cor)->base ), "ERROR : thread$ %p has been corrupted.\n StackPointer too small.\n", thrd );
[8fc652e0]305        /* paranoid */ verify( ! __preemption_enabled() );
[9d6e1b8a]306
307        /* paranoid */ verifyf( thrd == this->owner, "Expected owner to be %p, got %p (r: %i, m: %p)", thrd, this->owner, this->recursion, this );
[3ea8ad1]308        /* paranoid */ verify( thrd->state == Halting );
[5afb49a]309        /* paranoid */ verify( this->recursion == 1 );
[3381ed7]310
[5afb49a]311        // Leaving a recursion level, decrement the counter
312        this->recursion -= 1;
313        this->owner = 0p;
[b0c7419]314
[5afb49a]315        // Fetch the next thread, can be null
[e84ab3d]316        thread$ * new_owner = next_thread( this );
[1c273d0]317
[3ea8ad1]318        // Mark the state as fully halted
319        thrd->state = Halted;
320
[5afb49a]321        // Release the monitor lock
322        unlock( this->lock );
[97e3296]323
[5afb49a]324        // Unpark the next owner if needed
325        /* paranoid */ verifyf( !new_owner || new_owner == this->owner, "Expected owner to be %p, got %p (m: %p)", new_owner, this->owner, this );
[8fc652e0]326        /* paranoid */ verify( ! __preemption_enabled() );
[5afb49a]327        /* paranoid */ verify( thrd->state == Halted );
328        unpark( new_owner );
[2781e65]329}
330
[97e3296]331// Enter multiple monitor
332// relies on the monitor array being sorted
[6ae8c92]333static inline void enter( __monitor_group_t monitors ) {
[59a0bde]334        for( __lock_size_t i = 0; i < monitors.size; i++) {
[c7a900a]335                __enter( monitors[i], monitors );
[97e3296]336        }
[2781e65]337}
338
[97e3296]339// Leave multiple monitor
340// relies on the monitor array being sorted
[e84ab3d]341static inline void leave(monitor$ * monitors [], __lock_size_t count) {
[59a0bde]342        for( __lock_size_t i = count - 1; i >= 0; i--) {
[c7a900a]343                __leave( monitors[i] );
[2781e65]344        }
[5ea06d6]345}
346
[97e3296]347// Ctor for monitor guard
348// Sorts monitors before entering
[c18bf9e]349void ?{}( monitor_guard_t & this, monitor$ * m [], __lock_size_t count, fptr_t func ) libcfa_public {
[e84ab3d]350        thread$ * thrd = active_thread();
[14a61b5]351
[97e3296]352        // Store current array
[242a902]353        this.m = m;
354        this.count = count;
[97e3296]355
[09800e9]356        // Sort monitors based on address
[de737c8]357        __libcfa_small_sort(this.m, count);
[5ea06d6]358
[97e3296]359        // Save previous thread context
[14a61b5]360        this.prev = thrd->monitors;
[5ea06d6]361
[97e3296]362        // Update thread context (needed for conditions)
[14a61b5]363        (thrd->monitors){m, count, func};
[90c4df0]364
[169d944]365        // __cfaabi_dbg_print_safe( "MGUARD : enter %d\n", count);
[a843067]366
[90c4df0]367        // Enter the monitors in order
[6ae8c92]368        __monitor_group_t group = {this.m, this.count, func};
[b18830e]369        enter( group );
[a843067]370
[169d944]371        // __cfaabi_dbg_print_safe( "MGUARD : entered\n" );
[5ea06d6]372}
373
[c18bf9e]374void ?{}( monitor_guard_t & this, monitor$ * m [], __lock_size_t count ) libcfa_public {
[6cebfef]375        this{ m, count, 0p };
376}
377
[6b224a52]378
[97e3296]379// Dtor for monitor guard
[c18bf9e]380void ^?{}( monitor_guard_t & this ) libcfa_public {
[169d944]381        // __cfaabi_dbg_print_safe( "MGUARD : leaving %d\n", this.count);
[a843067]382
[97e3296]383        // Leave the monitors in order
[242a902]384        leave( this.m, this.count );
[5ea06d6]385
[169d944]386        // __cfaabi_dbg_print_safe( "MGUARD : left\n" );
[a843067]387
[97e3296]388        // Restore thread context
[8fc652e0]389        active_thread()->monitors = this.prev;
[5ea06d6]390}
391
[549c006]392// Ctor for monitor guard
393// Sorts monitors before entering
[c18bf9e]394void ?{}( monitor_dtor_guard_t & this, monitor$ * m [], fptr_t func, bool join ) libcfa_public {
[14a61b5]395        // optimization
[e84ab3d]396        thread$ * thrd = active_thread();
[14a61b5]397
[549c006]398        // Store current array
399        this.m = *m;
400
401        // Save previous thread context
[14a61b5]402        this.prev = thrd->monitors;
[549c006]403
[77a2994]404        // Save whether we are in a join or not
405        this.join = join;
406
[549c006]407        // Update thread context (needed for conditions)
[14a61b5]408        (thrd->monitors){m, 1, func};
[549c006]409
[77a2994]410        __dtor_enter( this.m, func, join );
[549c006]411}
412
413// Dtor for monitor guard
[c18bf9e]414void ^?{}( monitor_dtor_guard_t & this ) libcfa_public {
[549c006]415        // Leave the monitors in order
[77a2994]416        __dtor_leave( this.m, this.join );
[549c006]417
418        // Restore thread context
[8fc652e0]419        active_thread()->monitors = this.prev;
[549c006]420}
421
[97e3296]422//-----------------------------------------------------------------------------
423// Internal scheduling types
[c18bf9e]424static void ?{}(__condition_node_t & this, thread$ * waiting_thread, __lock_size_t count, uintptr_t user_info ) {
[242a902]425        this.waiting_thread = waiting_thread;
426        this.count = count;
[121be3e]427        this.next = 0p;
[242a902]428        this.user_info = user_info;
[be3d020]429}
430
[c18bf9e]431static void ?{}(__condition_criterion_t & this ) with( this ) {
[c40e7c5]432        ready  = false;
[121be3e]433        target = 0p;
434        owner  = 0p;
435        next   = 0p;
[be3d020]436}
437
[c18bf9e]438static void ?{}(__condition_criterion_t & this, monitor$ * target, __condition_node_t & owner ) {
[242a902]439        this.ready  = false;
440        this.target = target;
[8fc45b7]441        this.owner  = &owner;
[121be3e]442        this.next   = 0p;
[ad1a8dd]443}
444
[5ea06d6]445//-----------------------------------------------------------------------------
446// Internal scheduling
[c18bf9e]447void wait( condition & this, uintptr_t user_info = 0 ) libcfa_public {
[0c78741]448        brand_condition( this );
[5ea06d6]449
[97e3296]450        // Check that everything is as expected
[121be3e]451        assertf( this.monitors != 0p, "Waiting with no monitors (%p)", this.monitors );
[2f6a7e93]452        verifyf( this.monitor_count != 0, "Waiting with 0 monitors (%"PRIiFAST16")", this.monitor_count );
453        verifyf( this.monitor_count < 32u, "Excessive monitor count (%"PRIiFAST16")", this.monitor_count );
[5ea06d6]454
[97e3296]455        // Create storage for monitor context
[4cedd9f]456        monitor_ctx( this.monitors, this.monitor_count );
[0c78741]457
[97e3296]458        // Create the node specific to this wait operation
[8fc652e0]459        wait_ctx( active_thread(), user_info );
[0c78741]460
[97e3296]461        // Append the current wait operation to the ones already queued on the condition
462        // We don't need locks for that since conditions must always be waited on inside monitor mutual exclusion
[3381ed7]463        /* paranoid */ verify( waiter.next == 0p );
[8fc45b7]464        append( this.blocked, &waiter );
[3381ed7]465        /* paranoid */ verify( waiter.next == 1p );
[0c78741]466
[6ff4507]467        // Lock all monitors (aggregates the locks as well)
[97e3296]468        lock_all( monitors, locks, count );
[5ea06d6]469
[97e3296]470        // Find the next thread(s) to run
[59a0bde]471        __lock_size_t thread_count = 0;
[e84ab3d]472        thread$ * threads[ count ];
[66298de]473        __builtin_memset( threads, 0, sizeof( threads ) );
[ad1a8dd]474
[a843067]475        // Save monitor states
476        monitor_save;
477
[97e3296]478        // Remove any duplicate threads
[59a0bde]479        for( __lock_size_t i = 0; i < count; i++) {
[e84ab3d]480                thread$ * new_owner = next_thread( monitors[i] );
[6ff4507]481                insert_unique( threads, thread_count, new_owner );
[5ea06d6]482        }
483
[3381ed7]484        // Unlock the locks, we don't need them anymore
485        for(int i = 0; i < count; i++) {
486                unlock( *locks[i] );
487        }
488
489        // Wake the threads
490        for(int i = 0; i < thread_count; i++) {
[e235429]491                unpark( threads[i] );
[3381ed7]492        }
493
[a843067]494        // Everything is ready to go to sleep
[e235429]495        park();
[a843067]496
497        // We are back, restore the owners and recursions
498        monitor_restore;
[5ea06d6]499}
500
[c18bf9e]501bool signal( condition & this ) libcfa_public {
[97e3296]502        if( is_empty( this ) ) { return false; }
[5ea06d6]503
504        //Check that everything is as expected
[4cedd9f]505        verify( this.monitors );
506        verify( this.monitor_count != 0 );
[0c78741]507
[44264c5]508        //Some more checking in debug
[36982fc]509        __cfaabi_dbg_debug_do(
[e84ab3d]510                thread$ * this_thrd = active_thread();
[4cedd9f]511                if ( this.monitor_count != this_thrd->monitors.size ) {
[c2ca04d]512                        abort( "Signal on condition %p made with different number of monitor(s), expected %zi got %zi", &this, this.monitor_count, this_thrd->monitors.size );
[97e3296]513                }
[0c78741]514
[4cedd9f]515                for(int i = 0; i < this.monitor_count; i++) {
[0cf5b79]516                        if ( this.monitors[i] != this_thrd->monitors[i] ) {
[2fdbb3b]517                                abort( "Signal on condition %p made with different monitor, expected %p got %p", &this, this.monitors[i], this_thrd->monitors[i] );
[97e3296]518                        }
[0c78741]519                }
[5ea06d6]520        );
521
[59a0bde]522        __lock_size_t count = this.monitor_count;
[97e3296]523
524        // Lock all monitors
[121be3e]525        lock_all( this.monitors, 0p, count );
[0c78741]526
[44264c5]527        //Pop the head of the waiting queue
[8fc45b7]528        __condition_node_t * node = pop_head( this.blocked );
[44264c5]529
530        //Add the thread to the proper AS stack
[0c78741]531        for(int i = 0; i < count; i++) {
532                __condition_criterion_t * crit = &node->criteria[i];
533                assert( !crit->ready );
[8fc45b7]534                push( crit->target->signal_stack, crit );
[5ea06d6]535        }
[0c78741]536
[44264c5]537        //Release
[4cedd9f]538        unlock_all( this.monitors, count );
[be3d020]539
540        return true;
[5ea06d6]541}
542
[c18bf9e]543bool signal_block( condition & this ) libcfa_public {
[4cedd9f]544        if( !this.blocked.head ) { return false; }
[44264c5]545
546        //Check that everything is as expected
[121be3e]547        verifyf( this.monitors != 0p, "Waiting with no monitors (%p)", this.monitors );
[2f6a7e93]548        verifyf( this.monitor_count != 0, "Waiting with 0 monitors (%"PRIiFAST16")", this.monitor_count );
[44264c5]549
[97e3296]550        // Create storage for monitor context
[4cedd9f]551        monitor_ctx( this.monitors, this.monitor_count );
[44264c5]552
[97e3296]553        // Lock all monitors (aggregates the locks them as well)
554        lock_all( monitors, locks, count );
[44264c5]555
[2e9aed4]556
[97e3296]557        // Create the node specific to this wait operation
[8fc652e0]558        wait_ctx_primed( active_thread(), 0 )
[44264c5]559
560        //save contexts
[6ff4507]561        monitor_save;
[44264c5]562
563        //Find the thread to run
[e84ab3d]564        thread$ * signallee = pop_head( this.blocked )->waiting_thread;
[c7a900a]565        __set_owner( monitors, count, signallee );
[44264c5]566
[36982fc]567        __cfaabi_dbg_print_buffer_decl( "Kernel : signal_block condition %p (s: %p)\n", &this, signallee );
[de737c8]568
[3381ed7]569        // unlock all the monitors
570        unlock_all( locks, count );
571
572        // unpark the thread we signalled
[e235429]573        unpark( signallee );
[3381ed7]574
[44264c5]575        //Everything is ready to go to sleep
[e235429]576        park();
[44264c5]577
[c81ebf9]578
[97e3296]579        // WE WOKE UP
[c81ebf9]580
581
[36982fc]582        __cfaabi_dbg_print_buffer_local( "Kernel :   signal_block returned\n" );
[de737c8]583
[6ff4507]584        //We are back, restore the masks and recursions
585        monitor_restore;
[be3d020]586
587        return true;
588}
589
[97e3296]590// Access the user_info of the thread waiting at the front of the queue
[c18bf9e]591uintptr_t front( condition & this ) libcfa_public {
[2ac095d]592        verifyf( !is_empty(this),
[4aa2fb2]593                "Attempt to access user data on an empty condition.\n"
594                "Possible cause is not checking if the condition is empty before reading stored data."
[be3d020]595        );
[0cf5b79]596        return ((typeof(this.blocked.head))this.blocked.head)->user_info;
[44264c5]597}
598
[c81ebf9]599//-----------------------------------------------------------------------------
[b18830e]600// External scheduling
601// cases to handle :
602//      - target already there :
603//              block and wake
604//      - dtor already there
605//              put thread on signaller stack
606//      - non-blocking
607//              return else
608//      - timeout
609//              return timeout
610//      - block
611//              setup mask
612//              block
[c18bf9e]613void __waitfor_internal( const __waitfor_mask_t & mask, int duration ) libcfa_public {
[b18830e]614        // This statment doesn't have a contiguous list of monitors...
615        // Create one!
[59a0bde]616        __lock_size_t max = count_max( mask );
[e84ab3d]617        monitor$ * mon_storage[max];
[66298de]618        __builtin_memset( mon_storage, 0, sizeof( mon_storage ) );
[59a0bde]619        __lock_size_t actual_count = aggregate( mon_storage, mask );
[97e3296]620
[523232d]621        __cfaabi_dbg_print_buffer_decl( "Kernel : waitfor %"PRIdFAST16" (s: %"PRIdFAST16", m: %"PRIdFAST16")\n", actual_count, mask.size, (__lock_size_t)max);
[66298de]622
[daacf82]623        if(actual_count == 0) return;
[19c43b7]624
[169d944]625        __cfaabi_dbg_print_buffer_local( "Kernel : waitfor internal proceeding\n" );
[4cc9b13]626
[97e3296]627        // Create storage for monitor context
[b18830e]628        monitor_ctx( mon_storage, actual_count );
[c81ebf9]629
[6ff4507]630        // Lock all monitors (aggregates the locks as well)
[97e3296]631        lock_all( monitors, locks, count );
[c81ebf9]632
[b18830e]633        {
634                // Check if the entry queue
[e84ab3d]635                thread$ * next; int index;
[6ae8c92]636                [next, index] = search_entry_queue( mask, monitors, count );
[b18830e]637
638                if( next ) {
[19c43b7]639                        *mask.accepted = index;
[0cf5b79]640                        __acceptable_t& accepted = mask[index];
641                        if( accepted.is_dtor ) {
[169d944]642                                __cfaabi_dbg_print_buffer_local( "Kernel : dtor already there\n" );
[0cf5b79]643                                verifyf( accepted.size == 1,  "ERROR: Accepted dtor has more than 1 mutex parameter." );
[549c006]644
[e84ab3d]645                                monitor$ * mon2dtor = accepted[0];
[549c006]646                                verifyf( mon2dtor->dtor_node, "ERROR: Accepted monitor has no dtor_node." );
647
648                                __condition_criterion_t * dtor_crit = mon2dtor->dtor_node->criteria;
[8fc45b7]649                                push( mon2dtor->signal_stack, dtor_crit );
[549c006]650
651                                unlock_all( locks, count );
[b18830e]652                        }
653                        else {
[169d944]654                                __cfaabi_dbg_print_buffer_local( "Kernel : thread present, baton-passing\n" );
[19c43b7]655
656                                // Create the node specific to this wait operation
[8fc652e0]657                                wait_ctx_primed( active_thread(), 0 );
[19c43b7]658
659                                // Save monitor states
660                                monitor_save;
661
[523232d]662                                __cfaabi_dbg_print_buffer_local( "Kernel :  baton of %"PRIdFAST16" monitors : ", count );
[6a5be52]663                                #ifdef __CFA_DEBUG_PRINT__
664                                        for( int i = 0; i < count; i++) {
[36982fc]665                                                __cfaabi_dbg_print_buffer_local( "%p %p ", monitors[i], monitors[i]->signal_stack.top );
[6a5be52]666                                        }
667                                #endif
[169d944]668                                __cfaabi_dbg_print_buffer_local( "\n" );
[6a5be52]669
[19c43b7]670                                // Set the owners to be the next thread
[c7a900a]671                                __set_owner( monitors, count, next );
[19c43b7]672
[3381ed7]673                                // unlock all the monitors
674                                unlock_all( locks, count );
[19c43b7]675
[3381ed7]676                                // unpark the thread we signalled
[e235429]677                                unpark( next );
[3381ed7]678
679                                //Everything is ready to go to sleep
[e235429]680                                park();
[19c43b7]681
682                                // We are back, restore the owners and recursions
683                                monitor_restore;
684
[169d944]685                                __cfaabi_dbg_print_buffer_local( "Kernel : thread present, returned\n" );
[b18830e]686                        }
687
[36982fc]688                        __cfaabi_dbg_print_buffer_local( "Kernel : accepted %d\n", *mask.accepted);
[19c43b7]689                        return;
[90c4df0]690                }
691        }
692
[c81ebf9]693
[4cc9b13]694        if( duration == 0 ) {
[169d944]695                __cfaabi_dbg_print_buffer_local( "Kernel : non-blocking, exiting\n" );
[19c43b7]696
[4cc9b13]697                unlock_all( locks, count );
[19c43b7]698
[36982fc]699                __cfaabi_dbg_print_buffer_local( "Kernel : accepted %d\n", *mask.accepted);
[4cc9b13]700                return;
701        }
[b18830e]702
703
[169d944]704        verifyf( duration < 0, "Timeout on waitfor statments not supported yet." );
[b18830e]705
[169d944]706        __cfaabi_dbg_print_buffer_local( "Kernel : blocking waitfor\n" );
[19c43b7]707
708        // Create the node specific to this wait operation
[8fc652e0]709        wait_ctx_primed( active_thread(), 0 );
[b18830e]710
[6ff4507]711        monitor_save;
[6ae8c92]712        set_mask( monitors, count, mask );
[c81ebf9]713
[59a0bde]714        for( __lock_size_t i = 0; i < count; i++) {
[8fc652e0]715                verify( monitors[i]->owner == active_thread() );
[daacf82]716        }
717
[3381ed7]718        // unlock all the monitors
719        unlock_all( locks, count );
720
[19c43b7]721        //Everything is ready to go to sleep
[e235429]722        park();
[19c43b7]723
724
725        // WE WOKE UP
726
727
728        //We are back, restore the masks and recursions
729        monitor_restore;
730
[169d944]731        __cfaabi_dbg_print_buffer_local( "Kernel : exiting\n" );
[19c43b7]732
[36982fc]733        __cfaabi_dbg_print_buffer_local( "Kernel : accepted %d\n", *mask.accepted);
[c81ebf9]734}
735
[0c78741]736//-----------------------------------------------------------------------------
737// Utilities
738
[e84ab3d]739static inline void __set_owner( monitor$ * this, thread$ * owner ) {
[3381ed7]740        /* paranoid */ verify( this->lock.lock );
[a843067]741
[0c78741]742        //Pass the monitor appropriately
743        this->owner = owner;
744
745        //We are passing the monitor to someone else, which means recursion level is not 0
746        this->recursion = owner ? 1 : 0;
747}
748
[e84ab3d]749static inline void __set_owner( monitor$ * monitors [], __lock_size_t count, thread$ * owner ) {
[3381ed7]750        /* paranoid */ verify ( monitors[0]->lock.lock );
[8fc652e0]751        /* paranoid */ verifyf( monitors[0]->owner == active_thread(), "Expected owner to be %p, got %p (r: %i, m: %p)", active_thread(), monitors[0]->owner, monitors[0]->recursion, monitors[0] );
[3381ed7]752        monitors[0]->owner        = owner;
753        monitors[0]->recursion    = 1;
[513daec]754        for( __lock_size_t i = 1; i < count; i++ ) {
[3381ed7]755                /* paranoid */ verify ( monitors[i]->lock.lock );
[8fc652e0]756                /* paranoid */ verifyf( monitors[i]->owner == active_thread(), "Expected owner to be %p, got %p (r: %i, m: %p)", active_thread(), monitors[i]->owner, monitors[i]->recursion, monitors[i] );
[3381ed7]757                monitors[i]->owner        = owner;
758                monitors[i]->recursion    = 0;
[6ff4507]759        }
760}
761
[e84ab3d]762static inline void set_mask( monitor$ * storage [], __lock_size_t count, const __waitfor_mask_t & mask ) {
[513daec]763        for( __lock_size_t i = 0; i < count; i++) {
[6ff4507]764                storage[i]->mask = mask;
765        }
766}
767
[e84ab3d]768static inline void reset_mask( monitor$ * this ) {
[121be3e]769        this->mask.accepted = 0p;
770        this->mask.data = 0p;
[daacf82]771        this->mask.size = 0;
772}
773
[e84ab3d]774static inline thread$ * next_thread( monitor$ * this ) {
[0c78741]775        //Check the signaller stack
[169d944]776        __cfaabi_dbg_print_safe( "Kernel :  mon %p AS-stack top %p\n", this, this->signal_stack.top);
[8fc45b7]777        __condition_criterion_t * urgent = pop( this->signal_stack );
[0c78741]778        if( urgent ) {
779                //The signaller stack is not empty,
780                //regardless of if we are ready to baton pass,
781                //we need to set the monitor as in use
[8fc652e0]782                /* paranoid */ verifyf( !this->owner || active_thread() == this->owner, "Expected owner to be %p, got %p (r: %i, m: %p)", active_thread(), this->owner, this->recursion, this );
[c7a900a]783                __set_owner( this,  urgent->owner->waiting_thread );
[0c78741]784
785                return check_condition( urgent );
786        }
787
788        // No signaller thread
789        // Get the next thread in the entry_queue
[e84ab3d]790        thread$ * new_owner = pop_head( this->entry_queue );
[8fc652e0]791        /* paranoid */ verifyf( !this->owner || active_thread() == this->owner, "Expected owner to be %p, got %p (r: %i, m: %p)", active_thread(), this->owner, this->recursion, this );
[be5f0a5]792        /* paranoid */ verify( !new_owner || new_owner->user_link.next == 0p );
[c7a900a]793        __set_owner( this, new_owner );
[0c78741]794
795        return new_owner;
796}
797
[e84ab3d]798static inline bool is_accepted( monitor$ * this, const __monitor_group_t & group ) {
[0cf5b79]799        __acceptable_t * it = this->mask.data; // Optim
[59a0bde]800        __lock_size_t count = this->mask.size;
[6ff4507]801
802        // Check if there are any acceptable functions
[a843067]803        if( !it ) return false;
[6ff4507]804
805        // If this isn't the first monitor to test this, there is no reason to repeat the test.
806        if( this != group[0] ) return group[0]->mask.accepted >= 0;
807
808        // For all acceptable functions check if this is the current function.
[59a0bde]809        for( __lock_size_t i = 0; i < count; i++, it++ ) {
[6ff4507]810                if( *it == group ) {
811                        *this->mask.accepted = i;
812                        return true;
813                }
814        }
815
816        // No function matched
817        return false;
818}
819
[e84ab3d]820static inline void init( __lock_size_t count, monitor$ * monitors [], __condition_node_t & waiter, __condition_criterion_t criteria [] ) {
[513daec]821        for( __lock_size_t i = 0; i < count; i++) {
[6b224a52]822                (criteria[i]){ monitors[i], waiter };
[97e3296]823        }
824
[8fc45b7]825        waiter.criteria = criteria;
[97e3296]826}
827
[e84ab3d]828static inline void init_push( __lock_size_t count, monitor$ * monitors [], __condition_node_t & waiter, __condition_criterion_t criteria [] ) {
[513daec]829        for( __lock_size_t i = 0; i < count; i++) {
[6b224a52]830                (criteria[i]){ monitors[i], waiter };
[36982fc]831                __cfaabi_dbg_print_safe( "Kernel :  target %p = %p\n", criteria[i].target, &criteria[i] );
[8fc45b7]832                push( criteria[i].target->signal_stack, &criteria[i] );
[97e3296]833        }
834
[8fc45b7]835        waiter.criteria = criteria;
[97e3296]836}
837
[ea7d2b0]838static inline void lock_all( __spinlock_t * locks [], __lock_size_t count ) {
[513daec]839        for( __lock_size_t i = 0; i < count; i++ ) {
[2e9aed4]840                lock( *locks[i] __cfaabi_dbg_ctx2 );
[0c78741]841        }
842}
843
[e84ab3d]844static inline void lock_all( monitor$ * source [], __spinlock_t * /*out*/ locks [], __lock_size_t count ) {
[513daec]845        for( __lock_size_t i = 0; i < count; i++ ) {
[ea7d2b0]846                __spinlock_t * l = &source[i]->lock;
[2e9aed4]847                lock( *l __cfaabi_dbg_ctx2 );
[0c78741]848                if(locks) locks[i] = l;
849        }
850}
851
[ea7d2b0]852static inline void unlock_all( __spinlock_t * locks [], __lock_size_t count ) {
[513daec]853        for( __lock_size_t i = 0; i < count; i++ ) {
[ea7d2b0]854                unlock( *locks[i] );
[0c78741]855        }
856}
857
[e84ab3d]858static inline void unlock_all( monitor$ * locks [], __lock_size_t count ) {
[513daec]859        for( __lock_size_t i = 0; i < count; i++ ) {
[ea7d2b0]860                unlock( locks[i]->lock );
[0c78741]861        }
862}
863
[8fc45b7]864static inline void save(
[e84ab3d]865        monitor$ * ctx [],
[513daec]866        __lock_size_t count,
[ea7d2b0]867        __attribute((unused)) __spinlock_t * locks [],
[8fc45b7]868        unsigned int /*out*/ recursions [],
869        __waitfor_mask_t /*out*/ masks []
870) {
[513daec]871        for( __lock_size_t i = 0; i < count; i++ ) {
[0c78741]872                recursions[i] = ctx[i]->recursion;
[6ff4507]873                masks[i]      = ctx[i]->mask;
[0c78741]874        }
875}
876
[8fc45b7]877static inline void restore(
[e84ab3d]878        monitor$ * ctx [],
[513daec]879        __lock_size_t count,
[ea7d2b0]880        __spinlock_t * locks [],
[8fc45b7]881        unsigned int /*out*/ recursions [],
882        __waitfor_mask_t /*out*/ masks []
883) {
[6ff4507]884        lock_all( locks, count );
[513daec]885        for( __lock_size_t i = 0; i < count; i++ ) {
[0c78741]886                ctx[i]->recursion = recursions[i];
[6ff4507]887                ctx[i]->mask      = masks[i];
[0c78741]888        }
[6ff4507]889        unlock_all( locks, count );
[0c78741]890}
891
892// Function has 2 different behavior
893// 1 - Marks a monitors as being ready to run
894// 2 - Checks if all the monitors are ready to run
895//     if so return the thread to run
[e84ab3d]896static inline thread$ * check_condition( __condition_criterion_t * target ) {
[0c78741]897        __condition_node_t * node = target->owner;
898        unsigned short count = node->count;
899        __condition_criterion_t * criteria = node->criteria;
900
901        bool ready2run = true;
902
903        for(    int i = 0; i < count; i++ ) {
[44264c5]904
[36982fc]905                // __cfaabi_dbg_print_safe( "Checking %p for %p\n", &criteria[i], target );
[0c78741]906                if( &criteria[i] == target ) {
907                        criteria[i].ready = true;
[36982fc]908                        // __cfaabi_dbg_print_safe( "True\n" );
[0c78741]909                }
910
911                ready2run = criteria[i].ready && ready2run;
912        }
913
[504a7dc]914        __cfaabi_dbg_print_safe( "Kernel :  Runing %i (%p)\n", ready2run, ready2run ? (thread*)node->waiting_thread : (thread*)0p );
[121be3e]915        return ready2run ? node->waiting_thread : 0p;
[0c78741]916}
917
[4cedd9f]918static inline void brand_condition( condition & this ) {
[e84ab3d]919        thread$ * thrd = active_thread();
[4cedd9f]920        if( !this.monitors ) {
[169d944]921                // __cfaabi_dbg_print_safe( "Branding\n" );
[121be3e]922                assertf( thrd->monitors.data != 0p, "No current monitor to brand condition %p", thrd->monitors.data );
[4cedd9f]923                this.monitor_count = thrd->monitors.size;
[a933dcf4]924
[e84ab3d]925                this.monitors = (monitor$ **)malloc( this.monitor_count * sizeof( *this.monitors ) );
[4cedd9f]926                for( int i = 0; i < this.monitor_count; i++ ) {
[0cf5b79]927                        this.monitors[i] = thrd->monitors[i];
[a933dcf4]928                }
[0c78741]929        }
930}
931
[e84ab3d]932static inline [thread$ *, int] search_entry_queue( const __waitfor_mask_t & mask, monitor$ * monitors [], __lock_size_t count ) {
[90c4df0]933
[e84ab3d]934        __queue_t(thread$) & entry_queue = monitors[0]->entry_queue;
[90c4df0]935
[be5f0a5]936        #if defined( __CFA_WITH_VERIFY__ )
937                thread$ * last = 0p;
938        #endif
[90c4df0]939        // For each thread in the entry-queue
[e84ab3d]940        for(    thread$ ** thrd_it = &entry_queue.head;
[1b143de]941                (*thrd_it) != 1p;
[be5f0a5]942                thrd_it = &get_next(**thrd_it)
[4cc9b13]943        ) {
[be5f0a5]944                thread$ * curr = *thrd_it;
945
946                /* paranoid */ verifyf( !last || last->user_link.next == curr, "search not making progress, from %p (%p) to %p", last, last->user_link.next, curr );
947                /* paranoid */ verifyf( curr != last, "search not making progress, from %p to %p", last, curr );
948
[90c4df0]949                // For each acceptable check if it matches
[4cc9b13]950                int i = 0;
[0cf5b79]951                __acceptable_t * end   = end  (mask);
952                __acceptable_t * begin = begin(mask);
953                for( __acceptable_t * it = begin; it != end; it++, i++ ) {
[90c4df0]954                        // Check if we have a match
[be5f0a5]955                        if( *it == curr->monitors ) {
[90c4df0]956
957                                // If we have a match return it
958                                // after removeing it from the entry queue
[b18830e]959                                return [remove( entry_queue, thrd_it ), i];
[90c4df0]960                        }
961                }
[be5f0a5]962
963                #if defined( __CFA_WITH_VERIFY__ )
964                        last = curr;
965                #endif
[90c4df0]966        }
967
[b18830e]968        return [0, -1];
969}
970
[fd54fef]971forall(T & | sized( T ))
[59a0bde]972static inline __lock_size_t insert_unique( T * array [], __lock_size_t & size, T * val ) {
[6ff4507]973        if( !val ) return size;
974
[59a0bde]975        for( __lock_size_t i = 0; i <= size; i++) {
[6ff4507]976                if( array[i] == val ) return size;
977        }
978
979        array[size] = val;
980        size = size + 1;
981        return size;
982}
983
[59a0bde]984static inline __lock_size_t count_max( const __waitfor_mask_t & mask ) {
985        __lock_size_t max = 0;
986        for( __lock_size_t i = 0; i < mask.size; i++ ) {
[0cf5b79]987                __acceptable_t & accepted = mask[i];
988                max += accepted.size;
[b18830e]989        }
990        return max;
[97e3296]991}
[b18830e]992
[e84ab3d]993static inline __lock_size_t aggregate( monitor$ * storage [], const __waitfor_mask_t & mask ) {
[59a0bde]994        __lock_size_t size = 0;
995        for( __lock_size_t i = 0; i < mask.size; i++ ) {
[0cf5b79]996                __acceptable_t & accepted = mask[i];
997                __libcfa_small_sort( accepted.data, accepted.size );
998                for( __lock_size_t j = 0; j < accepted.size; j++) {
999                        insert_unique( storage, size, accepted[j] );
[6ff4507]1000                }
[b18830e]1001        }
[6a5be52]1002        // TODO insertion sort instead of this
[de737c8]1003        __libcfa_small_sort( storage, size );
[6ff4507]1004        return size;
[b18830e]1005}
1006
[af67ee1]1007//-----------------------------------------------------------------------------
1008// Enter routine for mutex stmt
1009// Can't be accepted since a mutex stmt is effectively an anonymous routine
1010// Thus we do not need a monitor group
[c18bf9e]1011void lock( monitor$ * this ) libcfa_public {
[af67ee1]1012        thread$ * thrd = active_thread();
1013
1014        // Lock the monitor spinlock
1015        lock( this->lock __cfaabi_dbg_ctx2 );
1016
1017        __cfaabi_dbg_print_safe( "Kernel : %10p Entering mon %p (%p)\n", thrd, this, this->owner);
1018
1019        if( unlikely(0 != (0x1 & (uintptr_t)this->owner)) ) {
1020                abort( "Attempt by thread \"%.256s\" (%p) to access joined monitor %p.", thrd->self_cor.name, thrd, this );
1021        }
1022        else if( !this->owner ) {
1023                // No one has the monitor, just take it
1024                __set_owner( this, thrd );
1025
1026                __cfaabi_dbg_print_safe( "Kernel :  mon is free \n" );
1027        }
1028        else if( this->owner == thrd) {
1029                // We already have the monitor, just note how many times we took it
1030                this->recursion += 1;
1031
1032                __cfaabi_dbg_print_safe( "Kernel :  mon already owned \n" );
1033        }
1034        else {
1035                __cfaabi_dbg_print_safe( "Kernel :  blocking \n" );
1036
1037                // Some one else has the monitor, wait in line for it
[be5f0a5]1038                /* paranoid */ verify( thrd->user_link.next == 0p );
[af67ee1]1039                append( this->entry_queue, thrd );
[be5f0a5]1040                /* paranoid */ verify( thrd->user_link.next == 1p );
[af67ee1]1041
1042                unlock( this->lock );
1043                park();
1044
1045                __cfaabi_dbg_print_safe( "Kernel : %10p Entered  mon %p\n", thrd, this);
1046
1047                /* paranoid */ verifyf( active_thread() == this->owner, "Expected owner to be %p, got %p (r: %i, m: %p)", active_thread(), this->owner, this->recursion, this );
1048                return;
1049        }
1050
1051        __cfaabi_dbg_print_safe( "Kernel : %10p Entered  mon %p\n", thrd, this);
1052
1053        /* paranoid */ verifyf( active_thread() == this->owner, "Expected owner to be %p, got %p (r: %i, m: %p)", active_thread(), this->owner, this->recursion, this );
1054        /* paranoid */ verify( this->lock.lock );
1055
1056        // Release the lock and leave
1057        unlock( this->lock );
1058        return;
1059}
1060
1061// Leave routine for mutex stmt
1062// Is just a wrapper around __leave for the is_lock trait to see
[c18bf9e]1063void unlock( monitor$ * this ) libcfa_public { __leave( this ); }
[af67ee1]1064
[6b0b624]1065// Local Variables: //
1066// mode: c //
1067// tab-width: 4 //
1068// End: //
Note: See TracBrowser for help on using the repository browser.