Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
prefer automatic memory management
[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         host_that_restart.push_back(get_host());
403       turn_on();
404     } else {
405       turn_off();
406       double date = surf_get_clock();
407
408       /* put all action running on cpu to failed */
409       for (CpuTiAction& action : action_set_) {
410         if (action.get_state() == kernel::resource::Action::State::INITED ||
411             action.get_state() == kernel::resource::Action::State::STARTED ||
412             action.get_state() == kernel::resource::Action::State::IGNORED) {
413           action.set_finish_time(date);
414           action.set_state(kernel::resource::Action::State::FAILED);
415           get_model()->get_action_heap().remove(&action);
416         }
417       }
418     }
419     tmgr_trace_event_unref(&state_event_);
420
421   } else {
422     xbt_die("Unknown event!\n");
423   }
424 }
425
426 /** Update the actions that are running on this CPU (which was modified recently) */
427 void CpuTi::update_actions_finish_time(double now)
428 {
429   /* update remaining amount of actions */
430   update_remaining_amount(now);
431
432   /* Compute the sum of priorities for the actions running on that CPU */
433   sum_priority_ = 0.0;
434   for (CpuTiAction const& action : action_set_) {
435     /* action not running, skip it */
436     if (action.get_state_set() != surf_cpu_model_pm->get_started_action_set())
437       continue;
438
439     /* bogus priority, skip it */
440     if (action.get_priority() <= 0)
441       continue;
442
443     /* action suspended, skip it */
444     if (action.suspended_ != kernel::resource::Action::SuspendStates::not_suspended)
445       continue;
446
447     sum_priority_ += 1.0 / action.get_priority();
448   }
449
450   for (CpuTiAction& action : action_set_) {
451     double min_finish = -1;
452     /* action not running, skip it */
453     if (action.get_state_set() != surf_cpu_model_pm->get_started_action_set())
454       continue;
455
456     /* verify if the action is really running on cpu */
457     if (action.suspended_ == kernel::resource::Action::SuspendStates::not_suspended && action.get_priority() > 0) {
458       /* total area needed to finish the action. Used in trace integration */
459       double total_area = (action.get_remains() * sum_priority_ * action.get_priority()) / speed_.peak;
460
461       action.set_finish_time(speed_integrated_trace_->solve(now, total_area));
462       /* verify which event will happen before (max_duration or finish time) */
463       if (action.get_max_duration() > NO_MAX_DURATION &&
464           action.get_start_time() + action.get_max_duration() < action.get_finish_time())
465         min_finish = action.get_start_time() + action.get_max_duration();
466       else
467         min_finish = action.get_finish_time();
468     } else {
469       /* put the max duration time on heap */
470       if (action.get_max_duration() > NO_MAX_DURATION)
471         min_finish = action.get_start_time() + action.get_max_duration();
472     }
473     /* add in action heap */
474     if (min_finish > NO_MAX_DURATION)
475       get_model()->get_action_heap().update(&action, min_finish, kernel::resource::ActionHeap::Type::unset);
476     else
477       get_model()->get_action_heap().remove(&action);
478
479     XBT_DEBUG("Update finish time: Cpu(%s) Action: %p, Start Time: %f Finish Time: %f Max duration %f", get_cname(),
480               &action, action.get_start_time(), action.get_finish_time(), action.get_max_duration());
481   }
482   /* remove from modified cpu */
483   set_modified(false);
484 }
485
486 bool CpuTi::is_used()
487 {
488   return not action_set_.empty();
489 }
490
491 double CpuTi::get_speed_ratio()
492 {
493   speed_.scale = speed_integrated_trace_->get_power_scale(surf_get_clock());
494   return Cpu::get_speed_ratio();
495 }
496
497 /** @brief Update the remaining amount of actions */
498 void CpuTi::update_remaining_amount(double now)
499 {
500   /* already up to date */
501   if (last_update_ >= now)
502     return;
503
504   /* compute the integration area */
505   double area_total = speed_integrated_trace_->integrate(last_update_, now) * speed_.peak;
506   XBT_DEBUG("Flops total: %f, Last update %f", area_total, last_update_);
507   for (CpuTiAction& action : action_set_) {
508     /* action not running, skip it */
509     if (action.get_state_set() != get_model()->get_started_action_set())
510       continue;
511
512     /* bogus priority, skip it */
513     if (action.get_priority() <= 0)
514       continue;
515
516     /* action suspended, skip it */
517     if (action.suspended_ != kernel::resource::Action::SuspendStates::not_suspended)
518       continue;
519
520     /* action don't need update */
521     if (action.get_start_time() >= now)
522       continue;
523
524     /* skip action that are finishing now */
525     if (action.get_finish_time() >= 0 && action.get_finish_time() <= now)
526       continue;
527
528     /* update remaining */
529     action.update_remains(area_total / (sum_priority_ * action.get_priority()));
530     XBT_DEBUG("Update remaining action(%p) remaining %f", &action, action.get_remains_no_update());
531   }
532   last_update_ = now;
533 }
534
535 CpuAction *CpuTi::execution_start(double size)
536 {
537   XBT_IN("(%s,%g)", get_cname(), size);
538   CpuTiAction* action = new CpuTiAction(this, size);
539
540   action_set_.push_back(*action); // Actually start the action
541
542   XBT_OUT();
543   return action;
544 }
545
546
547 CpuAction *CpuTi::sleep(double duration)
548 {
549   if (duration > 0)
550     duration = std::max(duration, sg_surf_precision);
551
552   XBT_IN("(%s,%g)", get_cname(), duration);
553   CpuTiAction* action = new CpuTiAction(this, 1.0);
554
555   action->set_max_duration(duration);
556   action->suspended_ = kernel::resource::Action::SuspendStates::sleeping;
557   if (duration < 0) // NO_MAX_DURATION
558     action->set_state(simgrid::kernel::resource::Action::State::IGNORED);
559
560   action_set_.push_back(*action);
561
562   XBT_OUT();
563   return action;
564 }
565
566 void CpuTi::set_modified(bool modified)
567 {
568   CpuTiList& modified_cpus = static_cast<CpuTiModel*>(get_model())->modified_cpus_;
569   if (modified) {
570     if (not cpu_ti_hook.is_linked()) {
571       modified_cpus.push_back(*this);
572     }
573   } else {
574     if (cpu_ti_hook.is_linked())
575       simgrid::xbt::intrusive_erase(modified_cpus, *this);
576   }
577 }
578
579 /**********
580  * Action *
581  **********/
582
583 CpuTiAction::CpuTiAction(CpuTi* cpu, double cost) : CpuAction(cpu->get_model(), cost, cpu->is_off()), cpu_(cpu)
584 {
585   cpu_->set_modified(true);
586 }
587 CpuTiAction::~CpuTiAction()
588 {
589   /* remove from action_set */
590   if (action_ti_hook.is_linked())
591     simgrid::xbt::intrusive_erase(cpu_->action_set_, *this);
592   /* remove from heap */
593   get_model()->get_action_heap().remove(this);
594   cpu_->set_modified(true);
595 }
596
597 void CpuTiAction::set_state(Action::State state)
598 {
599   CpuAction::set_state(state);
600   cpu_->set_modified(true);
601 }
602
603 void CpuTiAction::cancel()
604 {
605   this->set_state(Action::State::FAILED);
606   get_model()->get_action_heap().remove(this);
607   cpu_->set_modified(true);
608 }
609
610 void CpuTiAction::suspend()
611 {
612   XBT_IN("(%p)", this);
613   if (suspended_ != Action::SuspendStates::sleeping) {
614     suspended_ = Action::SuspendStates::suspended;
615     get_model()->get_action_heap().remove(this);
616     cpu_->set_modified(true);
617   }
618   XBT_OUT();
619 }
620
621 void CpuTiAction::resume()
622 {
623   XBT_IN("(%p)", this);
624   if (suspended_ != Action::SuspendStates::sleeping) {
625     suspended_ = Action::SuspendStates::not_suspended;
626     cpu_->set_modified(true);
627   }
628   XBT_OUT();
629 }
630
631 void CpuTiAction::set_max_duration(double duration)
632 {
633   double min_finish;
634
635   XBT_IN("(%p,%g)", this, duration);
636
637   Action::set_max_duration(duration);
638
639   if (duration >= 0)
640     min_finish = (get_start_time() + get_max_duration()) < get_finish_time() ? (get_start_time() + get_max_duration())
641                                                                              : get_finish_time();
642   else
643     min_finish = get_finish_time();
644
645   /* add in action heap */
646   get_model()->get_action_heap().update(this, min_finish, kernel::resource::ActionHeap::Type::unset);
647
648   XBT_OUT();
649 }
650
651 void CpuTiAction::set_priority(double priority)
652 {
653   XBT_IN("(%p,%g)", this, priority);
654   set_priority_no_update(priority);
655   cpu_->set_modified(true);
656   XBT_OUT();
657 }
658
659 double CpuTiAction::get_remains()
660 {
661   XBT_IN("(%p)", this);
662   cpu_->update_remaining_amount(surf_get_clock());
663   XBT_OUT();
664   return get_remains_no_update();
665 }
666
667 }
668 }