source: libcfa/src/concurrency/monitor.cfa @ 40841ff4

ADTarm-ehast-experimentalenumforall-pointer-decayjacob/cs343-translationnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since 40841ff4 was fd54fef, checked in by Michael Brooks <mlbrooks@…>, 4 years ago

Converting the project to use the new syntax for otype, dtype and ttytpe.

Changed prelude (gen), libcfa and test suite to use it. Added a simple deprecation rule of the old syntax to the parser; we might wish to support both syntaxes "officially," like with an extra CLI switch, but this measure should serve as a simple reminder for our team to try the new syntax.

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