Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Objectify MSG task send
[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 constexpr double 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 CpuTiProfile::CpuTiProfile(kernel::profile::Profile* profile)
23 {
24   double integral = 0;
25   double time = 0;
26   int i = 0;
27   nb_points_      = profile->event_list.size() + 1;
28   time_points_    = new double[nb_points_];
29   integral_       = new double[nb_points_];
30   for (auto const& val : profile->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 CpuTiProfile::~CpuTiProfile()
42 {
43   delete[] time_points_;
44   delete [] integral_;
45 }
46
47 CpuTiTmgr::~CpuTiTmgr()
48 {
49   delete profile_;
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 profile_->integrate_simple(a - (a_index - 1) * last_time_, b - (b_index)*last_time_);
85   }
86
87   double first_chunk  = profile_->integrate_simple(a - (a_index - 1) * last_time_, last_time_);
88   double middle_chunk = (b_index - a_index) * total_;
89   double last_chunk   = profile_->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 CpuTiProfile::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 CpuTiProfile::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 = profile_->solve_simple(reduced_a, reduced_amount);
179   } else {
180     reduced_b = last_time_ + profile_->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 CpuTiProfile::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                 = profile_->binary_search(profile_->time_points_, reduced_a, 0, profile_->nb_points_ - 1);
216   kernel::profile::DatedValue val = speed_profile_->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(kernel::profile::Profile* speed_profile, double value) : speed_profile_(speed_profile)
228 {
229   double total_time = 0.0;
230   profile_          = 0;
231
232   /* no availability file, fixed trace */
233   if (not speed_profile) {
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_profile->event_list.size() == 1) {
242     type_  = Type::FIXED;
243     value_ = speed_profile->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_profile->event_list)
251     total_time += val.date_;
252
253   profile_   = new CpuTiProfile(speed_profile);
254   last_time_ = total_time;
255   total_     = profile_->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 CpuTiProfile::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_profile(kernel::profile::Profile* profile)
371 {
372   delete speed_integrated_trace_;
373   speed_integrated_trace_ = new CpuTiTmgr(profile, speed_.scale);
374
375   /* add a fake trace event if periodicity == 0 */
376   if (profile && profile->event_list.size() > 1) {
377     kernel::profile::DatedValue val = profile->event_list.back();
378     if (val.date_ < 1e-12) {
379       simgrid::kernel::profile::Profile* prof = new simgrid::kernel::profile::Profile();
380       speed_.event                            = prof->schedule(&future_evt_set, this);
381     }
382   }
383 }
384
385 void CpuTi::apply_event(kernel::profile::Event* event, double value)
386 {
387   if (event == speed_.event) {
388     XBT_DEBUG("Speed changed in trace! New fixed value: %f", value);
389
390     /* update remaining of actions and put in modified cpu list */
391     update_remaining_amount(surf_get_clock());
392
393     set_modified(true);
394
395     delete speed_integrated_trace_;
396     speed_integrated_trace_ = new CpuTiTmgr(value);
397
398     speed_.scale = value;
399     tmgr_trace_event_unref(&speed_.event);
400
401   } else if (event == state_event_) {
402     if (value > 0) {
403       if (not is_on()) {
404         XBT_VERB("Restart processes on host %s", get_host()->get_cname());
405         get_host()->turn_on();
406       }
407     } else {
408       get_host()->turn_off();
409       double date = surf_get_clock();
410
411       /* put all action running on cpu to failed */
412       for (CpuTiAction& action : action_set_) {
413         if (action.get_state() == kernel::resource::Action::State::INITED ||
414             action.get_state() == kernel::resource::Action::State::STARTED ||
415             action.get_state() == kernel::resource::Action::State::IGNORED) {
416           action.set_finish_time(date);
417           action.set_state(kernel::resource::Action::State::FAILED);
418           get_model()->get_action_heap().remove(&action);
419         }
420       }
421     }
422     tmgr_trace_event_unref(&state_event_);
423
424   } else {
425     xbt_die("Unknown event!\n");
426   }
427 }
428
429 /** Update the actions that are running on this CPU (which was modified recently) */
430 void CpuTi::update_actions_finish_time(double now)
431 {
432   /* update remaining amount of actions */
433   update_remaining_amount(now);
434
435   /* Compute the sum of priorities for the actions running on that CPU */
436   sum_priority_ = 0.0;
437   for (CpuTiAction const& action : action_set_) {
438     /* action not running, skip it */
439     if (action.get_state_set() != surf_cpu_model_pm->get_started_action_set())
440       continue;
441
442     /* bogus priority, skip it */
443     if (action.get_priority() <= 0)
444       continue;
445
446     /* action suspended, skip it */
447     if (action.suspended_ != kernel::resource::Action::SuspendStates::not_suspended)
448       continue;
449
450     sum_priority_ += 1.0 / action.get_priority();
451   }
452
453   for (CpuTiAction& action : action_set_) {
454     double min_finish = -1;
455     /* action not running, skip it */
456     if (action.get_state_set() != surf_cpu_model_pm->get_started_action_set())
457       continue;
458
459     /* verify if the action is really running on cpu */
460     if (action.suspended_ == kernel::resource::Action::SuspendStates::not_suspended && action.get_priority() > 0) {
461       /* total area needed to finish the action. Used in trace integration */
462       double total_area = (action.get_remains() * sum_priority_ * action.get_priority()) / speed_.peak;
463
464       action.set_finish_time(speed_integrated_trace_->solve(now, total_area));
465       /* verify which event will happen before (max_duration or finish time) */
466       if (action.get_max_duration() != NO_MAX_DURATION &&
467           action.get_start_time() + action.get_max_duration() < action.get_finish_time())
468         min_finish = action.get_start_time() + action.get_max_duration();
469       else
470         min_finish = action.get_finish_time();
471     } else {
472       /* put the max duration time on heap */
473       if (action.get_max_duration() != NO_MAX_DURATION)
474         min_finish = action.get_start_time() + action.get_max_duration();
475     }
476     /* add in action heap */
477     if (min_finish != NO_MAX_DURATION)
478       get_model()->get_action_heap().update(&action, min_finish, kernel::resource::ActionHeap::Type::unset);
479     else
480       get_model()->get_action_heap().remove(&action);
481
482     XBT_DEBUG("Update finish time: Cpu(%s) Action: %p, Start Time: %f Finish Time: %f Max duration %f", get_cname(),
483               &action, action.get_start_time(), action.get_finish_time(), action.get_max_duration());
484   }
485   /* remove from modified cpu */
486   set_modified(false);
487 }
488
489 bool CpuTi::is_used()
490 {
491   return not action_set_.empty();
492 }
493
494 double CpuTi::get_speed_ratio()
495 {
496   speed_.scale = speed_integrated_trace_->get_power_scale(surf_get_clock());
497   return Cpu::get_speed_ratio();
498 }
499
500 /** @brief Update the remaining amount of actions */
501 void CpuTi::update_remaining_amount(double now)
502 {
503   /* already up to date */
504   if (last_update_ >= now)
505     return;
506
507   /* compute the integration area */
508   double area_total = speed_integrated_trace_->integrate(last_update_, now) * speed_.peak;
509   XBT_DEBUG("Flops total: %f, Last update %f", area_total, last_update_);
510   for (CpuTiAction& action : action_set_) {
511     /* action not running, skip it */
512     if (action.get_state_set() != get_model()->get_started_action_set())
513       continue;
514
515     /* bogus priority, skip it */
516     if (action.get_priority() <= 0)
517       continue;
518
519     /* action suspended, skip it */
520     if (action.suspended_ != kernel::resource::Action::SuspendStates::not_suspended)
521       continue;
522
523     /* action don't need update */
524     if (action.get_start_time() >= now)
525       continue;
526
527     /* skip action that are finishing now */
528     if (action.get_finish_time() >= 0 && action.get_finish_time() <= now)
529       continue;
530
531     /* update remaining */
532     action.update_remains(area_total / (sum_priority_ * action.get_priority()));
533     XBT_DEBUG("Update remaining action(%p) remaining %f", &action, action.get_remains_no_update());
534   }
535   last_update_ = now;
536 }
537
538 CpuAction *CpuTi::execution_start(double size)
539 {
540   XBT_IN("(%s,%g)", get_cname(), size);
541   CpuTiAction* action = new CpuTiAction(this, size);
542
543   action_set_.push_back(*action); // Actually start the action
544
545   XBT_OUT();
546   return action;
547 }
548
549
550 CpuAction *CpuTi::sleep(double duration)
551 {
552   if (duration > 0)
553     duration = std::max(duration, sg_surf_precision);
554
555   XBT_IN("(%s,%g)", get_cname(), duration);
556   CpuTiAction* action = new CpuTiAction(this, 1.0);
557
558   action->set_max_duration(duration);
559   action->suspended_ = kernel::resource::Action::SuspendStates::sleeping;
560   if (duration == NO_MAX_DURATION)
561     action->set_state(simgrid::kernel::resource::Action::State::IGNORED);
562
563   action_set_.push_back(*action);
564
565   XBT_OUT();
566   return action;
567 }
568
569 void CpuTi::set_modified(bool modified)
570 {
571   CpuTiList& modified_cpus = static_cast<CpuTiModel*>(get_model())->modified_cpus_;
572   if (modified) {
573     if (not cpu_ti_hook.is_linked()) {
574       modified_cpus.push_back(*this);
575     }
576   } else {
577     if (cpu_ti_hook.is_linked())
578       simgrid::xbt::intrusive_erase(modified_cpus, *this);
579   }
580 }
581
582 /**********
583  * Action *
584  **********/
585
586 CpuTiAction::CpuTiAction(CpuTi* cpu, double cost) : CpuAction(cpu->get_model(), cost, not cpu->is_on()), cpu_(cpu)
587 {
588   cpu_->set_modified(true);
589 }
590 CpuTiAction::~CpuTiAction()
591 {
592   /* remove from action_set */
593   if (action_ti_hook.is_linked())
594     simgrid::xbt::intrusive_erase(cpu_->action_set_, *this);
595   /* remove from heap */
596   get_model()->get_action_heap().remove(this);
597   cpu_->set_modified(true);
598 }
599
600 void CpuTiAction::set_state(Action::State state)
601 {
602   CpuAction::set_state(state);
603   cpu_->set_modified(true);
604 }
605
606 void CpuTiAction::cancel()
607 {
608   this->set_state(Action::State::FAILED);
609   get_model()->get_action_heap().remove(this);
610   cpu_->set_modified(true);
611 }
612
613 void CpuTiAction::suspend()
614 {
615   XBT_IN("(%p)", this);
616   if (suspended_ != Action::SuspendStates::sleeping) {
617     suspended_ = Action::SuspendStates::suspended;
618     get_model()->get_action_heap().remove(this);
619     cpu_->set_modified(true);
620   }
621   XBT_OUT();
622 }
623
624 void CpuTiAction::resume()
625 {
626   XBT_IN("(%p)", this);
627   if (suspended_ != Action::SuspendStates::sleeping) {
628     suspended_ = Action::SuspendStates::not_suspended;
629     cpu_->set_modified(true);
630   }
631   XBT_OUT();
632 }
633
634 void CpuTiAction::set_max_duration(double duration)
635 {
636   double min_finish;
637
638   XBT_IN("(%p,%g)", this, duration);
639
640   Action::set_max_duration(duration);
641
642   if (duration >= 0)
643     min_finish = (get_start_time() + get_max_duration()) < get_finish_time() ? (get_start_time() + get_max_duration())
644                                                                              : get_finish_time();
645   else
646     min_finish = get_finish_time();
647
648   /* add in action heap */
649   get_model()->get_action_heap().update(this, min_finish, kernel::resource::ActionHeap::Type::unset);
650
651   XBT_OUT();
652 }
653
654 void CpuTiAction::set_priority(double priority)
655 {
656   XBT_IN("(%p,%g)", this, priority);
657   set_priority_no_update(priority);
658   cpu_->set_modified(true);
659   XBT_OUT();
660 }
661
662 double CpuTiAction::get_remains()
663 {
664   XBT_IN("(%p)", this);
665   cpu_->update_remaining_amount(surf_get_clock());
666   XBT_OUT();
667   return get_remains_no_update();
668 }
669
670 }
671 }