-
Notifications
You must be signed in to change notification settings - Fork 78
Expand file tree
/
Copy pathengine.c
More file actions
3955 lines (3337 loc) · 135 KB
/
engine.c
File metadata and controls
3955 lines (3337 loc) · 135 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
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
78
79
80
81
82
83
84
85
86
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
128
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
292
293
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
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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
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
549
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
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
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
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
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
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*******************************************************************************
* This file is part of SWIFT.
* Copyright (c) 2012 Pedro Gonnet (pedro.gonnet@durham.ac.uk)
* Matthieu Schaller (schaller@strw.leidenuniv.nl)
* 2015 Peter W. Draper (p.w.draper@durham.ac.uk)
* Angus Lepper (angus.lepper@ed.ac.uk)
* 2016 John A. Regan (john.a.regan@durham.ac.uk)
* Tom Theuns (tom.theuns@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/>.
*
******************************************************************************/
/* Config parameters. */
#include <config.h>
/* Some standard headers. */
#include <float.h>
#include <limits.h>
#include <sched.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
/* MPI headers. */
#ifdef WITH_MPI
#include <mpi.h>
#endif
#ifdef HAVE_LIBNUMA
#include <numa.h>
#include <numaif.h>
#endif
/* This object's header. */
#include "engine.h"
/* Local headers. */
#include "active.h"
#include "atomic.h"
#include "black_holes_properties.h"
#include "cell.h"
#include "chemistry.h"
#include "clocks.h"
#include "cooling.h"
#include "cooling_properties.h"
#include "cosmology.h"
#include "csds.h"
#include "csds_io.h"
#include "cycle.h"
#include "debug.h"
#include "equation_of_state.h"
#include "error.h"
#include "extra_io.h"
#include "feedback.h"
#include "fof.h"
#include "forcing.h"
#include "gravity.h"
#include "gravity_cache.h"
#include "hydro.h"
#include "lightcone/lightcone.h"
#include "lightcone/lightcone_array.h"
#include "line_of_sight.h"
#include "map.h"
#include "memuse.h"
#include "minmax.h"
#include "mpiuse.h"
#include "multipole_struct.h"
#include "neutrino.h"
#include "neutrino_properties.h"
#include "output_list.h"
#include "output_options.h"
#include "partition.h"
#include "potential.h"
#include "power_spectrum.h"
#include "pressure_floor.h"
#include "profiler.h"
#include "proxy.h"
#include "restart.h"
#include "rt_properties.h"
#include "runner.h"
#include "sink_properties.h"
#include "sort_part.h"
#include "star_formation.h"
#include "star_formation_logger.h"
#include "stars_io.h"
#include "statistics.h"
#include "timers.h"
#include "tools.h"
#include "units.h"
#include "velociraptor_interface.h"
const char *engine_policy_names[] = {"none",
"rand",
"steal",
"keep",
"block",
"cpu tight",
"mpi",
"numa affinity",
"hydro",
"self gravity",
"external gravity",
"cosmological integration",
"drift everything",
"reconstruct multi-poles",
"temperature",
"cooling",
"stars",
"structure finding",
"star formation",
"feedback",
"black holes",
"fof search",
"time-step limiter",
"time-step sync",
"csds",
"line of sight",
"sink",
"rt",
"power spectra"};
const int engine_default_snapshot_subsample[swift_type_count] = {0};
/** The rank of the engine as a global variable (for messages). */
int engine_rank;
/** The current step of the engine as a global variable (for messages). */
int engine_current_step;
/**
* @brief Link a density/force task to a cell.
*
* @param e The #engine.
* @param l A pointer to the #link, will be modified atomically.
* @param t The #task.
*
* @return The new #link pointer.
*/
void engine_addlink(struct engine *e, struct link **l, struct task *t) {
#ifdef SWIFT_DEBUG_CHECKS
if (t == NULL) {
error("Trying to link NULL task.");
}
#endif
/* Get the next free link. */
const size_t ind = atomic_inc(&e->nr_links);
if (ind >= e->size_links) {
error(
"Link table overflow. Increase the value of "
"`Scheduler:links_per_tasks`.");
}
struct link *res = &e->links[ind];
/* Set it atomically. */
res->t = t;
res->next = atomic_swap(l, res);
}
/**
* @brief Repartition the cells amongst the nodes.
*
* @param e The #engine.
*/
void engine_repartition(struct engine *e) {
#if defined(WITH_MPI) && \
(defined(HAVE_PARMETIS) || defined(HAVE_METIS) || defined(HAVE_SCOTCH))
ticks tic = getticks();
#ifdef SWIFT_DEBUG_CHECKS
/* Be verbose about this. */
if (e->nodeID == 0 || e->verbose) message("repartitioning space");
fflush(stdout);
/* Check that all cells have been drifted to the current time */
space_check_drift_point(e->s, e->ti_current, /*check_multipoles=*/0);
#endif
/* Clear the repartition flag. */
e->forcerepart = 0;
/* Nothing to do if only using a single node. Also avoids METIS
* bug that doesn't handle this case well. */
if (e->nr_nodes == 1) return;
/* Generate the fixed costs include file. */
if (e->step > 3 && e->reparttype->trigger <= 1.f) {
task_dump_stats("partition_fixed_costs.h", e,
/* task_dump_threshold = */ 0.f,
/* header = */ 1, /* allranks = */ 1);
}
/* Do the repartitioning. */
partition_repartition(e->reparttype, e->nodeID, e->nr_nodes, e->s,
e->sched.tasks, e->sched.nr_tasks);
/* Partitioning requires copies of the particles, so we need to reduce the
* memory in use to the minimum, we can free the sorting indices and the
* tasks as these will be regenerated at the next rebuild. Also the foreign
* particle arrays can go as these will be regenerated in proxy exchange. */
/* Sorting indices. */
if (e->s->cells_top != NULL) space_free_cells(e->s);
/* Report the time spent in the different task categories */
if (e->verbose) scheduler_report_task_times(&e->sched, e->nr_threads);
/* Task arrays. */
scheduler_free_tasks(&e->sched);
/* Foreign parts. (no need to nullify the cell pointers as the cells
* will be regenerated) */
space_free_foreign_parts(e->s, /*clear_cell_pointers=*/0);
/* Now comes the tricky part: Exchange particles between all nodes.
This is done in two steps, first allreducing a matrix of
how many particles go from where to where, then re-allocating
the parts array, and emitting the sends and receives.
Finally, the space, tasks, and proxies need to be rebuilt. */
/* Redistribute the particles between the nodes. */
engine_redistribute(e);
/* Make the proxies. */
engine_makeproxies(e);
/* Tell the engine it should re-build whenever possible */
e->forcerebuild = 1;
/* Flag that a repartition has taken place */
e->step_props |= engine_step_prop_repartition;
if (e->verbose)
message("took %.3f %s.", clocks_from_ticks(getticks() - tic),
clocks_getunit());
#else
if (e->reparttype->type != REPART_NONE)
error("SWIFT was not compiled with MPI and METIS, ParMETIS or SCOTCH support.");
/* Clear the repartition flag. */
e->forcerepart = 0;
#endif
}
/**
* @brief Decide whether trigger a repartition the cells amongst the nodes.
*
* @param e The #engine.
*/
void engine_repartition_trigger(struct engine *e) {
#ifdef WITH_MPI
const ticks tic = getticks();
static int opened = 0;
if (e->restarting) opened = 1;
/* Do nothing if there have not been enough steps since the last repartition
* as we don't want to repeat this too often or immediately after a
* repartition step, or also immediately on restart. We check all this
* even when we are not repartitioning as the balance logs can still be
* interesting. */
if (e->step - e->last_repartition >= 2 && !e->restarting) {
/* If we have fixed costs available and this is step 2 or we are forcing
* repartitioning then we do a forced fixed costs repartition regardless. */
int forced = 0;
if (e->reparttype->type != REPART_NONE) {
if (e->reparttype->trigger > 1 ||
(e->step == 2 && e->reparttype->use_fixed_costs)) {
if (e->reparttype->trigger > 1) {
if ((e->step % (int)e->reparttype->trigger) == 0) e->forcerepart = 1;
} else {
e->forcerepart = 1;
}
e->reparttype->use_ticks = 0;
forced = 1;
}
}
/* We only check the CPU loads when we have processed a significant number
* of all particles as we require all tasks to have timings or are
* interested in the various balances logs. */
if ((e->updates > 1 &&
e->updates >= e->total_nr_parts * e->reparttype->minfrac) ||
(e->g_updates > 1 &&
e->g_updates >= e->total_nr_gparts * e->reparttype->minfrac)) {
/* Are we using the task tick timings or fixed costs? */
if (e->reparttype->use_fixed_costs > 1) {
e->reparttype->use_ticks = 0;
} else {
e->reparttype->use_ticks = 1;
}
/* Get the resident size of the process for the memory logs. */
long size, resident, shared, text, library, data, dirty;
memuse_use(&size, &resident, &shared, &text, &data, &library, &dirty);
/* Gather it together with the CPU times used by the tasks in the last
* step (and the deadtime fraction, for output). */
double timemem[4] = {
e->usertime_last_step, e->systime_last_step, (double)resident,
e->local_deadtime / (e->nr_threads * e->wallclock_time)};
double timemems[e->nr_nodes * 4];
MPI_Gather(&timemem, 4, MPI_DOUBLE, timemems, 4, MPI_DOUBLE, 0,
MPI_COMM_WORLD);
if (e->nodeID == 0) {
/* Get the range and mean of the two CPU times and memory. */
double umintime = timemems[0];
double umaxtime = timemems[0];
double smintime = timemems[1];
double smaxtime = timemems[1];
double minmem = timemems[2];
double maxmem = timemems[2];
double tmintime = umintime + smintime;
double tmaxtime = umaxtime + smaxtime;
double usum = timemems[0];
double ssum = timemems[1];
double tsum = usum + ssum;
double msum = timemems[2];
for (int k = 4; k < e->nr_nodes * 4; k += 4) {
if (timemems[k] > umaxtime) umaxtime = timemems[k];
if (timemems[k] < umintime) umintime = timemems[k];
if (timemems[k + 1] > smaxtime) smaxtime = timemems[k + 1];
if (timemems[k + 1] < smintime) smintime = timemems[k + 1];
double total = timemems[k] + timemems[k + 1];
if (total > tmaxtime) tmaxtime = total;
if (total < tmintime) tmintime = total;
usum += timemems[k];
ssum += timemems[k + 1];
tsum += total;
if (timemems[k + 2] > maxmem) maxmem = timemems[k + 2];
if (timemems[k + 2] < minmem) minmem = timemems[k + 2];
msum += timemems[k + 2];
}
double umean = usum / (double)e->nr_nodes;
double smean = ssum / (double)e->nr_nodes;
double tmean = tsum / (double)e->nr_nodes;
double mmean = msum / (double)e->nr_nodes;
/* Are we out of balance and need to repartition? */
/* ---------------------------------------------- */
double abs_trigger = fabs(e->reparttype->trigger);
double balance = (umaxtime - umintime) / umean;
if (e->reparttype->type != REPART_NONE) {
/* When forced we don't care about the balance. */
if (!forced) {
if (balance > abs_trigger) {
if (e->verbose)
message("trigger fraction %.3f > %.3f will repartition",
balance, abs_trigger);
e->forcerepart = 1;
} else {
if (e->verbose && e->reparttype->type != REPART_NONE)
message("trigger fraction %.3f =< %.3f will not repartition",
balance, abs_trigger);
}
}
} else {
/* Not repartitioning, would that have been done otherwise? */
if (e->verbose) {
if (balance > abs_trigger) {
message("trigger fraction %.3f > %.3f would have repartitioned",
balance, abs_trigger);
} else {
message(
"trigger fraction %.3f =< %.3f would not have repartitioned",
balance, abs_trigger);
}
}
}
/* Keep logs of all CPU times and resident memory size for debugging
* load issues. */
FILE *timelog = NULL;
FILE *memlog = NULL;
if (!opened) {
timelog = fopen("rank_cpu_balance.log", "w");
if (timelog == NULL)
error("Could not create file 'rank_cpu_balance.log'.");
fprintf(timelog, "# step rank user sys sum deadfrac\n");
memlog = fopen("rank_memory_balance.log", "w");
if (memlog == NULL)
error("Could not create file 'rank_memory_balance.log'.");
fprintf(memlog, "# step rank resident\n");
opened = 1;
} else {
timelog = fopen("rank_cpu_balance.log", "a");
if (timelog == NULL)
error("Could not open file 'rank_cpu_balance.log' for writing.");
memlog = fopen("rank_memory_balance.log", "a");
if (memlog == NULL)
error("Could not open file 'rank_memory_balance.log' for writing.");
}
for (int k = 0; k < e->nr_nodes * 4; k += 4) {
fprintf(timelog, "%d %d %f %f %f %f\n", e->step, k / 4, timemems[k],
timemems[k + 1], timemems[k] + timemems[k + 1],
timemems[k + 3]);
fprintf(memlog, "%d %d %ld\n", e->step, k / 4, (long)timemems[k + 2]);
}
fprintf(timelog, "# %d mean times: %f %f %f\n", e->step, umean, smean,
tmean);
if (abs_trigger > 1.f) abs_trigger = 0.f; /* Not relevant. */
double systime = smean > 0. ? (smaxtime - smintime) / smean : 0.;
double ttime = tmean > 0. ? (tmaxtime - tmintime) / tmean : 0.;
fprintf(timelog,
"# %d balance: %f, expected: %f (sys: %f, total: %f)\n",
e->step, balance, abs_trigger, systime, ttime);
fclose(timelog);
fprintf(memlog, "# %d mean resident memory: %f, balance: %f\n", e->step,
mmean, (maxmem - minmem) / mmean);
fclose(memlog);
}
/* All nodes do this together, so send to other ranks. */
MPI_Bcast(&e->forcerepart, 1, MPI_INT, 0, MPI_COMM_WORLD);
}
/* Remember we did this. */
if (e->forcerepart) e->last_repartition = e->step;
}
if (e->verbose)
message("took %.3f %s", clocks_from_ticks(getticks() - tic),
clocks_getunit());
#endif
}
/**
* @brief Exchange cell structures with other nodes.
*
* @param e The #engine.
*/
void engine_exchange_cells(struct engine *e) {
#ifdef WITH_MPI
const int with_gravity = e->policy & engine_policy_self_gravity;
const ticks tic = getticks();
/* Exchange the cell structure with neighbouring ranks. */
proxy_cells_exchange(e->proxies, e->nr_proxies, e->s, with_gravity);
if (e->verbose)
message("took %.3f %s.", clocks_from_ticks(getticks() - tic),
clocks_getunit());
#else
error("SWIFT was not compiled with MPI support.");
#endif
}
/**
* @brief Exchanges the top-level multipoles between all the nodes
* such that every node has a multipole for each top-level cell.
*
* @param e The #engine.
*/
void engine_exchange_top_multipoles(struct engine *e) {
#ifdef WITH_MPI
ticks tic = getticks();
#ifdef SWIFT_DEBUG_CHECKS
for (int i = 0; i < e->s->nr_cells; ++i) {
const struct gravity_tensors *m = &e->s->multipoles_top[i];
if (e->s->cells_top[i].nodeID == engine_rank) {
if (m->m_pole.M_000 > 0.) {
if (m->CoM[0] < 0. || m->CoM[0] > e->s->dim[0])
error("Invalid multipole position in X");
if (m->CoM[1] < 0. || m->CoM[1] > e->s->dim[1])
error("Invalid multipole position in Y");
if (m->CoM[2] < 0. || m->CoM[2] > e->s->dim[2])
error("Invalid multipole position in Z");
}
} else {
if (m->m_pole.M_000 != 0.) error("Non-zero mass for foreign m-pole");
if (m->CoM[0] != 0.) error("Non-zero position in X for foreign m-pole");
if (m->CoM[1] != 0.) error("Non-zero position in Y for foreign m-pole");
if (m->CoM[2] != 0.) error("Non-zero position in Z for foreign m-pole");
if (m->m_pole.num_gpart != 0)
error("Non-zero gpart count in foreign m-pole");
}
}
#endif
/* Each node (space) has constructed its own top-level multipoles.
* We now need to make sure every other node has a copy of everything.
*
* We use our home-made reduction operation that simply performs a XOR
* operation on the multipoles. Since only local multipoles are non-zero and
* each multipole is only present once, the bit-by-bit XOR will
* create the desired result.
*/
int err = MPI_Allreduce(MPI_IN_PLACE, e->s->multipoles_top, e->s->nr_cells,
multipole_mpi_type, multipole_mpi_reduce_op,
MPI_COMM_WORLD);
if (err != MPI_SUCCESS)
mpi_error(err, "Failed to all-reduce the top-level multipoles.");
#ifdef SWIFT_DEBUG_CHECKS
long long counter = 0;
/* Let's check that what we received makes sense */
for (int i = 0; i < e->s->nr_cells; ++i) {
const struct gravity_tensors *m = &e->s->multipoles_top[i];
counter += m->m_pole.num_gpart;
if (m->m_pole.num_gpart < 0) {
error("m->m_pole.num_gpart is negative: %lld", m->m_pole.num_gpart);
}
if (m->m_pole.M_000 > 0.) {
if (m->CoM[0] < 0. || m->CoM[0] > e->s->dim[0])
error("Invalid multipole position in X");
if (m->CoM[1] < 0. || m->CoM[1] > e->s->dim[1])
error("Invalid multipole position in Y");
if (m->CoM[2] < 0. || m->CoM[2] > e->s->dim[2])
error("Invalid multipole position in Z");
}
}
if (counter != e->total_nr_gparts)
error(
"Total particles in multipoles inconsistent with engine.\n "
" counter = %lld, nr_gparts = %lld",
counter, e->total_nr_gparts);
#endif
if (e->verbose)
message("took %.3f %s.", clocks_from_ticks(getticks() - tic),
clocks_getunit());
#else
error("SWIFT was not compiled with MPI support.");
#endif
}
void engine_exchange_proxy_multipoles(struct engine *e) {
#ifdef WITH_MPI
const ticks tic = getticks();
/* Start by counting the number of cells to send and receive */
int count_send_cells = 0;
int count_recv_cells = 0;
int count_send_requests = 0;
int count_recv_requests = 0;
/* Loop over the proxies. */
for (int pid = 0; pid < e->nr_proxies; pid++) {
/* Get a handle on the proxy. */
const struct proxy *p = &e->proxies[pid];
/* Now collect the number of requests associated */
count_recv_requests += p->nr_cells_in;
count_send_requests += p->nr_cells_out;
/* And the actual number of things we are going to ship */
for (int k = 0; k < p->nr_cells_in; k++)
count_recv_cells += p->cells_in[k]->mpi.pcell_size;
for (int k = 0; k < p->nr_cells_out; k++)
count_send_cells += p->cells_out[k]->mpi.pcell_size;
}
/* Allocate the buffers for the packed data */
struct gravity_tensors *buffer_send = NULL;
if (swift_memalign("send_gravity_tensors", (void **)&buffer_send,
SWIFT_CACHE_ALIGNMENT,
count_send_cells * sizeof(struct gravity_tensors)) != 0)
error("Unable to allocate memory for multipole transactions");
struct gravity_tensors *buffer_recv = NULL;
if (swift_memalign("recv_gravity_tensors", (void **)&buffer_recv,
SWIFT_CACHE_ALIGNMENT,
count_recv_cells * sizeof(struct gravity_tensors)) != 0)
error("Unable to allocate memory for multipole transactions");
/* Also allocate the MPI requests */
const int count_requests = count_send_requests + count_recv_requests;
MPI_Request *requests =
(MPI_Request *)malloc(sizeof(MPI_Request) * count_requests);
if (requests == NULL) error("Unable to allocate memory for MPI requests");
int this_request = 0;
int this_recv = 0;
int this_send = 0;
/* Loop over the proxies to issue the receives. */
for (int pid = 0; pid < e->nr_proxies; pid++) {
/* Get a handle on the proxy. */
const struct proxy *p = &e->proxies[pid];
for (int k = 0; k < p->nr_cells_in; k++) {
const int num_elements = p->cells_in[k]->mpi.pcell_size;
/* Receive everything */
MPI_Irecv(&buffer_recv[this_recv], num_elements, multipole_mpi_type,
p->cells_in[k]->nodeID, p->cells_in[k]->mpi.tag, MPI_COMM_WORLD,
&requests[this_request]);
/* Move to the next slot in the buffers */
this_recv += num_elements;
this_request++;
}
/* Loop over the proxies to issue the sends. */
for (int k = 0; k < p->nr_cells_out; k++) {
/* Number of multipoles in this cell hierarchy */
const int num_elements = p->cells_out[k]->mpi.pcell_size;
/* Let's pack everything recursively */
cell_pack_multipoles(p->cells_out[k], &buffer_send[this_send]);
/* Send everything (note the use of cells_in[0] to get the correct node
* ID. */
MPI_Isend(&buffer_send[this_send], num_elements, multipole_mpi_type,
p->cells_in[0]->nodeID, p->cells_out[k]->mpi.tag,
MPI_COMM_WORLD, &requests[this_request]);
/* Move to the next slot in the buffers */
this_send += num_elements;
this_request++;
}
}
/* Wait for all the requests to arrive home */
MPI_Status *stats = (MPI_Status *)malloc(count_requests * sizeof(MPI_Status));
int res;
if ((res = MPI_Waitall(count_requests, requests, stats)) != MPI_SUCCESS) {
for (int k = 0; k < count_requests; ++k) {
char buff[MPI_MAX_ERROR_STRING];
MPI_Error_string(stats[k].MPI_ERROR, buff, &res);
message("request from source %i, tag %i has error '%s'.",
stats[k].MPI_SOURCE, stats[k].MPI_TAG, buff);
}
error("Failed during waitall for multipole data.");
}
/* Let's now unpack the multipoles at the right place */
this_recv = 0;
for (int pid = 0; pid < e->nr_proxies; pid++) {
/* Get a handle on the proxy. */
const struct proxy *p = &e->proxies[pid];
for (int k = 0; k < p->nr_cells_in; k++) {
const int num_elements = p->cells_in[k]->mpi.pcell_size;
#ifdef SWIFT_DEBUG_CHECKS
/* Check that the first element (top-level cell's multipole) matches what
* we received */
if (p->cells_in[k]->grav.multipole->m_pole.num_gpart !=
buffer_recv[this_recv].m_pole.num_gpart)
error("Current: M_000=%e num_gpart=%lld\n New: M_000=%e num_gpart=%lld",
p->cells_in[k]->grav.multipole->m_pole.M_000,
p->cells_in[k]->grav.multipole->m_pole.num_gpart,
buffer_recv[this_recv].m_pole.M_000,
buffer_recv[this_recv].m_pole.num_gpart);
#endif
/* Unpack recursively */
cell_unpack_multipoles(p->cells_in[k], &buffer_recv[this_recv]);
/* Move to the next slot in the buffers */
this_recv += num_elements;
}
}
/* Free everything */
free(stats);
free(buffer_send);
free(buffer_recv);
free(requests);
/* How much time did this take? */
if (e->verbose)
message("took %.3f %s.", clocks_from_ticks(getticks() - tic),
clocks_getunit());
#else
error("SWIFT was not compiled with MPI support.");
#endif
}
/**
* @brief Allocate memory for the foreign particles.
*
* We look into the proxies for cells that have tasks and count
* the number of particles in these cells. We then allocate
* memory and link all the cells that have tasks and all cells
* deeper in the tree.
*
* When running FOF, we only need #gpart arrays so we restrict
* the allocations to this particle type only
*
* @param e The #engine.
* @param fof Are we allocating buffers just for FOF?
*/
void engine_allocate_foreign_particles(struct engine *e, const int fof) {
#ifdef WITH_MPI
const int nr_proxies = e->nr_proxies;
const int with_hydro = e->policy & engine_policy_hydro;
const int with_stars = e->policy & engine_policy_stars;
const int with_black_holes = e->policy & engine_policy_black_holes;
struct space *s = e->s;
ticks tic = getticks();
/* Count the number of particles we need to import and re-allocate
the buffer if needed. */
size_t count_parts_in = 0, count_gparts_in = 0, count_sparts_in = 0,
count_bparts_in = 0;
for (int k = 0; k < nr_proxies; k++) {
for (int j = 0; j < e->proxies[k].nr_cells_in; j++) {
if (e->proxies[k].cells_in_type[j] & proxy_cell_type_hydro) {
count_parts_in += cell_count_parts_for_tasks(e->proxies[k].cells_in[j]);
}
if (e->proxies[k].cells_in_type[j] & proxy_cell_type_gravity) {
count_gparts_in +=
cell_count_gparts_for_tasks(e->proxies[k].cells_in[j]);
}
/* For stars, we just use the numbers in the top-level cells */
count_sparts_in +=
e->proxies[k].cells_in[j]->stars.count + space_extra_sparts;
/* For black holes, we just use the numbers in the top-level cells */
count_bparts_in += e->proxies[k].cells_in[j]->black_holes.count;
}
}
if (!with_hydro && count_parts_in)
error(
"Not running with hydro but about to receive gas particles in "
"proxies!");
if (!with_stars && count_sparts_in)
error("Not running with stars but about to receive stars in proxies!");
if (!with_black_holes && count_bparts_in)
error(
"Not running with black holes but about to receive black holes in "
"proxies!");
if (e->verbose)
message("Counting number of foreign particles took %.3f %s.",
clocks_from_ticks(getticks() - tic), clocks_getunit());
tic = getticks();
/* Allocate space for the foreign particles we will receive */
size_t old_size_parts_foreign = s->size_parts_foreign;
if (!fof && count_parts_in > s->size_parts_foreign) {
if (s->parts_foreign != NULL) swift_free("parts_foreign", s->parts_foreign);
s->size_parts_foreign = engine_foreign_alloc_margin * count_parts_in;
if (swift_memalign("parts_foreign", (void **)&s->parts_foreign, part_align,
sizeof(struct part) * s->size_parts_foreign) != 0)
error("Failed to allocate foreign part data.");
}
/* Allocate space for the foreign particles we will receive */
size_t old_size_gparts_foreign = s->size_gparts_foreign;
if (count_gparts_in > s->size_gparts_foreign) {
if (s->gparts_foreign != NULL)
swift_free("gparts_foreign", s->gparts_foreign);
s->size_gparts_foreign = engine_foreign_alloc_margin * count_gparts_in;
if (swift_memalign("gparts_foreign", (void **)&s->gparts_foreign,
gpart_align,
sizeof(struct gpart) * s->size_gparts_foreign) != 0)
error("Failed to allocate foreign gpart data.");
}
/* Allocate space for the foreign particles we will receive */
size_t old_size_sparts_foreign = s->size_sparts_foreign;
if (!fof && count_sparts_in > s->size_sparts_foreign) {
if (s->sparts_foreign != NULL)
swift_free("sparts_foreign", s->sparts_foreign);
s->size_sparts_foreign = engine_foreign_alloc_margin * count_sparts_in;
if (swift_memalign("sparts_foreign", (void **)&s->sparts_foreign,
spart_align,
sizeof(struct spart) * s->size_sparts_foreign) != 0)
error("Failed to allocate foreign spart data.");
bzero(s->sparts_foreign, s->size_sparts_foreign * sizeof(struct spart));
for (size_t i = 0; i < s->size_sparts_foreign; ++i) {
s->sparts_foreign[i].time_bin = time_bin_not_created;
s->sparts_foreign[i].id = -43;
}
}
/* Allocate space for the foreign particles we will receive */
size_t old_size_bparts_foreign = s->size_bparts_foreign;
if (!fof && count_bparts_in > s->size_bparts_foreign) {
if (s->bparts_foreign != NULL)
swift_free("bparts_foreign", s->bparts_foreign);
s->size_bparts_foreign = engine_foreign_alloc_margin * count_bparts_in;
if (swift_memalign("bparts_foreign", (void **)&s->bparts_foreign,
bpart_align,
sizeof(struct bpart) * s->size_bparts_foreign) != 0)
error("Failed to allocate foreign bpart data.");
}
if (e->verbose) {
message(
"Allocating %zd/%zd/%zd/%zd foreign part/gpart/spart/bpart "
"(%zd/%zd/%zd/%zd MB)",
s->size_parts_foreign, s->size_gparts_foreign, s->size_sparts_foreign,
s->size_bparts_foreign,
s->size_parts_foreign * sizeof(struct part) / (1024 * 1024),
s->size_gparts_foreign * sizeof(struct gpart) / (1024 * 1024),
s->size_sparts_foreign * sizeof(struct spart) / (1024 * 1024),
s->size_bparts_foreign * sizeof(struct bpart) / (1024 * 1024));
if ((s->size_parts_foreign - old_size_parts_foreign) > 0 ||
(s->size_gparts_foreign - old_size_gparts_foreign) > 0 ||
(s->size_sparts_foreign - old_size_sparts_foreign) > 0 ||
(s->size_bparts_foreign - old_size_bparts_foreign) > 0) {
message(
"Re-allocations %zd/%zd/%zd/%zd part/gpart/spart/bpart "
"(%zd/%zd/%zd/%zd MB)",
(s->size_parts_foreign - old_size_parts_foreign),
(s->size_gparts_foreign - old_size_gparts_foreign),
(s->size_sparts_foreign - old_size_sparts_foreign),
(s->size_bparts_foreign - old_size_bparts_foreign),
(s->size_parts_foreign - old_size_parts_foreign) *
sizeof(struct part) / (1024 * 1024),
(s->size_gparts_foreign - old_size_gparts_foreign) *
sizeof(struct gpart) / (1024 * 1024),
(s->size_sparts_foreign - old_size_sparts_foreign) *
sizeof(struct spart) / (1024 * 1024),
(s->size_bparts_foreign - old_size_bparts_foreign) *
sizeof(struct bpart) / (1024 * 1024));
}
}
/* Unpack the cells and link to the particle data. */
struct part *parts = s->parts_foreign;
struct gpart *gparts = s->gparts_foreign;
struct spart *sparts = s->sparts_foreign;
struct bpart *bparts = s->bparts_foreign;
for (int k = 0; k < nr_proxies; k++) {
for (int j = 0; j < e->proxies[k].nr_cells_in; j++) {
if (!fof && e->proxies[k].cells_in_type[j] & proxy_cell_type_hydro) {
const size_t count_parts =
cell_link_foreign_parts(e->proxies[k].cells_in[j], parts);
parts = &parts[count_parts];
}
if (e->proxies[k].cells_in_type[j] & proxy_cell_type_gravity) {
const size_t count_gparts =
cell_link_foreign_gparts(e->proxies[k].cells_in[j], gparts);
gparts = &gparts[count_gparts];
}
if (!fof && with_stars) {
/* For stars, we just use the numbers in the top-level cells */
cell_link_sparts(e->proxies[k].cells_in[j], sparts);
sparts = &sparts[e->proxies[k].cells_in[j]->stars.count +
space_extra_sparts];
}
if (!fof && with_black_holes) {
/* For black holes, we just use the numbers in the top-level cells */
cell_link_bparts(e->proxies[k].cells_in[j], bparts);
bparts = &bparts[e->proxies[k].cells_in[j]->black_holes.count];
}
}
}
/* Update the counters */
s->nr_parts_foreign = parts - s->parts_foreign;
s->nr_gparts_foreign = gparts - s->gparts_foreign;
s->nr_sparts_foreign = sparts - s->sparts_foreign;
s->nr_bparts_foreign = bparts - s->bparts_foreign;
if (e->verbose)
message("Recursively linking foreign arrays took %.3f %s.",
clocks_from_ticks(getticks() - tic), clocks_getunit());
#else
error("SWIFT was not compiled with MPI support.");
#endif
}
void engine_do_tasks_count_mapper(void *map_data, int num_elements,
void *extra_data) {
const struct task *tasks = (struct task *)map_data;
int *const global_counts = (int *)extra_data;
/* Local accumulator copy */
int local_counts[task_type_count + 1];
for (int k = 0; k <= task_type_count; k++) local_counts[k] = 0;
/* Add task counts locally */
for (int k = 0; k < num_elements; k++) {
if (tasks[k].skip)
local_counts[task_type_count] += 1;
else
local_counts[(int)tasks[k].type] += 1;
}
/* Update the global counts */
for (int k = 0; k <= task_type_count; k++) {
if (local_counts[k]) atomic_add(global_counts + k, local_counts[k]);
}
}
/**
* @brief Prints the number of tasks in the engine
*
* @param e The #engine.
*/
void engine_print_task_counts(const struct engine *e) {
const ticks tic = getticks();
const struct scheduler *sched = &e->sched;
const int nr_tasks = sched->nr_tasks;
const struct task *const tasks = sched->tasks;
/* Global tasks and cells when using MPI. */
#ifdef WITH_MPI
if (e->nodeID == 0 && e->total_nr_tasks > 0)
printf(
"[%04i] %s engine_print_task_counts: System total: %lld,"
" no. cells: %lld\n",
e->nodeID, clocks_get_timesincestart(), e->total_nr_tasks,
e->total_nr_cells);
fflush(stdout);
#endif
/* Report value that can be used to estimate the task_per_cells parameter. */
float tasks_per_cell = (float)nr_tasks / (float)e->s->tot_cells;
#ifdef WITH_MPI
message("Total = %d (per cell = %.2f)", nr_tasks, tasks_per_cell);
/* And the system maximum on rank 0, only after first step, increase by our
* margin to allow for some variation in repartitioning. */
if (e->nodeID == 0 && e->total_nr_tasks > 0) {
message("Total = %d (maximum per cell = %.2f)", nr_tasks,
e->tasks_per_cell_max * engine_tasks_per_cell_margin);
}
#else
message("Total = %d (per cell = %.2f)", nr_tasks, tasks_per_cell);
#endif
fflush(stdout);