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

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 fd062a66 was d56ca354, checked in by Thierry Delisle <tdelisle@…>, 6 years ago

Merge branch 'master' of plg.uwaterloo.ca:software/cfa/cfa-cc

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