Logo AND Algorithmique Numérique Distribuée

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