intel_rdt plugin: Include "collectd.h" as first header.
[collectd.git] / src / intel_rdt.c
1 /**
2  * collectd - src/intel_rdt.c
3  *
4  * Copyright(c) 2016 Intel Corporation. All rights reserved.
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy of
7  * this software and associated documentation files (the "Software"), to deal in
8  * the Software without restriction, including without limitation the rights to
9  * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
10  * of the Software, and to permit persons to whom the Software is furnished to do
11  * so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in all
14  * 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  **/
27
28 #include "collectd.h"
29 #include "common.h"
30
31 #include <pqos.h>
32
33 #define RDT_PLUGIN "intel_rdt"
34
35 #define RDT_MAX_SOCKETS 8
36 #define RDT_MAX_SOCKET_CORES 64
37 #define RDT_MAX_CORES (RDT_MAX_SOCKET_CORES * RDT_MAX_SOCKETS)
38
39 struct rdt_core_group_s {
40   char *desc;
41   size_t num_cores;
42   unsigned *cores;
43   enum pqos_mon_event events;
44 };
45 typedef struct rdt_core_group_s rdt_core_group_t;
46
47 struct rdt_ctx_s {
48   rdt_core_group_t cgroups[RDT_MAX_CORES];
49   struct pqos_mon_data *pgroups[RDT_MAX_CORES];
50   size_t num_groups;
51   const struct pqos_cpuinfo *pqos_cpu;
52   const struct pqos_cap *pqos_cap;
53   const struct pqos_capability *cap_mon;
54 };
55 typedef struct rdt_ctx_s rdt_ctx_t;
56
57 static rdt_ctx_t *g_rdt = NULL;
58
59 static int isdup(const uint64_t *nums, size_t size, uint64_t val) {
60   for (size_t i = 0; i < size; i++)
61     if (nums[i] == val)
62       return 1;
63   return 0;
64 }
65
66 static int strtouint64(const char *s, uint64_t *n) {
67   char *endptr = NULL;
68
69   assert(s != NULL);
70   assert(n != NULL);
71
72   *n = strtoull(s, &endptr, 0);
73
74   if (!(*s != '\0' && *endptr == '\0')) {
75     DEBUG(RDT_PLUGIN ": Error converting '%s' to unsigned number.", s);
76     return (-EINVAL);
77   }
78
79   return (0);
80 }
81
82 /*
83  * NAME
84  *   strlisttonums
85  *
86  * DESCRIPTION
87  *   Converts string of characters representing list of numbers into array of
88  *   numbers. Allowed formats are:
89  *     0,1,2,3
90  *     0-10,20-18
91  *     1,3,5-8,10,0x10-12
92  *
93  *   Numbers can be in decimal or hexadecimal format.
94  *
95  * PARAMETERS
96  *   `s'         String representing list of unsigned numbers.
97  *   `nums'      Array to put converted numeric values into.
98  *   `max'       Maximum number of elements that nums can accommodate.
99  *
100  * RETURN VALUE
101  *    Number of elements placed into nums.
102  */
103 static size_t strlisttonums(char *s, uint64_t *nums, size_t max) {
104   int ret;
105   size_t index = 0;
106   char *saveptr = NULL;
107
108   if (s == NULL || nums == NULL || max == 0)
109     return index;
110
111   for (;;) {
112     char *p = NULL;
113     char *token = NULL;
114
115     token = strtok_r(s, ",", &saveptr);
116     if (token == NULL)
117       break;
118
119     s = NULL;
120
121     while (isspace(*token))
122       token++;
123     if (*token == '\0')
124       continue;
125
126     p = strchr(token, '-');
127     if (p != NULL) {
128       uint64_t n, start, end;
129       *p = '\0';
130       ret = strtouint64(token, &start);
131       if (ret < 0)
132         return (0);
133       ret = strtouint64(p + 1, &end);
134       if (ret < 0)
135         return (0);
136       if (start > end) {
137         return (0);
138       }
139       for (n = start; n <= end; n++) {
140         if (!(isdup(nums, index, n))) {
141           nums[index] = n;
142           index++;
143         }
144         if (index >= max)
145           return index;
146       }
147     } else {
148       uint64_t val;
149
150       ret = strtouint64(token, &val);
151       if (ret < 0)
152         return (0);
153
154       if (!(isdup(nums, index, val))) {
155         nums[index] = val;
156         index++;
157       }
158       if (index >= max)
159         return index;
160     }
161   }
162
163   return index;
164 }
165
166 /*
167  * NAME
168  *   cgroup_cmp
169  *
170  * DESCRIPTION
171  *   Function to compare cores in 2 core groups.
172  *
173  * PARAMETERS
174  *   `cg_a'      Pointer to core group a.
175  *   `cg_b'      Pointer to core group b.
176  *
177  * RETURN VALUE
178  *    1 if both groups contain the same cores
179  *    0 if none of their cores match
180  *    -1 if some but not all cores match
181  */
182 static int cgroup_cmp(const rdt_core_group_t *cg_a,
183                       const rdt_core_group_t *cg_b) {
184   int found = 0;
185
186   assert(cg_a != NULL);
187   assert(cg_b != NULL);
188
189   const int sz_a = cg_a->num_cores;
190   const int sz_b = cg_b->num_cores;
191   const unsigned *tab_a = cg_a->cores;
192   const unsigned *tab_b = cg_b->cores;
193
194   for (int i = 0; i < sz_a; i++) {
195     for (int j = 0; j < sz_b; j++)
196       if (tab_a[i] == tab_b[j])
197         found++;
198   }
199   /* if no cores are the same */
200   if (!found)
201     return 0;
202   /* if group contains same cores */
203   if (sz_a == sz_b && sz_b == found)
204     return 1;
205   /* if not all cores are the same */
206   return -1;
207 }
208
209 static int cgroup_set(rdt_core_group_t *cg, char *desc, uint64_t *cores,
210                       size_t num_cores) {
211   assert(cg != NULL);
212   assert(desc != NULL);
213   assert(cores != NULL);
214   assert(num_cores > 0);
215
216   cg->cores = calloc(num_cores, sizeof(unsigned));
217   if (cg->cores == NULL) {
218     ERROR(RDT_PLUGIN ": Error allocating core group table");
219     return (-ENOMEM);
220   }
221   cg->num_cores = num_cores;
222   cg->desc = strdup(desc);
223   if (cg->desc == NULL) {
224     ERROR(RDT_PLUGIN ": Error allocating core group description");
225     sfree(cg->cores);
226     return (-ENOMEM);
227   }
228
229   for (size_t i = 0; i < num_cores; i++)
230     cg->cores[i] = (unsigned)cores[i];
231
232   return 0;
233 }
234
235 /*
236  * NAME
237  *   oconfig_to_cgroups
238  *
239  * DESCRIPTION
240  *   Function to set the descriptions and cores for each core group.
241  *   Takes a config option containing list of strings that are used to set
242  *   core group values.
243  *
244  * PARAMETERS
245  *   `item'        Config option containing core groups.
246  *   `groups'      Table of core groups to set values in.
247  *   `max_groups'  Maximum number of core groups allowed.
248  *   `max_core'    Maximum allowed core value.
249  *
250  * RETURN VALUE
251  *   On success, the number of core groups set up. On error, appropriate
252  *   negative error value.
253  */
254 static int oconfig_to_cgroups(oconfig_item_t *item, rdt_core_group_t *groups,
255                               size_t max_groups, uint64_t max_core) {
256   int index = 0;
257
258   assert(groups != NULL);
259   assert(max_groups > 0);
260   assert(item != NULL);
261
262   for (int j = 0; j < item->values_num; j++) {
263     int ret;
264     size_t n;
265     uint64_t cores[RDT_MAX_CORES] = {0};
266     char value[DATA_MAX_NAME_LEN];
267
268     if ((item->values[j].value.string == NULL) || (strlen(item->values[j].value.string) == 0))
269       continue;
270
271     sstrncpy(value, item->values[j].value.string, sizeof(value));
272
273     n = strlisttonums(value, cores, STATIC_ARRAY_SIZE(cores));
274     if (n == 0) {
275       ERROR(RDT_PLUGIN ": Error parsing core group (%s)",
276             item->values[j].value.string);
277       return (-EINVAL);
278     }
279
280     for (int i = 0; i < n; i++) {
281       if (cores[i] > max_core) {
282         ERROR(RDT_PLUGIN ": Core group (%s) contains invalid core id (%d)",
283               item->values[j].value.string, (int)cores[i]);
284         return (-EINVAL);
285       }
286     }
287
288     /* set core group info */
289     ret = cgroup_set(&groups[index], item->values[j].value.string, cores, n);
290     if (ret < 0)
291       return ret;
292
293     index++;
294
295     if (index >= max_groups) {
296       WARNING(RDT_PLUGIN ": Too many core groups configured");
297       return index;
298     }
299   }
300
301   return index;
302 }
303
304 #if COLLECT_DEBUG
305 static void rdt_dump_cgroups(void) {
306   char cores[RDT_MAX_CORES * 4];
307
308   if (g_rdt == NULL)
309     return;
310
311   DEBUG(RDT_PLUGIN ": Core Groups Dump");
312   DEBUG(RDT_PLUGIN ":  groups count: %zu", g_rdt->num_groups);
313
314   for (int i = 0; i < g_rdt->num_groups; i++) {
315
316     memset(cores, 0, sizeof(cores));
317     for (int j = 0; j < g_rdt->cgroups[i].num_cores; j++) {
318       snprintf(cores + strlen(cores), sizeof(cores) - strlen(cores) - 1, " %d",
319                g_rdt->cgroups[i].cores[j]);
320     }
321
322     DEBUG(RDT_PLUGIN ":  group[%d]:", i);
323     DEBUG(RDT_PLUGIN ":    description: %s", g_rdt->cgroups[i].desc);
324     DEBUG(RDT_PLUGIN ":    cores: %s", cores);
325     DEBUG(RDT_PLUGIN ":    events: 0x%X", g_rdt->cgroups[i].events);
326   }
327
328   return;
329 }
330
331 static inline double bytes_to_kb(const double bytes) { return bytes / 1024.0; }
332
333 static inline double bytes_to_mb(const double bytes) {
334   return bytes / (1024.0 * 1024.0);
335 }
336
337 static void rdt_dump_data(void) {
338   /*
339    * CORE - monitored group of cores
340    * RMID - Resource Monitoring ID associated with the monitored group
341    * LLC - last level cache occupancy
342    * MBL - local memory bandwidth
343    * MBR - remote memory bandwidth
344    */
345   DEBUG("  CORE     RMID    LLC[KB]   MBL[MB]    MBR[MB]");
346   for (int i = 0; i < g_rdt->num_groups; i++) {
347
348     const struct pqos_event_values *pv = &g_rdt->pgroups[i]->values;
349
350     double llc = bytes_to_kb(pv->llc);
351     double mbr = bytes_to_mb(pv->mbm_remote_delta);
352     double mbl = bytes_to_mb(pv->mbm_local_delta);
353
354     DEBUG(" [%s] %8u %10.1f %10.1f %10.1f", g_rdt->cgroups[i].desc,
355           g_rdt->pgroups[i]->poll_ctx[0].rmid, llc, mbl, mbr);
356   }
357 }
358 #endif /* COLLECT_DEBUG */
359
360 static void rdt_free_cgroups(void) {
361   for (int i = 0; i < RDT_MAX_CORES; i++) {
362     sfree(g_rdt->cgroups[i].desc);
363
364     sfree(g_rdt->cgroups[i].cores);
365     g_rdt->cgroups[i].num_cores = 0;
366
367     sfree(g_rdt->pgroups[i]);
368   }
369 }
370
371 static int rdt_default_cgroups(void) {
372   int ret;
373
374   /* configure each core in separate group */
375   for (unsigned i = 0; i < g_rdt->pqos_cpu->num_cores; i++) {
376     char desc[DATA_MAX_NAME_LEN];
377     uint64_t core = i;
378
379     ssnprintf(desc, sizeof(desc), "%d", g_rdt->pqos_cpu->cores[i].lcore);
380
381     /* set core group info */
382     ret = cgroup_set(&g_rdt->cgroups[i], desc, &core, 1);
383     if (ret < 0)
384       return ret;
385   }
386
387   return g_rdt->pqos_cpu->num_cores;
388 }
389
390 static int rdt_config_cgroups(oconfig_item_t *item) {
391   int n = 0;
392   enum pqos_mon_event events = 0;
393
394   if (item == NULL) {
395     DEBUG(RDT_PLUGIN ": cgroups_config: Invalid argument.");
396     return (-EINVAL);
397   }
398
399   DEBUG(RDT_PLUGIN ": Core groups [%d]:", item->values_num);
400   for (int j = 0; j < item->values_num; j++) {
401     if (item->values[j].type != OCONFIG_TYPE_STRING) {
402       ERROR(RDT_PLUGIN ": given core group value is not a string [idx=%d]",
403             j);
404       return (-EINVAL);
405     }
406     DEBUG(RDT_PLUGIN ":  [%d]: %s", j, item->values[j].value.string);
407   }
408
409   n = oconfig_to_cgroups(item, g_rdt->cgroups, RDT_MAX_CORES,
410                          g_rdt->pqos_cpu->num_cores-1);
411   if (n < 0) {
412     rdt_free_cgroups();
413     ERROR(RDT_PLUGIN ": Error parsing core groups configuration.");
414     return (-EINVAL);
415   }
416
417   if (n == 0) {
418     /* create default core groups if "Cores" config option is empty */
419     n = rdt_default_cgroups();
420     if (n < 0) {
421       rdt_free_cgroups();
422       ERROR(RDT_PLUGIN
423             ": Error creating default core groups configuration.");
424       return n;
425     }
426     INFO(RDT_PLUGIN
427          ": No core groups configured. Default core groups created.");
428   }
429
430   /* Get all available events on this platform */
431   for (int i = 0; i < g_rdt->cap_mon->u.mon->num_events; i++)
432     events |= g_rdt->cap_mon->u.mon->events[i].type;
433
434   events &= ~(PQOS_PERF_EVENT_LLC_MISS);
435
436   DEBUG(RDT_PLUGIN ": Number of cores in the system: %u",
437         g_rdt->pqos_cpu->num_cores);
438   DEBUG(RDT_PLUGIN ": Available events to monitor: %#x", events);
439
440   g_rdt->num_groups = n;
441   for (int i = 0; i < n; i++) {
442     for (int j = 0; j < i; j++) {
443       int found = 0;
444       found = cgroup_cmp(&g_rdt->cgroups[j], &g_rdt->cgroups[i]);
445       if (found != 0) {
446         rdt_free_cgroups();
447         ERROR(RDT_PLUGIN ": Cannot monitor same cores in different groups.");
448         return (-EINVAL);
449       }
450     }
451
452     g_rdt->cgroups[i].events = events;
453     g_rdt->pgroups[i] = calloc(1, sizeof(*g_rdt->pgroups[i]));
454     if (g_rdt->pgroups[i] == NULL) {
455       rdt_free_cgroups();
456       ERROR(RDT_PLUGIN ": Failed to allocate memory for monitoring data.");
457       return (-ENOMEM);
458     }
459   }
460
461   return (0);
462 }
463
464 static int rdt_preinit(void) {
465   int ret;
466
467   if (g_rdt != NULL) {
468     /* already initialized if config callback was called before init callback */
469     return (0);
470   }
471
472   g_rdt = calloc(1, sizeof(*g_rdt));
473   if (g_rdt == NULL) {
474     ERROR(RDT_PLUGIN ": Failed to allocate memory for rdt context.");
475     return (-ENOMEM);
476   }
477
478   /* In case previous instance of the application was not closed properly
479    * call fini and ignore return code. */
480   pqos_fini();
481
482   /* TODO:
483    * stdout should not be used here. Will be reworked when support of log
484    * callback is added to PQoS library.
485   */
486   ret = pqos_init(&(struct pqos_config){.fd_log = STDOUT_FILENO});
487   if (ret != PQOS_RETVAL_OK) {
488     ERROR(RDT_PLUGIN ": Error initializing PQoS library!");
489     goto rdt_preinit_error1;
490   }
491
492   ret = pqos_cap_get(&g_rdt->pqos_cap, &g_rdt->pqos_cpu);
493   if (ret != PQOS_RETVAL_OK) {
494     ERROR(RDT_PLUGIN ": Error retrieving PQoS capabilities.");
495     goto rdt_preinit_error2;
496   }
497
498   ret = pqos_cap_get_type(g_rdt->pqos_cap, PQOS_CAP_TYPE_MON,
499                           &g_rdt->cap_mon);
500   if (ret == PQOS_RETVAL_PARAM) {
501     ERROR(RDT_PLUGIN ": Error retrieving monitoring capabilities.");
502     goto rdt_preinit_error2;
503   }
504
505   if (g_rdt->cap_mon == NULL) {
506     ERROR(
507         RDT_PLUGIN
508         ": Monitoring capability not detected. Nothing to do for the plugin.");
509     goto rdt_preinit_error2;
510   }
511
512   return (0);
513
514 rdt_preinit_error2:
515   pqos_fini();
516
517 rdt_preinit_error1:
518
519   sfree(g_rdt);
520
521   return (-1);
522 }
523
524 static int rdt_config(oconfig_item_t *ci) {
525   int ret = 0;
526
527   ret = rdt_preinit();
528   if (ret != 0)
529     return ret;
530
531   for (int i = 0; i < ci->children_num; i++) {
532     oconfig_item_t *child = ci->children + i;
533
534     if (strcasecmp("Cores", child->key) == 0) {
535
536       ret = rdt_config_cgroups(child);
537       if (ret != 0)
538         return ret;
539
540 #if COLLECT_DEBUG
541       rdt_dump_cgroups();
542 #endif /* COLLECT_DEBUG */
543
544     } else {
545       ERROR(RDT_PLUGIN ": Unknown configuration parameter \"%s\".",
546             child->key);
547     }
548   }
549
550   return (0);
551 }
552
553 static void rdt_submit_derive(char *cgroup, char *type, char *type_instance,
554                                 derive_t value) {
555   value_list_t vl = VALUE_LIST_INIT;
556
557   vl.values = &(value_t) { .derive = value };
558   vl.values_len = 1;
559
560   sstrncpy(vl.plugin, RDT_PLUGIN, sizeof(vl.plugin));
561   snprintf(vl.plugin_instance, sizeof(vl.plugin_instance), "%s", cgroup);
562   sstrncpy(vl.type, type, sizeof(vl.type));
563   if (type_instance)
564     sstrncpy(vl.type_instance, type_instance, sizeof(vl.type_instance));
565
566   plugin_dispatch_values(&vl);
567 }
568
569 static void rdt_submit_gauge(char *cgroup, char *type, char *type_instance,
570                                 gauge_t value) {
571   value_list_t vl = VALUE_LIST_INIT;
572
573   vl.values = &(value_t) { .gauge = value };
574   vl.values_len = 1;
575
576   sstrncpy(vl.plugin, RDT_PLUGIN, sizeof(vl.plugin));
577   snprintf(vl.plugin_instance, sizeof(vl.plugin_instance), "%s", cgroup);
578   sstrncpy(vl.type, type, sizeof(vl.type));
579   if (type_instance)
580     sstrncpy(vl.type_instance, type_instance, sizeof(vl.type_instance));
581
582   plugin_dispatch_values(&vl);
583 }
584
585 static int rdt_read(__attribute__((unused)) user_data_t *ud) {
586   int ret;
587
588   if (g_rdt == NULL) {
589     ERROR(RDT_PLUGIN ": rdt_read: plugin not initialized.");
590     return (-EINVAL);
591   }
592
593   ret = pqos_mon_poll(&g_rdt->pgroups[0], (unsigned)g_rdt->num_groups);
594   if (ret != PQOS_RETVAL_OK) {
595     ERROR(RDT_PLUGIN ": Failed to poll monitoring data.");
596     return (-1);
597   }
598
599 #if COLLECT_DEBUG
600   rdt_dump_data();
601 #endif /* COLLECT_DEBUG */
602
603   for (int i = 0; i < g_rdt->num_groups; i++) {
604     enum pqos_mon_event mbm_events =
605         (PQOS_MON_EVENT_LMEM_BW | PQOS_MON_EVENT_TMEM_BW |
606          PQOS_MON_EVENT_RMEM_BW);
607
608     const struct pqos_event_values *pv = &g_rdt->pgroups[i]->values;
609
610     /* Submit only monitored events data */
611
612     if (g_rdt->cgroups[i].events & PQOS_MON_EVENT_L3_OCCUP)
613       rdt_submit_gauge(g_rdt->cgroups[i].desc, "bytes", "llc", pv->llc);
614
615     if (g_rdt->cgroups[i].events & PQOS_PERF_EVENT_IPC)
616       rdt_submit_gauge(g_rdt->cgroups[i].desc, "ipc", NULL, pv->ipc);
617
618     if (g_rdt->cgroups[i].events & mbm_events) {
619       rdt_submit_derive(g_rdt->cgroups[i].desc, "memory_bandwidth",
620                            "local", pv->mbm_local_delta);
621       rdt_submit_derive(g_rdt->cgroups[i].desc, "memory_bandwidth",
622                            "remote", pv->mbm_remote_delta);
623     }
624   }
625
626   return (0);
627 }
628
629 static int rdt_init(void) {
630   int ret;
631
632   ret = rdt_preinit();
633   if (ret != 0)
634     return ret;
635
636   /* Start monitoring */
637   for (int i = 0; i < g_rdt->num_groups; i++) {
638     rdt_core_group_t *cg = &g_rdt->cgroups[i];
639
640     ret = pqos_mon_start(cg->num_cores, cg->cores, cg->events, (void *)cg->desc,
641                          g_rdt->pgroups[i]);
642
643     if (ret != PQOS_RETVAL_OK)
644       ERROR(RDT_PLUGIN ": Error starting monitoring group %s (pqos status=%d)",
645             cg->desc, ret);
646   }
647
648   return (0);
649 }
650
651 static int rdt_shutdown(void) {
652   int ret;
653
654   DEBUG(RDT_PLUGIN ": rdt_shutdown.");
655
656   if (g_rdt == NULL)
657     return (0);
658
659   /* Stop monitoring */
660   for (int i = 0; i < g_rdt->num_groups; i++) {
661     pqos_mon_stop(g_rdt->pgroups[i]);
662   }
663
664   ret = pqos_fini();
665   if (ret != PQOS_RETVAL_OK)
666     ERROR(RDT_PLUGIN ": Error shutting down PQoS library.");
667
668   rdt_free_cgroups();
669   sfree(g_rdt);
670
671   return (0);
672 }
673
674 void module_register(void) {
675   plugin_register_init(RDT_PLUGIN, rdt_init);
676   plugin_register_complex_config(RDT_PLUGIN, rdt_config);
677   plugin_register_complex_read(NULL, RDT_PLUGIN, rdt_read, 0, NULL);
678   plugin_register_shutdown(RDT_PLUGIN, rdt_shutdown);
679 }