Main.c 18.1 KB
Newer Older
1
2
3
#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>
iker_martin's avatar
iker_martin committed
4
#include <fcntl.h>
5
#include <unistd.h>
iker_martin's avatar
iker_martin committed
6
#include <sys/stat.h>
7
8
#include "process_stage.h"
#include "Main_datatypes.h"
9
#include "configuration.h"
10
#include "../IOcodes/results.h"
11
#include "../malleability/CommDist.h"
12
13
#include "../malleability/malleabilityManager.h"
#include "../malleability/malleabilityStates.h"
14

15
16
#define DR_MAX_SIZE 1000000000

iker_martin's avatar
iker_martin committed
17
int work();
18
double iterate(int async_comm);
19
20
double iterate_relaxed(double *time, double *times_stages);
double iterate_rigid(double *time, double *times_stages);
21

22
void init_group_struct(char *argv[], int argc, int myId, int numP);
23
void init_application();
24
void obtain_op_times();
25
26
void free_application_data();

27
void print_general_info(int myId, int grp, int numP);
28
int print_local_results();
29
int print_final_results();
iker_martin's avatar
iker_martin committed
30
int create_out_file(char *nombre, int *ptr, int newstdout);
31

iker_martin's avatar
iker_martin committed
32
33
configuration *config_file;
group_data *group;
34
results_data *results;
35
MPI_Comm comm;
36
int run_id = 0; // Utilizado para diferenciar más fácilmente ejecuciones en el análisis
37

38
int main(int argc, char *argv[]) {
39
    int numP, myId, res;
iker_martin's avatar
iker_martin committed
40
    int req;
41
    int im_child;
42
    size_t i;
43

44
    int num_cpus, num_nodes;
45
    char *nodelist = NULL;
46
    num_cpus = 20; //FIXME NUMERO MAGICO //TODO Usar openMP para obtener el valor con un pragma
47
48
49
    if (argc >= 5) {
      nodelist = argv[3];
      num_nodes = atoi(argv[4]);
50
      num_cpus = num_nodes * num_cpus;
51
52
    }

53
    MPI_Init_thread(&argc, &argv, MPI_THREAD_MULTIPLE, &req);
iker_martin's avatar
iker_martin committed
54
    MPI_Comm_rank(MPI_COMM_WORLD, &myId);
55
    MPI_Comm_size(MPI_COMM_WORLD, &numP);
56
    comm = MPI_COMM_WORLD;
iker_martin's avatar
iker_martin committed
57

58
59
60
61
    if(req != MPI_THREAD_MULTIPLE) {
      printf("No se ha obtenido la configuración de hilos necesaria\nSolicitada %d -- Devuelta %d\n", req, MPI_THREAD_MULTIPLE);
    }

62
    init_group_struct(argv, argc, myId, numP);
63
    im_child = init_malleability(myId, numP, ROOT, comm, argv[0], nodelist, num_cpus, num_nodes);
64

65
    if(!im_child) { //TODO REFACTOR Simplificar inicio
66
67
      init_application();

68
      set_benchmark_grp(group->grp);
69
70
71
      set_benchmark_configuration(config_file);
      set_benchmark_results(results);

72
73
      set_malleability_configuration(config_file->groups[group->grp+1].sm, config_file->groups[group->grp+1].ss, 
	config_file->groups[group->grp+1].phy_dist, config_file->groups[group->grp+1].rm, config_file->groups[group->grp+1].rs);
74
      set_children_number(config_file->groups[group->grp+1].procs); // TODO TO BE DEPRECATED
75

76
77
78
79
      malleability_add_data(&(group->grp), 1, MAL_INT, 1, 1);
      malleability_add_data(&run_id, 1, MAL_INT, 1, 1);
      malleability_add_data(&(group->iter_start), 1, MAL_INT, 1, 1);

80
      if(config_file->sdr) {
81
82
83
	for(i=0; i<group->sync_data_groups; i++) {
          malleability_add_data(group->sync_array[i], group->sync_qty[i], MAL_CHAR, 0, 1);
	}
84
85
      }
      if(config_file->adr) {
86
87
88
	for(i=0; i<group->async_data_groups; i++) {
          malleability_add_data(group->async_array[i], group->async_qty[i], MAL_CHAR, 0, 0);
	}
89
90
      }

91
      MPI_Barrier(comm);
92
      results->exec_start = MPI_Wtime();
93
    } else { //Init hijos
94

95
      get_malleability_user_comm(&comm);
96
97
      get_benchmark_configuration(&config_file);
      get_benchmark_results(&results);
98

99
100
      // TODO Refactor - Que sea una unica funcion
      // Obtiene las variables que van a utilizar los hijos
101
      void *value = NULL;
102
      size_t entries;
103
104
      malleability_get_data(&value, 0, 1, 1);
      group->grp = *((int *)value);
105

106
107
      malleability_get_data(&value, 1, 1, 1);
      run_id = *((int *)value);
108
109
110
      
      malleability_get_data(&value, 2, 1, 1);
      group->iter_start = *((int *)value);
111

112
      if(config_file->sdr) {
113
114
115
116
117
118
        malleability_get_entries(&entries, 0, 1);
        group->sync_array = (char **) malloc(entries * sizeof(char *));
	for(i=0; i<entries; i++) {
          malleability_get_data(&value, i, 0, 1);
          group->sync_array[i] = (char *)value;
	}
119
120
      }
      if(config_file->adr) {
121
122
123
124
125
126
        malleability_get_entries(&entries, 0, 0);
        group->async_array = (char **) malloc(entries * sizeof(char *));
	for(i=0; i<entries; i++) {
          malleability_get_data(&value, i, 0, 0);
          group->async_array[i] = (char *)value;
	}
127
128
      }

129
      group->grp = group->grp + 1;
130
      realloc_results_iters(results, config_file->n_stages, config_file->groups[group->grp].iters);
131
132
    }

133
134
135
    //
    // EMPIEZA LA EJECUCION-------------------------------
    //
136
137
    group->grp = group->grp - 1; // TODO REFACTOR???
    do {
138
139
140
141

      get_malleability_user_comm(&comm);
      MPI_Comm_size(comm, &(group->numP));
      MPI_Comm_rank(comm, &(group->myId));
142
143
      group->grp = group->grp + 1;
      set_benchmark_grp(group->grp);
144

145
      if(group->grp != 0) {
146
        obtain_op_times(0); //Obtener los nuevos valores de tiempo para el computo
147
        set_results_post_reconfig(results, group->grp, config_file->sdr, config_file->adr);
148
      }
149

150
      if(config_file->n_groups != group->grp + 1) { //TODO Llevar a otra funcion
151
        set_malleability_configuration(config_file->groups[group->grp+1].sm, config_file->groups[group->grp+1].ss, 
152
			config_file->groups[group->grp+1].phy_dist, config_file->groups[group->grp+1].rm, config_file->groups[group->grp+1].rs);
153
        set_children_number(config_file->groups[group->grp+1].procs); // TODO TO BE DEPRECATED
154

155
156
        if(group->grp != 0) {
          malleability_modify_data(&(group->grp), 0, 1, MAL_INT, 1, 1);
157
        }
158
      }
159
160

      res = work();
161
      if(res == MALL_ZOMBIE) break;
162
      if(res==1) { // Se ha llegado al final de la aplicacion
163
        MPI_Barrier(comm);
164
165
        results->exec_time = MPI_Wtime() - results->exec_start - results->wasted_time;
      }
166

167
      print_local_results();
168
      reset_results_index(results);
169
    } while(config_file->n_groups > group->grp + 1 && config_file->groups[group->grp+1].sm == MALL_SPAWN_MERGE);
170

171
172
173
    //
    // TERMINA LA EJECUCION ----------------------------------------------------------
    //
174
    print_final_results(); // Pasado este punto ya no pueden escribir los procesos
175

176
    MPI_Barrier(comm);
177
178
179
180
    if(comm != MPI_COMM_WORLD && comm != MPI_COMM_NULL) {
      MPI_Comm_free(&comm);
    }

181
    if(group->myId == ROOT && config_file->groups[group->grp].sm == MALL_SPAWN_MERGE) {
182
183
      MPI_Abort(MPI_COMM_WORLD, -100);
    }
184
    free_application_data();
185

186
187
188
189
190
    MPI_Finalize();
    return 0;
}

/*
191
192
193
194
195
196
197
198
199
 * Función de trabajo principal.
 *
 * Incializa los datos para realizar el computo y a continuacion
 * pasa a realizar "maxiter" iteraciones de computo.
 *
 * Terminadas las iteraciones realiza el redimensionado de procesos.
 * Si el redimensionado se realiza de forma asincrona se 
 * siguen realizando iteraciones de computo hasta que termine la 
 * comunicacion asincrona y realizar entonces la sincrona.
200
201
202
203
 *
 * Si el grupo de procesos es el ultimo que va a ejecutar, se devuelve
 * el valor 1 para indicar que no se va a seguir trabajando con nuevos grupos
 * de procesos. En caso contrario se devuelve 0.
204
 */
iker_martin's avatar
iker_martin committed
205
int work() {
206
  int iter, maxiter, state, res;
207

208
  maxiter = config_file->groups[group->grp].iters;
209
  state = MALL_NOT_STARTED;
210

211
  res = 0;
212
  for(iter=group->iter_start; iter < maxiter; iter++) {
213
    iterate(state);
214
  }
215

216
  if(config_file->n_groups != group->grp + 1)
217
218
    state = malleability_checkpoint();

219
  iter = 0;
220
  while(state == MALL_DIST_PENDING || state == MALL_SPAWN_PENDING || state == MALL_SPAWN_SINGLE_PENDING || state == MALL_SPAWN_ADAPT_POSTPONE || state == MALL_SPAWN_ADAPT_PENDING) {
221
    if(iter < config_file->groups[group->grp+1].iters) {
222
      iterate(state);
223
224
225
      iter++;
      group->iter_start = iter;
    }
226
    state = malleability_checkpoint();
227
  }
228

229
  
230
  if(config_file->n_groups == group->grp + 1) res=1;
231
  if(state == MALL_ZOMBIE) res=state;
232
  return res;
233
234
}

235
236
237
238
239
240
241
242
243
244

/////////////////////////////////////////
/////////////////////////////////////////
//COMPUTE FUNCTIONS
/////////////////////////////////////////
/////////////////////////////////////////


/*
 * Simula la ejecucción de una iteración de computo en la aplicación
245
246
 * que dura al menos un tiempo determinado por la suma de todas las
 * etapas definidas en la configuracion.
247
 */
248
double iterate(int async_comm) {
249
  double time, *times_stages_aux;
250
  size_t i;
251
252
  double aux = 0;

253
  times_stages_aux = malloc(config_file->n_stages * sizeof(double));
254

255
  if(config_file->rigid_times) {
256
    aux = iterate_rigid(&time, times_stages_aux);
257
  } else {
258
    aux = iterate_relaxed(&time, times_stages_aux);
259
260
  }

261
262
  // Se esta realizando una redistribucion de datos asincrona
  if(async_comm == MALL_DIST_PENDING || async_comm == MALL_SPAWN_PENDING || async_comm == MALL_SPAWN_SINGLE_PENDING) { 
263
  // TODO Que diferencie entre ambas en el IO
264
    results->iters_async += 1;
265
266
  }

267
  // TODO Pasar el resto de este código a results.c
268
  if(results->iter_index == results->iters_size) { // Aumentar tamaño de ambos vectores de resultados
269
    realloc_results_iters(results, config_file->n_stages, results->iters_size + 100);
270
  }
271
  results->iters_time[results->iter_index] = time;
272
  for(i=0; i < config_file->n_stages; i++) {
273
    results->stage_times[i][results->iter_index] = times_stages_aux[i];
274
  }
275
  results->iter_index = results->iter_index + 1;
276
  // TODO Pasar hasta aqui
277

278
  free(times_stages_aux);
279

280
  return aux;
281
282
}

283
284
285

/*
 * Performs an iteration. The gathered times for iterations
286
 * and stages could be IMPRECISE in order to ensure the 
287
288
289
290
291
 * global execution time is precise.
 */
double iterate_relaxed(double *time, double *times_stages) {
  size_t i;
  double start_time, start_time_stage, aux=0;
292
  start_time = MPI_Wtime(); // Imprecise timings
293
294

  for(i=0; i < config_file->n_stages; i++) {
295
    start_time_stage = MPI_Wtime(); 
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
    aux+= process_stage(*config_file, config_file->stages[i], *group, comm);
    times_stages[i] = MPI_Wtime() - start_time_stage;
  }

  *time = MPI_Wtime() - start_time; // Guardar tiempos
  return aux;
}

/*
 * Performs an iteration. The gathered times for iterations
 * and stages are ensured to be precise but the global 
 * execution time could be imprecise.
 */
double iterate_rigid(double *time, double *times_stages) {
  size_t i;
  double start_time, start_time_stage, aux=0;

  MPI_Barrier(comm);
  start_time = MPI_Wtime();

  for(i=0; i < config_file->n_stages; i++) {
317
    MPI_Barrier(comm);
318
319
320
321
322
    start_time_stage = MPI_Wtime();
    aux+= process_stage(*config_file, config_file->stages[i], *group, comm);
    times_stages[i] = MPI_Wtime() - start_time_stage;
  }

323
  MPI_Barrier(comm);
324
325
326
327
  *time = MPI_Wtime() - start_time; // Guardar tiempos
  return aux;
}

328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
//======================================================||
//======================================================||
//=============INIT/FREE/PRINT FUNCTIONS================||
//======================================================||
//======================================================||

/*
 * Muestra datos generales sobre los procesos, su grupo,
 * en que nodo residen y la version de MPI utilizada.
 */
void print_general_info(int myId, int grp, int numP) {
  int len;
  char *name = malloc(MPI_MAX_PROCESSOR_NAME * sizeof(char));
  char *version = malloc(MPI_MAX_LIBRARY_VERSION_STRING * sizeof(char));
  MPI_Get_processor_name(name, &len);
  MPI_Get_library_version(version, &len);
  printf("P%d Nuevo GRUPO %d de %d procs en nodo %s con %s\n", myId, grp, numP, name, version);

  free(name);
  free(version);
}

350

351
352
353
/*
 * Pide al proceso raiz imprimir los datos sobre las iteraciones realizadas por el grupo de procesos.
 */
354
355
int print_local_results() {
  int ptr_local, ptr_out, err;
356
357
  char *file_name;

358
  compute_results_iter(results, group->myId, group->numP, ROOT, comm);
359
  compute_results_stages(results, group->myId, group->numP, config_file->n_stages, ROOT, comm);
360
  if(group->myId == ROOT) {
361
362
    ptr_out = dup(1);

363
364
365
366
367
368
369
370
    file_name = NULL;
    file_name = malloc(40 * sizeof(char));
    if(file_name == NULL) return -1; // No ha sido posible alojar la memoria
    err = snprintf(file_name, 40, "R%d_G%dNP%dID%d.out", run_id, group->grp, group->numP, group->myId);
    if(err < 0) return -2; // No ha sido posible obtener el nombre de fichero
    create_out_file(file_name, &ptr_local, 1);
  
    print_config_group(config_file, group->grp);
371
    print_iter_results(*results);
372
    print_stage_results(*results, config_file->n_stages);
373
374
    free(file_name);

375
    fflush(stdout);
376
377
    close(1);
    dup(ptr_out);
378
    close(ptr_out);
379
380
381
382
383
384
385
386
387
  }
  return 0;
}

/*
 * Si es el ultimo grupo de procesos, pide al proceso raiz mostrar los datos obtenidos de tiempo de ejecucion, creacion de procesos
 * y las comunicaciones.
 */
int print_final_results() {
388
  int ptr_global, err, ptr_out;
389
390
391
392
  char *file_name;

  if(group->myId == ROOT) {

393
    if(config_file->n_groups == group->grp+1) {
394
395
396
397
398
399
      file_name = NULL;
      file_name = malloc(20 * sizeof(char));
      if(file_name == NULL) return -1; // No ha sido posible alojar la memoria
      err = snprintf(file_name, 20, "R%d_Global.out", run_id);
      if(err < 0) return -2; // No ha sido posible obtener el nombre de fichero

400
      ptr_out = dup(1);
401
      create_out_file(file_name, &ptr_global, 1);
402
403
      print_config(config_file);
      print_global_results(*results, config_file->n_resizes);
404
      fflush(stdout);
405
      free(file_name);
406
407
408

      close(1);
      dup(ptr_out);
409
410
411
412
413
414
415
416
417
    }
  }
  return 0;
}

/*
 * Inicializa la estructura group
 */
void init_group_struct(char *argv[], int argc, int myId, int numP) {
418
  group = malloc(sizeof(group_data));
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
  group->myId        = myId;
  group->numP        = numP;
  group->grp         = 0;
  group->iter_start  = 0;
  group->argc        = argc;
  group->argv        = argv;
}

/*
 * Inicializa los datos para este grupo de procesos.
 *
 * En caso de ser el primer grupo de procesos, lee el fichero de configuracion
 * e inicializa los vectores de comunicacion.
 *
 * En caso de ser otro grupo de procesos entra a la funcion "Sons_init()" donde
 * se comunican con los padres para inicializar sus datos.
 */
void init_application() {
437
438
  int i, last_index;

439
440
441
442
443
444
445
446
  if(group->argc < 2) {
    printf("Falta el fichero de configuracion. Uso:\n./programa config.ini id\nEl argumento numerico id es opcional\n");
    MPI_Abort(MPI_COMM_WORLD, -1);
  }
  if(group->argc > 2) {
    run_id = atoi(group->argv[2]);
  }

447
  init_config(group->argv[1], &config_file);
448
  results = malloc(sizeof(results_data));
449
  init_results_data(results, config_file->n_resizes, config_file->n_stages, config_file->groups[group->grp].iters);
450
  if(config_file->sdr) {
451
452
453
454
455
456
457
458
459
460
    group->sync_data_groups = config_file->sdr % DR_MAX_SIZE ? config_file->sdr/DR_MAX_SIZE+1 : config_file->sdr/DR_MAX_SIZE;
    group->sync_qty = (int *) malloc(group->sync_data_groups * sizeof(int));
    group->sync_array = (char **) malloc(group->sync_data_groups * sizeof(char *));
    last_index = group->sync_data_groups-1; 
    for(i=0; i<last_index; i++) {
      group->sync_qty[i] = DR_MAX_SIZE;
      malloc_comm_array(&(group->sync_array[i]), group->sync_qty[i], group->myId, group->numP);
    }
    group->sync_qty[last_index] = config_file->sdr % DR_MAX_SIZE ? config_file->sdr % DR_MAX_SIZE : DR_MAX_SIZE;
    malloc_comm_array(&(group->sync_array[last_index]), group->sync_qty[last_index], group->myId, group->numP);
461
  }
462

463
  if(config_file->adr) {
464
465
466
467
468
469
470
471
472
473
    group->async_data_groups = config_file->adr % DR_MAX_SIZE ? config_file->adr/DR_MAX_SIZE+1 : config_file->adr/DR_MAX_SIZE;
    group->async_qty = (int *) malloc(group->async_data_groups * sizeof(int));
    group->async_array = (char **) malloc(group->async_data_groups * sizeof(char *));
    last_index = group->async_data_groups-1; 
    for(i=0; i<last_index; i++) {
      group->async_qty[i] = DR_MAX_SIZE;
      malloc_comm_array(&(group->async_array[i]), group->async_qty[i], group->myId, group->numP);
    }
    group->async_qty[last_index] = config_file->adr % DR_MAX_SIZE ? config_file->adr % DR_MAX_SIZE : DR_MAX_SIZE;
    malloc_comm_array(&(group->async_array[last_index]), group->async_qty[last_index], group->myId, group->numP);
474
  }
475
476

  obtain_op_times(1);
477
478
479
480
}

/*
 * Obtiene cuanto tiempo es necesario para realizar una operacion de PI
481
482
483
484
485
486
487
488
 *
 * Si compute esta a 1 se considera que se esta inicializando el entorno
 * y realizará trabajo extra.
 *
 * Si compute esta a 0 se considera un entorno inicializado y solo hay que
 * realizar algunos cambios de reserva de memoria. Si es necesario recalcular
 * algo se obtiene el total de tiempo utilizado en dichas tareas y se resta
 * al tiempo total de ejecucion.
489
 */
490
void obtain_op_times(int compute) {
491
  size_t i;
492
  double time = 0;
493
  for(i=0; i<config_file->n_stages; i++) {
494
    time+=init_stage(config_file, i, *group, comm, compute);
495
  }
496
  if(!compute) {results->wasted_time += time;}
497
498
499
500
501
502
}

/*
 * Libera toda la memoria asociada con la aplicacion
 */
void free_application_data() {
503
504
	// FIXME Arreglar para que se liberen estos datos
                                        if (group->grp==1000){
505
  if(config_file->sdr && group->sync_array != NULL) {
506
    free(group->sync_array);
507
    group->sync_array = NULL;
508
  }
509
  if(config_file->adr && group->async_array != NULL) {
510
    free(group->async_array);
511
    group->async_array = NULL;
512
  }
513
                                        } 
514
515
  free_malleability();

516
517
518
  free_results_data(results, config_file->n_stages);
  free(results);

519
  free_config(config_file);
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
  free(group);
}


/* 
 * Función para crear un fichero con el nombre pasado como argumento.
 * Si el nombre ya existe, se escribe la informacion a continuacion.
 *
 * El proceso que llama a la función pasa a tener como salida estandar
 * dicho fichero si el valor "newstdout" es verdadero.
 *
 */
int create_out_file(char *nombre, int *ptr, int newstdout) {
  int err;

  *ptr = open(nombre, O_WRONLY | O_CREAT | O_APPEND, 0644);
  if(*ptr < 0) return -1; // No ha sido posible crear el fichero

  if(newstdout) {
    err = close(1);
    if(err < 0) return -2; // No es posible modificar la salida estandar
    err = dup(*ptr);
    if(err < 0) return -3; // No es posible modificar la salida estandar
  }

  return 0;
}