Logo AND Algorithmique Numérique Distribuée

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