source: libcfa/src/concurrency/monitor.cfa @ 4407b7e

ADTast-experimentalpthread-emulation
Last change on this file since 4407b7e was c18bf9e, checked in by Thierry Delisle <tdelisle@…>, 2 years ago

Visibility concurrency

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