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, "Logging specific to the SURF CPU TRACE INTEGRATION module");
20 void cpu_ti_action_update_index_heap(void *action, int i)
22 (static_cast<simgrid::surf::CpuTiAction*>(action))->updateIndexHeap(i);
29 CpuTiTrace::CpuTiTrace(tmgr_trace_t speedTrace)
36 timePoints_ = static_cast<double*>(xbt_malloc0(sizeof(double) * (xbt_dynar_length(speedTrace->event_list) + 1)));
37 integral_ = static_cast<double*>(xbt_malloc0(sizeof(double) * (xbt_dynar_length(speedTrace->event_list) + 1)));
38 nbPoints_ = xbt_dynar_length(speedTrace->event_list) + 1;
39 xbt_dynar_foreach(speedTrace->event_list, cpt, val) {
40 timePoints_[i] = time;
41 integral_[i] = integral;
42 integral += val.delta * val.value;
46 timePoints_[i] = time;
47 integral_[i] = integral;
50 CpuTiTrace::~CpuTiTrace()
52 xbt_free(timePoints_);
56 CpuTiTgmr::~CpuTiTgmr()
63 * \brief Integrate trace
65 * Wrapper around surf_cpu_integrate_trace_simple() to get
68 * \param a Begin of interval
69 * \param b End of interval
70 * \return the integrate value. -1 if an error occurs.
72 double CpuTiTgmr::integrate(double a, double b)
80 if ((a < 0.0) || (a > b)) {
81 xbt_die("Error, invalid integration interval [%.2f,%.2f]. "
82 "You probably have a task executing with negative computation amount. Check your code.", a, b);
84 if (fabs(a -b) < EPSILON)
87 if (type_ == TRACE_FIXED) {
88 return ((b - a) * value_);
91 if (fabs(ceil(a / lastTime_) - a / lastTime_) < EPSILON)
92 a_index = 1 + static_cast<int>(ceil(a / lastTime_));
94 a_index = static_cast<int> (ceil(a / lastTime_));
96 b_index = static_cast<int> (floor(b / lastTime_));
98 if (a_index > b_index) { /* Same chunk */
99 return trace_->integrateSimple(a - (a_index - 1) * lastTime_, b - (b_index) * lastTime_);
102 first_chunk = trace_->integrateSimple(a - (a_index - 1) * lastTime_, lastTime_);
103 middle_chunk = (b_index - a_index) * total_;
104 last_chunk = trace_->integrateSimple(0.0, b - (b_index) * lastTime_);
106 XBT_DEBUG("first_chunk=%.2f middle_chunk=%.2f last_chunk=%.2f\n", first_chunk, middle_chunk, last_chunk);
108 return (first_chunk + middle_chunk + last_chunk);
112 * \brief Auxiliary function to compute the integral between a and b.
113 * It simply computes the integrals at point a and b and returns the difference between them.
114 * \param a Initial point
115 * \param b Final point
117 double CpuTiTrace::integrateSimple(double a, double b)
119 return integrateSimplePoint(b) - integrateSimplePoint(a);
123 * \brief Auxiliary function to compute the integral at point a.
126 double CpuTiTrace::integrateSimplePoint(double a)
131 ind = binarySearch(timePoints_, a, 0, nbPoints_ - 1);
132 integral += integral_[ind];
133 XBT_DEBUG("a %f ind %d integral %f ind + 1 %f ind %f time +1 %f time %f",
134 a, ind, integral, integral_[ind + 1], integral_[ind], timePoints_[ind + 1], timePoints_[ind]);
135 double_update(&a_aux, timePoints_[ind], sg_maxmin_precision*sg_surf_precision);
137 integral += ((integral_[ind + 1] - integral_[ind]) / (timePoints_[ind + 1] - timePoints_[ind])) *
138 (a - timePoints_[ind]);
139 XBT_DEBUG("Integral a %f = %f", a, integral);
145 * \brief Computes the time needed to execute "amount" on cpu.
147 * Here, amount can span multiple trace periods
149 * \param a Initial time
150 * \param amount Amount to be executed
153 double CpuTiTgmr::solve(double a, double amount)
155 /* Fix very small negative numbers */
156 if ((a < 0.0) && (a > -EPSILON)) {
159 if ((amount < 0.0) && (amount > -EPSILON)) {
164 if ((a < 0.0) || (amount < 0.0)) {
165 XBT_CRITICAL ("Error, invalid parameters [a = %.2f, amount = %.2f]. "
166 "You probably have a task executing with negative computation amount. Check your code.", a, amount);
170 /* At this point, a and amount are positive */
171 if (amount < EPSILON)
174 /* Is the trace fixed ? */
175 if (type_ == TRACE_FIXED) {
176 return (a + (amount / value_));
179 XBT_DEBUG("amount %f total %f", amount, total_);
180 /* Reduce the problem to one where amount <= trace_total */
181 int quotient = static_cast<int>(floor(amount / total_));
182 double reduced_amount = (total_) * ((amount / total_) - floor(amount / total_));
183 double reduced_a = a - (lastTime_) * static_cast<int>(floor(a / lastTime_));
185 XBT_DEBUG("Quotient: %d reduced_amount: %f reduced_a: %f", quotient, reduced_amount, reduced_a);
187 /* Now solve for new_amount which is <= trace_total */
188 double reduced_b = solveSomewhatSimple(reduced_a, reduced_amount);
190 /* Re-map to the original b and amount */
191 double b = (lastTime_) * static_cast<int>(floor(a / lastTime_)) + (quotient * lastTime_) + reduced_b;
196 * \brief Auxiliary function to solve integral
198 * Here, amount is <= trace->total
199 * and a <=trace->last_time
202 double CpuTiTgmr::solveSomewhatSimple(double a, double amount)
206 XBT_DEBUG("Solve integral: [%.2f, amount=%.2f]", a, amount);
207 double amount_till_end = integrate(a, lastTime_);
209 if (amount_till_end > amount) {
210 b = trace_->solveSimple(a, amount);
212 b = lastTime_ + trace_->solveSimple(0.0, amount - amount_till_end);
218 * \brief Auxiliary function to solve integral.
219 * It returns the date when the requested amount of flops is available
220 * \param a Initial point
221 * \param amount Amount of flops
222 * \return The date when amount is available.
224 double CpuTiTrace::solveSimple(double a, double amount)
226 double integral_a = integrateSimplePoint(a);
227 int ind = binarySearch(integral_, integral_a + amount, 0, nbPoints_ - 1);
228 double time = timePoints_[ind];
229 time += (integral_a + amount - integral_[ind]) /
230 ((integral_[ind + 1] - integral_[ind]) / (timePoints_[ind + 1] - timePoints_[ind]));
236 * \brief Auxiliary function to update the CPU speed scale.
238 * This function uses the trace structure to return the speed scale at the determined time a.
240 * \return CPU speed scale
242 double CpuTiTgmr::getPowerScale(double a)
246 double reduced_a = a - floor(a / lastTime_) * lastTime_;
247 int point = trace_->binarySearch(trace_->timePoints_, reduced_a, 0, trace_->nbPoints_ - 1);
248 xbt_dynar_get_cpy(speedTrace_->event_list, point, &val);
253 * \brief Creates a new integration trace from a tmgr_trace_t
255 * \param speedTrace CPU availability trace
256 * \param value Percentage of CPU speed available (useful to fixed tracing)
257 * \return Integration trace structure
259 CpuTiTgmr::CpuTiTgmr(tmgr_trace_t speedTrace, double value)
261 double total_time = 0.0;
266 /* no availability file, fixed trace */
270 XBT_DEBUG("No availability trace. Constant value = %f", value);
274 /* only one point available, fixed trace */
275 if (xbt_dynar_length(speedTrace->event_list) == 1) {
276 xbt_dynar_get_cpy(speedTrace->event_list, 0, &val);
282 type_ = TRACE_DYNAMIC;
283 speedTrace_ = speedTrace;
285 /* count the total time of trace file */
286 xbt_dynar_foreach(speedTrace->event_list, cpt, val) {
287 total_time += val.delta;
289 trace_ = new CpuTiTrace(speedTrace);
290 lastTime_ = total_time;
291 total_ = trace_->integrateSimple(0, total_time);
293 XBT_DEBUG("Total integral %f, last_time %f ", total_, lastTime_);
297 * \brief Binary search in array.
298 * It returns the first point of the interval in which "a" is.
300 * \param a Value to search
301 * \param low Low bound to search in array
302 * \param high Upper bound to search in array
303 * \return Index of point
305 int CpuTiTrace::binarySearch(double *array, double a, int low, int high)
307 xbt_assert(low < high, "Wrong parameters: low (%d) should be smaller than high (%d)", low, high);
311 mid = low + (high - low) / 2;
312 XBT_DEBUG("a %f low %d high %d mid %d value %f", a, low, high, mid, array[mid]);
319 while (low < high - 1);
331 void surf_cpu_model_init_ti()
333 xbt_assert(!surf_cpu_model_pm,"CPU model already initialized. This should not happen.");
334 xbt_assert(!surf_cpu_model_vm,"CPU model already initialized. This should not happen.");
336 surf_cpu_model_pm = new simgrid::surf::CpuTiModel();
337 xbt_dynar_push(all_existing_models, &surf_cpu_model_pm);
339 surf_cpu_model_vm = new simgrid::surf::CpuTiModel();
340 xbt_dynar_push(all_existing_models, &surf_cpu_model_vm);
346 CpuTiModel::CpuTiModel() : CpuModel()
348 runningActionSetThatDoesNotNeedBeingChecked_ = new ActionList();
350 modifiedCpu_ = new CpuTiList();
352 tiActionHeap_ = xbt_heap_new(8, nullptr);
353 xbt_heap_set_update_callback(tiActionHeap_, cpu_ti_action_update_index_heap);
356 CpuTiModel::~CpuTiModel()
358 surf_cpu_model_pm = nullptr;
359 delete runningActionSetThatDoesNotNeedBeingChecked_;
361 xbt_heap_free(tiActionHeap_);
364 Cpu *CpuTiModel::createCpu(simgrid::s4u::Host *host, xbt_dynar_t speedPerPstate, int core)
366 return new CpuTi(this, host, speedPerPstate, core);
369 double CpuTiModel::next_occuring_event(double now)
371 double min_action_duration = -1;
373 /* iterates over modified cpus to update share resources */
374 for(CpuTiList::iterator it(modifiedCpu_->begin()), itend(modifiedCpu_->end()) ; it != itend ;) {
377 ti->updateActionsFinishTime(now);
380 /* get the min next event if heap not empty */
381 if (xbt_heap_size(tiActionHeap_) > 0)
382 min_action_duration = xbt_heap_maxkey(tiActionHeap_) - now;
384 XBT_DEBUG("Share resources, min next event date: %f", min_action_duration);
386 return min_action_duration;
389 void CpuTiModel::updateActionsState(double now, double /*delta*/)
391 while ((xbt_heap_size(tiActionHeap_) > 0) && (xbt_heap_maxkey(tiActionHeap_) <= now)) {
392 CpuTiAction *action = static_cast<CpuTiAction*>(xbt_heap_pop(tiActionHeap_));
393 XBT_DEBUG("Action %p: finish", action);
395 /* set the remains to 0 due to precision problems when updating the remaining amount */
396 action->setRemains(0);
397 action->setState(Action::State::done);
398 /* update remaining amount of all actions */
399 action->cpu_->updateRemainingAmount(surf_get_clock());
406 CpuTi::CpuTi(CpuTiModel *model, simgrid::s4u::Host *host, xbt_dynar_t speedPerPstate, int core)
407 : Cpu(model, host, speedPerPstate, core)
409 xbt_assert(core==1,"Multi-core not handled by this model yet");
412 actionSet_ = new ActionTiList();
414 xbt_dynar_get_cpy(speedPerPstate, 0, &speed_.peak);
415 XBT_DEBUG("CPU create: peak=%f", speed_.peak);
417 speedIntegratedTrace_ = new CpuTiTgmr(nullptr, 1/*scale*/);
423 delete speedIntegratedTrace_;
426 void CpuTi::setSpeedTrace(tmgr_trace_t trace)
428 if (speedIntegratedTrace_)
429 delete speedIntegratedTrace_;
431 speedIntegratedTrace_ = new CpuTiTgmr(trace, speed_.scale);
433 /* add a fake trace event if periodicity == 0 */
434 if (trace && xbt_dynar_length(trace->event_list) > 1) {
436 xbt_dynar_get_cpy(trace->event_list, xbt_dynar_length(trace->event_list) - 1, &val);
437 if (val.delta < 1e-12)
438 speed_.event = future_evt_set->add_trace(tmgr_empty_trace_new(), 0.0, this);
442 void CpuTi::apply_event(tmgr_trace_iterator_t event, double value)
444 if (event == speed_.event) {
445 tmgr_trace_t speedTrace;
449 XBT_DEBUG("Finish trace date: value %f", value);
450 /* update remaining of actions and put in modified cpu swag */
451 updateRemainingAmount(surf_get_clock());
455 speedTrace = speedIntegratedTrace_->speedTrace_;
456 xbt_dynar_get_cpy(speedTrace->event_list, xbt_dynar_length(speedTrace->event_list) - 1, &val);
457 delete speedIntegratedTrace_;
458 speed_.scale = val.value;
460 trace = new CpuTiTgmr(TRACE_FIXED, val.value);
461 XBT_DEBUG("value %f", val.value);
463 speedIntegratedTrace_ = trace;
465 tmgr_trace_event_unref(&speed_.event);
467 } else if (event == stateEvent_) {
470 xbt_dynar_push_as(host_that_restart, char*, (char *)getName());
474 double date = surf_get_clock();
476 /* put all action running on cpu to failed */
477 for(ActionTiList::iterator it(actionSet_->begin()), itend(actionSet_->end()); it != itend ; ++it) {
479 CpuTiAction *action = &*it;
480 if (action->getState() == Action::State::running
481 || action->getState() == Action::State::ready
482 || action->getState() == Action::State::not_in_the_system) {
483 action->setFinishTime(date);
484 action->setState(Action::State::failed);
485 if (action->indexHeap_ >= 0) {
486 CpuTiAction *heap_act =
487 static_cast<CpuTiAction*>(xbt_heap_remove(static_cast<CpuTiModel*>(getModel())->tiActionHeap_, action->indexHeap_));
488 if (heap_act != action)
494 tmgr_trace_event_unref(&stateEvent_);
497 xbt_die("Unknown event!\n");
501 void CpuTi::updateActionsFinishTime(double now)
504 double sum_priority = 0.0;
506 double min_finish = -1;
508 /* update remaining amount of actions */
509 updateRemainingAmount(now);
511 for(ActionTiList::iterator it(actionSet_->begin()), itend(actionSet_->end()) ; it != itend ; ++it) {
513 /* action not running, skip it */
514 if (action->getStateSet() != surf_cpu_model_pm->getRunningActionSet())
517 /* bogus priority, skip it */
518 if (action->getPriority() <= 0)
521 /* action suspended, skip it */
522 if (action->suspended_ != 0)
525 sum_priority += 1.0 / action->getPriority();
527 sumPriority_ = sum_priority;
529 for(ActionTiList::iterator it(actionSet_->begin()), itend(actionSet_->end()) ; it != itend ; ++it) {
532 /* action not running, skip it */
533 if (action->getStateSet() != surf_cpu_model_pm->getRunningActionSet())
536 /* verify if the action is really running on cpu */
537 if (action->suspended_ == 0 && action->getPriority() > 0) {
538 /* total area needed to finish the action. Used in trace integration */
539 total_area = (action->getRemains()) * sum_priority * action->getPriority();
541 total_area /= speed_.peak;
543 action->setFinishTime(speedIntegratedTrace_->solve(now, total_area));
544 /* verify which event will happen before (max_duration or finish time) */
545 if (action->getMaxDuration() > NO_MAX_DURATION &&
546 action->getStartTime() + action->getMaxDuration() < action->finishTime_)
547 min_finish = action->getStartTime() + action->getMaxDuration();
549 min_finish = action->finishTime_;
551 /* put the max duration time on heap */
552 if (action->getMaxDuration() > NO_MAX_DURATION)
553 min_finish = action->getStartTime() + action->getMaxDuration();
555 /* add in action heap */
556 XBT_DEBUG("action(%p) index %d", action, action->indexHeap_);
557 if (action->indexHeap_ >= 0) {
558 CpuTiAction *heap_act =
559 static_cast<CpuTiAction*>(xbt_heap_remove(static_cast<CpuTiModel*>(getModel())->tiActionHeap_, action->indexHeap_));
560 if (heap_act != action)
563 if (min_finish > NO_MAX_DURATION)
564 xbt_heap_push(static_cast<CpuTiModel*>(getModel())->tiActionHeap_, action, min_finish);
566 XBT_DEBUG("Update finish time: Cpu(%s) Action: %p, Start Time: %f Finish Time: %f Max duration %f",
567 getName(), action, action->getStartTime(), action->finishTime_, action->getMaxDuration());
569 /* remove from modified cpu */
575 return !actionSet_->empty();
578 double CpuTi::getAvailableSpeed()
580 speed_.scale = speedIntegratedTrace_->getPowerScale(surf_get_clock());
581 return Cpu::getAvailableSpeed();
584 /** @brief Update the remaining amount of actions */
585 void CpuTi::updateRemainingAmount(double now)
588 /* already updated */
589 if (lastUpdate_ >= now)
592 /* compute the integration area */
593 double area_total = speedIntegratedTrace_->integrate(lastUpdate_, now) * speed_.peak;
594 XBT_DEBUG("Flops total: %f, Last update %f", area_total, lastUpdate_);
596 for(ActionTiList::iterator it(actionSet_->begin()), itend(actionSet_->end()) ; it != itend ; ++it) {
597 CpuTiAction *action = &*it;
598 /* action not running, skip it */
599 if (action->getStateSet() != getModel()->getRunningActionSet())
602 /* bogus priority, skip it */
603 if (action->getPriority() <= 0)
606 /* action suspended, skip it */
607 if (action->suspended_ != 0)
610 /* action don't need update */
611 if (action->getStartTime() >= now)
614 /* skip action that are finishing now */
615 if (action->finishTime_ >= 0 && action->finishTime_ <= now)
618 /* update remaining */
619 action->updateRemains(area_total / (sumPriority_ * action->getPriority()));
620 XBT_DEBUG("Update remaining action(%p) remaining %f", action, action->remains_);
625 CpuAction *CpuTi::execution_start(double size)
627 XBT_IN("(%s,%g)", getName(), size);
628 CpuTiAction *action = new CpuTiAction(static_cast<CpuTiModel*>(getModel()), size, isOff(), this);
630 actionSet_->push_back(*action);
637 CpuAction *CpuTi::sleep(double duration)
640 duration = MAX(duration, sg_surf_precision);
642 XBT_IN("(%s,%g)", getName(), duration);
643 CpuTiAction *action = new CpuTiAction(static_cast<CpuTiModel*>(getModel()), 1.0, isOff(), this);
645 action->maxDuration_ = duration;
646 action->suspended_ = 2;
647 if (duration == NO_MAX_DURATION) {
648 /* Move to the *end* of the corresponding action set. This convention
649 is used to speed up update_resource_state */
650 action->getStateSet()->erase(action->getStateSet()->iterator_to(*action));
651 action->stateSet_ = static_cast<CpuTiModel*>(getModel())->runningActionSetThatDoesNotNeedBeingChecked_;
652 action->getStateSet()->push_back(*action);
655 actionSet_->push_back(*action);
661 void CpuTi::modified(bool modified){
662 CpuTiList *modifiedCpu = static_cast<CpuTiModel*>(getModel())->modifiedCpu_;
664 if (!cpu_ti_hook.is_linked()) {
665 modifiedCpu->push_back(*this);
668 if (cpu_ti_hook.is_linked()) {
669 modifiedCpu->erase(modifiedCpu->iterator_to(*this));
678 CpuTiAction::CpuTiAction(CpuTiModel *model_, double cost, bool failed, CpuTi *cpu)
679 : CpuAction(model_, cost, failed)
683 cpu_->modified(true);
686 void CpuTiAction::updateIndexHeap(int i)
691 void CpuTiAction::setState(Action::State state)
693 CpuAction::setState(state);
694 cpu_->modified(true);
697 int CpuTiAction::unref()
701 if (action_hook.is_linked())
702 getStateSet()->erase(getStateSet()->iterator_to(*this));
703 /* remove from action_set */
704 if (action_ti_hook.is_linked())
705 cpu_->actionSet_->erase(cpu_->actionSet_->iterator_to(*this));
706 /* remove from heap */
707 xbt_heap_remove(static_cast<CpuTiModel*>(getModel())->tiActionHeap_, this->indexHeap_);
708 cpu_->modified(true);
715 void CpuTiAction::cancel()
717 this->setState(Action::State::failed);
718 xbt_heap_remove(getModel()->getActionHeap(), this->indexHeap_);
719 cpu_->modified(true);
723 void CpuTiAction::suspend()
725 XBT_IN("(%p)", this);
726 if (suspended_ != 2) {
728 xbt_heap_remove(getModel()->getActionHeap(), indexHeap_);
729 cpu_->modified(true);
734 void CpuTiAction::resume()
736 XBT_IN("(%p)", this);
737 if (suspended_ != 2) {
739 cpu_->modified(true);
744 void CpuTiAction::setMaxDuration(double duration)
748 XBT_IN("(%p,%g)", this, duration);
750 maxDuration_ = duration;
753 min_finish = (getStartTime() + getMaxDuration()) < getFinishTime() ?
754 (getStartTime() + getMaxDuration()) : getFinishTime();
756 min_finish = getFinishTime();
758 /* add in action heap */
759 if (indexHeap_ >= 0) {
760 CpuTiAction *heap_act = static_cast<CpuTiAction*>(xbt_heap_remove(getModel()->getActionHeap(), indexHeap_));
761 if (heap_act != this)
764 xbt_heap_push(getModel()->getActionHeap(), this, min_finish);
769 void CpuTiAction::setPriority(double priority)
771 XBT_IN("(%p,%g)", this, priority);
772 priority_ = priority;
773 cpu_->modified(true);
777 double CpuTiAction::getRemains()
779 XBT_IN("(%p)", this);
780 cpu_->updateRemainingAmount(surf_get_clock());
788 #endif /* SURF_MODEL_CPUTI_H_ */