1 /* Copyright (c) 2013-2017. 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. */
8 #include "src/surf/trace_mgr.hpp"
10 #ifndef SURF_MODEL_CPUTI_H_
11 #define SURF_MODEL_CPUTI_H_
13 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(surf_cpu_ti, surf_cpu, "Logging specific to the SURF CPU TRACE INTEGRATION module");
22 CpuTiTrace::CpuTiTrace(tmgr_trace_t speedTrace)
27 nbPoints_ = speedTrace->event_list.size() + 1;
28 timePoints_ = new double[nbPoints_];
29 integral_ = new double[nbPoints_];
30 for (auto const& val : speedTrace->event_list) {
31 timePoints_[i] = time;
32 integral_[i] = integral;
33 integral += val.date_ * val.value_;
37 timePoints_[i] = time;
38 integral_[i] = integral;
41 CpuTiTrace::~CpuTiTrace()
43 delete [] timePoints_;
47 CpuTiTgmr::~CpuTiTgmr()
54 * \brief Integrate trace
56 * Wrapper around surf_cpu_integrate_trace_simple() to get
59 * \param a Begin of interval
60 * \param b End of interval
61 * \return the integrate value. -1 if an error occurs.
63 double CpuTiTgmr::integrate(double a, double b)
67 if ((a < 0.0) || (a > b)) {
68 xbt_die("Error, invalid integration interval [%.2f,%.2f]. "
69 "You probably have a task executing with negative computation amount. Check your code.", a, b);
71 if (fabs(a -b) < EPSILON)
74 if (type_ == TRACE_FIXED) {
75 return ((b - a) * value_);
78 if (fabs(ceil(a / lastTime_) - a / lastTime_) < EPSILON)
79 a_index = 1 + static_cast<int>(ceil(a / lastTime_));
81 a_index = static_cast<int> (ceil(a / lastTime_));
83 int b_index = static_cast<int> (floor(b / lastTime_));
85 if (a_index > b_index) { /* Same chunk */
86 return trace_->integrateSimple(a - (a_index - 1) * lastTime_, b - (b_index) * lastTime_);
89 double first_chunk = trace_->integrateSimple(a - (a_index - 1) * lastTime_, lastTime_);
90 double middle_chunk = (b_index - a_index) * total_;
91 double last_chunk = trace_->integrateSimple(0.0, b - (b_index) * lastTime_);
93 XBT_DEBUG("first_chunk=%.2f middle_chunk=%.2f last_chunk=%.2f\n", first_chunk, middle_chunk, last_chunk);
95 return (first_chunk + middle_chunk + last_chunk);
99 * \brief Auxiliary function to compute the integral between a and b.
100 * It simply computes the integrals at point a and b and returns the difference between them.
101 * \param a Initial point
102 * \param b Final point
104 double CpuTiTrace::integrateSimple(double a, double b)
106 return integrateSimplePoint(b) - integrateSimplePoint(a);
110 * \brief Auxiliary function to compute the integral at point a.
113 double CpuTiTrace::integrateSimplePoint(double a)
117 int ind = binarySearch(timePoints_, a, 0, nbPoints_ - 1);
118 integral += integral_[ind];
120 XBT_DEBUG("a %f ind %d integral %f ind + 1 %f ind %f time +1 %f time %f",
121 a, ind, integral, integral_[ind + 1], integral_[ind], timePoints_[ind + 1], timePoints_[ind]);
122 double_update(&a_aux, timePoints_[ind], sg_maxmin_precision*sg_surf_precision);
124 integral += ((integral_[ind + 1] - integral_[ind]) / (timePoints_[ind + 1] - timePoints_[ind])) *
125 (a - timePoints_[ind]);
126 XBT_DEBUG("Integral a %f = %f", a, integral);
132 * \brief Computes the time needed to execute "amount" on cpu.
134 * Here, amount can span multiple trace periods
136 * \param a Initial time
137 * \param amount Amount to be executed
140 double CpuTiTgmr::solve(double a, double amount)
142 /* Fix very small negative numbers */
143 if ((a < 0.0) && (a > -EPSILON)) {
146 if ((amount < 0.0) && (amount > -EPSILON)) {
151 if ((a < 0.0) || (amount < 0.0)) {
152 XBT_CRITICAL ("Error, invalid parameters [a = %.2f, amount = %.2f]. "
153 "You probably have a task executing with negative computation amount. Check your code.", a, amount);
157 /* At this point, a and amount are positive */
158 if (amount < EPSILON)
161 /* Is the trace fixed ? */
162 if (type_ == TRACE_FIXED) {
163 return (a + (amount / value_));
166 XBT_DEBUG("amount %f total %f", amount, total_);
167 /* Reduce the problem to one where amount <= trace_total */
168 int quotient = static_cast<int>(floor(amount / total_));
169 double reduced_amount = (total_) * ((amount / total_) - floor(amount / total_));
170 double reduced_a = a - (lastTime_) * static_cast<int>(floor(a / lastTime_));
172 XBT_DEBUG("Quotient: %d reduced_amount: %f reduced_a: %f", quotient, reduced_amount, reduced_a);
174 /* Now solve for new_amount which is <= trace_total */
175 double reduced_b = solveSomewhatSimple(reduced_a, reduced_amount);
177 /* Re-map to the original b and amount */
178 double b = (lastTime_) * static_cast<int>(floor(a / lastTime_)) + (quotient * lastTime_) + reduced_b;
183 * \brief Auxiliary function to solve integral
185 * Here, amount is <= trace->total
186 * and a <=trace->last_time
189 double CpuTiTgmr::solveSomewhatSimple(double a, double amount)
193 XBT_DEBUG("Solve integral: [%.2f, amount=%.2f]", a, amount);
194 double amount_till_end = integrate(a, lastTime_);
196 if (amount_till_end > amount) {
197 b = trace_->solveSimple(a, amount);
199 b = lastTime_ + trace_->solveSimple(0.0, amount - amount_till_end);
205 * \brief Auxiliary function to solve integral.
206 * It returns the date when the requested amount of flops is available
207 * \param a Initial point
208 * \param amount Amount of flops
209 * \return The date when amount is available.
211 double CpuTiTrace::solveSimple(double a, double amount)
213 double integral_a = integrateSimplePoint(a);
214 int ind = binarySearch(integral_, integral_a + amount, 0, nbPoints_ - 1);
215 double time = timePoints_[ind];
216 time += (integral_a + amount - integral_[ind]) /
217 ((integral_[ind + 1] - integral_[ind]) / (timePoints_[ind + 1] - timePoints_[ind]));
223 * \brief Auxiliary function to update the CPU speed scale.
225 * This function uses the trace structure to return the speed scale at the determined time a.
227 * \return CPU speed scale
229 double CpuTiTgmr::getPowerScale(double a)
231 double reduced_a = a - floor(a / lastTime_) * lastTime_;
232 int point = trace_->binarySearch(trace_->timePoints_, reduced_a, 0, trace_->nbPoints_ - 1);
233 trace_mgr::DatedValue val = speedTrace_->event_list.at(point);
238 * \brief Creates a new integration trace from a tmgr_trace_t
240 * \param speedTrace CPU availability trace
241 * \param value Percentage of CPU speed available (useful to fixed tracing)
242 * \return Integration trace structure
244 CpuTiTgmr::CpuTiTgmr(tmgr_trace_t speedTrace, double value) :
245 speedTrace_(speedTrace)
247 double total_time = 0.0;
250 /* no availability file, fixed trace */
251 if (not speedTrace) {
254 XBT_DEBUG("No availability trace. Constant value = %f", value);
258 /* only one point available, fixed trace */
259 if (speedTrace->event_list.size() == 1) {
260 trace_mgr::DatedValue val = speedTrace->event_list.front();
266 type_ = TRACE_DYNAMIC;
268 /* count the total time of trace file */
269 for (auto const& val : speedTrace->event_list)
270 total_time += val.date_;
272 trace_ = new CpuTiTrace(speedTrace);
273 lastTime_ = total_time;
274 total_ = trace_->integrateSimple(0, total_time);
276 XBT_DEBUG("Total integral %f, last_time %f ", total_, lastTime_);
280 * \brief Binary search in array.
281 * It returns the first point of the interval in which "a" is.
283 * \param a Value to search
284 * \param low Low bound to search in array
285 * \param high Upper bound to search in array
286 * \return Index of point
288 int CpuTiTrace::binarySearch(double *array, double a, int low, int high)
290 xbt_assert(low < high, "Wrong parameters: low (%d) should be smaller than high (%d)", low, high);
293 int mid = low + (high - low) / 2;
294 XBT_DEBUG("a %f low %d high %d mid %d value %f", a, low, high, mid, array[mid]);
301 while (low < high - 1);
313 void surf_cpu_model_init_ti()
315 xbt_assert(not surf_cpu_model_pm, "CPU model already initialized. This should not happen.");
316 xbt_assert(not surf_cpu_model_vm, "CPU model already initialized. This should not happen.");
318 surf_cpu_model_pm = new simgrid::surf::CpuTiModel();
319 all_existing_models->push_back(surf_cpu_model_pm);
321 surf_cpu_model_vm = new simgrid::surf::CpuTiModel();
322 all_existing_models->push_back(surf_cpu_model_vm);
328 CpuTiModel::CpuTiModel() : CpuModel()
330 runningActionSetThatDoesNotNeedBeingChecked_ = new ActionList();
332 modifiedCpu_ = new CpuTiList();
335 CpuTiModel::~CpuTiModel()
337 surf_cpu_model_pm = nullptr;
338 delete runningActionSetThatDoesNotNeedBeingChecked_;
342 Cpu *CpuTiModel::createCpu(simgrid::s4u::Host *host, std::vector<double>* speedPerPstate, int core)
344 return new CpuTi(this, host, speedPerPstate, core);
347 double CpuTiModel::nextOccuringEvent(double now)
349 double min_action_duration = -1;
351 /* iterates over modified cpus to update share resources */
352 CpuTiList::iterator itend(modifiedCpu_->end());
353 CpuTiList::iterator it(modifiedCpu_->begin());
354 while (it != itend) {
357 ti->updateActionsFinishTime(now);
360 /* get the min next event if heap not empty */
361 if (not actionHeapIsEmpty())
362 min_action_duration = actionHeapTopDate() - now;
364 XBT_DEBUG("Share resources, min next event date: %f", min_action_duration);
366 return min_action_duration;
369 void CpuTiModel::updateActionsState(double now, double /*delta*/)
371 while (not actionHeapIsEmpty() && actionHeapTopDate() <= now) {
372 CpuTiAction* action = static_cast<CpuTiAction*>(actionHeapPop());
373 XBT_DEBUG("Action %p: finish", action);
374 action->finish(Action::State::done);
375 /* set the remains to 0 due to precision problems when updating the remaining amount */
376 action->setRemains(0);
377 /* update remaining amount of all actions */
378 action->cpu_->updateRemainingAmount(surf_get_clock());
385 CpuTi::CpuTi(CpuTiModel *model, simgrid::s4u::Host *host, std::vector<double> *speedPerPstate, int core)
386 : Cpu(model, host, speedPerPstate, core)
388 xbt_assert(core==1,"Multi-core not handled by this model yet");
391 actionSet_ = new ActionTiList();
393 speed_.peak = speedPerPstate->front();
394 XBT_DEBUG("CPU create: peak=%f", speed_.peak);
396 speedIntegratedTrace_ = new CpuTiTgmr(nullptr, 1/*scale*/);
402 delete speedIntegratedTrace_;
405 void CpuTi::setSpeedTrace(tmgr_trace_t trace)
407 if (speedIntegratedTrace_)
408 delete speedIntegratedTrace_;
410 speedIntegratedTrace_ = new CpuTiTgmr(trace, speed_.scale);
412 /* add a fake trace event if periodicity == 0 */
413 if (trace && trace->event_list.size() > 1) {
414 trace_mgr::DatedValue val = trace->event_list.back();
415 if (val.date_ < 1e-12)
416 speed_.event = future_evt_set->add_trace(new simgrid::trace_mgr::trace(), this);
420 void CpuTi::apply_event(tmgr_trace_event_t event, double value)
422 if (event == speed_.event) {
423 tmgr_trace_t speedTrace;
426 XBT_DEBUG("Finish trace date: value %f", value);
427 /* update remaining of actions and put in modified cpu swag */
428 updateRemainingAmount(surf_get_clock());
432 speedTrace = speedIntegratedTrace_->speedTrace_;
433 trace_mgr::DatedValue val = speedTrace->event_list.back();
434 delete speedIntegratedTrace_;
435 speed_.scale = val.value_;
437 trace = new CpuTiTgmr(TRACE_FIXED, val.value_);
438 XBT_DEBUG("value %f", val.value_);
440 speedIntegratedTrace_ = trace;
442 tmgr_trace_event_unref(&speed_.event);
444 } else if (event == stateEvent_) {
447 host_that_restart.push_back(getHost());
451 double date = surf_get_clock();
453 /* put all action running on cpu to failed */
454 ActionTiList::iterator itend(actionSet_->end());
455 for (ActionTiList::iterator it(actionSet_->begin()); it != itend; ++it) {
456 CpuTiAction *action = &*it;
457 if (action->getState() == Action::State::running
458 || action->getState() == Action::State::ready
459 || action->getState() == Action::State::not_in_the_system) {
460 action->setFinishTime(date);
461 action->setState(Action::State::failed);
462 action->heapRemove(model()->getActionHeap());
466 tmgr_trace_event_unref(&stateEvent_);
469 xbt_die("Unknown event!\n");
473 void CpuTi::updateActionsFinishTime(double now)
476 double sum_priority = 0.0;
479 /* update remaining amount of actions */
480 updateRemainingAmount(now);
482 ActionTiList::iterator itend(actionSet_->end());
483 for (ActionTiList::iterator it(actionSet_->begin()); it != itend; ++it) {
485 /* action not running, skip it */
486 if (action->getStateSet() != surf_cpu_model_pm->getRunningActionSet())
489 /* bogus priority, skip it */
490 if (action->getPriority() <= 0)
493 /* action suspended, skip it */
494 if (action->suspended_ != 0)
497 sum_priority += 1.0 / action->getPriority();
499 sumPriority_ = sum_priority;
501 for (ActionTiList::iterator it(actionSet_->begin()); it != itend; ++it) {
503 double min_finish = -1;
504 /* action not running, skip it */
505 if (action->getStateSet() != surf_cpu_model_pm->getRunningActionSet())
508 /* verify if the action is really running on cpu */
509 if (action->suspended_ == 0 && action->getPriority() > 0) {
510 /* total area needed to finish the action. Used in trace integration */
511 total_area = (action->getRemains()) * sum_priority * action->getPriority();
513 total_area /= speed_.peak;
515 action->setFinishTime(speedIntegratedTrace_->solve(now, total_area));
516 /* verify which event will happen before (max_duration or finish time) */
517 if (action->getMaxDuration() > NO_MAX_DURATION &&
518 action->getStartTime() + action->getMaxDuration() < action->getFinishTime())
519 min_finish = action->getStartTime() + action->getMaxDuration();
521 min_finish = action->getFinishTime();
523 /* put the max duration time on heap */
524 if (action->getMaxDuration() > NO_MAX_DURATION)
525 min_finish = action->getStartTime() + action->getMaxDuration();
527 /* add in action heap */
528 XBT_DEBUG("action(%p) index %d", action, action->getIndexHeap());
529 if (min_finish > NO_MAX_DURATION)
530 action->heapUpdate(model()->getActionHeap(), min_finish, NOTSET);
532 action->heapRemove(model()->getActionHeap());
534 XBT_DEBUG("Update finish time: Cpu(%s) Action: %p, Start Time: %f Finish Time: %f Max duration %f", getCname(),
535 action, action->getStartTime(), action->getFinishTime(), action->getMaxDuration());
537 /* remove from modified cpu */
543 return not actionSet_->empty();
546 double CpuTi::getAvailableSpeed()
548 speed_.scale = speedIntegratedTrace_->getPowerScale(surf_get_clock());
549 return Cpu::getAvailableSpeed();
552 /** @brief Update the remaining amount of actions */
553 void CpuTi::updateRemainingAmount(double now)
556 /* already updated */
557 if (lastUpdate_ >= now)
560 /* compute the integration area */
561 double area_total = speedIntegratedTrace_->integrate(lastUpdate_, now) * speed_.peak;
562 XBT_DEBUG("Flops total: %f, Last update %f", area_total, lastUpdate_);
563 ActionTiList::iterator itend(actionSet_->end());
564 for (ActionTiList::iterator it(actionSet_->begin()); it != itend; ++it) {
565 CpuTiAction *action = &*it;
566 /* action not running, skip it */
567 if (action->getStateSet() != model()->getRunningActionSet())
570 /* bogus priority, skip it */
571 if (action->getPriority() <= 0)
574 /* action suspended, skip it */
575 if (action->suspended_ != 0)
578 /* action don't need update */
579 if (action->getStartTime() >= now)
582 /* skip action that are finishing now */
583 if (action->getFinishTime() >= 0 && action->getFinishTime() <= now)
586 /* update remaining */
587 action->updateRemains(area_total / (sumPriority_ * action->getPriority()));
588 XBT_DEBUG("Update remaining action(%p) remaining %f", action, action->getRemainsNoUpdate());
593 CpuAction *CpuTi::execution_start(double size)
595 XBT_IN("(%s,%g)", getCname(), size);
596 CpuTiAction* action = new CpuTiAction(static_cast<CpuTiModel*>(model()), size, isOff(), this);
598 actionSet_->push_back(*action);
605 CpuAction *CpuTi::sleep(double duration)
608 duration = MAX(duration, sg_surf_precision);
610 XBT_IN("(%s,%g)", getCname(), duration);
611 CpuTiAction* action = new CpuTiAction(static_cast<CpuTiModel*>(model()), 1.0, isOff(), this);
613 action->setMaxDuration(duration);
614 action->suspended_ = 2;
615 if (duration == NO_MAX_DURATION) {
616 /* Move to the *end* of the corresponding action set. This convention
617 is used to speed up update_resource_state */
618 action->getStateSet()->erase(action->getStateSet()->iterator_to(*action));
619 action->stateSet_ = static_cast<CpuTiModel*>(model())->runningActionSetThatDoesNotNeedBeingChecked_;
620 action->getStateSet()->push_back(*action);
623 actionSet_->push_back(*action);
629 void CpuTi::modified(bool modified){
630 CpuTiList* modifiedCpu = static_cast<CpuTiModel*>(model())->modifiedCpu_;
632 if (not cpu_ti_hook.is_linked()) {
633 modifiedCpu->push_back(*this);
636 if (cpu_ti_hook.is_linked()) {
637 modifiedCpu->erase(modifiedCpu->iterator_to(*this));
646 CpuTiAction::CpuTiAction(CpuTiModel *model_, double cost, bool failed, CpuTi *cpu)
647 : CpuAction(model_, cost, failed)
651 cpu_->modified(true);
654 void CpuTiAction::setState(Action::State state)
656 CpuAction::setState(state);
657 cpu_->modified(true);
660 int CpuTiAction::unref()
664 if (action_hook.is_linked())
665 getStateSet()->erase(getStateSet()->iterator_to(*this));
666 /* remove from action_set */
667 if (action_ti_hook.is_linked())
668 cpu_->actionSet_->erase(cpu_->actionSet_->iterator_to(*this));
669 /* remove from heap */
670 heapRemove(getModel()->getActionHeap());
671 cpu_->modified(true);
678 void CpuTiAction::cancel()
680 this->setState(Action::State::failed);
681 heapRemove(getModel()->getActionHeap());
682 cpu_->modified(true);
685 void CpuTiAction::suspend()
687 XBT_IN("(%p)", this);
688 if (suspended_ != 2) {
690 heapRemove(getModel()->getActionHeap());
691 cpu_->modified(true);
696 void CpuTiAction::resume()
698 XBT_IN("(%p)", this);
699 if (suspended_ != 2) {
701 cpu_->modified(true);
706 void CpuTiAction::setMaxDuration(double duration)
710 XBT_IN("(%p,%g)", this, duration);
712 Action::setMaxDuration(duration);
715 min_finish = (getStartTime() + getMaxDuration()) < getFinishTime() ?
716 (getStartTime() + getMaxDuration()) : getFinishTime();
718 min_finish = getFinishTime();
720 /* add in action heap */
721 heapUpdate(getModel()->getActionHeap(), min_finish, NOTSET);
726 void CpuTiAction::setSharingWeight(double priority)
728 XBT_IN("(%p,%g)", this, priority);
729 setSharingWeightNoUpdate(priority);
730 cpu_->modified(true);
734 double CpuTiAction::getRemains()
736 XBT_IN("(%p)", this);
737 cpu_->updateRemainingAmount(surf_get_clock());
739 return getRemainsNoUpdate();
745 #endif /* SURF_MODEL_CPUTI_H_ */