source: libcfa/src/concurrency/monitor.cfa @ 9d6e1b8a

arm-ehjacob/cs343-translationnew-ast-unique-expr
Last change on this file since 9d6e1b8a was 9d6e1b8a, checked in by Thierry Delisle <tdelisle@…>, 14 months ago

Minor improvments to assertions and comments

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