Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
[DVFS] Use accessors instead of fields
[simgrid.git] / src / plugins / host_dvfs.cpp
1 /* Copyright (c) 2010-2018. The SimGrid Team. All rights reserved.          */
2
3 /* This program is free software; you can redistribute it and/or modify it
4  * under the terms of the license (GNU LGPL) which comes with this package. */
5
6 #include "simgrid/plugins/dvfs.h"
7 #include "simgrid/plugins/load.h"
8 #include "simgrid/s4u/Engine.hpp"
9 #include "src/kernel/activity/ExecImpl.hpp"
10 #include "src/plugins/vm/VirtualMachineImpl.hpp"
11 #include "src/smpi/plugins/ampi/ampi.hpp"
12 #include <xbt/config.hpp>
13
14 #include <boost/algorithm/string.hpp>
15
16 SIMGRID_REGISTER_PLUGIN(host_dvfs, "Dvfs support", &sg_host_dvfs_plugin_init)
17
18 static simgrid::config::Flag<double> cfg_sampling_rate("plugin/dvfs/sampling-rate", {"plugin/dvfs/sampling_rate"},
19     "How often should the dvfs plugin check whether the frequency needs to be changed?", 0.1,
20     [](double val){if (val != 0.1) sg_host_dvfs_plugin_init();});
21
22 static simgrid::config::Flag<std::string> cfg_governor("plugin/dvfs/governor",
23     "Which Governor should be used that adapts the CPU frequency?", "performance",
24
25     std::map<std::string, std::string>({
26         {"adagio", "TODO: Doc"},
27         {"conservative", "TODO: Doc"},
28         {"ondemand", "TODO: Doc"},
29         {"performance", "TODO: Doc"},
30         {"powersave", "TODO: Doc"},
31     }),
32
33     [](std::string val) { if (val != "performance") sg_host_dvfs_plugin_init(); });
34
35 static simgrid::config::Flag<int> cfg_min_pstate("plugin/dvfs/min-pstate", {"plugin/dvfs/min_pstate"},
36     "Which pstate is the minimum (and hence fastest) pstate for this governor?", 0,
37     [](int index) {});
38
39 static const int max_pstate_not_limited = -1;
40 static simgrid::config::Flag<int> cfg_max_pstate("plugin/dvfs/max-pstate", {"plugin/dvfs/max_pstate"},
41     "Which pstate is the maximum (and hence slowest) pstate for this governor?", max_pstate_not_limited,
42     [](int index) {});
43
44 /** @addtogroup SURF_plugin_load
45
46   This plugin makes it very simple for users to obtain the current load for each host.
47
48 */
49
50 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(surf_plugin_dvfs, surf, "Logging specific to the SURF HostDvfs plugin");
51
52 namespace simgrid {
53 namespace plugin {
54
55 namespace dvfs {
56
57 /**
58  *  Add this to your host tag:
59  *    - \<prop id="plugin/dvfs/governor" value="performance" /\>
60  *
61  *  Valid values as of now are: performance, powersave, ondemand, conservative
62  *  It doesn't matter if you use uppercase or lowercase.
63  *
64  *  For the sampling rate, use this:
65  *
66  *    - \<prop id="plugin/dvfs/sampling-rate" value="2" /\>
67  *
68  *  This will run the update() method of the specified governor every 2 seconds
69  *  on that host.
70  *
71  *  These properties can also be used within the \<config\> tag to configure
72  *  these values globally. Using them within the \<host\> will overwrite this
73  *  global configuration
74  */
75 class Governor {
76
77 private:
78   simgrid::s4u::Host* const host_;
79   double sampling_rate_;
80   int min_pstate; //< Never use a pstate less than this one
81   int max_pstate; //< Never use a pstate larger than this one
82
83 public:
84   explicit Governor(simgrid::s4u::Host* ptr)
85       : host_(ptr)
86       , min_pstate(cfg_min_pstate)
87       , max_pstate(cfg_max_pstate == max_pstate_not_limited ? host_->get_pstate_count() - 1 : cfg_max_pstate)
88   {
89     init();
90   }
91   virtual ~Governor() = default;
92   virtual std::string get_name() const = 0;
93   simgrid::s4u::Host* get_host() const { return host_; }
94   int get_min_pstate() const { return min_pstate; }
95   int get_max_pstate() const { return max_pstate; }
96
97   void init()
98   {
99     const char* local_sampling_rate_config = host_->get_property(cfg_sampling_rate.get_name());
100     if (local_sampling_rate_config != nullptr) {
101       sampling_rate_ = std::stod(local_sampling_rate_config);
102     } else {
103       sampling_rate_ = cfg_sampling_rate;
104     }
105     const char* local_min_pstate_config = host_->get_property(cfg_min_pstate.get_name());
106     if (local_min_pstate_config != nullptr) {
107       min_pstate = std::stoi(local_min_pstate_config);
108     }
109
110     const char* local_max_pstate_config = host_->get_property(cfg_max_pstate.get_name());
111     if (local_max_pstate_config != nullptr) {
112       max_pstate = std::stod(local_max_pstate_config);
113     }
114     xbt_assert(max_pstate <= host_->get_pstate_count() - 1, "Value for max_pstate too large!");
115     xbt_assert(min_pstate <= max_pstate, "min_pstate is larger than max_pstate!");
116     xbt_assert(0 <= min_pstate, "min_pstate is negative!");
117   }
118
119   virtual void update()         = 0;
120   double get_sampling_rate() const { return sampling_rate_; }
121 };
122
123 /**
124  * The linux kernel doc describes this governor as follows:
125  * https://www.kernel.org/doc/Documentation/cpu-freq/governors.txt
126  *
127  * > The CPUfreq governor "performance" sets the CPU statically to the
128  * > highest frequency within the borders of scaling_min_freq and
129  * > scaling_max_freq.
130  *
131  * We do not support scaling_min_freq/scaling_max_freq -- we just pick the lowest frequency.
132  */
133 class Performance : public Governor {
134 public:
135   explicit Performance(simgrid::s4u::Host* ptr) : Governor(ptr) {}
136   std::string get_name() const override { return "Performance"; }
137
138   void update() override { get_host()->set_pstate(get_min_pstate()); }
139 };
140
141 /**
142  * The linux kernel doc describes this governor as follows:
143  * https://www.kernel.org/doc/Documentation/cpu-freq/governors.txt
144  *
145  * > The CPUfreq governor "powersave" sets the CPU statically to the
146  * > lowest frequency within the borders of scaling_min_freq and
147  * > scaling_max_freq.
148  *
149  * We do not support scaling_min_freq/scaling_max_freq -- we just pick the lowest frequency.
150  */
151 class Powersave : public Governor {
152 public:
153   explicit Powersave(simgrid::s4u::Host* ptr) : Governor(ptr) {}
154   std::string get_name() const override { return "Powersave"; }
155
156   void update() override { get_host()->set_pstate(get_max_pstate()); }
157 };
158
159 /**
160  * The linux kernel doc describes this governor as follows:
161  * https://www.kernel.org/doc/Documentation/cpu-freq/governors.txt
162  *
163  * > The CPUfreq governor "ondemand" sets the CPU frequency depending on the
164  * > current system load. [...] when triggered, cpufreq checks
165  * > the CPU-usage statistics over the last period and the governor sets the
166  * > CPU accordingly.
167  */
168 class OnDemand : public Governor {
169   /**
170    * See https://elixir.bootlin.com/linux/v4.15.4/source/drivers/cpufreq/cpufreq_ondemand.c
171    * DEF_FREQUENCY_UP_THRESHOLD and od_update()
172    */
173   double freq_up_threshold_ = 0.80;
174
175 public:
176   explicit OnDemand(simgrid::s4u::Host* ptr) : Governor(ptr) {}
177   std::string get_name() const override { return "OnDemand"; }
178
179   void update() override
180   {
181     double load = get_host()->get_core_count() * sg_host_get_avg_load(get_host());
182     sg_host_load_reset(get_host()); // Only consider the period between two calls to this method!
183
184     if (load > freq_up_threshold_) {
185       get_host()->set_pstate(get_min_pstate()); /* Run at max. performance! */
186       XBT_INFO("Load: %f > threshold: %f --> changed to pstate %i", load, freq_up_threshold_, get_min_pstate());
187     } else {
188       /* The actual implementation uses a formula here: (See Kernel file cpufreq_ondemand.c:158)
189        *
190        *    freq_next = min_f + load * (max_f - min_f) / 100
191        *
192        * So they assume that frequency increases by 100 MHz. We will just use
193        * lowest_pstate - load*pstatesCount()
194        */
195       // Load is now < freq_up_threshold; exclude pstate 0 (the fastest)
196       // because pstate 0 can only be selected if load > freq_up_threshold_
197       int new_pstate = get_max_pstate() - load * (get_max_pstate() + 1);
198       if (new_pstate < get_min_pstate())
199         new_pstate = get_min_pstate();
200       get_host()->set_pstate(new_pstate);
201
202       XBT_DEBUG("Load: %f < threshold: %f --> changed to pstate %i", load, freq_up_threshold_, new_pstate);
203     }
204   }
205 };
206
207 /**
208  * This is the conservative governor, which is very similar to the
209  * OnDemand governor. The Linux Kernel Documentation describes it
210  * very well, see https://www.kernel.org/doc/Documentation/cpu-freq/governors.txt:
211  *
212  * > The CPUfreq governor "conservative", much like the "ondemand"
213  * > governor, sets the CPU frequency depending on the current usage.  It
214  * > differs in behaviour in that it gracefully increases and decreases the
215  * > CPU speed rather than jumping to max speed the moment there is any load
216  * > on the CPU. This behaviour is more suitable in a battery powered
217  * > environment.
218  */
219 class Conservative : public Governor {
220   double freq_up_threshold_   = .8;
221   double freq_down_threshold_ = .2;
222
223 public:
224   explicit Conservative(simgrid::s4u::Host* ptr) : Governor(ptr) {}
225   virtual std::string get_name() const override { return "Conservative"; }
226
227   virtual void update() override
228   {
229     double load = get_host()->get_core_count() * sg_host_get_avg_load(get_host());
230     int pstate  = get_host()->get_pstate();
231     sg_host_load_reset(get_host()); // Only consider the period between two calls to this method!
232
233     if (load > freq_up_threshold_) {
234       if (pstate != get_min_pstate()) {
235         get_host()->set_pstate(pstate - 1);
236         XBT_INFO("Load: %f > threshold: %f -> increasing performance to pstate %d", load, freq_up_threshold_,
237                  pstate - 1);
238       } else {
239         XBT_DEBUG("Load: %f > threshold: %f -> but cannot speed up even more, already in highest pstate %d", load,
240                   freq_up_threshold_, pstate);
241       }
242     } else if (load < freq_down_threshold_) {
243       if (pstate != get_max_pstate()) { // Are we in the slowest pstate already?
244         get_host()->set_pstate(pstate + 1);
245         XBT_INFO("Load: %f < threshold: %f -> slowing down to pstate %d", load, freq_down_threshold_, pstate + 1);
246       } else {
247         XBT_DEBUG("Load: %f < threshold: %f -> cannot slow down even more, already in slowest pstate %d", load,
248                   freq_down_threshold_, pstate);
249       }
250     }
251   }
252 };
253
254 class Adagio : public Governor {
255 private:
256   int best_pstate     = 0;
257   double start_time   = 0;
258   double comp_counter = 0;
259   double comp_timer   = 0;
260
261   std::vector<std::vector<double>> rates;
262
263   unsigned int task_id   = 0;
264   bool iteration_running = false; /*< Are we currently between iteration_in and iteration_out calls? */
265
266 public:
267   explicit Adagio(simgrid::s4u::Host* ptr)
268       : Governor(ptr), rates(100, std::vector<double>(ptr->get_pstate_count(), 0.0))
269   {
270     simgrid::smpi::plugin::ampi::on_iteration_in.connect([this](simgrid::s4u::ActorPtr actor) {
271       // Every instance of this class subscribes to this event, so one per host
272       // This means that for any actor, all 'hosts' are normally notified of these
273       // changes, even those who don't currently run the actor 'proc_id'.
274       // -> Let's check if this signal call is for us!
275       if (get_host() == actor->get_host()) {
276         iteration_running = true;
277       }
278     });
279     simgrid::smpi::plugin::ampi::on_iteration_out.connect([this](simgrid::s4u::ActorPtr actor) {
280       if (get_host() == actor->get_host()) {
281         iteration_running = false;
282         task_id           = 0;
283       }
284     });
285     simgrid::kernel::activity::ExecImpl::on_creation.connect([this](simgrid::kernel::activity::ExecImplPtr activity) {
286       if (activity->host_ == get_host())
287         pre_task();
288     });
289     simgrid::kernel::activity::ExecImpl::on_completion.connect([this](simgrid::kernel::activity::ExecImplPtr activity) {
290       // For more than one host (not yet supported), we can access the host via
291       // simcalls_.front()->issuer->iface()->get_host()
292       if (activity->host_ == get_host() && iteration_running) {
293         comp_timer += activity->surf_action_->get_finish_time() - activity->surf_action_->get_start_time();
294       }
295     });
296     simgrid::s4u::Link::on_communicate.connect(
297         [this](kernel::resource::NetworkAction* action, s4u::Host* src, s4u::Host* dst) {
298           if ((get_host() == src || get_host() == dst) && iteration_running) {
299             post_task();
300           }
301         });
302   }
303
304   virtual std::string get_name() const override { return "Adagio"; }
305
306   void pre_task()
307   {
308     sg_host_load_reset(get_host());
309     comp_counter = sg_host_get_computed_flops(get_host()); // Should be 0 because of the reset
310     comp_timer   = 0;
311     start_time   = simgrid::s4u::Engine::get_clock();
312     if (rates.size() <= task_id)
313       rates.resize(task_id + 5, std::vector<double>(get_host()->get_pstate_count(), 0.0));
314     if (rates[task_id][best_pstate] == 0)
315       best_pstate = 0;
316     get_host()->set_pstate(best_pstate); // Load our schedule
317     XBT_DEBUG("Set pstate to %i", best_pstate);
318   }
319
320   void post_task()
321   {
322     double computed_flops = sg_host_get_computed_flops(get_host()) - comp_counter;
323     double target_time    = (simgrid::s4u::Engine::get_clock() - start_time);
324     target_time =
325         target_time *
326         static_cast<double>(99.0 / 100.0); // FIXME We account for t_copy arbitrarily with 1% -- this needs to be fixed
327
328     bool is_initialized         = rates[task_id][best_pstate] != 0;
329     rates[task_id][best_pstate] = computed_flops / comp_timer;
330     if (not is_initialized) {
331       for (int i = 1; i < get_host()->get_pstate_count(); i++) {
332         rates[task_id][i] = rates[task_id][0] * (get_host()->get_pstate_speed(i) / get_host()->get_speed());
333       }
334       is_initialized = true;
335     }
336
337     for (int pstate = get_host()->get_pstate_count() - 1; pstate >= 0; pstate--) {
338       if (computed_flops / rates[task_id][pstate] <= target_time) {
339         // We just found the pstate we want to use!
340         best_pstate = pstate;
341         break;
342       }
343     }
344     task_id++;
345   }
346
347   virtual void update() override {}
348 };
349 } // namespace dvfs
350 } // namespace plugin
351 } // namespace simgrid
352
353 /* **************************** events  callback *************************** */
354 static void on_host_added(simgrid::s4u::Host& host)
355 {
356   if (dynamic_cast<simgrid::s4u::VirtualMachine*>(&host)) // Ignore virtual machines
357     return;
358
359   std::string name              = std::string("dvfs-daemon-") + host.get_cname();
360   simgrid::s4u::ActorPtr daemon = simgrid::s4u::Actor::create(name.c_str(), &host, []() {
361     /**
362      * This lambda function is the function the actor (daemon) will execute
363      * all the time - in the case of the dvfs plugin, this controls when to
364      * lower/raise the frequency.
365      */
366     simgrid::s4u::ActorPtr daemon_proc = simgrid::s4u::Actor::self();
367
368     XBT_DEBUG("DVFS process on %s is a daemon: %d", daemon_proc->get_host()->get_cname(), daemon_proc->is_daemon());
369
370     std::string dvfs_governor;
371     const char* host_conf = daemon_proc->get_host()->get_property("plugin/dvfs/governor");
372     if (host_conf != nullptr) {
373       dvfs_governor = std::string(host_conf);
374       boost::algorithm::to_lower(dvfs_governor);
375     } else {
376       dvfs_governor = cfg_governor;
377       boost::algorithm::to_lower(dvfs_governor);
378     }
379
380     auto governor = [&dvfs_governor, &daemon_proc]() {
381       if (dvfs_governor == "conservative") {
382         return std::unique_ptr<simgrid::plugin::dvfs::Governor>(
383             new simgrid::plugin::dvfs::Conservative(daemon_proc->get_host()));
384       } else if (dvfs_governor == "ondemand") {
385         return std::unique_ptr<simgrid::plugin::dvfs::Governor>(
386             new simgrid::plugin::dvfs::OnDemand(daemon_proc->get_host()));
387       } else if (dvfs_governor == "adagio") {
388         return std::unique_ptr<simgrid::plugin::dvfs::Governor>(
389             new simgrid::plugin::dvfs::Adagio(daemon_proc->get_host()));
390       } else if (dvfs_governor == "performance") {
391         return std::unique_ptr<simgrid::plugin::dvfs::Governor>(
392             new simgrid::plugin::dvfs::Performance(daemon_proc->get_host()));
393       } else if (dvfs_governor == "powersave") {
394         return std::unique_ptr<simgrid::plugin::dvfs::Governor>(
395             new simgrid::plugin::dvfs::Powersave(daemon_proc->get_host()));
396       } else {
397         XBT_CRITICAL("No governor specified for host %s, falling back to Performance",
398                      daemon_proc->get_host()->get_cname());
399         return std::unique_ptr<simgrid::plugin::dvfs::Governor>(
400             new simgrid::plugin::dvfs::Performance(daemon_proc->get_host()));
401       }
402     }();
403
404     while (1) {
405       // Sleep *before* updating; important for startup (i.e., t = 0).
406       // In the beginning, we want to go with the pstates specified in the platform file
407       // (so we sleep first)
408       simgrid::s4u::this_actor::sleep_for(governor->get_sampling_rate());
409       governor->update();
410       XBT_DEBUG("Governor (%s) just updated!", governor->get_name().c_str());
411     }
412
413     XBT_WARN("I should have never reached this point: daemons should be killed when all regular processes are done");
414     return 0;
415   });
416
417   // This call must be placed in this function. Otherwise, the daemonize() call comes too late and
418   // SMPI will take this process as an MPI process!
419   daemon->daemonize();
420 }
421
422 /* **************************** Public interface *************************** */
423
424 /** @ingroup SURF_plugin_load
425  * @brief Initializes the HostDvfs plugin
426  * @details The HostDvfs plugin provides an API to get the current load of each host.
427  */
428 void sg_host_dvfs_plugin_init()
429 {
430   static bool inited = false;
431   if (inited)
432     return;
433   inited = true;
434
435   sg_host_load_plugin_init();
436
437   simgrid::s4u::Host::on_creation.connect(&on_host_added);
438 }