Logo AND Algorithmique Numérique Distribuée

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