source: src/libcfa/concurrency/monitor.c @ 2e9aed4

aaron-thesisarm-ehcleanup-dtorsdeferred_resndemanglerjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprnew-envno_listpersistent-indexerresolv-newwith_gc
Last change on this file since 2e9aed4 was 2e9aed4, checked in by Thierry Delisle <tdelisle@…>, 4 years ago

Fixed non-preemptive locks

  • Property mode set to 100644
File size: 29.0 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 : Mon Jul 31 14:59:05 2017
13// Update Count     : 3
14//
15
16#include "monitor"
17
18#include <stdlib>
19#include <inttypes.h>
20
21#include "kernel_private.h"
22
23#include "bits/algorithms.h"
24
25//-----------------------------------------------------------------------------
26// Forward declarations
27static inline void set_owner ( monitor_desc * this, thread_desc * owner );
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 );
30static inline void reset_mask( monitor_desc * this );
31
32static inline thread_desc * next_thread( monitor_desc * this );
33static inline bool is_accepted( monitor_desc * this, const __monitor_group_t & monitors );
34
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 );
38static inline void unlock_all( monitor_desc * locks [], __lock_size_t count );
39
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 [] );
42
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 [] );
45
46static inline thread_desc *        check_condition   ( __condition_criterion_t * );
47static inline void                 brand_condition   ( condition & );
48static inline [thread_desc *, int] search_entry_queue( const __waitfor_mask_t &, monitor_desc * monitors [], __lock_size_t count );
49
50forall(dtype T | sized( T ))
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 );
54
55//-----------------------------------------------------------------------------
56// Useful defines
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                            */ \
60        init( count, monitors, waiter, criteria );                /* Link everything together                                                            */ \
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                            */ \
65        init_push( count, monitors, waiter, criteria );           /* Link everything together and push it to the AS-Stack                                */ \
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                                                          */ \
69        __lock_size_t count = cnt;                                /* Save the count to a local variable                                                  */ \
70        unsigned int recursions[ count ];                         /* Save the current recursion levels to restore them later                             */ \
71        __waitfor_mask_t masks [ count ];                         /* Save the current waitfor masks to restore them later                                */ \
72        __spinlock_t *   locks [ count ];                         /* We need to pass-in an array of locks to BlockInternal                               */ \
73
74#define monitor_save    save   ( monitors, count, locks, recursions, masks )
75#define monitor_restore restore( monitors, count, locks, recursions, masks )
76
77
78//-----------------------------------------------------------------------------
79// Enter/Leave routines
80
81
82extern "C" {
83        // Enter single monitor
84        static void __enter_monitor_desc( monitor_desc * this, const __monitor_group_t & group ) {
85                // Lock the monitor spinlock
86                lock( this->lock __cfaabi_dbg_ctx2 );
87                thread_desc * thrd = this_thread;
88
89                verify( disable_preempt_count > 0 );
90
91                __cfaabi_dbg_print_safe("Kernel : %10p Entering mon %p (%p)\n", thrd, this, this->owner);
92
93                if( !this->owner ) {
94                        // No one has the monitor, just take it
95                        set_owner( this, thrd );
96
97                        __cfaabi_dbg_print_safe("Kernel :  mon is free \n");
98                }
99                else if( this->owner == thrd) {
100                        // We already have the monitor, just note how many times we took it
101                        this->recursion += 1;
102
103                        __cfaabi_dbg_print_safe("Kernel :  mon already owned \n");
104                }
105                else if( is_accepted( this, group) ) {
106                        // Some one was waiting for us, enter
107                        set_owner( this, thrd );
108
109                        // Reset mask
110                        reset_mask( this );
111
112                        __cfaabi_dbg_print_safe("Kernel :  mon accepts \n");
113                }
114                else {
115                        __cfaabi_dbg_print_safe("Kernel :  blocking \n");
116
117                        // Some one else has the monitor, wait in line for it
118                        append( this->entry_queue, thrd );
119
120                        verify( disable_preempt_count > 0 );
121
122                        BlockInternal( &this->lock );
123
124                        __cfaabi_dbg_print_safe("Kernel : %10p Entered  mon %p\n", thrd, this);
125
126                        // BlockInternal will unlock spinlock, no need to unlock ourselves
127                        return;
128                }
129
130                __cfaabi_dbg_print_safe("Kernel : %10p Entered  mon %p\n", thrd, this);
131
132                // Release the lock and leave
133                unlock( this->lock );
134                return;
135        }
136
137        static void __enter_monitor_dtor( monitor_desc * this, fptr_t func ) {
138                // Lock the monitor spinlock
139                lock( this->lock __cfaabi_dbg_ctx2 );
140                thread_desc * thrd = 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                        abortf("Attempt to destroy monitor %p by thread \"%.256s\" (%p) in nested mutex.");
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( this_thread, 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( this_thread, 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", this_thread, this, this->owner);
206
207                verifyf( this_thread == this->owner, "Expected owner to be %p, got %p (r: %i, m: %p)", 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( this_thread != this->owner ) {
234                                abortf("Destroyed monitor %p has inconsistent owner, expected %p got %p.\n", this, this_thread, this->owner);
235                        }
236                        if( this->recursion != 1 ) {
237                                abortf("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) { abortf("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        // Store current array
296        this.m = m;
297        this.count = count;
298
299        // Sort monitors based on address -> TODO use a sort specialized for small numbers
300        __libcfa_small_sort(this.m, count);
301
302        // Save previous thread context
303        this.prev = this_thread->monitors;
304
305        // Update thread context (needed for conditions)
306        (this_thread->monitors){m, count, func};
307
308        // __cfaabi_dbg_print_safe("MGUARD : enter %d\n", count);
309
310        // Enter the monitors in order
311        __monitor_group_t group = {this.m, this.count, func};
312        enter( group );
313
314        // __cfaabi_dbg_print_safe("MGUARD : entered\n");
315}
316
317
318// Dtor for monitor guard
319void ^?{}( monitor_guard_t & this ) {
320        // __cfaabi_dbg_print_safe("MGUARD : leaving %d\n", this.count);
321
322        // Leave the monitors in order
323        leave( this.m, this.count );
324
325        // __cfaabi_dbg_print_safe("MGUARD : left\n");
326
327        // Restore thread context
328        this_thread->monitors = this.prev;
329}
330
331// Ctor for monitor guard
332// Sorts monitors before entering
333void ?{}( monitor_dtor_guard_t & this, monitor_desc * m [], fptr_t func ) {
334        // Store current array
335        this.m = *m;
336
337        // Save previous thread context
338        this.prev = this_thread->monitors;
339
340        // Update thread context (needed for conditions)
341        (this_thread->monitors){m, 1, func};
342
343        __enter_monitor_dtor( this.m, func );
344}
345
346// Dtor for monitor guard
347void ^?{}( monitor_dtor_guard_t & this ) {
348        // Leave the monitors in order
349        __leave_dtor_monitor_desc( this.m );
350
351        // Restore thread context
352        this_thread->monitors = this.prev;
353}
354
355//-----------------------------------------------------------------------------
356// Internal scheduling types
357void ?{}(__condition_node_t & this, thread_desc * waiting_thread, __lock_size_t count, uintptr_t user_info ) {
358        this.waiting_thread = waiting_thread;
359        this.count = count;
360        this.next = NULL;
361        this.user_info = user_info;
362}
363
364void ?{}(__condition_criterion_t & this ) {
365        this.ready  = false;
366        this.target = NULL;
367        this.owner  = NULL;
368        this.next   = NULL;
369}
370
371void ?{}(__condition_criterion_t & this, monitor_desc * target, __condition_node_t & owner ) {
372        this.ready  = false;
373        this.target = target;
374        this.owner  = &owner;
375        this.next   = NULL;
376}
377
378//-----------------------------------------------------------------------------
379// Internal scheduling
380void wait( condition & this, uintptr_t user_info = 0 ) {
381        brand_condition( this );
382
383        // Check that everything is as expected
384        assertf( this.monitors != NULL, "Waiting with no monitors (%p)", this.monitors );
385        verifyf( this.monitor_count != 0, "Waiting with 0 monitors (%"PRIiFAST16")", this.monitor_count );
386        verifyf( this.monitor_count < 32u, "Excessive monitor count (%"PRIiFAST16")", this.monitor_count );
387
388        // Create storage for monitor context
389        monitor_ctx( this.monitors, this.monitor_count );
390
391        // Create the node specific to this wait operation
392        wait_ctx( this_thread, user_info );
393
394        // Append the current wait operation to the ones already queued on the condition
395        // We don't need locks for that since conditions must always be waited on inside monitor mutual exclusion
396        append( this.blocked, &waiter );
397
398        verify( disable_preempt_count == 0 );
399
400        // Lock all monitors (aggregates the locks as well)
401        lock_all( monitors, locks, count );
402
403        // verifyf( disable_preempt_count == count, "Got %d, expected %d\n", disable_preempt_count, count );
404        if(disable_preempt_count != count) { __cfaabi_dbg_print_buffer_decl("----------Gonna crash\n"); }
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 = this_thread;
437                if ( this.monitor_count != this_thrd->monitors.size ) {
438                        abortf( "Signal on condition %p made with different number of monitor(s), expected %i got %i", &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                                abortf( "Signal on condition %p made with different monitor, expected %p got %i", &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        verify( disable_preempt_count == 0 );
480
481        // Lock all monitors (aggregates the locks them as well)
482        lock_all( monitors, locks, count );
483
484        // verify( disable_preempt_count == count );
485        if(disable_preempt_count != count) { __cfaabi_dbg_print_buffer_decl("----------Gonna crash\n"); }
486
487
488        // Create the node specific to this wait operation
489        wait_ctx_primed( this_thread, 0 )
490
491        //save contexts
492        monitor_save;
493
494        //Find the thread to run
495        thread_desc * signallee = pop_head( this.blocked )->waiting_thread;
496        set_owner( monitors, count, signallee );
497
498        __cfaabi_dbg_print_buffer_decl( "Kernel : signal_block condition %p (s: %p)\n", &this, signallee );
499
500        //Everything is ready to go to sleep
501        BlockInternal( locks, count, &signallee, 1 );
502
503
504        // WE WOKE UP
505
506
507        __cfaabi_dbg_print_buffer_local( "Kernel :   signal_block returned\n" );
508
509        //We are back, restore the masks and recursions
510        monitor_restore;
511
512        return true;
513}
514
515// Access the user_info of the thread waiting at the front of the queue
516uintptr_t front( condition & this ) {
517        verifyf( !is_empty(this),
518                "Attempt to access user data on an empty condition.\n"
519                "Possible cause is not checking if the condition is empty before reading stored data."
520        );
521        return ((typeof(this.blocked.head))this.blocked.head)->user_info;
522}
523
524//-----------------------------------------------------------------------------
525// External scheduling
526// cases to handle :
527//      - target already there :
528//              block and wake
529//      - dtor already there
530//              put thread on signaller stack
531//      - non-blocking
532//              return else
533//      - timeout
534//              return timeout
535//      - block
536//              setup mask
537//              block
538void __waitfor_internal( const __waitfor_mask_t & mask, int duration ) {
539        // This statment doesn't have a contiguous list of monitors...
540        // Create one!
541        __lock_size_t max = count_max( mask );
542        monitor_desc * mon_storage[max];
543        __builtin_memset( mon_storage, 0, sizeof( mon_storage ) );
544        __lock_size_t actual_count = aggregate( mon_storage, mask );
545
546        __cfaabi_dbg_print_buffer_decl( "Kernel : waitfor %"PRIdFAST16" (s: %"PRIdFAST16", m: %"PRIdFAST16")\n", actual_count, mask.size, (__lock_size_t)max);
547
548        if(actual_count == 0) return;
549
550        __cfaabi_dbg_print_buffer_local( "Kernel : waitfor internal proceeding\n");
551
552        // Create storage for monitor context
553        monitor_ctx( mon_storage, actual_count );
554
555        // Lock all monitors (aggregates the locks as well)
556        lock_all( monitors, locks, count );
557
558        {
559                // Check if the entry queue
560                thread_desc * next; int index;
561                [next, index] = search_entry_queue( mask, monitors, count );
562
563                if( next ) {
564                        *mask.accepted = index;
565                        __acceptable_t& accepted = mask[index];
566                        if( accepted.is_dtor ) {
567                                __cfaabi_dbg_print_buffer_local( "Kernel : dtor already there\n");
568                                verifyf( accepted.size == 1,  "ERROR: Accepted dtor has more than 1 mutex parameter." );
569
570                                monitor_desc * mon2dtor = accepted[0];
571                                verifyf( mon2dtor->dtor_node, "ERROR: Accepted monitor has no dtor_node." );
572
573                                __condition_criterion_t * dtor_crit = mon2dtor->dtor_node->criteria;
574                                push( mon2dtor->signal_stack, dtor_crit );
575
576                                unlock_all( locks, count );
577                        }
578                        else {
579                                __cfaabi_dbg_print_buffer_local( "Kernel : thread present, baton-passing\n");
580
581                                // Create the node specific to this wait operation
582                                wait_ctx_primed( this_thread, 0 );
583
584                                // Save monitor states
585                                monitor_save;
586
587                                __cfaabi_dbg_print_buffer_local( "Kernel :  baton of %"PRIdFAST16" monitors : ", count );
588                                #ifdef __CFA_DEBUG_PRINT__
589                                        for( int i = 0; i < count; i++) {
590                                                __cfaabi_dbg_print_buffer_local( "%p %p ", monitors[i], monitors[i]->signal_stack.top );
591                                        }
592                                #endif
593                                __cfaabi_dbg_print_buffer_local( "\n");
594
595                                // Set the owners to be the next thread
596                                set_owner( monitors, count, next );
597
598                                // Everything is ready to go to sleep
599                                BlockInternal( locks, count, &next, 1 );
600
601                                // We are back, restore the owners and recursions
602                                monitor_restore;
603
604                                __cfaabi_dbg_print_buffer_local( "Kernel : thread present, returned\n");
605                        }
606
607                        __cfaabi_dbg_print_buffer_local( "Kernel : accepted %d\n", *mask.accepted);
608                        return;
609                }
610        }
611
612
613        if( duration == 0 ) {
614                __cfaabi_dbg_print_buffer_local( "Kernel : non-blocking, exiting\n");
615
616                unlock_all( locks, count );
617
618                __cfaabi_dbg_print_buffer_local( "Kernel : accepted %d\n", *mask.accepted);
619                return;
620        }
621
622
623        verifyf( duration < 0, "Timeout on waitfor statments not supported yet.");
624
625        __cfaabi_dbg_print_buffer_local( "Kernel : blocking waitfor\n");
626
627        // Create the node specific to this wait operation
628        wait_ctx_primed( this_thread, 0 );
629
630        monitor_save;
631        set_mask( monitors, count, mask );
632
633        for( __lock_size_t i = 0; i < count; i++) {
634                verify( monitors[i]->owner == this_thread );
635        }
636
637        //Everything is ready to go to sleep
638        BlockInternal( locks, count );
639
640
641        // WE WOKE UP
642
643
644        //We are back, restore the masks and recursions
645        monitor_restore;
646
647        __cfaabi_dbg_print_buffer_local( "Kernel : exiting\n");
648
649        __cfaabi_dbg_print_buffer_local( "Kernel : accepted %d\n", *mask.accepted);
650}
651
652//-----------------------------------------------------------------------------
653// Utilities
654
655static inline void set_owner( monitor_desc * this, thread_desc * owner ) {
656        // __cfaabi_dbg_print_safe("Kernal :   Setting owner of %p to %p ( was %p)\n", this, owner, this->owner );
657
658        //Pass the monitor appropriately
659        this->owner = owner;
660
661        //We are passing the monitor to someone else, which means recursion level is not 0
662        this->recursion = owner ? 1 : 0;
663}
664
665static inline void set_owner( monitor_desc * monitors [], __lock_size_t count, thread_desc * owner ) {
666        monitors[0]->owner     = owner;
667        monitors[0]->recursion = 1;
668        for( __lock_size_t i = 1; i < count; i++ ) {
669                monitors[i]->owner     = owner;
670                monitors[i]->recursion = 0;
671        }
672}
673
674static inline void set_mask( monitor_desc * storage [], __lock_size_t count, const __waitfor_mask_t & mask ) {
675        for( __lock_size_t i = 0; i < count; i++) {
676                storage[i]->mask = mask;
677        }
678}
679
680static inline void reset_mask( monitor_desc * this ) {
681        this->mask.accepted = NULL;
682        this->mask.data = NULL;
683        this->mask.size = 0;
684}
685
686static inline thread_desc * next_thread( monitor_desc * this ) {
687        //Check the signaller stack
688        __cfaabi_dbg_print_safe("Kernel :  mon %p AS-stack top %p\n", this, this->signal_stack.top);
689        __condition_criterion_t * urgent = pop( this->signal_stack );
690        if( urgent ) {
691                //The signaller stack is not empty,
692                //regardless of if we are ready to baton pass,
693                //we need to set the monitor as in use
694                set_owner( this,  urgent->owner->waiting_thread );
695
696                return check_condition( urgent );
697        }
698
699        // No signaller thread
700        // Get the next thread in the entry_queue
701        thread_desc * new_owner = pop_head( this->entry_queue );
702        set_owner( this, new_owner );
703
704        return new_owner;
705}
706
707static inline bool is_accepted( monitor_desc * this, const __monitor_group_t & group ) {
708        __acceptable_t * it = this->mask.data; // Optim
709        __lock_size_t count = this->mask.size;
710
711        // Check if there are any acceptable functions
712        if( !it ) return false;
713
714        // If this isn't the first monitor to test this, there is no reason to repeat the test.
715        if( this != group[0] ) return group[0]->mask.accepted >= 0;
716
717        // For all acceptable functions check if this is the current function.
718        for( __lock_size_t i = 0; i < count; i++, it++ ) {
719                if( *it == group ) {
720                        *this->mask.accepted = i;
721                        return true;
722                }
723        }
724
725        // No function matched
726        return false;
727}
728
729static inline void init( __lock_size_t count, monitor_desc * monitors [], __condition_node_t & waiter, __condition_criterion_t criteria [] ) {
730        for( __lock_size_t i = 0; i < count; i++) {
731                (criteria[i]){ monitors[i], waiter };
732        }
733
734        waiter.criteria = criteria;
735}
736
737static inline void init_push( __lock_size_t count, monitor_desc * monitors [], __condition_node_t & waiter, __condition_criterion_t criteria [] ) {
738        for( __lock_size_t i = 0; i < count; i++) {
739                (criteria[i]){ monitors[i], waiter };
740                __cfaabi_dbg_print_safe( "Kernel :  target %p = %p\n", criteria[i].target, &criteria[i] );
741                push( criteria[i].target->signal_stack, &criteria[i] );
742        }
743
744        waiter.criteria = criteria;
745}
746
747static inline void lock_all( __spinlock_t * locks [], __lock_size_t count ) {
748        for( __lock_size_t i = 0; i < count; i++ ) {
749                lock( *locks[i] __cfaabi_dbg_ctx2 );
750        }
751}
752
753static inline void lock_all( monitor_desc * source [], __spinlock_t * /*out*/ locks [], __lock_size_t count ) {
754        for( __lock_size_t i = 0; i < count; i++ ) {
755                __spinlock_t * l = &source[i]->lock;
756                lock( *l __cfaabi_dbg_ctx2 );
757                if(locks) locks[i] = l;
758        }
759}
760
761static inline void unlock_all( __spinlock_t * locks [], __lock_size_t count ) {
762        for( __lock_size_t i = 0; i < count; i++ ) {
763                unlock( *locks[i] );
764        }
765}
766
767static inline void unlock_all( monitor_desc * locks [], __lock_size_t count ) {
768        for( __lock_size_t i = 0; i < count; i++ ) {
769                unlock( locks[i]->lock );
770        }
771}
772
773static inline void save(
774        monitor_desc * ctx [],
775        __lock_size_t count,
776        __attribute((unused)) __spinlock_t * locks [],
777        unsigned int /*out*/ recursions [],
778        __waitfor_mask_t /*out*/ masks []
779) {
780        for( __lock_size_t i = 0; i < count; i++ ) {
781                recursions[i] = ctx[i]->recursion;
782                masks[i]      = ctx[i]->mask;
783        }
784}
785
786static inline void restore(
787        monitor_desc * ctx [],
788        __lock_size_t count,
789        __spinlock_t * locks [],
790        unsigned int /*out*/ recursions [],
791        __waitfor_mask_t /*out*/ masks []
792) {
793        lock_all( locks, count );
794        for( __lock_size_t i = 0; i < count; i++ ) {
795                ctx[i]->recursion = recursions[i];
796                ctx[i]->mask      = masks[i];
797        }
798        unlock_all( locks, count );
799}
800
801// Function has 2 different behavior
802// 1 - Marks a monitors as being ready to run
803// 2 - Checks if all the monitors are ready to run
804//     if so return the thread to run
805static inline thread_desc * check_condition( __condition_criterion_t * target ) {
806        __condition_node_t * node = target->owner;
807        unsigned short count = node->count;
808        __condition_criterion_t * criteria = node->criteria;
809
810        bool ready2run = true;
811
812        for(    int i = 0; i < count; i++ ) {
813
814                // __cfaabi_dbg_print_safe( "Checking %p for %p\n", &criteria[i], target );
815                if( &criteria[i] == target ) {
816                        criteria[i].ready = true;
817                        // __cfaabi_dbg_print_safe( "True\n" );
818                }
819
820                ready2run = criteria[i].ready && ready2run;
821        }
822
823        __cfaabi_dbg_print_safe( "Kernel :  Runing %i (%p)\n", ready2run, ready2run ? node->waiting_thread : NULL );
824        return ready2run ? node->waiting_thread : NULL;
825}
826
827static inline void brand_condition( condition & this ) {
828        thread_desc * thrd = this_thread;
829        if( !this.monitors ) {
830                // __cfaabi_dbg_print_safe("Branding\n");
831                assertf( thrd->monitors.data != NULL, "No current monitor to brand condition %p", thrd->monitors.data );
832                this.monitor_count = thrd->monitors.size;
833
834                this.monitors = (monitor_desc **)malloc( this.monitor_count * sizeof( *this.monitors ) );
835                for( int i = 0; i < this.monitor_count; i++ ) {
836                        this.monitors[i] = thrd->monitors[i];
837                }
838        }
839}
840
841static inline [thread_desc *, int] search_entry_queue( const __waitfor_mask_t & mask, monitor_desc * monitors [], __lock_size_t count ) {
842
843        __queue_t(thread_desc) & entry_queue = monitors[0]->entry_queue;
844
845        // For each thread in the entry-queue
846        for(    thread_desc ** thrd_it = &entry_queue.head;
847                *thrd_it;
848                thrd_it = &(*thrd_it)->next
849        ) {
850                // For each acceptable check if it matches
851                int i = 0;
852                __acceptable_t * end   = end  (mask);
853                __acceptable_t * begin = begin(mask);
854                for( __acceptable_t * it = begin; it != end; it++, i++ ) {
855                        // Check if we have a match
856                        if( *it == (*thrd_it)->monitors ) {
857
858                                // If we have a match return it
859                                // after removeing it from the entry queue
860                                return [remove( entry_queue, thrd_it ), i];
861                        }
862                }
863        }
864
865        return [0, -1];
866}
867
868forall(dtype T | sized( T ))
869static inline __lock_size_t insert_unique( T * array [], __lock_size_t & size, T * val ) {
870        if( !val ) return size;
871
872        for( __lock_size_t i = 0; i <= size; i++) {
873                if( array[i] == val ) return size;
874        }
875
876        array[size] = val;
877        size = size + 1;
878        return size;
879}
880
881static inline __lock_size_t count_max( const __waitfor_mask_t & mask ) {
882        __lock_size_t max = 0;
883        for( __lock_size_t i = 0; i < mask.size; i++ ) {
884                __acceptable_t & accepted = mask[i];
885                max += accepted.size;
886        }
887        return max;
888}
889
890static inline __lock_size_t aggregate( monitor_desc * storage [], const __waitfor_mask_t & mask ) {
891        __lock_size_t size = 0;
892        for( __lock_size_t i = 0; i < mask.size; i++ ) {
893                __acceptable_t & accepted = mask[i];
894                __libcfa_small_sort( accepted.data, accepted.size );
895                for( __lock_size_t j = 0; j < accepted.size; j++) {
896                        insert_unique( storage, size, accepted[j] );
897                }
898        }
899        // TODO insertion sort instead of this
900        __libcfa_small_sort( storage, size );
901        return size;
902}
903
904// Local Variables: //
905// mode: c //
906// tab-width: 4 //
907// End: //
Note: See TracBrowser for help on using the repository browser.