Logo AND Algorithmique Numérique Distribuée

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