source: src/libcfa/concurrency/monitor.c @ 513daec

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsdeferred_resndemanglerenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprnew-envno_listpersistent-indexerpthread-emulationqualifiedEnumresolv-newwith_gc
Last change on this file since 513daec was 513daec, checked in by Thierry Delisle <tdelisle@…>, 8 years ago

started using int_fast16_t for counts of monitors

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