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"
10 #include "src/surf/platform.hpp"
12 #ifndef SURF_MODEL_CPUTI_H_
13 #define SURF_MODEL_CPUTI_H_
15 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(surf_cpu_ti, surf_cpu,
16 "Logging specific to the SURF CPU TRACE INTEGRATION module");
22 void cpu_ti_action_update_index_heap(void *action, int i)
24 ((simgrid::surf::CpuTiAction*)action)->updateIndexHeap(i);
31 CpuTiTrace::CpuTiTrace(tmgr_trace_t speedTrace)
38 timePoints_ = (double*) xbt_malloc0(sizeof(double) *
39 (xbt_dynar_length(speedTrace->event_list) + 1));
40 integral_ = (double*) xbt_malloc0(sizeof(double) *
41 (xbt_dynar_length(speedTrace->event_list) + 1));
42 nbPoints_ = xbt_dynar_length(speedTrace->event_list) + 1;
43 xbt_dynar_foreach(speedTrace->event_list, cpt, val) {
44 timePoints_[i] = time;
45 integral_[i] = integral;
46 integral += val.delta * val.value;
50 timePoints_[i] = time;
51 integral_[i] = integral;
54 CpuTiTrace::~CpuTiTrace()
56 xbt_free(timePoints_);
60 CpuTiTgmr::~CpuTiTgmr()
67 * \brief Integrate trace
69 * Wrapper around surf_cpu_integrate_trace_simple() to get
72 * \param trace Trace structure.
73 * \param a Begin of interval
74 * \param b End of interval
75 * \return the integrate value. -1 if an error occurs.
77 double CpuTiTgmr::integrate(double a, double b)
84 if ((a < 0.0) || (a > b)) {
86 ("Error, invalid integration interval [%.2f,%.2f]. You probably have a task executing with negative computation amount. Check your code.",
93 if (type_ == TRACE_FIXED) {
94 return ((b - a) * value_);
97 if (ceil(a / lastTime_) == a / lastTime_)
98 a_index = 1 + (int) (ceil(a / lastTime_));
100 a_index = (int) (ceil(a / lastTime_));
102 b_index = (int) (floor(b / lastTime_));
104 if (a_index > b_index) { /* Same chunk */
105 return trace_->integrateSimple(a - (a_index -
112 first_chunk = trace_->integrateSimple(a - (a_index -
116 middle_chunk = (b_index - a_index) * total_;
117 last_chunk = trace_->integrateSimple(0.0,
122 XBT_DEBUG("first_chunk=%.2f middle_chunk=%.2f last_chunk=%.2f\n",
123 first_chunk, middle_chunk, last_chunk);
125 return (first_chunk + middle_chunk + last_chunk);
129 * \brief Auxiliary function to compute the integral between a and b.
130 * It simply computes the integrals at point a and b and returns the difference between them.
131 * \param a Initial point
132 * \param b Final point
134 double CpuTiTrace::integrateSimple(double a, double b)
136 return integrateSimplePoint(b) - integrateSimplePoint(a);
140 * \brief Auxiliary function to compute the integral at point a.
143 double CpuTiTrace::integrateSimplePoint(double a)
148 ind = binarySearch(timePoints_, a, 0, nbPoints_ - 1);
149 integral += integral_[ind];
150 XBT_DEBUG("a %f ind %d integral %f ind + 1 %f ind %f time +1 %f time %f",
151 a, ind, integral, integral_[ind + 1], integral_[ind],
152 timePoints_[ind + 1], timePoints_[ind]);
153 double_update(&a_aux, timePoints_[ind], sg_maxmin_precision*sg_surf_precision);
155 integral +=((integral_[ind + 1] -
156 integral_[ind]) / (timePoints_[ind + 1] - timePoints_[ind])) * (a - timePoints_[ind]);
157 XBT_DEBUG("Integral a %f = %f", a, integral);
163 * \brief Computes the time needed to execute "amount" on cpu.
165 * Here, amount can span multiple trace periods
167 * \param a Initial time
168 * \param amount Amount to be executed
171 double CpuTiTgmr::solve(double a, double amount)
175 double reduced_amount;
179 /* Fix very small negative numbers */
180 if ((a < 0.0) && (a > -EPSILON)) {
183 if ((amount < 0.0) && (amount > -EPSILON)) {
188 if ((a < 0.0) || (amount < 0.0)) {
190 ("Error, invalid parameters [a = %.2f, amount = %.2f]. You probably have a task executing with negative computation amount. Check your code.",
195 /* At this point, a and amount are positive */
197 if (amount < EPSILON)
200 /* Is the trace fixed ? */
201 if (type_ == TRACE_FIXED) {
202 return (a + (amount / value_));
205 XBT_DEBUG("amount %f total %f", amount, total_);
206 /* Reduce the problem to one where amount <= trace_total */
207 quotient = (int) (floor(amount / total_));
208 reduced_amount = (total_) * ((amount / total_) -
209 floor(amount / total_));
210 reduced_a = a - (lastTime_) * (int) (floor(a / lastTime_));
212 XBT_DEBUG("Quotient: %d reduced_amount: %f reduced_a: %f", quotient,
213 reduced_amount, reduced_a);
215 /* Now solve for new_amount which is <= trace_total */
217 fprintf(stderr,"reduced_a = %.2f\n",reduced_a);
218 fprintf(stderr,"reduced_amount = %.2f\n",reduced_amount);
220 reduced_b = solveSomewhatSimple(reduced_a, reduced_amount);
222 /* Re-map to the original b and amount */
223 b = (lastTime_) * (int) (floor(a / lastTime_)) +
224 (quotient * lastTime_) + reduced_b;
229 * \brief Auxiliary function to solve integral
231 * Here, amount is <= trace->total
232 * and a <=trace->last_time
235 double CpuTiTgmr::solveSomewhatSimple(double a, double amount)
237 double amount_till_end;
240 XBT_DEBUG("Solve integral: [%.2f, amount=%.2f]", a, amount);
241 amount_till_end = integrate(a, lastTime_);
243 fprintf(stderr,"amount_till_end=%.2f\n",amount_till_end);
246 if (amount_till_end > amount) {
247 b = trace_->solveSimple(a, amount);
249 b = lastTime_ + trace_->solveSimple(0.0, amount - amount_till_end);
255 * \brief Auxiliary function to solve integral.
256 * It returns the date when the requested amount of flops is available
257 * \param trace Trace structure
258 * \param a Initial point
259 * \param amount Amount of flops
260 * \return The date when amount is available.
262 double CpuTiTrace::solveSimple(double a, double amount)
267 integral_a = integrateSimplePoint(a);
268 ind = binarySearch(integral_, integral_a + amount, 0, nbPoints_ - 1);
269 time = timePoints_[ind];
271 (integral_a + amount -
272 integral_[ind]) / ((integral_[ind + 1] -
274 (timePoints_[ind + 1] -
281 * \brief Auxiliary function to update the CPU speed scale.
283 * This function uses the trace structure to return the speed scale at the determined time a.
284 * \param trace Trace structure to search the updated speed scale
286 * \return CPU speed scale
288 double CpuTiTgmr::getPowerScale(double a)
294 reduced_a = a - floor(a / lastTime_) * lastTime_;
295 point = trace_->binarySearch(trace_->timePoints_, reduced_a, 0,
296 trace_->nbPoints_ - 1);
297 xbt_dynar_get_cpy(speedTrace_->event_list, point, &val);
302 * \brief Creates a new integration trace from a tmgr_trace_t
304 * \param speedTrace CPU availability trace
305 * \param value Percentage of CPU speed available (useful to fixed tracing)
306 * \param spacing Initial spacing
307 * \return Integration trace structure
309 CpuTiTgmr::CpuTiTgmr(tmgr_trace_t speedTrace, double value)
311 double total_time = 0.0;
316 /* no availability file, fixed trace */
320 XBT_DEBUG("No availability trace. Constant value = %f", value);
324 /* only one point available, fixed trace */
325 if (xbt_dynar_length(speedTrace->event_list) == 1) {
326 xbt_dynar_get_cpy(speedTrace->event_list, 0, &val);
332 type_ = TRACE_DYNAMIC;
333 speedTrace_ = speedTrace;
335 /* count the total time of trace file */
336 xbt_dynar_foreach(speedTrace->event_list, cpt, val) {
337 total_time += val.delta;
339 trace_ = new CpuTiTrace(speedTrace);
340 lastTime_ = total_time;
341 total_ = trace_->integrateSimple(0, total_time);
343 XBT_DEBUG("Total integral %f, last_time %f ",
348 * \brief Binary search in array.
349 * It returns the first point of the interval in which "a" is.
351 * \param a Value to search
352 * \param low Low bound to search in array
353 * \param high Upper bound to search in array
354 * \return Index of point
356 int CpuTiTrace::binarySearch(double *array, double a, int low, int high)
358 xbt_assert(low < high, "Wrong parameters: low (%d) should be smaller than"
359 " high (%d)", low, high);
363 mid = low + (high - low) / 2;
364 XBT_DEBUG("a %f low %d high %d mid %d value %f", a, low, high, mid,
372 while (low < high - 1);
384 void surf_cpu_model_init_ti()
386 xbt_assert(!surf_cpu_model_pm,"CPU model already initialized. This should not happen.");
387 xbt_assert(!surf_cpu_model_vm,"CPU model already initialized. This should not happen.");
389 surf_cpu_model_pm = new simgrid::surf::CpuTiModel();
390 xbt_dynar_push(all_existing_models, &surf_cpu_model_pm);
392 surf_cpu_model_vm = new simgrid::surf::CpuTiModel();
393 xbt_dynar_push(all_existing_models, &surf_cpu_model_vm);
399 CpuTiModel::CpuTiModel() : CpuModel()
401 runningActionSetThatDoesNotNeedBeingChecked_ = new ActionList();
403 modifiedCpu_ = new CpuTiList();
405 tiActionHeap_ = xbt_heap_new(8, NULL);
406 xbt_heap_set_update_callback(tiActionHeap_,
407 cpu_ti_action_update_index_heap);
410 CpuTiModel::~CpuTiModel()
412 surf_cpu_model_pm = NULL;
413 delete runningActionSetThatDoesNotNeedBeingChecked_;
415 xbt_heap_free(tiActionHeap_);
418 Cpu *CpuTiModel::createCpu(simgrid::s4u::Host *host,
419 xbt_dynar_t speedPeak,
422 tmgr_trace_t speedTrace,
425 tmgr_trace_t stateTrace)
427 xbt_assert(core==1,"Multi-core not handled with this model yet");
428 xbt_assert(xbt_dynar_getfirst_as(speedPeak, double) > 0.0,
429 "Speed has to be >0.0. Did you forget to specify the mandatory speed attribute?");
430 CpuTi *cpu = new CpuTi(this, host, speedPeak, pstate, speedScale, speedTrace,
431 core, initiallyOn, stateTrace);
435 double CpuTiModel::next_occuring_event(double now)
437 double min_action_duration = -1;
439 /* iterates over modified cpus to update share resources */
440 for(CpuTiList::iterator it(modifiedCpu_->begin()), itend(modifiedCpu_->end())
444 ti->updateActionsFinishTime(now);
447 /* get the min next event if heap not empty */
448 if (xbt_heap_size(tiActionHeap_) > 0)
449 min_action_duration = xbt_heap_maxkey(tiActionHeap_) - now;
451 XBT_DEBUG("Share resources, min next event date: %f", min_action_duration);
453 return min_action_duration;
456 void CpuTiModel::updateActionsState(double now, double /*delta*/)
458 while ((xbt_heap_size(tiActionHeap_) > 0)
459 && (xbt_heap_maxkey(tiActionHeap_) <= now)) {
460 CpuTiAction *action = (CpuTiAction*) xbt_heap_pop(tiActionHeap_);
461 XBT_DEBUG("Action %p: finish", action);
463 /* set the remains to 0 due to precision problems when updating the remaining amount */
464 action->setRemains(0);
465 action->setState(SURF_ACTION_DONE);
466 /* update remaining amount of all actions */
467 action->cpu_->updateRemainingAmount(surf_get_clock());
474 CpuTi::CpuTi(CpuTiModel *model, simgrid::s4u::Host *host, xbt_dynar_t speedPeak,
475 int pstate, double speedScale, tmgr_trace_t speedTrace, int core,
476 int initiallyOn, tmgr_trace_t stateTrace)
477 : Cpu(model, host, NULL, pstate, core, 0, speedScale, initiallyOn)
479 xbt_assert(core==1,"Multi-core not handled by this model yet");
482 p_speed.scale = speedScale;
483 availTrace_ = new CpuTiTgmr(speedTrace, speedScale);
485 actionSet_ = new ActionTiList();
487 xbt_dynar_get_cpy(speedPeak, 0, &p_speed.peak);
488 XBT_DEBUG("CPU create: peak=%f", p_speed.peak);
491 p_stateEvent = future_evt_set->add_trace(stateTrace, 0.0, this);
493 if (speedTrace && xbt_dynar_length(speedTrace->event_list) > 1) {
495 // add a fake trace event if periodicity == 0
496 xbt_dynar_get_cpy(speedTrace->event_list,
497 xbt_dynar_length(speedTrace->event_list) - 1, &val);
498 if (val.delta == 0) {
500 future_evt_set->add_trace(tmgr_empty_trace_new(), availTrace_->lastTime_, this);
511 void CpuTi::set_speed_trace(tmgr_trace_t trace)
516 availTrace_ = new CpuTiTgmr(trace, p_speed.scale);
518 /* add a fake trace event if periodicity == 0 */
519 if (trace && xbt_dynar_length(trace->event_list) > 1) {
521 xbt_dynar_get_cpy(trace->event_list, xbt_dynar_length(trace->event_list) - 1, &val);
523 p_speed.event = future_evt_set->add_trace(tmgr_empty_trace_new(), 0.0, this);
527 void CpuTi::apply_event(tmgr_trace_iterator_t event, double value)
529 if (event == p_speed.event) {
530 tmgr_trace_t speedTrace;
534 XBT_DEBUG("Finish trace date: value %f", value);
535 /* update remaining of actions and put in modified cpu swag */
536 updateRemainingAmount(surf_get_clock());
540 speedTrace = availTrace_->speedTrace_;
541 xbt_dynar_get_cpy(speedTrace->event_list, xbt_dynar_length(speedTrace->event_list) - 1, &val);
543 p_speed.scale = val.value;
545 trace = new CpuTiTgmr(TRACE_FIXED, val.value);
546 XBT_DEBUG("value %f", val.value);
550 tmgr_trace_event_unref(&p_speed.event);
552 } else if (event == p_stateEvent) {
555 xbt_dynar_push_as(host_that_restart, char*, (char *)getName());
559 double date = surf_get_clock();
561 /* put all action running on cpu to failed */
562 for(ActionTiList::iterator it(actionSet_->begin()), itend(actionSet_->end())
563 ; it != itend ; ++it) {
565 CpuTiAction *action = &*it;
566 if (action->getState() == SURF_ACTION_RUNNING
567 || action->getState() == SURF_ACTION_READY
568 || action->getState() == SURF_ACTION_NOT_IN_THE_SYSTEM) {
569 action->setFinishTime(date);
570 action->setState(SURF_ACTION_FAILED);
571 if (action->indexHeap_ >= 0) {
572 CpuTiAction *heap_act = (CpuTiAction*)
573 xbt_heap_remove(static_cast<CpuTiModel*>(getModel())->tiActionHeap_, action->indexHeap_);
574 if (heap_act != action)
580 tmgr_trace_event_unref(&p_stateEvent);
583 xbt_die("Unknown event!\n");
587 void CpuTi::updateActionsFinishTime(double now)
590 double sum_priority = 0.0, total_area, min_finish = -1;
592 /* update remaining amount of actions */
593 updateRemainingAmount(now);
595 for(ActionTiList::iterator it(actionSet_->begin()), itend(actionSet_->end()) ; it != itend ; ++it) {
597 /* action not running, skip it */
598 if (action->getStateSet() != surf_cpu_model_pm->getRunningActionSet())
601 /* bogus priority, skip it */
602 if (action->getPriority() <= 0)
605 /* action suspended, skip it */
606 if (action->suspended_ != 0)
609 sum_priority += 1.0 / action->getPriority();
611 sumPriority_ = sum_priority;
613 for(ActionTiList::iterator it(actionSet_->begin()), itend(actionSet_->end()) ; it != itend ; ++it) {
616 /* action not running, skip it */
617 if (action->getStateSet() !=
618 surf_cpu_model_pm->getRunningActionSet())
621 /* verify if the action is really running on cpu */
622 if (action->suspended_ == 0 && action->getPriority() > 0) {
623 /* total area needed to finish the action. Used in trace integration */
625 (action->getRemains()) * sum_priority *
626 action->getPriority();
628 total_area /= p_speed.peak;
630 action->setFinishTime(availTrace_->solve(now, total_area));
631 /* verify which event will happen before (max_duration or finish time) */
632 if (action->getMaxDuration() != NO_MAX_DURATION &&
633 action->getStartTime() + action->getMaxDuration() < action->m_finish)
634 min_finish = action->getStartTime() + action->getMaxDuration();
636 min_finish = action->m_finish;
638 /* put the max duration time on heap */
639 if (action->getMaxDuration() != NO_MAX_DURATION)
640 min_finish = action->getStartTime() + action->getMaxDuration();
642 /* add in action heap */
643 XBT_DEBUG("action(%p) index %d", action, action->indexHeap_);
644 if (action->indexHeap_ >= 0) {
645 CpuTiAction *heap_act = (CpuTiAction*)
646 xbt_heap_remove(static_cast<CpuTiModel*>(getModel())->tiActionHeap_, action->indexHeap_);
647 if (heap_act != action)
650 if (min_finish != NO_MAX_DURATION)
651 xbt_heap_push(static_cast<CpuTiModel*>(getModel())->tiActionHeap_, action, min_finish);
654 ("Update finish time: Cpu(%s) Action: %p, Start Time: %f Finish Time: %f Max duration %f",
655 getName(), action, action->getStartTime(),
657 action->getMaxDuration());
659 /* remove from modified cpu */
665 return !actionSet_->empty();
668 double CpuTi::getAvailableSpeed()
670 p_speed.scale = availTrace_->getPowerScale(surf_get_clock());
671 return Cpu::getAvailableSpeed();
674 /** @brief Update the remaining amount of actions */
675 void CpuTi::updateRemainingAmount(double now)
678 /* already updated */
679 if (lastUpdate_ >= now)
682 /* compute the integration area */
683 double area_total = availTrace_->integrate(lastUpdate_, now) * p_speed.peak;
684 XBT_DEBUG("Flops total: %f, Last update %f", area_total, lastUpdate_);
686 for(ActionTiList::iterator it(actionSet_->begin()), itend(actionSet_->end()) ; it != itend ; ++it) {
687 CpuTiAction *action = &*it;
688 /* action not running, skip it */
689 if (action->getStateSet() != getModel()->getRunningActionSet())
692 /* bogus priority, skip it */
693 if (action->getPriority() <= 0)
696 /* action suspended, skip it */
697 if (action->suspended_ != 0)
700 /* action don't need update */
701 if (action->getStartTime() >= now)
704 /* skip action that are finishing now */
705 if (action->m_finish >= 0 && action->m_finish <= now)
708 /* update remaining */
709 action->updateRemains(area_total / (sumPriority_ * action->getPriority()));
710 XBT_DEBUG("Update remaining action(%p) remaining %f", action, action->m_remains);
715 CpuAction *CpuTi::execution_start(double size)
717 XBT_IN("(%s,%g)", getName(), size);
718 CpuTiAction *action = new CpuTiAction(static_cast<CpuTiModel*>(getModel()), size, isOff(), this);
720 actionSet_->push_back(*action);
727 CpuAction *CpuTi::sleep(double duration)
730 duration = MAX(duration, sg_surf_precision);
732 XBT_IN("(%s,%g)", getName(), duration);
733 CpuTiAction *action = new CpuTiAction(static_cast<CpuTiModel*>(getModel()), 1.0, isOff(), this);
735 action->m_maxDuration = duration;
736 action->suspended_ = 2;
737 if (duration == NO_MAX_DURATION) {
738 /* Move to the *end* of the corresponding action set. This convention
739 is used to speed up update_resource_state */
740 action->getStateSet()->erase(action->getStateSet()->iterator_to(*action));
741 action->p_stateSet = static_cast<CpuTiModel*>(getModel())->runningActionSetThatDoesNotNeedBeingChecked_;
742 action->getStateSet()->push_back(*action);
745 actionSet_->push_back(*action);
751 void CpuTi::modified(bool modified){
752 CpuTiList *modifiedCpu = static_cast<CpuTiModel*>(getModel())->modifiedCpu_;
754 if (!cpu_ti_hook.is_linked()) {
755 modifiedCpu->push_back(*this);
758 if (cpu_ti_hook.is_linked()) {
759 modifiedCpu->erase(modifiedCpu->iterator_to(*this));
768 CpuTiAction::CpuTiAction(CpuTiModel *model_, double cost, bool failed, CpuTi *cpu)
769 : CpuAction(model_, cost, failed)
773 cpu_->modified(true);
776 void CpuTiAction::updateIndexHeap(int i)
781 void CpuTiAction::setState(e_surf_action_state_t state)
783 CpuAction::setState(state);
784 cpu_->modified(true);
787 int CpuTiAction::unref()
791 if (action_hook.is_linked())
792 getStateSet()->erase(getStateSet()->iterator_to(*this));
793 /* remove from action_set */
794 if (action_ti_hook.is_linked())
795 cpu_->actionSet_->erase(cpu_->actionSet_->iterator_to(*this));
796 /* remove from heap */
797 xbt_heap_remove(static_cast<CpuTiModel*>(getModel())->tiActionHeap_, this->indexHeap_);
798 cpu_->modified(true);
805 void CpuTiAction::cancel()
807 this->setState(SURF_ACTION_FAILED);
808 xbt_heap_remove(getModel()->getActionHeap(), this->indexHeap_);
809 cpu_->modified(true);
813 void CpuTiAction::suspend()
815 XBT_IN("(%p)", this);
816 if (suspended_ != 2) {
818 xbt_heap_remove(getModel()->getActionHeap(), indexHeap_);
819 cpu_->modified(true);
824 void CpuTiAction::resume()
826 XBT_IN("(%p)", this);
827 if (suspended_ != 2) {
829 cpu_->modified(true);
834 void CpuTiAction::setMaxDuration(double duration)
838 XBT_IN("(%p,%g)", this, duration);
840 m_maxDuration = duration;
843 min_finish = (getStartTime() + getMaxDuration()) < getFinishTime() ?
844 (getStartTime() + getMaxDuration()) : getFinishTime();
846 min_finish = getFinishTime();
848 /* add in action heap */
849 if (indexHeap_ >= 0) {
850 CpuTiAction *heap_act = (CpuTiAction*)
851 xbt_heap_remove(getModel()->getActionHeap(), indexHeap_);
852 if (heap_act != this)
855 xbt_heap_push(getModel()->getActionHeap(), this, min_finish);
860 void CpuTiAction::setPriority(double priority)
862 XBT_IN("(%p,%g)", this, priority);
863 m_priority = priority;
864 cpu_->modified(true);
868 double CpuTiAction::getRemains()
870 XBT_IN("(%p)", this);
871 cpu_->updateRemainingAmount(surf_get_clock());
879 #endif /* SURF_MODEL_CPUTI_H_ */