Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Merge branch 'master' of framagit.org:simgrid/simgrid
[simgrid.git] / src / smpi / internals / smpi_utils.cpp
1 /* Copyright (c) 2016-2022. The SimGrid Team. All rights reserved.          */
2
3 /* This program is free software; you can redistribute it and/or modify it
4  * under the terms of the license (GNU LGPL) which comes with this package. */
5
6 #include "smpi_utils.hpp"
7
8 #include "private.hpp"
9 #include "smpi_config.hpp"
10 #include "src/surf/xml/platf.hpp"
11 #include "xbt/ex.h"
12 #include "xbt/file.hpp"
13 #include "xbt/log.h"
14 #include "xbt/parse_units.hpp"
15 #include "xbt/str.h"
16 #include "xbt/sysdep.h"
17 #include <algorithm>
18 #include <boost/tokenizer.hpp>
19
20 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(smpi_utils, smpi, "Logging specific to SMPI (utils)");
21
22 extern std::string surf_parsed_filename;
23 extern int surf_parse_lineno;
24
25 namespace simgrid::smpi::utils {
26
27 double total_benched_time=0;
28 unsigned long total_malloc_size=0;
29 unsigned long total_shared_size=0;
30 unsigned int total_shared_calls=0;
31 struct alloc_metadata_t {
32   size_t size          = 0;
33   unsigned int numcall = 0;
34   int line             = 0;
35   std::string file;
36 };
37
38 struct current_buffer_metadata_t {
39   alloc_metadata_t alloc;
40   std::string name;
41 };
42
43 alloc_metadata_t max_malloc;
44 F2C* current_handle = nullptr;
45 current_buffer_metadata_t current_buffer1;
46 current_buffer_metadata_t current_buffer2;
47
48 std::unordered_map<const void*, alloc_metadata_t> allocs;
49
50 std::unordered_map<int, std::vector<std::string>> collective_calls;
51
52 void add_benched_time(double time){
53   total_benched_time += time;
54 }
55
56 void account_malloc_size(size_t size, std::string_view file, int line, const void* ptr)
57 {
58   if (smpi_cfg_display_alloc()) {
59     alloc_metadata_t metadata;
60     metadata.size = size;
61     metadata.line = line;
62     metadata.numcall = 1;
63     metadata.file    = file;
64     allocs.try_emplace(ptr, metadata);
65
66     total_malloc_size += size;
67     if(size > max_malloc.size){
68       max_malloc.size = size;
69       max_malloc.line = line;
70       max_malloc.numcall = 1;
71       max_malloc.file    = file;
72     } else if (size == max_malloc.size && max_malloc.line == line && max_malloc.file == file) {
73       max_malloc.numcall++;
74     }
75   }
76 }
77
78 void account_shared_size(size_t size){
79   if (smpi_cfg_display_alloc()) {
80     total_shared_size += size;
81     total_shared_calls++;
82   }
83 }
84
85 void print_time_analysis(double global_time){
86   if (simgrid::config::get_value<bool>("smpi/display-timing")) {
87     XBT_INFO("Simulated time: %g seconds. \n\n"
88              "The simulation took %g seconds (after parsing and platform setup)\n"
89              "%g seconds were actual computation of the application",
90              simgrid_get_clock(), global_time, total_benched_time);
91     if (total_benched_time/global_time>=0.75)
92       XBT_INFO("More than 75%% of the time was spent inside the application code.\n"
93     "You may want to use sampling functions or trace replay to reduce this.");
94   }
95 }
96
97 static void print_leaked_handles()
98 {
99   // Put the leaked non-default handles in a vector to sort them by id
100   std::vector<std::pair<unsigned int, smpi::F2C*>> handles;
101   if (simgrid::smpi::F2C::lookup() != nullptr)
102     std::copy_if(simgrid::smpi::F2C::lookup()->begin(), simgrid::smpi::F2C::lookup()->end(),
103                  std::back_inserter(handles),
104                  [](auto const& entry) { return entry.first >= simgrid::smpi::F2C::get_num_default_handles(); });
105   if (handles.empty())
106     return;
107
108   auto max            = static_cast<unsigned long>(simgrid::config::get_value<int>("smpi/list-leaks"));
109   std::string message = "Probable memory leaks in your code: SMPI detected %zu unfreed MPI handles:";
110   if (max == 0)
111     message += "\nHINT: Display types and addresses (n max) with --cfg=smpi/list-leaks:n.\n"
112                "Running smpirun with -wrapper \"valgrind --leak-check=full\" can provide more information";
113   XBT_INFO(message.c_str(), handles.size());
114   if (max == 0)
115     return;
116
117   // we cannot trust F2C::lookup()->size() > F2C::get_num_default_handles() because some default handles are already
118   // freed at this point
119   bool display_advice = false;
120   std::map<std::string, int, std::less<>> count;
121   for (const auto& [_, elem] : handles) {
122     std::string key = elem->name();
123     if ((not xbt_log_no_loc) && (not elem->call_location().empty()))
124       key += " at " + elem->call_location();
125     else
126       display_advice = true;
127     auto& result = count.try_emplace(key, 0).first->second;
128     result++;
129   }
130   if (display_advice)
131     XBT_WARN("To get more information (location of allocations), compile your code with -trace-call-location flag of "
132              "smpicc/f90");
133   unsigned int i = 0;
134   for (const auto& [key, value] : count) {
135     if (value == 1)
136       XBT_INFO("leaked handle of type %s", key.c_str());
137     else
138       XBT_INFO("%d leaked handles of type %s", value, key.c_str());
139     i++;
140     if (i == max)
141       break;
142   }
143   if (max < count.size())
144     XBT_INFO("(%lu more handle leaks hidden as you wanted to see only %lu of them)", count.size() - max, max);
145 }
146
147 static void print_leaked_buffers()
148 {
149   if (allocs.empty())
150     return;
151
152   auto max            = static_cast<unsigned long>(simgrid::config::get_value<int>("smpi/list-leaks"));
153   std::string message = "Probable memory leaks in your code: SMPI detected %zu unfreed buffers:";
154   if (max == 0)
155     message += "display types and addresses (n max) with --cfg=smpi/list-leaks:n.\nRunning smpirun with -wrapper "
156                "\"valgrind --leak-check=full\" can provide more information";
157   XBT_INFO(message.c_str(), allocs.size());
158
159   if (max == 0)
160     return;
161
162   // gather by allocation origin (only one group reported in case of no-loc or if trace-call-location is not used)
163   struct buff_leak {
164     int count;
165     size_t total_size;
166     size_t min_size;
167     size_t max_size;
168   };
169   std::map<std::string, struct buff_leak, std::less<>> leaks_aggreg;
170   for (const auto& [_, elem] : allocs) {
171     std::string key = "leaked allocations";
172     if (not xbt_log_no_loc)
173       key = elem.file + ":" + std::to_string(elem.line) + ": " + key;
174     auto& result = leaks_aggreg.try_emplace(key, buff_leak{0, 0, elem.size, elem.size}).first->second;
175     result.count++;
176     result.total_size += elem.size;
177     if (elem.size > result.max_size)
178       result.max_size = elem.size;
179     else if (elem.size < result.min_size)
180       result.min_size = elem.size;
181   }
182   // now we can order by total size.
183   std::vector<std::pair<std::string, buff_leak>> leaks(leaks_aggreg.begin(), leaks_aggreg.end());
184   std::sort(leaks.begin(), leaks.end(),
185             [](auto const& a, auto const& b) { return a.second.total_size > b.second.total_size; });
186
187   unsigned int i = 0;
188   for (const auto& [key, value] : leaks) {
189     if (value.min_size == value.max_size)
190       XBT_INFO("%s of total size %zu, called %d times, each with size %zu", key.c_str(), value.total_size, value.count,
191                value.min_size);
192     else
193       XBT_INFO("%s of total size %zu, called %d times, with minimum size %zu and maximum size %zu", key.c_str(),
194                value.total_size, value.count, value.min_size, value.max_size);
195     i++;
196     if (i == max)
197       break;
198   }
199   if (max < leaks_aggreg.size())
200     XBT_INFO("(more buffer leaks hidden as you wanted to see only %lu of them)", max);
201 }
202
203 void print_memory_analysis()
204 {
205   if (smpi_cfg_display_alloc()) {
206     print_leaked_handles();
207     print_leaked_buffers();
208
209     if(total_malloc_size != 0)
210       XBT_INFO("Memory Usage: Simulated application allocated %lu bytes during its lifetime through malloc/calloc calls.\n"
211              "Largest allocation at once from a single process was %zu bytes, at %s:%d. It was called %u times during the whole simulation.\n"
212              "If this is too much, consider sharing allocations for computation buffers.\n"
213              "This can be done automatically by setting --cfg=smpi/auto-shared-malloc-thresh to the minimum size wanted size (this can alter execution if data content is necessary)\n",
214              total_malloc_size, max_malloc.size, simgrid::xbt::Path(max_malloc.file).get_base_name().c_str(), max_malloc.line, max_malloc.numcall
215       );
216     else
217       XBT_INFO(
218           "Allocations analysis asked, but 0 bytes were allocated through malloc/calloc calls intercepted by SMPI.\n"
219           "The code may not use malloc() to allocate memory, or it was built with SMPI_NO_OVERRIDE_MALLOC");
220     if(total_shared_size != 0)
221       XBT_INFO("%lu bytes were automatically shared between processes, in %u calls\n", total_shared_size, total_shared_calls);
222   }
223 }
224
225 void set_current_handle(F2C* handle){
226   current_handle=handle;
227 }
228
229 void print_current_handle(){
230   if(current_handle){
231     if(current_handle->call_location().empty())
232       XBT_INFO("To get handle location information, pass -trace-call-location flag to smpicc/f90 as well");
233     else
234       XBT_INFO("Handle %s was allocated by a call at %s", current_handle->name().c_str(),
235                (char*)(current_handle->call_location().c_str()));
236   }
237 }
238
239 void set_current_buffer(int i, const char* name, const void* buf){
240   //clear previous one
241   if(i==1){
242     if(not current_buffer1.name.empty()){
243       current_buffer1.name="";
244     }
245     if(not current_buffer2.name.empty()){
246       current_buffer2.name="";
247     }
248   }
249   auto meta = allocs.find(buf);
250   if (meta == allocs.end()) {
251     XBT_DEBUG("Buffer %p was not allocated with malloc/calloc", buf);
252     return;
253   }
254   if(i==1){
255     current_buffer1.alloc = meta->second;
256     current_buffer1.name = name;
257   }else{
258     current_buffer2.alloc=meta->second;
259     current_buffer2.name=name;
260   }
261 }
262
263 void print_buffer_info()
264 {
265   if (not current_buffer1.name.empty())
266     XBT_INFO("Buffer %s was allocated from %s line %d, with size %zu", current_buffer1.name.c_str(),
267              current_buffer1.alloc.file.c_str(), current_buffer1.alloc.line, current_buffer1.alloc.size);
268   if (not current_buffer2.name.empty())
269     XBT_INFO("Buffer %s was allocated from %s line %d, with size %zu", current_buffer2.name.c_str(),
270              current_buffer2.alloc.file.c_str(), current_buffer2.alloc.line, current_buffer2.alloc.size);
271 }
272
273 size_t get_buffer_size(const void* buf){
274   auto meta = allocs.find(buf);
275   if (meta == allocs.end()) {
276     //we don't know this buffer (on stack or feature disabled), assume it's fine.
277     return  std::numeric_limits<std::size_t>::max();
278   }
279   return meta->second.size;
280 }
281
282 void account_free(const void* ptr){
283   if (smpi_cfg_display_alloc()) {
284     allocs.erase(ptr);
285   }
286 }
287
288 int check_collectives_ordering(MPI_Comm comm, const std::string& call)
289 {
290   unsigned int count = comm->get_collectives_count();
291   comm->increment_collectives_count();
292   if (auto vec = collective_calls.find(comm->id()); vec == collective_calls.end()) {
293     collective_calls.try_emplace(comm->id(), std::vector<std::string>{call});
294   } else {
295     // are we the first ? add the call
296     if (vec->second.size() == count) {
297       vec->second.emplace_back(call);
298     } else if (vec->second.size() > count) {
299       if (vec->second[count] != call) {
300         XBT_WARN("Collective operation mismatch. For process %ld, expected %s, got %s",
301                  simgrid::s4u::this_actor::get_pid(), vec->second[count].c_str(), call.c_str());
302         return MPI_ERR_OTHER;
303       }
304     } else {
305       THROW_IMPOSSIBLE;
306     }
307   }
308   return MPI_SUCCESS;
309 }
310 } // namespace simgrid::smpi::utils