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 trace Trace structure.
72 * \param a Begin of interval
73 * \param b End of interval
74 * \return the integrate value. -1 if an error occurs.
76 double CpuTiTgmr::integrate(double a, double b)
83 if ((a < 0.0) || (a > b)) {
85 ("Error, invalid integration interval [%.2f,%.2f]. You probably have a task executing with negative computation amount. Check your code.",
92 if (type_ == TRACE_FIXED) {
93 return ((b - a) * value_);
96 if (ceil(a / lastTime_) == a / lastTime_)
97 a_index = 1 + (int) (ceil(a / lastTime_));
99 a_index = (int) (ceil(a / lastTime_));
101 b_index = (int) (floor(b / lastTime_));
103 if (a_index > b_index) { /* Same chunk */
104 return trace_->integrateSimple(a - (a_index -
111 first_chunk = trace_->integrateSimple(a - (a_index -
115 middle_chunk = (b_index - a_index) * total_;
116 last_chunk = trace_->integrateSimple(0.0,
121 XBT_DEBUG("first_chunk=%.2f middle_chunk=%.2f last_chunk=%.2f\n",
122 first_chunk, middle_chunk, last_chunk);
124 return (first_chunk + middle_chunk + last_chunk);
128 * \brief Auxiliary function to compute the integral between a and b.
129 * It simply computes the integrals at point a and b and returns the difference between them.
130 * \param a Initial point
131 * \param b Final point
133 double CpuTiTrace::integrateSimple(double a, double b)
135 return integrateSimplePoint(b) - integrateSimplePoint(a);
139 * \brief Auxiliary function to compute the integral at point a.
142 double CpuTiTrace::integrateSimplePoint(double a)
147 ind = binarySearch(timePoints_, a, 0, nbPoints_ - 1);
148 integral += integral_[ind];
149 XBT_DEBUG("a %f ind %d integral %f ind + 1 %f ind %f time +1 %f time %f",
150 a, ind, integral, integral_[ind + 1], integral_[ind],
151 timePoints_[ind + 1], timePoints_[ind]);
152 double_update(&a_aux, timePoints_[ind], sg_maxmin_precision*sg_surf_precision);
154 integral +=((integral_[ind + 1] -
155 integral_[ind]) / (timePoints_[ind + 1] - timePoints_[ind])) * (a - timePoints_[ind]);
156 XBT_DEBUG("Integral a %f = %f", a, integral);
162 * \brief Computes the time needed to execute "amount" on cpu.
164 * Here, amount can span multiple trace periods
166 * \param a Initial time
167 * \param amount Amount to be executed
170 double CpuTiTgmr::solve(double a, double amount)
174 double reduced_amount;
178 /* Fix very small negative numbers */
179 if ((a < 0.0) && (a > -EPSILON)) {
182 if ((amount < 0.0) && (amount > -EPSILON)) {
187 if ((a < 0.0) || (amount < 0.0)) {
189 ("Error, invalid parameters [a = %.2f, amount = %.2f]. You probably have a task executing with negative computation amount. Check your code.",
194 /* At this point, a and amount are positive */
196 if (amount < EPSILON)
199 /* Is the trace fixed ? */
200 if (type_ == TRACE_FIXED) {
201 return (a + (amount / value_));
204 XBT_DEBUG("amount %f total %f", amount, total_);
205 /* Reduce the problem to one where amount <= trace_total */
206 quotient = (int) (floor(amount / total_));
207 reduced_amount = (total_) * ((amount / total_) -
208 floor(amount / total_));
209 reduced_a = a - (lastTime_) * (int) (floor(a / lastTime_));
211 XBT_DEBUG("Quotient: %d reduced_amount: %f reduced_a: %f", quotient,
212 reduced_amount, reduced_a);
214 /* Now solve for new_amount which is <= trace_total */
216 fprintf(stderr,"reduced_a = %.2f\n",reduced_a);
217 fprintf(stderr,"reduced_amount = %.2f\n",reduced_amount);
219 reduced_b = solveSomewhatSimple(reduced_a, reduced_amount);
221 /* Re-map to the original b and amount */
222 b = (lastTime_) * (int) (floor(a / lastTime_)) +
223 (quotient * lastTime_) + reduced_b;
228 * \brief Auxiliary function to solve integral
230 * Here, amount is <= trace->total
231 * and a <=trace->last_time
234 double CpuTiTgmr::solveSomewhatSimple(double a, double amount)
236 double amount_till_end;
239 XBT_DEBUG("Solve integral: [%.2f, amount=%.2f]", a, amount);
240 amount_till_end = integrate(a, lastTime_);
242 fprintf(stderr,"amount_till_end=%.2f\n",amount_till_end);
245 if (amount_till_end > amount) {
246 b = trace_->solveSimple(a, amount);
248 b = lastTime_ + trace_->solveSimple(0.0, amount - amount_till_end);
254 * \brief Auxiliary function to solve integral.
255 * It returns the date when the requested amount of flops is available
256 * \param trace Trace structure
257 * \param a Initial point
258 * \param amount Amount of flops
259 * \return The date when amount is available.
261 double CpuTiTrace::solveSimple(double a, double amount)
266 integral_a = integrateSimplePoint(a);
267 ind = binarySearch(integral_, integral_a + amount, 0, nbPoints_ - 1);
268 time = timePoints_[ind];
270 (integral_a + amount -
271 integral_[ind]) / ((integral_[ind + 1] -
273 (timePoints_[ind + 1] -
280 * \brief Auxiliary function to update the CPU speed scale.
282 * This function uses the trace structure to return the speed scale at the determined time a.
283 * \param trace Trace structure to search the updated speed scale
285 * \return CPU speed scale
287 double CpuTiTgmr::getPowerScale(double a)
293 reduced_a = a - floor(a / lastTime_) * lastTime_;
294 point = trace_->binarySearch(trace_->timePoints_, reduced_a, 0,
295 trace_->nbPoints_ - 1);
296 xbt_dynar_get_cpy(speedTrace_->event_list, point, &val);
301 * \brief Creates a new integration trace from a tmgr_trace_t
303 * \param speedTrace CPU availability trace
304 * \param value Percentage of CPU speed available (useful to fixed tracing)
305 * \param spacing Initial spacing
306 * \return Integration trace structure
308 CpuTiTgmr::CpuTiTgmr(tmgr_trace_t speedTrace, double value)
310 double total_time = 0.0;
315 /* no availability file, fixed trace */
319 XBT_DEBUG("No availability trace. Constant value = %f", value);
323 /* only one point available, fixed trace */
324 if (xbt_dynar_length(speedTrace->event_list) == 1) {
325 xbt_dynar_get_cpy(speedTrace->event_list, 0, &val);
331 type_ = TRACE_DYNAMIC;
332 speedTrace_ = speedTrace;
334 /* count the total time of trace file */
335 xbt_dynar_foreach(speedTrace->event_list, cpt, val) {
336 total_time += val.delta;
338 trace_ = new CpuTiTrace(speedTrace);
339 lastTime_ = total_time;
340 total_ = trace_->integrateSimple(0, total_time);
342 XBT_DEBUG("Total integral %f, last_time %f ",
347 * \brief Binary search in array.
348 * It returns the first point of the interval in which "a" is.
350 * \param a Value to search
351 * \param low Low bound to search in array
352 * \param high Upper bound to search in array
353 * \return Index of point
355 int CpuTiTrace::binarySearch(double *array, double a, int low, int high)
357 xbt_assert(low < high, "Wrong parameters: low (%d) should be smaller than"
358 " high (%d)", low, high);
362 mid = low + (high - low) / 2;
363 XBT_DEBUG("a %f low %d high %d mid %d value %f", a, low, high, mid,
371 while (low < high - 1);
383 void surf_cpu_model_init_ti()
385 xbt_assert(!surf_cpu_model_pm,"CPU model already initialized. This should not happen.");
386 xbt_assert(!surf_cpu_model_vm,"CPU model already initialized. This should not happen.");
388 surf_cpu_model_pm = new simgrid::surf::CpuTiModel();
389 xbt_dynar_push(all_existing_models, &surf_cpu_model_pm);
391 surf_cpu_model_vm = new simgrid::surf::CpuTiModel();
392 xbt_dynar_push(all_existing_models, &surf_cpu_model_vm);
398 CpuTiModel::CpuTiModel() : CpuModel()
400 runningActionSetThatDoesNotNeedBeingChecked_ = new ActionList();
402 modifiedCpu_ = new CpuTiList();
404 tiActionHeap_ = xbt_heap_new(8, NULL);
405 xbt_heap_set_update_callback(tiActionHeap_,
406 cpu_ti_action_update_index_heap);
409 CpuTiModel::~CpuTiModel()
411 surf_cpu_model_pm = NULL;
412 delete runningActionSetThatDoesNotNeedBeingChecked_;
414 xbt_heap_free(tiActionHeap_);
417 Cpu *CpuTiModel::createCpu(simgrid::s4u::Host *host,
418 xbt_dynar_t speedPeak,
421 tmgr_trace_t speedTrace,
424 tmgr_trace_t stateTrace)
426 xbt_assert(core==1,"Multi-core not handled with this model yet");
427 xbt_assert(xbt_dynar_getfirst_as(speedPeak, double) > 0.0,
428 "Speed has to be >0.0. Did you forget to specify the mandatory speed attribute?");
429 CpuTi *cpu = new CpuTi(this, host, speedPeak, pstate, speedScale, speedTrace,
430 core, initiallyOn, stateTrace);
434 double CpuTiModel::next_occuring_event(double now)
436 double min_action_duration = -1;
438 /* iterates over modified cpus to update share resources */
439 for(CpuTiList::iterator it(modifiedCpu_->begin()), itend(modifiedCpu_->end())
443 ti->updateActionsFinishTime(now);
446 /* get the min next event if heap not empty */
447 if (xbt_heap_size(tiActionHeap_) > 0)
448 min_action_duration = xbt_heap_maxkey(tiActionHeap_) - now;
450 XBT_DEBUG("Share resources, min next event date: %f", min_action_duration);
452 return min_action_duration;
455 void CpuTiModel::updateActionsState(double now, double /*delta*/)
457 while ((xbt_heap_size(tiActionHeap_) > 0)
458 && (xbt_heap_maxkey(tiActionHeap_) <= now)) {
459 CpuTiAction *action = (CpuTiAction*) xbt_heap_pop(tiActionHeap_);
460 XBT_DEBUG("Action %p: finish", action);
462 /* set the remains to 0 due to precision problems when updating the remaining amount */
463 action->setRemains(0);
464 action->setState(SURF_ACTION_DONE);
465 /* update remaining amount of all actions */
466 action->cpu_->updateRemainingAmount(surf_get_clock());
473 CpuTi::CpuTi(CpuTiModel *model, simgrid::s4u::Host *host, xbt_dynar_t speedPeak,
474 int pstate, double speedScale, tmgr_trace_t speedTrace, int core,
475 int initiallyOn, tmgr_trace_t stateTrace)
476 : Cpu(model, host, NULL, pstate, core, 0, speedScale, initiallyOn)
478 xbt_assert(core==1,"Multi-core not handled by this model yet");
481 p_speed.scale = speedScale;
482 availTrace_ = new CpuTiTgmr(speedTrace, speedScale);
484 actionSet_ = new ActionTiList();
486 xbt_dynar_get_cpy(speedPeak, 0, &p_speed.peak);
487 XBT_DEBUG("CPU create: peak=%f", p_speed.peak);
490 p_stateEvent = future_evt_set->add_trace(stateTrace, 0.0, this);
492 if (speedTrace && xbt_dynar_length(speedTrace->event_list) > 1) {
494 // add a fake trace event if periodicity == 0
495 xbt_dynar_get_cpy(speedTrace->event_list,
496 xbt_dynar_length(speedTrace->event_list) - 1, &val);
497 if (val.delta == 0) {
499 future_evt_set->add_trace(tmgr_empty_trace_new(), availTrace_->lastTime_, this);
510 void CpuTi::set_speed_trace(tmgr_trace_t trace)
515 availTrace_ = new CpuTiTgmr(trace, p_speed.scale);
517 /* add a fake trace event if periodicity == 0 */
518 if (trace && xbt_dynar_length(trace->event_list) > 1) {
520 xbt_dynar_get_cpy(trace->event_list, xbt_dynar_length(trace->event_list) - 1, &val);
522 p_speed.event = future_evt_set->add_trace(tmgr_empty_trace_new(), 0.0, this);
526 void CpuTi::apply_event(tmgr_trace_iterator_t event, double value)
528 if (event == p_speed.event) {
529 tmgr_trace_t speedTrace;
533 XBT_DEBUG("Finish trace date: value %f", value);
534 /* update remaining of actions and put in modified cpu swag */
535 updateRemainingAmount(surf_get_clock());
539 speedTrace = availTrace_->speedTrace_;
540 xbt_dynar_get_cpy(speedTrace->event_list, xbt_dynar_length(speedTrace->event_list) - 1, &val);
542 p_speed.scale = val.value;
544 trace = new CpuTiTgmr(TRACE_FIXED, val.value);
545 XBT_DEBUG("value %f", val.value);
549 tmgr_trace_event_unref(&p_speed.event);
551 } else if (event == p_stateEvent) {
554 xbt_dynar_push_as(host_that_restart, char*, (char *)getName());
558 double date = surf_get_clock();
560 /* put all action running on cpu to failed */
561 for(ActionTiList::iterator it(actionSet_->begin()), itend(actionSet_->end())
562 ; it != itend ; ++it) {
564 CpuTiAction *action = &*it;
565 if (action->getState() == SURF_ACTION_RUNNING
566 || action->getState() == SURF_ACTION_READY
567 || action->getState() == SURF_ACTION_NOT_IN_THE_SYSTEM) {
568 action->setFinishTime(date);
569 action->setState(SURF_ACTION_FAILED);
570 if (action->indexHeap_ >= 0) {
571 CpuTiAction *heap_act = (CpuTiAction*)
572 xbt_heap_remove(static_cast<CpuTiModel*>(getModel())->tiActionHeap_, action->indexHeap_);
573 if (heap_act != action)
579 tmgr_trace_event_unref(&p_stateEvent);
582 xbt_die("Unknown event!\n");
586 void CpuTi::updateActionsFinishTime(double now)
589 double sum_priority = 0.0, total_area, min_finish = -1;
591 /* update remaining amount of actions */
592 updateRemainingAmount(now);
594 for(ActionTiList::iterator it(actionSet_->begin()), itend(actionSet_->end()) ; it != itend ; ++it) {
596 /* action not running, skip it */
597 if (action->getStateSet() != surf_cpu_model_pm->getRunningActionSet())
600 /* bogus priority, skip it */
601 if (action->getPriority() <= 0)
604 /* action suspended, skip it */
605 if (action->suspended_ != 0)
608 sum_priority += 1.0 / action->getPriority();
610 sumPriority_ = sum_priority;
612 for(ActionTiList::iterator it(actionSet_->begin()), itend(actionSet_->end()) ; it != itend ; ++it) {
615 /* action not running, skip it */
616 if (action->getStateSet() !=
617 surf_cpu_model_pm->getRunningActionSet())
620 /* verify if the action is really running on cpu */
621 if (action->suspended_ == 0 && action->getPriority() > 0) {
622 /* total area needed to finish the action. Used in trace integration */
624 (action->getRemains()) * sum_priority *
625 action->getPriority();
627 total_area /= p_speed.peak;
629 action->setFinishTime(availTrace_->solve(now, total_area));
630 /* verify which event will happen before (max_duration or finish time) */
631 if (action->getMaxDuration() != NO_MAX_DURATION &&
632 action->getStartTime() + action->getMaxDuration() < action->m_finish)
633 min_finish = action->getStartTime() + action->getMaxDuration();
635 min_finish = action->m_finish;
637 /* put the max duration time on heap */
638 if (action->getMaxDuration() != NO_MAX_DURATION)
639 min_finish = action->getStartTime() + action->getMaxDuration();
641 /* add in action heap */
642 XBT_DEBUG("action(%p) index %d", action, action->indexHeap_);
643 if (action->indexHeap_ >= 0) {
644 CpuTiAction *heap_act = (CpuTiAction*)
645 xbt_heap_remove(static_cast<CpuTiModel*>(getModel())->tiActionHeap_, action->indexHeap_);
646 if (heap_act != action)
649 if (min_finish != NO_MAX_DURATION)
650 xbt_heap_push(static_cast<CpuTiModel*>(getModel())->tiActionHeap_, action, min_finish);
653 ("Update finish time: Cpu(%s) Action: %p, Start Time: %f Finish Time: %f Max duration %f",
654 getName(), action, action->getStartTime(),
656 action->getMaxDuration());
658 /* remove from modified cpu */
664 return !actionSet_->empty();
667 double CpuTi::getAvailableSpeed()
669 p_speed.scale = availTrace_->getPowerScale(surf_get_clock());
670 return Cpu::getAvailableSpeed();
673 /** @brief Update the remaining amount of actions */
674 void CpuTi::updateRemainingAmount(double now)
677 /* already updated */
678 if (lastUpdate_ >= now)
681 /* compute the integration area */
682 double area_total = availTrace_->integrate(lastUpdate_, now) * p_speed.peak;
683 XBT_DEBUG("Flops total: %f, Last update %f", area_total, lastUpdate_);
685 for(ActionTiList::iterator it(actionSet_->begin()), itend(actionSet_->end()) ; it != itend ; ++it) {
686 CpuTiAction *action = &*it;
687 /* action not running, skip it */
688 if (action->getStateSet() != getModel()->getRunningActionSet())
691 /* bogus priority, skip it */
692 if (action->getPriority() <= 0)
695 /* action suspended, skip it */
696 if (action->suspended_ != 0)
699 /* action don't need update */
700 if (action->getStartTime() >= now)
703 /* skip action that are finishing now */
704 if (action->m_finish >= 0 && action->m_finish <= now)
707 /* update remaining */
708 action->updateRemains(area_total / (sumPriority_ * action->getPriority()));
709 XBT_DEBUG("Update remaining action(%p) remaining %f", action, action->m_remains);
714 CpuAction *CpuTi::execution_start(double size)
716 XBT_IN("(%s,%g)", getName(), size);
717 CpuTiAction *action = new CpuTiAction(static_cast<CpuTiModel*>(getModel()), size, isOff(), this);
719 actionSet_->push_back(*action);
726 CpuAction *CpuTi::sleep(double duration)
729 duration = MAX(duration, sg_surf_precision);
731 XBT_IN("(%s,%g)", getName(), duration);
732 CpuTiAction *action = new CpuTiAction(static_cast<CpuTiModel*>(getModel()), 1.0, isOff(), this);
734 action->m_maxDuration = duration;
735 action->suspended_ = 2;
736 if (duration == NO_MAX_DURATION) {
737 /* Move to the *end* of the corresponding action set. This convention
738 is used to speed up update_resource_state */
739 action->getStateSet()->erase(action->getStateSet()->iterator_to(*action));
740 action->p_stateSet = static_cast<CpuTiModel*>(getModel())->runningActionSetThatDoesNotNeedBeingChecked_;
741 action->getStateSet()->push_back(*action);
744 actionSet_->push_back(*action);
750 void CpuTi::modified(bool modified){
751 CpuTiList *modifiedCpu = static_cast<CpuTiModel*>(getModel())->modifiedCpu_;
753 if (!cpu_ti_hook.is_linked()) {
754 modifiedCpu->push_back(*this);
757 if (cpu_ti_hook.is_linked()) {
758 modifiedCpu->erase(modifiedCpu->iterator_to(*this));
767 CpuTiAction::CpuTiAction(CpuTiModel *model_, double cost, bool failed, CpuTi *cpu)
768 : CpuAction(model_, cost, failed)
772 cpu_->modified(true);
775 void CpuTiAction::updateIndexHeap(int i)
780 void CpuTiAction::setState(e_surf_action_state_t state)
782 CpuAction::setState(state);
783 cpu_->modified(true);
786 int CpuTiAction::unref()
790 if (action_hook.is_linked())
791 getStateSet()->erase(getStateSet()->iterator_to(*this));
792 /* remove from action_set */
793 if (action_ti_hook.is_linked())
794 cpu_->actionSet_->erase(cpu_->actionSet_->iterator_to(*this));
795 /* remove from heap */
796 xbt_heap_remove(static_cast<CpuTiModel*>(getModel())->tiActionHeap_, this->indexHeap_);
797 cpu_->modified(true);
804 void CpuTiAction::cancel()
806 this->setState(SURF_ACTION_FAILED);
807 xbt_heap_remove(getModel()->getActionHeap(), this->indexHeap_);
808 cpu_->modified(true);
812 void CpuTiAction::suspend()
814 XBT_IN("(%p)", this);
815 if (suspended_ != 2) {
817 xbt_heap_remove(getModel()->getActionHeap(), indexHeap_);
818 cpu_->modified(true);
823 void CpuTiAction::resume()
825 XBT_IN("(%p)", this);
826 if (suspended_ != 2) {
828 cpu_->modified(true);
833 void CpuTiAction::setMaxDuration(double duration)
837 XBT_IN("(%p,%g)", this, duration);
839 m_maxDuration = duration;
842 min_finish = (getStartTime() + getMaxDuration()) < getFinishTime() ?
843 (getStartTime() + getMaxDuration()) : getFinishTime();
845 min_finish = getFinishTime();
847 /* add in action heap */
848 if (indexHeap_ >= 0) {
849 CpuTiAction *heap_act = (CpuTiAction*)
850 xbt_heap_remove(getModel()->getActionHeap(), indexHeap_);
851 if (heap_act != this)
854 xbt_heap_push(getModel()->getActionHeap(), this, min_finish);
859 void CpuTiAction::setPriority(double priority)
861 XBT_IN("(%p,%g)", this, priority);
862 m_priority = priority;
863 cpu_->modified(true);
867 double CpuTiAction::getRemains()
869 XBT_IN("(%p)", this);
870 cpu_->updateRemainingAmount(surf_get_clock());
878 #endif /* SURF_MODEL_CPUTI_H_ */