Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Use std::unique_ptr to manage memory.
[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 #include <algorithm>
12
13 constexpr double EPSILON = 0.000000001;
14
15 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(surf_cpu_ti, surf_cpu, "Logging specific to the SURF CPU TRACE INTEGRATION module");
16
17 namespace simgrid {
18 namespace kernel {
19 namespace resource {
20
21 /*********
22  * Trace *
23  *********/
24
25 CpuTiProfile::CpuTiProfile(profile::Profile* profile)
26 {
27   double integral = 0;
28   double time = 0;
29   unsigned nb_points = profile->event_list.size() + 1;
30   time_points_.reserve(nb_points);
31   integral_.reserve(nb_points);
32   for (auto const& val : profile->event_list) {
33     time_points_.push_back(time);
34     integral_.push_back(integral);
35     time += val.date_;
36     integral += val.date_ * val.value_;
37   }
38   time_points_.push_back(time);
39   integral_.push_back(integral);
40 }
41
42 /**
43  * @brief Integrate trace
44  *
45  * Wrapper around surf_cpu_integrate_trace_simple() to get
46  * the cyclic effect.
47  *
48  * @param a      Begin of interval
49  * @param b      End of interval
50  * @return the integrate value. -1 if an error occurs.
51  */
52 double CpuTiTmgr::integrate(double a, double b)
53 {
54   if ((a < 0.0) || (a > b)) {
55     xbt_die("Error, invalid integration interval [%.2f,%.2f]. "
56         "You probably have a task executing with negative computation amount. Check your code.", a, b);
57   }
58   if (fabs(a - b) < EPSILON)
59     return 0.0;
60
61   if (type_ == Type::FIXED) {
62     return (b - a) * value_;
63   }
64
65   int a_index;
66   if (fabs(ceil(a / last_time_) - a / last_time_) < EPSILON)
67     a_index = 1 + static_cast<int>(ceil(a / last_time_));
68   else
69     a_index = static_cast<int>(ceil(a / last_time_));
70
71   int b_index = static_cast<int>(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)
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)
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)
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   int quotient = static_cast<int>(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: %d 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_) * static_cast<int>(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)
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)
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     type_  = Type::FIXED;
225     value_ = value;
226     XBT_DEBUG("No availability trace. Constant value = %f", value);
227     return;
228   }
229
230   /* only one point available, fixed trace */
231   if (speed_profile->event_list.size() == 1) {
232     type_  = Type::FIXED;
233     value_ = speed_profile->event_list.front().value_;
234     return;
235   }
236
237   type_ = Type::DYNAMIC;
238
239   /* count the total time of trace file */
240   for (auto const& val : speed_profile->event_list)
241     total_time += val.date_;
242
243   profile_.reset(new CpuTiProfile(speed_profile));
244   last_time_ = total_time;
245   total_     = profile_->integrate_simple(0, total_time);
246
247   XBT_DEBUG("Total integral %f, last_time %f ", total_, last_time_);
248 }
249
250 /**
251  * @brief Binary search in array.
252  *  It returns the last point of the interval in which "a" is.
253  * @param array    Array
254  * @param a        Value to search
255  * @return Index of point
256  */
257 int CpuTiProfile::binary_search(const std::vector<double>& array, double a)
258 {
259   if (array[0] > a)
260     return 0;
261   auto pos = std::upper_bound(begin(array), end(array), a);
262   return std::distance(begin(array), pos) - 1;
263 }
264
265 /*********
266  * Model *
267  *********/
268
269 void CpuTiModel::create_pm_vm_models()
270 {
271   xbt_assert(surf_cpu_model_pm == nullptr, "CPU model already initialized. This should not happen.");
272   xbt_assert(surf_cpu_model_vm == nullptr, "CPU model already initialized. This should not happen.");
273
274   surf_cpu_model_pm = new simgrid::kernel::resource::CpuTiModel();
275   surf_cpu_model_vm = new simgrid::kernel::resource::CpuTiModel();
276 }
277
278 CpuTiModel::CpuTiModel() : CpuModel(Model::UpdateAlgo::FULL)
279 {
280   all_existing_models.push_back(this);
281 }
282
283 CpuTiModel::~CpuTiModel()
284 {
285   surf_cpu_model_pm = nullptr;
286 }
287
288 kernel::resource::Cpu* CpuTiModel::create_cpu(s4u::Host* host, const std::vector<double>& speed_per_pstate, int core)
289 {
290   return new CpuTi(this, host, speed_per_pstate, core);
291 }
292
293 double CpuTiModel::next_occuring_event(double now)
294 {
295   double min_action_duration = -1;
296
297   /* iterates over modified cpus to update share resources */
298   for (auto it = std::begin(modified_cpus_); it != std::end(modified_cpus_);) {
299     CpuTi& cpu = *it;
300     ++it; // increment iterator here since the following call to ti.update_actions_finish_time() may invalidate it
301     cpu.update_actions_finish_time(now);
302   }
303
304   /* get the min next event if heap not empty */
305   if (not get_action_heap().empty())
306     min_action_duration = get_action_heap().top_date() - now;
307
308   XBT_DEBUG("Share resources, min next event date: %f", min_action_duration);
309
310   return min_action_duration;
311 }
312
313 void CpuTiModel::update_actions_state(double now, double /*delta*/)
314 {
315   while (not get_action_heap().empty() && double_equals(get_action_heap().top_date(), now, sg_surf_precision)) {
316     CpuTiAction* action = static_cast<CpuTiAction*>(get_action_heap().pop());
317     XBT_DEBUG("Action %p: finish", action);
318     action->finish(kernel::resource::Action::State::FINISHED);
319     /* update remaining amount of all actions */
320     action->cpu_->update_remaining_amount(surf_get_clock());
321   }
322 }
323
324 /************
325  * Resource *
326  ************/
327 CpuTi::CpuTi(CpuTiModel* model, simgrid::s4u::Host* host, const std::vector<double>& speed_per_pstate, int core)
328     : Cpu(model, host, speed_per_pstate, core)
329 {
330   xbt_assert(core == 1, "Multi-core not handled by this model yet");
331
332   speed_.peak = speed_per_pstate.front();
333   XBT_DEBUG("CPU create: peak=%f", speed_.peak);
334
335   speed_integrated_trace_ = new CpuTiTmgr(nullptr, 1 /*scale*/);
336 }
337
338 CpuTi::~CpuTi()
339 {
340   set_modified(false);
341   delete speed_integrated_trace_;
342 }
343 void CpuTi::set_speed_profile(kernel::profile::Profile* profile)
344 {
345   delete speed_integrated_trace_;
346   speed_integrated_trace_ = new CpuTiTmgr(profile, speed_.scale);
347
348   /* add a fake trace event if periodicity == 0 */
349   if (profile && profile->event_list.size() > 1) {
350     kernel::profile::DatedValue val = profile->event_list.back();
351     if (val.date_ < 1e-12) {
352       simgrid::kernel::profile::Profile* prof = new simgrid::kernel::profile::Profile();
353       speed_.event                            = prof->schedule(&future_evt_set, this);
354     }
355   }
356 }
357
358 void CpuTi::apply_event(kernel::profile::Event* event, double value)
359 {
360   if (event == speed_.event) {
361     XBT_DEBUG("Speed changed in trace! New fixed value: %f", value);
362
363     /* update remaining of actions and put in modified cpu list */
364     update_remaining_amount(surf_get_clock());
365
366     set_modified(true);
367
368     delete speed_integrated_trace_;
369     speed_integrated_trace_ = new CpuTiTmgr(value);
370
371     speed_.scale = value;
372     tmgr_trace_event_unref(&speed_.event);
373
374   } else if (event == state_event_) {
375     if (value > 0) {
376       if (not is_on()) {
377         XBT_VERB("Restart processes on host %s", get_host()->get_cname());
378         get_host()->turn_on();
379       }
380     } else {
381       get_host()->turn_off();
382       double date = surf_get_clock();
383
384       /* put all action running on cpu to failed */
385       for (CpuTiAction& action : action_set_) {
386         if (action.get_state() == kernel::resource::Action::State::INITED ||
387             action.get_state() == kernel::resource::Action::State::STARTED ||
388             action.get_state() == kernel::resource::Action::State::IGNORED) {
389           action.set_finish_time(date);
390           action.set_state(kernel::resource::Action::State::FAILED);
391           get_model()->get_action_heap().remove(&action);
392         }
393       }
394     }
395     tmgr_trace_event_unref(&state_event_);
396
397   } else {
398     xbt_die("Unknown event!\n");
399   }
400 }
401
402 /** Update the actions that are running on this CPU (which was modified recently) */
403 void CpuTi::update_actions_finish_time(double now)
404 {
405   /* update remaining amount of actions */
406   update_remaining_amount(now);
407
408   /* Compute the sum of priorities for the actions running on that CPU */
409   sum_priority_ = 0.0;
410   for (CpuTiAction const& action : action_set_) {
411     /* action not running, skip it */
412     if (action.get_state_set() != surf_cpu_model_pm->get_started_action_set())
413       continue;
414
415     /* bogus priority, skip it */
416     if (action.get_priority() <= 0)
417       continue;
418
419     /* action suspended, skip it */
420     if (not action.is_running())
421       continue;
422
423     sum_priority_ += 1.0 / action.get_priority();
424   }
425
426   for (CpuTiAction& action : action_set_) {
427     double min_finish = -1;
428     /* action not running, skip it */
429     if (action.get_state_set() != surf_cpu_model_pm->get_started_action_set())
430       continue;
431
432     /* verify if the action is really running on cpu */
433     if (action.is_running() && action.get_priority() > 0) {
434       /* total area needed to finish the action. Used in trace integration */
435       double total_area = (action.get_remains() * sum_priority_ * action.get_priority()) / speed_.peak;
436
437       action.set_finish_time(speed_integrated_trace_->solve(now, total_area));
438       /* verify which event will happen before (max_duration or finish time) */
439       if (action.get_max_duration() != NO_MAX_DURATION &&
440           action.get_start_time() + action.get_max_duration() < action.get_finish_time())
441         min_finish = action.get_start_time() + action.get_max_duration();
442       else
443         min_finish = action.get_finish_time();
444     } else {
445       /* put the max duration time on heap */
446       if (action.get_max_duration() != NO_MAX_DURATION)
447         min_finish = action.get_start_time() + action.get_max_duration();
448     }
449     /* add in action heap */
450     if (min_finish != NO_MAX_DURATION)
451       get_model()->get_action_heap().update(&action, min_finish, kernel::resource::ActionHeap::Type::unset);
452     else
453       get_model()->get_action_heap().remove(&action);
454
455     XBT_DEBUG("Update finish time: Cpu(%s) Action: %p, Start Time: %f Finish Time: %f Max duration %f", get_cname(),
456               &action, action.get_start_time(), action.get_finish_time(), action.get_max_duration());
457   }
458   /* remove from modified cpu */
459   set_modified(false);
460 }
461
462 bool CpuTi::is_used()
463 {
464   return not action_set_.empty();
465 }
466
467 double CpuTi::get_speed_ratio()
468 {
469   speed_.scale = speed_integrated_trace_->get_power_scale(surf_get_clock());
470   return Cpu::get_speed_ratio();
471 }
472
473 /** @brief Update the remaining amount of actions */
474 void CpuTi::update_remaining_amount(double now)
475 {
476   /* already up to date */
477   if (last_update_ >= now)
478     return;
479
480   /* compute the integration area */
481   double area_total = speed_integrated_trace_->integrate(last_update_, now) * speed_.peak;
482   XBT_DEBUG("Flops total: %f, Last update %f", area_total, last_update_);
483   for (CpuTiAction& action : action_set_) {
484     /* action not running, skip it */
485     if (action.get_state_set() != get_model()->get_started_action_set())
486       continue;
487
488     /* bogus priority, skip it */
489     if (action.get_priority() <= 0)
490       continue;
491
492     /* action suspended, skip it */
493     if (not action.is_running())
494       continue;
495
496     /* action don't need update */
497     if (action.get_start_time() >= now)
498       continue;
499
500     /* skip action that are finishing now */
501     if (action.get_finish_time() >= 0 && action.get_finish_time() <= now)
502       continue;
503
504     /* update remaining */
505     action.update_remains(area_total / (sum_priority_ * action.get_priority()));
506     XBT_DEBUG("Update remaining action(%p) remaining %f", &action, action.get_remains_no_update());
507   }
508   last_update_ = now;
509 }
510
511 kernel::resource::CpuAction* CpuTi::execution_start(double size)
512 {
513   XBT_IN("(%s,%g)", get_cname(), size);
514   CpuTiAction* action = new CpuTiAction(this, size);
515
516   action_set_.push_back(*action); // Actually start the action
517
518   XBT_OUT();
519   return action;
520 }
521
522 kernel::resource::CpuAction* CpuTi::sleep(double duration)
523 {
524   if (duration > 0)
525     duration = std::max(duration, sg_surf_precision);
526
527   XBT_IN("(%s,%g)", get_cname(), duration);
528   CpuTiAction* action = new CpuTiAction(this, 1.0);
529
530   action->set_max_duration(duration);
531   action->set_suspend_state(kernel::resource::Action::SuspendStates::SLEEPING);
532   if (duration == NO_MAX_DURATION)
533     action->set_state(simgrid::kernel::resource::Action::State::IGNORED);
534
535   action_set_.push_back(*action);
536
537   XBT_OUT();
538   return action;
539 }
540
541 void CpuTi::set_modified(bool modified)
542 {
543   CpuTiList& modified_cpus = static_cast<CpuTiModel*>(get_model())->modified_cpus_;
544   if (modified) {
545     if (not cpu_ti_hook.is_linked()) {
546       modified_cpus.push_back(*this);
547     }
548   } else {
549     if (cpu_ti_hook.is_linked())
550       simgrid::xbt::intrusive_erase(modified_cpus, *this);
551   }
552 }
553
554 /**********
555  * Action *
556  **********/
557
558 CpuTiAction::CpuTiAction(CpuTi* cpu, double cost) : CpuAction(cpu->get_model(), cost, not cpu->is_on()), cpu_(cpu)
559 {
560   cpu_->set_modified(true);
561 }
562 CpuTiAction::~CpuTiAction()
563 {
564   /* remove from action_set */
565   if (action_ti_hook.is_linked())
566     simgrid::xbt::intrusive_erase(cpu_->action_set_, *this);
567   /* remove from heap */
568   get_model()->get_action_heap().remove(this);
569   cpu_->set_modified(true);
570 }
571
572 void CpuTiAction::set_state(Action::State state)
573 {
574   CpuAction::set_state(state);
575   cpu_->set_modified(true);
576 }
577
578 void CpuTiAction::cancel()
579 {
580   this->set_state(Action::State::FAILED);
581   get_model()->get_action_heap().remove(this);
582   cpu_->set_modified(true);
583 }
584
585 void CpuTiAction::suspend()
586 {
587   XBT_IN("(%p)", this);
588   if (is_running()) {
589     set_suspend_state(Action::SuspendStates::SUSPENDED);
590     get_model()->get_action_heap().remove(this);
591     cpu_->set_modified(true);
592   }
593   XBT_OUT();
594 }
595
596 void CpuTiAction::resume()
597 {
598   XBT_IN("(%p)", this);
599   if (is_suspended()) {
600     set_suspend_state(Action::SuspendStates::RUNNING);
601     cpu_->set_modified(true);
602   }
603   XBT_OUT();
604 }
605
606 void CpuTiAction::set_max_duration(double duration)
607 {
608   double min_finish;
609
610   XBT_IN("(%p,%g)", this, duration);
611
612   Action::set_max_duration(duration);
613
614   if (duration >= 0)
615     min_finish = (get_start_time() + get_max_duration()) < get_finish_time() ? (get_start_time() + get_max_duration())
616                                                                              : get_finish_time();
617   else
618     min_finish = get_finish_time();
619
620   /* add in action heap */
621   get_model()->get_action_heap().update(this, min_finish, kernel::resource::ActionHeap::Type::unset);
622
623   XBT_OUT();
624 }
625
626 void CpuTiAction::set_priority(double priority)
627 {
628   XBT_IN("(%p,%g)", this, priority);
629   set_priority_no_update(priority);
630   cpu_->set_modified(true);
631   XBT_OUT();
632 }
633
634 double CpuTiAction::get_remains()
635 {
636   XBT_IN("(%p)", this);
637   cpu_->update_remaining_amount(surf_get_clock());
638   XBT_OUT();
639   return get_remains_no_update();
640 }
641
642 } // namespace resource
643 } // namespace kernel
644 } // namespace simgrid