Logo AND Algorithmique Numérique Distribuée

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