1 /* Copyright (c) 2013-2018. The SimGrid Team. All rights reserved. */
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. */
7 #include "src/surf/trace_mgr.hpp"
8 #include "xbt/utility.hpp"
11 #ifndef SURF_MODEL_CPUTI_H_
12 #define SURF_MODEL_CPUTI_H_
14 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(surf_cpu_ti, surf_cpu, "Logging specific to the SURF CPU TRACE INTEGRATION module");
23 CpuTiTrace::CpuTiTrace(tmgr_trace_t speedTrace)
28 nbPoints_ = speedTrace->event_list.size() + 1;
29 timePoints_ = new double[nbPoints_];
30 integral_ = new double[nbPoints_];
31 for (auto const& val : speedTrace->event_list) {
32 timePoints_[i] = time;
33 integral_[i] = integral;
34 integral += val.date_ * val.value_;
38 timePoints_[i] = time;
39 integral_[i] = integral;
42 CpuTiTrace::~CpuTiTrace()
44 delete [] timePoints_;
48 CpuTiTgmr::~CpuTiTgmr()
55 * \brief Integrate trace
57 * Wrapper around surf_cpu_integrate_trace_simple() to get
60 * \param a Begin of interval
61 * \param b End of interval
62 * \return the integrate value. -1 if an error occurs.
64 double CpuTiTgmr::integrate(double a, double b)
68 if ((a < 0.0) || (a > b)) {
69 xbt_die("Error, invalid integration interval [%.2f,%.2f]. "
70 "You probably have a task executing with negative computation amount. Check your code.", a, b);
72 if (fabs(a -b) < EPSILON)
75 if (type_ == TRACE_FIXED) {
76 return ((b - a) * value_);
79 if (fabs(ceil(a / lastTime_) - a / lastTime_) < EPSILON)
80 a_index = 1 + static_cast<int>(ceil(a / lastTime_));
82 a_index = static_cast<int> (ceil(a / lastTime_));
84 int b_index = static_cast<int> (floor(b / lastTime_));
86 if (a_index > b_index) { /* Same chunk */
87 return trace_->integrateSimple(a - (a_index - 1) * lastTime_, b - (b_index) * lastTime_);
90 double first_chunk = trace_->integrateSimple(a - (a_index - 1) * lastTime_, lastTime_);
91 double middle_chunk = (b_index - a_index) * total_;
92 double last_chunk = trace_->integrateSimple(0.0, b - (b_index) * lastTime_);
94 XBT_DEBUG("first_chunk=%.2f middle_chunk=%.2f last_chunk=%.2f\n", first_chunk, middle_chunk, last_chunk);
96 return (first_chunk + middle_chunk + last_chunk);
100 * \brief Auxiliary function to compute the integral between a and b.
101 * It simply computes the integrals at point a and b and returns the difference between them.
102 * \param a Initial point
103 * \param b Final point
105 double CpuTiTrace::integrateSimple(double a, double b)
107 return integrateSimplePoint(b) - integrateSimplePoint(a);
111 * \brief Auxiliary function to compute the integral at point a.
114 double CpuTiTrace::integrateSimplePoint(double a)
118 int ind = binarySearch(timePoints_, a, 0, nbPoints_ - 1);
119 integral += integral_[ind];
121 XBT_DEBUG("a %f ind %d integral %f ind + 1 %f ind %f time +1 %f time %f",
122 a, ind, integral, integral_[ind + 1], integral_[ind], timePoints_[ind + 1], timePoints_[ind]);
123 double_update(&a_aux, timePoints_[ind], sg_maxmin_precision*sg_surf_precision);
125 integral += ((integral_[ind + 1] - integral_[ind]) / (timePoints_[ind + 1] - timePoints_[ind])) *
126 (a - timePoints_[ind]);
127 XBT_DEBUG("Integral a %f = %f", a, integral);
133 * \brief Computes the time needed to execute "amount" on cpu.
135 * Here, amount can span multiple trace periods
137 * \param a Initial time
138 * \param amount Amount to be executed
141 double CpuTiTgmr::solve(double a, double amount)
143 /* Fix very small negative numbers */
144 if ((a < 0.0) && (a > -EPSILON)) {
147 if ((amount < 0.0) && (amount > -EPSILON)) {
152 if ((a < 0.0) || (amount < 0.0)) {
153 XBT_CRITICAL ("Error, invalid parameters [a = %.2f, amount = %.2f]. "
154 "You probably have a task executing with negative computation amount. Check your code.", a, amount);
158 /* At this point, a and amount are positive */
159 if (amount < EPSILON)
162 /* Is the trace fixed ? */
163 if (type_ == TRACE_FIXED) {
164 return (a + (amount / value_));
167 XBT_DEBUG("amount %f total %f", amount, total_);
168 /* Reduce the problem to one where amount <= trace_total */
169 int quotient = static_cast<int>(floor(amount / total_));
170 double reduced_amount = (total_) * ((amount / total_) - floor(amount / total_));
171 double reduced_a = a - (lastTime_) * static_cast<int>(floor(a / lastTime_));
173 XBT_DEBUG("Quotient: %d reduced_amount: %f reduced_a: %f", quotient, reduced_amount, reduced_a);
175 /* Now solve for new_amount which is <= trace_total */
176 double reduced_b = solveSomewhatSimple(reduced_a, reduced_amount);
178 /* Re-map to the original b and amount */
179 double b = (lastTime_) * static_cast<int>(floor(a / lastTime_)) + (quotient * lastTime_) + reduced_b;
184 * \brief Auxiliary function to solve integral
186 * Here, amount is <= trace->total
187 * and a <=trace->last_time
190 double CpuTiTgmr::solveSomewhatSimple(double a, double amount)
194 XBT_DEBUG("Solve integral: [%.2f, amount=%.2f]", a, amount);
195 double amount_till_end = integrate(a, lastTime_);
197 if (amount_till_end > amount) {
198 b = trace_->solveSimple(a, amount);
200 b = lastTime_ + trace_->solveSimple(0.0, amount - amount_till_end);
206 * \brief Auxiliary function to solve integral.
207 * It returns the date when the requested amount of flops is available
208 * \param a Initial point
209 * \param amount Amount of flops
210 * \return The date when amount is available.
212 double CpuTiTrace::solveSimple(double a, double amount)
214 double integral_a = integrateSimplePoint(a);
215 int ind = binarySearch(integral_, integral_a + amount, 0, nbPoints_ - 1);
216 double time = timePoints_[ind];
217 time += (integral_a + amount - integral_[ind]) /
218 ((integral_[ind + 1] - integral_[ind]) / (timePoints_[ind + 1] - timePoints_[ind]));
224 * \brief Auxiliary function to update the CPU speed scale.
226 * This function uses the trace structure to return the speed scale at the determined time a.
228 * \return CPU speed scale
230 double CpuTiTgmr::getPowerScale(double a)
232 double reduced_a = a - floor(a / lastTime_) * lastTime_;
233 int point = trace_->binarySearch(trace_->timePoints_, reduced_a, 0, trace_->nbPoints_ - 1);
234 trace_mgr::DatedValue val = speedTrace_->event_list.at(point);
239 * \brief Creates a new integration trace from a tmgr_trace_t
241 * \param speedTrace CPU availability trace
242 * \param value Percentage of CPU speed available (useful to fixed tracing)
243 * \return Integration trace structure
245 CpuTiTgmr::CpuTiTgmr(tmgr_trace_t speedTrace, double value) :
246 speedTrace_(speedTrace)
248 double total_time = 0.0;
251 /* no availability file, fixed trace */
252 if (not speedTrace) {
255 XBT_DEBUG("No availability trace. Constant value = %f", value);
259 /* only one point available, fixed trace */
260 if (speedTrace->event_list.size() == 1) {
261 trace_mgr::DatedValue val = speedTrace->event_list.front();
267 type_ = TRACE_DYNAMIC;
269 /* count the total time of trace file */
270 for (auto const& val : speedTrace->event_list)
271 total_time += val.date_;
273 trace_ = new CpuTiTrace(speedTrace);
274 lastTime_ = total_time;
275 total_ = trace_->integrateSimple(0, total_time);
277 XBT_DEBUG("Total integral %f, last_time %f ", total_, lastTime_);
281 * \brief Binary search in array.
282 * It returns the first point of the interval in which "a" is.
284 * \param a Value to search
285 * \param low Low bound to search in array
286 * \param high Upper bound to search in array
287 * \return Index of point
289 int CpuTiTrace::binarySearch(double *array, double a, int low, int high)
291 xbt_assert(low < high, "Wrong parameters: low (%d) should be smaller than high (%d)", low, high);
294 int mid = low + (high - low) / 2;
295 XBT_DEBUG("a %f low %d high %d mid %d value %f", a, low, high, mid, array[mid]);
302 while (low < high - 1);
314 void surf_cpu_model_init_ti()
316 xbt_assert(not surf_cpu_model_pm, "CPU model already initialized. This should not happen.");
317 xbt_assert(not surf_cpu_model_vm, "CPU model already initialized. This should not happen.");
319 surf_cpu_model_pm = new simgrid::surf::CpuTiModel();
320 all_existing_models->push_back(surf_cpu_model_pm);
322 surf_cpu_model_vm = new simgrid::surf::CpuTiModel();
323 all_existing_models->push_back(surf_cpu_model_vm);
329 CpuTiModel::~CpuTiModel()
331 surf_cpu_model_pm = nullptr;
334 Cpu *CpuTiModel::createCpu(simgrid::s4u::Host *host, std::vector<double>* speedPerPstate, int core)
336 return new CpuTi(this, host, speedPerPstate, core);
339 double CpuTiModel::next_occuring_event(double now)
341 double min_action_duration = -1;
343 /* iterates over modified cpus to update share resources */
344 for (auto it = std::begin(modifiedCpu_); it != std::end(modifiedCpu_);) {
346 ++it; // increment iterator here since the following call to ti.updateActionsFinishTime() may invalidate it
347 ti.updateActionsFinishTime(now);
350 /* get the min next event if heap not empty */
351 if (not actionHeapIsEmpty())
352 min_action_duration = actionHeapTopDate() - now;
354 XBT_DEBUG("Share resources, min next event date: %f", min_action_duration);
356 return min_action_duration;
359 void CpuTiModel::update_actions_state(double now, double /*delta*/)
361 while (not actionHeapIsEmpty() && actionHeapTopDate() <= now) {
362 CpuTiAction* action = static_cast<CpuTiAction*>(actionHeapPop());
363 XBT_DEBUG("Action %p: finish", action);
364 action->finish(kernel::resource::Action::State::done);
365 /* update remaining amount of all actions */
366 action->cpu_->updateRemainingAmount(surf_get_clock());
373 CpuTi::CpuTi(CpuTiModel *model, simgrid::s4u::Host *host, std::vector<double> *speedPerPstate, int core)
374 : Cpu(model, host, speedPerPstate, core)
376 xbt_assert(core==1,"Multi-core not handled by this model yet");
379 speed_.peak = speedPerPstate->front();
380 XBT_DEBUG("CPU create: peak=%f", speed_.peak);
382 speedIntegratedTrace_ = new CpuTiTgmr(nullptr, 1/*scale*/);
388 delete speedIntegratedTrace_;
390 void CpuTi::setSpeedTrace(tmgr_trace_t trace)
392 if (speedIntegratedTrace_)
393 delete speedIntegratedTrace_;
395 speedIntegratedTrace_ = new CpuTiTgmr(trace, speed_.scale);
397 /* add a fake trace event if periodicity == 0 */
398 if (trace && trace->event_list.size() > 1) {
399 trace_mgr::DatedValue val = trace->event_list.back();
400 if (val.date_ < 1e-12)
401 speed_.event = future_evt_set->add_trace(new simgrid::trace_mgr::trace(), this);
405 void CpuTi::apply_event(tmgr_trace_event_t event, double value)
407 if (event == speed_.event) {
408 tmgr_trace_t speedTrace;
411 XBT_DEBUG("Finish trace date: value %f", value);
412 /* update remaining of actions and put in modified cpu list */
413 updateRemainingAmount(surf_get_clock());
417 speedTrace = speedIntegratedTrace_->speedTrace_;
418 trace_mgr::DatedValue val = speedTrace->event_list.back();
419 delete speedIntegratedTrace_;
420 speed_.scale = val.value_;
422 trace = new CpuTiTgmr(TRACE_FIXED, val.value_);
423 XBT_DEBUG("value %f", val.value_);
425 speedIntegratedTrace_ = trace;
427 tmgr_trace_event_unref(&speed_.event);
429 } else if (event == stateEvent_) {
432 host_that_restart.push_back(getHost());
436 double date = surf_get_clock();
438 /* put all action running on cpu to failed */
439 for (CpuTiAction& action : actionSet_) {
440 if (action.get_state() == kernel::resource::Action::State::running ||
441 action.get_state() == kernel::resource::Action::State::ready ||
442 action.get_state() == kernel::resource::Action::State::not_in_the_system) {
443 action.set_finish_time(date);
444 action.set_state(kernel::resource::Action::State::failed);
449 tmgr_trace_event_unref(&stateEvent_);
452 xbt_die("Unknown event!\n");
456 void CpuTi::updateActionsFinishTime(double now)
458 double sum_priority = 0.0;
461 /* update remaining amount of actions */
462 updateRemainingAmount(now);
464 for (CpuTiAction const& action : actionSet_) {
465 /* action not running, skip it */
466 if (action.get_state_set() != surf_cpu_model_pm->get_running_action_set())
469 /* bogus priority, skip it */
470 if (action.get_priority() <= 0)
473 /* action suspended, skip it */
474 if (action.suspended_ != kernel::resource::Action::SuspendStates::not_suspended)
477 sum_priority += 1.0 / action.get_priority();
479 sumPriority_ = sum_priority;
481 for (CpuTiAction& action : actionSet_) {
482 double min_finish = -1;
483 /* action not running, skip it */
484 if (action.get_state_set() != surf_cpu_model_pm->get_running_action_set())
487 /* verify if the action is really running on cpu */
488 if (action.suspended_ == kernel::resource::Action::SuspendStates::not_suspended && action.get_priority() > 0) {
489 /* total area needed to finish the action. Used in trace integration */
490 total_area = (action.get_remains()) * sum_priority * action.get_priority();
492 total_area /= speed_.peak;
494 action.set_finish_time(speedIntegratedTrace_->solve(now, total_area));
495 /* verify which event will happen before (max_duration or finish time) */
496 if (action.get_max_duration() > NO_MAX_DURATION &&
497 action.get_start_time() + action.get_max_duration() < action.get_finish_time())
498 min_finish = action.get_start_time() + action.get_max_duration();
500 min_finish = action.get_finish_time();
502 /* put the max duration time on heap */
503 if (action.get_max_duration() > NO_MAX_DURATION)
504 min_finish = action.get_start_time() + action.get_max_duration();
506 /* add in action heap */
507 if (min_finish > NO_MAX_DURATION)
508 action.heapUpdate(min_finish, kernel::resource::Action::Type::NOTSET);
512 XBT_DEBUG("Update finish time: Cpu(%s) Action: %p, Start Time: %f Finish Time: %f Max duration %f", getCname(),
513 &action, action.get_start_time(), action.get_finish_time(), action.get_max_duration());
515 /* remove from modified cpu */
521 return not actionSet_.empty();
524 double CpuTi::getAvailableSpeed()
526 speed_.scale = speedIntegratedTrace_->getPowerScale(surf_get_clock());
527 return Cpu::getAvailableSpeed();
530 /** @brief Update the remaining amount of actions */
531 void CpuTi::updateRemainingAmount(double now)
534 /* already updated */
535 if (lastUpdate_ >= now)
538 /* compute the integration area */
539 double area_total = speedIntegratedTrace_->integrate(lastUpdate_, now) * speed_.peak;
540 XBT_DEBUG("Flops total: %f, Last update %f", area_total, lastUpdate_);
541 for (CpuTiAction& action : actionSet_) {
542 /* action not running, skip it */
543 if (action.get_state_set() != model()->get_running_action_set())
546 /* bogus priority, skip it */
547 if (action.get_priority() <= 0)
550 /* action suspended, skip it */
551 if (action.suspended_ != kernel::resource::Action::SuspendStates::not_suspended)
554 /* action don't need update */
555 if (action.get_start_time() >= now)
558 /* skip action that are finishing now */
559 if (action.get_finish_time() >= 0 && action.get_finish_time() <= now)
562 /* update remaining */
563 action.update_remains(area_total / (sumPriority_ * action.get_priority()));
564 XBT_DEBUG("Update remaining action(%p) remaining %f", &action, action.get_remains_no_update());
569 CpuAction *CpuTi::execution_start(double size)
571 XBT_IN("(%s,%g)", getCname(), size);
572 CpuTiAction* action = new CpuTiAction(static_cast<CpuTiModel*>(model()), size, isOff(), this);
574 actionSet_.push_back(*action);
581 CpuAction *CpuTi::sleep(double duration)
584 duration = std::max(duration, sg_surf_precision);
586 XBT_IN("(%s,%g)", getCname(), duration);
587 CpuTiAction* action = new CpuTiAction(static_cast<CpuTiModel*>(model()), 1.0, isOff(), this);
589 action->set_max_duration(duration);
590 action->suspended_ = kernel::resource::Action::SuspendStates::sleeping;
591 if (duration == NO_MAX_DURATION) {
592 /* Move to the *end* of the corresponding action set. This convention is used to speed up update_resource_state */
593 simgrid::xbt::intrusive_erase(*action->get_state_set(), *action);
594 action->state_set_ = &static_cast<CpuTiModel*>(model())->runningActionSetThatDoesNotNeedBeingChecked_;
595 action->get_state_set()->push_back(*action);
598 actionSet_.push_back(*action);
604 void CpuTi::modified(bool modified){
605 CpuTiList& modifiedCpu = static_cast<CpuTiModel*>(model())->modifiedCpu_;
607 if (not cpu_ti_hook.is_linked()) {
608 modifiedCpu.push_back(*this);
611 if (cpu_ti_hook.is_linked())
612 simgrid::xbt::intrusive_erase(modifiedCpu, *this);
620 CpuTiAction::CpuTiAction(CpuTiModel *model_, double cost, bool failed, CpuTi *cpu)
621 : CpuAction(model_, cost, failed)
624 cpu_->modified(true);
626 CpuTiAction::~CpuTiAction()
628 /* remove from action_set */
629 if (action_ti_hook.is_linked())
630 simgrid::xbt::intrusive_erase(cpu_->actionSet_, *this);
631 /* remove from heap */
633 cpu_->modified(true);
636 void CpuTiAction::set_state(Action::State state)
638 CpuAction::set_state(state);
639 cpu_->modified(true);
642 void CpuTiAction::cancel()
644 this->set_state(Action::State::failed);
646 cpu_->modified(true);
649 void CpuTiAction::suspend()
651 XBT_IN("(%p)", this);
652 if (suspended_ != Action::SuspendStates::sleeping) {
653 suspended_ = Action::SuspendStates::suspended;
655 cpu_->modified(true);
660 void CpuTiAction::resume()
662 XBT_IN("(%p)", this);
663 if (suspended_ != Action::SuspendStates::sleeping) {
664 suspended_ = Action::SuspendStates::not_suspended;
665 cpu_->modified(true);
670 void CpuTiAction::set_max_duration(double duration)
674 XBT_IN("(%p,%g)", this, duration);
676 Action::set_max_duration(duration);
679 min_finish = (get_start_time() + get_max_duration()) < get_finish_time() ? (get_start_time() + get_max_duration())
682 min_finish = get_finish_time();
684 /* add in action heap */
685 heapUpdate(min_finish, Action::Type::NOTSET);
690 void CpuTiAction::set_priority(double priority)
692 XBT_IN("(%p,%g)", this, priority);
693 set_priority_no_update(priority);
694 cpu_->modified(true);
698 double CpuTiAction::get_remains()
700 XBT_IN("(%p)", this);
701 cpu_->updateRemainingAmount(surf_get_clock());
703 return get_remains_no_update();
709 #endif /* SURF_MODEL_CPUTI_H_ */