Main.c 19.7 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
void free_application_data();
26
void free_zombie_process();
27

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

33
34
35

void init_originals();
void init_targets();
36
void update_targets();
37
void user_redistribution(void *args);
38

iker_martin's avatar
iker_martin committed
39
40
configuration *config_file;
group_data *group;
41
results_data *results;
42
MPI_Comm comm, new_comm;
43
int run_id = 0; // Utilizado para diferenciar más fácilmente ejecuciones en el análisis
44

45
int main(int argc, char *argv[]) {
46
    int numP, myId, res;
iker_martin's avatar
iker_martin committed
47
    int req;
48
    int im_child;
49
    int abort_needed = 0;
50

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

57
58
    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);
59
60
      fflush(stdout);
      MPI_Abort(MPI_COMM_WORLD, -50);
61
62
    }

63
    init_group_struct(argv, argc, myId, numP);
64
    im_child = MAM_Init(ROOT, &comm, argv[0], user_redistribution, NULL);
65

66
67
68
    if(im_child) {
      update_targets();
    } else {
69
      init_application();
70
      init_originals();
71

72
      MPI_Barrier(comm);
73
      results->exec_start = MPI_Wtime();
74
75
    }

76
77
78
    //
    // EMPIEZA LA EJECUCION-------------------------------
    //
79
    do {
80
81
      MPI_Comm_size(comm, &(group->numP));
      MPI_Comm_rank(comm, &(group->myId));
82

83
      if(group->grp != 0) {
84
        obtain_op_times(0); //Obtener los nuevos valores de tiempo para el computo
85
        MAM_Retrieve_times(&results->spawn_time[group->grp - 1], &results->sync_time[group->grp - 1], &results->async_time[group->grp - 1], &results->malleability_time[group->grp - 1]);
86
      }
87

88
      if(config_file->n_groups != group->grp + 1) { //TODO Llevar a otra funcion
89
        MAM_Set_configuration(config_file->groups[group->grp+1].sm, config_file->groups[group->grp+1].ss, 
90
			config_file->groups[group->grp+1].phy_dist, config_file->groups[group->grp+1].rm, config_file->groups[group->grp+1].rs);
91
        MAM_Set_target_number(config_file->groups[group->grp+1].procs); // TODO TO BE DEPRECATED
92

93
        if(group->grp != 0) {
94
95
          malleability_modify_data(&(group->grp), 0, 1, MPI_INT, 1, 1);
          malleability_modify_data(&(group->iter_start), 0, 1, MPI_INT, 1, 0);
96
        }
97
      }
98
99

      res = work();
100

101
      if(res==1) { // Se ha llegado al final de la aplicacion
102
        MPI_Barrier(comm);
103
        results->exec_time = MPI_Wtime() - results->exec_start - results->wasted_time;
104
        print_local_results();
105
      }
106
      
107

108
      reset_results_index(results);
109

110
      group->grp = group->grp + 1;
111
    } while(config_file->n_groups > group->grp);
112

113
114
    //
    // TERMINA LA EJECUCION ----------------------------------------------------------
115
    // 
116
    print_final_results(); // Pasado este punto ya no pueden escribir los procesos
117

118
    MPI_Barrier(comm);
119
120
121
122
    if(comm != MPI_COMM_WORLD && comm != MPI_COMM_NULL) {
      MPI_Comm_free(&comm);
    }

123
124
    if(group->myId == ROOT && config_file->groups[group->grp-1].sm == MALL_SPAWN_MERGE) {
      abort_needed = 1;
125
    }
126
    free_application_data();
127

128
    if(abort_needed) { MPI_Abort(MPI_COMM_WORLD, -100); }
129
130
131
132
133
    MPI_Finalize();
    return 0;
}

/*
134
135
136
137
138
139
140
141
142
 * 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.
143
144
145
146
 *
 * 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.
147
 */
iker_martin's avatar
iker_martin committed
148
int work() {
149
  int iter, maxiter, state, res;
150
  int wait_completed = MAM_CHECK_COMPLETION;
151

152
  maxiter = config_file->groups[group->grp].iters;
153
  state = MAM_NOT_STARTED;
154
  res = 0;
155

156
  for(iter=group->iter_start; iter < maxiter; iter++) {
157
    iterate(state);
158
  }
159

160
  if(config_file->n_groups != group->grp + 1)
161
    MAM_Checkpoint(&state, wait_completed, user_redistribution, NULL);
162

163
  iter = 0;
164
  while(state == MAM_PENDING || state == MAM_USER_PENDING) {
165
    if(group->grp+1 < config_file->n_groups && iter < config_file->groups[group->grp+1].iters) {
166
      iterate(state);
167
168
      iter++;
      group->iter_start = iter;
169
    } else { wait_completed = MAM_WAIT_COMPLETION; }
170
    MAM_Checkpoint(&state, wait_completed, user_redistribution, NULL);
171
  }
172

173
  if(config_file->n_groups == group->grp + 1) { res=1; }
174
  return res;
175
176
}

177
178
179
180
181
182
183
184
185
186

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


/*
 * Simula la ejecucción de una iteración de computo en la aplicación
187
188
 * que dura al menos un tiempo determinado por la suma de todas las
 * etapas definidas en la configuracion.
189
 */
190
double iterate(int async_comm) {
191
  double time, *times_stages_aux;
192
  size_t i;
193
194
  double aux = 0;

195
  times_stages_aux = malloc(config_file->n_stages * sizeof(double));
196

197
  if(config_file->rigid_times) {
198
    aux = iterate_rigid(&time, times_stages_aux);
199
  } else {
200
    aux = iterate_relaxed(&time, times_stages_aux);
201
202
  }

203
  // Se esta realizando una redistribucion de datos asincrona
204
  if(async_comm == MAM_PENDING) { 
205
    // TODO Que diferencie entre tipo de partes asincronas?
206
    results->iters_async += 1;
207
208
  }

209
  // TODO Pasar el resto de este código a results.c
210
  if(results->iter_index == results->iters_size) { // Aumentar tamaño de ambos vectores de resultados
211
    realloc_results_iters(results, config_file->n_stages, results->iters_size + 100);
212
  }
213
  results->iters_time[results->iter_index] = time;
214
  for(i=0; i < config_file->n_stages; i++) {
215
    results->stage_times[i][results->iter_index] = times_stages_aux[i];
216
  }
217
  results->iter_index = results->iter_index + 1;
218
  // TODO Pasar hasta aqui
219

220
  free(times_stages_aux);
221

222
  return aux;
223
224
}

225
226
227

/*
 * Performs an iteration. The gathered times for iterations
228
 * and stages could be IMPRECISE in order to ensure the 
229
230
231
232
233
 * global execution time is precise.
 */
double iterate_relaxed(double *time, double *times_stages) {
  size_t i;
  double start_time, start_time_stage, aux=0;
234
  start_time = MPI_Wtime(); // Imprecise timings
235
236

  for(i=0; i < config_file->n_stages; i++) {
237
    start_time_stage = MPI_Wtime(); 
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
    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++) {
    start_time_stage = MPI_Wtime();
    aux+= process_stage(*config_file, config_file->stages[i], *group, comm);
261
    MPI_Barrier(comm);
262
263
264
    times_stages[i] = MPI_Wtime() - start_time_stage;
  }

265
  MPI_Barrier(comm);
266
267
268
269
  *time = MPI_Wtime() - start_time; // Guardar tiempos
  return aux;
}

270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
//======================================================||
//======================================================||
//=============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);
}

292

293
294
295
/*
 * Pide al proceso raiz imprimir los datos sobre las iteraciones realizadas por el grupo de procesos.
 */
296
297
int print_local_results() {
  int ptr_local, ptr_out, err;
298
299
  char *file_name;

300
301
  // This function causes an overhead in the recorded time for last group
  compute_results_iter(results, group->myId, group->numP, ROOT, config_file->n_stages, config_file->capture_method, comm);
302
  if(group->myId == ROOT) {
303
304
    ptr_out = dup(1);

305
306
307
308
309
310
311
312
    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);
313
    print_iter_results(*results);
314
    print_stage_results(*results, config_file->n_stages);
315
316
    free(file_name);

317
    fflush(stdout);
318
319
    close(1);
    dup(ptr_out);
320
    close(ptr_out);
321
322
323
324
325
326
327
328
329
  }
  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() {
330
  int ptr_global, err, ptr_out;
331
332
333
334
  char *file_name;

  if(group->myId == ROOT) {

335
    if(config_file->n_groups == group->grp) {
336
337
338
339
340
341
      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

342
      ptr_out = dup(1);
343
      create_out_file(file_name, &ptr_global, 1);
344
345
      print_config(config_file);
      print_global_results(*results, config_file->n_resizes);
346
      fflush(stdout);
347
      free(file_name);
348
349
350

      close(1);
      dup(ptr_out);
351
352
353
354
355
356
357
358
359
    }
  }
  return 0;
}

/*
 * Inicializa la estructura group
 */
void init_group_struct(char *argv[], int argc, int myId, int numP) {
360
  group = malloc(sizeof(group_data));
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
  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() {
379
380
  int i, last_index;

381
382
383
384
385
386
387
388
  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]);
  }

389
  init_config(group->argv[1], &config_file);
390
  results = malloc(sizeof(results_data));
391
  init_results_data(results, config_file->n_resizes, config_file->n_stages, config_file->groups[group->grp].iters);
392
  if(config_file->sdr) {
393
394
395
396
397
398
399
400
401
402
    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);
403
  }
404

405
  if(config_file->adr) {
406
407
408
409
410
411
412
413
414
415
    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);
416
  }
417
418

  obtain_op_times(1);
419
420
421
422
}

/*
 * Obtiene cuanto tiempo es necesario para realizar una operacion de PI
423
424
425
426
427
428
429
430
 *
 * 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.
431
 */
432
void obtain_op_times(int compute) {
433
  size_t i;
434
  double time = 0;
435
  for(i=0; i<config_file->n_stages; i++) {
436
    time+=init_stage(config_file, i, *group, comm, compute);
437
  }
438
  if(!compute) {results->wasted_time += time;}
439
440
441
442
443
444
}

/*
 * Libera toda la memoria asociada con la aplicacion
 */
void free_application_data() {
445
446
447
448
449
450
451
452
453
  size_t i;

  if(config_file->sdr && group->sync_array != NULL) {
    for(i=0; i<group->sync_data_groups; i++) {
      free(group->sync_array[i]);
      group->sync_array[i] = NULL;
    }
    free(group->sync_qty);
    group->sync_qty = NULL;
454
    free(group->sync_array);
455
456
    group->sync_array = NULL;

457
  }
458
459
460
461
462
463
464
  if(config_file->adr && group->async_array != NULL) {
    for(i=0; i<group->async_data_groups; i++) {
      free(group->async_array[i]);
      group->async_array[i] = NULL;
    }
    free(group->async_qty);
    group->async_qty = NULL;
465
    free(group->async_array);
466
    group->async_array = NULL;
467
  }
468
  MAM_Finalize();
469
470
  free_zombie_process();
}
471

472
473
474
475
476

/*
 * Libera la memoria asociada a un proceso Zombie
 */
void free_zombie_process() {
477
478
479
  free_results_data(results, config_file->n_stages);
  free(results);

480
  free_config(config_file);
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
  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;
}
509
510
511
512
513
514
515
516
517
518
519
520


//======================================================||
//======================================================||
//================ INIT MALLEABILITY ===================||
//======================================================||
//======================================================||

void init_originals() {
  size_t i;

  if(config_file->n_groups > 1) {
521
    MAM_Set_configuration(config_file->groups[group->grp+1].sm, config_file->groups[group->grp+1].ss, 
522
      config_file->groups[group->grp+1].phy_dist, config_file->groups[group->grp+1].rm, config_file->groups[group->grp+1].rs);
523
    MAM_Set_target_number(config_file->groups[group->grp+1].procs);
524

525
526
    malleability_add_data(&(group->grp), 1, MPI_INT, 1, 1);
    malleability_add_data(&run_id, 1, MPI_INT, 1, 1);
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
    malleability_add_data(&(group->iter_start), 1, MPI_INT, 1, 0);

    if(config_file->sdr) {
      for(i=0; i<group->sync_data_groups; i++) {
        malleability_add_data(group->sync_array[i], group->sync_qty[i], MPI_CHAR, 0, 0);
      }
    }
    if(config_file->adr) {
      for(i=0; i<group->async_data_groups; i++) {
        malleability_add_data(group->async_array[i], group->async_qty[i], MPI_CHAR, 0, 1);
      }
    }
  }
}

void init_targets() {
543
544
  size_t i, entries;
  void *value = NULL;
545

546
  malleability_get_data(&value, 0, 1, 1);
547
548
549
  group->grp = *((int *)value);
  group->grp = group->grp + 1;

550
  recv_config_file(ROOT, new_comm, &config_file);
551
552
553
  results = malloc(sizeof(results_data));
  init_results_data(results, config_file->n_resizes, config_file->n_stages, config_file->groups[group->grp].iters);
  results_comm(results, ROOT, config_file->n_resizes, new_comm);
554

555
  malleability_get_data(&value, 1, 1, 1);
556
557
  run_id = *((int *)value);
      
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
  if(config_file->adr) {
    malleability_get_entries(&entries, 0, 1);
    group->async_qty = (int *) malloc(entries * sizeof(int));
    group->async_array = (char **) malloc(entries * sizeof(char *));
    for(i=0; i<entries; i++) {
      malleability_get_data(&value, i, 0, 1);
      group->async_array[i] = (char *)value;
      group->async_qty[i] = DR_MAX_SIZE;
    }
    group->async_qty[entries-1] = config_file->adr % DR_MAX_SIZE ? config_file->adr % DR_MAX_SIZE : DR_MAX_SIZE;
    group->async_data_groups = entries;
  }
}

void update_targets() { //FIXME Should not be needed after redist -- Declarar antes
  size_t i, entries;
  void *value = NULL;

  malleability_get_data(&value, 0, 1, 0);
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
  group->iter_start = *((int *)value);

  if(config_file->sdr) {
    malleability_get_entries(&entries, 0, 0);
    group->sync_qty = (int *) malloc(entries * sizeof(int));
    group->sync_array = (char **) malloc(entries * sizeof(char *));
    for(i=0; i<entries; i++) {
      malleability_get_data(&value, i, 0, 0);
      group->sync_array[i] = (char *)value;
      group->sync_qty[i] = DR_MAX_SIZE;
    }
    group->sync_qty[entries-1] = config_file->sdr % DR_MAX_SIZE ? config_file->sdr % DR_MAX_SIZE : DR_MAX_SIZE;
    group->sync_data_groups = entries;
  }
}
592
593
594
595
596
597
598

void user_redistribution(void *args) {
  int commited;
  mam_user_reconf_t user_reconf;

  MAM_Get_Reconf_Info(&user_reconf);
  new_comm = user_reconf.comm;
599
  if(user_reconf.rank_state == MAM_PROC_NEW_RANK) {
600
601
602
603
604
605
    init_targets();
  } else {
    send_config_file(config_file, ROOT, new_comm);
    results_comm(results, ROOT, config_file->n_resizes, new_comm);

    print_local_results();
606
607
608
    if(user_reconf.rank_state == MAM_PROC_ZOMBIE) {
      free_zombie_process();
    }
609
610
  }

611
  MAM_Resume_redistribution(&commited);
612
}