Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
01e32b0a97ddabcd9f86d74f945552a1f7845cc4
[simgrid.git] / src / mc / checker / CommunicationDeterminismChecker.cpp
1 /* Copyright (c) 2008-2020. 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 "src/mc/checker/CommunicationDeterminismChecker.hpp"
7 #include "src/kernel/activity/MailboxImpl.hpp"
8 #include "src/mc/Session.hpp"
9 #include "src/mc/mc_api.hpp"
10 #include "src/mc/mc_config.hpp"
11 #include "src/mc/mc_exit.hpp"
12 #include "src/mc/mc_private.hpp"
13 #include "src/mc/mc_request.hpp"
14 #include "src/mc/mc_smx.hpp"
15
16 #if HAVE_SMPI
17 #include "smpi_request.hpp"
18 #endif
19
20 #include <cstdint>
21
22 using simgrid::mc::remote;
23 using mcapi = simgrid::mc::mc_api;
24
25 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(mc_comm_determinism, mc, "Logging specific to MC communication determinism detection");
26
27 /********** Global variables **********/
28
29 std::vector<simgrid::mc::PatternCommunicationList> initial_communications_pattern;
30 std::vector<std::vector<simgrid::mc::PatternCommunication*>> incomplete_communications_pattern;
31
32 /********** Static functions ***********/
33
34 static simgrid::mc::CommPatternDifference compare_comm_pattern(const simgrid::mc::PatternCommunication* comm1,
35                                                                const simgrid::mc::PatternCommunication* comm2)
36 {
37   using simgrid::mc::CommPatternDifference;
38   if (comm1->type != comm2->type)
39     return CommPatternDifference::TYPE;
40   if (comm1->rdv != comm2->rdv)
41     return CommPatternDifference::RDV;
42   if (comm1->src_proc != comm2->src_proc)
43     return CommPatternDifference::SRC_PROC;
44   if (comm1->dst_proc != comm2->dst_proc)
45     return CommPatternDifference::DST_PROC;
46   if (comm1->tag != comm2->tag)
47     return CommPatternDifference::TAG;
48   if (comm1->data.size() != comm2->data.size())
49     return CommPatternDifference::DATA_SIZE;
50   if (comm1->data != comm2->data)
51     return CommPatternDifference::DATA;
52   return CommPatternDifference::NONE;
53 }
54
55 static char* print_determinism_result(simgrid::mc::CommPatternDifference diff, int process,
56                                       const simgrid::mc::PatternCommunication* comm, unsigned int cursor)
57 {
58   char* type;
59   char* res;
60
61   if (comm->type == simgrid::mc::PatternCommunicationType::send)
62     type = bprintf("The send communications pattern of the process %d is different!", process - 1);
63   else
64     type = bprintf("The recv communications pattern of the process %d is different!", process - 1);
65
66   using simgrid::mc::CommPatternDifference;
67   switch (diff) {
68     case CommPatternDifference::TYPE:
69       res = bprintf("%s Different type for communication #%u", type, cursor);
70       break;
71     case CommPatternDifference::RDV:
72       res = bprintf("%s Different rdv for communication #%u", type, cursor);
73       break;
74     case CommPatternDifference::TAG:
75       res = bprintf("%s Different tag for communication #%u", type, cursor);
76       break;
77     case CommPatternDifference::SRC_PROC:
78       res = bprintf("%s Different source for communication #%u", type, cursor);
79       break;
80     case CommPatternDifference::DST_PROC:
81       res = bprintf("%s Different destination for communication #%u", type, cursor);
82       break;
83     case CommPatternDifference::DATA_SIZE:
84       res = bprintf("%s Different data size for communication #%u", type, cursor);
85       break;
86     case CommPatternDifference::DATA:
87       res = bprintf("%s Different data for communication #%u", type, cursor);
88       break;
89     default:
90       res = nullptr;
91       break;
92   }
93
94   return res;
95 }
96
97 static void update_comm_pattern(simgrid::mc::PatternCommunication* comm_pattern,
98                                 simgrid::mc::RemotePtr<simgrid::kernel::activity::CommImpl> comm_addr)
99 {
100   // HACK, type punning
101   simgrid::mc::Remote<simgrid::kernel::activity::CommImpl> temp_comm;
102   mc_model_checker->get_remote_simulation().read(temp_comm, comm_addr);
103   const simgrid::kernel::activity::CommImpl* comm = temp_comm.get_buffer();
104
105   smx_actor_t src_proc =
106       mc_model_checker->get_remote_simulation().resolve_actor(simgrid::mc::remote(comm->src_actor_.get()));
107   smx_actor_t dst_proc =
108       mc_model_checker->get_remote_simulation().resolve_actor(simgrid::mc::remote(comm->dst_actor_.get()));
109   comm_pattern->src_proc = src_proc->get_pid();
110   comm_pattern->dst_proc = dst_proc->get_pid();
111   comm_pattern->src_host = MC_smx_actor_get_host_name(src_proc);
112   comm_pattern->dst_host = MC_smx_actor_get_host_name(dst_proc);
113   if (comm_pattern->data.empty() && comm->src_buff_ != nullptr) {
114     size_t buff_size;
115     mc_model_checker->get_remote_simulation().read(&buff_size, remote(comm->dst_buff_size_));
116     comm_pattern->data.resize(buff_size);
117     mc_model_checker->get_remote_simulation().read_bytes(comm_pattern->data.data(), comm_pattern->data.size(),
118                                                          remote(comm->src_buff_));
119   }
120 }
121
122 namespace simgrid {
123 namespace mc {
124
125 void CommunicationDeterminismChecker::deterministic_comm_pattern(int process, const PatternCommunication* comm,
126                                                                  int backtracking)
127 {
128   if (not backtracking) {
129     PatternCommunicationList& list = initial_communications_pattern[process];
130     CommPatternDifference diff     = compare_comm_pattern(list.list[list.index_comm].get(), comm);
131
132     if (diff != CommPatternDifference::NONE) {
133       if (comm->type == PatternCommunicationType::send) {
134         this->send_deterministic = false;
135         if (this->send_diff != nullptr)
136           xbt_free(this->send_diff);
137         this->send_diff = print_determinism_result(diff, process, comm, list.index_comm + 1);
138       } else {
139         this->recv_deterministic = false;
140         if (this->recv_diff != nullptr)
141           xbt_free(this->recv_diff);
142         this->recv_diff = print_determinism_result(diff, process, comm, list.index_comm + 1);
143       }
144       if (_sg_mc_send_determinism && not this->send_deterministic) {
145         XBT_INFO("*********************************************************");
146         XBT_INFO("***** Non-send-deterministic communications pattern *****");
147         XBT_INFO("*********************************************************");
148         XBT_INFO("%s", this->send_diff);
149         xbt_free(this->send_diff);
150         this->send_diff = nullptr;
151         mc::session->log_state();
152         mc_model_checker->exit(SIMGRID_MC_EXIT_NON_DETERMINISM);
153       } else if (_sg_mc_comms_determinism && (not this->send_deterministic && not this->recv_deterministic)) {
154         XBT_INFO("****************************************************");
155         XBT_INFO("***** Non-deterministic communications pattern *****");
156         XBT_INFO("****************************************************");
157         if (this->send_diff) {
158           XBT_INFO("%s", this->send_diff);
159           xbt_free(this->send_diff);
160           this->send_diff = nullptr;
161         }
162         if (this->recv_diff) {
163           XBT_INFO("%s", this->recv_diff);
164           xbt_free(this->recv_diff);
165           this->recv_diff = nullptr;
166         }
167         mc::session->log_state();
168         mc_model_checker->exit(SIMGRID_MC_EXIT_NON_DETERMINISM);
169       }
170     }
171   }
172 }
173
174 /********** Non Static functions ***********/
175
176 void CommunicationDeterminismChecker::get_comm_pattern(smx_simcall_t request, CallType call_type, int backtracking)
177 {
178   const smx_actor_t issuer                                     = mcapi::get().mc_smx_simcall_get_issuer(request);
179   const mc::PatternCommunicationList& initial_pattern          = initial_communications_pattern[issuer->get_pid()];
180   const std::vector<PatternCommunication*>& incomplete_pattern = incomplete_communications_pattern[issuer->get_pid()];
181
182   auto pattern   = std::make_unique<PatternCommunication>();
183   pattern->index = initial_pattern.index_comm + incomplete_pattern.size();
184
185   if (call_type == CallType::SEND) {
186     /* Create comm pattern */
187     pattern->type      = PatternCommunicationType::send;
188     pattern->comm_addr = mcapi::get().get_pattern_comm_addr(request);
189     pattern->rdv      = mcapi::get().get_pattern_comm_rdv(pattern->comm_addr);
190     pattern->src_proc = mcapi::get().get_pattern_comm_src_proc(pattern->comm_addr);
191     pattern->src_host = mc_api::get().get_actor_host_name(issuer);
192
193 #if HAVE_SMPI
194     simgrid::smpi::Request mpi_request;
195     mc_model_checker->get_remote_simulation().read(
196         &mpi_request, remote(static_cast<smpi::Request*>(simcall_comm_isend__get__data(request))));
197     // pattern->tag = mpi_request.tag();
198     pattern->tag = mcapi::get().get_smpi_request_tag(request, simgrid::simix::Simcall::COMM_ISEND);
199 #endif
200     auto pattern_data = mcapi::get().get_pattern_comm_data(pattern->comm_addr);
201     if (pattern_data.data() != nullptr) {
202       auto data_size = pattern_data.size();
203       pattern->data.resize(data_size);
204       memcpy(pattern->data.data(), pattern_data.data(), data_size);
205     }
206
207 #if HAVE_SMPI
208     if (mpi_request.detached()) {
209       if (this->initial_communications_pattern_done) {
210         /* Evaluate comm determinism */
211         this->deterministic_comm_pattern(pattern->src_proc, pattern.get(), backtracking);
212         initial_communications_pattern[pattern->src_proc].index_comm++;
213       } else {
214         /* Store comm pattern */
215         initial_communications_pattern[pattern->src_proc].list.push_back(std::move(pattern));
216       }
217       return;
218     }
219 #endif
220   } else if (call_type == CallType::RECV) {
221     pattern->type = PatternCommunicationType::receive;
222     pattern->comm_addr = mcapi::get().get_pattern_comm_addr(request);
223
224 #if HAVE_SMPI
225     pattern->tag = mcapi::get().get_smpi_request_tag(request, simgrid::simix::Simcall::COMM_IRECV);
226 #endif
227     Remote<kernel::activity::CommImpl> temp_comm;
228     mc_model_checker->get_remote_simulation().read(temp_comm, remote(pattern->comm_addr));
229     const kernel::activity::CommImpl* comm = temp_comm.get_buffer();
230
231     char* remote_name;
232     mc_model_checker->get_remote_simulation().read(
233         &remote_name, remote(comm->get_mailbox() ? &xbt::string::to_string_data(comm->get_mailbox()->name_).data
234                                                  : &xbt::string::to_string_data(comm->mbox_cpy->name_).data));
235     pattern->rdv = mc_model_checker->get_remote_simulation().read_string(RemotePtr<char>(remote_name));
236     pattern->dst_proc =
237         mc_model_checker->get_remote_simulation().resolve_actor(mc::remote(comm->dst_actor_.get()))->get_pid();
238     pattern->dst_host = MC_smx_actor_get_host_name(issuer);
239   } else
240     xbt_die("Unexpected call_type %i", (int)call_type);
241
242   XBT_DEBUG("Insert incomplete comm pattern %p for process %ld", pattern.get(), issuer->get_pid());
243   incomplete_communications_pattern[issuer->get_pid()].push_back(pattern.release());
244 }
245
246 void CommunicationDeterminismChecker::complete_comm_pattern(RemotePtr<kernel::activity::CommImpl> comm_addr,
247                                                             unsigned int issuer, int backtracking)
248 {
249   /* Complete comm pattern */
250   std::vector<PatternCommunication*>& incomplete_pattern = incomplete_communications_pattern[issuer];
251   auto current_comm_pattern =
252       std::find_if(begin(incomplete_pattern), end(incomplete_pattern),
253                    [&comm_addr](const PatternCommunication* comm) { return remote(comm->comm_addr) == comm_addr; });
254   if (current_comm_pattern == std::end(incomplete_pattern))
255     xbt_die("Corresponding communication not found!");
256
257   update_comm_pattern(*current_comm_pattern, comm_addr);
258   std::unique_ptr<PatternCommunication> comm_pattern(*current_comm_pattern);
259   XBT_DEBUG("Remove incomplete comm pattern for process %u at cursor %zd", issuer,
260             std::distance(begin(incomplete_pattern), current_comm_pattern));
261   incomplete_pattern.erase(current_comm_pattern);
262
263   if (this->initial_communications_pattern_done) {
264     /* Evaluate comm determinism */
265     this->deterministic_comm_pattern(issuer, comm_pattern.get(), backtracking);
266     initial_communications_pattern[issuer].index_comm++;
267   } else {
268     /* Store comm pattern */
269     initial_communications_pattern[issuer].list.push_back(std::move(comm_pattern));
270   }
271 }
272
273 CommunicationDeterminismChecker::CommunicationDeterminismChecker(Session& s) : Checker(s) {}
274
275 CommunicationDeterminismChecker::~CommunicationDeterminismChecker() = default;
276
277 RecordTrace CommunicationDeterminismChecker::get_record_trace() // override
278 {
279   RecordTrace res;
280   for (auto const& state : stack_)
281     res.push_back(state->get_transition());
282   return res;
283 }
284
285 std::vector<std::string> CommunicationDeterminismChecker::get_textual_trace() // override
286 {
287   std::vector<std::string> trace;
288   for (auto const& state : stack_) {
289     smx_simcall_t req = &state->executed_req_;
290     trace.push_back(mcapi::get().request_to_string(req, state->transition_.argument_, RequestType::executed));
291   }
292   return trace;
293 }
294
295 void CommunicationDeterminismChecker::log_state() // override
296 {
297   if (_sg_mc_comms_determinism) {
298     if (this->send_deterministic && not this->recv_deterministic) {
299       XBT_INFO("*******************************************************");
300       XBT_INFO("**** Only-send-deterministic communication pattern ****");
301       XBT_INFO("*******************************************************");
302       XBT_INFO("%s", this->recv_diff);
303     }
304     if (not this->send_deterministic && this->recv_deterministic) {
305       XBT_INFO("*******************************************************");
306       XBT_INFO("**** Only-recv-deterministic communication pattern ****");
307       XBT_INFO("*******************************************************");
308       XBT_INFO("%s", this->send_diff);
309     }
310   }
311   XBT_INFO("Expanded states = %lu", expanded_states_count_);
312   XBT_INFO("Visited states = %lu", mcapi::get().mc_get_visited_states());
313   XBT_INFO("Executed transitions = %lu", mcapi::get().mc_get_executed_trans());
314   XBT_INFO("Send-deterministic : %s", this->send_deterministic ? "Yes" : "No");
315   if (_sg_mc_comms_determinism)
316     XBT_INFO("Recv-deterministic : %s", this->recv_deterministic ? "Yes" : "No");
317 }
318
319 void CommunicationDeterminismChecker::prepare()
320 {
321   const int maxpid = mcapi::get().get_maxpid();
322
323   initial_communications_pattern.resize(maxpid);
324   incomplete_communications_pattern.resize(maxpid);
325
326   ++expanded_states_count_;
327   auto initial_state = std::make_unique<State>(expanded_states_count_);
328
329   XBT_DEBUG("********* Start communication determinism verification *********");
330
331   /* Get an enabled actor and insert it in the interleave set of the initial state */
332   auto actors = mcapi::get().get_actors();
333   for (auto& actor : actors)
334     if (mcapi::get().actor_is_enabled(actor.copy.get_buffer()->get_pid()))
335       initial_state->add_interleaving_set(actor.copy.get_buffer());
336
337   stack_.push_back(std::move(initial_state));
338 }
339
340 static inline bool all_communications_are_finished()
341 {
342   auto maxpid = mcapi::get().get_maxpid();
343   for (size_t current_actor = 1; current_actor < maxpid; current_actor++) {
344     if (not incomplete_communications_pattern[current_actor].empty()) {
345       XBT_DEBUG("Some communications are not finished, cannot stop the exploration! State not visited.");
346       return false;
347     }
348   }
349   return true;
350 }
351
352 void CommunicationDeterminismChecker::restoreState()
353 {
354   /* Intermediate backtracking */
355   State* last_state = stack_.back().get();
356   if (last_state->system_state_) {
357     last_state->system_state_->restore(&mcapi::get().mc_get_remote_simulation());
358     MC_restore_communications_pattern(last_state);
359     return;
360   }
361
362   /* Restore the initial state */
363   mcapi::get().s_restore_initial_state();
364
365   unsigned n = mcapi::get().get_maxpid();
366   assert(n == incomplete_communications_pattern.size());
367   assert(n == initial_communications_pattern.size());
368   for (unsigned j = 0; j < n; j++) {
369     incomplete_communications_pattern[j].clear();
370     initial_communications_pattern[j].index_comm = 0;
371   }
372
373   /* Traverse the stack from the state at position start and re-execute the transitions */
374   for (std::unique_ptr<simgrid::mc::State> const& state : stack_) {
375     if (state == stack_.back())
376       break;
377
378     int req_num                    = state->transition_.argument_;
379     const s_smx_simcall* saved_req = &state->executed_req_;
380     xbt_assert(saved_req);
381
382     /* because we got a copy of the executed request, we have to fetch the
383        real one, pointed by the request field of the issuer process */
384
385     const smx_actor_t issuer = mcapi::get().mc_smx_simcall_get_issuer(saved_req);
386     smx_simcall_t req        = &issuer->simcall_;
387
388     /* TODO : handle test and testany simcalls */
389     CallType call = MC_get_call_type(req);
390     mcapi::get().handle_simcall(state->transition_);
391     MC_handle_comm_pattern(call, req, req_num, 1);
392     mcapi::get().mc_wait_for_requests();
393
394     /* Update statistics */
395     mcapi::get().mc_inc_visited_states();
396     mcapi::get().mc_inc_executed_trans();
397   }
398 }
399
400 void CommunicationDeterminismChecker::real_run()
401 {
402   std::unique_ptr<VisitedState> visited_state = nullptr;
403   smx_simcall_t req                           = nullptr;
404
405   while (not stack_.empty()) {
406     /* Get current state */
407     State* cur_state = stack_.back().get();
408
409     XBT_DEBUG("**************************************************");
410     XBT_DEBUG("Exploration depth = %zu (state = %d, interleaved processes = %zu)", stack_.size(), cur_state->num_,
411               cur_state->interleave_size());
412
413     /* Update statistics */
414     mcapi::get().mc_inc_visited_states();
415
416     if (stack_.size() <= (std::size_t)_sg_mc_max_depth)
417       req = mcapi::get().mc_state_choose_request(cur_state);
418     else
419       req = nullptr;
420
421     if (req != nullptr && visited_state == nullptr) {
422       int req_num = cur_state->transition_.argument_;
423
424       XBT_DEBUG("Execute: %s", mcapi::get().request_to_string(req, req_num, RequestType::simix).c_str());
425
426       std::string req_str;
427       if (dot_output != nullptr)
428         req_str = mcapi::get().request_get_dot_output(req, req_num);
429
430       mcapi::get().mc_inc_executed_trans();
431
432       /* TODO : handle test and testany simcalls */
433       CallType call = CallType::NONE;
434       if (_sg_mc_comms_determinism || _sg_mc_send_determinism)
435         call = MC_get_call_type(req);
436
437       /* Answer the request */
438       mcapi::get().handle_simcall(cur_state->transition_);
439       /* After this call req is no longer useful */
440
441       MC_handle_comm_pattern(call, req, req_num, 0);
442
443       /* Wait for requests (schedules processes) */
444       mcapi::get().mc_wait_for_requests();
445
446       /* Create the new expanded state */
447       ++expanded_states_count_;
448       auto next_state = std::make_unique<State>(expanded_states_count_);
449
450       /* If comm determinism verification, we cannot stop the exploration if some communications are not finished (at
451        * least, data are transferred). These communications  are incomplete and they cannot be analyzed and compared
452        * with the initial pattern. */
453       bool compare_snapshots = this->initial_communications_pattern_done && all_communications_are_finished();
454
455       if (_sg_mc_max_visited_states != 0)
456         visited_state = visited_states_.addVisitedState(expanded_states_count_, next_state.get(), compare_snapshots);
457       else
458         visited_state = nullptr;
459
460       if (visited_state == nullptr) {
461         /* Get enabled actors and insert them in the interleave set of the next state */
462         auto actors = mcapi::get().mc_get_remote_simulation().actors();
463         for (auto& actor : actors)
464           if (mcapi::get().actor_is_enabled(actor.copy.get_buffer()->get_pid()))
465             next_state->add_interleaving_set(actor.copy.get_buffer());
466
467         if (dot_output != nullptr)
468           fprintf(dot_output, "\"%d\" -> \"%d\" [%s];\n", cur_state->num_, next_state->num_, req_str.c_str());
469
470       } else if (dot_output != nullptr)
471         fprintf(dot_output, "\"%d\" -> \"%d\" [%s];\n", cur_state->num_,
472                 visited_state->original_num == -1 ? visited_state->num : visited_state->original_num, req_str.c_str());
473
474       stack_.push_back(std::move(next_state));
475     } else {
476       if (stack_.size() > (std::size_t)_sg_mc_max_depth)
477         XBT_WARN("/!\\ Max depth reached! /!\\ ");
478       else if (visited_state != nullptr)
479         XBT_DEBUG("State already visited (equal to state %d), exploration stopped on this path.",
480                   visited_state->original_num == -1 ? visited_state->num : visited_state->original_num);
481       else
482         XBT_DEBUG("There are no more processes to interleave. (depth %zu)", stack_.size());
483
484       this->initial_communications_pattern_done = true;
485
486       /* Trash the current state, no longer needed */
487       XBT_DEBUG("Delete state %d at depth %zu", cur_state->num_, stack_.size());
488       stack_.pop_back();
489
490       visited_state = nullptr;
491
492       /* Check for deadlocks */
493       if (mcapi::get().mc_check_deadlock()) {
494         mcapi::get().mc_show_deadlock();
495         throw simgrid::mc::DeadlockError();
496       }
497
498       while (not stack_.empty()) {
499         std::unique_ptr<State> state(std::move(stack_.back()));
500         stack_.pop_back();
501         if (state->interleave_size() && stack_.size() < (std::size_t)_sg_mc_max_depth) {
502           /* We found a back-tracking point, let's loop */
503           XBT_DEBUG("Back-tracking to state %d at depth %zu", state->num_, stack_.size() + 1);
504           stack_.push_back(std::move(state));
505
506           this->restoreState();
507
508           XBT_DEBUG("Back-tracking to state %d at depth %zu done", stack_.back()->num_, stack_.size());
509
510           break;
511         } else {
512           XBT_DEBUG("Delete state %d at depth %zu", state->num_, stack_.size() + 1);
513         }
514       }
515     }
516   }
517
518   mcapi::get().s_log_state();
519 }
520
521 void CommunicationDeterminismChecker::run()
522 {
523   XBT_INFO("Check communication determinism");
524   mcapi::get().s_initialize();
525
526   this->prepare();
527   this->real_run();
528 }
529
530 Checker* createCommunicationDeterminismChecker(Session& s)
531 {
532   return new CommunicationDeterminismChecker(s);
533 }
534
535 } // namespace mc
536 } // namespace simgrid