source: src/libcfa/concurrency/monitor.c @ 43725bd

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsdeferred_resndemanglerenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxnew-astnew-ast-unique-exprnew-envno_listpersistent-indexerpthread-emulationqualifiedEnumwith_gc
Last change on this file since 43725bd was c2ca04d, checked in by Peter A. Buhr <pabuhr@…>, 7 years ago

use %z for length of size_t in print

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