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

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

Added new sort function for monitors

  • Property mode set to 100644
File size: 28.8 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, short count, thread_desc * owner );
29static inline void set_mask  ( monitor_desc ** storage, short 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, unsigned short count );
36static inline void lock_all( monitor_desc ** source, spinlock ** /*out*/ locks, unsigned short count );
37static inline void unlock_all( spinlock ** locks, unsigned short count );
38static inline void unlock_all( monitor_desc ** locks, unsigned short count );
39
40static inline void save   ( monitor_desc ** ctx, short count, spinlock ** locks, unsigned int * /*out*/ recursions, __waitfor_mask_t * /*out*/ masks );
41static inline void restore( monitor_desc ** ctx, short count, spinlock ** locks, unsigned int * /*in */ recursions, __waitfor_mask_t * /*in */ masks );
42
43static inline void init     ( int count, monitor_desc ** monitors, __condition_node_t * waiter, __condition_criterion_t * criteria );
44static inline void init_push( int 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
333// Ctor for monitor guard
334// Sorts monitors before entering
335void ?{}( monitor_dtor_guard_t & this, monitor_desc ** m, fptr_t func ) {
336        // Store current array
337        this.m = *m;
338
339        // Save previous thread context
340        this.prev_mntrs = this_thread->monitors.list;
341        this.prev_count = this_thread->monitors.size;
342        this.prev_func  = this_thread->monitors.func;
343
344        // Update thread context (needed for conditions)
345        this_thread->monitors.list = m;
346        this_thread->monitors.size = 1;
347        this_thread->monitors.func = func;
348
349        __enter_monitor_dtor( this.m, func );
350}
351
352
353// Dtor for monitor guard
354void ^?{}( monitor_dtor_guard_t & this ) {
355        // Leave the monitors in order
356        __leave_dtor_monitor_desc( this.m );
357
358        // Restore thread context
359        this_thread->monitors.list = this.prev_mntrs;
360        this_thread->monitors.size = this.prev_count;
361        this_thread->monitors.func = this.prev_func;
362}
363
364//-----------------------------------------------------------------------------
365// Internal scheduling types
366void ?{}(__condition_node_t & this, thread_desc * waiting_thread, unsigned short count, uintptr_t user_info ) {
367        this.waiting_thread = waiting_thread;
368        this.count = count;
369        this.next = NULL;
370        this.user_info = user_info;
371}
372
373void ?{}(__condition_criterion_t & this ) {
374        this.ready  = false;
375        this.target = NULL;
376        this.owner  = NULL;
377        this.next   = NULL;
378}
379
380void ?{}(__condition_criterion_t & this, monitor_desc * target, __condition_node_t * owner ) {
381        this.ready  = false;
382        this.target = target;
383        this.owner  = owner;
384        this.next   = NULL;
385}
386
387//-----------------------------------------------------------------------------
388// Internal scheduling
389void wait( condition * this, uintptr_t user_info = 0 ) {
390        brand_condition( this );
391
392        // Check that everything is as expected
393        assertf( this->monitors != NULL, "Waiting with no monitors (%p)", this->monitors );
394        verifyf( this->monitor_count != 0, "Waiting with 0 monitors (%i)", this->monitor_count );
395        verifyf( this->monitor_count < 32u, "Excessive monitor count (%i)", this->monitor_count );
396
397        // Create storage for monitor context
398        monitor_ctx( this->monitors, this->monitor_count );
399
400        // Create the node specific to this wait operation
401        wait_ctx( this_thread, user_info );
402
403        // Append the current wait operation to the ones already queued on the condition
404        // We don't need locks for that since conditions must always be waited on inside monitor mutual exclusion
405        append( &this->blocked, &waiter );
406
407        // Lock all monitors (aggregates the locks as well)
408        lock_all( monitors, locks, count );
409
410        // Find the next thread(s) to run
411        short thread_count = 0;
412        thread_desc * threads[ count ];
413        __builtin_memset( threads, 0, sizeof( threads ) );
414
415        // Save monitor states
416        monitor_save;
417
418        // Remove any duplicate threads
419        for( int i = 0; i < count; i++) {
420                thread_desc * new_owner = next_thread( monitors[i] );
421                insert_unique( threads, thread_count, new_owner );
422        }
423
424        // Everything is ready to go to sleep
425        BlockInternal( locks, count, threads, thread_count );
426
427        // We are back, restore the owners and recursions
428        monitor_restore;
429}
430
431bool signal( condition * this ) {
432        if( is_empty( this ) ) { return false; }
433
434        //Check that everything is as expected
435        verify( this->monitors );
436        verify( this->monitor_count != 0 );
437
438        //Some more checking in debug
439        LIB_DEBUG_DO(
440                thread_desc * this_thrd = this_thread;
441                if ( this->monitor_count != this_thrd->monitors.size ) {
442                        abortf( "Signal on condition %p made with different number of monitor(s), expected %i got %i", this, this->monitor_count, this_thrd->monitors.size );
443                }
444
445                for(int i = 0; i < this->monitor_count; i++) {
446                        if ( this->monitors[i] != this_thrd->monitors.list[i] ) {
447                                abortf( "Signal on condition %p made with different monitor, expected %p got %i", this, this->monitors[i], this_thrd->monitors.list[i] );
448                        }
449                }
450        );
451
452        unsigned short count = this->monitor_count;
453
454        // Lock all monitors
455        lock_all( this->monitors, NULL, count );
456
457        //Pop the head of the waiting queue
458        __condition_node_t * node = pop_head( &this->blocked );
459
460        //Add the thread to the proper AS stack
461        for(int i = 0; i < count; i++) {
462                __condition_criterion_t * crit = &node->criteria[i];
463                assert( !crit->ready );
464                push( &crit->target->signal_stack, crit );
465        }
466
467        //Release
468        unlock_all( this->monitors, count );
469
470        return true;
471}
472
473bool signal_block( condition * this ) {
474        if( !this->blocked.head ) { return false; }
475
476        //Check that everything is as expected
477        verifyf( this->monitors != NULL, "Waiting with no monitors (%p)", this->monitors );
478        verifyf( this->monitor_count != 0, "Waiting with 0 monitors (%i)", this->monitor_count );
479
480        // Create storage for monitor context
481        monitor_ctx( this->monitors, this->monitor_count );
482
483        // Lock all monitors (aggregates the locks them as well)
484        lock_all( monitors, locks, count );
485
486        // Create the node specific to this wait operation
487        wait_ctx_primed( this_thread, 0 )
488
489        //save contexts
490        monitor_save;
491
492        //Find the thread to run
493        thread_desc * signallee = pop_head( &this->blocked )->waiting_thread;
494        set_owner( monitors, count, signallee );
495
496        LIB_DEBUG_PRINT_BUFFER_DECL( "Kernel : signal_block condition %p (s: %p)\n", this, signallee );
497
498        //Everything is ready to go to sleep
499        BlockInternal( locks, count, &signallee, 1 );
500
501
502        // WE WOKE UP
503
504
505        LIB_DEBUG_PRINT_BUFFER_LOCAL( "Kernel :   signal_block returned\n" );
506
507        //We are back, restore the masks and recursions
508        monitor_restore;
509
510        return true;
511}
512
513// Access the user_info of the thread waiting at the front of the queue
514uintptr_t front( condition * this ) {
515        verifyf( !is_empty(this),
516                "Attempt to access user data on an empty condition.\n"
517                "Possible cause is not checking if the condition is empty before reading stored data."
518        );
519        return this->blocked.head->user_info;
520}
521
522//-----------------------------------------------------------------------------
523// External scheduling
524// cases to handle :
525//      - target already there :
526//              block and wake
527//      - dtor already there
528//              put thread on signaller stack
529//      - non-blocking
530//              return else
531//      - timeout
532//              return timeout
533//      - block
534//              setup mask
535//              block
536void __waitfor_internal( const __waitfor_mask_t & mask, int duration ) {
537        // This statment doesn't have a contiguous list of monitors...
538        // Create one!
539        short max = count_max( mask );
540        monitor_desc * mon_storage[max];
541        __builtin_memset( mon_storage, 0, sizeof( mon_storage ) );
542        short actual_count = aggregate( mon_storage, mask );
543
544        LIB_DEBUG_PRINT_BUFFER_DECL( "Kernel : waitfor %d (s: %d, m: %d)\n", actual_count, mask.size, (short)max);
545
546        if(actual_count == 0) return;
547
548        LIB_DEBUG_PRINT_BUFFER_LOCAL( "Kernel : waitfor internal proceeding\n");
549
550        // Create storage for monitor context
551        monitor_ctx( mon_storage, actual_count );
552
553        // Lock all monitors (aggregates the locks as well)
554        lock_all( monitors, locks, count );
555
556        {
557                // Check if the entry queue
558                thread_desc * next; int index;
559                [next, index] = search_entry_queue( mask, monitors, count );
560
561                if( next ) {
562                        *mask.accepted = index;
563                        if( mask.clauses[index].is_dtor ) {
564                                LIB_DEBUG_PRINT_BUFFER_LOCAL( "Kernel : dtor already there\n");
565                                verifyf( mask.clauses[index].size == 1        , "ERROR: Accepted dtor has more than 1 mutex parameter." );
566
567                                monitor_desc * mon2dtor = mask.clauses[index].list[0];
568                                verifyf( mon2dtor->dtor_node, "ERROR: Accepted monitor has no dtor_node." );
569
570                                __condition_criterion_t * dtor_crit = mon2dtor->dtor_node->criteria;
571                                push( &mon2dtor->signal_stack, dtor_crit );
572
573                                unlock_all( locks, count );
574                        }
575                        else {
576                                LIB_DEBUG_PRINT_BUFFER_LOCAL( "Kernel : thread present, baton-passing\n");
577
578                                // Create the node specific to this wait operation
579                                wait_ctx_primed( this_thread, 0 );
580
581                                // Save monitor states
582                                monitor_save;
583
584                                LIB_DEBUG_PRINT_BUFFER_LOCAL( "Kernel :  baton of %d monitors : ", count );
585                                #ifdef __CFA_DEBUG_PRINT__
586                                        for( int i = 0; i < count; i++) {
587                                                LIB_DEBUG_PRINT_BUFFER_LOCAL( "%p %p ", monitors[i], monitors[i]->signal_stack.top );
588                                        }
589                                #endif
590                                LIB_DEBUG_PRINT_BUFFER_LOCAL( "\n");
591
592                                // Set the owners to be the next thread
593                                set_owner( monitors, count, next );
594
595                                // Everything is ready to go to sleep
596                                BlockInternal( locks, count, &next, 1 );
597
598                                // We are back, restore the owners and recursions
599                                monitor_restore;
600
601                                LIB_DEBUG_PRINT_BUFFER_LOCAL( "Kernel : thread present, returned\n");
602                        }
603
604                        LIB_DEBUG_PRINT_BUFFER_LOCAL( "Kernel : accepted %d\n", *mask.accepted);
605
606                        return;
607                }
608        }
609
610
611        if( duration == 0 ) {
612                LIB_DEBUG_PRINT_BUFFER_LOCAL( "Kernel : non-blocking, exiting\n");
613
614                unlock_all( locks, count );
615
616                LIB_DEBUG_PRINT_BUFFER_LOCAL( "Kernel : accepted %d\n", *mask.accepted);
617                return;
618        }
619
620
621        verifyf( duration < 0, "Timeout on waitfor statments not supported yet.");
622
623        LIB_DEBUG_PRINT_BUFFER_LOCAL( "Kernel : blocking waitfor\n");
624
625        // Create the node specific to this wait operation
626        wait_ctx_primed( this_thread, 0 );
627
628        monitor_save;
629        set_mask( monitors, count, mask );
630
631        for(int i = 0; i < count; i++) {
632                verify( monitors[i]->owner == this_thread );
633        }
634
635        //Everything is ready to go to sleep
636        BlockInternal( locks, count );
637
638
639        // WE WOKE UP
640
641
642        //We are back, restore the masks and recursions
643        monitor_restore;
644
645        LIB_DEBUG_PRINT_BUFFER_LOCAL( "Kernel : exiting\n");
646
647        LIB_DEBUG_PRINT_BUFFER_LOCAL( "Kernel : accepted %d\n", *mask.accepted);
648}
649
650//-----------------------------------------------------------------------------
651// Utilities
652
653static inline void set_owner( monitor_desc * this, thread_desc * owner ) {
654        // LIB_DEBUG_PRINT_SAFE("Kernal :   Setting owner of %p to %p ( was %p)\n", this, owner, this->owner );
655
656        //Pass the monitor appropriately
657        this->owner = owner;
658
659        //We are passing the monitor to someone else, which means recursion level is not 0
660        this->recursion = owner ? 1 : 0;
661}
662
663static inline void set_owner( monitor_desc ** monitors, short count, thread_desc * owner ) {
664        monitors[0]->owner     = owner;
665        monitors[0]->recursion = 1;
666        for( int i = 1; i < count; i++ ) {
667                monitors[i]->owner     = owner;
668                monitors[i]->recursion = 0;
669        }
670}
671
672static inline void set_mask( monitor_desc ** storage, short count, const __waitfor_mask_t & mask ) {
673        for(int i = 0; i < count; i++) {
674                storage[i]->mask = mask;
675        }
676}
677
678static inline void reset_mask( monitor_desc * this ) {
679        this->mask.accepted = NULL;
680        this->mask.clauses = NULL;
681        this->mask.size = 0;
682}
683
684static inline thread_desc * next_thread( monitor_desc * this ) {
685        //Check the signaller stack
686        LIB_DEBUG_PRINT_SAFE("Kernel :  mon %p AS-stack top %p\n", this, this->signal_stack.top);
687        __condition_criterion_t * urgent = pop( &this->signal_stack );
688        if( urgent ) {
689                //The signaller stack is not empty,
690                //regardless of if we are ready to baton pass,
691                //we need to set the monitor as in use
692                set_owner( this,  urgent->owner->waiting_thread );
693
694                return check_condition( urgent );
695        }
696
697        // No signaller thread
698        // Get the next thread in the entry_queue
699        thread_desc * new_owner = pop_head( &this->entry_queue );
700        set_owner( this, new_owner );
701
702        return new_owner;
703}
704
705static inline bool is_accepted( monitor_desc * this, const __monitor_group_t & group ) {
706        __acceptable_t * it = this->mask.clauses; // Optim
707        int count = this->mask.size;
708
709        // Check if there are any acceptable functions
710        if( !it ) return false;
711
712        // If this isn't the first monitor to test this, there is no reason to repeat the test.
713        if( this != group[0] ) return group[0]->mask.accepted >= 0;
714
715        // For all acceptable functions check if this is the current function.
716        for( short i = 0; i < count; i++, it++ ) {
717                if( *it == group ) {
718                        *this->mask.accepted = i;
719                        return true;
720                }
721        }
722
723        // No function matched
724        return false;
725}
726
727static inline void init( int count, monitor_desc ** monitors, __condition_node_t * waiter, __condition_criterion_t * criteria ) {
728        for(int i = 0; i < count; i++) {
729                (criteria[i]){ monitors[i], waiter };
730        }
731
732        waiter->criteria = criteria;
733}
734
735static inline void init_push( int count, monitor_desc ** monitors, __condition_node_t * waiter, __condition_criterion_t * criteria ) {
736        for(int i = 0; i < count; i++) {
737                (criteria[i]){ monitors[i], waiter };
738                LIB_DEBUG_PRINT_SAFE( "Kernel :  target %p = %p\n", criteria[i].target, &criteria[i] );
739                push( &criteria[i].target->signal_stack, &criteria[i] );
740        }
741
742        waiter->criteria = criteria;
743}
744
745static inline void lock_all( spinlock ** locks, unsigned short count ) {
746        for( int i = 0; i < count; i++ ) {
747                lock_yield( locks[i] DEBUG_CTX2 );
748        }
749}
750
751static inline void lock_all( monitor_desc ** source, spinlock ** /*out*/ locks, unsigned short count ) {
752        for( int i = 0; i < count; i++ ) {
753                spinlock * l = &source[i]->lock;
754                lock_yield( l DEBUG_CTX2 );
755                if(locks) locks[i] = l;
756        }
757}
758
759static inline void unlock_all( spinlock ** locks, unsigned short count ) {
760        for( int i = 0; i < count; i++ ) {
761                unlock( locks[i] );
762        }
763}
764
765static inline void unlock_all( monitor_desc ** locks, unsigned short count ) {
766        for( int i = 0; i < count; i++ ) {
767                unlock( &locks[i]->lock );
768        }
769}
770
771static inline void save( monitor_desc ** ctx, short count, __attribute((unused)) spinlock ** locks, unsigned int * /*out*/ recursions, __waitfor_mask_t * /*out*/ masks ) {
772        for( int i = 0; i < count; i++ ) {
773                recursions[i] = ctx[i]->recursion;
774                masks[i]      = ctx[i]->mask;
775        }
776}
777
778static inline void restore( monitor_desc ** ctx, short count, spinlock ** locks, unsigned int * /*out*/ recursions, __waitfor_mask_t * /*out*/ masks ) {
779        lock_all( locks, count );
780        for( int i = 0; i < count; i++ ) {
781                ctx[i]->recursion = recursions[i];
782                ctx[i]->mask      = masks[i];
783        }
784        unlock_all( locks, count );
785}
786
787// Function has 2 different behavior
788// 1 - Marks a monitors as being ready to run
789// 2 - Checks if all the monitors are ready to run
790//     if so return the thread to run
791static inline thread_desc * check_condition( __condition_criterion_t * target ) {
792        __condition_node_t * node = target->owner;
793        unsigned short count = node->count;
794        __condition_criterion_t * criteria = node->criteria;
795
796        bool ready2run = true;
797
798        for(    int i = 0; i < count; i++ ) {
799
800                // LIB_DEBUG_PRINT_SAFE( "Checking %p for %p\n", &criteria[i], target );
801                if( &criteria[i] == target ) {
802                        criteria[i].ready = true;
803                        // LIB_DEBUG_PRINT_SAFE( "True\n" );
804                }
805
806                ready2run = criteria[i].ready && ready2run;
807        }
808
809        LIB_DEBUG_PRINT_SAFE( "Kernel :  Runing %i (%p)\n", ready2run, ready2run ? node->waiting_thread : NULL );
810        return ready2run ? node->waiting_thread : NULL;
811}
812
813static inline void brand_condition( condition * this ) {
814        thread_desc * thrd = this_thread;
815        if( !this->monitors ) {
816                // LIB_DEBUG_PRINT_SAFE("Branding\n");
817                assertf( thrd->monitors.list != NULL, "No current monitor to brand condition %p", thrd->monitors.list );
818                this->monitor_count = thrd->monitors.size;
819
820                this->monitors = malloc( this->monitor_count * sizeof( *this->monitors ) );
821                for( int i = 0; i < this->monitor_count; i++ ) {
822                        this->monitors[i] = thrd->monitors.list[i];
823                }
824        }
825}
826
827static inline [thread_desc *, int] search_entry_queue( const __waitfor_mask_t & mask, monitor_desc ** monitors, int count ) {
828
829        __thread_queue_t * entry_queue = &monitors[0]->entry_queue;
830
831        // For each thread in the entry-queue
832        for(    thread_desc ** thrd_it = &entry_queue->head;
833                *thrd_it;
834                thrd_it = &(*thrd_it)->next
835        ) {
836                // For each acceptable check if it matches
837                int i = 0;
838                __acceptable_t * end = mask.clauses + mask.size;
839                for( __acceptable_t * it = mask.clauses; it != end; it++, i++ ) {
840                        // Check if we have a match
841                        if( *it == (*thrd_it)->monitors ) {
842
843                                // If we have a match return it
844                                // after removeing it from the entry queue
845                                return [remove( entry_queue, thrd_it ), i];
846                        }
847                }
848        }
849
850        return [0, -1];
851}
852
853forall(dtype T | sized( T ))
854static inline short insert_unique( T ** array, short & size, T * val ) {
855        if( !val ) return size;
856
857        for(int i = 0; i <= size; i++) {
858                if( array[i] == val ) return size;
859        }
860
861        array[size] = val;
862        size = size + 1;
863        return size;
864}
865
866static inline short count_max( const __waitfor_mask_t & mask ) {
867        short max = 0;
868        for( int i = 0; i < mask.size; i++ ) {
869                max += mask.clauses[i].size;
870        }
871        return max;
872}
873
874static inline short aggregate( monitor_desc ** storage, const __waitfor_mask_t & mask ) {
875        short size = 0;
876        for( int i = 0; i < mask.size; i++ ) {
877                __libcfa_small_sort( mask.clauses[i].list, mask.clauses[i].size );
878                for( int j = 0; j < mask.clauses[i].size; j++) {
879                        insert_unique( storage, size, mask.clauses[i].list[j] );
880                }
881        }
882        // TODO insertion sort instead of this
883        __libcfa_small_sort( storage, size );
884        return size;
885}
886
887void ?{}( __condition_blocked_queue_t & this ) {
888        this.head = NULL;
889        this.tail = &this.head;
890}
891
892void append( __condition_blocked_queue_t * this, __condition_node_t * c ) {
893        verify(this->tail != NULL);
894        *this->tail = c;
895        this->tail = &c->next;
896}
897
898__condition_node_t * pop_head( __condition_blocked_queue_t * this ) {
899        __condition_node_t * head = this->head;
900        if( head ) {
901                this->head = head->next;
902                if( !head->next ) {
903                        this->tail = &this->head;
904                }
905                head->next = NULL;
906        }
907        return head;
908}
909
910// Local Variables: //
911// mode: c //
912// tab-width: 4 //
913// End: //
Note: See TracBrowser for help on using the repository browser.