source: src/libcfa/concurrency/monitor.c @ 549c006

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

Implemented out of order waitfor for destructors

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