Logo AND Algorithmique Numérique Distribuée

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