intel-rdt: Changed memory allocation of new and lost pids tables from static to dynamic
[collectd.git] / src / intel_rdt.c
1 /**
2  * collectd - src/intel_rdt.c
3  *
4  * Copyright(c) 2016-2018 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  **/
29
30 #include "collectd.h"
31 #include "utils/common/common.h"
32 #include "utils/config_cores/config_cores.h"
33 #include <pqos.h>
34
35 #define RDT_PLUGIN "intel_rdt"
36
37 /* libpqos v2.0 or newer is required for process monitoring*/
38 #undef LIBPQOS2
39 #if defined(PQOS_VERSION) && PQOS_VERSION >= 20000
40 #define LIBPQOS2
41 #endif
42
43 #define RDT_PLUGIN "intel_rdt"
44
45 #define RDT_MAX_SOCKETS 8
46 #define RDT_MAX_SOCKET_CORES 64
47 #define RDT_MAX_CORES (RDT_MAX_SOCKET_CORES * RDT_MAX_SOCKETS)
48
49 #ifdef LIBPQOS2
50 /*
51  * Process name inside comm file is limited to 16 chars.
52  * More info here: http://man7.org/linux/man-pages/man5/proc.5.html
53  */
54 #define RDT_MAX_NAME_LEN 16
55 #define RDT_MAX_NAMES_GROUPS 64
56
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 /* Helper typedef for process name array
67  * Extra 1 char is added for string null termination.
68  */
69 typedef char proc_comm_t[RDT_MAX_NAME_LEN + 1];
70
71 /* Linked one-way list of pids. */
72 typedef struct pids_list_s {
73   pid_t pid;
74   struct pids_list_s *next;
75 } pids_list_t;
76
77 /* Holds process name and list of pids assigned to that name */
78 typedef struct proc_pids_s {
79   proc_comm_t proccess_name;
80   pids_list_t *pids;
81 } proc_pids_t;
82
83 struct rdt_name_group_s {
84   char *desc;
85   size_t num_names;
86   char **names;
87   proc_pids_t *proc_pids_array;
88   size_t monitored_pids_count;
89   enum pqos_mon_event events;
90 };
91 typedef struct rdt_name_group_s rdt_name_group_t;
92 #endif /* LIBPQOS2 */
93
94 struct rdt_ctx_s {
95   core_groups_list_t cores;
96   enum pqos_mon_event events[RDT_MAX_CORES];
97   struct pqos_mon_data *pcgroups[RDT_MAX_CORES];
98 #ifdef LIBPQOS2
99   rdt_name_group_t ngroups[RDT_MAX_NAMES_GROUPS];
100   struct pqos_mon_data *pngroups[RDT_MAX_NAMES_GROUPS];
101   size_t num_ngroups;
102 #endif /* LIBPQOS2 */
103   const struct pqos_cpuinfo *pqos_cpu;
104   const struct pqos_cap *pqos_cap;
105   const struct pqos_capability *cap_mon;
106 };
107 typedef struct rdt_ctx_s rdt_ctx_t;
108
109 static rdt_ctx_t *g_rdt;
110
111 static rdt_config_status g_state = UNKNOWN;
112
113 static int g_interface = -1;
114
115 #ifdef LIBPQOS2
116 static int isdupstr(const char *names[], const size_t size, const char *name) {
117   for (size_t i = 0; i < size; i++)
118     if (strncmp(names[i], name, (size_t)RDT_MAX_NAME_LEN) == 0)
119       return 1;
120
121   return 0;
122 }
123
124 /*
125  * NAME
126  *   strlisttoarray
127  *
128  * DESCRIPTION
129  *   Converts string representing list of strings into array of strings.
130  *   Allowed format is:
131  *     name,name1,name2,name3
132  *
133  * PARAMETERS
134  *   `str_list'  String representing list of strings.
135  *   `names'     Array to put extracted strings into.
136  *   `names_num' Variable to put number of extracted strings.
137  *
138  * RETURN VALUE
139  *    Number of elements placed into names.
140  */
141 static int strlisttoarray(char *str_list, char ***names, size_t *names_num) {
142   char *saveptr = NULL;
143
144   if (str_list == NULL || names == NULL)
145     return -EINVAL;
146
147   if (strstr(str_list, ",,")) {
148     /* strtok ignores empty words between separators.
149      * This condition handles that by rejecting strings
150      * with consecutive seprators */
151     ERROR(RDT_PLUGIN ": Empty process name");
152     return -EINVAL;
153   }
154
155   for (;;) {
156     char *token = strtok_r(str_list, ",", &saveptr);
157     if (token == NULL)
158       break;
159
160     str_list = NULL;
161
162     while (isspace(*token))
163       token++;
164
165     if (*token == '\0')
166       continue;
167
168     if ((isdupstr((const char **)*names, *names_num, token))) {
169       ERROR(RDT_PLUGIN ": Duplicated process name \'%s\' in group \'%s\'",
170             token, str_list);
171       return -EINVAL;
172     } else {
173       if (0 != strarray_add(names, names_num, token)) {
174         ERROR(RDT_PLUGIN ": Error allocating process name string");
175         return -ENOMEM;
176       }
177     }
178   }
179
180   return 0;
181 }
182
183 /*
184  * NAME
185  *   ngroup_cmp
186  *
187  * DESCRIPTION
188  *   Function to compare names in two name groups.
189  *
190  * PARAMETERS
191  *   `ng_a'      Pointer to name group a.
192  *   `ng_b'      Pointer to name group b.
193  *
194  * RETURN VALUE
195  *    1 if both groups contain the same names
196  *    0 if none of their names match
197  *    -1 if some but not all names match
198  */
199 static int ngroup_cmp(const rdt_name_group_t *ng_a,
200                       const rdt_name_group_t *ng_b) {
201   unsigned found = 0;
202
203   assert(ng_a != NULL);
204   assert(ng_b != NULL);
205
206   const size_t sz_a = (unsigned)ng_a->num_names;
207   const size_t sz_b = (unsigned)ng_b->num_names;
208   const char **tab_a = (const char **)ng_a->names;
209   const char **tab_b = (const char **)ng_b->names;
210
211   for (size_t i = 0; i < sz_a; i++) {
212     for (size_t j = 0; j < sz_b; j++)
213       if (strncmp(tab_a[i], tab_b[j], (size_t)RDT_MAX_NAME_LEN) == 0)
214         found++;
215   }
216   /* if no names are the same */
217   if (!found)
218     return 0;
219   /* if group contains same names */
220   if (sz_a == sz_b && sz_b == (size_t)found)
221     return 1;
222   /* if not all names are the same */
223   return -1;
224 }
225
226 /*
227  * NAME
228  *   oconfig_to_ngroups
229  *
230  * DESCRIPTION
231  *   Function to set the descriptions and names for each process names group.
232  *   Takes a config option containing list of strings that are used to set
233  *   process group values.
234  *
235  * PARAMETERS
236  *   `item'        Config option containing process names groups.
237  *   `groups'      Table of process name groups to set values in.
238  *   `max_groups'  Maximum number of process name groups allowed.
239  *
240  * RETURN VALUE
241  *   On success, the number of name groups set up. On error, appropriate
242  *   negative error value.
243  */
244 static int oconfig_to_ngroups(const oconfig_item_t *item,
245                               rdt_name_group_t *groups,
246                               const size_t max_groups) {
247   int index = 0;
248
249   assert(groups != NULL);
250   assert(max_groups > 0);
251   assert(item != NULL);
252
253   for (int j = 0; j < item->values_num; j++) {
254     int ret;
255     char value[DATA_MAX_NAME_LEN];
256
257     if ((item->values[j].value.string == NULL) ||
258         (strlen(item->values[j].value.string) == 0)) {
259       ERROR(RDT_PLUGIN ": Error - empty group");
260       return -EINVAL;
261     }
262
263     sstrncpy(value, item->values[j].value.string, sizeof(value));
264
265     ret = strlisttoarray(value, &groups[index].names, &groups[index].num_names);
266     if (ret != 0 || groups[index].num_names == 0) {
267       ERROR(RDT_PLUGIN ": Error parsing process names group (%s)",
268             item->values[j].value.string);
269       return -EINVAL;
270     }
271
272     /* set group description info */
273     groups[index].desc = sstrdup(item->values[j].value.string);
274     if (groups[index].desc == NULL) {
275       ERROR(RDT_PLUGIN ": Error allocating name group description");
276       return -ENOMEM;
277     }
278
279     groups[index].proc_pids_array = NULL;
280     groups[index].monitored_pids_count = 0;
281
282     index++;
283
284     if (index >= (const int)max_groups) {
285       WARNING(RDT_PLUGIN ": Too many process names groups configured");
286       return index;
287     }
288   }
289
290   return index;
291 }
292 #endif /* LIBPQOS2 */
293
294 #if COLLECT_DEBUG
295 static void rdt_dump_cgroups(void) {
296   char cores[RDT_MAX_CORES * 4];
297
298   if (g_rdt == NULL)
299     return;
300
301   DEBUG(RDT_PLUGIN ": Core Groups Dump");
302   DEBUG(RDT_PLUGIN ":  groups count: %" PRIsz, g_rdt->cores.num_cgroups);
303
304   for (size_t i = 0; i < g_rdt->cores.num_cgroups; i++) {
305     core_group_t *cgroup = g_rdt->cores.cgroups + i;
306
307     memset(cores, 0, sizeof(cores));
308     for (size_t j = 0; j < cgroup->num_cores; j++) {
309       snprintf(cores + strlen(cores), sizeof(cores) - strlen(cores) - 1, " %d",
310                cgroup->cores[j]);
311     }
312
313     DEBUG(RDT_PLUGIN ":  group[%zu]:", i);
314     DEBUG(RDT_PLUGIN ":    description: %s", cgroup->desc);
315     DEBUG(RDT_PLUGIN ":    cores: %s", cores);
316     DEBUG(RDT_PLUGIN ":    events: 0x%X", g_rdt->events[i]);
317   }
318
319   return;
320 }
321
322 #ifdef LIBPQOS2
323 static void rdt_dump_ngroups(void) {
324
325   char names[DATA_MAX_NAME_LEN];
326
327   if (g_rdt == NULL)
328     return;
329
330   DEBUG(RDT_PLUGIN ": Process Names Groups Dump");
331   DEBUG(RDT_PLUGIN ":  groups count: %" PRIsz, g_rdt->num_ngroups);
332
333   for (size_t i = 0; i < g_rdt->num_ngroups; i++) {
334     memset(names, 0, sizeof(names));
335     for (size_t j = 0; j < g_rdt->ngroups[i].num_names; j++)
336       snprintf(names + strlen(names), sizeof(names) - strlen(names) - 1, " %s",
337                g_rdt->ngroups[i].names[j]);
338
339     DEBUG(RDT_PLUGIN ":  group[%d]:", (int)i);
340     DEBUG(RDT_PLUGIN ":    description: %s", g_rdt->ngroups[i].desc);
341     DEBUG(RDT_PLUGIN ":    process names:%s", names);
342     DEBUG(RDT_PLUGIN ":    events: 0x%X", g_rdt->ngroups[i].events);
343   }
344
345   return;
346 }
347 #endif /* LIBPQOS2 */
348
349 static inline double bytes_to_kb(const double bytes) { return bytes / 1024.0; }
350
351 static inline double bytes_to_mb(const double bytes) {
352   return bytes / (1024.0 * 1024.0);
353 }
354
355 static void rdt_dump_cores_data(void) {
356 /*
357  * CORE - monitored group of cores
358  * RMID - Resource Monitoring ID associated with the monitored group
359  *        This is not available for monitoring with resource control
360  * LLC - last level cache occupancy
361  * MBL - local memory bandwidth
362  * MBR - remote memory bandwidth
363  */
364 #ifdef LIBPQOS2
365   if (g_interface == PQOS_INTER_OS_RESCTRL_MON) {
366     DEBUG(RDT_PLUGIN ":  CORE     LLC[KB]   MBL[MB]    MBR[MB]");
367   } else {
368     DEBUG(RDT_PLUGIN ":  CORE     RMID    LLC[KB]   MBL[MB]    MBR[MB]");
369   }
370 #else
371   DEBUG(RDT_PLUGIN ":  CORE     RMID    LLC[KB]   MBL[MB]    MBR[MB]");
372 #endif /* LIBPQOS2 */
373
374   for (size_t i = 0; i < g_rdt->cores.num_cgroups; i++) {
375     const struct pqos_event_values *pv = &g_rdt->pcgroups[i]->values;
376
377     double llc = bytes_to_kb(pv->llc);
378     double mbr = bytes_to_mb(pv->mbm_remote_delta);
379     double mbl = bytes_to_mb(pv->mbm_local_delta);
380 #ifdef LIBPQOS2
381     if (g_interface == PQOS_INTER_OS_RESCTRL_MON) {
382       DEBUG(RDT_PLUGIN ": [%s] %10.1f %10.1f %10.1f",
383             g_rdt->cores.cgroups[i].desc, llc, mbl, mbr);
384     } else {
385       DEBUG(RDT_PLUGIN ": [%s] %8u %10.1f %10.1f %10.1f",
386             g_rdt->cores.cgroups[i].desc, g_rdt->pcgroups[i]->poll_ctx[0].rmid,
387             llc, mbl, mbr);
388     }
389 #else
390     DEBUG(RDT_PLUGIN ": [%s] %8u %10.1f %10.1f %10.1f",
391           g_rdt->cores.cgroups[i].desc, g_rdt->pcgroups[i]->poll_ctx[0].rmid,
392           llc, mbl, mbr);
393 #endif /* LIBPQOS2 */
394   }
395 }
396
397 #ifdef LIBPQOS2
398 static void rdt_dump_pids_data(void) {
399   /*
400    * NAME - monitored group of processes
401    * PIDs - list of PID numbers in the NAME group
402    * LLC - last level cache occupancy
403    * MBL - local memory bandwidth
404    * MBR - remote memory bandwidth
405    */
406
407   DEBUG(RDT_PLUGIN ":  NAME     PIDs");
408   char pids[DATA_MAX_NAME_LEN];
409   for (size_t i = 0; i < g_rdt->num_ngroups; ++i) {
410     memset(pids, 0, sizeof(pids));
411     for (size_t j = 0; j < g_rdt->ngroups[i].num_names; ++j) {
412       pids_list_t *list = g_rdt->ngroups[i].proc_pids_array[j].pids;
413       while (list != NULL) {
414         snprintf(pids + strlen(pids), sizeof(pids) - strlen(pids) - 1, " %u",
415                  list->pid);
416         list = list->next;
417       }
418     }
419     DEBUG(RDT_PLUGIN ":  [%s] %s", g_rdt->ngroups[i].desc, pids);
420   }
421
422   DEBUG(RDT_PLUGIN ":  NAME    LLC[KB]   MBL[MB]    MBR[MB]");
423   for (size_t i = 0; i < g_rdt->num_ngroups; i++) {
424
425     const struct pqos_event_values *pv = &g_rdt->pngroups[i]->values;
426
427     double llc = bytes_to_kb(pv->llc);
428     double mbr = bytes_to_mb(pv->mbm_remote_delta);
429     double mbl = bytes_to_mb(pv->mbm_local_delta);
430
431     DEBUG(RDT_PLUGIN ":  [%s] %10.1f %10.1f %10.1f", g_rdt->ngroups[i].desc,
432           llc, mbl, mbr);
433   }
434 }
435 #endif /* LIBPQOS2 */
436 #endif /* COLLECT_DEBUG */
437
438 static void rdt_free_cgroups(void) {
439   config_cores_cleanup(&g_rdt->cores);
440   for (int i = 0; i < RDT_MAX_CORES; i++) {
441     sfree(g_rdt->pcgroups[i]);
442   }
443 }
444
445 #ifdef LIBPQOS2
446 static int pids_list_free(pids_list_t *list) {
447   assert(list);
448
449   pids_list_t *current = list;
450   while (current != NULL) {
451     pids_list_t *previous = current;
452     current = current->next;
453     sfree(previous);
454   }
455   return 0;
456 }
457
458 static void rdt_free_ngroups(rdt_ctx_t *rdt) {
459   for (int i = 0; i < RDT_MAX_NAMES_GROUPS; i++) {
460     if (rdt->ngroups[i].desc)
461       DEBUG(RDT_PLUGIN ": Freeing pids \'%s\' group\'s data...",
462             rdt->ngroups[i].desc);
463     sfree(rdt->ngroups[i].desc);
464
465     strarray_free(rdt->ngroups[i].names, rdt->ngroups[i].num_names);
466
467     if (rdt->ngroups[i].proc_pids_array) {
468       for (size_t j = 0; j < rdt->ngroups[i].num_names; ++j) {
469         if (NULL == rdt->ngroups[i].proc_pids_array[j].pids)
470           continue;
471         pids_list_free(rdt->ngroups[i].proc_pids_array[j].pids);
472       }
473
474       sfree(rdt->ngroups[i].proc_pids_array);
475     }
476
477     rdt->ngroups[i].num_names = 0;
478     sfree(rdt->pngroups[i]);
479   }
480 }
481 #endif /* LIBPQOS2 */
482
483 static int rdt_default_cgroups(void) {
484   unsigned num_cores = g_rdt->pqos_cpu->num_cores;
485
486   g_rdt->cores.cgroups = calloc(num_cores, sizeof(*g_rdt->cores.cgroups));
487   if (g_rdt->cores.cgroups == NULL) {
488     ERROR(RDT_PLUGIN ": Error allocating core groups array");
489     return -ENOMEM;
490   }
491   g_rdt->cores.num_cgroups = num_cores;
492
493   /* configure each core in separate group */
494   for (unsigned i = 0; i < num_cores; i++) {
495     core_group_t *cgroup = g_rdt->cores.cgroups + i;
496     char desc[DATA_MAX_NAME_LEN];
497
498     /* set core group info */
499     cgroup->cores = calloc(1, sizeof(*cgroup->cores));
500     if (cgroup->cores == NULL) {
501       ERROR(RDT_PLUGIN ": Error allocating cores array");
502       rdt_free_cgroups();
503       return -ENOMEM;
504     }
505     cgroup->num_cores = 1;
506     cgroup->cores[0] = i;
507
508     snprintf(desc, sizeof(desc), "%d", g_rdt->pqos_cpu->cores[i].lcore);
509     cgroup->desc = strdup(desc);
510     if (cgroup->desc == NULL) {
511       ERROR(RDT_PLUGIN ": Error allocating core group description");
512       rdt_free_cgroups();
513       return -ENOMEM;
514     }
515   }
516
517   return num_cores;
518 }
519
520 static int rdt_is_core_id_valid(unsigned int core_id) {
521
522   for (unsigned int i = 0; i < g_rdt->pqos_cpu->num_cores; i++)
523     if (core_id == g_rdt->pqos_cpu->cores[i].lcore)
524       return 1;
525
526   return 0;
527 }
528
529 #ifdef LIBPQOS2
530 static int rdt_is_proc_name_valid(const char *name) {
531
532   if (name != NULL) {
533     unsigned len = strlen(name);
534     if (len > 0 && len <= RDT_MAX_NAME_LEN)
535       return 1;
536     else {
537       DEBUG(RDT_PLUGIN
538             ": Process name \'%s\' is too long. Max supported len is %d chars.",
539             name, RDT_MAX_NAME_LEN);
540     }
541   }
542
543   return 0;
544 }
545 #endif /* LIBPQOS2 */
546
547 static int rdt_config_cgroups(oconfig_item_t *item) {
548   size_t n = 0;
549   enum pqos_mon_event events = 0;
550
551   if (config_cores_parse(item, &g_rdt->cores) < 0) {
552     rdt_free_cgroups();
553     ERROR(RDT_PLUGIN ": Error parsing core groups configuration.");
554     return -EINVAL;
555   }
556   n = g_rdt->cores.num_cgroups;
557
558   /* validate configured core id values */
559   for (size_t group_idx = 0; group_idx < n; group_idx++) {
560     core_group_t *cgroup = g_rdt->cores.cgroups + group_idx;
561     for (size_t core_idx = 0; core_idx < cgroup->num_cores; core_idx++) {
562       if (!rdt_is_core_id_valid(cgroup->cores[core_idx])) {
563         ERROR(RDT_PLUGIN ": Core group '%s' contains invalid core id '%u'",
564               cgroup->desc, cgroup->cores[core_idx]);
565         rdt_free_cgroups();
566         return -EINVAL;
567       }
568     }
569   }
570
571   if (n == 0) {
572     /* create default core groups if "Cores" config option is empty */
573     int ret = rdt_default_cgroups();
574     if (ret < 0) {
575       rdt_free_cgroups();
576       ERROR(RDT_PLUGIN ": Error creating default core groups configuration.");
577       return ret;
578     }
579     n = (size_t)ret;
580     INFO(RDT_PLUGIN
581          ": No core groups configured. Default core groups created.");
582   }
583
584   /* Get all available events on this platform */
585   for (unsigned int i = 0; i < g_rdt->cap_mon->u.mon->num_events; i++)
586     events |= g_rdt->cap_mon->u.mon->events[i].type;
587
588   events &= ~(PQOS_PERF_EVENT_LLC_MISS);
589
590   DEBUG(RDT_PLUGIN ": Number of cores in the system: %u",
591         g_rdt->pqos_cpu->num_cores);
592   DEBUG(RDT_PLUGIN ": Available events to monitor: %#x", events);
593
594   g_rdt->cores.num_cgroups = n;
595   for (int i = 0; i < n; i++) {
596     for (int j = 0; j < i; j++) {
597       int found = 0;
598       found = config_cores_cmp_cgroups(&g_rdt->cores.cgroups[j],
599                                        &g_rdt->cores.cgroups[i]);
600       if (found != 0) {
601         rdt_free_cgroups();
602         ERROR(RDT_PLUGIN ": Cannot monitor same cores in different groups.");
603         return -EINVAL;
604       }
605     }
606
607     g_rdt->events[i] = events;
608     g_rdt->pcgroups[i] = calloc(1, sizeof(*g_rdt->pcgroups[i]));
609     if (g_rdt->pcgroups[i] == NULL) {
610       rdt_free_cgroups();
611       ERROR(RDT_PLUGIN ": Failed to allocate memory for monitoring data.");
612       return -ENOMEM;
613     }
614   }
615
616   return 0;
617 }
618
619 #ifdef LIBPQOS2
620 static int rdt_config_ngroups(rdt_ctx_t *rdt, const oconfig_item_t *item) {
621   int n = 0;
622   enum pqos_mon_event events = 0;
623
624   if (item == NULL) {
625     DEBUG(RDT_PLUGIN ": ngroups_config: Invalid argument.");
626     return -EINVAL;
627   }
628
629   DEBUG(RDT_PLUGIN ": Process names groups [%d]:", item->values_num);
630   for (int j = 0; j < item->values_num; j++) {
631     if (item->values[j].type != OCONFIG_TYPE_STRING) {
632       ERROR(RDT_PLUGIN
633             ": given process names group value is not a string [idx=%d]",
634             j);
635       return -EINVAL;
636     }
637     DEBUG(RDT_PLUGIN ":  [%d]: %s", j, item->values[j].value.string);
638   }
639
640   n = oconfig_to_ngroups(item, rdt->ngroups, RDT_MAX_NAMES_GROUPS);
641   if (n < 0) {
642     rdt_free_ngroups(rdt);
643     ERROR(RDT_PLUGIN ": Error parsing process name groups configuration.");
644     return -EINVAL;
645   }
646
647   /* validate configured process name values */
648   for (int group_idx = 0; group_idx < n; group_idx++) {
649     DEBUG(RDT_PLUGIN ":  checking group [%d]: %s", group_idx,
650           rdt->ngroups[group_idx].desc);
651     for (size_t name_idx = 0; name_idx < rdt->ngroups[group_idx].num_names;
652          name_idx++) {
653       DEBUG(RDT_PLUGIN ":    checking process name [%zu]: %s", name_idx,
654             rdt->ngroups[group_idx].names[name_idx]);
655       if (!rdt_is_proc_name_valid(rdt->ngroups[group_idx].names[name_idx])) {
656         ERROR(RDT_PLUGIN ": Process name group '%s' contains invalid name '%s'",
657               rdt->ngroups[group_idx].desc,
658               rdt->ngroups[group_idx].names[name_idx]);
659         rdt_free_ngroups(rdt);
660         return -EINVAL;
661       }
662     }
663   }
664
665   if (n == 0) {
666     ERROR(RDT_PLUGIN ": Empty process name groups configured.");
667     return -EINVAL;
668   }
669
670   /* Get all available events on this platform */
671   for (unsigned i = 0; i < rdt->cap_mon->u.mon->num_events; i++)
672     events |= rdt->cap_mon->u.mon->events[i].type;
673
674   events &= ~(PQOS_PERF_EVENT_LLC_MISS);
675
676   DEBUG(RDT_PLUGIN ": Available events to monitor: %#x", events);
677
678   rdt->num_ngroups = n;
679   for (int i = 0; i < n; i++) {
680     for (int j = 0; j < i; j++) {
681       int found = ngroup_cmp(&rdt->ngroups[j], &rdt->ngroups[i]);
682       if (found != 0) {
683         rdt_free_ngroups(rdt);
684         ERROR(RDT_PLUGIN
685               ": Cannot monitor same process name in different groups.");
686         return -EINVAL;
687       }
688     }
689
690     rdt->ngroups[i].events = events;
691     rdt->pngroups[i] = calloc(1, sizeof(*rdt->pngroups[i]));
692     if (rdt->pngroups[i] == NULL) {
693       rdt_free_ngroups(rdt);
694       ERROR(RDT_PLUGIN
695             ": Failed to allocate memory for process name monitoring data.");
696       return -ENOMEM;
697     }
698   }
699
700   return 0;
701 }
702
703 /*
704  * NAME
705  *   pids_list_add_pid
706  *
707  * DESCRIPTION
708  *   Adds pid at the end of the pids list.
709  *   Allocates memory for new pid element, it is up to user to free it.
710  *
711  * PARAMETERS
712  *   `list'     Head of target pids_list.
713  *   `pid'      Pid to be added.
714  *
715  * RETURN VALUE
716  *   On success, returns 0.
717  *   -1 on memory allocation error.
718  */
719 static int pids_list_add_pid(pids_list_t **list, const pid_t pid) {
720   assert(list);
721
722   pids_list_t *new_element = calloc(1, sizeof(*new_element));
723
724   if (new_element == NULL) {
725     ERROR(RDT_PLUGIN ": Alloc error\n");
726     return -1;
727   }
728   new_element->pid = pid;
729   new_element->next = NULL;
730
731   pids_list_t **current = list;
732   while (*current != NULL) {
733     current = &((*current)->next);
734   }
735   *current = new_element;
736   return 0;
737 }
738
739 /*
740  * NAME
741  *   pids_list_contains_pid
742  *
743  * DESCRIPTION
744  *   Tests if pids list contains specific pid.
745  *
746  * PARAMETERS
747  *   `list'     Head of pids_list.
748  *   `pid'      Pid to be searched for.
749  *
750  * RETURN VALUE
751  *   If PID found in list, returns 1,
752  *   Otherwise returns 0.
753  */
754 static int pids_list_contains_pid(pids_list_t *list, const pid_t pid) {
755   assert(list);
756
757   pids_list_t *current = list;
758   while (current != NULL) {
759     if (current->pid == pid)
760       return 1;
761     current = current->next;
762   }
763   return 0;
764 }
765
766 /*
767  * NAME
768  *   pids_list_add_pids_list
769  *
770  * DESCRIPTION
771  *   Adds pids list at the end of the pids list.
772  *   Allocates memory for new pid elements, it is up to user to free it.
773  *   Increases dst_num by a number of added PIDs.
774  *
775  * PARAMETERS
776  *   `dst'      Head of target PIDs list.
777  *   `src'      Head of source PIDs list.
778  *   `dst_num'  Variable to be increased by a number of appended PIDs.
779  *
780  * RETURN VALUE
781  *   On success, returns 0.
782  *   -1 on memory allocation error.
783  */
784 static int pids_list_add_pids_list(pids_list_t **dst, pids_list_t *src,
785                                    size_t *dst_num) {
786   assert(dst);
787   assert(src);
788   assert(dst_num);
789
790   pids_list_t *current = src;
791   int ret;
792
793   while (current != NULL) {
794     ret = pids_list_add_pid(dst, current->pid);
795     if (0 != ret)
796       return ret;
797
798     ++(*dst_num);
799     current = current->next;
800   }
801
802   return 0;
803 }
804
805 /*
806  * NAME
807  *   read_proc_name
808  *
809  * DESCRIPTION
810  *   Reads process name from given pid directory.
811  *   Strips new-line character (\n).
812  *
813  * PARAMETERS
814  *   `procfs_path` Path to systems proc directory (e.g. /proc)
815  *   `pid_entry'   Dirent for PID directory
816  *   `name'        Output buffer for process name, recommended proc_comm.
817  *   `out_size'    Output buffer size, recommended sizeof(proc_comm)
818  *
819  * RETURN VALUE
820  *   On success, the number of read bytes (includes stripped \n).
821  *   -1 on file open error
822  */
823 static int read_proc_name(const char *procfs_path,
824                           const struct dirent *pid_entry, char *name,
825                           const size_t out_size) {
826   assert(procfs_path);
827   assert(pid_entry);
828   assert(name);
829   assert(out_size);
830   memset(name, 0, out_size);
831
832   const char *comm_file_name = "comm";
833
834   char *path = ssnprintf_alloc("%s/%s/%s", procfs_path, pid_entry->d_name,
835                                comm_file_name);
836   if (path == NULL)
837     return -1;
838   FILE *f = fopen(path, "r");
839   if (f == NULL) {
840     ERROR(RDT_PLUGIN ": Failed to open comm file, error: %d\n", errno);
841     sfree(path);
842     return -1;
843   }
844   size_t read_length = fread(name, sizeof(char), out_size, f);
845   name[out_size - 1] = '\0';
846   fclose(f);
847   sfree(path);
848   /* strip new line ending */
849   char *newline = strchr(name, '\n');
850   if (newline) {
851     *newline = '\0';
852   }
853
854   return read_length;
855 }
856
857 /*
858  * NAME
859  *   get_pid_number
860  *
861  * DESCRIPTION
862  *   Gets pid number for given /proc/pid directory entry or
863  *   returns error if input directory does not hold PID information.
864  *
865  * PARAMETERS
866  *   `entry'    Dirent for PID directory
867  *   `pid'      PID number to be filled
868  *
869  * RETURN VALUE
870  *   0 on success. -1 on error.
871  */
872 static int get_pid_number(struct dirent *entry, pid_t *pid) {
873   char *tmp_end; /* used for strtoul error check*/
874
875   if (pid == NULL || entry == NULL)
876     return -1;
877
878   if (entry->d_type != DT_DIR)
879     return -1;
880
881   /* trying to get pid number from directory name*/
882   *pid = strtoul(entry->d_name, &tmp_end, 10);
883   if (*tmp_end != '\0') {
884     return -1; /* conversion failed, not proc-pid */
885   }
886   /* all checks passed, marking as success */
887   return 0;
888 }
889
890 /*
891  * NAME
892  *   pids_list_to_array
893  *
894  * DESCRIPTION
895  *   Copies element from list to array. Assumes the space for the array is
896  *   allocated.
897  *
898  * PARAMETERS
899  *   `array'      First element of target array
900  *   `list'       Head of the list
901  *   `array_length' Length (element count) of the target array
902  */
903 static void pids_list_to_array(pid_t *array, pids_list_t *list,
904                                const size_t array_length) {
905
906   assert(list);
907   assert(array);
908   assert(array_length > 0);
909
910   size_t current = 0;
911
912   while (list != NULL && current < array_length) {
913     array[current] = list->pid;
914     list = list->next;
915     ++current;
916   }
917 }
918
919 /*
920  * NAME
921  *   initialize_proc_pids
922  *
923  * DESCRIPTION
924  *   Helper function to properly initialize array of proc_pids.
925  *   Allocates memory for proc_pids structs.
926  *
927  * PARAMETERS
928  *   `procs_names_array'      Array of null-terminated strings with
929  *                            process' names to be copied to new array
930  *   `procs_names_array_size' procs_names_array element count
931  *   `proc_pids_array'        Address of pointer, under which new
932  *                            array of proc_pids will be allocated.
933  *                            Must be NULL.
934  * RETURN VALUE
935  *   0 on success. Negative number on error:
936  *   -1: allocation error
937  */
938 static int initialize_proc_pids(const char **procs_names_array,
939                                 const size_t procs_names_array_size,
940                                 proc_pids_t **proc_pids_array) {
941
942   assert(proc_pids_array);
943   assert(NULL == *proc_pids_array);
944
945   /* Copy procs names to output array. Initialize pids list with NULL value. */
946   *proc_pids_array = calloc(procs_names_array_size, sizeof(**proc_pids_array));
947
948   if (NULL == *proc_pids_array)
949     return -1;
950
951   for (size_t i = 0; i < procs_names_array_size; ++i) {
952     sstrncpy((*proc_pids_array)[i].proccess_name, procs_names_array[i],
953              STATIC_ARRAY_SIZE((*proc_pids_array)[i].proccess_name));
954     (*proc_pids_array)[i].pids = NULL;
955   }
956
957   return 0;
958 }
959
960 /*
961  * NAME
962  *   fetch_pids_for_procs
963  *
964  * DESCRIPTION
965  *   Finds PIDs matching given process's names.
966  *   Searches all PID directories in /proc fs and
967  *   allocates memory for proc_pids structs, it is up to user to free it.
968  *   Output array will have same element count as input array.
969  *
970  * PARAMETERS
971  *   `procfs_path'            Path to systems proc directory (e.g. /proc)
972  *   `procs_names_array'      Array of null-terminated strings with
973  *                            process' names to be copied to new array
974  *   `procs_names_array_size' procs_names_array element count
975  *   `proc_pids_array'        Address of pointer, under which new
976  *                            array of proc_pids will be allocated.
977  *                            Must be NULL.
978  *
979  * RETURN VALUE
980  *   0 on success. -1 on error.
981  */
982 static int fetch_pids_for_procs(const char *procfs_path,
983                                 const char **procs_names_array,
984                                 const size_t procs_names_array_size,
985                                 proc_pids_t **proc_pids_array) {
986   assert(procfs_path);
987   assert(procs_names_array);
988   assert(procs_names_array_size);
989
990   DIR *proc_dir = opendir(procfs_path);
991   if (proc_dir == NULL) {
992     ERROR(RDT_PLUGIN ": Could not open %s directory, error: %d", procfs_path,
993           errno);
994     return -1;
995   }
996
997   int init_result = initialize_proc_pids(
998       procs_names_array, procs_names_array_size, proc_pids_array);
999   if (0 != init_result)
1000     return -1;
1001
1002   /* Go through procfs and find PIDS and their comms */
1003   struct dirent *entry;
1004   while ((entry = readdir(proc_dir)) != NULL) {
1005
1006     pid_t pid;
1007     int pid_conversion = get_pid_number(entry, &pid);
1008     if (pid_conversion < 0)
1009       continue;
1010
1011     proc_comm_t comm;
1012     int read_result =
1013         read_proc_name(procfs_path, entry, comm, sizeof(proc_comm_t));
1014     if (read_result <= 0) {
1015       ERROR(RDT_PLUGIN ": Comm file skipped. Read result: %d", read_result);
1016       continue;
1017     }
1018
1019     /* Try to find comm in input procs array (proc_pids_array has same names) */
1020     for (size_t i = 0; i < procs_names_array_size; ++i) {
1021       if (0 == strncmp(comm, (*proc_pids_array)[i].proccess_name,
1022                        STATIC_ARRAY_SIZE(comm)))
1023         pids_list_add_pid(&((*proc_pids_array)[i].pids), pid);
1024     }
1025   }
1026
1027   int close_result = closedir(proc_dir);
1028   if (0 != close_result) {
1029     ERROR(RDT_PLUGIN ": failed to close %s directory, error: %d", procfs_path,
1030           errno);
1031     sfree(*proc_pids_array);
1032     return -1;
1033   }
1034   return 0;
1035 }
1036 #endif /* LIBPQOS2 */
1037
1038 static void rdt_pqos_log(void *context, const size_t size, const char *msg) {
1039   DEBUG(RDT_PLUGIN ": %s", msg);
1040 }
1041
1042 static int rdt_preinit(void) {
1043   int ret;
1044
1045   if (g_rdt != NULL) {
1046     /* already initialized if config callback was called before init callback */
1047     return 0;
1048   }
1049
1050   g_rdt = calloc(1, sizeof(*g_rdt));
1051   if (g_rdt == NULL) {
1052     ERROR(RDT_PLUGIN ": Failed to allocate memory for rdt context.");
1053     return -ENOMEM;
1054   }
1055
1056   struct pqos_config pqos = {.fd_log = -1,
1057                              .callback_log = rdt_pqos_log,
1058                              .context_log = NULL,
1059                              .verbose = 0,
1060 #ifdef LIBPQOS2
1061                              .interface = PQOS_INTER_OS_RESCTRL_MON};
1062   DEBUG(RDT_PLUGIN ": Initializing PQoS with RESCTRL interface");
1063 #else
1064                              .interface = PQOS_INTER_MSR};
1065   DEBUG(RDT_PLUGIN ": Initializing PQoS with MSR interface");
1066 #endif
1067
1068   ret = pqos_init(&pqos);
1069   DEBUG(RDT_PLUGIN ": PQoS initialization result: [%d]", ret);
1070
1071 #ifdef LIBPQOS2
1072   if (ret == PQOS_RETVAL_INTER) {
1073     pqos.interface = PQOS_INTER_MSR;
1074     DEBUG(RDT_PLUGIN ": Initializing PQoS with MSR interface");
1075     ret = pqos_init(&pqos);
1076     DEBUG(RDT_PLUGIN ": PQoS initialization result: [%d]", ret);
1077   }
1078 #endif
1079
1080   if (ret != PQOS_RETVAL_OK) {
1081     ERROR(RDT_PLUGIN ": Error initializing PQoS library!");
1082     goto rdt_preinit_error1;
1083   }
1084
1085   g_interface = pqos.interface;
1086
1087   ret = pqos_cap_get(&g_rdt->pqos_cap, &g_rdt->pqos_cpu);
1088   if (ret != PQOS_RETVAL_OK) {
1089     ERROR(RDT_PLUGIN ": Error retrieving PQoS capabilities.");
1090     goto rdt_preinit_error2;
1091   }
1092
1093   ret = pqos_cap_get_type(g_rdt->pqos_cap, PQOS_CAP_TYPE_MON, &g_rdt->cap_mon);
1094   if (ret == PQOS_RETVAL_PARAM) {
1095     ERROR(RDT_PLUGIN ": Error retrieving monitoring capabilities.");
1096     goto rdt_preinit_error2;
1097   }
1098
1099   if (g_rdt->cap_mon == NULL) {
1100     ERROR(
1101         RDT_PLUGIN
1102         ": Monitoring capability not detected. Nothing to do for the plugin.");
1103     goto rdt_preinit_error2;
1104   }
1105
1106   /* Reset pqos monitoring groups registers */
1107   pqos_mon_reset();
1108
1109   return 0;
1110
1111 rdt_preinit_error2:
1112   pqos_fini();
1113
1114 rdt_preinit_error1:
1115   sfree(g_rdt);
1116
1117   return -1;
1118 }
1119
1120 static int rdt_config(oconfig_item_t *ci) {
1121   if (rdt_preinit() != 0) {
1122     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
1130   for (int i = 0; i < ci->children_num; i++) {
1131     oconfig_item_t *child = ci->children + i;
1132
1133     if (strncasecmp("Cores", child->key, (size_t)strlen("Cores")) == 0) {
1134       if (rdt_config_cgroups(child) != 0) {
1135         g_state = CONFIGURATION_ERROR;
1136         /* if we return -1 at this point collectd
1137            reports a failure in configuration and
1138            aborts
1139          */
1140         return (0);
1141       }
1142
1143 #if COLLECT_DEBUG
1144       rdt_dump_cgroups();
1145 #endif /* COLLECT_DEBUG */
1146     } else if (strncasecmp("Processes", child->key,
1147                            (size_t)strlen("Processes")) == 0) {
1148 #ifdef LIBPQOS2
1149       if (g_interface != PQOS_INTER_OS_RESCTRL_MON) {
1150         ERROR(RDT_PLUGIN ": Configuration parameter \"%s\" not supported. "
1151                          "Resctrl monitoring is needed for PIDs monitoring.",
1152               child->key);
1153         g_state = CONFIGURATION_ERROR;
1154         /* if we return -1 at this point collectd
1155            reports a failure in configuration and
1156            aborts
1157          */
1158         return 0;
1159       }
1160
1161       if (rdt_config_ngroups(g_rdt, child) != 0) {
1162         g_state = CONFIGURATION_ERROR;
1163         /* if we return -1 at this point collectd
1164            reports a failure in configuration and
1165            aborts
1166          */
1167         return 0;
1168       }
1169
1170 #if COLLECT_DEBUG
1171       rdt_dump_ngroups();
1172 #endif /* COLLECT_DEBUG */
1173 #else  /* !LIBPQOS2 */
1174       ERROR(RDT_PLUGIN ": Configuration parameter \"%s\" not supported, please "
1175                        "recompile collectd with libpqos version 2.0 or newer.",
1176             child->key);
1177 #endif /* LIBPQOS2 */
1178     } else {
1179       ERROR(RDT_PLUGIN ": Unknown configuration parameter \"%s\".", child->key);
1180     }
1181   }
1182
1183   return 0;
1184 }
1185
1186 static void rdt_submit_derive(const char *cgroup, const char *type,
1187                               const char *type_instance, derive_t value) {
1188   value_list_t vl = VALUE_LIST_INIT;
1189
1190   vl.values = &(value_t){.derive = value};
1191   vl.values_len = 1;
1192
1193   sstrncpy(vl.plugin, RDT_PLUGIN, sizeof(vl.plugin));
1194   snprintf(vl.plugin_instance, sizeof(vl.plugin_instance), "%s", cgroup);
1195   sstrncpy(vl.type, type, sizeof(vl.type));
1196   if (type_instance)
1197     sstrncpy(vl.type_instance, type_instance, sizeof(vl.type_instance));
1198
1199   plugin_dispatch_values(&vl);
1200 }
1201
1202 static void rdt_submit_gauge(const char *cgroup, const char *type,
1203                              const char *type_instance, gauge_t value) {
1204   value_list_t vl = VALUE_LIST_INIT;
1205
1206   vl.values = &(value_t){.gauge = value};
1207   vl.values_len = 1;
1208
1209   sstrncpy(vl.plugin, RDT_PLUGIN, sizeof(vl.plugin));
1210   snprintf(vl.plugin_instance, sizeof(vl.plugin_instance), "%s", cgroup);
1211   sstrncpy(vl.type, type, sizeof(vl.type));
1212   if (type_instance)
1213     sstrncpy(vl.type_instance, type_instance, sizeof(vl.type_instance));
1214
1215   plugin_dispatch_values(&vl);
1216 }
1217
1218 #ifdef LIBPQOS2
1219 static int rdt_pid_list_diff(pids_list_t *prev, pids_list_t *curr,
1220                              pids_list_t **added, size_t *added_num,
1221                              pids_list_t **removed, size_t *removed_num) {
1222   assert(prev || curr);
1223   assert(added);
1224   assert(removed);
1225
1226   if (NULL == prev) {
1227     /* append all PIDs from curr to added*/
1228     return pids_list_add_pids_list(added, curr, added_num);
1229   } else if (NULL == curr) {
1230     /* append all PIDs from prev to removed*/
1231     return pids_list_add_pids_list(removed, prev, removed_num);
1232   }
1233
1234   pids_list_t *item = prev;
1235   while (item != NULL) {
1236     if (0 == pids_list_contains_pid(curr, item->pid)) {
1237       pids_list_add_pid(removed, item->pid);
1238       ++(*removed_num);
1239     }
1240     item = item->next;
1241   }
1242
1243   item = curr;
1244   while (item != NULL) {
1245     if (0 == pids_list_contains_pid(prev, item->pid)) {
1246       pids_list_add_pid(added, item->pid);
1247       ++(*added_num);
1248     }
1249     item = item->next;
1250   }
1251
1252   return 0;
1253 }
1254
1255 static int rdt_refresh_ngroup(rdt_name_group_t *ngroup,
1256                               struct pqos_mon_data *group_mon_data) {
1257
1258   int result = 0;
1259
1260   if (NULL == ngroup)
1261     return -1;
1262
1263   if (NULL == ngroup->proc_pids_array) {
1264     ERROR(RDT_PLUGIN
1265           ": rdt_refresh_ngroup: \'%s\' uninitialized process pids array.",
1266           ngroup->desc);
1267
1268     return -1;
1269   }
1270
1271   DEBUG(RDT_PLUGIN ": rdt_refresh_ngroup: \'%s\' process names group.",
1272         ngroup->desc);
1273
1274   proc_pids_t *proc_pids_array_prev = ngroup->proc_pids_array;
1275   proc_pids_t *proc_pids_array_curr = NULL;
1276
1277   int fetch_result =
1278       fetch_pids_for_procs(RDT_PROC_PATH, (const char **)ngroup->names,
1279                            ngroup->num_names, &proc_pids_array_curr);
1280
1281   if (0 != fetch_result) {
1282     ERROR(RDT_PLUGIN ": rdt_refresh_ngroup: \'%s\' failed to fetch PIDs.",
1283           ngroup->desc);
1284     return fetch_result;
1285   }
1286
1287   pids_list_t *new_pids = NULL;
1288   pid_t *new_pids_array = NULL;
1289   size_t new_pids_count = 0;
1290
1291   pids_list_t *lost_pids = NULL;
1292   pid_t *lost_pids_array = NULL;
1293   size_t lost_pids_count = 0;
1294
1295   for (size_t i = 0; i < ngroup->num_names; ++i) {
1296     if (NULL == proc_pids_array_prev[i].pids &&
1297         NULL == proc_pids_array_curr[i].pids)
1298       continue;
1299     int diff_result = rdt_pid_list_diff(
1300         proc_pids_array_prev[i].pids, proc_pids_array_curr[i].pids, &new_pids,
1301         &new_pids_count, &lost_pids, &lost_pids_count);
1302     if (0 != diff_result) {
1303       ERROR(RDT_PLUGIN
1304             ": rdt_refresh_ngroup: \'%s\'. Error [%d] during PID diff.",
1305             ngroup->desc, diff_result);
1306       result = -1;
1307       goto cleanup;
1308     }
1309   }
1310
1311   DEBUG(RDT_PLUGIN ": rdt_refresh_ngroup: \'%s\' process names group, added: "
1312                    "%u, removed: %u.",
1313         ngroup->desc, (unsigned)new_pids_count, (unsigned)lost_pids_count);
1314
1315   if (new_pids && new_pids_count > 0) {
1316     new_pids_array = malloc(new_pids_count * sizeof(pid_t));
1317     if (new_pids_array == NULL) {
1318       ERROR(RDT_PLUGIN ": rdt_refresh_ngroup: \'%s\'. Memory "
1319                        "allocation failed",
1320             ngroup->desc);
1321       result = -1;
1322       goto cleanup;
1323     }
1324     pids_list_to_array(new_pids_array, new_pids, new_pids_count);
1325
1326     /* no pids are monitored for this group yet: start monitoring */
1327     if (0 == ngroup->monitored_pids_count) {
1328
1329       int start_result =
1330           pqos_mon_start_pids(new_pids_count, new_pids_array, ngroup->events,
1331                               (void *)ngroup->desc, group_mon_data);
1332       if (PQOS_RETVAL_OK == start_result) {
1333         ngroup->monitored_pids_count = new_pids_count;
1334       } else {
1335         ERROR(RDT_PLUGIN ": rdt_refresh_ngroup: \'%s\'. Error [%d] while "
1336                          "STARTING pids monitoring",
1337               ngroup->desc, start_result);
1338         result = -1;
1339         goto pqos_error_recovery;
1340       }
1341
1342     } else {
1343
1344       int add_result =
1345           pqos_mon_add_pids(new_pids_count, new_pids_array, group_mon_data);
1346       if (PQOS_RETVAL_OK == add_result)
1347         ngroup->monitored_pids_count += new_pids_count;
1348       else {
1349         ERROR(RDT_PLUGIN
1350               ": rdt_refresh_ngroup: \'%s\'. Error [%d] while ADDING pids.",
1351               ngroup->desc, add_result);
1352         result = -1;
1353         goto pqos_error_recovery;
1354       }
1355     }
1356   }
1357
1358   if (lost_pids && lost_pids_count > 0) {
1359     lost_pids_array = malloc(lost_pids_count * sizeof(pid_t));
1360     if (lost_pids_array == NULL) {
1361       ERROR(RDT_PLUGIN ": rdt_refresh_ngroup: \'%s\'. Memory "
1362                        "allocation failed",
1363             ngroup->desc);
1364       result = -1;
1365       goto cleanup;
1366     }
1367     pids_list_to_array(lost_pids_array, lost_pids, lost_pids_count);
1368
1369     if (lost_pids_count == ngroup->monitored_pids_count) {
1370       /* all pids for this group are lost: stop monitoring */
1371       int stop_result = pqos_mon_stop(group_mon_data);
1372       if (PQOS_RETVAL_OK != stop_result) {
1373         ERROR(RDT_PLUGIN ": rdt_refresh_ngroup: \'%s\'. Error [%d] while "
1374                          "STOPPING monitoring",
1375               ngroup->desc, stop_result);
1376         result = -1;
1377         goto pqos_error_recovery;
1378       }
1379       ngroup->monitored_pids_count = 0;
1380     } else {
1381       assert(lost_pids_count < ngroup->monitored_pids_count);
1382       int remove_result = pqos_mon_remove_pids(lost_pids_count, lost_pids_array,
1383                                                group_mon_data);
1384       if (PQOS_RETVAL_OK == remove_result) {
1385         ngroup->monitored_pids_count -= lost_pids_count;
1386       } else {
1387         ERROR(RDT_PLUGIN
1388               ": rdt_refresh_ngroup: \'%s\'. Error [%d] while REMOVING pids.",
1389               ngroup->desc, remove_result);
1390         result = -1;
1391         goto pqos_error_recovery;
1392       }
1393     }
1394   }
1395
1396   if (new_pids_count > 0 || lost_pids_count > 0)
1397     ngroup->proc_pids_array = proc_pids_array_curr;
1398
1399   goto cleanup;
1400
1401 pqos_error_recovery:
1402   /* Why?
1403    * Resources might be temporary unavailable.
1404    *
1405    * How?
1406    * Collectd will halt the reading thread for this
1407    * plugin if it returns an error.
1408    * Consecutive errors will be increasing the read period
1409    * up to 1 day interval.
1410    * On pqos error stop monitoring current group
1411    * and reset the proc_pids array
1412    * monitoring will be restarted on next collectd read cycle
1413    */
1414   DEBUG(RDT_PLUGIN ": rdt_refresh_ngroup: \'%s\' group RESET after error.",
1415         ngroup->desc);
1416   pqos_mon_stop(group_mon_data);
1417   for (size_t i = 0; i < ngroup->num_names; ++i) {
1418     if (ngroup->proc_pids_array[i].pids)
1419       pids_list_free(ngroup->proc_pids_array[i].pids);
1420   }
1421   sfree(ngroup->proc_pids_array);
1422
1423   initialize_proc_pids((const char **)ngroup->names, ngroup->num_names,
1424                        &ngroup->proc_pids_array);
1425   ngroup->monitored_pids_count = 0;
1426
1427 cleanup:
1428   if (ngroup->proc_pids_array == proc_pids_array_curr) {
1429     assert(proc_pids_array_curr);
1430     /* new list was successfully saved, free the old one */
1431     for (size_t i = 0; i < ngroup->num_names; ++i)
1432       if (proc_pids_array_prev[i].pids)
1433         pids_list_free(proc_pids_array_prev[i].pids);
1434
1435     sfree(proc_pids_array_prev);
1436
1437   } else {
1438     /* new list was not saved. Free the new list, keep the old one*/
1439     for (size_t i = 0; i < ngroup->num_names; ++i)
1440       if (proc_pids_array_curr[i].pids)
1441         pids_list_free(proc_pids_array_curr[i].pids);
1442
1443     sfree(proc_pids_array_curr);
1444   }
1445
1446   if (new_pids)
1447     pids_list_free(new_pids);
1448
1449   if (new_pids_array)
1450     free(new_pids_array);
1451
1452   if (lost_pids)
1453     pids_list_free(lost_pids);
1454
1455   if (lost_pids_array)
1456     free(lost_pids_array);
1457
1458   return result;
1459 }
1460
1461 static int read_pids_data() {
1462
1463   if (0 == g_rdt->num_ngroups) {
1464     DEBUG(RDT_PLUGIN ": read_pids_data: not configured - PIDs read skipped");
1465     return 0;
1466   }
1467
1468   DEBUG(RDT_PLUGIN ": read_pids_data: Scanning active groups");
1469   struct pqos_mon_data *active_groups[RDT_MAX_NAMES_GROUPS] = {0};
1470   size_t active_group_idx = 0;
1471   for (size_t pngroups_idx = 0;
1472        pngroups_idx < STATIC_ARRAY_SIZE(g_rdt->pngroups); ++pngroups_idx)
1473     if (0 != g_rdt->ngroups[pngroups_idx].monitored_pids_count)
1474       active_groups[active_group_idx++] = g_rdt->pngroups[pngroups_idx];
1475
1476   int ret = 0;
1477
1478   if (0 == active_group_idx) {
1479     DEBUG(RDT_PLUGIN ": read_pids_data: no active groups - PIDs read skipped");
1480     goto groups_refresh;
1481   }
1482
1483   DEBUG(RDT_PLUGIN ": read_pids_data: PIDs data polling");
1484
1485   int poll_result = pqos_mon_poll(active_groups, active_group_idx);
1486   if (poll_result != PQOS_RETVAL_OK) {
1487     ERROR(RDT_PLUGIN ": read_pids_data: Failed to poll monitoring data for "
1488                      "pids. Error [%d].",
1489           poll_result);
1490     ret = -poll_result;
1491     goto groups_refresh;
1492   }
1493
1494   for (size_t i = 0; i < g_rdt->num_ngroups; i++) {
1495     enum pqos_mon_event mbm_events =
1496         (PQOS_MON_EVENT_LMEM_BW | PQOS_MON_EVENT_TMEM_BW |
1497          PQOS_MON_EVENT_RMEM_BW);
1498
1499     if (g_rdt->pngroups[i] == NULL ||
1500         g_rdt->ngroups[i].monitored_pids_count == 0)
1501       continue;
1502
1503     const struct pqos_event_values *pv = &g_rdt->pngroups[i]->values;
1504
1505     /* Submit only monitored events data */
1506
1507     if (g_rdt->ngroups[i].events & PQOS_MON_EVENT_L3_OCCUP)
1508       rdt_submit_gauge(g_rdt->ngroups[i].desc, "bytes", "llc", pv->llc);
1509
1510     if (g_rdt->ngroups[i].events & PQOS_PERF_EVENT_IPC)
1511       rdt_submit_gauge(g_rdt->ngroups[i].desc, "ipc", NULL, pv->ipc);
1512
1513     if (g_rdt->ngroups[i].events & mbm_events) {
1514       rdt_submit_derive(g_rdt->ngroups[i].desc, "memory_bandwidth", "local",
1515                         pv->mbm_local_delta);
1516       rdt_submit_derive(g_rdt->ngroups[i].desc, "memory_bandwidth", "remote",
1517                         pv->mbm_remote_delta);
1518     }
1519   }
1520
1521 #if COLLECT_DEBUG
1522   rdt_dump_pids_data();
1523 #endif /* COLLECT_DEBUG */
1524
1525 groups_refresh:
1526   for (size_t i = 0; i < g_rdt->num_ngroups; i++) {
1527     int refresh_result =
1528         rdt_refresh_ngroup(&(g_rdt->ngroups[i]), g_rdt->pngroups[i]);
1529
1530     if (0 != refresh_result) {
1531       ERROR(RDT_PLUGIN ": read_pids_data: NGroup %zu refresh failed. Error: %d",
1532             i, refresh_result);
1533       if (0 == ret) {
1534         /* refresh error will be escalated only if there were no
1535          * errors before.
1536          */
1537         ret = refresh_result;
1538       }
1539     }
1540   }
1541
1542   assert(ret <= 0);
1543   return ret;
1544 }
1545
1546 static void rdt_init_pids_monitoring() {
1547   for (size_t group_idx = 0; group_idx < g_rdt->num_ngroups; group_idx++) {
1548     /*
1549      * Each group must have not-null proc_pids array.
1550      * Initial refresh is not mandatory for proper
1551      * PIDs statistics detection.
1552      */
1553     rdt_name_group_t *ng = &g_rdt->ngroups[group_idx];
1554     int init_result = initialize_proc_pids((const char **)ng->names,
1555                                            ng->num_names, &ng->proc_pids_array);
1556     if (0 != init_result) {
1557       ERROR(RDT_PLUGIN
1558             ": Initialization of proc_pids for group %zu failed. Error: %d",
1559             group_idx, init_result);
1560       continue;
1561     }
1562
1563     int refresh_result = rdt_refresh_ngroup(&(g_rdt->ngroups[group_idx]),
1564                                             g_rdt->pngroups[group_idx]);
1565     if (0 != refresh_result)
1566       ERROR(RDT_PLUGIN ": Initial refresh of group %zu failed. Error: %d",
1567             group_idx, refresh_result);
1568   }
1569 }
1570 #endif /* LIBPQOS2 */
1571
1572 static int read_cores_data() {
1573
1574   if (0 == g_rdt->cores.num_cgroups) {
1575     DEBUG(RDT_PLUGIN ": read_cores_data: not configured - Cores read skipped");
1576     return 0;
1577   }
1578   DEBUG(RDT_PLUGIN ": read_cores_data: Cores data poll");
1579
1580   int ret =
1581       pqos_mon_poll(&g_rdt->pcgroups[0], (unsigned)g_rdt->cores.num_cgroups);
1582   if (ret != PQOS_RETVAL_OK) {
1583     ERROR(RDT_PLUGIN ": read_cores_data: Failed to poll monitoring data for "
1584                      "cores. Error [%d].",
1585           ret);
1586     return -1;
1587   }
1588
1589   for (size_t i = 0; i < g_rdt->cores.num_cgroups; i++) {
1590     core_group_t *cgroup = g_rdt->cores.cgroups + i;
1591     enum pqos_mon_event mbm_events =
1592         (PQOS_MON_EVENT_LMEM_BW | PQOS_MON_EVENT_TMEM_BW |
1593          PQOS_MON_EVENT_RMEM_BW);
1594
1595     const struct pqos_event_values *pv = &g_rdt->pcgroups[i]->values;
1596
1597     /* Submit only monitored events data */
1598
1599     if (g_rdt->events[i] & PQOS_MON_EVENT_L3_OCCUP)
1600       rdt_submit_gauge(cgroup->desc, "bytes", "llc", pv->llc);
1601
1602     if (g_rdt->events[i] & PQOS_PERF_EVENT_IPC)
1603       rdt_submit_gauge(cgroup->desc, "ipc", NULL, pv->ipc);
1604
1605     if (g_rdt->events[i] & mbm_events) {
1606       rdt_submit_derive(cgroup->desc, "memory_bandwidth", "local",
1607                         pv->mbm_local_delta);
1608       rdt_submit_derive(cgroup->desc, "memory_bandwidth", "remote",
1609                         pv->mbm_remote_delta);
1610     }
1611   }
1612
1613 #if COLLECT_DEBUG
1614   rdt_dump_cores_data();
1615 #endif /* COLLECT_DEBUG */
1616
1617   return 0;
1618 }
1619
1620 static int rdt_read(__attribute__((unused)) user_data_t *ud) {
1621
1622   if (g_rdt == NULL) {
1623     ERROR(RDT_PLUGIN ": rdt_read: plugin not initialized.");
1624     return -EINVAL;
1625   }
1626
1627   int cores_read_result = read_cores_data();
1628
1629 #ifdef LIBPQOS2
1630   int pids_read_result = read_pids_data();
1631 #endif /* LIBPQOS2 */
1632
1633   if (0 != cores_read_result)
1634     return cores_read_result;
1635
1636 #ifdef LIBPQOS2
1637   if (0 != pids_read_result)
1638     return pids_read_result;
1639 #endif /* LIBPQOS2 */
1640
1641   return 0;
1642 }
1643
1644 static void rdt_init_cores_monitoring() {
1645   for (size_t i = 0; i < g_rdt->cores.num_cgroups; i++) {
1646     core_group_t *cg = g_rdt->cores.cgroups + i;
1647
1648     int mon_start_result =
1649         pqos_mon_start(cg->num_cores, cg->cores, g_rdt->events[i],
1650                        (void *)cg->desc, g_rdt->pcgroups[i]);
1651
1652     if (mon_start_result != PQOS_RETVAL_OK)
1653       ERROR(RDT_PLUGIN
1654             ": Error starting cores monitoring group %s (pqos status=%d)",
1655             cg->desc, mon_start_result);
1656   }
1657 }
1658
1659 static int rdt_init(void) {
1660
1661   if (g_state == CONFIGURATION_ERROR)
1662     return -1;
1663
1664   int rdt_preinint_result = rdt_preinit();
1665   if (rdt_preinint_result != 0)
1666     return rdt_preinint_result;
1667
1668   rdt_init_cores_monitoring();
1669 #ifdef LIBPQOS2
1670   rdt_init_pids_monitoring();
1671 #endif /* LIBPQOS2 */
1672
1673   return 0;
1674 }
1675
1676 static int rdt_shutdown(void) {
1677   int ret;
1678
1679   DEBUG(RDT_PLUGIN ": rdt_shutdown.");
1680
1681   if (g_rdt == NULL)
1682     return 0;
1683
1684   /* Stop monitoring cores */
1685   for (size_t i = 0; i < g_rdt->cores.num_cgroups; i++) {
1686     pqos_mon_stop(g_rdt->pcgroups[i]);
1687   }
1688
1689 /* Stop pids monitoring */
1690 #ifdef LIBPQOS2
1691   for (size_t i = 0; i < g_rdt->num_ngroups; i++)
1692     pqos_mon_stop(g_rdt->pngroups[i]);
1693 #endif
1694
1695   ret = pqos_fini();
1696   if (ret != PQOS_RETVAL_OK)
1697     ERROR(RDT_PLUGIN ": Error shutting down PQoS library.");
1698
1699   rdt_free_cgroups();
1700 #ifdef LIBPQOS2
1701   rdt_free_ngroups(g_rdt);
1702 #endif /* LIBPQOS2 */
1703   sfree(g_rdt);
1704
1705   return 0;
1706 }
1707
1708 void module_register(void) {
1709   plugin_register_init(RDT_PLUGIN, rdt_init);
1710   plugin_register_complex_config(RDT_PLUGIN, rdt_config);
1711   plugin_register_complex_read(NULL, RDT_PLUGIN, rdt_read, 0, NULL);
1712   plugin_register_shutdown(RDT_PLUGIN, rdt_shutdown);
1713 }