Logo AND Algorithmique Numérique Distribuée

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