source: libcfa/src/concurrency/monitor.cfa @ b0c7419

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

Yield now uses force_yield instead of park/unpark.
Final ctxswitch of a thread now uses ad-hoc mechanism instead of park/unpark.

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