source: libcfa/src/concurrency/monitor.cfa @ 4cae032

ADTarm-ehast-experimentalenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since 4cae032 was 2026bb6, checked in by Thierry Delisle <tdelisle@…>, 5 years ago

More robust fix for optionally linking threads

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