Logo AND Algorithmique Numérique Distribuée

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