runner.c 29.3 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/*******************************************************************************
 * This file is part of GadgetSMP.
 * Coypright (c) 2012 Pedro Gonnet (pedro.gonnet@durham.ac.uk)
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published
 * by the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * 
 ******************************************************************************/
Pedro Gonnet's avatar
Pedro Gonnet committed
19

Pedro Gonnet's avatar
Pedro Gonnet committed
20
21
/* Config parameters. */
#include "../config.h"
Pedro Gonnet's avatar
Pedro Gonnet committed
22
23
24
25
26
27
28
29
30
31

/* Some standard headers. */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <math.h>
#include <float.h>
#include <limits.h>
#include <omp.h>
Pedro Gonnet's avatar
Pedro Gonnet committed
32
#include <sched.h>
Pedro Gonnet's avatar
Pedro Gonnet committed
33
34
35
36

/* Local headers. */
#include "cycle.h"
#include "lock.h"
37
38
39
#include "task.h"
#include "part.h"
#include "cell.h"
Pedro Gonnet's avatar
Pedro Gonnet committed
40
#include "space.h"
41
#include "queue.h"
Pedro Gonnet's avatar
Pedro Gonnet committed
42
#include "runner.h"
43
#include "runner_iact.h"
Pedro Gonnet's avatar
Pedro Gonnet committed
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77

/* Error macro. */
#define error(s) { printf( "%s:%s:%i: %s\n" , __FILE__ , __FUNCTION__ , __LINE__ , s ); abort(); }

/* Convert cell location to ID. */
#define cell_getid( cdim , i , j , k ) ( (int)(k) + (cdim)[2]*( (int)(j) + (cdim)[1]*(int)(i) ) )

/* The timers. */
ticks runner_timer[ runner_timer_count ];

/* The counters. */
int runner_counter[ runner_counter_count ];

        

const float runner_shift[13*3] = {
     5.773502691896258e-01 ,  5.773502691896258e-01 ,  5.773502691896258e-01 ,
     7.071067811865475e-01 ,  7.071067811865475e-01 ,  0.0                   ,
     5.773502691896258e-01 ,  5.773502691896258e-01 , -5.773502691896258e-01 ,
     7.071067811865475e-01 ,  0.0                   ,  7.071067811865475e-01 ,
     1.0                   ,  0.0                   ,  0.0                   ,
     7.071067811865475e-01 ,  0.0                   , -7.071067811865475e-01 ,
     5.773502691896258e-01 , -5.773502691896258e-01 ,  5.773502691896258e-01 ,
     7.071067811865475e-01 , -7.071067811865475e-01 ,  0.0                   ,
     5.773502691896258e-01 , -5.773502691896258e-01 , -5.773502691896258e-01 ,
     0.0                   ,  7.071067811865475e-01 ,  7.071067811865475e-01 ,
     0.0                   ,  1.0                   ,  0.0                   ,
     0.0                   ,  7.071067811865475e-01 , -7.071067811865475e-01 ,
     0.0                   ,  0.0                   ,  1.0                   ,
    };
const char runner_flip[27] = { 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 0 ,
                               0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 }; 


78
79
80
81
82
83
84
85
86
/* Import the density functions. */
#define FUNCTION density
#include "runner_doiact.h"

#undef FUNCTION
#define FUNCTION force
#include "runner_doiact.h"


Pedro Gonnet's avatar
Pedro Gonnet committed
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
/** 
 * @brief Sort the tasks in topological order over all queues.
 *
 * @param r The #runner.
 */
 
void runner_ranktasks ( struct runner *r ) {

    int i, j = 0, k, temp, left = 0, rank;
    struct task *t;
    struct space *s = r->s;
    int *tid;

    /* Run throught the tasks and get all the waits right. */
    for ( k = 0 ; k < s->nr_tasks ; k++ ) {
        for ( j = 0 ; j < s->tasks[k].nr_unlock_tasks ; j++ )
            s->tasks[k].unlock_tasks[j]->wait += 1;
        }
        
    /* Allocate and init the task-ID array. */
    if ( ( tid = (int *)malloc( sizeof(int) * s->nr_tasks ) ) == NULL )
        error( "Failed to allocate temporary tid array." );
    for ( k = 0 ; k < s->nr_tasks ; k++ )
        tid[k] = k;
        
    /* Main loop. */
    for ( rank = 0 ; left < s->nr_tasks ; rank++ ) {
        
        /* Load the tids of tasks with no waits. */
        for ( k = left ; k < s->nr_tasks ; k++ )
            if ( s->tasks[ tid[k] ].wait == 0 ) {
                temp = tid[j]; tid[j] = tid[k]; tid[k] = temp;
                j += 1;
                }

        /* Traverse the task tree and add tasks with no weight. */
        for ( i = left ; i < j ; i++ ) {
            t = &s->tasks[ tid[i] ];
            t->rank = rank;
            s->tasks_ind[i] = t - s->tasks;
            /* printf( "runner_ranktasks: task %i of type %s has rank %i.\n" , i , 
128
                (t->type == task_type_self) ? "self" : (t->type == task_type_pair) ? "pair" : "sort" , rank ); */
Pedro Gonnet's avatar
Pedro Gonnet committed
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
            for ( k = 0 ; k < t->nr_unlock_tasks ; k++ )
                t->unlock_tasks[k]->wait -= 1;
            }
            
        /* The new left (no, not tony). */
        left = j;
            
        }
        
    /* Release the temporary array. */
    free(tid);
    
    }


/**
 * @brief Sort the entries in ascending order using QuickSort.
 *
 * @param sort The entries
 * @param N The number of entries.
 */
 
void runner_dosort_ascending ( struct entry *sort , int N ) {

    struct {
        short int lo, hi;
        } qstack[10];
    int qpos, i, j, lo, hi, imin;
    struct entry temp;
    float pivot;
        
    /* Sort parts in cell_i in decreasing order with quicksort */
    qstack[0].lo = 0; qstack[0].hi = N - 1; qpos = 0;
    while ( qpos >= 0 ) {
        lo = qstack[qpos].lo; hi = qstack[qpos].hi;
        qpos -= 1;
        if ( hi - lo < 15 ) {
            for ( i = lo ; i < hi ; i++ ) {
                imin = i;
                for ( j = i+1 ; j <= hi ; j++ )
                    if ( sort[j].d < sort[imin].d )
                        imin = j;
                if ( imin != i ) {
                    temp = sort[imin]; sort[imin] = sort[i]; sort[i] = temp;
                    }
                }
            }
        else {
            pivot = sort[ ( lo + hi ) / 2 ].d;
            i = lo; j = hi;
            while ( i <= j ) {
                while ( sort[i].d < pivot ) i++;
                while ( sort[j].d > pivot ) j--;
                if ( i <= j ) {
                    if ( i < j ) {
                        temp = sort[i]; sort[i] = sort[j]; sort[j] = temp;
                        }
                    i += 1; j -= 1;
                    }
                }
            if ( j > ( lo + hi ) / 2 ) {
                if ( lo < j ) {
                    qpos += 1;
                    qstack[qpos].lo = lo;
                    qstack[qpos].hi = j;
                    }
                if ( i < hi ) {
                    qpos += 1;
                    qstack[qpos].lo = i;
                    qstack[qpos].hi = hi;
                    }
                }
            else {
                if ( i < hi ) {
                    qpos += 1;
                    qstack[qpos].lo = i;
                    qstack[qpos].hi = hi;
                    }
                if ( lo < j ) {
                    qpos += 1;
                    qstack[qpos].lo = lo;
                    qstack[qpos].hi = j;
                    }
                }
            }
        }
                
    }
    
    
/**
 * @brief inline helper fuction to merge two entry arrays (forward).
 *
 * @param one the first array
 * @param none the length of the first array
 * @param two the second array
 * @param ntwo the length of the second array
 * @param dest the destination array.
 */
 
inline void merge_forward ( struct entry *__restrict__ one , int none , struct entry *__restrict__ two , int ntwo , struct entry *__restrict__ dest ) {

    int i = 0, j = 0, k = 0;
    
    while ( j < none && k < ntwo )
        if ( one[j].d < two[k].d )
            dest[i++] = one[j++];
        else
            dest[i++] = two[k++];
    if ( j == none )
        for ( ; k < ntwo ; k++ )
            dest[i++] = two[k];
    else
        for ( ; j < none ; j++ )
            dest[i++] = one[j];

    }
    

/**
 * @brief inline helper fuction to merge two entry arrays (forward).
 *
 * @param one the first array
 * @param none the length of the first array
 * @param two the second array
 * @param ntwo the length of the second array
 * @param dest the destination array.
 */
 
inline void merge_backward ( struct entry *__restrict__ one , int none , struct entry *__restrict__ two , int ntwo , struct entry *__restrict__ dest ) {

    int i = none + ntwo - 1, j = none - 1, k = ntwo - 1;
    
    while ( j >= 0 && k >= 0 )
        if ( one[j].d > two[k].d )
            dest[i--] = one[j--];
        else
            dest[i--] = two[k--];
    if ( j < 0 )
        for ( ; k >= 0 ; k-- )
            dest[i--] = two[k];
    else
        for ( ; j >= 0 ; j-- )
            dest[i--] = one[j];

    }
    

/**
 * @brief Sort the particles in the given cell along all cardinal directions.
 *
 * @param r The #runner.
 * @param c The #cell.
 */
 
void runner_dosort ( struct runner_thread *rt , struct cell *c , int flags ) {

    struct entry *finger;
    struct entry *fingers[8];
    struct part *parts = c->parts;
    int j, k, count = c->count;
    int cone, ctwo;
    int i, ind, off[8], inds[8], temp_i;
292
    // float shift[3];
Pedro Gonnet's avatar
Pedro Gonnet committed
293
    float buff[8], px[3];
Pedro Gonnet's avatar
Pedro Gonnet committed
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
    struct cell *temp_c;
    TIMER_TIC
    
    /* Does this cell even need to be sorted? */
    for ( temp_c = c ; temp_c != NULL && temp_c->nr_pairs == 0 ; temp_c = temp_c->parent );
    if ( temp_c == NULL )
        return;

    /* start by allocating the entry arrays. */
    if ( lock_lock( &c->lock ) != 0 )
        error( "Failed to lock cell." );
    if ( c->sort == NULL )
        if ( ( c->sort = (struct entry *)malloc( sizeof(struct entry) * (c->count + 1) * 13 ) ) == NULL )
            error( "Failed to allocate sort memory." );
    if ( lock_unlock( &c->lock ) != 0 )
        error( "Failed to unlock cell." );
        
    /* Does this cell have any progeny? */
    if ( c->split ) {
    
        /* Loop over the 13 different sort arrays. */
        for ( j = 0 ; j < 13 ; j++ ) {
        
            /* Has this sort array been flagged? */
            if ( !( flags & (1 << j) ) )
                continue;
                
            if ( 0 ) {
            
                /* Get a finger on the sorting array. */
                finger = &c->sort[ j*(count + 1) ];
                
                /* Merge the two first sub-cells forward into this cell. */
                cone = c->progeny[0]->count;
                ctwo = c->progeny[1]->count;
                merge_forward( &c->progeny[0]->sort[ j*(cone + 1) ] , cone ,
                               &c->progeny[1]->sort[ j*(ctwo + 1) ] , ctwo ,
                               finger );
                               
                /* Merge-in the remaining arrays, alternating forward and
                   backward merges. */
                for ( k = 2 ; k < 8 ; k++ ) {
                    cone = cone + ctwo;
                    ctwo = c->progeny[k]->count;
                    if ( k & 1 )
                        merge_forward( &finger[ count - cone ] , cone ,
                                       &c->progeny[k]->sort[ j*(ctwo + 1) ] , ctwo ,
                                       finger );
                    else
                        merge_backward( finger , cone ,
                                        &c->progeny[k]->sort[ j*(ctwo + 1) ] , ctwo ,
                                        &finger[ count - cone - ctwo ] );
                    }
                
                }
                
            else {
            
                /* Init the particle index offsets. */
                for ( off[0] = 0 , k = 1 ; k < 8 ; k++ )
                    if ( c->progeny[k-1] != NULL )
                        off[k] = off[k-1] + c->progeny[k-1]->count;
                    else
                        off[k] = off[k-1];

                /* Init the entries and indices. */
                for ( k = 0 ; k < 8 ; k++ ) {
                    inds[k] = k;
                    if ( c->progeny[k] != NULL && c->progeny[k]->count > 0 ) {
                        fingers[k] = &c->progeny[k]->sort[ j*(c->progeny[k]->count + 1) ];
                        buff[k] = fingers[k]->d;
                        off[k] = off[k];
                        }
                    else
                        buff[k] = FLT_MAX;
                    }

                /* Sort the buffer. */
                for ( i = 0 ; i < 7 ; i++ )
                    for ( k = i+1 ; k < 8 ; k++ )
                        if ( buff[ inds[k] ] < buff[ inds[i] ] ) {
                            temp_i = inds[i]; inds[i] = inds[k]; inds[k] = temp_i;
                            }

                /* For each entry in the new sort list. */
                finger = &c->sort[ j*(count + 1) ];
                for ( ind = 0 ; ind < count ; ind++ ) {

                    /* Copy the minimum into the new sort array. */
                    finger[ind].d = buff[inds[0]];
                    finger[ind].i = fingers[inds[0]]->i + off[inds[0]];

                    /* Update the buffer. */
                    fingers[inds[0]] += 1;
                    buff[inds[0]] = fingers[inds[0]]->d;

                    /* Find the smallest entry. */
                    for ( k = 1 ; k < 8 && buff[inds[k]] < buff[inds[k-1]] ; k++ ) {
                        temp_i = inds[k-1]; inds[k-1] = inds[k]; inds[k] = temp_i;
                        }

                    } /* Merge. */
                    
                }
            
            /* Add a sentinel. */
            c->sort[ j*(c->count + 1) + c->count ].d = FLT_MAX;
            c->sort[ j*(c->count + 1) + c->count ].i = 0;
            
            } /* loop over sort arrays. */
    
        } /* progeny? */
        
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
    /* Otherwise, just sort. */
    // else {
    // 
    //     /* Loop over the different cell axes. */
    //     for ( j = 0 ; j < 13 ; j++ ) {
    //     
    //         /* Has this sort array been flagged? */
    //         if ( !( flags & (1 << j) ) )
    //             continue;
    //     
    //         /* Get the shift vector. */
    //         shift[0] = runner_shift[ 3*j + 0 ];
    //         shift[1] = runner_shift[ 3*j + 1 ];
    //         shift[2] = runner_shift[ 3*j + 2 ];
    //         
    //         /* Fill the sort array. */
    //         finger = &c->sort[ j*(count + 1) ];
    //         for ( k = 0 ; k < count ; k++ ) {
    //             finger[k].i = k;
    //             finger[k].d = parts[k].x[0]*shift[0] + parts[k].x[1]*shift[1] + parts[k].x[2]*shift[2];
    //             }
    //             
    //         /* Add the sentinel. */
    //         finger[ c->count ].d = FLT_MAX;
    //         finger[ c->count ].i = 0;
    //             
    //         /* Sort descending. */
    //         runner_dosort_ascending( finger , c->count );
    //     
    //         }
    //         
    //     }
        
Pedro Gonnet's avatar
Pedro Gonnet committed
440
441
442
    /* Otherwise, just sort. */
    else {
    
443
        /* Fill the sort array. */
Pedro Gonnet's avatar
Pedro Gonnet committed
444
445
446
447
        for ( k = 0 ; k < count ; k++ ) {
            px[0] = parts[k].x[0];
            px[1] = parts[k].x[1];
            px[2] = parts[k].x[2];
448
449
450
            for ( j = 0 ; j < 13 ; j++ )
                if ( flags & (1 << j) ) {
                    c->sort[ j*(count + 1) + k].i = k;
Pedro Gonnet's avatar
Pedro Gonnet committed
451
                    c->sort[ j*(count + 1) + k].d = px[0]*runner_shift[ 3*j + 0 ] + px[1]*runner_shift[ 3*j + 1 ] + px[2]*runner_shift[ 3*j + 2 ];
452
                    }
Pedro Gonnet's avatar
Pedro Gonnet committed
453
            }
454
455
456
457
458
459
460

        /* Add the sentinel and sort. */
        for ( j = 0 ; j < 13 ; j++ )
            if ( flags & (1 << j) ) {
                c->sort[ j*(count + 1) + c->count ].d = FLT_MAX;
                c->sort[ j*(count + 1) + c->count ].i = 0;
                runner_dosort_ascending( &c->sort[ j*(count + 1) ] , c->count );
Pedro Gonnet's avatar
Pedro Gonnet committed
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
                }
            
        }
        
    /* Verify the sorting. */
    /* for ( j = 0 ; j < 13 ; j++ ) {
        if ( !( flags & (1 << j) ) )
            continue;
        finger = &c->sort[ j*(c->count + 1) ];
        for ( k = 1 ; k < c->count ; k++ ) {
            if ( finger[k].d < finger[k-1].d )
                error( "Sorting failed, ascending array." );
            if ( finger[k].i >= c->count )
                error( "Sorting failed, indices borked." );
            }
        } */

    #ifdef TIMER_VERBOSE
        printf( "runner_dosort[%02i]: %i parts at depth %i (flags = %i%i%i%i%i%i%i%i%i%i%i%i%i) took %.3f ms.\n" ,
            rt->id , c->count , c->depth ,
            (flags & 0x1000) >> 12 , (flags & 0x800) >> 11 , (flags & 0x400) >> 10 , (flags & 0x200) >> 9 , (flags & 0x100) >> 8 , (flags & 0x80) >> 7 , (flags & 0x40) >> 6 , (flags & 0x20) >> 5 , (flags & 0x10) >> 4 , (flags & 0x8) >> 3 , (flags & 0x4) >> 2 , (flags & 0x2) >> 1 , (flags & 0x1) >> 0 , 
            ((double)TIMER_TOC(runner_timer_dosort)) / CPU_TPS * 1000 ); fflush(stdout);
    #else
        TIMER_TOC(runner_timer_dosort);
    #endif

    }


/**
 * @brief Implements a barrier for the #runner threads.
 *
 */
 
void runner_barrier( struct runner *r ) {

    /* First, get the barrier mutex. */
    if ( pthread_mutex_lock( &r->barrier_mutex ) != 0 )
        error( "Failed to get barrier mutex." );
        
    /* Wait for the barrier to close. */
    while ( r->barrier_count < 0 )
        if ( pthread_cond_wait( &r->barrier_cond , &r->barrier_mutex ) != 0 )
            error( "Eror waiting for barrier to close." );
        
    /* Once I'm in, increase the barrier count. */
    r->barrier_count += 1;
    
    /* If all threads are in, send a signal... */
    if ( r->barrier_count == r->nr_threads )
        if ( pthread_cond_broadcast( &r->barrier_cond ) != 0 )
            error( "Failed to broadcast barrier full condition." );
        
    /* Wait for barrier to be released. */
    while ( r->barrier_count > 0 )
        if ( pthread_cond_wait( &r->barrier_cond , &r->barrier_mutex ) != 0 )
            error( "Error waiting for barrier to be released." );
            
    /* Decrease the counter before leaving... */
    r->barrier_count += 1;
    
    /* If I'm the last one out, signal the condition again. */
    if ( r->barrier_count == 0 )
        if ( pthread_cond_broadcast( &r->barrier_cond ) != 0 )
            error( "Failed to broadcast empty barrier condition." );
            
    /* Last but not least, release the mutex. */
    if ( pthread_mutex_unlock( &r->barrier_mutex ) != 0 )
        error( "Failed to get unlock the barrier mutex." );

    }
    
    
/**
 * @brief The #runner main thread routine.
 *
 * @param data A pointer to this thread's data.
 */
 
void *runner_main ( void *data ) {

    struct runner_thread *rt = (struct runner_thread *)data;
    struct runner *r = rt->r;
    int threadID = rt->id;
    int k, qid, naq, keep, tpq;
    struct queue *queues[ r->nr_queues ], *myq;
    struct task *t;
    struct cell *ci, *cj;
549
    unsigned int myseed = rand() + rt->id;
Pedro Gonnet's avatar
Pedro Gonnet committed
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
    #ifdef TIMER
        ticks stalled;
    #endif
    
    /* Main loop. */
    while ( 1 ) {
    
        /* Wait at the barrier. */
        runner_barrier( r );
        
        /* Set some convenient local data. */
        keep = r->policy & runner_policy_keep;
        myq = &r->queues[ threadID % r->nr_queues ];
        tpq = ceil( ((double)r->nr_threads) / r->nr_queues );
        stalled = 0;
        
        /* Set up the local list of active queues. */
        naq = r->nr_queues;
        for ( k = 0 ; k < naq ; k++ )
            queues[k] = &r->queues[k];
    
        /* Set up the local list of active queues. */
        naq = r->nr_queues;
        for ( k = 0 ; k < naq ; k++ )
            queues[k] = &r->queues[k];
    
        /* Loop while there are tasks... */
        while ( 1 ) {
        
            /* Remove any inactive queues. */
            for ( k = 0 ; k < naq ; k++ )
                if ( queues[k]->next == queues[k]->count ) {
                    naq -= 1;
                    queues[k] = queues[naq];
                    k -= 1;
                    }
            if ( naq == 0 )
                break;
        
            /* Get a task, how and from where depends on the policy. */
            TIMER_TIC
            t = NULL;
            if ( r->nr_queues == 1 ) {
Pedro Gonnet's avatar
Pedro Gonnet committed
593
                t = queue_gettask( &r->queues[0] , 1 , 0 );
Pedro Gonnet's avatar
Pedro Gonnet committed
594
595
596
                }
            else if ( r->policy & runner_policy_steal ) {
                if ( ( myq->next == myq->count ) ||
Pedro Gonnet's avatar
Pedro Gonnet committed
597
                     ( t = queue_gettask_new( myq , rt->id , 0 , 0 ) ) == NULL ) {
Pedro Gonnet's avatar
Pedro Gonnet committed
598
                    TIMER_TIC2
599
                    qid = rand_r( &myseed ) % naq;
Pedro Gonnet's avatar
Pedro Gonnet committed
600
601
602
603
604
605
                    keep = ( r->policy & runner_policy_keep ) &&
                           ( myq->count <= myq->size-tpq );
                    if ( myq->next == myq->count )
                        COUNT(runner_counter_steal_empty);
                    else
                        COUNT(runner_counter_steal_stall);
Pedro Gonnet's avatar
Pedro Gonnet committed
606
607
608
                    t = queue_gettask_new( queues[qid] , rt->id , 0 , keep );
                    if ( t != NULL && keep )
                        queue_insert( myq , t );
Pedro Gonnet's avatar
Pedro Gonnet committed
609
610
611
612
                    TIMER_TOC2(runner_timer_steal);
                    }
                }
            else if ( r->policy & runner_policy_rand ) {
613
                qid = rand_r( &myseed ) % naq;
Pedro Gonnet's avatar
Pedro Gonnet committed
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
                t = queue_gettask( queues[qid] , r->policy & runner_policy_block , 0 );
                }
            else {
                t = queue_gettask( &r->queues[threadID] , r->policy & runner_policy_block , 0 );
                }
            TIMER_TOC(runner_timer_getpair);
            
            /* Did I get anything? */
            if ( t == NULL ) {
                COUNT(runner_counter_stall);
                if ( !stalled )
                    stalled = getticks();
                continue;
                }
            #ifdef TIMER
            else if ( stalled ) {
                stalled = getticks() - stalled;
                __sync_add_and_fetch( &runner_timer[runner_timer_stalled] , stalled );
                #ifdef TIMER_VERBOSE
                    printf( "runner_main[%02i]: stalled %.3f ms\n" , rt->id , ((double)stalled) / CPU_TPS * 1000 );
                    fflush(stdout);
                #endif
                stalled = 0;
                }
            #endif
        
            /* Get the cells. */
            ci = t->ci;
            cj = t->cj;
            
            /* Different types of tasks... */
            switch ( t->type ) {
646
647
648
649
650
651
652
                case task_type_self:
                    if ( t->subtype == task_subtype_density )
                        runner_doself_density( rt , ci );
                    else if ( t->subtype == task_subtype_force )
                        runner_doself_force( rt , ci );
                    else
                        error( "Unknown task subtype." );
Pedro Gonnet's avatar
Pedro Gonnet committed
653
654
                    cell_unlocktree( ci );
                    break;
655
656
657
658
659
660
661
                case task_type_pair:
                    if ( t->subtype == task_subtype_density )
                        runner_dopair_density( rt , ci , cj );
                    else if ( t->subtype == task_subtype_force )
                        runner_dopair_force( rt , ci , cj );
                    else
                        error( "Unknown task subtype." );
Pedro Gonnet's avatar
Pedro Gonnet committed
662
663
664
                    cell_unlocktree( ci );
                    cell_unlocktree( cj );
                    break;
665
                case task_type_sort:
Pedro Gonnet's avatar
Pedro Gonnet committed
666
667
                    runner_dosort( rt , ci , t->flags );
                    break;
668
669
670
671
672
673
674
                case task_type_sub:
                    if ( t->subtype == task_subtype_density )
                        runner_dosub_density( rt , ci , cj , t->flags );
                    else if ( t->subtype == task_subtype_force )
                        runner_dosub_force( rt , ci , cj , t->flags );
                    else
                        error( "Unknown task subtype." );
Pedro Gonnet's avatar
Pedro Gonnet committed
675
676
677
678
                    cell_unlocktree( ci );
                    if ( cj != NULL )
                        cell_unlocktree( cj );
                    break;
679
680
                case task_type_ghost:
                    break;
Pedro Gonnet's avatar
Pedro Gonnet committed
681
682
683
684
685
686
687
688
                default:
                    error( "Unknown task type." );
                }
                
            t->done = 1;
            
            /* Resolve any dependencies. */
            for ( k = 0 ; k < t->nr_unlock_tasks ; k++ )
Pedro Gonnet's avatar
Pedro Gonnet committed
689
690
                if ( __sync_fetch_and_sub( &t->unlock_tasks[k]->wait , 1 ) == 0 )
                    abort();
Pedro Gonnet's avatar
Pedro Gonnet committed
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
            for ( k = 0 ; k < t->nr_unlock_cells ; k++ )
                __sync_fetch_and_sub( &t->unlock_cells[k]->wait , 1 );
        
            } /* main loop. */
            
    	/* Any leftover stalls? */    
        #ifdef TIMER
        if ( stalled ) {
            stalled = getticks() - stalled;
            __sync_add_and_fetch( &runner_timer[runner_timer_stalled] , stalled );
            #ifdef TIMER_VERBOSE
                printf( "runner_main[%02i]: stalled %.3f ms\n" , rt->id , ((double)stalled) / CPU_TPS * 1000 );
                fflush(stdout);
            #endif
            stalled = 0;
            }
        #endif
            
        }
        
    /* Be kind, rewind. */
    return NULL;

    }
    

/**
 * @brief Let the #runner loose on the given #space.
 *
 * @param r The #runner.
 * @param s The #space.
 */
 
void runner_run ( struct runner *r , int sort_queues ) {

    int j, k;
    struct space *s = r->s;
    
    /* Run throught the tasks and get all the waits right. */
    for ( k = 0 ; k < s->nr_tasks ; k++ ) {
        s->tasks[k].done = 0;
        for ( j = 0 ; j < s->tasks[k].nr_unlock_tasks ; j++ )
            s->tasks[k].unlock_tasks[j]->wait += 1;
        for ( j = 0 ; j < s->tasks[k].nr_unlock_cells ; j++ )
            s->tasks[k].unlock_cells[j]->wait += 1;
        }
    
    /* Re-set the queues.*/
    if ( sort_queues ) {
        #pragma omp parallel for default(none), shared(r)
        for ( k = 0 ; k < r->nr_queues ; k++ ) {
            queue_sort( &r->queues[k] );
            r->queues[k].next = 0;
            }
        }
    else
        for ( k = 0 ; k < r->nr_queues ; k++ )
            r->queues[k].next = 0;
    
    /* Cry havoc and let loose the dogs of war. */
    r->barrier_count = -r->barrier_count;
    if ( pthread_cond_broadcast( &r->barrier_cond ) != 0 )
        error( "Failed to broadcast barrier open condition." );
        
    /* Sit back and wait for the runner_threads to come home. */
    while ( r->barrier_count < r->nr_threads )
        if ( pthread_cond_wait( &r->barrier_cond , &r->barrier_mutex ) != 0 )
            error( "Error while waiting for barrier." );
    
    }
    
    
/**
 * @brief init a runner with the given number of threads, queues, and
 *      the given policy.
 *
 * @param r The #runner.
 * @param s The #space in which this #runner will run.
 * @param nr_threads The number of threads to spawn.
 * @param nr_queues The number of task queues to create.
 * @param policy The queueing policy to use.
 */
 
void runner_init ( struct runner *r , struct space *s , int nr_threads , int nr_queues , int policy ) {

Pedro Gonnet's avatar
Pedro Gonnet committed
776
777
778
    #if defined(HAVE_SETAFFINITY)
        cpu_set_t cpuset;
    #endif
Pedro Gonnet's avatar
Pedro Gonnet committed
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
    int k, qid, nrq;
    
    /* Store the values. */
    r->s = s;
    r->nr_threads = nr_threads;
    r->nr_queues = nr_queues;
    r->policy = policy;
    
    /* First of all, init the barrier and lock it. */
    if ( pthread_mutex_init( &r->barrier_mutex , NULL ) != 0 )
        error( "Failed to initialize barrier mutex." );
    if ( pthread_cond_init( &r->barrier_cond , NULL ) != 0 )
        error( "Failed to initialize barrier condition variable." );
    if ( pthread_mutex_lock( &r->barrier_mutex ) != 0 )
        error( "Failed to lock barrier mutex." );
    r->barrier_count = 0;
    
    /* Allocate the queues. */
    if ( posix_memalign( (void *)(&r->queues) , 64 , nr_queues * sizeof(struct queue) ) != 0 )
        error( "Failed to allocate queues." );
    bzero( r->queues , nr_queues * sizeof(struct queue) );
        
    /* Init the queues. */
802
803
    for ( k = 0 ; k < nr_queues ; k++ )
        queue_init( &r->queues[k] , s->nr_tasks , s->tasks );
Pedro Gonnet's avatar
Pedro Gonnet committed
804
805
806
807
808
809
810
811
812
813
        
    /* Rank the tasks in topological order. */
    runner_ranktasks( r );
    
    /* How many queues to fill initially? */
    for ( nrq = 0 , k = nr_queues ; k > 0 ; k = k / 2 )
        nrq += 1;
        
    /* Fill the queues (round-robin). */
    for ( k = 0 ; k < s->nr_tasks ; k++ ) {
814
        if ( s->tasks[ s->tasks_ind[k] ].type == task_type_none )
Pedro Gonnet's avatar
Pedro Gonnet committed
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
            continue;
        // qid = 0;
        // qid = k % nrq;
        qid = k % nr_queues;
        r->queues[qid].tid[ r->queues[qid].count ] = s->tasks_ind[k];
        r->queues[qid].count += 1;
        }
        
    /* Sort the queues topologically. */
    for ( k = 0 ; k < nr_queues ; k++ )
        queue_sort( &r->queues[k] );
        
    /* Allocate and init the threads. */
    if ( ( r->threads = (struct runner_thread *)malloc( sizeof(struct runner_thread) * nr_threads ) ) == NULL )
        error( "Failed to allocate threads array." );
    for ( k = 0 ; k < nr_threads ; k++ ) {
        r->threads[k].id = k;
        r->threads[k].r = r;
        if ( pthread_create( &r->threads[k].thread , NULL , &runner_main , &r->threads[k] ) != 0 )
            error( "Failed to create runner thread." );
Pedro Gonnet's avatar
Pedro Gonnet committed
835
836
837
838
839
840
841
842
843
        #if defined(HAVE_SETAFFINITY)
            /* Set the cpu mask to zero | r->id. */
            CPU_ZERO( &cpuset );
            CPU_SET( r->threads[k].id , &cpuset );

            /* Apply this mask to the runner's pthread. */
            if ( pthread_setaffinity_np( r->threads[k].thread , sizeof(cpu_set_t) , &cpuset ) != 0 )
                error( "Failed to set thread affinity." );
        #endif
Pedro Gonnet's avatar
Pedro Gonnet committed
844
845
846
847
848
849
850
851
852
853
854
        }
        
    /* Wait for the runner threads to be in place. */
    while ( r->barrier_count != r->nr_threads )
        if ( pthread_cond_wait( &r->barrier_cond , &r->barrier_mutex ) != 0 )
            error( "Error while waiting for runner threads to get in place." );
    
    }