Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Concatenate nested namespaces (sonar).
[simgrid.git] / src / smpi / internals / smpi_utils.cpp
1 /* Copyright (c) 2016-2022. The SimGrid Team.
2  * All rights reserved.                                                     */
3
4 /* This program is free software; you can redistribute it and/or modify it
5  * under the terms of the license (GNU LGPL) which comes with this package. */
6
7 #include "smpi_utils.hpp"
8
9 #include "private.hpp"
10 #include "smpi_config.hpp"
11 #include "src/surf/xml/platf.hpp"
12 #include "xbt/file.hpp"
13 #include "xbt/log.h"
14 #include "xbt/ex.h"
15 #include "xbt/parse_units.hpp"
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 std::vector<s_smpi_factor_t> parse_factor(const std::string& smpi_coef_string)
53 {
54   std::vector<s_smpi_factor_t> smpi_factor;
55
56   /** Setup the tokenizer that parses the string **/
57   using Tokenizer = boost::tokenizer<boost::char_separator<char>>;
58   boost::char_separator<char> sep(";");
59   boost::char_separator<char> factor_separator(":");
60   Tokenizer tokens(smpi_coef_string, sep);
61
62   /**
63    * Iterate over patterns like A:B:C:D;E:F;G:H
64    * These will be broken down into:
65    * A --> B, C, D
66    * E --> F
67    * G --> H
68    */
69   for (auto token_iter = tokens.begin(); token_iter != tokens.end(); ++token_iter) {
70     XBT_DEBUG("token: %s", token_iter->c_str());
71     Tokenizer factor_values(*token_iter, factor_separator);
72     s_smpi_factor_t fact;
73     xbt_assert(factor_values.begin() != factor_values.end(), "Malformed radical for smpi factor: '%s'",
74                smpi_coef_string.c_str());
75     unsigned int iteration = 0;
76     for (auto factor_iter = factor_values.begin(); factor_iter != factor_values.end(); ++factor_iter) {
77       iteration++;
78
79       if (factor_iter == factor_values.begin()) { /* first element */
80         try {
81           fact.factor = std::stoi(*factor_iter);
82         } catch (const std::invalid_argument&) {
83           throw std::invalid_argument(std::string("Invalid factor in chunk ") + std::to_string(smpi_factor.size() + 1) +
84                                       ": " + *factor_iter);
85         }
86       } else {
87         try {
88           fact.values.push_back(xbt_parse_get_time(surf_parsed_filename, surf_parse_lineno, *factor_iter, ""));
89         } catch (const std::invalid_argument&) {
90           throw std::invalid_argument(std::string("Invalid factor value ") + std::to_string(iteration) + " in chunk " +
91                                       std::to_string(smpi_factor.size() + 1) + ": " + *factor_iter);
92         }
93       }
94     }
95
96     smpi_factor.push_back(fact);
97     XBT_DEBUG("smpi_factor:\t%zu: %zu values, first: %f", fact.factor, smpi_factor.size(), fact.values[0]);
98   }
99   std::sort(smpi_factor.begin(), smpi_factor.end(), [](const s_smpi_factor_t &pa, const s_smpi_factor_t &pb) {
100     return (pa.factor < pb.factor);
101   });
102   for (auto const& fact : smpi_factor) {
103     XBT_DEBUG("smpi_factor:\t%zu: %zu values, first: %f", fact.factor, smpi_factor.size(), fact.values[0]);
104   }
105   smpi_factor.shrink_to_fit();
106
107   return smpi_factor;
108 }
109
110 void add_benched_time(double time){
111   total_benched_time += time;
112 }
113
114 void account_malloc_size(size_t size, std::string_view file, int line, const void* ptr)
115 {
116   if (smpi_cfg_display_alloc()) {
117     alloc_metadata_t metadata;
118     metadata.size = size;
119     metadata.line = line;
120     metadata.numcall = 1;
121     metadata.file    = file;
122     allocs.try_emplace(ptr, metadata);
123
124     total_malloc_size += size;
125     if(size > max_malloc.size){
126       max_malloc.size = size;
127       max_malloc.line = line;
128       max_malloc.numcall = 1;
129       max_malloc.file    = file;
130     } else if (size == max_malloc.size && max_malloc.line == line && max_malloc.file == file) {
131       max_malloc.numcall++;
132     }
133   }
134 }
135
136 void account_shared_size(size_t size){
137   if (smpi_cfg_display_alloc()) {
138     total_shared_size += size;
139     total_shared_calls++;
140   }
141 }
142
143 void print_time_analysis(double global_time){
144   if (simgrid::config::get_value<bool>("smpi/display-timing")) {
145     XBT_INFO("Simulated time: %g seconds. \n\n"
146              "The simulation took %g seconds (after parsing and platform setup)\n"
147              "%g seconds were actual computation of the application",
148              simgrid_get_clock(), global_time, total_benched_time);
149     if (total_benched_time/global_time>=0.75)
150       XBT_INFO("More than 75%% of the time was spent inside the application code.\n"
151     "You may want to use sampling functions or trace replay to reduce this.");
152   }
153 }
154
155 static void print_leaked_handles()
156 {
157   // Put the leaked non-default handles in a vector to sort them by id
158   std::vector<std::pair<unsigned int, smpi::F2C*>> handles;
159   if (simgrid::smpi::F2C::lookup() != nullptr)
160     std::copy_if(simgrid::smpi::F2C::lookup()->begin(), simgrid::smpi::F2C::lookup()->end(),
161                  std::back_inserter(handles),
162                  [](auto const& entry) { return entry.first >= simgrid::smpi::F2C::get_num_default_handles(); });
163   if (handles.empty())
164     return;
165
166   auto max            = static_cast<unsigned long>(simgrid::config::get_value<int>("smpi/list-leaks"));
167   std::string message = "Probable memory leaks in your code: SMPI detected %zu unfreed MPI handles:";
168   if (max == 0)
169     message += "\nHINT: Display types and addresses (n max) with --cfg=smpi/list-leaks:n.\n"
170                "Running smpirun with -wrapper \"valgrind --leak-check=full\" can provide more information";
171   XBT_INFO(message.c_str(), handles.size());
172   if (max == 0)
173     return;
174
175   // we cannot trust F2C::lookup()->size() > F2C::get_num_default_handles() because some default handles are already
176   // freed at this point
177   bool display_advice = false;
178   std::map<std::string, int, std::less<>> count;
179   for (const auto& [_, elem] : handles) {
180     std::string key = elem->name();
181     if ((not xbt_log_no_loc) && (not elem->call_location().empty()))
182       key += " at " + elem->call_location();
183     else
184       display_advice = true;
185     auto& result = count.try_emplace(key, 0).first->second;
186     result++;
187   }
188   if (display_advice)
189     XBT_WARN("To get more information (location of allocations), compile your code with -trace-call-location flag of "
190              "smpicc/f90");
191   unsigned int i = 0;
192   for (const auto& [key, value] : count) {
193     if (value == 1)
194       XBT_INFO("leaked handle of type %s", key.c_str());
195     else
196       XBT_INFO("%d leaked handles of type %s", value, key.c_str());
197     i++;
198     if (i == max)
199       break;
200   }
201   if (max < count.size())
202     XBT_INFO("(%lu more handle leaks hidden as you wanted to see only %lu of them)", count.size() - max, max);
203 }
204
205 static void print_leaked_buffers()
206 {
207   if (allocs.empty())
208     return;
209
210   auto max            = static_cast<unsigned long>(simgrid::config::get_value<int>("smpi/list-leaks"));
211   std::string message = "Probable memory leaks in your code: SMPI detected %zu unfreed buffers:";
212   if (max == 0)
213     message += "display types and addresses (n max) with --cfg=smpi/list-leaks:n.\nRunning smpirun with -wrapper "
214                "\"valgrind --leak-check=full\" can provide more information";
215   XBT_INFO(message.c_str(), allocs.size());
216
217   if (max == 0)
218     return;
219
220   // gather by allocation origin (only one group reported in case of no-loc or if trace-call-location is not used)
221   struct buff_leak {
222     int count;
223     size_t total_size;
224     size_t min_size;
225     size_t max_size;
226   };
227   std::map<std::string, struct buff_leak, std::less<>> leaks_aggreg;
228   for (const auto& [_, elem] : allocs) {
229     std::string key = "leaked allocations";
230     if (not xbt_log_no_loc)
231       key = elem.file + ":" + std::to_string(elem.line) + ": " + key;
232     auto& result = leaks_aggreg.try_emplace(key, buff_leak{0, 0, elem.size, elem.size}).first->second;
233     result.count++;
234     result.total_size += elem.size;
235     if (elem.size > result.max_size)
236       result.max_size = elem.size;
237     else if (elem.size < result.min_size)
238       result.min_size = elem.size;
239   }
240   // now we can order by total size.
241   std::vector<std::pair<std::string, buff_leak>> leaks(leaks_aggreg.begin(), leaks_aggreg.end());
242   std::sort(leaks.begin(), leaks.end(),
243             [](auto const& a, auto const& b) { return a.second.total_size > b.second.total_size; });
244
245   unsigned int i = 0;
246   for (const auto& [key, value] : leaks) {
247     if (value.min_size == value.max_size)
248       XBT_INFO("%s of total size %zu, called %d times, each with size %zu", key.c_str(), value.total_size, value.count,
249                value.min_size);
250     else
251       XBT_INFO("%s of total size %zu, called %d times, with minimum size %zu and maximum size %zu", key.c_str(),
252                value.total_size, value.count, value.min_size, value.max_size);
253     i++;
254     if (i == max)
255       break;
256   }
257   if (max < leaks_aggreg.size())
258     XBT_INFO("(more buffer leaks hidden as you wanted to see only %lu of them)", max);
259 }
260
261 void print_memory_analysis()
262 {
263   if (smpi_cfg_display_alloc()) {
264     print_leaked_handles();
265     print_leaked_buffers();
266
267     if(total_malloc_size != 0)
268       XBT_INFO("Memory Usage: Simulated application allocated %lu bytes during its lifetime through malloc/calloc calls.\n"
269              "Largest allocation at once from a single process was %zu bytes, at %s:%d. It was called %u times during the whole simulation.\n"
270              "If this is too much, consider sharing allocations for computation buffers.\n"
271              "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",
272              total_malloc_size, max_malloc.size, simgrid::xbt::Path(max_malloc.file).get_base_name().c_str(), max_malloc.line, max_malloc.numcall
273       );
274     else
275       XBT_INFO(
276           "Allocations analysis asked, but 0 bytes were allocated through malloc/calloc calls intercepted by SMPI.\n"
277           "The code may not use malloc() to allocate memory, or it was built with SMPI_NO_OVERRIDE_MALLOC");
278     if(total_shared_size != 0)
279       XBT_INFO("%lu bytes were automatically shared between processes, in %u calls\n", total_shared_size, total_shared_calls);
280   }
281 }
282
283 void set_current_handle(F2C* handle){
284   current_handle=handle;
285 }
286
287 void print_current_handle(){
288   if(current_handle){
289     if(current_handle->call_location().empty())
290       XBT_INFO("To get handle location information, pass -trace-call-location flag to smpicc/f90 as well");
291     else
292       XBT_INFO("Handle %s was allocated by a call at %s", current_handle->name().c_str(),
293                (char*)(current_handle->call_location().c_str()));
294   }
295 }
296
297 void set_current_buffer(int i, const char* name, const void* buf){
298   //clear previous one
299   if(i==1){
300     if(not current_buffer1.name.empty()){
301       current_buffer1.name="";
302     }
303     if(not current_buffer2.name.empty()){
304       current_buffer2.name="";
305     }
306   }
307   auto meta = allocs.find(buf);
308   if (meta == allocs.end()) {
309     XBT_DEBUG("Buffer %p was not allocated with malloc/calloc", buf);
310     return;
311   }
312   if(i==1){
313     current_buffer1.alloc = meta->second;
314     current_buffer1.name = name;
315   }else{
316     current_buffer2.alloc=meta->second;
317     current_buffer2.name=name;
318   }
319 }
320
321 void print_buffer_info()
322 {
323   if (not current_buffer1.name.empty())
324     XBT_INFO("Buffer %s was allocated from %s line %d, with size %zu", current_buffer1.name.c_str(),
325              current_buffer1.alloc.file.c_str(), current_buffer1.alloc.line, current_buffer1.alloc.size);
326   if (not current_buffer2.name.empty())
327     XBT_INFO("Buffer %s was allocated from %s line %d, with size %zu", current_buffer2.name.c_str(),
328              current_buffer2.alloc.file.c_str(), current_buffer2.alloc.line, current_buffer2.alloc.size);
329 }
330
331 size_t get_buffer_size(const void* buf){
332   auto meta = allocs.find(buf);
333   if (meta == allocs.end()) {
334     //we don't know this buffer (on stack or feature disabled), assume it's fine.
335     return  std::numeric_limits<std::size_t>::max();
336   }
337   return meta->second.size;
338 }
339
340 void account_free(const void* ptr){
341   if (smpi_cfg_display_alloc()) {
342     allocs.erase(ptr);
343   }
344 }
345
346 int check_collectives_ordering(MPI_Comm comm, const std::string& call)
347 {
348   unsigned int count = comm->get_collectives_count();
349   comm->increment_collectives_count();
350   if (auto vec = collective_calls.find(comm->id()); vec == collective_calls.end()) {
351     collective_calls.try_emplace(comm->id(), std::vector<std::string>{call});
352   } else {
353     // are we the first ? add the call
354     if (vec->second.size() == count) {
355       vec->second.emplace_back(call);
356     } else if (vec->second.size() > count) {
357       if (vec->second[count] != call) {
358         XBT_WARN("Collective operation mismatch. For process %ld, expected %s, got %s",
359                  simgrid::s4u::this_actor::get_pid(), vec->second[count].c_str(), call.c_str());
360         return MPI_ERR_OTHER;
361       }
362     } else {
363       THROW_IMPOSSIBLE;
364     }
365   }
366   return MPI_SUCCESS;
367 }
368 } // namespace simgrid::smpi::utils