source: libcfa/src/concurrency/monitor.cfa @ 43784ac

jacob/cs343-translationnew-ast-unique-expr
Last change on this file since 43784ac was 43784ac, checked in by Thierry Delisle <tdelisle@…>, 3 months ago

Changed libcfathread to consistently define _GNU_SOURCE

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