source: src/libcfa/concurrency/monitor.c @ f4a6101

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 f4a6101 was 523232d, checked in by Rob Schluntz <rschlunt@…>, 6 years ago

Fix warnings when printing int_fast16_t

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