Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
[sonar] Remove custom destructors for xbt_replay.
[simgrid.git] / src / surf / cpu_ti.cpp
1 /* Copyright (c) 2013-2019. 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 "cpu_ti.hpp"
7 #include "src/kernel/resource/profile/trace_mgr.hpp"
8 #include "src/surf/surf_interface.hpp"
9 #include "surf/surf.hpp"
10
11 constexpr double EPSILON = 0.000000001;
12
13 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(surf_cpu_ti, surf_cpu, "Logging specific to the SURF CPU TRACE INTEGRATION module");
14
15 namespace simgrid {
16 namespace kernel {
17 namespace resource {
18
19 /*********
20  * Trace *
21  *********/
22
23 CpuTiProfile::CpuTiProfile(profile::Profile* profile)
24 {
25   double integral = 0;
26   double time = 0;
27   int i = 0;
28   nb_points_      = profile->event_list.size() + 1;
29   time_points_    = new double[nb_points_];
30   integral_       = new double[nb_points_];
31   for (auto const& val : profile->event_list) {
32     time_points_[i] = time;
33     integral_[i] = integral;
34     integral += val.date_ * val.value_;
35     time += val.date_;
36     i++;
37   }
38   time_points_[i] = time;
39   integral_[i] = integral;
40 }
41
42 CpuTiProfile::~CpuTiProfile()
43 {
44   delete[] time_points_;
45   delete [] integral_;
46 }
47
48 CpuTiTmgr::~CpuTiTmgr()
49 {
50   delete profile_;
51 }
52
53 /**
54  * @brief Integrate trace
55  *
56  * Wrapper around surf_cpu_integrate_trace_simple() to get
57  * the cyclic effect.
58  *
59  * @param a      Begin of interval
60  * @param b      End of interval
61  * @return the integrate value. -1 if an error occurs.
62  */
63 double CpuTiTmgr::integrate(double a, double b)
64 {
65   if ((a < 0.0) || (a > b)) {
66     xbt_die("Error, invalid integration interval [%.2f,%.2f]. "
67         "You probably have a task executing with negative computation amount. Check your code.", a, b);
68   }
69   if (fabs(a - b) < EPSILON)
70     return 0.0;
71
72   if (type_ == Type::FIXED) {
73     return (b - a) * value_;
74   }
75
76   int a_index;
77   if (fabs(ceil(a / last_time_) - a / last_time_) < EPSILON)
78     a_index = 1 + static_cast<int>(ceil(a / last_time_));
79   else
80     a_index = static_cast<int>(ceil(a / last_time_));
81
82   int b_index = static_cast<int>(floor(b / last_time_));
83
84   if (a_index > b_index) {      /* Same chunk */
85     return profile_->integrate_simple(a - (a_index - 1) * last_time_, b - (b_index)*last_time_);
86   }
87
88   double first_chunk  = profile_->integrate_simple(a - (a_index - 1) * last_time_, last_time_);
89   double middle_chunk = (b_index - a_index) * total_;
90   double last_chunk   = profile_->integrate_simple(0.0, b - (b_index)*last_time_);
91
92   XBT_DEBUG("first_chunk=%.2f  middle_chunk=%.2f  last_chunk=%.2f\n", first_chunk, middle_chunk, last_chunk);
93
94   return (first_chunk + middle_chunk + last_chunk);
95 }
96
97 /**
98  * @brief Auxiliary function to compute the integral between a and b.
99  *     It simply computes the integrals at point a and b and returns the difference between them.
100  * @param a  Initial point
101  * @param b  Final point
102  */
103 double CpuTiProfile::integrate_simple(double a, double b)
104 {
105   return integrate_simple_point(b) - integrate_simple_point(a);
106 }
107
108 /**
109  * @brief Auxiliary function to compute the integral at point a.
110  * @param a        point
111  */
112 double CpuTiProfile::integrate_simple_point(double a)
113 {
114   double integral = 0;
115   double a_aux = a;
116   int ind         = binary_search(time_points_, a, 0, nb_points_ - 1);
117   integral += integral_[ind];
118
119   XBT_DEBUG("a %f ind %d integral %f ind + 1 %f ind %f time +1 %f time %f", a, ind, integral, integral_[ind + 1],
120             integral_[ind], time_points_[ind + 1], time_points_[ind]);
121   double_update(&a_aux, time_points_[ind], sg_maxmin_precision * sg_surf_precision);
122   if (a_aux > 0)
123     integral +=
124         ((integral_[ind + 1] - integral_[ind]) / (time_points_[ind + 1] - time_points_[ind])) * (a - time_points_[ind]);
125   XBT_DEBUG("Integral a %f = %f", a, integral);
126
127   return integral;
128 }
129
130 /**
131  * @brief Computes the time needed to execute "amount" on cpu.
132  *
133  * Here, amount can span multiple trace periods
134  *
135  * @param a        Initial time
136  * @param amount  Amount to be executed
137  * @return  End time
138  */
139 double CpuTiTmgr::solve(double a, double amount)
140 {
141   /* Fix very small negative numbers */
142   if ((a < 0.0) && (a > -EPSILON)) {
143     a = 0.0;
144   }
145   if ((amount < 0.0) && (amount > -EPSILON)) {
146     amount = 0.0;
147   }
148
149   /* Sanity checks */
150   if ((a < 0.0) || (amount < 0.0)) {
151     XBT_CRITICAL ("Error, invalid parameters [a = %.2f, amount = %.2f]. "
152         "You probably have a task executing with negative computation amount. Check your code.", a, amount);
153     xbt_abort();
154   }
155
156   /* At this point, a and amount are positive */
157   if (amount < EPSILON)
158     return a;
159
160   /* Is the trace fixed ? */
161   if (type_ == Type::FIXED) {
162     return (a + (amount / value_));
163   }
164
165   XBT_DEBUG("amount %f total %f", amount, total_);
166   /* Reduce the problem to one where amount <= trace_total */
167   int quotient = static_cast<int>(floor(amount / total_));
168   double reduced_amount = (total_) * ((amount / total_) - floor(amount / total_));
169   double reduced_a      = a - (last_time_) * static_cast<int>(floor(a / last_time_));
170
171   XBT_DEBUG("Quotient: %d reduced_amount: %f reduced_a: %f", quotient, reduced_amount, reduced_a);
172
173   /* Now solve for new_amount which is <= trace_total */
174   double reduced_b;
175   XBT_DEBUG("Solve integral: [%.2f, amount=%.2f]", reduced_a, reduced_amount);
176   double amount_till_end = integrate(reduced_a, last_time_);
177
178   if (amount_till_end > reduced_amount) {
179     reduced_b = profile_->solve_simple(reduced_a, reduced_amount);
180   } else {
181     reduced_b = last_time_ + profile_->solve_simple(0.0, reduced_amount - amount_till_end);
182   }
183
184   /* Re-map to the original b and amount */
185   return (last_time_) * static_cast<int>(floor(a / last_time_)) + (quotient * last_time_) + reduced_b;
186 }
187
188 /**
189  * @brief Auxiliary function to solve integral.
190  *  It returns the date when the requested amount of flops is available
191  * @param a        Initial point
192  * @param amount  Amount of flops
193  * @return The date when amount is available.
194  */
195 double CpuTiProfile::solve_simple(double a, double amount)
196 {
197   double integral_a = integrate_simple_point(a);
198   int ind           = binary_search(integral_, integral_a + amount, 0, nb_points_ - 1);
199   double time       = time_points_[ind];
200   time += (integral_a + amount - integral_[ind]) /
201           ((integral_[ind + 1] - integral_[ind]) / (time_points_[ind + 1] - time_points_[ind]));
202
203   return time;
204 }
205
206 /**
207  * @brief Auxiliary function to update the CPU speed scale.
208  *
209  *  This function uses the trace structure to return the speed scale at the determined time a.
210  * @param a        Time
211  * @return CPU speed scale
212  */
213 double CpuTiTmgr::get_power_scale(double a)
214 {
215   double reduced_a          = a - floor(a / last_time_) * last_time_;
216   int point                 = profile_->binary_search(profile_->time_points_, reduced_a, 0, profile_->nb_points_ - 1);
217   kernel::profile::DatedValue val = speed_profile_->event_list.at(point);
218   return val.value_;
219 }
220
221 /**
222  * @brief Creates a new integration trace from a tmgr_trace_t
223  *
224  * @param  speed_trace    CPU availability trace
225  * @param  value          Percentage of CPU speed available (useful to fixed tracing)
226  * @return  Integration trace structure
227  */
228 CpuTiTmgr::CpuTiTmgr(kernel::profile::Profile* speed_profile, double value) : speed_profile_(speed_profile)
229 {
230   double total_time = 0.0;
231   profile_          = 0;
232
233   /* no availability file, fixed trace */
234   if (not speed_profile) {
235     type_  = Type::FIXED;
236     value_ = value;
237     XBT_DEBUG("No availability trace. Constant value = %f", value);
238     return;
239   }
240
241   /* only one point available, fixed trace */
242   if (speed_profile->event_list.size() == 1) {
243     type_  = Type::FIXED;
244     value_ = speed_profile->event_list.front().value_;
245     return;
246   }
247
248   type_ = Type::DYNAMIC;
249
250   /* count the total time of trace file */
251   for (auto const& val : speed_profile->event_list)
252     total_time += val.date_;
253
254   profile_   = new CpuTiProfile(speed_profile);
255   last_time_ = total_time;
256   total_     = profile_->integrate_simple(0, total_time);
257
258   XBT_DEBUG("Total integral %f, last_time %f ", total_, last_time_);
259 }
260
261 /**
262  * @brief Binary search in array.
263  *  It returns the first point of the interval in which "a" is.
264  * @param array    Array
265  * @param a        Value to search
266  * @param low     Low bound to search in array
267  * @param high    Upper bound to search in array
268  * @return Index of point
269  */
270 int CpuTiProfile::binary_search(double* array, double a, int low, int high)
271 {
272   xbt_assert(low < high, "Wrong parameters: low (%d) should be smaller than high (%d)", low, high);
273
274   do {
275     int mid = low + (high - low) / 2;
276     XBT_DEBUG("a %f low %d high %d mid %d value %f", a, low, high, mid, array[mid]);
277
278     if (array[mid] > a)
279       high = mid;
280     else
281       low = mid;
282   }
283   while (low < high - 1);
284
285   return low;
286 }
287
288 /*********
289  * Model *
290  *********/
291
292 void CpuTiModel::create_pm_vm_models()
293 {
294   xbt_assert(surf_cpu_model_pm == nullptr, "CPU model already initialized. This should not happen.");
295   xbt_assert(surf_cpu_model_vm == nullptr, "CPU model already initialized. This should not happen.");
296
297   surf_cpu_model_pm = new simgrid::kernel::resource::CpuTiModel();
298   surf_cpu_model_vm = new simgrid::kernel::resource::CpuTiModel();
299 }
300
301 CpuTiModel::CpuTiModel() : CpuModel(Model::UpdateAlgo::FULL)
302 {
303   all_existing_models.push_back(this);
304 }
305
306 CpuTiModel::~CpuTiModel()
307 {
308   surf_cpu_model_pm = nullptr;
309 }
310
311 kernel::resource::Cpu* CpuTiModel::create_cpu(s4u::Host* host, const std::vector<double>& speed_per_pstate, int core)
312 {
313   return new CpuTi(this, host, speed_per_pstate, core);
314 }
315
316 double CpuTiModel::next_occuring_event(double now)
317 {
318   double min_action_duration = -1;
319
320   /* iterates over modified cpus to update share resources */
321   for (auto it = std::begin(modified_cpus_); it != std::end(modified_cpus_);) {
322     CpuTi& cpu = *it;
323     ++it; // increment iterator here since the following call to ti.update_actions_finish_time() may invalidate it
324     cpu.update_actions_finish_time(now);
325   }
326
327   /* get the min next event if heap not empty */
328   if (not get_action_heap().empty())
329     min_action_duration = get_action_heap().top_date() - now;
330
331   XBT_DEBUG("Share resources, min next event date: %f", min_action_duration);
332
333   return min_action_duration;
334 }
335
336 void CpuTiModel::update_actions_state(double now, double /*delta*/)
337 {
338   while (not get_action_heap().empty() && double_equals(get_action_heap().top_date(), now, sg_surf_precision)) {
339     CpuTiAction* action = static_cast<CpuTiAction*>(get_action_heap().pop());
340     XBT_DEBUG("Action %p: finish", action);
341     action->finish(kernel::resource::Action::State::FINISHED);
342     /* update remaining amount of all actions */
343     action->cpu_->update_remaining_amount(surf_get_clock());
344   }
345 }
346
347 /************
348  * Resource *
349  ************/
350 CpuTi::CpuTi(CpuTiModel* model, simgrid::s4u::Host* host, const std::vector<double>& speed_per_pstate, int core)
351     : Cpu(model, host, speed_per_pstate, core)
352 {
353   xbt_assert(core == 1, "Multi-core not handled by this model yet");
354
355   speed_.peak = speed_per_pstate.front();
356   XBT_DEBUG("CPU create: peak=%f", speed_.peak);
357
358   speed_integrated_trace_ = new CpuTiTmgr(nullptr, 1 /*scale*/);
359 }
360
361 CpuTi::~CpuTi()
362 {
363   set_modified(false);
364   delete speed_integrated_trace_;
365 }
366 void CpuTi::set_speed_profile(kernel::profile::Profile* profile)
367 {
368   delete speed_integrated_trace_;
369   speed_integrated_trace_ = new CpuTiTmgr(profile, speed_.scale);
370
371   /* add a fake trace event if periodicity == 0 */
372   if (profile && profile->event_list.size() > 1) {
373     kernel::profile::DatedValue val = profile->event_list.back();
374     if (val.date_ < 1e-12) {
375       simgrid::kernel::profile::Profile* prof = new simgrid::kernel::profile::Profile();
376       speed_.event                            = prof->schedule(&future_evt_set, this);
377     }
378   }
379 }
380
381 void CpuTi::apply_event(kernel::profile::Event* event, double value)
382 {
383   if (event == speed_.event) {
384     XBT_DEBUG("Speed changed in trace! New fixed value: %f", value);
385
386     /* update remaining of actions and put in modified cpu list */
387     update_remaining_amount(surf_get_clock());
388
389     set_modified(true);
390
391     delete speed_integrated_trace_;
392     speed_integrated_trace_ = new CpuTiTmgr(value);
393
394     speed_.scale = value;
395     tmgr_trace_event_unref(&speed_.event);
396
397   } else if (event == state_event_) {
398     if (value > 0) {
399       if (not is_on()) {
400         XBT_VERB("Restart processes on host %s", get_host()->get_cname());
401         get_host()->turn_on();
402       }
403     } else {
404       get_host()->turn_off();
405       double date = surf_get_clock();
406
407       /* put all action running on cpu to failed */
408       for (CpuTiAction& action : action_set_) {
409         if (action.get_state() == kernel::resource::Action::State::INITED ||
410             action.get_state() == kernel::resource::Action::State::STARTED ||
411             action.get_state() == kernel::resource::Action::State::IGNORED) {
412           action.set_finish_time(date);
413           action.set_state(kernel::resource::Action::State::FAILED);
414           get_model()->get_action_heap().remove(&action);
415         }
416       }
417     }
418     tmgr_trace_event_unref(&state_event_);
419
420   } else {
421     xbt_die("Unknown event!\n");
422   }
423 }
424
425 /** Update the actions that are running on this CPU (which was modified recently) */
426 void CpuTi::update_actions_finish_time(double now)
427 {
428   /* update remaining amount of actions */
429   update_remaining_amount(now);
430
431   /* Compute the sum of priorities for the actions running on that CPU */
432   sum_priority_ = 0.0;
433   for (CpuTiAction const& action : action_set_) {
434     /* action not running, skip it */
435     if (action.get_state_set() != surf_cpu_model_pm->get_started_action_set())
436       continue;
437
438     /* bogus priority, skip it */
439     if (action.get_priority() <= 0)
440       continue;
441
442     /* action suspended, skip it */
443     if (not action.is_running())
444       continue;
445
446     sum_priority_ += 1.0 / action.get_priority();
447   }
448
449   for (CpuTiAction& action : action_set_) {
450     double min_finish = -1;
451     /* action not running, skip it */
452     if (action.get_state_set() != surf_cpu_model_pm->get_started_action_set())
453       continue;
454
455     /* verify if the action is really running on cpu */
456     if (action.is_running() && action.get_priority() > 0) {
457       /* total area needed to finish the action. Used in trace integration */
458       double total_area = (action.get_remains() * sum_priority_ * action.get_priority()) / speed_.peak;
459
460       action.set_finish_time(speed_integrated_trace_->solve(now, total_area));
461       /* verify which event will happen before (max_duration or finish time) */
462       if (action.get_max_duration() != NO_MAX_DURATION &&
463           action.get_start_time() + action.get_max_duration() < action.get_finish_time())
464         min_finish = action.get_start_time() + action.get_max_duration();
465       else
466         min_finish = action.get_finish_time();
467     } else {
468       /* put the max duration time on heap */
469       if (action.get_max_duration() != NO_MAX_DURATION)
470         min_finish = action.get_start_time() + action.get_max_duration();
471     }
472     /* add in action heap */
473     if (min_finish != NO_MAX_DURATION)
474       get_model()->get_action_heap().update(&action, min_finish, kernel::resource::ActionHeap::Type::unset);
475     else
476       get_model()->get_action_heap().remove(&action);
477
478     XBT_DEBUG("Update finish time: Cpu(%s) Action: %p, Start Time: %f Finish Time: %f Max duration %f", get_cname(),
479               &action, action.get_start_time(), action.get_finish_time(), action.get_max_duration());
480   }
481   /* remove from modified cpu */
482   set_modified(false);
483 }
484
485 bool CpuTi::is_used()
486 {
487   return not action_set_.empty();
488 }
489
490 double CpuTi::get_speed_ratio()
491 {
492   speed_.scale = speed_integrated_trace_->get_power_scale(surf_get_clock());
493   return Cpu::get_speed_ratio();
494 }
495
496 /** @brief Update the remaining amount of actions */
497 void CpuTi::update_remaining_amount(double now)
498 {
499   /* already up to date */
500   if (last_update_ >= now)
501     return;
502
503   /* compute the integration area */
504   double area_total = speed_integrated_trace_->integrate(last_update_, now) * speed_.peak;
505   XBT_DEBUG("Flops total: %f, Last update %f", area_total, last_update_);
506   for (CpuTiAction& action : action_set_) {
507     /* action not running, skip it */
508     if (action.get_state_set() != get_model()->get_started_action_set())
509       continue;
510
511     /* bogus priority, skip it */
512     if (action.get_priority() <= 0)
513       continue;
514
515     /* action suspended, skip it */
516     if (not action.is_running())
517       continue;
518
519     /* action don't need update */
520     if (action.get_start_time() >= now)
521       continue;
522
523     /* skip action that are finishing now */
524     if (action.get_finish_time() >= 0 && action.get_finish_time() <= now)
525       continue;
526
527     /* update remaining */
528     action.update_remains(area_total / (sum_priority_ * action.get_priority()));
529     XBT_DEBUG("Update remaining action(%p) remaining %f", &action, action.get_remains_no_update());
530   }
531   last_update_ = now;
532 }
533
534 kernel::resource::CpuAction* CpuTi::execution_start(double size)
535 {
536   XBT_IN("(%s,%g)", get_cname(), size);
537   CpuTiAction* action = new CpuTiAction(this, size);
538
539   action_set_.push_back(*action); // Actually start the action
540
541   XBT_OUT();
542   return action;
543 }
544
545 kernel::resource::CpuAction* CpuTi::sleep(double duration)
546 {
547   if (duration > 0)
548     duration = std::max(duration, sg_surf_precision);
549
550   XBT_IN("(%s,%g)", get_cname(), duration);
551   CpuTiAction* action = new CpuTiAction(this, 1.0);
552
553   action->set_max_duration(duration);
554   action->set_suspend_state(kernel::resource::Action::SuspendStates::SLEEPING);
555   if (duration == NO_MAX_DURATION)
556     action->set_state(simgrid::kernel::resource::Action::State::IGNORED);
557
558   action_set_.push_back(*action);
559
560   XBT_OUT();
561   return action;
562 }
563
564 void CpuTi::set_modified(bool modified)
565 {
566   CpuTiList& modified_cpus = static_cast<CpuTiModel*>(get_model())->modified_cpus_;
567   if (modified) {
568     if (not cpu_ti_hook.is_linked()) {
569       modified_cpus.push_back(*this);
570     }
571   } else {
572     if (cpu_ti_hook.is_linked())
573       simgrid::xbt::intrusive_erase(modified_cpus, *this);
574   }
575 }
576
577 /**********
578  * Action *
579  **********/
580
581 CpuTiAction::CpuTiAction(CpuTi* cpu, double cost) : CpuAction(cpu->get_model(), cost, not cpu->is_on()), cpu_(cpu)
582 {
583   cpu_->set_modified(true);
584 }
585 CpuTiAction::~CpuTiAction()
586 {
587   /* remove from action_set */
588   if (action_ti_hook.is_linked())
589     simgrid::xbt::intrusive_erase(cpu_->action_set_, *this);
590   /* remove from heap */
591   get_model()->get_action_heap().remove(this);
592   cpu_->set_modified(true);
593 }
594
595 void CpuTiAction::set_state(Action::State state)
596 {
597   CpuAction::set_state(state);
598   cpu_->set_modified(true);
599 }
600
601 void CpuTiAction::cancel()
602 {
603   this->set_state(Action::State::FAILED);
604   get_model()->get_action_heap().remove(this);
605   cpu_->set_modified(true);
606 }
607
608 void CpuTiAction::suspend()
609 {
610   XBT_IN("(%p)", this);
611   if (is_running()) {
612     set_suspend_state(Action::SuspendStates::SUSPENDED);
613     get_model()->get_action_heap().remove(this);
614     cpu_->set_modified(true);
615   }
616   XBT_OUT();
617 }
618
619 void CpuTiAction::resume()
620 {
621   XBT_IN("(%p)", this);
622   if (is_suspended()) {
623     set_suspend_state(Action::SuspendStates::RUNNING);
624     cpu_->set_modified(true);
625   }
626   XBT_OUT();
627 }
628
629 void CpuTiAction::set_max_duration(double duration)
630 {
631   double min_finish;
632
633   XBT_IN("(%p,%g)", this, duration);
634
635   Action::set_max_duration(duration);
636
637   if (duration >= 0)
638     min_finish = (get_start_time() + get_max_duration()) < get_finish_time() ? (get_start_time() + get_max_duration())
639                                                                              : get_finish_time();
640   else
641     min_finish = get_finish_time();
642
643   /* add in action heap */
644   get_model()->get_action_heap().update(this, min_finish, kernel::resource::ActionHeap::Type::unset);
645
646   XBT_OUT();
647 }
648
649 void CpuTiAction::set_priority(double priority)
650 {
651   XBT_IN("(%p,%g)", this, priority);
652   set_priority_no_update(priority);
653   cpu_->set_modified(true);
654   XBT_OUT();
655 }
656
657 double CpuTiAction::get_remains()
658 {
659   XBT_IN("(%p)", this);
660   cpu_->update_remaining_amount(surf_get_clock());
661   XBT_OUT();
662   return get_remains_no_update();
663 }
664
665 } // namespace resource
666 } // namespace kernel
667 } // namespace simgrid