source: libcfa/src/concurrency/monitor.cfa @ af67ee1

enumforall-pointer-decayjacob/cs343-translation
Last change on this file since af67ee1 was af67ee1, checked in by caparsons <caparson@…>, 9 months ago

Added support for locks as parameters to mutex stmt

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