Run all changed files 68 8.c/1 *.h through clang-format agin..
[collectd.git] / src / intel_rdt.c
1 /**
2  * collectd - src/intel_rdt.c
3  *
4  * Copyright(c) 2016-2019 Intel Corporation. All rights reserved.
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy
7  * of this software and associated documentation files (the "Software"), to deal
8  * in the Software without restriction, including without limitation the rights
9  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10  * copies of the Software, and to permit persons to whom the Software is
11  * furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22  * SOFTWARE.
23  *
24  * Authors:
25  *   Serhiy Pshyk <serhiyx.pshyk@intel.com>
26  *   Starzyk, Mateusz <mateuszx.starzyk@intel.com>
27  *   Wojciech Andralojc <wojciechx.andralojc@intel.com>
28  *   Michał Aleksiński <michalx.aleksinski@intel.com>
29  **/
30
31 #include <pqos.h>
32 #include "utils/common/common.h"
33 #include "utils/config_cores/config_cores.h"
34 #include "utils/proc_pids/proc_pids.h"
35 #include "collectd.h"
36
37 #define RDT_PLUGIN "intel_rdt"
38
39 /* libpqos v2.0 or newer is required for process monitoring*/
40 #undef LIBPQOS2
41 #if defined(PQOS_VERSION) && PQOS_VERSION >= 20000
42 #define LIBPQOS2
43 #endif
44
45 #define RDT_PLUGIN "intel_rdt"
46
47 #define RDT_MAX_SOCKETS 8
48 #define RDT_MAX_SOCKET_CORES 64
49 #define RDT_MAX_CORES (RDT_MAX_SOCKET_CORES * RDT_MAX_SOCKETS)
50
51 #ifdef LIBPQOS2
52 /*
53  * Process name inside comm file is limited to 16 chars.
54  * More info here: http://man7.org/linux/man-pages/man5/proc.5.html
55  */
56 #define RDT_MAX_NAMES_GROUPS 64
57 #define RDT_PROC_PATH "/proc"
58 #endif /* LIBPQOS2 */
59
60 typedef enum {
61   UNKNOWN = 0,
62   CONFIGURATION_ERROR,
63 } rdt_config_status;
64
65 #ifdef LIBPQOS2
66 struct rdt_name_group_s {
67   char *desc;
68   size_t num_names;
69   char **names;
70   proc_pids_t **proc_pids;
71   size_t monitored_pids_count;
72   enum pqos_mon_event events;
73 };
74 typedef struct rdt_name_group_s rdt_name_group_t;
75 #endif /* LIBPQOS2 */
76
77 struct rdt_ctx_s {
78   core_groups_list_t cores;
79   enum pqos_mon_event events[RDT_MAX_CORES];
80   struct pqos_mon_data *pcgroups[RDT_MAX_CORES];
81 #ifdef LIBPQOS2
82   rdt_name_group_t ngroups[RDT_MAX_NAMES_GROUPS];
83   struct pqos_mon_data *pngroups[RDT_MAX_NAMES_GROUPS];
84   size_t num_ngroups;
85   proc_pids_t **proc_pids;
86   size_t num_proc_pids;
87 #endif /* LIBPQOS2 */
88   const struct pqos_cpuinfo *pqos_cpu;
89   const struct pqos_cap *pqos_cap;
90   const struct pqos_capability *cap_mon;
91 };
92 typedef struct rdt_ctx_s rdt_ctx_t;
93
94 static rdt_ctx_t *g_rdt;
95
96 static rdt_config_status g_state = UNKNOWN;
97
98 static int g_interface = -1;
99
100 static void rdt_submit_derive(const char *cgroup, const char *type,
101                               const char *type_instance, derive_t value) {
102   value_list_t vl = VALUE_LIST_INIT;
103
104   vl.values = &(value_t){.derive = value};
105   vl.values_len = 1;
106
107   sstrncpy(vl.plugin, RDT_PLUGIN, sizeof(vl.plugin));
108   ssnprintf(vl.plugin_instance, sizeof(vl.plugin_instance), "%s", cgroup);
109   sstrncpy(vl.type, type, sizeof(vl.type));
110   if (type_instance)
111     sstrncpy(vl.type_instance, type_instance, sizeof(vl.type_instance));
112
113   plugin_dispatch_values(&vl);
114 }
115
116 static void rdt_submit_gauge(const char *cgroup, const char *type,
117                              const char *type_instance, gauge_t value) {
118   value_list_t vl = VALUE_LIST_INIT;
119
120   vl.values = &(value_t){.gauge = value};
121   vl.values_len = 1;
122
123   sstrncpy(vl.plugin, RDT_PLUGIN, sizeof(vl.plugin));
124   ssnprintf(vl.plugin_instance, sizeof(vl.plugin_instance), "%s", cgroup);
125   sstrncpy(vl.type, type, sizeof(vl.type));
126   if (type_instance)
127     sstrncpy(vl.type_instance, type_instance, sizeof(vl.type_instance));
128
129   plugin_dispatch_values(&vl);
130 }
131
132 #if COLLECT_DEBUG
133 static void rdt_dump_cgroups(void) {
134   char cores[RDT_MAX_CORES * 4];
135
136   if (g_rdt == NULL)
137     return;
138
139   DEBUG(RDT_PLUGIN ": Core Groups Dump");
140   DEBUG(RDT_PLUGIN ":  groups count: %" PRIsz, g_rdt->cores.num_cgroups);
141
142   for (size_t i = 0; i < g_rdt->cores.num_cgroups; i++) {
143     core_group_t *cgroup = g_rdt->cores.cgroups + i;
144
145     memset(cores, 0, sizeof(cores));
146     for (size_t j = 0; j < cgroup->num_cores; j++) {
147       ssnprintf(cores + strlen(cores), sizeof(cores) - strlen(cores) - 1, " %d",
148                 cgroup->cores[j]);
149     }
150
151     DEBUG(RDT_PLUGIN ":  group[%zu]:", i);
152     DEBUG(RDT_PLUGIN ":    description: %s", cgroup->desc);
153     DEBUG(RDT_PLUGIN ":    cores: %s", cores);
154     DEBUG(RDT_PLUGIN ":    events: 0x%X", g_rdt->events[i]);
155   }
156
157   return;
158 }
159
160 #ifdef LIBPQOS2
161 static void rdt_dump_ngroups(void) {
162
163   char names[DATA_MAX_NAME_LEN];
164
165   if (g_rdt == NULL)
166     return;
167
168   DEBUG(RDT_PLUGIN ": Process Names Groups Dump");
169   DEBUG(RDT_PLUGIN ":  groups count: %" PRIsz, g_rdt->num_ngroups);
170
171   for (size_t i = 0; i < g_rdt->num_ngroups; i++) {
172     memset(names, 0, sizeof(names));
173     for (size_t j = 0; j < g_rdt->ngroups[i].num_names; j++)
174       ssnprintf(names + strlen(names), sizeof(names) - strlen(names) - 1, " %s",
175                 g_rdt->ngroups[i].names[j]);
176
177     DEBUG(RDT_PLUGIN ":  group[%d]:", (int)i);
178     DEBUG(RDT_PLUGIN ":    description: %s", g_rdt->ngroups[i].desc);
179     DEBUG(RDT_PLUGIN ":    process names:%s", names);
180     DEBUG(RDT_PLUGIN ":    events: 0x%X", g_rdt->ngroups[i].events);
181   }
182
183   return;
184 }
185 #endif /* LIBPQOS2 */
186
187 static inline double bytes_to_kb(const double bytes) { return bytes / 1024.0; }
188
189 static inline double bytes_to_mb(const double bytes) {
190   return bytes / (1024.0 * 1024.0);
191 }
192
193 static void rdt_dump_cores_data(void) {
194 /*
195  * CORE - monitored group of cores
196  * RMID - Resource Monitoring ID associated with the monitored group
197  *        This is not available for monitoring with resource control
198  * LLC - last level cache occupancy
199  * MBL - local memory bandwidth
200  * MBR - remote memory bandwidth
201  */
202 #ifdef LIBPQOS2
203   if (g_interface == PQOS_INTER_OS_RESCTRL_MON) {
204     DEBUG(RDT_PLUGIN ":  CORE     LLC[KB]   MBL[MB]    MBR[MB]");
205   } else {
206     DEBUG(RDT_PLUGIN ":  CORE     RMID    LLC[KB]   MBL[MB]    MBR[MB]");
207   }
208 #else
209   DEBUG(RDT_PLUGIN ":  CORE     RMID    LLC[KB]   MBL[MB]    MBR[MB]");
210 #endif /* LIBPQOS2 */
211
212   for (int i = 0; i < g_rdt->cores.num_cgroups; i++) {
213     const struct pqos_event_values *pv = &g_rdt->pcgroups[i]->values;
214
215     double llc = bytes_to_kb(pv->llc);
216     double mbr = bytes_to_mb(pv->mbm_remote_delta);
217     double mbl = bytes_to_mb(pv->mbm_local_delta);
218 #ifdef LIBPQOS2
219     if (g_interface == PQOS_INTER_OS_RESCTRL_MON) {
220       DEBUG(RDT_PLUGIN ": [%s] %10.1f %10.1f %10.1f",
221             g_rdt->cores.cgroups[i].desc, llc, mbl, mbr);
222     } else {
223       DEBUG(RDT_PLUGIN ": [%s] %8u %10.1f %10.1f %10.1f",
224             g_rdt->cores.cgroups[i].desc, g_rdt->pcgroups[i]->poll_ctx[0].rmid,
225             llc, mbl, mbr);
226     }
227 #else
228     DEBUG(RDT_PLUGIN ": [%s] %8u %10.1f %10.1f %10.1f",
229           g_rdt->cores.cgroups[i].desc, g_rdt->pcgroups[i]->poll_ctx[0].rmid,
230           llc, mbl, mbr);
231 #endif /* LIBPQOS2 */
232   }
233 }
234
235 #ifdef LIBPQOS2
236 static void rdt_dump_pids_data(void) {
237   /*
238    * NAME - monitored group of processes
239    * PIDs - list of PID numbers in the NAME group
240    * LLC - last level cache occupancy
241    * MBL - local memory bandwidth
242    * MBR - remote memory bandwidth
243    */
244
245   DEBUG(RDT_PLUGIN ":  NAME     PIDs");
246   char pids[DATA_MAX_NAME_LEN];
247   for (size_t i = 0; i < g_rdt->num_ngroups; ++i) {
248     memset(pids, 0, sizeof(pids));
249     for (size_t j = 0; j < g_rdt->ngroups[i].num_names; ++j) {
250       pids_list_t *list = g_rdt->ngroups[i].proc_pids[j]->curr;
251       for (size_t k = 0; k < list->size; k++)
252         ssnprintf(pids + strlen(pids), sizeof(pids) - strlen(pids) - 1, " %u",
253                   list->pids[k]);
254     }
255     DEBUG(RDT_PLUGIN ":  [%s] %s", g_rdt->ngroups[i].desc, pids);
256   }
257
258   DEBUG(RDT_PLUGIN ":  NAME    LLC[KB]   MBL[MB]    MBR[MB]");
259   for (size_t i = 0; i < g_rdt->num_ngroups; i++) {
260
261     const struct pqos_event_values *pv = &g_rdt->pngroups[i]->values;
262
263     double llc = bytes_to_kb(pv->llc);
264     double mbr = bytes_to_mb(pv->mbm_remote_delta);
265     double mbl = bytes_to_mb(pv->mbm_local_delta);
266
267     DEBUG(RDT_PLUGIN ":  [%s] %10.1f %10.1f %10.1f", g_rdt->ngroups[i].desc,
268           llc, mbl, mbr);
269   }
270 }
271 #endif /* LIBPQOS2 */
272 #endif /* COLLECT_DEBUG */
273
274 #ifdef LIBPQOS2
275 static int isdupstr(const char *names[], const size_t size, const char *name) {
276   for (size_t i = 0; i < size; i++)
277     if (strncmp(names[i], name, (size_t)MAX_PROC_NAME_LEN) == 0)
278       return 1;
279
280   return 0;
281 }
282
283 /*
284  * NAME
285  *   strlisttoarray
286  *
287  * DESCRIPTION
288  *   Converts string representing list of strings into array of strings.
289  *   Allowed format is:
290  *     name,name1,name2,name3
291  *
292  * PARAMETERS
293  *   `str_list'  String representing list of strings.
294  *   `names'     Array to put extracted strings into.
295  *   `names_num' Variable to put number of extracted strings.
296  *
297  * RETURN VALUE
298  *    Number of elements placed into names.
299  */
300 static int strlisttoarray(char *str_list, char ***names, size_t *names_num) {
301   char *saveptr = NULL;
302
303   if (str_list == NULL || names == NULL)
304     return -EINVAL;
305
306   if (strstr(str_list, ",,")) {
307     /* strtok ignores empty words between separators.
308      * This condition handles that by rejecting strings
309      * with consecutive seprators */
310     ERROR(RDT_PLUGIN ": Empty process name");
311     return -EINVAL;
312   }
313
314   for (;;) {
315     char *token = strtok_r(str_list, ",", &saveptr);
316     if (token == NULL)
317       break;
318
319     str_list = NULL;
320
321     while (isspace(*token))
322       token++;
323
324     if (*token == '\0')
325       continue;
326
327     if ((isdupstr((const char **)*names, *names_num, token))) {
328       ERROR(RDT_PLUGIN ": Duplicated process name \'%s\' in group \'%s\'",
329             token, str_list);
330       return -EINVAL;
331     } else {
332       if (0 != strarray_add(names, names_num, token)) {
333         ERROR(RDT_PLUGIN ": Error allocating process name string");
334         return -ENOMEM;
335       }
336     }
337   }
338
339   return 0;
340 }
341
342 /*
343  * NAME
344  *   ngroup_cmp
345  *
346  * DESCRIPTION
347  *   Function to compare names in two name groups.
348  *
349  * PARAMETERS
350  *   `ng_a'      Pointer to name group a.
351  *   `ng_b'      Pointer to name group b.
352  *
353  * RETURN VALUE
354  *    1 if both groups contain the same names
355  *    0 if none of their names match
356  *    -1 if some but not all names match
357  */
358 static int ngroup_cmp(const rdt_name_group_t *ng_a,
359                       const rdt_name_group_t *ng_b) {
360   unsigned found = 0;
361
362   assert(ng_a != NULL);
363   assert(ng_b != NULL);
364
365   const size_t sz_a = (unsigned)ng_a->num_names;
366   const size_t sz_b = (unsigned)ng_b->num_names;
367   const char **tab_a = (const char **)ng_a->names;
368   const char **tab_b = (const char **)ng_b->names;
369
370   for (size_t i = 0; i < sz_a; i++) {
371     for (size_t j = 0; j < sz_b; j++)
372       if (strncmp(tab_a[i], tab_b[j], (size_t)MAX_PROC_NAME_LEN) == 0)
373         found++;
374   }
375   /* if no names are the same */
376   if (!found)
377     return 0;
378   /* if group contains same names */
379   if (sz_a == sz_b && sz_b == (size_t)found)
380     return 1;
381   /* if not all names are the same */
382   return -1;
383 }
384
385 /*
386  * NAME
387  *   oconfig_to_ngroups
388  *
389  * DESCRIPTION
390  *   Function to set the descriptions and names for each process names group.
391  *   Takes a config option containing list of strings that are used to set
392  *   process group values.
393  *
394  * PARAMETERS
395  *   `item'        Config option containing process names groups.
396  *   `groups'      Table of process name groups to set values in.
397  *   `max_groups'  Maximum number of process name groups allowed.
398  *
399  * RETURN VALUE
400  *   On success, the number of name groups set up. On error, appropriate
401  *   negative error value.
402  */
403 static int oconfig_to_ngroups(const oconfig_item_t *item,
404                               rdt_name_group_t *groups,
405                               const size_t max_groups) {
406   int index = 0;
407
408   assert(groups != NULL);
409   assert(max_groups > 0);
410   assert(item != NULL);
411
412   for (int j = 0; j < item->values_num; j++) {
413     int ret;
414     char value[DATA_MAX_NAME_LEN];
415
416     if ((item->values[j].value.string == NULL) ||
417         (strlen(item->values[j].value.string) == 0)) {
418       ERROR(RDT_PLUGIN ": Error - empty group");
419       return -EINVAL;
420     }
421
422     sstrncpy(value, item->values[j].value.string, sizeof(value));
423
424     ret = strlisttoarray(value, &groups[index].names, &groups[index].num_names);
425     if (ret != 0 || groups[index].num_names == 0) {
426       ERROR(RDT_PLUGIN ": Error parsing process names group (%s)",
427             item->values[j].value.string);
428       return -EINVAL;
429     }
430
431     /* set group description info */
432     groups[index].desc = sstrdup(item->values[j].value.string);
433     if (groups[index].desc == NULL) {
434       ERROR(RDT_PLUGIN ": Error allocating name group description");
435       return -ENOMEM;
436     }
437
438     groups[index].proc_pids = NULL;
439     groups[index].monitored_pids_count = 0;
440
441     index++;
442
443     if (index >= (const int)max_groups) {
444       WARNING(RDT_PLUGIN ": Too many process names groups configured");
445       return index;
446     }
447   }
448
449   return index;
450 }
451
452 /*
453  * NAME
454  *   rdt_free_ngroups
455  *
456  * DESCRIPTION
457  *   Function to deallocate memory allocated for name groups.
458  *
459  * PARAMETERS
460  *   `rdt'       Pointer to rdt context
461  */
462 static void rdt_free_ngroups(rdt_ctx_t *rdt) {
463   for (int i = 0; i < RDT_MAX_NAMES_GROUPS; i++) {
464     if (rdt->ngroups[i].desc)
465       DEBUG(RDT_PLUGIN ": Freeing pids \'%s\' group\'s data...",
466             rdt->ngroups[i].desc);
467     sfree(rdt->ngroups[i].desc);
468     strarray_free(rdt->ngroups[i].names, rdt->ngroups[i].num_names);
469
470     if (rdt->ngroups[i].proc_pids)
471       proc_pids_free(rdt->ngroups[i].proc_pids, rdt->ngroups[i].num_names);
472
473     rdt->ngroups[i].num_names = 0;
474     sfree(rdt->pngroups[i]);
475   }
476   if (rdt->proc_pids)
477     sfree(rdt->proc_pids);
478
479   rdt->num_ngroups = 0;
480 }
481
482 /*
483  * NAME
484  *   rdt_config_ngroups
485  *
486  * DESCRIPTION
487  *   Reads name groups configuration.
488  *
489  * PARAMETERS
490  *   `rdt`       Pointer to rdt context
491  *   `item'      Config option containing process names groups.
492  *
493  * RETURN VALUE
494  *  0 on success. Negative number on error.
495  */
496 static int rdt_config_ngroups(rdt_ctx_t *rdt, const oconfig_item_t *item) {
497   int n = 0;
498   enum pqos_mon_event events = 0;
499
500   if (item == NULL) {
501     DEBUG(RDT_PLUGIN ": ngroups_config: Invalid argument.");
502     return -EINVAL;
503   }
504
505   DEBUG(RDT_PLUGIN ": Process names groups [%d]:", item->values_num);
506   for (int j = 0; j < item->values_num; j++) {
507     if (item->values[j].type != OCONFIG_TYPE_STRING) {
508       ERROR(RDT_PLUGIN
509             ": given process names group value is not a string [idx=%d]",
510             j);
511       return -EINVAL;
512     }
513     DEBUG(RDT_PLUGIN ":  [%d]: %s", j, item->values[j].value.string);
514   }
515
516   n = oconfig_to_ngroups(item, rdt->ngroups, RDT_MAX_NAMES_GROUPS);
517   if (n < 0) {
518     rdt_free_ngroups(rdt);
519     ERROR(RDT_PLUGIN ": Error parsing process name groups configuration.");
520     return -EINVAL;
521   }
522
523   /* validate configured process name values */
524   for (int group_idx = 0; group_idx < n; group_idx++) {
525     DEBUG(RDT_PLUGIN ":  checking group [%d]: %s", group_idx,
526           rdt->ngroups[group_idx].desc);
527     for (size_t name_idx = 0; name_idx < rdt->ngroups[group_idx].num_names;
528          name_idx++) {
529       DEBUG(RDT_PLUGIN ":    checking process name [%zu]: %s", name_idx,
530             rdt->ngroups[group_idx].names[name_idx]);
531       if (!proc_pids_is_name_valid(rdt->ngroups[group_idx].names[name_idx])) {
532         ERROR(RDT_PLUGIN ": Process name group '%s' contains invalid name '%s'",
533               rdt->ngroups[group_idx].desc,
534               rdt->ngroups[group_idx].names[name_idx]);
535         rdt_free_ngroups(rdt);
536         return -EINVAL;
537       }
538     }
539   }
540
541   if (n == 0) {
542     ERROR(RDT_PLUGIN ": Empty process name groups configured.");
543     return -EINVAL;
544   }
545
546   /* Get all available events on this platform */
547   for (unsigned i = 0; i < rdt->cap_mon->u.mon->num_events; i++)
548     events |= rdt->cap_mon->u.mon->events[i].type;
549
550   events &= ~(PQOS_PERF_EVENT_LLC_MISS);
551
552   DEBUG(RDT_PLUGIN ": Available events to monitor: %#x", events);
553
554   rdt->num_ngroups = n;
555   for (int i = 0; i < n; i++) {
556     for (int j = 0; j < i; j++) {
557       int found = ngroup_cmp(&rdt->ngroups[j], &rdt->ngroups[i]);
558       if (found != 0) {
559         rdt_free_ngroups(rdt);
560         ERROR(RDT_PLUGIN
561               ": Cannot monitor same process name in different groups.");
562         return -EINVAL;
563       }
564     }
565
566     rdt->ngroups[i].events = events;
567     rdt->pngroups[i] = calloc(1, sizeof(*rdt->pngroups[i]));
568     if (rdt->pngroups[i] == NULL) {
569       rdt_free_ngroups(rdt);
570       ERROR(RDT_PLUGIN
571             ": Failed to allocate memory for process name monitoring data.");
572       return -ENOMEM;
573     }
574   }
575
576   return 0;
577 }
578
579 /*
580  * NAME
581  *   rdt_refresh_ngroup
582  *
583  * DESCRIPTION
584  *   Refresh pids monitored by name group.
585  *
586  * PARAMETERS
587  *   `ngroup`         Pointer to name group.
588  *   `group_mon_data' PQoS monitoring context.
589  *
590  * RETURN VALUE
591  *  0 on success. Negative number on error.
592  */
593 static int rdt_refresh_ngroup(rdt_name_group_t *ngroup,
594                               struct pqos_mon_data *group_mon_data) {
595
596   int result = 0;
597
598   if (NULL == ngroup)
599     return -1;
600
601   if (NULL == ngroup->proc_pids) {
602     ERROR(RDT_PLUGIN
603           ": rdt_refresh_ngroup: \'%s\' uninitialized process pids array.",
604           ngroup->desc);
605
606     return -1;
607   }
608
609   DEBUG(RDT_PLUGIN ": rdt_refresh_ngroup: \'%s\' process names group.",
610         ngroup->desc);
611
612   proc_pids_t **proc_pids = ngroup->proc_pids;
613   pids_list_t added_pids;
614   pids_list_t removed_pids;
615
616   memset(&added_pids, 0, sizeof(added_pids));
617   memset(&removed_pids, 0, sizeof(removed_pids));
618
619   for (size_t i = 0; i < ngroup->num_names; ++i) {
620     int diff_result = pids_list_diff(proc_pids[i], &added_pids, &removed_pids);
621     if (0 != diff_result) {
622       ERROR(RDT_PLUGIN
623             ": rdt_refresh_ngroup: \'%s\'. Error [%d] during PID diff.",
624             ngroup->desc, diff_result);
625       result = -1;
626       goto cleanup;
627     }
628   }
629
630   DEBUG(RDT_PLUGIN ": rdt_refresh_ngroup: \'%s\' process names group, added: "
631                    "%u, removed: %u.",
632         ngroup->desc, (unsigned)added_pids.size, (unsigned)removed_pids.size);
633
634   if (added_pids.size > 0) {
635
636     /* no pids are monitored for this group yet: start monitoring */
637     if (0 == ngroup->monitored_pids_count) {
638
639       int start_result =
640           pqos_mon_start_pids(added_pids.size, added_pids.pids, ngroup->events,
641                               (void *)ngroup->desc, group_mon_data);
642       if (PQOS_RETVAL_OK == start_result) {
643         ngroup->monitored_pids_count = added_pids.size;
644       } else {
645         ERROR(RDT_PLUGIN ": rdt_refresh_ngroup: \'%s\'. Error [%d] while "
646                          "STARTING pids monitoring",
647               ngroup->desc, start_result);
648         result = -1;
649         goto pqos_error_recovery;
650       }
651
652     } else {
653
654       int add_result =
655           pqos_mon_add_pids(added_pids.size, added_pids.pids, group_mon_data);
656       if (PQOS_RETVAL_OK == add_result)
657         ngroup->monitored_pids_count += added_pids.size;
658       else {
659         ERROR(RDT_PLUGIN
660               ": rdt_refresh_ngroup: \'%s\'. Error [%d] while ADDING pids.",
661               ngroup->desc, add_result);
662         result = -1;
663         goto pqos_error_recovery;
664       }
665     }
666   }
667
668   if (removed_pids.size > 0) {
669
670     /* all pids are removed: stop monitoring */
671     if (removed_pids.size == ngroup->monitored_pids_count) {
672       /* all pids for this group are lost: stop monitoring */
673       int stop_result = pqos_mon_stop(group_mon_data);
674       if (PQOS_RETVAL_OK != stop_result) {
675         ERROR(RDT_PLUGIN ": rdt_refresh_ngroup: \'%s\'. Error [%d] while "
676                          "STOPPING monitoring",
677               ngroup->desc, stop_result);
678         result = -1;
679         goto pqos_error_recovery;
680       }
681       ngroup->monitored_pids_count = 0;
682     } else {
683       int remove_result = pqos_mon_remove_pids(
684           removed_pids.size, removed_pids.pids, group_mon_data);
685       if (PQOS_RETVAL_OK == remove_result) {
686         ngroup->monitored_pids_count -= removed_pids.size;
687       } else {
688         ERROR(RDT_PLUGIN
689               ": rdt_refresh_ngroup: \'%s\'. Error [%d] while REMOVING pids.",
690               ngroup->desc, remove_result);
691         result = -1;
692         goto pqos_error_recovery;
693       }
694     }
695   }
696
697   goto cleanup;
698
699 pqos_error_recovery:
700   /* Why?
701    * Resources might be temporary unavailable.
702    *
703    * How?
704    * Collectd will halt the reading thread for this
705    * plugin if it returns an error.
706    * Consecutive errors will be increasing the read period
707    * up to 1 day interval.
708    * On pqos error stop monitoring current group
709    * and reset the proc_pids array
710    * monitoring will be restarted on next collectd read cycle
711    */
712   DEBUG(RDT_PLUGIN ": rdt_refresh_ngroup: \'%s\' group RESET after error.",
713         ngroup->desc);
714   pqos_mon_stop(group_mon_data);
715   for (size_t i = 0; i < ngroup->num_names; ++i)
716     if (ngroup->proc_pids[i]->curr)
717       ngroup->proc_pids[i]->curr->size = 0;
718
719   ngroup->monitored_pids_count = 0;
720
721 cleanup:
722   pids_list_clear(&added_pids);
723   pids_list_clear(&removed_pids);
724
725   return result;
726 }
727
728 /*
729  * NAME
730  *   read_pids_data
731  *
732  * DESCRIPTION
733  *   Poll monitoring statistics for name groups
734  *
735  * RETURN VALUE
736  *  0 on success. Negative number on error.
737  */
738 static int read_pids_data() {
739
740   if (0 == g_rdt->num_ngroups) {
741     DEBUG(RDT_PLUGIN ": read_pids_data: not configured - PIDs read skipped");
742     return 0;
743   }
744
745   DEBUG(RDT_PLUGIN ": read_pids_data: Scanning active groups");
746   struct pqos_mon_data *active_groups[RDT_MAX_NAMES_GROUPS] = {0};
747   size_t active_group_idx = 0;
748   for (size_t pngroups_idx = 0;
749        pngroups_idx < STATIC_ARRAY_SIZE(g_rdt->pngroups); ++pngroups_idx)
750     if (0 != g_rdt->ngroups[pngroups_idx].monitored_pids_count)
751       active_groups[active_group_idx++] = g_rdt->pngroups[pngroups_idx];
752
753   int ret = 0;
754
755   if (0 == active_group_idx) {
756     DEBUG(RDT_PLUGIN ": read_pids_data: no active groups - PIDs read skipped");
757     goto groups_refresh;
758   }
759
760   DEBUG(RDT_PLUGIN ": read_pids_data: PIDs data polling");
761
762   int poll_result = pqos_mon_poll(active_groups, active_group_idx);
763   if (poll_result != PQOS_RETVAL_OK) {
764     ERROR(RDT_PLUGIN ": read_pids_data: Failed to poll monitoring data for "
765                      "pids. Error [%d].",
766           poll_result);
767     ret = -poll_result;
768     goto groups_refresh;
769   }
770
771   for (size_t i = 0; i < g_rdt->num_ngroups; i++) {
772     enum pqos_mon_event mbm_events =
773         (PQOS_MON_EVENT_LMEM_BW | PQOS_MON_EVENT_TMEM_BW |
774          PQOS_MON_EVENT_RMEM_BW);
775
776     if (g_rdt->pngroups[i] == NULL ||
777         g_rdt->ngroups[i].monitored_pids_count == 0)
778       continue;
779
780     const struct pqos_event_values *pv = &g_rdt->pngroups[i]->values;
781
782     /* Submit only monitored events data */
783
784     if (g_rdt->ngroups[i].events & PQOS_MON_EVENT_L3_OCCUP)
785       rdt_submit_gauge(g_rdt->ngroups[i].desc, "bytes", "llc", pv->llc);
786
787     if (g_rdt->ngroups[i].events & PQOS_PERF_EVENT_IPC)
788       rdt_submit_gauge(g_rdt->ngroups[i].desc, "ipc", NULL, pv->ipc);
789
790     if (g_rdt->ngroups[i].events & mbm_events) {
791       rdt_submit_derive(g_rdt->ngroups[i].desc, "memory_bandwidth", "local",
792                         pv->mbm_local_delta);
793       rdt_submit_derive(g_rdt->ngroups[i].desc, "memory_bandwidth", "remote",
794                         pv->mbm_remote_delta);
795     }
796   }
797
798 #if COLLECT_DEBUG
799   rdt_dump_pids_data();
800 #endif /* COLLECT_DEBUG */
801
802 groups_refresh:
803   ret = proc_pids_update(RDT_PROC_PATH, g_rdt->proc_pids, g_rdt->num_proc_pids);
804   if (0 != ret) {
805     ERROR(RDT_PLUGIN ": Initial update of proc pids failed");
806     return ret;
807   }
808
809   for (size_t i = 0; i < g_rdt->num_ngroups; i++) {
810     int refresh_result =
811         rdt_refresh_ngroup(&(g_rdt->ngroups[i]), g_rdt->pngroups[i]);
812
813     if (0 != refresh_result) {
814       ERROR(RDT_PLUGIN ": read_pids_data: NGroup %zu refresh failed. Error: %d",
815             i, refresh_result);
816       if (0 == ret) {
817         /* refresh error will be escalated only if there were no
818          * errors before.
819          */
820         ret = refresh_result;
821       }
822     }
823   }
824
825   assert(ret <= 0);
826   return ret;
827 }
828
829 /*
830  * NAME
831  *   rdt_init_pids_monitoring
832  *
833  * DESCRIPTION
834  *   Initialize pids monitoring for all name groups
835  */
836 static void rdt_init_pids_monitoring() {
837   for (size_t group_idx = 0; group_idx < g_rdt->num_ngroups; group_idx++) {
838     /*
839      * Each group must have not-null proc_pids array.
840      * Initial refresh is not mandatory for proper
841      * PIDs statistics detection.
842      */
843     rdt_name_group_t *ng = &g_rdt->ngroups[group_idx];
844     int init_result =
845         proc_pids_init((const char **)ng->names, ng->num_names, &ng->proc_pids);
846     if (0 != init_result) {
847       ERROR(RDT_PLUGIN
848             ": Initialization of proc_pids for group %zu failed. Error: %d",
849             group_idx, init_result);
850       continue;
851     }
852
853     /* update global proc_pids table */
854     proc_pids_t **proc_pids =
855         realloc(g_rdt->proc_pids, (g_rdt->num_proc_pids + ng->num_names) *
856                                       sizeof(*g_rdt->proc_pids));
857     if (NULL == proc_pids) {
858       ERROR(RDT_PLUGIN ": Alloc error\n");
859       continue;
860     }
861
862     for (size_t i = 0; i < ng->num_names; i++)
863       proc_pids[g_rdt->num_proc_pids + i] = ng->proc_pids[i];
864
865     g_rdt->proc_pids = proc_pids;
866     g_rdt->num_proc_pids += ng->num_names;
867   }
868
869   if (g_rdt->num_ngroups > 0) {
870     int update_result =
871         proc_pids_update(RDT_PROC_PATH, g_rdt->proc_pids, g_rdt->num_proc_pids);
872     if (0 != update_result)
873       ERROR(RDT_PLUGIN ": Initial update of proc pids failed");
874   }
875
876   for (size_t group_idx = 0; group_idx < g_rdt->num_ngroups; group_idx++) {
877     int refresh_result = rdt_refresh_ngroup(&(g_rdt->ngroups[group_idx]),
878                                             g_rdt->pngroups[group_idx]);
879     if (0 != refresh_result)
880       ERROR(RDT_PLUGIN ": Initial refresh of group %zu failed. Error: %d",
881             group_idx, refresh_result);
882   }
883 }
884 #endif /* LIBPQOS2 */
885 /*
886  * NAME
887  *   rdt_free_cgroups
888  *
889  * DESCRIPTION
890  *   Function to deallocate memory allocated for core groups.
891  */
892 static void rdt_free_cgroups(void) {
893   config_cores_cleanup(&g_rdt->cores);
894   for (int i = 0; i < RDT_MAX_CORES; i++) {
895     sfree(g_rdt->pcgroups[i]);
896   }
897   g_rdt->cores.num_cgroups = 0;
898 }
899
900 static int rdt_default_cgroups(void) {
901   unsigned num_cores = g_rdt->pqos_cpu->num_cores;
902
903   g_rdt->cores.cgroups = calloc(num_cores, sizeof(*(g_rdt->cores.cgroups)));
904   if (g_rdt->cores.cgroups == NULL) {
905     ERROR(RDT_PLUGIN ": Error allocating core groups array");
906     return -ENOMEM;
907   }
908   g_rdt->cores.num_cgroups = num_cores;
909
910   /* configure each core in separate group */
911   for (unsigned i = 0; i < num_cores; i++) {
912     core_group_t *cgroup = g_rdt->cores.cgroups + i;
913     char desc[DATA_MAX_NAME_LEN];
914
915     /* set core group info */
916     cgroup->cores = calloc(1, sizeof(*cgroup->cores));
917     if (cgroup->cores == NULL) {
918       ERROR(RDT_PLUGIN ": Error allocating cores array");
919       rdt_free_cgroups();
920       return -ENOMEM;
921     }
922     cgroup->num_cores = 1;
923     cgroup->cores[0] = i;
924
925     ssnprintf(desc, sizeof(desc), "%d", g_rdt->pqos_cpu->cores[i].lcore);
926     cgroup->desc = strdup(desc);
927     if (cgroup->desc == NULL) {
928       ERROR(RDT_PLUGIN ": Error allocating core group description");
929       rdt_free_cgroups();
930       return -ENOMEM;
931     }
932   }
933
934   return num_cores;
935 }
936
937 static int rdt_is_core_id_valid(unsigned int core_id) {
938
939   for (unsigned int i = 0; i < g_rdt->pqos_cpu->num_cores; i++)
940     if (core_id == g_rdt->pqos_cpu->cores[i].lcore)
941       return 1;
942
943   return 0;
944 }
945
946 static int rdt_config_cgroups(oconfig_item_t *item) {
947   size_t n = 0;
948   enum pqos_mon_event events = 0;
949
950   if (config_cores_parse(item, &g_rdt->cores) < 0) {
951     rdt_free_cgroups();
952     ERROR(RDT_PLUGIN ": Error parsing core groups configuration.");
953     return -EINVAL;
954   }
955   n = g_rdt->cores.num_cgroups;
956
957   /* validate configured core id values */
958   for (size_t group_idx = 0; group_idx < n; group_idx++) {
959     core_group_t *cgroup = g_rdt->cores.cgroups + group_idx;
960     for (size_t core_idx = 0; core_idx < cgroup->num_cores; core_idx++) {
961       if (!rdt_is_core_id_valid(cgroup->cores[core_idx])) {
962         ERROR(RDT_PLUGIN ": Core group '%s' contains invalid core id '%u'",
963               cgroup->desc, cgroup->cores[core_idx]);
964         rdt_free_cgroups();
965         return -EINVAL;
966       }
967     }
968   }
969
970   if (n == 0) {
971     /* create default core groups if "Cores" config option is empty */
972     int ret = rdt_default_cgroups();
973     if (ret < 0) {
974       rdt_free_cgroups();
975       ERROR(RDT_PLUGIN ": Error creating default core groups configuration.");
976       return ret;
977     }
978     n = (size_t)ret;
979     INFO(RDT_PLUGIN
980          ": No core groups configured. Default core groups created.");
981   }
982
983   /* Get all available events on this platform */
984   for (unsigned int i = 0; i < g_rdt->cap_mon->u.mon->num_events; i++)
985     events |= g_rdt->cap_mon->u.mon->events[i].type;
986
987   events &= ~(PQOS_PERF_EVENT_LLC_MISS);
988
989   DEBUG(RDT_PLUGIN ": Number of cores in the system: %u",
990         g_rdt->pqos_cpu->num_cores);
991   DEBUG(RDT_PLUGIN ": Available events to monitor: %#x", events);
992
993   g_rdt->cores.num_cgroups = n;
994   for (int i = 0; i < n; i++) {
995     for (int j = 0; j < i; j++) {
996       int found = 0;
997       found = config_cores_cmp_cgroups(&g_rdt->cores.cgroups[j],
998                                        &g_rdt->cores.cgroups[i]);
999       if (found != 0) {
1000         rdt_free_cgroups();
1001         ERROR(RDT_PLUGIN ": Cannot monitor same cores in different groups.");
1002         return -EINVAL;
1003       }
1004     }
1005
1006     g_rdt->events[i] = events;
1007     g_rdt->pcgroups[i] = calloc(1, sizeof(*g_rdt->pcgroups[i]));
1008     if (g_rdt->pcgroups[i] == NULL) {
1009       rdt_free_cgroups();
1010       ERROR(RDT_PLUGIN ": Failed to allocate memory for monitoring data.");
1011       return -ENOMEM;
1012     }
1013   }
1014
1015   return 0;
1016 }
1017
1018 static void rdt_pqos_log(void *context, const size_t size, const char *msg) {
1019   DEBUG(RDT_PLUGIN ": %s", msg);
1020 }
1021
1022 static int rdt_preinit(void) {
1023   int ret;
1024
1025   if (g_rdt != NULL) {
1026     /* already initialized if config callback was called before init callback */
1027     return 0;
1028   }
1029
1030   g_rdt = calloc(1, sizeof(*g_rdt));
1031   if (g_rdt == NULL) {
1032     ERROR(RDT_PLUGIN ": Failed to allocate memory for rdt context.");
1033     return -ENOMEM;
1034   }
1035
1036   struct pqos_config pqos = {.fd_log = -1,
1037                              .callback_log = rdt_pqos_log,
1038                              .context_log = NULL,
1039                              .verbose = 0,
1040 #ifdef LIBPQOS2
1041                              .interface = PQOS_INTER_OS_RESCTRL_MON};
1042   DEBUG(RDT_PLUGIN ": Initializing PQoS with RESCTRL interface");
1043 #else
1044                              .interface = PQOS_INTER_MSR};
1045   DEBUG(RDT_PLUGIN ": Initializing PQoS with MSR interface");
1046 #endif
1047
1048   ret = pqos_init(&pqos);
1049   DEBUG(RDT_PLUGIN ": PQoS initialization result: [%d]", ret);
1050
1051 #ifdef LIBPQOS2
1052   if (ret == PQOS_RETVAL_INTER) {
1053     pqos.interface = PQOS_INTER_MSR;
1054     DEBUG(RDT_PLUGIN ": Initializing PQoS with MSR interface");
1055     ret = pqos_init(&pqos);
1056     DEBUG(RDT_PLUGIN ": PQoS initialization result: [%d]", ret);
1057   }
1058 #endif
1059
1060   if (ret != PQOS_RETVAL_OK) {
1061     ERROR(RDT_PLUGIN ": Error initializing PQoS library!");
1062     goto rdt_preinit_error1;
1063   }
1064
1065   g_interface = pqos.interface;
1066
1067   ret = pqos_cap_get(&g_rdt->pqos_cap, &g_rdt->pqos_cpu);
1068   if (ret != PQOS_RETVAL_OK) {
1069     ERROR(RDT_PLUGIN ": Error retrieving PQoS capabilities.");
1070     goto rdt_preinit_error2;
1071   }
1072
1073   ret = pqos_cap_get_type(g_rdt->pqos_cap, PQOS_CAP_TYPE_MON, &g_rdt->cap_mon);
1074   if (ret == PQOS_RETVAL_PARAM) {
1075     ERROR(RDT_PLUGIN ": Error retrieving monitoring capabilities.");
1076     goto rdt_preinit_error2;
1077   }
1078
1079   if (g_rdt->cap_mon == NULL) {
1080     ERROR(
1081         RDT_PLUGIN
1082         ": Monitoring capability not detected. Nothing to do for the plugin.");
1083     goto rdt_preinit_error2;
1084   }
1085
1086   /* Reset pqos monitoring groups registers */
1087   pqos_mon_reset();
1088
1089   return 0;
1090
1091 rdt_preinit_error2:
1092   pqos_fini();
1093
1094 rdt_preinit_error1:
1095   sfree(g_rdt);
1096
1097   return -1;
1098 }
1099
1100 static int rdt_config(oconfig_item_t *ci) {
1101   if (rdt_preinit() != 0) {
1102     g_state = CONFIGURATION_ERROR;
1103     /* if we return -1 at this point collectd
1104       reports a failure in configuration and
1105       aborts
1106     */
1107     return 0;
1108   }
1109
1110   for (int i = 0; i < ci->children_num; i++) {
1111     oconfig_item_t *child = ci->children + i;
1112
1113     if (strncasecmp("Cores", child->key, (size_t)strlen("Cores")) == 0) {
1114       if (g_rdt->cores.num_cgroups > 0) {
1115         ERROR(RDT_PLUGIN
1116               ": Configuration parameter \"%s\" can be used only once.",
1117               child->key);
1118         g_state = CONFIGURATION_ERROR;
1119       } else if (rdt_config_cgroups(child) != 0)
1120         g_state = CONFIGURATION_ERROR;
1121
1122       if (g_state == CONFIGURATION_ERROR)
1123         /* if we return -1 at this point collectd
1124            reports a failure in configuration and
1125            aborts
1126          */
1127         return 0;
1128
1129 #if COLLECT_DEBUG
1130       rdt_dump_cgroups();
1131 #endif /* COLLECT_DEBUG */
1132     } else if (strncasecmp("Processes", child->key,
1133                            (size_t)strlen("Processes")) == 0) {
1134 #ifdef LIBPQOS2
1135       if (g_interface != PQOS_INTER_OS_RESCTRL_MON) {
1136         ERROR(RDT_PLUGIN ": Configuration parameter \"%s\" not supported. "
1137                          "Resctrl monitoring is needed for PIDs monitoring.",
1138               child->key);
1139         g_state = CONFIGURATION_ERROR;
1140       }
1141
1142       else if (g_rdt->num_ngroups > 0) {
1143         ERROR(RDT_PLUGIN
1144               ": Configuration parameter \"%s\" can be used only once.",
1145               child->key);
1146         g_state = CONFIGURATION_ERROR;
1147       }
1148
1149       else if (rdt_config_ngroups(g_rdt, child) != 0)
1150         g_state = CONFIGURATION_ERROR;
1151
1152       if (g_state == CONFIGURATION_ERROR)
1153         /* if we return -1 at this point collectd
1154            reports a failure in configuration and
1155            aborts
1156          */
1157         return 0;
1158
1159 #if COLLECT_DEBUG
1160       rdt_dump_ngroups();
1161 #endif /* COLLECT_DEBUG */
1162 #else  /* !LIBPQOS2 */
1163       ERROR(RDT_PLUGIN ": Configuration parameter \"%s\" not supported, please "
1164                        "recompile collectd with libpqos version 2.0 or newer.",
1165             child->key);
1166 #endif /* LIBPQOS2 */
1167     } else {
1168       ERROR(RDT_PLUGIN ": Unknown configuration parameter \"%s\".", child->key);
1169     }
1170   }
1171
1172   return 0;
1173 }
1174
1175 static int read_cores_data() {
1176
1177   if (0 == g_rdt->cores.num_cgroups) {
1178     DEBUG(RDT_PLUGIN ": read_cores_data: not configured - Cores read skipped");
1179     return 0;
1180   }
1181   DEBUG(RDT_PLUGIN ": read_cores_data: Cores data poll");
1182
1183   int ret =
1184       pqos_mon_poll(&g_rdt->pcgroups[0], (unsigned)g_rdt->cores.num_cgroups);
1185   if (ret != PQOS_RETVAL_OK) {
1186     ERROR(RDT_PLUGIN ": read_cores_data: Failed to poll monitoring data for "
1187                      "cores. Error [%d].",
1188           ret);
1189     return -1;
1190   }
1191
1192   for (size_t i = 0; i < g_rdt->cores.num_cgroups; i++) {
1193     core_group_t *cgroup = g_rdt->cores.cgroups + i;
1194     enum pqos_mon_event mbm_events =
1195         (PQOS_MON_EVENT_LMEM_BW | PQOS_MON_EVENT_TMEM_BW |
1196          PQOS_MON_EVENT_RMEM_BW);
1197
1198     const struct pqos_event_values *pv = &g_rdt->pcgroups[i]->values;
1199
1200     /* Submit only monitored events data */
1201
1202     if (g_rdt->events[i] & PQOS_MON_EVENT_L3_OCCUP)
1203       rdt_submit_gauge(cgroup->desc, "bytes", "llc", pv->llc);
1204
1205     if (g_rdt->events[i] & PQOS_PERF_EVENT_IPC)
1206       rdt_submit_gauge(cgroup->desc, "ipc", NULL, pv->ipc);
1207
1208     if (g_rdt->events[i] & mbm_events) {
1209       rdt_submit_derive(cgroup->desc, "memory_bandwidth", "local",
1210                         pv->mbm_local_delta);
1211       rdt_submit_derive(cgroup->desc, "memory_bandwidth", "remote",
1212                         pv->mbm_remote_delta);
1213     }
1214   }
1215
1216 #if COLLECT_DEBUG
1217   rdt_dump_cores_data();
1218 #endif /* COLLECT_DEBUG */
1219
1220   return 0;
1221 }
1222
1223 static int rdt_read(__attribute__((unused)) user_data_t *ud) {
1224
1225   if (g_rdt == NULL) {
1226     ERROR(RDT_PLUGIN ": rdt_read: plugin not initialized.");
1227     return -EINVAL;
1228   }
1229
1230   int cores_read_result = read_cores_data();
1231
1232 #ifdef LIBPQOS2
1233   int pids_read_result = read_pids_data();
1234 #endif /* LIBPQOS2 */
1235
1236   if (0 != cores_read_result)
1237     return cores_read_result;
1238
1239 #ifdef LIBPQOS2
1240   if (0 != pids_read_result)
1241     return pids_read_result;
1242 #endif /* LIBPQOS2 */
1243
1244   return 0;
1245 }
1246
1247 static void rdt_init_cores_monitoring() {
1248   for (size_t i = 0; i < g_rdt->cores.num_cgroups; i++) {
1249     core_group_t *cg = g_rdt->cores.cgroups + i;
1250
1251     int mon_start_result =
1252         pqos_mon_start(cg->num_cores, cg->cores, g_rdt->events[i],
1253                        (void *)cg->desc, g_rdt->pcgroups[i]);
1254
1255     if (mon_start_result != PQOS_RETVAL_OK)
1256       ERROR(RDT_PLUGIN
1257             ": Error starting cores monitoring group %s (pqos status=%d)",
1258             cg->desc, mon_start_result);
1259   }
1260 }
1261
1262 static int rdt_init(void) {
1263
1264   if (g_state == CONFIGURATION_ERROR) {
1265     if (g_rdt != NULL) {
1266       if (g_rdt->cores.num_cgroups > 0)
1267         rdt_free_cgroups();
1268 #ifdef LIBPQOS2
1269       if (g_rdt->num_ngroups > 0)
1270         rdt_free_ngroups(g_rdt);
1271 #endif
1272     }
1273     return -1;
1274   }
1275
1276   int rdt_preinint_result = rdt_preinit();
1277   if (rdt_preinint_result != 0)
1278     return rdt_preinint_result;
1279
1280   rdt_init_cores_monitoring();
1281 #ifdef LIBPQOS2
1282   rdt_init_pids_monitoring();
1283 #endif /* LIBPQOS2 */
1284
1285   return 0;
1286 }
1287
1288 static int rdt_shutdown(void) {
1289   int ret;
1290
1291   DEBUG(RDT_PLUGIN ": rdt_shutdown.");
1292
1293   if (g_rdt == NULL)
1294     return 0;
1295
1296   /* Stop monitoring cores */
1297   for (size_t i = 0; i < g_rdt->cores.num_cgroups; i++) {
1298     pqos_mon_stop(g_rdt->pcgroups[i]);
1299   }
1300
1301 /* Stop pids monitoring */
1302 #ifdef LIBPQOS2
1303   for (size_t i = 0; i < g_rdt->num_ngroups; i++)
1304     pqos_mon_stop(g_rdt->pngroups[i]);
1305 #endif
1306
1307   ret = pqos_fini();
1308   if (ret != PQOS_RETVAL_OK)
1309     ERROR(RDT_PLUGIN ": Error shutting down PQoS library.");
1310   rdt_free_cgroups();
1311 #ifdef LIBPQOS2
1312   rdt_free_ngroups(g_rdt);
1313 #endif /* LIBPQOS2 */
1314   sfree(g_rdt);
1315
1316   return 0;
1317 }
1318
1319 void module_register(void) {
1320   plugin_register_init(RDT_PLUGIN, rdt_init);
1321   plugin_register_complex_config(RDT_PLUGIN, rdt_config);
1322   plugin_register_complex_read(NULL, RDT_PLUGIN, rdt_read, 0, NULL);
1323   plugin_register_shutdown(RDT_PLUGIN, rdt_shutdown);
1324 }