Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
4b82f5d22842f584df53bff8698f46930880faf2
[simgrid.git] / src / smpi / internals / smpi_utils.cpp
1 /* Copyright (c) 2016-2021. 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 "src/surf/xml/platf_private.hpp"
10 #include "xbt/log.h"
11 #include "xbt/parse_units.hpp"
12 #include "xbt/sysdep.h"
13 #include "xbt/file.hpp"
14 #include <boost/tokenizer.hpp>
15 #include "smpi_config.hpp"
16 #include <algorithm>
17 #include "private.hpp"
18
19 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(smpi_utils, smpi, "Logging specific to SMPI (utils)");
20
21 extern std::string surf_parsed_filename;
22 extern int surf_parse_lineno;
23
24 namespace simgrid {
25 namespace smpi {
26 namespace utils {
27
28 double total_benched_time=0;
29 unsigned long total_malloc_size=0;
30 unsigned long total_shared_size=0;
31 unsigned int total_shared_calls=0;
32 struct alloc_metadata_t {
33   size_t size          = 0;
34   unsigned int numcall = 0;
35   int line             = 0;
36   std::string file;
37 };
38
39 struct current_buffer_metadata_t {
40   alloc_metadata_t alloc;
41   std::string name;
42 };
43
44 alloc_metadata_t max_malloc;
45 F2C* current_handle = nullptr;
46 current_buffer_metadata_t current_buffer1;
47 current_buffer_metadata_t current_buffer2;
48
49 std::unordered_map<const void*, alloc_metadata_t> allocs;
50
51 std::vector<s_smpi_factor_t> parse_factor(const std::string& smpi_coef_string)
52 {
53   std::vector<s_smpi_factor_t> smpi_factor;
54
55   /** Setup the tokenizer that parses the string **/
56   using Tokenizer = boost::tokenizer<boost::char_separator<char>>;
57   boost::char_separator<char> sep(";");
58   boost::char_separator<char> factor_separator(":");
59   Tokenizer tokens(smpi_coef_string, sep);
60
61   /**
62    * Iterate over patterns like A:B:C:D;E:F;G:H
63    * These will be broken down into:
64    * A --> B, C, D
65    * E --> F
66    * G --> H
67    */
68   for (Tokenizer::iterator token_iter = tokens.begin(); token_iter != tokens.end(); ++token_iter) {
69     XBT_DEBUG("token: %s", token_iter->c_str());
70     Tokenizer factor_values(*token_iter, factor_separator);
71     s_smpi_factor_t fact;
72     xbt_assert(factor_values.begin() != factor_values.end(), "Malformed radical for smpi factor: '%s'",
73                smpi_coef_string.c_str());
74     unsigned int iteration = 0;
75     for (Tokenizer::iterator factor_iter = factor_values.begin(); factor_iter != factor_values.end(); ++factor_iter) {
76       iteration++;
77
78       if (factor_iter == factor_values.begin()) { /* first element */
79         try {
80           fact.factor = std::stoi(*factor_iter);
81         } catch (const std::invalid_argument&) {
82           throw std::invalid_argument(std::string("Invalid factor in chunk ") + std::to_string(smpi_factor.size() + 1) +
83                                       ": " + *factor_iter);
84         }
85       } else {
86         try {
87           fact.values.push_back(xbt_parse_get_time(surf_parsed_filename, surf_parse_lineno, *factor_iter, ""));
88         } catch (const std::invalid_argument&) {
89           throw std::invalid_argument(std::string("Invalid factor value ") + std::to_string(iteration) + " in chunk " +
90                                       std::to_string(smpi_factor.size() + 1) + ": " + *factor_iter);
91         }
92       }
93     }
94
95     smpi_factor.push_back(fact);
96     XBT_DEBUG("smpi_factor:\t%zu: %zu values, first: %f", fact.factor, smpi_factor.size(), fact.values[0]);
97   }
98   std::sort(smpi_factor.begin(), smpi_factor.end(), [](const s_smpi_factor_t &pa, const s_smpi_factor_t &pb) {
99     return (pa.factor < pb.factor);
100   });
101   for (auto const& fact : smpi_factor) {
102     XBT_DEBUG("smpi_factor:\t%zu: %zu values, first: %f", fact.factor, smpi_factor.size(), fact.values[0]);
103   }
104   smpi_factor.shrink_to_fit();
105
106   return smpi_factor;
107 }
108
109 void add_benched_time(double time){
110   total_benched_time += time;
111 }
112
113 void account_malloc_size(size_t size, const std::string& file, int line, void* ptr)
114 {
115   if (smpi_cfg_display_alloc()) {
116     alloc_metadata_t metadata;
117     metadata.size = size;
118     metadata.line = line;
119     metadata.numcall = 1;
120     metadata.file    = file;
121     allocs.emplace(ptr, metadata);
122
123     total_malloc_size += size;
124     if(size > max_malloc.size){
125       max_malloc.size = size;
126       max_malloc.line = line;
127       max_malloc.numcall = 1;
128       max_malloc.file    = file;
129     } else if (size == max_malloc.size && max_malloc.line == line && max_malloc.file == file) {
130       max_malloc.numcall++;
131     }
132   }
133 }
134
135 void account_shared_size(size_t size){
136   if (smpi_cfg_display_alloc()) {
137     total_shared_size += size;
138     total_shared_calls++;
139   }
140 }
141
142 void print_time_analysis(double global_time){
143   if (simgrid::config::get_value<bool>("smpi/display-timing")) {
144     XBT_INFO("Simulated time: %g seconds. \n\n"
145              "The simulation took %g seconds (after parsing and platform setup)\n"
146              "%g seconds were actual computation of the application",
147              simgrid_get_clock(), global_time, total_benched_time);
148     if (total_benched_time/global_time>=0.75)
149       XBT_INFO("More than 75%% of the time was spent inside the application code.\n"
150     "You may want to use sampling functions or trace replay to reduce this.");
151   }
152 }
153
154 static void print_leaked_handles()
155 {
156   // Put the leaked non-default handles in a vector to sort them by id
157   std::vector<std::pair<unsigned int, smpi::F2C*>> handles;
158   if (simgrid::smpi::F2C::lookup() != nullptr)
159     std::copy_if(simgrid::smpi::F2C::lookup()->begin(), simgrid::smpi::F2C::lookup()->end(),
160                  std::back_inserter(handles),
161                  [](auto const& entry) { return entry.first >= simgrid::smpi::F2C::get_num_default_handles(); });
162   if (handles.empty())
163     return;
164
165   auto max            = static_cast<unsigned long>(simgrid::config::get_value<int>("smpi/list-leaks"));
166   std::string message = "Probable memory leaks in your code: SMPI detected %zu unfreed MPI handles:";
167   if (max == 0)
168     message += "\nHINT: Display types and addresses (n max) with --cfg=smpi/list-leaks:n.\n"
169                "Running smpirun with -wrapper \"valgrind --leak-check=full\" can provide more information";
170   XBT_INFO(message.c_str(), handles.size());
171   if (max == 0)
172     return;
173
174   // we cannot trust F2C::lookup()->size() > F2C::get_num_default_handles() because some default handles are already
175   // freed at this point
176   bool display_advice = false;
177   std::map<std::string, int, std::less<>> count;
178   for (const auto& elem : handles) {
179     std::string key = elem.second->name();
180     if ((not xbt_log_no_loc) && (not elem.second->call_location().empty()))
181       key += " at " + elem.second->call_location();
182     else
183       display_advice = true;
184     auto result      = count.emplace(key, 1);
185     if (result.second == false)
186       result.first->second++;
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& p : count) {
193     if (p.second == 1)
194       XBT_INFO("leaked handle of type %s", p.first.c_str());
195     else
196       XBT_INFO("%d leaked handles of type %s", p.second, p.first.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.second.file + ":" + std::to_string(elem.second.line) + ": " + key;
232     auto result = leaks_aggreg.emplace(key, buff_leak{1, elem.second.size, elem.second.size, elem.second.size});
233     if (result.second == false) {
234       result.first->second.count++;
235       result.first->second.total_size += elem.second.size;
236       if (elem.second.size > result.first->second.max_size)
237         result.first->second.max_size = elem.second.size;
238       else if (elem.second.size < result.first->second.min_size)
239         result.first->second.min_size = elem.second.size;
240     }
241   }
242   // now we can order by total size.
243   std::vector<std::pair<std::string, buff_leak>> leaks(leaks_aggreg.begin(), leaks_aggreg.end());
244   std::sort(leaks.begin(), leaks.end(),
245             [](auto const& a, auto const& b) { return a.second.total_size > b.second.total_size; });
246
247   unsigned int i = 0;
248   for (const auto& p : leaks) {
249     if (p.second.min_size == p.second.max_size)
250       XBT_INFO("%s of total size %zu, called %d times, each with size %zu", p.first.c_str(), p.second.total_size,
251                p.second.count, p.second.min_size);
252     else
253       XBT_INFO("%s of total size %zu, called %d times, with minimum size %zu and maximum size %zu", p.first.c_str(),
254                p.second.total_size, p.second.count, p.second.min_size, p.second.max_size);
255     i++;
256     if (i == max)
257       break;
258   }
259   if (max < leaks_aggreg.size())
260     XBT_INFO("(more buffer leaks hidden as you wanted to see only %lu of them)", max);
261 }
262
263 void print_memory_analysis()
264 {
265   if (smpi_cfg_display_alloc()) {
266     print_leaked_handles();
267     print_leaked_buffers();
268
269     if(total_malloc_size != 0)
270       XBT_INFO("Memory Usage: Simulated application allocated %lu bytes during its lifetime through malloc/calloc calls.\n"
271              "Largest allocation at once from a single process was %zu bytes, at %s:%d. It was called %u times during the whole simulation.\n"
272              "If this is too much, consider sharing allocations for computation buffers.\n"
273              "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",
274              total_malloc_size, max_malloc.size, simgrid::xbt::Path(max_malloc.file).get_base_name().c_str(), max_malloc.line, max_malloc.numcall
275       );
276     else
277       XBT_INFO(
278           "Allocations analysis asked, but 0 bytes were allocated through malloc/calloc calls intercepted by SMPI.\n"
279           "The code may not use malloc() to allocate memory, or it was built with SMPI_NO_OVERRIDE_MALLOC");
280     if(total_shared_size != 0)
281       XBT_INFO("%lu bytes were automatically shared between processes, in %u calls\n", total_shared_size, total_shared_calls);
282   }
283 }
284
285 void set_current_handle(F2C* handle){
286   current_handle=handle;
287 }
288
289 void print_current_handle(){
290   if(current_handle){
291     if(current_handle->call_location().empty())
292       XBT_INFO("To get handle location information, pass -trace-call-location flag to smpicc/f90 as well");
293     else
294       XBT_INFO("Handle %s was allocated by a call at %s", current_handle->name().c_str(),
295                (char*)(current_handle->call_location().c_str()));
296   }
297 }
298
299 void set_current_buffer(int i, const char* name, const void* buf){
300   //clear previous one
301   if(i==1){
302     if(not current_buffer1.name.empty()){
303       current_buffer1.name="";
304     }
305     if(not current_buffer2.name.empty()){
306       current_buffer2.name="";
307     }
308   }
309   auto meta = allocs.find(buf);
310   if (meta == allocs.end()) {
311     XBT_DEBUG("Buffer %p was not allocated with malloc/calloc", buf);
312     return;
313   }
314   if(i==1){
315     current_buffer1.alloc = meta->second;
316     current_buffer1.name = name;
317   }else{
318     current_buffer2.alloc=meta->second;
319     current_buffer2.name=name;
320   }
321 }
322
323 void print_buffer_info(){
324     if(not current_buffer1.name.empty())
325       XBT_INFO("Buffer %s was allocated from %s line %d, with size %zu", current_buffer1.name.c_str(), 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(), current_buffer2.alloc.file.c_str(), current_buffer2.alloc.line, current_buffer2.alloc.size);    
328 }
329
330 size_t get_buffer_size(const void* buf){
331   auto meta = allocs.find(buf);
332   if (meta == allocs.end()) {
333     //we don't know this buffer (on stack or feature disabled), assume it's fine.
334     return  std::numeric_limits<std::size_t>::max();
335   }
336   return meta->second.size;
337 }
338
339 void account_free(const void* ptr){
340   if (smpi_cfg_display_alloc()) {
341     allocs.erase(ptr);
342   }
343 }
344
345 }
346 }
347 } // namespace simgrid