source: libcfa/src/concurrency/monitor.cfa @ 51e7583

ADTarm-ehast-experimentalenumforall-pointer-decayjacob/cs343-translationnew-ast-unique-exprpthread-emulationqualifiedEnum
Last change on this file since 51e7583 was ab8c6a6, checked in by Andrew Beach <ajbeach@…>, 4 years ago

Thread Cancellation, a test for it and a required fix to Specialization.

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