source: libcfa/src/concurrency/monitor.cfa @ 5afb49a

ADTarm-ehast-experimentalenumforall-pointer-decayjacob/cs343-translationnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since 5afb49a was 5afb49a, checked in by Thierry Delisle <tdelisle@…>, 4 years ago

Split thread_leave so backend is called from the kernel once the kernel no longer needs the thread.
This hopefully solves the non-deterministic crashes in the build.

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