Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
6ce941766bc356d9c48bb5adf0896ed4f7c8a0df
[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  speed_trace    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 speed_trace, double value) : speed_trace_(speed_trace)
230 {
231   double total_time = 0.0;
232   trace_ = 0;
233
234   /* no availability file, fixed trace */
235   if (not speed_trace) {
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 (speed_trace->event_list.size() == 1) {
244     type_  = TRACE_FIXED;
245     value_ = speed_trace->event_list.front().value_;
246     return;
247   }
248
249   type_ = TRACE_DYNAMIC;
250
251   /* count the total time of trace file */
252   for (auto const& val : speed_trace->event_list)
253     total_time += val.date_;
254
255   trace_     = new CpuTiTrace(speed_trace);
256   last_time_ = total_time;
257   total_     = trace_->integrate_simple(0, total_time);
258
259   XBT_DEBUG("Total integral %f, last_time %f ", total_, last_time_);
260 }
261
262 /**
263  * \brief Binary search in array.
264  *  It returns the first point of the interval in which "a" is.
265  * \param array    Array
266  * \param a        Value to search
267  * \param low     Low bound to search in array
268  * \param high    Upper bound to search in array
269  * \return Index of point
270 */
271 int CpuTiTrace::binary_search(double* array, double a, int low, int high)
272 {
273   xbt_assert(low < high, "Wrong parameters: low (%d) should be smaller than high (%d)", low, high);
274
275   do {
276     int mid = low + (high - low) / 2;
277     XBT_DEBUG("a %f low %d high %d mid %d value %f", a, low, high, mid, array[mid]);
278
279     if (array[mid] > a)
280       high = mid;
281     else
282       low = mid;
283   }
284   while (low < high - 1);
285
286   return low;
287 }
288
289 }
290 }
291
292 /*********
293  * Model *
294  *********/
295
296 void surf_cpu_model_init_ti()
297 {
298   xbt_assert(not surf_cpu_model_pm, "CPU model already initialized. This should not happen.");
299   xbt_assert(not surf_cpu_model_vm, "CPU model already initialized. This should not happen.");
300
301   surf_cpu_model_pm = new simgrid::surf::CpuTiModel();
302   all_existing_models->push_back(surf_cpu_model_pm);
303
304   surf_cpu_model_vm = new simgrid::surf::CpuTiModel();
305   all_existing_models->push_back(surf_cpu_model_vm);
306 }
307
308 namespace simgrid {
309 namespace surf {
310
311 CpuTiModel::~CpuTiModel()
312 {
313   surf_cpu_model_pm = nullptr;
314 }
315
316 Cpu *CpuTiModel::createCpu(simgrid::s4u::Host *host, std::vector<double>* speedPerPstate, int core)
317 {
318   return new CpuTi(this, host, speedPerPstate, 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 == stateEvent_) {
406     if (value > 0) {
407       if (is_off())
408         host_that_restart.push_back(getHost());
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(&stateEvent_);
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_available_speed()
498 {
499   speed_.scale = speed_integrated_trace_->get_power_scale(surf_get_clock());
500   return Cpu::get_available_speed();
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 == NO_MAX_DURATION) {
565     /* Move to the *end* of the corresponding action set. This convention is used to speed up update_resource_state */
566     simgrid::xbt::intrusive_erase(*action->get_state_set(), *action);
567     action->state_set_ = &static_cast<CpuTiModel*>(get_model())->runningActionSetThatDoesNotNeedBeingChecked_;
568     action->get_state_set()->push_back(*action);
569   }
570
571   action_set_.push_back(*action);
572
573   XBT_OUT();
574   return action;
575 }
576
577 void CpuTi::set_modified(bool modified)
578 {
579   CpuTiList& modified_cpus = static_cast<CpuTiModel*>(get_model())->modified_cpus_;
580   if (modified) {
581     if (not cpu_ti_hook.is_linked()) {
582       modified_cpus.push_back(*this);
583     }
584   } else {
585     if (cpu_ti_hook.is_linked())
586       simgrid::xbt::intrusive_erase(modified_cpus, *this);
587   }
588 }
589
590 /**********
591  * Action *
592  **********/
593
594 CpuTiAction::CpuTiAction(CpuTi* cpu, double cost) : CpuAction(cpu->get_model(), cost, cpu->is_off()), cpu_(cpu)
595 {
596   cpu_->set_modified(true);
597 }
598 CpuTiAction::~CpuTiAction()
599 {
600   /* remove from action_set */
601   if (action_ti_hook.is_linked())
602     simgrid::xbt::intrusive_erase(cpu_->action_set_, *this);
603   /* remove from heap */
604   get_model()->get_action_heap().remove(this);
605   cpu_->set_modified(true);
606 }
607
608 void CpuTiAction::set_state(Action::State state)
609 {
610   CpuAction::set_state(state);
611   cpu_->set_modified(true);
612 }
613
614 void CpuTiAction::cancel()
615 {
616   this->set_state(Action::State::FAILED);
617   get_model()->get_action_heap().remove(this);
618   cpu_->set_modified(true);
619 }
620
621 void CpuTiAction::suspend()
622 {
623   XBT_IN("(%p)", this);
624   if (suspended_ != Action::SuspendStates::sleeping) {
625     suspended_ = Action::SuspendStates::suspended;
626     get_model()->get_action_heap().remove(this);
627     cpu_->set_modified(true);
628   }
629   XBT_OUT();
630 }
631
632 void CpuTiAction::resume()
633 {
634   XBT_IN("(%p)", this);
635   if (suspended_ != Action::SuspendStates::sleeping) {
636     suspended_ = Action::SuspendStates::not_suspended;
637     cpu_->set_modified(true);
638   }
639   XBT_OUT();
640 }
641
642 void CpuTiAction::set_max_duration(double duration)
643 {
644   double min_finish;
645
646   XBT_IN("(%p,%g)", this, duration);
647
648   Action::set_max_duration(duration);
649
650   if (duration >= 0)
651     min_finish = (get_start_time() + get_max_duration()) < get_finish_time() ? (get_start_time() + get_max_duration())
652                                                                              : get_finish_time();
653   else
654     min_finish = get_finish_time();
655
656   /* add in action heap */
657   get_model()->get_action_heap().update(this, min_finish, kernel::resource::ActionHeap::Type::unset);
658
659   XBT_OUT();
660 }
661
662 void CpuTiAction::set_priority(double priority)
663 {
664   XBT_IN("(%p,%g)", this, priority);
665   set_priority_no_update(priority);
666   cpu_->set_modified(true);
667   XBT_OUT();
668 }
669
670 double CpuTiAction::get_remains()
671 {
672   XBT_IN("(%p)", this);
673   cpu_->update_remaining_amount(surf_get_clock());
674   XBT_OUT();
675   return get_remains_no_update();
676 }
677
678 }
679 }
680
681 #endif /* SURF_MODEL_CPUTI_H_ */