Logo AND Algorithmique Numérique Distribuée

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