source: trunk/user/sort/sort.c @ 656

Last change on this file since 656 was 656, checked in by alain, 4 years ago

Fix several bugs in the FATFS and in the VFS,
related to the creation of big files requiring
more than 4 Kbytes (one cluster) on device.

  • Property svn:executable set to *
File size: 13.9 KB
Line 
1/*
2 * sort.c - Parallel sort
3 *
4 * Author     Cesar Fuguet Tortolero (2013)
5 *            Alain Greiner (2019)
6 *
7 * Copyright (c) UPMC Sorbonne Universites
8 *
9 * This is free software; you can redistribute it and/or modify it
10 * under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; version 2.0 of the License.
12 *
13 * It is distributed in the hope that it will be useful, but
14 * WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16 * General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with ALMOS-MKH; if not, write to the Free Software Foundation,
20 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
21 */
22
23///////////////////////////////////////////////////////////////////////////////
24// This multi-threaded application implement a multi-stage sort.
25// It has been writen by Cesar Fuget Tortolero in 2013.
26// It has been ported on ALMOS-MKH by Alain Greiner in 2019.
27//
28// There is one thread per physical cores.
29// Computation is organised as a binary tree:
30// - All threads execute in parallel a buble sort on a sub-array during the
31//   the first stage of parallel sort,
32// - The number of participating threads is divided by 2 at each next stage,
33//   to make a merge sort, on two subsets of previous stage.
34//
35//       Number_of_stages = number of barriers = log2(Number_of_threads)
36//
37// The various stages are separated by synchronisation barriers, and the
38// main thread uses the join syscall to check that all threads completed
39// before printing the computation time (sequencial & parallel).
40// These results can be - optionnaly - registered in an instrumentation file.
41//
42// Constraints :
43// - It supports up to 1024 cores: x_size, y_size, and ncores must be
44//   power of 2 (max 16*16 clusters / max 4 cores per cluster)
45// _ The array of values to be sorted (ARRAY_LENGTH) must be power of 2
46//   larger than the number of cores.
47///////////////////////////////////////////////////////////////////////////////
48
49#include <stdio.h>
50#include <stdlib.h>
51#include <unistd.h>
52#include <pthread.h>
53#include <almosmkh.h>
54#include <hal_macros.h>
55
56#define ARRAY_LENGTH        2048            // number of items
57#define MAX_THREADS         1024            // 16 * 16 * 4
58
59#define X_MAX               16              // max number of clusters in a row
60#define Y_MAX               16              // max number of clusters in a column
61#define CORES_MAX           4               // max number of cores in a cluster
62#define CLUSTERS_MAX        X_MAX * Y_MAX
63
64#define USE_DQT_BARRIER     1               // use DQT barrier if non zero
65#define DISPLAY_ARRAY       0               // display items values before and after
66#define DEBUG_MAIN          0               // trace main function
67#define DEBUG_SORT          0               // trace sort function
68#define CHECK_RESULT        0               // for debug
69#define INSTRUMENTATION     1               // register computation times on file
70
71////////////////////////////////////////////////////////////////////////////////////
72//            Sort specific global variables
73////////////////////////////////////////////////////////////////////////////////////
74
75int                 array0[ARRAY_LENGTH];    // values to sort
76int                 array1[ARRAY_LENGTH];   
77
78unsigned int        threads;                // total number of working threads
79
80pthread_barrier_t   barrier;                 // synchronisation variables
81
82/////////////////////////////////////////////////////////////////////////////////////
83//             Global variables required by parallel_pthread_create()
84/////////////////////////////////////////////////////////////////////////////////////
85
86
87////////////////////////////////////
88static void bubbleSort( int * array,
89                        unsigned int length,
90                        unsigned int init_pos )
91{
92    unsigned int i;
93    unsigned int j;
94    int          aux;
95
96    for(i = 0; i < length; i++)
97    {
98        for(j = init_pos; j < (init_pos + length - i - 1); j++)
99        {
100            if(array[j] > array[j + 1])
101            {
102                aux          = array[j + 1];
103                array[j + 1] = array[j];
104                array[j]     = aux;
105            }
106        }
107    }
108}  // end bubbleSort()
109
110
111///////////////////////////////////
112static void merge( const int * src,               // source array
113                   int       * dst,               // destination array
114                   int         length,            // number of items in a subset
115                   int         init_pos_src_a,    // index first item in src subset A
116                   int         init_pos_src_b,    // index first item in src subset B
117                   int         init_pos_dst )     // index first item in destination
118{
119    int i;
120    int j;
121    int k;
122
123    i = 0;
124    j = 0;
125    k = init_pos_dst;
126
127    while((i < length) || (j < length))
128    {
129        if((i < length) && (j < length))
130        {
131            if(src[init_pos_src_a + i] < src[init_pos_src_b + j])
132            {
133                dst[k++] = src[init_pos_src_a + i];
134                i++;
135            }
136            else
137            {
138                dst[k++] = src[init_pos_src_b + j];
139                j++;
140            }
141        }
142        else if(i < length)
143        {
144            dst[k++] = src[init_pos_src_a + i];
145            i++;
146        }
147        else
148        {
149            dst[k++] = src[init_pos_src_b + j];
150            j++;
151        }
152    }
153}  // end merge()
154
155///////////////////////////////
156void * sort( void * arguments )
157{
158    unsigned int        i;
159    int               * src_array  = NULL;
160    int               * dst_array  = NULL;
161
162    // get arguments
163    pthread_parallel_work_args_t * ptr = (pthread_parallel_work_args_t *)arguments;
164
165    unsigned int        tid            = ptr->tid;
166    pthread_barrier_t * parent_barrier = ptr->barrier;
167
168    unsigned int        items      = ARRAY_LENGTH / threads;
169    unsigned int        stages     = __builtin_ctz( threads ) + 1;
170
171#if DEBUG_SORT
172printf("\n[sort] start : ptr %x / tid %d / threads %d / parent_barrier %x\n",
173ptr, tid, threads, parent_barrier );
174#endif
175
176    bubbleSort( array0, items, items * tid );
177
178#if DEBUG_SORT
179printf("\n[sort] thread[%d] : stage 0 completed\n", tid );
180#endif
181
182    /////////////////////////////////
183    pthread_barrier_wait( &barrier ); 
184
185#if DEBUG_SORT
186printf("\n[sort] thread[%d] exit barrier 0\n", tid );
187#endif
188
189    // the number of threads contributing to sort is divided by 2
190    // and the number of items is multiplied by 2 at each next stage
191    for ( i = 1 ; i < stages ; i++ )
192    {
193        if((i % 2) == 1)               // odd stage
194        {
195            src_array = array0;
196            dst_array = array1;
197        }
198        else                           // even stage
199        {
200            src_array = array1;
201            dst_array = array0;
202        }
203
204        if( (tid & ((1<<i)-1)) == 0 )
205        {
206
207#if DEBUG_SORT
208printf("\n[sort] thread[%d] : stage %d start\n", tid , i );
209#endif
210            merge( src_array, 
211                   dst_array,
212                   items << (i-1),
213                   items * tid,
214                   items * (tid + (1 << (i-1))),
215                   items * tid );
216
217#if DEBUG_SORT
218printf("\n[sort] thread[%d] : stage %d completed\n", tid , i );
219#endif
220        }
221
222        /////////////////////////////////
223        pthread_barrier_wait( &barrier );
224
225#if DEBUG_SORT
226printf("\n[sort] thread[%d] exit barrier %d\n", tid , i );
227#endif
228
229    }  // en for stages
230
231    // sort thread signal completion to pthtread_parallel_create()
232    pthread_barrier_wait( parent_barrier );
233
234#if DEBUG_SORT
235printf("\n[sort] thread[%d] exit\n", tid );
236#endif
237
238    // sort thread exit
239    pthread_exit( NULL );
240
241    return NULL;
242
243} // end sort()
244
245
246////////////////
247int main( void )
248{
249    int                    error;
250    unsigned int           x_size;             // number of rows
251    unsigned int           y_size;             // number of columns
252    unsigned int           ncores;             // number of cores per cluster
253    pthread_barrierattr_t  barrier_attr;       // barrier attributes (used for DQT)
254    unsigned int           n;                  // index in array to sort
255
256    unsigned long long     start_cycle;
257    unsigned long long     seq_end_cycle;
258    unsigned long long     para_end_cycle;
259
260    /////////////////////////
261    get_cycle( &start_cycle );
262 
263    // compute number of working threads (one thread per core)
264    get_config( &x_size , &y_size , &ncores );
265    threads = x_size * y_size * ncores;
266
267    // compute covering DQT size an level
268    unsigned int z = (x_size > y_size) ? x_size : y_size;
269    unsigned int root_level = (z == 1) ? 0 : (z == 2) ? 1 : (z == 4) ? 2 : (z == 8) ? 3 : 4;
270
271    // checks number of threads
272    if ( (threads != 1)   && (threads != 2)   && (threads != 4)   && 
273         (threads != 8)   && (threads != 16 ) && (threads != 32)  && 
274         (threads != 64)  && (threads != 128) && (threads != 256) && 
275         (threads != 512) && (threads != 1024) )
276    {
277        printf("\n[sort] ERROR : number of cores must be power of 2\n");
278        exit( 0 );
279    }
280
281    // check array size
282    if ( ARRAY_LENGTH % threads) 
283    {
284        printf("\n[sort] ERROR : array size must be multiple of number of threads\n");
285        exit( 0 );
286    }
287
288    printf("\n[sort] main starts / %d threads / %d items / pid %x / cycle %d\n",
289    threads, ARRAY_LENGTH, getpid(), (unsigned int)start_cycle );
290
291    // initialize barrier
292    if( USE_DQT_BARRIER )
293    {
294        barrier_attr.x_size   = x_size; 
295        barrier_attr.y_size   = y_size;
296        barrier_attr.nthreads = ncores;
297        error = pthread_barrier_init( &barrier, &barrier_attr , threads );
298    }
299    else // use SIMPLE_BARRIER
300    {
301        error = pthread_barrier_init( &barrier, NULL , threads );
302    }
303
304    if( error )
305    {
306        printf("\n[sort] ERROR : cannot initialise barrier\n" );
307        exit( 0 );
308    }
309
310#if DEBUG_MAIN
311if( USE_DQT_BARRIER ) printf("\n[sort] main completes DQT barrier init\n");
312else                  printf("\n[sort] main completes simple barrier init\n");
313#endif
314
315    // Array to sort initialization
316    for ( n = 0 ; n < ARRAY_LENGTH ; n++ )
317    {
318        array0[n] = ARRAY_LENGTH - n - 1;
319    }
320
321#if DISPLAY_ARRAY
322    printf("\n*** array before sort\n");
323    for( n=0; n<ARRAY_LENGTH; n++) printf("array[%d] = %d\n", n , array0[n] );
324#endif
325
326#if DEBUG_MAIN
327printf("\n[sort] main completes array init\n");
328#endif
329
330    ///////////////////////////
331    get_cycle( &seq_end_cycle );
332
333#if DEBUG_MAIN
334printf("\n[sort] main completes sequencial init at cycle %d\n",
335(unsigned int)seq_end_cycle );
336#endif
337
338    // create and execute the working threads
339    if( pthread_parallel_create( root_level,
340                                 &sort ) )
341    {
342        printf("\n[sort] ERROR : cannot create threads\n");
343        exit( 0 );
344    }
345
346    ////////////////////////////
347    get_cycle( &para_end_cycle );
348
349#if DEBUG_main
350printf("\n[sort] main completes parallel sort at cycle %d\n", 
351(unsigned int)para_end_cycle );
352#endif
353
354    // destroy barrier
355    pthread_barrier_destroy( &barrier );
356
357#if DISPLAY_ARRAY
358    printf("\n*** array after merge %d\n", i );
359    for( n=0; n<ARRAY_LENGTH; n++) printf("array[%d] = %d\n", n , dst_array[n] );
360#endif
361
362#if CHECK_RESULT
363    int    success = 1;
364    int *  res_array = ( (threads ==   2) ||
365                         (threads ==   8) || 
366                         (threads ==  32) || 
367                         (threads == 128) || 
368                         (threads == 512) ) ? array1 : array0;
369
370    for( n=0 ; n<(ARRAY_LENGTH-2) ; n++ )
371    {
372        if ( res_array[n] > res_array[n+1] )
373        {
374            printf("\n[sort] array[%d] = %d > array[%d] = %d\n",
375            n , res_array[n] , n+1 , res_array[n+1] );
376            success = 0;
377            break;
378        }
379    }
380
381    if ( success ) printf("\n[sort] success\n");
382    else           printf("\n[sort] failure\n");
383#endif
384
385#if INSTRUMENTATION
386    char               name[64];
387    char               path[128];
388    unsigned long long instru_cycle;
389
390    // build file name
391    if( USE_DQT_BARRIER )
392    snprintf( name , 64 , "p_sort_dqt_%d_%d_%d", ARRAY_LENGTH, x_size * y_size, ncores );
393    else
394    snprintf( name , 64 , "p_sort_smp_%d_%d_%d", ARRAY_LENGTH, x_size * y_size, ncores );
395
396    // build file pathname
397    snprintf( path , 128 , "home/%s" , name );
398
399    // compute results
400    unsigned int sequencial = (unsigned int)(seq_end_cycle - start_cycle);
401    unsigned int parallel   = (unsigned int)(para_end_cycle - seq_end_cycle);
402
403    // display results on process terminal
404    printf("\n----- %s -----\n"
405           " - sequencial : %d cycles\n"
406           " - parallel   : %d cycles\n", 
407           name, sequencial, parallel );
408
409    // open file
410    get_cycle( &instru_cycle );
411    FILE * stream = fopen( path , NULL );
412
413    if( stream == NULL )
414    {
415        printf("\n[sort] ERROR : cannot open instrumentation file <%s>\n", path );
416        exit(0);
417    }
418
419    printf("\n[sort] file <%s> open at cycle %d\n", path, (unsigned int)instru_cycle );
420
421#if IDBG
422idbg();
423#endif
424
425    // register results to file
426    get_cycle( &instru_cycle );
427    int ret = fprintf( stream , "\n----- %s -----\n"
428                                " - sequencial : %d cycles\n"
429                                " - parallel   : %d cycles\n", name, sequencial, parallel );
430    if( ret < 0 )
431    {
432        printf("\n[sort] ERROR : cannot write to instrumentation file <%s>\n", path );
433        exit(0);
434    }
435
436    printf("\n[sort] file <%s> written at cycle %d\n", path, (unsigned int)instru_cycle );
437
438#if IDBG
439idbg();
440#endif
441
442    // close instrumentation file
443    get_cycle( &instru_cycle );
444    ret = fclose( stream );
445
446    if( ret )
447    {
448        printf("\n[sort] ERROR : cannot close instrumentation file <%s>\n", path );
449        exit(0);
450    }
451
452    printf("\n[sort] file <%s> closed at cycle %d\n", path, (unsigned int)instru_cycle );
453
454#endif
455
456    exit( 0 );
457
458    return 0;
459
460}  // end main()
461
462/*
463vim: tabstop=4 : shiftwidth=4 : expandtab
464*/
Note: See TracBrowser for help on using the repository browser.