Logo AND Algorithmique Numérique Distribuée

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