source: src/libcfa/concurrency/monitor.c @ 35bae526

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsdeferred_resndemanglerenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprnew-envno_listpersistent-indexerpthread-emulationqualifiedEnumresolv-newwith_gc
Last change on this file since 35bae526 was 36982fc, checked in by Thierry Delisle <tdelisle@…>, 7 years ago

Renamed internal stuff to cfaabi_...

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