1 /* Copyright (c) 2013-2015. The SimGrid Team.
2 * All rights reserved. */
4 /* This program is free software; you can redistribute it and/or modify it
5 * under the terms of the license (GNU LGPL) which comes with this package. */
9 #include "src/surf/trace_mgr.hpp"
11 #ifndef SURF_MODEL_CPUTI_H_
12 #define SURF_MODEL_CPUTI_H_
14 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(surf_cpu_ti, surf_cpu,
15 "Logging specific to the SURF CPU TRACE INTEGRATION module");
21 void cpu_ti_action_update_index_heap(void *action, int i)
23 ((simgrid::surf::CpuTiAction*)action)->updateIndexHeap(i);
30 CpuTiTrace::CpuTiTrace(tmgr_trace_t speedTrace)
37 timePoints_ = (double*) xbt_malloc0(sizeof(double) *
38 (xbt_dynar_length(speedTrace->event_list) + 1));
39 integral_ = (double*) xbt_malloc0(sizeof(double) *
40 (xbt_dynar_length(speedTrace->event_list) + 1));
41 nbPoints_ = xbt_dynar_length(speedTrace->event_list) + 1;
42 xbt_dynar_foreach(speedTrace->event_list, cpt, val) {
43 timePoints_[i] = time;
44 integral_[i] = integral;
45 integral += val.delta * val.value;
49 timePoints_[i] = time;
50 integral_[i] = integral;
53 CpuTiTrace::~CpuTiTrace()
55 xbt_free(timePoints_);
59 CpuTiTgmr::~CpuTiTgmr()
66 * \brief Integrate trace
68 * Wrapper around surf_cpu_integrate_trace_simple() to get
71 * \param a Begin of interval
72 * \param b End of interval
73 * \return the integrate value. -1 if an error occurs.
75 double CpuTiTgmr::integrate(double a, double b)
82 if ((a < 0.0) || (a > b)) {
84 ("Error, invalid integration interval [%.2f,%.2f]. You probably have a task executing with negative computation amount. Check your code.",
91 if (type_ == TRACE_FIXED) {
92 return ((b - a) * value_);
95 if (ceil(a / lastTime_) == a / lastTime_)
96 a_index = 1 + (int) (ceil(a / lastTime_));
98 a_index = (int) (ceil(a / lastTime_));
100 b_index = (int) (floor(b / lastTime_));
102 if (a_index > b_index) { /* Same chunk */
103 return trace_->integrateSimple(a - (a_index -
110 first_chunk = trace_->integrateSimple(a - (a_index -
114 middle_chunk = (b_index - a_index) * total_;
115 last_chunk = trace_->integrateSimple(0.0,
120 XBT_DEBUG("first_chunk=%.2f middle_chunk=%.2f last_chunk=%.2f\n",
121 first_chunk, middle_chunk, last_chunk);
123 return (first_chunk + middle_chunk + last_chunk);
127 * \brief Auxiliary function to compute the integral between a and b.
128 * It simply computes the integrals at point a and b and returns the difference between them.
129 * \param a Initial point
130 * \param b Final point
132 double CpuTiTrace::integrateSimple(double a, double b)
134 return integrateSimplePoint(b) - integrateSimplePoint(a);
138 * \brief Auxiliary function to compute the integral at point a.
141 double CpuTiTrace::integrateSimplePoint(double a)
146 ind = binarySearch(timePoints_, a, 0, nbPoints_ - 1);
147 integral += integral_[ind];
148 XBT_DEBUG("a %f ind %d integral %f ind + 1 %f ind %f time +1 %f time %f",
149 a, ind, integral, integral_[ind + 1], integral_[ind],
150 timePoints_[ind + 1], timePoints_[ind]);
151 double_update(&a_aux, timePoints_[ind], sg_maxmin_precision*sg_surf_precision);
153 integral +=((integral_[ind + 1] -
154 integral_[ind]) / (timePoints_[ind + 1] - timePoints_[ind])) * (a - timePoints_[ind]);
155 XBT_DEBUG("Integral a %f = %f", a, integral);
161 * \brief Computes the time needed to execute "amount" on cpu.
163 * Here, amount can span multiple trace periods
165 * \param a Initial time
166 * \param amount Amount to be executed
169 double CpuTiTgmr::solve(double a, double amount)
173 double reduced_amount;
177 /* Fix very small negative numbers */
178 if ((a < 0.0) && (a > -EPSILON)) {
181 if ((amount < 0.0) && (amount > -EPSILON)) {
186 if ((a < 0.0) || (amount < 0.0)) {
188 ("Error, invalid parameters [a = %.2f, amount = %.2f]. You probably have a task executing with negative computation amount. Check your code.",
193 /* At this point, a and amount are positive */
195 if (amount < EPSILON)
198 /* Is the trace fixed ? */
199 if (type_ == TRACE_FIXED) {
200 return (a + (amount / value_));
203 XBT_DEBUG("amount %f total %f", amount, total_);
204 /* Reduce the problem to one where amount <= trace_total */
205 quotient = (int) (floor(amount / total_));
206 reduced_amount = (total_) * ((amount / total_) -
207 floor(amount / total_));
208 reduced_a = a - (lastTime_) * (int) (floor(a / lastTime_));
210 XBT_DEBUG("Quotient: %d reduced_amount: %f reduced_a: %f", quotient,
211 reduced_amount, reduced_a);
213 /* Now solve for new_amount which is <= trace_total */
215 fprintf(stderr,"reduced_a = %.2f\n",reduced_a);
216 fprintf(stderr,"reduced_amount = %.2f\n",reduced_amount);
218 reduced_b = solveSomewhatSimple(reduced_a, reduced_amount);
220 /* Re-map to the original b and amount */
221 b = (lastTime_) * (int) (floor(a / lastTime_)) +
222 (quotient * lastTime_) + reduced_b;
227 * \brief Auxiliary function to solve integral
229 * Here, amount is <= trace->total
230 * and a <=trace->last_time
233 double CpuTiTgmr::solveSomewhatSimple(double a, double amount)
235 double amount_till_end;
238 XBT_DEBUG("Solve integral: [%.2f, amount=%.2f]", a, amount);
239 amount_till_end = integrate(a, lastTime_);
241 fprintf(stderr,"amount_till_end=%.2f\n",amount_till_end);
244 if (amount_till_end > amount) {
245 b = trace_->solveSimple(a, amount);
247 b = lastTime_ + trace_->solveSimple(0.0, amount - amount_till_end);
253 * \brief Auxiliary function to solve integral.
254 * It returns the date when the requested amount of flops is available
255 * \param a Initial point
256 * \param amount Amount of flops
257 * \return The date when amount is available.
259 double CpuTiTrace::solveSimple(double a, double amount)
264 integral_a = integrateSimplePoint(a);
265 ind = binarySearch(integral_, integral_a + amount, 0, nbPoints_ - 1);
266 time = timePoints_[ind];
268 (integral_a + amount -
269 integral_[ind]) / ((integral_[ind + 1] -
271 (timePoints_[ind + 1] -
278 * \brief Auxiliary function to update the CPU speed scale.
280 * This function uses the trace structure to return the speed scale at the determined time a.
282 * \return CPU speed scale
284 double CpuTiTgmr::getPowerScale(double a)
290 reduced_a = a - floor(a / lastTime_) * lastTime_;
291 point = trace_->binarySearch(trace_->timePoints_, reduced_a, 0,
292 trace_->nbPoints_ - 1);
293 xbt_dynar_get_cpy(speedTrace_->event_list, point, &val);
298 * \brief Creates a new integration trace from a tmgr_trace_t
300 * \param speedTrace CPU availability trace
301 * \param value Percentage of CPU speed available (useful to fixed tracing)
302 * \return Integration trace structure
304 CpuTiTgmr::CpuTiTgmr(tmgr_trace_t speedTrace, double value)
306 double total_time = 0.0;
311 /* no availability file, fixed trace */
315 XBT_DEBUG("No availability trace. Constant value = %f", value);
319 /* only one point available, fixed trace */
320 if (xbt_dynar_length(speedTrace->event_list) == 1) {
321 xbt_dynar_get_cpy(speedTrace->event_list, 0, &val);
327 type_ = TRACE_DYNAMIC;
328 speedTrace_ = speedTrace;
330 /* count the total time of trace file */
331 xbt_dynar_foreach(speedTrace->event_list, cpt, val) {
332 total_time += val.delta;
334 trace_ = new CpuTiTrace(speedTrace);
335 lastTime_ = total_time;
336 total_ = trace_->integrateSimple(0, total_time);
338 XBT_DEBUG("Total integral %f, last_time %f ",
343 * \brief Binary search in array.
344 * It returns the first point of the interval in which "a" is.
346 * \param a Value to search
347 * \param low Low bound to search in array
348 * \param high Upper bound to search in array
349 * \return Index of point
351 int CpuTiTrace::binarySearch(double *array, double a, int low, int high)
353 xbt_assert(low < high, "Wrong parameters: low (%d) should be smaller than"
354 " high (%d)", low, high);
358 mid = low + (high - low) / 2;
359 XBT_DEBUG("a %f low %d high %d mid %d value %f", a, low, high, mid,
367 while (low < high - 1);
379 void surf_cpu_model_init_ti()
381 xbt_assert(!surf_cpu_model_pm,"CPU model already initialized. This should not happen.");
382 xbt_assert(!surf_cpu_model_vm,"CPU model already initialized. This should not happen.");
384 surf_cpu_model_pm = new simgrid::surf::CpuTiModel();
385 xbt_dynar_push(all_existing_models, &surf_cpu_model_pm);
387 surf_cpu_model_vm = new simgrid::surf::CpuTiModel();
388 xbt_dynar_push(all_existing_models, &surf_cpu_model_vm);
394 CpuTiModel::CpuTiModel() : CpuModel()
396 runningActionSetThatDoesNotNeedBeingChecked_ = new ActionList();
398 modifiedCpu_ = new CpuTiList();
400 tiActionHeap_ = xbt_heap_new(8, nullptr);
401 xbt_heap_set_update_callback(tiActionHeap_,
402 cpu_ti_action_update_index_heap);
405 CpuTiModel::~CpuTiModel()
407 surf_cpu_model_pm = nullptr;
408 delete runningActionSetThatDoesNotNeedBeingChecked_;
410 xbt_heap_free(tiActionHeap_);
413 Cpu *CpuTiModel::createCpu(simgrid::s4u::Host *host, xbt_dynar_t speedPerPstate, int core)
415 return new CpuTi(this, host, speedPerPstate, core);
418 double CpuTiModel::next_occuring_event(double now)
420 double min_action_duration = -1;
422 /* iterates over modified cpus to update share resources */
423 for(CpuTiList::iterator it(modifiedCpu_->begin()), itend(modifiedCpu_->end())
427 ti->updateActionsFinishTime(now);
430 /* get the min next event if heap not empty */
431 if (xbt_heap_size(tiActionHeap_) > 0)
432 min_action_duration = xbt_heap_maxkey(tiActionHeap_) - now;
434 XBT_DEBUG("Share resources, min next event date: %f", min_action_duration);
436 return min_action_duration;
439 void CpuTiModel::updateActionsState(double now, double /*delta*/)
441 while ((xbt_heap_size(tiActionHeap_) > 0)
442 && (xbt_heap_maxkey(tiActionHeap_) <= now)) {
443 CpuTiAction *action = (CpuTiAction*) xbt_heap_pop(tiActionHeap_);
444 XBT_DEBUG("Action %p: finish", action);
446 /* set the remains to 0 due to precision problems when updating the remaining amount */
447 action->setRemains(0);
448 action->setState(Action::State::done);
449 /* update remaining amount of all actions */
450 action->cpu_->updateRemainingAmount(surf_get_clock());
457 CpuTi::CpuTi(CpuTiModel *model, simgrid::s4u::Host *host, xbt_dynar_t speedPerPstate, int core)
458 : Cpu(model, host, speedPerPstate, core)
460 xbt_assert(core==1,"Multi-core not handled by this model yet");
463 actionSet_ = new ActionTiList();
465 xbt_dynar_get_cpy(speedPerPstate, 0, &speed_.peak);
466 XBT_DEBUG("CPU create: peak=%f", speed_.peak);
468 speedIntegratedTrace_ = new CpuTiTgmr(nullptr, 1/*scale*/);
474 delete speedIntegratedTrace_;
477 void CpuTi::setSpeedTrace(tmgr_trace_t trace)
479 if (speedIntegratedTrace_)
480 delete speedIntegratedTrace_;
482 speedIntegratedTrace_ = new CpuTiTgmr(trace, speed_.scale);
484 /* add a fake trace event if periodicity == 0 */
485 if (trace && xbt_dynar_length(trace->event_list) > 1) {
487 xbt_dynar_get_cpy(trace->event_list, xbt_dynar_length(trace->event_list) - 1, &val);
489 speed_.event = future_evt_set->add_trace(tmgr_empty_trace_new(), 0.0, this);
493 void CpuTi::apply_event(tmgr_trace_iterator_t event, double value)
495 if (event == speed_.event) {
496 tmgr_trace_t speedTrace;
500 XBT_DEBUG("Finish trace date: value %f", value);
501 /* update remaining of actions and put in modified cpu swag */
502 updateRemainingAmount(surf_get_clock());
506 speedTrace = speedIntegratedTrace_->speedTrace_;
507 xbt_dynar_get_cpy(speedTrace->event_list, xbt_dynar_length(speedTrace->event_list) - 1, &val);
508 delete speedIntegratedTrace_;
509 speed_.scale = val.value;
511 trace = new CpuTiTgmr(TRACE_FIXED, val.value);
512 XBT_DEBUG("value %f", val.value);
514 speedIntegratedTrace_ = trace;
516 tmgr_trace_event_unref(&speed_.event);
518 } else if (event == stateEvent_) {
521 xbt_dynar_push_as(host_that_restart, char*, (char *)getName());
525 double date = surf_get_clock();
527 /* put all action running on cpu to failed */
528 for(ActionTiList::iterator it(actionSet_->begin()), itend(actionSet_->end())
529 ; it != itend ; ++it) {
531 CpuTiAction *action = &*it;
532 if (action->getState() == Action::State::running
533 || action->getState() == Action::State::ready
534 || action->getState() == Action::State::not_in_the_system) {
535 action->setFinishTime(date);
536 action->setState(Action::State::failed);
537 if (action->indexHeap_ >= 0) {
538 CpuTiAction *heap_act = (CpuTiAction*)
539 xbt_heap_remove(static_cast<CpuTiModel*>(getModel())->tiActionHeap_, action->indexHeap_);
540 if (heap_act != action)
546 tmgr_trace_event_unref(&stateEvent_);
549 xbt_die("Unknown event!\n");
553 void CpuTi::updateActionsFinishTime(double now)
556 double sum_priority = 0.0, total_area, min_finish = -1;
558 /* update remaining amount of actions */
559 updateRemainingAmount(now);
561 for(ActionTiList::iterator it(actionSet_->begin()), itend(actionSet_->end()) ; it != itend ; ++it) {
563 /* action not running, skip it */
564 if (action->getStateSet() != surf_cpu_model_pm->getRunningActionSet())
567 /* bogus priority, skip it */
568 if (action->getPriority() <= 0)
571 /* action suspended, skip it */
572 if (action->suspended_ != 0)
575 sum_priority += 1.0 / action->getPriority();
577 sumPriority_ = sum_priority;
579 for(ActionTiList::iterator it(actionSet_->begin()), itend(actionSet_->end()) ; it != itend ; ++it) {
582 /* action not running, skip it */
583 if (action->getStateSet() !=
584 surf_cpu_model_pm->getRunningActionSet())
587 /* verify if the action is really running on cpu */
588 if (action->suspended_ == 0 && action->getPriority() > 0) {
589 /* total area needed to finish the action. Used in trace integration */
591 (action->getRemains()) * sum_priority *
592 action->getPriority();
594 total_area /= speed_.peak;
596 action->setFinishTime(speedIntegratedTrace_->solve(now, total_area));
597 /* verify which event will happen before (max_duration or finish time) */
598 if (action->getMaxDuration() != NO_MAX_DURATION &&
599 action->getStartTime() + action->getMaxDuration() < action->finishTime_)
600 min_finish = action->getStartTime() + action->getMaxDuration();
602 min_finish = action->finishTime_;
604 /* put the max duration time on heap */
605 if (action->getMaxDuration() != NO_MAX_DURATION)
606 min_finish = action->getStartTime() + action->getMaxDuration();
608 /* add in action heap */
609 XBT_DEBUG("action(%p) index %d", action, action->indexHeap_);
610 if (action->indexHeap_ >= 0) {
611 CpuTiAction *heap_act = (CpuTiAction*)
612 xbt_heap_remove(static_cast<CpuTiModel*>(getModel())->tiActionHeap_, action->indexHeap_);
613 if (heap_act != action)
616 if (min_finish != NO_MAX_DURATION)
617 xbt_heap_push(static_cast<CpuTiModel*>(getModel())->tiActionHeap_, action, min_finish);
620 ("Update finish time: Cpu(%s) Action: %p, Start Time: %f Finish Time: %f Max duration %f",
621 getName(), action, action->getStartTime(),
623 action->getMaxDuration());
625 /* remove from modified cpu */
631 return !actionSet_->empty();
634 double CpuTi::getAvailableSpeed()
636 speed_.scale = speedIntegratedTrace_->getPowerScale(surf_get_clock());
637 return Cpu::getAvailableSpeed();
640 /** @brief Update the remaining amount of actions */
641 void CpuTi::updateRemainingAmount(double now)
644 /* already updated */
645 if (lastUpdate_ >= now)
648 /* compute the integration area */
649 double area_total = speedIntegratedTrace_->integrate(lastUpdate_, now) * speed_.peak;
650 XBT_DEBUG("Flops total: %f, Last update %f", area_total, lastUpdate_);
652 for(ActionTiList::iterator it(actionSet_->begin()), itend(actionSet_->end()) ; it != itend ; ++it) {
653 CpuTiAction *action = &*it;
654 /* action not running, skip it */
655 if (action->getStateSet() != getModel()->getRunningActionSet())
658 /* bogus priority, skip it */
659 if (action->getPriority() <= 0)
662 /* action suspended, skip it */
663 if (action->suspended_ != 0)
666 /* action don't need update */
667 if (action->getStartTime() >= now)
670 /* skip action that are finishing now */
671 if (action->finishTime_ >= 0 && action->finishTime_ <= now)
674 /* update remaining */
675 action->updateRemains(area_total / (sumPriority_ * action->getPriority()));
676 XBT_DEBUG("Update remaining action(%p) remaining %f", action, action->remains_);
681 CpuAction *CpuTi::execution_start(double size)
683 XBT_IN("(%s,%g)", getName(), size);
684 CpuTiAction *action = new CpuTiAction(static_cast<CpuTiModel*>(getModel()), size, isOff(), this);
686 actionSet_->push_back(*action);
693 CpuAction *CpuTi::sleep(double duration)
696 duration = MAX(duration, sg_surf_precision);
698 XBT_IN("(%s,%g)", getName(), duration);
699 CpuTiAction *action = new CpuTiAction(static_cast<CpuTiModel*>(getModel()), 1.0, isOff(), this);
701 action->maxDuration_ = duration;
702 action->suspended_ = 2;
703 if (duration == NO_MAX_DURATION) {
704 /* Move to the *end* of the corresponding action set. This convention
705 is used to speed up update_resource_state */
706 action->getStateSet()->erase(action->getStateSet()->iterator_to(*action));
707 action->stateSet_ = static_cast<CpuTiModel*>(getModel())->runningActionSetThatDoesNotNeedBeingChecked_;
708 action->getStateSet()->push_back(*action);
711 actionSet_->push_back(*action);
717 void CpuTi::modified(bool modified){
718 CpuTiList *modifiedCpu = static_cast<CpuTiModel*>(getModel())->modifiedCpu_;
720 if (!cpu_ti_hook.is_linked()) {
721 modifiedCpu->push_back(*this);
724 if (cpu_ti_hook.is_linked()) {
725 modifiedCpu->erase(modifiedCpu->iterator_to(*this));
734 CpuTiAction::CpuTiAction(CpuTiModel *model_, double cost, bool failed, CpuTi *cpu)
735 : CpuAction(model_, cost, failed)
739 cpu_->modified(true);
742 void CpuTiAction::updateIndexHeap(int i)
747 void CpuTiAction::setState(Action::State state)
749 CpuAction::setState(state);
750 cpu_->modified(true);
753 int CpuTiAction::unref()
757 if (action_hook.is_linked())
758 getStateSet()->erase(getStateSet()->iterator_to(*this));
759 /* remove from action_set */
760 if (action_ti_hook.is_linked())
761 cpu_->actionSet_->erase(cpu_->actionSet_->iterator_to(*this));
762 /* remove from heap */
763 xbt_heap_remove(static_cast<CpuTiModel*>(getModel())->tiActionHeap_, this->indexHeap_);
764 cpu_->modified(true);
771 void CpuTiAction::cancel()
773 this->setState(Action::State::failed);
774 xbt_heap_remove(getModel()->getActionHeap(), this->indexHeap_);
775 cpu_->modified(true);
779 void CpuTiAction::suspend()
781 XBT_IN("(%p)", this);
782 if (suspended_ != 2) {
784 xbt_heap_remove(getModel()->getActionHeap(), indexHeap_);
785 cpu_->modified(true);
790 void CpuTiAction::resume()
792 XBT_IN("(%p)", this);
793 if (suspended_ != 2) {
795 cpu_->modified(true);
800 void CpuTiAction::setMaxDuration(double duration)
804 XBT_IN("(%p,%g)", this, duration);
806 maxDuration_ = duration;
809 min_finish = (getStartTime() + getMaxDuration()) < getFinishTime() ?
810 (getStartTime() + getMaxDuration()) : getFinishTime();
812 min_finish = getFinishTime();
814 /* add in action heap */
815 if (indexHeap_ >= 0) {
816 CpuTiAction *heap_act = (CpuTiAction*)
817 xbt_heap_remove(getModel()->getActionHeap(), indexHeap_);
818 if (heap_act != this)
821 xbt_heap_push(getModel()->getActionHeap(), this, min_finish);
826 void CpuTiAction::setPriority(double priority)
828 XBT_IN("(%p,%g)", this, priority);
829 priority_ = priority;
830 cpu_->modified(true);
834 double CpuTiAction::getRemains()
836 XBT_IN("(%p)", this);
837 cpu_->updateRemainingAmount(surf_get_clock());
845 #endif /* SURF_MODEL_CPUTI_H_ */