Logo AND Algorithmique Numérique Distribuée

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