Auto-Merge pull request #2610 from rpv-tomsk/fix-2609
[collectd.git] / src / processes.c
1 /**
2  * collectd - src/processes.c
3  * Copyright (C) 2005       Lyonel Vincent
4  * Copyright (C) 2006-2017  Florian octo Forster
5  * Copyright (C) 2008       Oleg King
6  * Copyright (C) 2009       Sebastian Harl
7  * Copyright (C) 2009       Andrés J. Díaz
8  * Copyright (C) 2009       Manuel Sanmartin
9  * Copyright (C) 2010       Clément Stenac
10  * Copyright (C) 2012       Cosmin Ioiart
11  *
12  * This program is free software; you can redistribute it and/or modify it
13  * under the terms of the GNU General Public License as published by the
14  * Free Software Foundation; either version 2 of the License, or (at your
15  * option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful, but
18  * WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
20  * General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License along
23  * with this program; if not, write to the Free Software Foundation, Inc.,
24  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
25  *
26  * Authors:
27  *   Lyonel Vincent <lyonel at ezix.org>
28  *   Florian octo Forster <octo at collectd.org>
29  *   Oleg King <king2 at kaluga.ru>
30  *   Sebastian Harl <sh at tokkee.org>
31  *   Andrés J. Díaz <ajdiaz at connectical.com>
32  *   Manuel Sanmartin
33  *   Clément Stenac <clement.stenac at diwi.org>
34  *   Cosmin Ioiart <cioiart at gmail.com>
35  *   Pavel Rochnyack <pavel2000 at ngs.ru>
36  *   Wilfried Goesgens <dothebart at citadel.org>
37  **/
38
39 #include "collectd.h"
40
41 #include "common.h"
42 #include "plugin.h"
43
44 #if HAVE_LIBTASKSTATS
45 #include "utils_complain.h"
46 #include "utils_taskstats.h"
47 #endif
48
49 /* Include header files for the mach system, if they exist.. */
50 #if HAVE_THREAD_INFO
51 #if HAVE_MACH_MACH_INIT_H
52 #include <mach/mach_init.h>
53 #endif
54 #if HAVE_MACH_HOST_PRIV_H
55 #include <mach/host_priv.h>
56 #endif
57 #if HAVE_MACH_MACH_ERROR_H
58 #include <mach/mach_error.h>
59 #endif
60 #if HAVE_MACH_MACH_HOST_H
61 #include <mach/mach_host.h>
62 #endif
63 #if HAVE_MACH_MACH_PORT_H
64 #include <mach/mach_port.h>
65 #endif
66 #if HAVE_MACH_MACH_TYPES_H
67 #include <mach/mach_types.h>
68 #endif
69 #if HAVE_MACH_MESSAGE_H
70 #include <mach/message.h>
71 #endif
72 #if HAVE_MACH_PROCESSOR_SET_H
73 #include <mach/processor_set.h>
74 #endif
75 #if HAVE_MACH_TASK_H
76 #include <mach/task.h>
77 #endif
78 #if HAVE_MACH_THREAD_ACT_H
79 #include <mach/thread_act.h>
80 #endif
81 #if HAVE_MACH_VM_REGION_H
82 #include <mach/vm_region.h>
83 #endif
84 #if HAVE_MACH_VM_MAP_H
85 #include <mach/vm_map.h>
86 #endif
87 #if HAVE_MACH_VM_PROT_H
88 #include <mach/vm_prot.h>
89 #endif
90 #if HAVE_SYS_SYSCTL_H
91 #include <sys/sysctl.h>
92 #endif
93 /* #endif HAVE_THREAD_INFO */
94
95 #elif KERNEL_LINUX
96 #if HAVE_LINUX_CONFIG_H
97 #include <linux/config.h>
98 #endif
99 #ifndef CONFIG_HZ
100 #define CONFIG_HZ 100
101 #endif
102 /* #endif KERNEL_LINUX */
103
104 #elif HAVE_LIBKVM_GETPROCS &&                                                  \
105     (HAVE_STRUCT_KINFO_PROC_FREEBSD || HAVE_STRUCT_KINFO_PROC_OPENBSD)
106 #include <kvm.h>
107 #include <sys/param.h>
108 #include <sys/proc.h>
109 #include <sys/sysctl.h>
110 #include <sys/user.h>
111 /* #endif HAVE_LIBKVM_GETPROCS && (HAVE_STRUCT_KINFO_PROC_FREEBSD ||
112  * HAVE_STRUCT_KINFO_PROC_OPENBSD) */
113
114 #elif HAVE_PROCINFO_H
115 #include <procinfo.h>
116 #include <sys/types.h>
117
118 #define MAXPROCENTRY 32
119 #define MAXTHRDENTRY 16
120 #define MAXARGLN 1024
121 /* #endif HAVE_PROCINFO_H */
122
123 #elif KERNEL_SOLARIS
124 /* Hack: Avoid #error when building a 32-bit binary with
125  * _FILE_OFFSET_BITS=64. There is a reason for this #error, as one
126  * of the structures in <sys/procfs.h> uses an off_t, but that
127  * isn't relevant to our usage of procfs. */
128 #if !defined(_LP64) && _FILE_OFFSET_BITS == 64
129 #define SAVE_FOB_64
130 #undef _FILE_OFFSET_BITS
131 #endif
132
133 #include <procfs.h>
134
135 #ifdef SAVE_FOB_64
136 #define _FILE_OFFSET_BITS 64
137 #undef SAVE_FOB_64
138 #endif
139
140 #include <dirent.h>
141 #include <sys/user.h>
142
143 #ifndef MAXCOMLEN
144 #define MAXCOMLEN 16
145 #endif
146
147 /* #endif KERNEL_SOLARIS */
148
149 #else
150 #error "No applicable input method."
151 #endif
152
153 #if HAVE_REGEX_H
154 #include <regex.h>
155 #endif
156
157 #if HAVE_KSTAT_H
158 #include <kstat.h>
159 #endif
160
161 #ifdef HAVE_SYS_CAPABILITY_H
162 #include <sys/capability.h>
163 #endif
164
165 #ifndef CMDLINE_BUFFER_SIZE
166 #if defined(ARG_MAX) && (ARG_MAX < 4096)
167 #define CMDLINE_BUFFER_SIZE ARG_MAX
168 #else
169 #define CMDLINE_BUFFER_SIZE 4096
170 #endif
171 #endif
172
173 #define PROCSTAT_NAME_LEN 256
174 typedef struct process_entry_s {
175   unsigned long id;
176   char name[PROCSTAT_NAME_LEN];
177
178   unsigned long num_proc;
179   unsigned long num_lwp;
180   unsigned long num_fd;
181   unsigned long num_maps;
182   unsigned long vmem_size;
183   unsigned long vmem_rss;
184   unsigned long vmem_data;
185   unsigned long vmem_code;
186   unsigned long stack_size;
187
188   derive_t vmem_minflt_counter;
189   derive_t vmem_majflt_counter;
190
191   derive_t cpu_user_counter;
192   derive_t cpu_system_counter;
193
194   /* io data */
195   derive_t io_rchar;
196   derive_t io_wchar;
197   derive_t io_syscr;
198   derive_t io_syscw;
199   derive_t io_diskr;
200   derive_t io_diskw;
201   _Bool has_io;
202
203   derive_t cswitch_vol;
204   derive_t cswitch_invol;
205   _Bool has_cswitch;
206
207 #if HAVE_LIBTASKSTATS
208   ts_delay_t delay;
209 #endif
210   _Bool has_delay;
211
212   _Bool has_fd;
213
214   _Bool has_maps;
215 } process_entry_t;
216
217 typedef struct procstat_entry_s {
218   unsigned long id;
219   unsigned long age;
220
221   derive_t vmem_minflt_counter;
222   derive_t vmem_majflt_counter;
223
224   derive_t cpu_user_counter;
225   derive_t cpu_system_counter;
226
227   /* io data */
228   derive_t io_rchar;
229   derive_t io_wchar;
230   derive_t io_syscr;
231   derive_t io_syscw;
232   derive_t io_diskr;
233   derive_t io_diskw;
234
235   derive_t cswitch_vol;
236   derive_t cswitch_invol;
237
238 #if HAVE_LIBTASKSTATS
239   value_to_rate_state_t delay_cpu;
240   value_to_rate_state_t delay_blkio;
241   value_to_rate_state_t delay_swapin;
242   value_to_rate_state_t delay_freepages;
243 #endif
244
245   struct procstat_entry_s *next;
246 } procstat_entry_t;
247
248 typedef struct procstat {
249   char name[PROCSTAT_NAME_LEN];
250 #if HAVE_REGEX_H
251   regex_t *re;
252 #endif
253
254   unsigned long num_proc;
255   unsigned long num_lwp;
256   unsigned long num_fd;
257   unsigned long num_maps;
258   unsigned long vmem_size;
259   unsigned long vmem_rss;
260   unsigned long vmem_data;
261   unsigned long vmem_code;
262   unsigned long stack_size;
263
264   derive_t vmem_minflt_counter;
265   derive_t vmem_majflt_counter;
266
267   derive_t cpu_user_counter;
268   derive_t cpu_system_counter;
269
270   /* io data */
271   derive_t io_rchar;
272   derive_t io_wchar;
273   derive_t io_syscr;
274   derive_t io_syscw;
275   derive_t io_diskr;
276   derive_t io_diskw;
277
278   derive_t cswitch_vol;
279   derive_t cswitch_invol;
280
281   /* Linux Delay Accounting. Unit is ns/s. */
282   gauge_t delay_cpu;
283   gauge_t delay_blkio;
284   gauge_t delay_swapin;
285   gauge_t delay_freepages;
286
287   _Bool report_fd_num;
288   _Bool report_maps_num;
289   _Bool report_ctx_switch;
290   _Bool report_delay;
291
292   struct procstat *next;
293   struct procstat_entry_s *instances;
294 } procstat_t;
295
296 static procstat_t *list_head_g = NULL;
297
298 static _Bool want_init = 1;
299 static _Bool report_ctx_switch = 0;
300 static _Bool report_fd_num = 0;
301 static _Bool report_maps_num = 0;
302 static _Bool report_delay = 0;
303
304 #if HAVE_THREAD_INFO
305 static mach_port_t port_host_self;
306 static mach_port_t port_task_self;
307
308 static processor_set_name_array_t pset_list;
309 static mach_msg_type_number_t pset_list_len;
310 /* #endif HAVE_THREAD_INFO */
311
312 #elif KERNEL_LINUX
313 static long pagesize_g;
314 static void ps_fill_details(const procstat_t *ps, process_entry_t *entry);
315 /* #endif KERNEL_LINUX */
316
317 #elif HAVE_LIBKVM_GETPROCS &&                                                  \
318     (HAVE_STRUCT_KINFO_PROC_FREEBSD || HAVE_STRUCT_KINFO_PROC_OPENBSD)
319 static int pagesize;
320 /* #endif HAVE_LIBKVM_GETPROCS && (HAVE_STRUCT_KINFO_PROC_FREEBSD ||
321  * HAVE_STRUCT_KINFO_PROC_OPENBSD) */
322
323 #elif HAVE_PROCINFO_H
324 static struct procentry64 procentry[MAXPROCENTRY];
325 static struct thrdentry64 thrdentry[MAXTHRDENTRY];
326 static int pagesize;
327
328 #ifndef _AIXVERSION_610
329 int getprocs64(void *procsinfo, int sizproc, void *fdsinfo, int sizfd,
330                pid_t *index, int count);
331 int getthrds64(pid_t, void *, int, tid64_t *, int);
332 #endif
333 int getargs(void *processBuffer, int bufferLen, char *argsBuffer, int argsLen);
334 #endif /* HAVE_PROCINFO_H */
335
336 #if HAVE_LIBTASKSTATS
337 static ts_t *taskstats_handle = NULL;
338 #endif
339
340 /* put name of process from config to list_head_g tree
341  * list_head_g is a list of 'procstat_t' structs with
342  * processes names we want to watch */
343 static procstat_t *ps_list_register(const char *name, const char *regexp) {
344   procstat_t *new;
345   procstat_t *ptr;
346   int status;
347
348   new = calloc(1, sizeof(*new));
349   if (new == NULL) {
350     ERROR("processes plugin: ps_list_register: calloc failed.");
351     return NULL;
352   }
353   sstrncpy(new->name, name, sizeof(new->name));
354
355   new->io_rchar = -1;
356   new->io_wchar = -1;
357   new->io_syscr = -1;
358   new->io_syscw = -1;
359   new->io_diskr = -1;
360   new->io_diskw = -1;
361   new->cswitch_vol = -1;
362   new->cswitch_invol = -1;
363
364   new->report_fd_num = report_fd_num;
365   new->report_maps_num = report_maps_num;
366   new->report_ctx_switch = report_ctx_switch;
367   new->report_delay = report_delay;
368
369 #if HAVE_REGEX_H
370   if (regexp != NULL) {
371     DEBUG("ProcessMatch: adding \"%s\" as criteria to process %s.", regexp,
372           name);
373     new->re = malloc(sizeof(*new->re));
374     if (new->re == NULL) {
375       ERROR("processes plugin: ps_list_register: malloc failed.");
376       sfree(new);
377       return NULL;
378     }
379
380     status = regcomp(new->re, regexp, REG_EXTENDED | REG_NOSUB);
381     if (status != 0) {
382       DEBUG("ProcessMatch: compiling the regular expression \"%s\" failed.",
383             regexp);
384       sfree(new->re);
385       sfree(new);
386       return NULL;
387     }
388   }
389 #else
390   if (regexp != NULL) {
391     ERROR("processes plugin: ps_list_register: "
392           "Regular expression \"%s\" found in config "
393           "file, but support for regular expressions "
394           "has been disabled at compile time.",
395           regexp);
396     sfree(new);
397     return NULL;
398   }
399 #endif
400
401   for (ptr = list_head_g; ptr != NULL; ptr = ptr->next) {
402     if (strcmp(ptr->name, name) == 0) {
403       WARNING("processes plugin: You have configured more "
404               "than one `Process' or "
405               "`ProcessMatch' with the same name. "
406               "All but the first setting will be "
407               "ignored.");
408 #if HAVE_REGEX_H
409       sfree(new->re);
410 #endif
411       sfree(new);
412       return NULL;
413     }
414
415     if (ptr->next == NULL)
416       break;
417   }
418
419   if (ptr == NULL)
420     list_head_g = new;
421   else
422     ptr->next = new;
423
424   return new;
425 } /* void ps_list_register */
426
427 /* try to match name against entry, returns 1 if success */
428 static int ps_list_match(const char *name, const char *cmdline,
429                          procstat_t *ps) {
430 #if HAVE_REGEX_H
431   if (ps->re != NULL) {
432     int status;
433     const char *str;
434
435     str = cmdline;
436     if ((str == NULL) || (str[0] == 0))
437       str = name;
438
439     assert(str != NULL);
440
441     status = regexec(ps->re, str,
442                      /* nmatch = */ 0,
443                      /* pmatch = */ NULL,
444                      /* eflags = */ 0);
445     if (status == 0)
446       return 1;
447   } else
448 #endif
449       if (strcmp(ps->name, name) == 0)
450     return 1;
451
452   return 0;
453 } /* int ps_list_match */
454
455 static void ps_update_counter(derive_t *group_counter, derive_t *curr_counter,
456                               derive_t new_counter) {
457   unsigned long curr_value;
458
459   if (want_init) {
460     *curr_counter = new_counter;
461     return;
462   }
463
464   if (new_counter < *curr_counter)
465     curr_value = new_counter + (ULONG_MAX - *curr_counter);
466   else
467     curr_value = new_counter - *curr_counter;
468
469   if (*group_counter == -1)
470     *group_counter = 0;
471
472   *curr_counter = new_counter;
473   *group_counter += curr_value;
474 }
475
476 #if HAVE_LIBTASKSTATS
477 static void ps_update_delay_one(gauge_t *out_rate_sum,
478                                 value_to_rate_state_t *state, uint64_t cnt,
479                                 cdtime_t t) {
480   gauge_t rate = NAN;
481   int status = value_to_rate(&rate, (value_t){.counter = (counter_t)cnt},
482                              DS_TYPE_COUNTER, t, state);
483   if ((status != 0) || isnan(rate)) {
484     return;
485   }
486
487   if (isnan(*out_rate_sum)) {
488     *out_rate_sum = rate;
489   } else {
490     *out_rate_sum += rate;
491   }
492 }
493
494 static void ps_update_delay(procstat_t *out, procstat_entry_t *prev,
495                             process_entry_t *curr) {
496   cdtime_t now = cdtime();
497
498   ps_update_delay_one(&out->delay_cpu, &prev->delay_cpu, curr->delay.cpu_ns,
499                       now);
500   ps_update_delay_one(&out->delay_blkio, &prev->delay_blkio,
501                       curr->delay.blkio_ns, now);
502   ps_update_delay_one(&out->delay_swapin, &prev->delay_swapin,
503                       curr->delay.swapin_ns, now);
504   ps_update_delay_one(&out->delay_freepages, &prev->delay_freepages,
505                       curr->delay.freepages_ns, now);
506 }
507 #endif
508
509 /* add process entry to 'instances' of process 'name' (or refresh it) */
510 static void ps_list_add(const char *name, const char *cmdline,
511                         process_entry_t *entry) {
512   procstat_entry_t *pse;
513
514   if (entry->id == 0)
515     return;
516
517   for (procstat_t *ps = list_head_g; ps != NULL; ps = ps->next) {
518     if ((ps_list_match(name, cmdline, ps)) == 0)
519       continue;
520
521 #if KERNEL_LINUX
522     ps_fill_details(ps, entry);
523 #endif
524
525     for (pse = ps->instances; pse != NULL; pse = pse->next)
526       if ((pse->id == entry->id) || (pse->next == NULL))
527         break;
528
529     if ((pse == NULL) || (pse->id != entry->id)) {
530       procstat_entry_t *new;
531
532       new = calloc(1, sizeof(*new));
533       if (new == NULL)
534         return;
535       new->id = entry->id;
536
537       if (pse == NULL)
538         ps->instances = new;
539       else
540         pse->next = new;
541
542       pse = new;
543     }
544
545     pse->age = 0;
546
547     ps->num_proc += entry->num_proc;
548     ps->num_lwp += entry->num_lwp;
549     ps->num_fd += entry->num_fd;
550     ps->num_maps += entry->num_maps;
551     ps->vmem_size += entry->vmem_size;
552     ps->vmem_rss += entry->vmem_rss;
553     ps->vmem_data += entry->vmem_data;
554     ps->vmem_code += entry->vmem_code;
555     ps->stack_size += entry->stack_size;
556
557     if ((entry->io_rchar != -1) && (entry->io_wchar != -1)) {
558       ps_update_counter(&ps->io_rchar, &pse->io_rchar, entry->io_rchar);
559       ps_update_counter(&ps->io_wchar, &pse->io_wchar, entry->io_wchar);
560     }
561
562     if ((entry->io_syscr != -1) && (entry->io_syscw != -1)) {
563       ps_update_counter(&ps->io_syscr, &pse->io_syscr, entry->io_syscr);
564       ps_update_counter(&ps->io_syscw, &pse->io_syscw, entry->io_syscw);
565     }
566
567     if ((entry->io_diskr != -1) && (entry->io_diskw != -1)) {
568       ps_update_counter(&ps->io_diskr, &pse->io_diskr, entry->io_diskr);
569       ps_update_counter(&ps->io_diskw, &pse->io_diskw, entry->io_diskw);
570     }
571
572     if ((entry->cswitch_vol != -1) && (entry->cswitch_invol != -1)) {
573       ps_update_counter(&ps->cswitch_vol, &pse->cswitch_vol,
574                         entry->cswitch_vol);
575       ps_update_counter(&ps->cswitch_invol, &pse->cswitch_invol,
576                         entry->cswitch_invol);
577     }
578
579     ps_update_counter(&ps->vmem_minflt_counter, &pse->vmem_minflt_counter,
580                       entry->vmem_minflt_counter);
581     ps_update_counter(&ps->vmem_majflt_counter, &pse->vmem_majflt_counter,
582                       entry->vmem_majflt_counter);
583
584     ps_update_counter(&ps->cpu_user_counter, &pse->cpu_user_counter,
585                       entry->cpu_user_counter);
586     ps_update_counter(&ps->cpu_system_counter, &pse->cpu_system_counter,
587                       entry->cpu_system_counter);
588
589 #if HAVE_LIBTASKSTATS
590     ps_update_delay(ps, pse, entry);
591 #endif
592   }
593 }
594
595 /* remove old entries from instances of processes in list_head_g */
596 static void ps_list_reset(void) {
597   procstat_entry_t *pse;
598   procstat_entry_t *pse_prev;
599
600   for (procstat_t *ps = list_head_g; ps != NULL; ps = ps->next) {
601     ps->num_proc = 0;
602     ps->num_lwp = 0;
603     ps->num_fd = 0;
604     ps->num_maps = 0;
605     ps->vmem_size = 0;
606     ps->vmem_rss = 0;
607     ps->vmem_data = 0;
608     ps->vmem_code = 0;
609     ps->stack_size = 0;
610
611     ps->delay_cpu = NAN;
612     ps->delay_blkio = NAN;
613     ps->delay_swapin = NAN;
614     ps->delay_freepages = NAN;
615
616     pse_prev = NULL;
617     pse = ps->instances;
618     while (pse != NULL) {
619       if (pse->age > 10) {
620         DEBUG("Removing this procstat entry cause it's too old: "
621               "id = %lu; name = %s;",
622               pse->id, ps->name);
623
624         if (pse_prev == NULL) {
625           ps->instances = pse->next;
626           free(pse);
627           pse = ps->instances;
628         } else {
629           pse_prev->next = pse->next;
630           free(pse);
631           pse = pse_prev->next;
632         }
633       } else {
634         pse->age++;
635         pse_prev = pse;
636         pse = pse->next;
637       }
638     } /* while (pse != NULL) */
639   }   /* for (ps = list_head_g; ps != NULL; ps = ps->next) */
640 }
641
642 static void ps_tune_instance(oconfig_item_t *ci, procstat_t *ps) {
643   for (int i = 0; i < ci->children_num; i++) {
644     oconfig_item_t *c = ci->children + i;
645
646     if (strcasecmp(c->key, "CollectContextSwitch") == 0)
647       cf_util_get_boolean(c, &ps->report_ctx_switch);
648     else if (strcasecmp(c->key, "CollectFileDescriptor") == 0)
649       cf_util_get_boolean(c, &ps->report_fd_num);
650     else if (strcasecmp(c->key, "CollectMemoryMaps") == 0)
651       cf_util_get_boolean(c, &ps->report_maps_num);
652     else if (strcasecmp(c->key, "CollectDelayAccounting") == 0) {
653 #if HAVE_LIBTASKSTATS
654       cf_util_get_boolean(c, &ps->report_delay);
655 #else
656       WARNING("processes plugin: The plugin has been compiled without support "
657               "for the \"CollectDelayAccounting\" option.");
658 #endif
659     } else {
660       ERROR("processes plugin: Option \"%s\" not allowed here.", c->key);
661     }
662   } /* for (ci->children) */
663 } /* void ps_tune_instance */
664
665 /* put all pre-defined 'Process' names from config to list_head_g tree */
666 static int ps_config(oconfig_item_t *ci) {
667 #if KERNEL_LINUX
668   const size_t max_procname_len = 15;
669 #elif KERNEL_SOLARIS || KERNEL_FREEBSD
670   const size_t max_procname_len = MAXCOMLEN - 1;
671 #endif
672
673   procstat_t *ps;
674
675   for (int i = 0; i < ci->children_num; ++i) {
676     oconfig_item_t *c = ci->children + i;
677
678     if (strcasecmp(c->key, "Process") == 0) {
679       if ((c->values_num != 1) || (OCONFIG_TYPE_STRING != c->values[0].type)) {
680         ERROR("processes plugin: `Process' expects exactly "
681               "one string argument (got %i).",
682               c->values_num);
683         continue;
684       }
685
686 #if KERNEL_LINUX || KERNEL_SOLARIS || KERNEL_FREEBSD
687       if (strlen(c->values[0].value.string) > max_procname_len) {
688         WARNING("processes plugin: this platform has a %zu character limit "
689                 "to process names. The `Process \"%s\"' option will "
690                 "not work as expected.",
691                 max_procname_len, c->values[0].value.string);
692       }
693 #endif
694
695       ps = ps_list_register(c->values[0].value.string, NULL);
696
697       if (c->children_num != 0 && ps != NULL)
698         ps_tune_instance(c, ps);
699     } else if (strcasecmp(c->key, "ProcessMatch") == 0) {
700       if ((c->values_num != 2) || (OCONFIG_TYPE_STRING != c->values[0].type) ||
701           (OCONFIG_TYPE_STRING != c->values[1].type)) {
702         ERROR("processes plugin: `ProcessMatch' needs exactly "
703               "two string arguments (got %i).",
704               c->values_num);
705         continue;
706       }
707
708       ps = ps_list_register(c->values[0].value.string,
709                             c->values[1].value.string);
710
711       if (c->children_num != 0 && ps != NULL)
712         ps_tune_instance(c, ps);
713     } else if (strcasecmp(c->key, "CollectContextSwitch") == 0) {
714       cf_util_get_boolean(c, &report_ctx_switch);
715     } else if (strcasecmp(c->key, "CollectFileDescriptor") == 0) {
716       cf_util_get_boolean(c, &report_fd_num);
717     } else if (strcasecmp(c->key, "CollectMemoryMaps") == 0) {
718       cf_util_get_boolean(c, &report_maps_num);
719     } else if (strcasecmp(c->key, "CollectDelayAccounting") == 0) {
720 #if HAVE_LIBTASKSTATS
721       cf_util_get_boolean(c, &report_delay);
722 #else
723       WARNING("processes plugin: The plugin has been compiled without support "
724               "for the \"CollectDelayAccounting\" option.");
725 #endif
726     } else {
727       ERROR("processes plugin: The `%s' configuration option is not "
728             "understood and will be ignored.",
729             c->key);
730       continue;
731     }
732   }
733
734   return 0;
735 }
736
737 static int ps_init(void) {
738 #if HAVE_THREAD_INFO
739   kern_return_t status;
740
741   port_host_self = mach_host_self();
742   port_task_self = mach_task_self();
743
744   if (pset_list != NULL) {
745     vm_deallocate(port_task_self, (vm_address_t)pset_list,
746                   pset_list_len * sizeof(processor_set_t));
747     pset_list = NULL;
748     pset_list_len = 0;
749   }
750
751   if ((status = host_processor_sets(port_host_self, &pset_list,
752                                     &pset_list_len)) != KERN_SUCCESS) {
753     ERROR("host_processor_sets failed: %s\n", mach_error_string(status));
754     pset_list = NULL;
755     pset_list_len = 0;
756     return -1;
757   }
758 /* #endif HAVE_THREAD_INFO */
759
760 #elif KERNEL_LINUX
761   pagesize_g = sysconf(_SC_PAGESIZE);
762   DEBUG("pagesize_g = %li; CONFIG_HZ = %i;", pagesize_g, CONFIG_HZ);
763
764 #if HAVE_LIBTASKSTATS
765   if (taskstats_handle == NULL) {
766     taskstats_handle = ts_create();
767     if (taskstats_handle == NULL) {
768       WARNING("processes plugin: Creating taskstats handle failed.");
769     }
770   }
771 #endif
772 /* #endif KERNEL_LINUX */
773
774 #elif HAVE_LIBKVM_GETPROCS &&                                                  \
775     (HAVE_STRUCT_KINFO_PROC_FREEBSD || HAVE_STRUCT_KINFO_PROC_OPENBSD)
776   pagesize = getpagesize();
777 /* #endif HAVE_LIBKVM_GETPROCS && (HAVE_STRUCT_KINFO_PROC_FREEBSD ||
778  * HAVE_STRUCT_KINFO_PROC_OPENBSD) */
779
780 #elif HAVE_PROCINFO_H
781   pagesize = getpagesize();
782 #endif /* HAVE_PROCINFO_H */
783
784   return 0;
785 } /* int ps_init */
786
787 /* submit global state (e.g.: qty of zombies, running, etc..) */
788 static void ps_submit_state(const char *state, double value) {
789   value_list_t vl = VALUE_LIST_INIT;
790
791   vl.values = &(value_t){.gauge = value};
792   vl.values_len = 1;
793   sstrncpy(vl.plugin, "processes", sizeof(vl.plugin));
794   sstrncpy(vl.plugin_instance, "", sizeof(vl.plugin_instance));
795   sstrncpy(vl.type, "ps_state", sizeof(vl.type));
796   sstrncpy(vl.type_instance, state, sizeof(vl.type_instance));
797
798   plugin_dispatch_values(&vl);
799 }
800
801 /* submit info about specific process (e.g.: memory taken, cpu usage, etc..) */
802 static void ps_submit_proc_list(procstat_t *ps) {
803   value_list_t vl = VALUE_LIST_INIT;
804   value_t values[2];
805
806   vl.values = values;
807   sstrncpy(vl.plugin, "processes", sizeof(vl.plugin));
808   sstrncpy(vl.plugin_instance, ps->name, sizeof(vl.plugin_instance));
809
810   sstrncpy(vl.type, "ps_vm", sizeof(vl.type));
811   vl.values[0].gauge = ps->vmem_size;
812   vl.values_len = 1;
813   plugin_dispatch_values(&vl);
814
815   sstrncpy(vl.type, "ps_rss", sizeof(vl.type));
816   vl.values[0].gauge = ps->vmem_rss;
817   vl.values_len = 1;
818   plugin_dispatch_values(&vl);
819
820   sstrncpy(vl.type, "ps_data", sizeof(vl.type));
821   vl.values[0].gauge = ps->vmem_data;
822   vl.values_len = 1;
823   plugin_dispatch_values(&vl);
824
825   sstrncpy(vl.type, "ps_code", sizeof(vl.type));
826   vl.values[0].gauge = ps->vmem_code;
827   vl.values_len = 1;
828   plugin_dispatch_values(&vl);
829
830   sstrncpy(vl.type, "ps_stacksize", sizeof(vl.type));
831   vl.values[0].gauge = ps->stack_size;
832   vl.values_len = 1;
833   plugin_dispatch_values(&vl);
834
835   sstrncpy(vl.type, "ps_cputime", sizeof(vl.type));
836   vl.values[0].derive = ps->cpu_user_counter;
837   vl.values[1].derive = ps->cpu_system_counter;
838   vl.values_len = 2;
839   plugin_dispatch_values(&vl);
840
841   sstrncpy(vl.type, "ps_count", sizeof(vl.type));
842   vl.values[0].gauge = ps->num_proc;
843   vl.values[1].gauge = ps->num_lwp;
844   vl.values_len = 2;
845   plugin_dispatch_values(&vl);
846
847   sstrncpy(vl.type, "ps_pagefaults", sizeof(vl.type));
848   vl.values[0].derive = ps->vmem_minflt_counter;
849   vl.values[1].derive = ps->vmem_majflt_counter;
850   vl.values_len = 2;
851   plugin_dispatch_values(&vl);
852
853   if ((ps->io_rchar != -1) && (ps->io_wchar != -1)) {
854     sstrncpy(vl.type, "io_octets", sizeof(vl.type));
855     vl.values[0].derive = ps->io_rchar;
856     vl.values[1].derive = ps->io_wchar;
857     vl.values_len = 2;
858     plugin_dispatch_values(&vl);
859   }
860
861   if ((ps->io_syscr != -1) && (ps->io_syscw != -1)) {
862     sstrncpy(vl.type, "io_ops", sizeof(vl.type));
863     vl.values[0].derive = ps->io_syscr;
864     vl.values[1].derive = ps->io_syscw;
865     vl.values_len = 2;
866     plugin_dispatch_values(&vl);
867   }
868
869   if ((ps->io_diskr != -1) && (ps->io_diskw != -1)) {
870     sstrncpy(vl.type, "disk_octets", sizeof(vl.type));
871     vl.values[0].derive = ps->io_diskr;
872     vl.values[1].derive = ps->io_diskw;
873     vl.values_len = 2;
874     plugin_dispatch_values(&vl);
875   }
876
877   if (ps->num_fd > 0) {
878     sstrncpy(vl.type, "file_handles", sizeof(vl.type));
879     vl.values[0].gauge = ps->num_fd;
880     vl.values_len = 1;
881     plugin_dispatch_values(&vl);
882   }
883
884   if (ps->num_maps > 0) {
885     sstrncpy(vl.type, "file_handles", sizeof(vl.type));
886     sstrncpy(vl.type_instance, "mapped", sizeof(vl.type_instance));
887     vl.values[0].gauge = ps->num_maps;
888     vl.values_len = 1;
889     plugin_dispatch_values(&vl);
890   }
891
892   if ((ps->cswitch_vol != -1) && (ps->cswitch_invol != -1)) {
893     sstrncpy(vl.type, "contextswitch", sizeof(vl.type));
894     sstrncpy(vl.type_instance, "voluntary", sizeof(vl.type_instance));
895     vl.values[0].derive = ps->cswitch_vol;
896     vl.values_len = 1;
897     plugin_dispatch_values(&vl);
898
899     sstrncpy(vl.type, "contextswitch", sizeof(vl.type));
900     sstrncpy(vl.type_instance, "involuntary", sizeof(vl.type_instance));
901     vl.values[0].derive = ps->cswitch_invol;
902     vl.values_len = 1;
903     plugin_dispatch_values(&vl);
904   }
905
906   /* The ps->delay_* metrics are in nanoseconds per second. Convert to seconds
907    * per second. */
908   gauge_t const delay_factor = 1000000000.0;
909
910   struct {
911     char *type_instance;
912     gauge_t rate_ns;
913   } delay_metrics[] = {
914       {"delay-cpu", ps->delay_cpu},
915       {"delay-blkio", ps->delay_blkio},
916       {"delay-swapin", ps->delay_swapin},
917       {"delay-freepages", ps->delay_freepages},
918   };
919   for (size_t i = 0; i < STATIC_ARRAY_SIZE(delay_metrics); i++) {
920     if (isnan(delay_metrics[i].rate_ns)) {
921       continue;
922     }
923     sstrncpy(vl.type, "delay_rate", sizeof(vl.type));
924     sstrncpy(vl.type_instance, delay_metrics[i].type_instance,
925              sizeof(vl.type_instance));
926     vl.values[0].gauge = delay_metrics[i].rate_ns * delay_factor;
927     vl.values_len = 1;
928     plugin_dispatch_values(&vl);
929   }
930
931   DEBUG(
932       "name = %s; num_proc = %lu; num_lwp = %lu; num_fd = %lu; num_maps = %lu; "
933       "vmem_size = %lu; vmem_rss = %lu; vmem_data = %lu; "
934       "vmem_code = %lu; "
935       "vmem_minflt_counter = %" PRIi64 "; vmem_majflt_counter = %" PRIi64 "; "
936       "cpu_user_counter = %" PRIi64 "; cpu_system_counter = %" PRIi64 "; "
937       "io_rchar = %" PRIi64 "; io_wchar = %" PRIi64 "; "
938       "io_syscr = %" PRIi64 "; io_syscw = %" PRIi64 "; "
939       "io_diskr = %" PRIi64 "; io_diskw = %" PRIi64 "; "
940       "cswitch_vol = %" PRIi64 "; cswitch_invol = %" PRIi64 "; "
941       "delay_cpu = %g; delay_blkio = %g; "
942       "delay_swapin = %g; delay_freepages = %g;",
943       ps->name, ps->num_proc, ps->num_lwp, ps->num_fd, ps->num_maps,
944       ps->vmem_size, ps->vmem_rss, ps->vmem_data, ps->vmem_code,
945       ps->vmem_minflt_counter, ps->vmem_majflt_counter, ps->cpu_user_counter,
946       ps->cpu_system_counter, ps->io_rchar, ps->io_wchar, ps->io_syscr,
947       ps->io_syscw, ps->io_diskr, ps->io_diskw, ps->cswitch_vol,
948       ps->cswitch_invol, ps->delay_cpu, ps->delay_blkio, ps->delay_swapin,
949       ps->delay_freepages);
950
951 } /* void ps_submit_proc_list */
952
953 #if KERNEL_LINUX || KERNEL_SOLARIS
954 static void ps_submit_fork_rate(derive_t value) {
955   value_list_t vl = VALUE_LIST_INIT;
956
957   vl.values = &(value_t){.derive = value};
958   vl.values_len = 1;
959   sstrncpy(vl.plugin, "processes", sizeof(vl.plugin));
960   sstrncpy(vl.plugin_instance, "", sizeof(vl.plugin_instance));
961   sstrncpy(vl.type, "fork_rate", sizeof(vl.type));
962   sstrncpy(vl.type_instance, "", sizeof(vl.type_instance));
963
964   plugin_dispatch_values(&vl);
965 }
966 #endif /* KERNEL_LINUX || KERNEL_SOLARIS*/
967
968 /* ------- additional functions for KERNEL_LINUX/HAVE_THREAD_INFO ------- */
969 #if KERNEL_LINUX
970 static int ps_read_tasks_status(process_entry_t *ps) {
971   char dirname[64];
972   DIR *dh;
973   char filename[64];
974   FILE *fh;
975   struct dirent *ent;
976   derive_t cswitch_vol = 0;
977   derive_t cswitch_invol = 0;
978   char buffer[1024];
979   char *fields[8];
980   int numfields;
981
982   snprintf(dirname, sizeof(dirname), "/proc/%li/task", ps->id);
983
984   if ((dh = opendir(dirname)) == NULL) {
985     DEBUG("Failed to open directory `%s'", dirname);
986     return -1;
987   }
988
989   while ((ent = readdir(dh)) != NULL) {
990     char *tpid;
991
992     if (!isdigit((int)ent->d_name[0]))
993       continue;
994
995     tpid = ent->d_name;
996
997     if (snprintf(filename, sizeof(filename), "/proc/%li/task/%s/status", ps->id,
998                  tpid) >= sizeof(filename)) {
999       DEBUG("Filename too long: `%s'", filename);
1000       continue;
1001     }
1002
1003     if ((fh = fopen(filename, "r")) == NULL) {
1004       DEBUG("Failed to open file `%s'", filename);
1005       continue;
1006     }
1007
1008     while (fgets(buffer, sizeof(buffer), fh) != NULL) {
1009       derive_t tmp;
1010       char *endptr;
1011
1012       if (strncmp(buffer, "voluntary_ctxt_switches", 23) != 0 &&
1013           strncmp(buffer, "nonvoluntary_ctxt_switches", 26) != 0)
1014         continue;
1015
1016       numfields = strsplit(buffer, fields, STATIC_ARRAY_SIZE(fields));
1017
1018       if (numfields < 2)
1019         continue;
1020
1021       errno = 0;
1022       endptr = NULL;
1023       tmp = (derive_t)strtoll(fields[1], &endptr, /* base = */ 10);
1024       if ((errno == 0) && (endptr != fields[1])) {
1025         if (strncmp(buffer, "voluntary_ctxt_switches", 23) == 0) {
1026           cswitch_vol += tmp;
1027         } else if (strncmp(buffer, "nonvoluntary_ctxt_switches", 26) == 0) {
1028           cswitch_invol += tmp;
1029         }
1030       }
1031     } /* while (fgets) */
1032
1033     if (fclose(fh)) {
1034       WARNING("processes: fclose: %s", STRERRNO);
1035     }
1036   }
1037   closedir(dh);
1038
1039   ps->cswitch_vol = cswitch_vol;
1040   ps->cswitch_invol = cswitch_invol;
1041
1042   return 0;
1043 } /* int *ps_read_tasks_status */
1044
1045 /* Read data from /proc/pid/status */
1046 static int ps_read_status(long pid, process_entry_t *ps) {
1047   FILE *fh;
1048   char buffer[1024];
1049   char filename[64];
1050   unsigned long lib = 0;
1051   unsigned long exe = 0;
1052   unsigned long data = 0;
1053   unsigned long threads = 0;
1054   char *fields[8];
1055   int numfields;
1056
1057   snprintf(filename, sizeof(filename), "/proc/%li/status", pid);
1058   if ((fh = fopen(filename, "r")) == NULL)
1059     return -1;
1060
1061   while (fgets(buffer, sizeof(buffer), fh) != NULL) {
1062     unsigned long tmp;
1063     char *endptr;
1064
1065     if (strncmp(buffer, "Vm", 2) != 0 && strncmp(buffer, "Threads", 7) != 0)
1066       continue;
1067
1068     numfields = strsplit(buffer, fields, STATIC_ARRAY_SIZE(fields));
1069
1070     if (numfields < 2)
1071       continue;
1072
1073     errno = 0;
1074     endptr = NULL;
1075     tmp = strtoul(fields[1], &endptr, /* base = */ 10);
1076     if ((errno == 0) && (endptr != fields[1])) {
1077       if (strncmp(buffer, "VmData", 6) == 0) {
1078         data = tmp;
1079       } else if (strncmp(buffer, "VmLib", 5) == 0) {
1080         lib = tmp;
1081       } else if (strncmp(buffer, "VmExe", 5) == 0) {
1082         exe = tmp;
1083       } else if (strncmp(buffer, "Threads", 7) == 0) {
1084         threads = tmp;
1085       }
1086     }
1087   } /* while (fgets) */
1088
1089   if (fclose(fh)) {
1090     WARNING("processes: fclose: %s", STRERRNO);
1091   }
1092
1093   ps->vmem_data = data * 1024;
1094   ps->vmem_code = (exe + lib) * 1024;
1095   if (threads != 0)
1096     ps->num_lwp = threads;
1097
1098   return 0;
1099 } /* int *ps_read_status */
1100
1101 static int ps_read_io(process_entry_t *ps) {
1102   FILE *fh;
1103   char buffer[1024];
1104   char filename[64];
1105
1106   char *fields[8];
1107   int numfields;
1108
1109   snprintf(filename, sizeof(filename), "/proc/%li/io", ps->id);
1110   if ((fh = fopen(filename, "r")) == NULL) {
1111     DEBUG("ps_read_io: Failed to open file `%s'", filename);
1112     return -1;
1113   }
1114
1115   while (fgets(buffer, sizeof(buffer), fh) != NULL) {
1116     derive_t *val = NULL;
1117     long long tmp;
1118     char *endptr;
1119
1120     if (strncasecmp(buffer, "rchar:", 6) == 0)
1121       val = &(ps->io_rchar);
1122     else if (strncasecmp(buffer, "wchar:", 6) == 0)
1123       val = &(ps->io_wchar);
1124     else if (strncasecmp(buffer, "syscr:", 6) == 0)
1125       val = &(ps->io_syscr);
1126     else if (strncasecmp(buffer, "syscw:", 6) == 0)
1127       val = &(ps->io_syscw);
1128     else if (strncasecmp(buffer, "read_bytes:", 11) == 0)
1129       val = &(ps->io_diskr);
1130     else if (strncasecmp(buffer, "write_bytes:", 12) == 0)
1131       val = &(ps->io_diskw);
1132     else
1133       continue;
1134
1135     numfields = strsplit(buffer, fields, STATIC_ARRAY_SIZE(fields));
1136
1137     if (numfields < 2)
1138       continue;
1139
1140     errno = 0;
1141     endptr = NULL;
1142     tmp = strtoll(fields[1], &endptr, /* base = */ 10);
1143     if ((errno != 0) || (endptr == fields[1]))
1144       *val = -1;
1145     else
1146       *val = (derive_t)tmp;
1147   } /* while (fgets) */
1148
1149   if (fclose(fh)) {
1150     WARNING("processes: fclose: %s", STRERRNO);
1151   }
1152   return 0;
1153 } /* int ps_read_io (...) */
1154
1155 static int ps_count_maps(pid_t pid) {
1156   FILE *fh;
1157   char buffer[1024];
1158   char filename[64];
1159   int count = 0;
1160
1161   snprintf(filename, sizeof(filename), "/proc/%d/maps", pid);
1162   if ((fh = fopen(filename, "r")) == NULL) {
1163     DEBUG("ps_count_maps: Failed to open file `%s'", filename);
1164     return -1;
1165   }
1166
1167   while (fgets(buffer, sizeof(buffer), fh) != NULL) {
1168     if (strchr(buffer, '\n')) {
1169       count++;
1170     }
1171   } /* while (fgets) */
1172
1173   if (fclose(fh)) {
1174     WARNING("processes: fclose: %s", STRERRNO);
1175   }
1176   return count;
1177 } /* int ps_count_maps (...) */
1178
1179 static int ps_count_fd(int pid) {
1180   char dirname[64];
1181   DIR *dh;
1182   struct dirent *ent;
1183   int count = 0;
1184
1185   snprintf(dirname, sizeof(dirname), "/proc/%i/fd", pid);
1186
1187   if ((dh = opendir(dirname)) == NULL) {
1188     DEBUG("Failed to open directory `%s'", dirname);
1189     return -1;
1190   }
1191   while ((ent = readdir(dh)) != NULL) {
1192     if (!isdigit((int)ent->d_name[0]))
1193       continue;
1194     else
1195       count++;
1196   }
1197   closedir(dh);
1198
1199   return (count >= 1) ? count : 1;
1200 } /* int ps_count_fd (pid) */
1201
1202 #if HAVE_LIBTASKSTATS
1203 static int ps_delay(process_entry_t *ps) {
1204   if (taskstats_handle == NULL) {
1205     return ENOTCONN;
1206   }
1207
1208   int status = ts_delay_by_tgid(taskstats_handle, (uint32_t)ps->id, &ps->delay);
1209   if (status == EPERM) {
1210     static c_complain_t c;
1211 #if defined(HAVE_SYS_CAPABILITY_H) && defined(CAP_NET_ADMIN)
1212     if (check_capability(CAP_NET_ADMIN) != 0) {
1213       if (getuid() == 0) {
1214         c_complain(
1215             LOG_ERR, &c,
1216             "processes plugin: Reading Delay Accounting metric failed: %s. "
1217             "collectd is running as root, but missing the CAP_NET_ADMIN "
1218             "capability. The most common cause for this is that the init "
1219             "system is dropping capabilities.",
1220             STRERROR(status));
1221       } else {
1222         c_complain(
1223             LOG_ERR, &c,
1224             "processes plugin: Reading Delay Accounting metric failed: %s. "
1225             "collectd is not running as root and missing the CAP_NET_ADMIN "
1226             "capability. Either run collectd as root or grant it the "
1227             "CAP_NET_ADMIN capability using \"setcap cap_net_admin=ep " PREFIX
1228             "/sbin/collectd\".",
1229             STRERROR(status));
1230       }
1231     } else {
1232       ERROR("processes plugin: ts_delay_by_tgid failed: %s. The CAP_NET_ADMIN "
1233             "capability is available (I checked), so this error is utterly "
1234             "unexpected.",
1235             STRERROR(status));
1236     }
1237 #else
1238     c_complain(LOG_ERR, &c,
1239                "processes plugin: Reading Delay Accounting metric failed: %s. "
1240                "Reading Delay Accounting metrics requires root privileges.",
1241                STRERROR(status));
1242 #endif
1243     return status;
1244   } else if (status != 0) {
1245     ERROR("processes plugin: ts_delay_by_tgid failed: %s", STRERROR(status));
1246     return status;
1247   }
1248
1249   return 0;
1250 }
1251 #endif
1252
1253 static void ps_fill_details(const procstat_t *ps, process_entry_t *entry) {
1254   if (entry->has_io == 0) {
1255     ps_read_io(entry);
1256     entry->has_io = 1;
1257   }
1258
1259   if (ps->report_ctx_switch) {
1260     if (entry->has_cswitch == 0) {
1261       ps_read_tasks_status(entry);
1262       entry->has_cswitch = 1;
1263     }
1264   }
1265
1266   if (ps->report_maps_num) {
1267     int num_maps;
1268     if (entry->has_maps == 0 && (num_maps = ps_count_maps(entry->id)) > 0) {
1269       entry->num_maps = num_maps;
1270     }
1271     entry->has_maps = 1;
1272   }
1273
1274   if (ps->report_fd_num) {
1275     int num_fd;
1276     if (entry->has_fd == 0 && (num_fd = ps_count_fd(entry->id)) > 0) {
1277       entry->num_fd = num_fd;
1278     }
1279     entry->has_fd = 1;
1280   }
1281
1282 #if HAVE_LIBTASKSTATS
1283   if (ps->report_delay && !entry->has_delay) {
1284     if (ps_delay(entry) == 0) {
1285       entry->has_delay = 1;
1286     }
1287   }
1288 #endif
1289 } /* void ps_fill_details (...) */
1290
1291 /* ps_read_process reads process counters on Linux. */
1292 static int ps_read_process(long pid, process_entry_t *ps, char *state) {
1293   char filename[64];
1294   char buffer[1024];
1295
1296   char *fields[64];
1297   char fields_len;
1298
1299   size_t buffer_len;
1300
1301   char *buffer_ptr;
1302   size_t name_start_pos;
1303   size_t name_end_pos;
1304   size_t name_len;
1305
1306   derive_t cpu_user_counter;
1307   derive_t cpu_system_counter;
1308   long long unsigned vmem_size;
1309   long long unsigned vmem_rss;
1310   long long unsigned stack_size;
1311
1312   ssize_t status;
1313
1314   snprintf(filename, sizeof(filename), "/proc/%li/stat", pid);
1315
1316   status = read_file_contents(filename, buffer, sizeof(buffer) - 1);
1317   if (status <= 0)
1318     return -1;
1319   buffer_len = (size_t)status;
1320   buffer[buffer_len] = 0;
1321
1322   /* The name of the process is enclosed in parens. Since the name can
1323    * contain parens itself, spaces, numbers and pretty much everything
1324    * else, use these to determine the process name. We don't use
1325    * strchr(3) and strrchr(3) to avoid pointer arithmetic which would
1326    * otherwise be required to determine name_len. */
1327   name_start_pos = 0;
1328   while (name_start_pos < buffer_len && buffer[name_start_pos] != '(')
1329     name_start_pos++;
1330
1331   name_end_pos = buffer_len;
1332   while (name_end_pos > 0 && buffer[name_end_pos] != ')')
1333     name_end_pos--;
1334
1335   /* Either '(' or ')' is not found or they are in the wrong order.
1336    * Anyway, something weird that shouldn't happen ever. */
1337   if (name_start_pos >= name_end_pos) {
1338     ERROR("processes plugin: name_start_pos = %zu >= name_end_pos = %zu",
1339           name_start_pos, name_end_pos);
1340     return -1;
1341   }
1342
1343   name_len = (name_end_pos - name_start_pos) - 1;
1344   if (name_len >= sizeof(ps->name))
1345     name_len = sizeof(ps->name) - 1;
1346
1347   sstrncpy(ps->name, &buffer[name_start_pos + 1], name_len + 1);
1348
1349   if ((buffer_len - name_end_pos) < 2)
1350     return -1;
1351   buffer_ptr = &buffer[name_end_pos + 2];
1352
1353   fields_len = strsplit(buffer_ptr, fields, STATIC_ARRAY_SIZE(fields));
1354   if (fields_len < 22) {
1355     DEBUG("processes plugin: ps_read_process (pid = %li):"
1356           " `%s' has only %i fields..",
1357           pid, filename, fields_len);
1358     return -1;
1359   }
1360
1361   *state = fields[0][0];
1362
1363   if (*state == 'Z') {
1364     ps->num_lwp = 0;
1365     ps->num_proc = 0;
1366   } else {
1367     ps->num_lwp = strtoul(fields[17], /* endptr = */ NULL, /* base = */ 10);
1368     if ((ps_read_status(pid, ps)) != 0) {
1369       /* No VMem data */
1370       ps->vmem_data = -1;
1371       ps->vmem_code = -1;
1372       DEBUG("ps_read_process: did not get vmem data for pid %li", pid);
1373     }
1374     if (ps->num_lwp == 0)
1375       ps->num_lwp = 1;
1376     ps->num_proc = 1;
1377   }
1378
1379   /* Leave the rest at zero if this is only a zombi */
1380   if (ps->num_proc == 0) {
1381     DEBUG("processes plugin: This is only a zombie: pid = %li; "
1382           "name = %s;",
1383           pid, ps->name);
1384     return 0;
1385   }
1386
1387   cpu_user_counter = atoll(fields[11]);
1388   cpu_system_counter = atoll(fields[12]);
1389   vmem_size = atoll(fields[20]);
1390   vmem_rss = atoll(fields[21]);
1391   ps->vmem_minflt_counter = atol(fields[7]);
1392   ps->vmem_majflt_counter = atol(fields[9]);
1393
1394   {
1395     unsigned long long stack_start = atoll(fields[25]);
1396     unsigned long long stack_ptr = atoll(fields[26]);
1397
1398     stack_size = (stack_start > stack_ptr) ? stack_start - stack_ptr
1399                                            : stack_ptr - stack_start;
1400   }
1401
1402   /* Convert jiffies to useconds */
1403   cpu_user_counter = cpu_user_counter * 1000000 / CONFIG_HZ;
1404   cpu_system_counter = cpu_system_counter * 1000000 / CONFIG_HZ;
1405   vmem_rss = vmem_rss * pagesize_g;
1406
1407   ps->cpu_user_counter = cpu_user_counter;
1408   ps->cpu_system_counter = cpu_system_counter;
1409   ps->vmem_size = (unsigned long)vmem_size;
1410   ps->vmem_rss = (unsigned long)vmem_rss;
1411   ps->stack_size = (unsigned long)stack_size;
1412
1413   /* no data by default. May be filled by ps_fill_details () */
1414   ps->io_rchar = -1;
1415   ps->io_wchar = -1;
1416   ps->io_syscr = -1;
1417   ps->io_syscw = -1;
1418   ps->io_diskr = -1;
1419   ps->io_diskw = -1;
1420
1421   ps->cswitch_vol = -1;
1422   ps->cswitch_invol = -1;
1423
1424   /* success */
1425   return 0;
1426 } /* int ps_read_process (...) */
1427
1428 static char *ps_get_cmdline(long pid, char *name, char *buf, size_t buf_len) {
1429   char *buf_ptr;
1430   size_t len;
1431
1432   char file[PATH_MAX];
1433   int fd;
1434
1435   size_t n;
1436
1437   if ((pid < 1) || (NULL == buf) || (buf_len < 2))
1438     return NULL;
1439
1440   snprintf(file, sizeof(file), "/proc/%li/cmdline", pid);
1441
1442   errno = 0;
1443   fd = open(file, O_RDONLY);
1444   if (fd < 0) {
1445     /* ENOENT means the process exited while we were handling it.
1446      * Don't complain about this, it only fills the logs. */
1447     if (errno != ENOENT)
1448       WARNING("processes plugin: Failed to open `%s': %s.", file, STRERRNO);
1449     return NULL;
1450   }
1451
1452   buf_ptr = buf;
1453   len = buf_len;
1454
1455   n = 0;
1456
1457   while (42) {
1458     ssize_t status;
1459
1460     status = read(fd, (void *)buf_ptr, len);
1461
1462     if (status < 0) {
1463
1464       if ((EAGAIN == errno) || (EINTR == errno))
1465         continue;
1466
1467       WARNING("processes plugin: Failed to read from `%s': %s.", file,
1468               STRERRNO);
1469       close(fd);
1470       return NULL;
1471     }
1472
1473     n += status;
1474
1475     if (status == 0)
1476       break;
1477
1478     buf_ptr += status;
1479     len -= status;
1480
1481     if (len == 0)
1482       break;
1483   }
1484
1485   close(fd);
1486
1487   if (0 == n) {
1488     /* cmdline not available; e.g. kernel thread, zombie */
1489     if (NULL == name)
1490       return NULL;
1491
1492     snprintf(buf, buf_len, "[%s]", name);
1493     return buf;
1494   }
1495
1496   assert(n <= buf_len);
1497
1498   if (n == buf_len)
1499     --n;
1500   buf[n] = '\0';
1501
1502   --n;
1503   /* remove trailing whitespace */
1504   while ((n > 0) && (isspace(buf[n]) || ('\0' == buf[n]))) {
1505     buf[n] = '\0';
1506     --n;
1507   }
1508
1509   /* arguments are separated by '\0' in /proc/<pid>/cmdline */
1510   while (n > 0) {
1511     if ('\0' == buf[n])
1512       buf[n] = ' ';
1513     --n;
1514   }
1515   return buf;
1516 } /* char *ps_get_cmdline (...) */
1517
1518 static int read_fork_rate(void) {
1519   FILE *proc_stat;
1520   char buffer[1024];
1521   value_t value;
1522   _Bool value_valid = 0;
1523
1524   proc_stat = fopen("/proc/stat", "r");
1525   if (proc_stat == NULL) {
1526     ERROR("processes plugin: fopen (/proc/stat) failed: %s", STRERRNO);
1527     return -1;
1528   }
1529
1530   while (fgets(buffer, sizeof(buffer), proc_stat) != NULL) {
1531     int status;
1532     char *fields[3];
1533     int fields_num;
1534
1535     fields_num = strsplit(buffer, fields, STATIC_ARRAY_SIZE(fields));
1536     if (fields_num != 2)
1537       continue;
1538
1539     if (strcmp("processes", fields[0]) != 0)
1540       continue;
1541
1542     status = parse_value(fields[1], &value, DS_TYPE_DERIVE);
1543     if (status == 0)
1544       value_valid = 1;
1545
1546     break;
1547   }
1548   fclose(proc_stat);
1549
1550   if (!value_valid)
1551     return -1;
1552
1553   ps_submit_fork_rate(value.derive);
1554   return 0;
1555 }
1556 #endif /*KERNEL_LINUX */
1557
1558 #if KERNEL_SOLARIS
1559 static char *ps_get_cmdline(long pid,
1560                             char *name __attribute__((unused)), /* {{{ */
1561                             char *buffer, size_t buffer_size) {
1562   char path[PATH_MAX];
1563   psinfo_t info;
1564   ssize_t status;
1565
1566   snprintf(path, sizeof(path), "/proc/%li/psinfo", pid);
1567
1568   status = read_file_contents(path, (void *)&info, sizeof(info));
1569   if ((status < 0) || (((size_t)status) != sizeof(info))) {
1570     ERROR("processes plugin: Unexpected return value "
1571           "while reading \"%s\": "
1572           "Returned %zd but expected %zu.",
1573           path, status, buffer_size);
1574     return NULL;
1575   }
1576
1577   info.pr_psargs[sizeof(info.pr_psargs) - 1] = 0;
1578   sstrncpy(buffer, info.pr_psargs, buffer_size);
1579
1580   return buffer;
1581 } /* }}} int ps_get_cmdline */
1582
1583 /*
1584  * Reads process information on the Solaris OS. The information comes mainly
1585  * from
1586  * /proc/PID/status, /proc/PID/psinfo and /proc/PID/usage
1587  * The values for input and ouput chars are calculated "by hand"
1588  * Added a few "solaris" specific process states as well
1589  */
1590 static int ps_read_process(long pid, process_entry_t *ps, char *state) {
1591   char filename[64];
1592   char f_psinfo[64], f_usage[64];
1593   char *buffer;
1594
1595   pstatus_t *myStatus;
1596   psinfo_t *myInfo;
1597   prusage_t *myUsage;
1598
1599   snprintf(filename, sizeof(filename), "/proc/%li/status", pid);
1600   snprintf(f_psinfo, sizeof(f_psinfo), "/proc/%li/psinfo", pid);
1601   snprintf(f_usage, sizeof(f_usage), "/proc/%li/usage", pid);
1602
1603   buffer = calloc(1, sizeof(pstatus_t));
1604   read_file_contents(filename, buffer, sizeof(pstatus_t));
1605   myStatus = (pstatus_t *)buffer;
1606
1607   buffer = calloc(1, sizeof(psinfo_t));
1608   read_file_contents(f_psinfo, buffer, sizeof(psinfo_t));
1609   myInfo = (psinfo_t *)buffer;
1610
1611   buffer = calloc(1, sizeof(prusage_t));
1612   read_file_contents(f_usage, buffer, sizeof(prusage_t));
1613   myUsage = (prusage_t *)buffer;
1614
1615   sstrncpy(ps->name, myInfo->pr_fname, sizeof(myInfo->pr_fname));
1616   ps->num_lwp = myStatus->pr_nlwp;
1617   if (myInfo->pr_wstat != 0) {
1618     ps->num_proc = 0;
1619     ps->num_lwp = 0;
1620     *state = (char)'Z';
1621
1622     sfree(myStatus);
1623     sfree(myInfo);
1624     sfree(myUsage);
1625     return 0;
1626   } else {
1627     ps->num_proc = 1;
1628     ps->num_lwp = myInfo->pr_nlwp;
1629   }
1630
1631   /*
1632    * Convert system time and user time from nanoseconds to microseconds
1633    * for compatibility with the linux module
1634    */
1635   ps->cpu_system_counter = myStatus->pr_stime.tv_nsec / 1000;
1636   ps->cpu_user_counter = myStatus->pr_utime.tv_nsec / 1000;
1637
1638   /*
1639    * Convert rssize from KB to bytes to be consistent w/ the linux module
1640    */
1641   ps->vmem_rss = myInfo->pr_rssize * 1024;
1642   ps->vmem_size = myInfo->pr_size * 1024;
1643   ps->vmem_minflt_counter = myUsage->pr_minf;
1644   ps->vmem_majflt_counter = myUsage->pr_majf;
1645
1646   /*
1647    * TODO: Data and code segment calculations for Solaris
1648    */
1649
1650   ps->vmem_data = -1;
1651   ps->vmem_code = -1;
1652   ps->stack_size = myStatus->pr_stksize;
1653
1654   /*
1655    * TODO: File descriptor count for Solaris
1656    */
1657   ps->num_fd = 0;
1658
1659   /* Number of memory mappings */
1660   ps->num_maps = 0;
1661
1662   /*
1663    * Calculating input/ouput chars
1664    * Formula used is total chars / total blocks => chars/block
1665    * then convert input/output blocks to chars
1666    */
1667   ulong_t tot_chars = myUsage->pr_ioch;
1668   ulong_t tot_blocks = myUsage->pr_inblk + myUsage->pr_oublk;
1669   ulong_t chars_per_block = 1;
1670   if (tot_blocks != 0)
1671     chars_per_block = tot_chars / tot_blocks;
1672   ps->io_rchar = myUsage->pr_inblk * chars_per_block;
1673   ps->io_wchar = myUsage->pr_oublk * chars_per_block;
1674   ps->io_syscr = myUsage->pr_sysc;
1675   ps->io_syscw = myUsage->pr_sysc;
1676   ps->io_diskr = -1;
1677   ps->io_diskw = -1;
1678
1679   /*
1680    * TODO: context switch counters for Solaris
1681 */
1682   ps->cswitch_vol = -1;
1683   ps->cswitch_invol = -1;
1684
1685   /*
1686    * TODO: Find way of setting BLOCKED and PAGING status
1687    */
1688
1689   *state = (char)'R';
1690   if (myStatus->pr_flags & PR_ASLEEP)
1691     *state = (char)'S';
1692   else if (myStatus->pr_flags & PR_STOPPED)
1693     *state = (char)'T';
1694   else if (myStatus->pr_flags & PR_DETACH)
1695     *state = (char)'E';
1696   else if (myStatus->pr_flags & PR_DAEMON)
1697     *state = (char)'A';
1698   else if (myStatus->pr_flags & PR_ISSYS)
1699     *state = (char)'Y';
1700   else if (myStatus->pr_flags & PR_ORPHAN)
1701     *state = (char)'O';
1702
1703   sfree(myStatus);
1704   sfree(myInfo);
1705   sfree(myUsage);
1706
1707   return 0;
1708 }
1709
1710 /*
1711  * Reads the number of threads created since the last reboot. On Solaris these
1712  * are retrieved from kstat (module cpu, name sys, class misc, stat nthreads).
1713  * The result is the sum for all the threads created on each cpu
1714  */
1715 static int read_fork_rate(void) {
1716   extern kstat_ctl_t *kc;
1717   derive_t result = 0;
1718
1719   if (kc == NULL)
1720     return -1;
1721
1722   for (kstat_t *ksp_chain = kc->kc_chain; ksp_chain != NULL;
1723        ksp_chain = ksp_chain->ks_next) {
1724     if ((strcmp(ksp_chain->ks_module, "cpu") == 0) &&
1725         (strcmp(ksp_chain->ks_name, "sys") == 0) &&
1726         (strcmp(ksp_chain->ks_class, "misc") == 0)) {
1727       long long tmp;
1728
1729       kstat_read(kc, ksp_chain, NULL);
1730
1731       tmp = get_kstat_value(ksp_chain, "nthreads");
1732       if (tmp != -1LL)
1733         result += tmp;
1734     }
1735   }
1736
1737   ps_submit_fork_rate(result);
1738   return 0;
1739 }
1740 #endif /* KERNEL_SOLARIS */
1741
1742 #if HAVE_THREAD_INFO
1743 static int mach_get_task_name(task_t t, int *pid, char *name,
1744                               size_t name_max_len) {
1745   int mib[4];
1746
1747   struct kinfo_proc kp;
1748   size_t kp_size;
1749
1750   mib[0] = CTL_KERN;
1751   mib[1] = KERN_PROC;
1752   mib[2] = KERN_PROC_PID;
1753
1754   if (pid_for_task(t, pid) != KERN_SUCCESS)
1755     return -1;
1756   mib[3] = *pid;
1757
1758   kp_size = sizeof(kp);
1759   if (sysctl(mib, 4, &kp, &kp_size, NULL, 0) != 0)
1760     return -1;
1761
1762   if (name_max_len > (MAXCOMLEN + 1))
1763     name_max_len = MAXCOMLEN + 1;
1764
1765   strncpy(name, kp.kp_proc.p_comm, name_max_len - 1);
1766   name[name_max_len - 1] = '\0';
1767
1768   DEBUG("pid = %i; name = %s;", *pid, name);
1769
1770   /* We don't do the special handling for `p_comm == "LaunchCFMApp"' as
1771    * `top' does it, because it is a lot of work and only used when
1772    * debugging. -octo */
1773
1774   return 0;
1775 }
1776 #endif /* HAVE_THREAD_INFO */
1777 /* end of additional functions for KERNEL_LINUX/HAVE_THREAD_INFO */
1778
1779 /* do actual readings from kernel */
1780 static int ps_read(void) {
1781 #if HAVE_THREAD_INFO
1782   kern_return_t status;
1783
1784   processor_set_t port_pset_priv;
1785
1786   task_array_t task_list;
1787   mach_msg_type_number_t task_list_len;
1788
1789   int task_pid;
1790   char task_name[MAXCOMLEN + 1];
1791
1792   thread_act_array_t thread_list;
1793   mach_msg_type_number_t thread_list_len;
1794   thread_basic_info_data_t thread_data;
1795   mach_msg_type_number_t thread_data_len;
1796
1797   int running = 0;
1798   int sleeping = 0;
1799   int zombies = 0;
1800   int stopped = 0;
1801   int blocked = 0;
1802
1803   procstat_t *ps;
1804   process_entry_t pse;
1805
1806   ps_list_reset();
1807
1808   /*
1809    * The Mach-concept is a little different from the traditional UNIX
1810    * concept: All the work is done in threads. Threads are contained in
1811    * `tasks'. Therefore, `task status' doesn't make much sense, since
1812    * it's actually a `thread status'.
1813    * Tasks are assigned to sets of processors, so that's where you go to
1814    * get a list.
1815    */
1816   for (mach_msg_type_number_t pset = 0; pset < pset_list_len; pset++) {
1817     if ((status = host_processor_set_priv(port_host_self, pset_list[pset],
1818                                           &port_pset_priv)) != KERN_SUCCESS) {
1819       ERROR("host_processor_set_priv failed: %s\n", mach_error_string(status));
1820       continue;
1821     }
1822
1823     if ((status = processor_set_tasks(port_pset_priv, &task_list,
1824                                       &task_list_len)) != KERN_SUCCESS) {
1825       ERROR("processor_set_tasks failed: %s\n", mach_error_string(status));
1826       mach_port_deallocate(port_task_self, port_pset_priv);
1827       continue;
1828     }
1829
1830     for (mach_msg_type_number_t task = 0; task < task_list_len; task++) {
1831       ps = NULL;
1832       if (mach_get_task_name(task_list[task], &task_pid, task_name,
1833                              PROCSTAT_NAME_LEN) == 0) {
1834         /* search for at least one match */
1835         for (ps = list_head_g; ps != NULL; ps = ps->next)
1836           /* FIXME: cmdline should be here instead of NULL */
1837           if (ps_list_match(task_name, NULL, ps) == 1)
1838             break;
1839       }
1840
1841       /* Collect more detailed statistics for this process */
1842       if (ps != NULL) {
1843         task_basic_info_data_t task_basic_info;
1844         mach_msg_type_number_t task_basic_info_len;
1845         task_events_info_data_t task_events_info;
1846         mach_msg_type_number_t task_events_info_len;
1847         task_absolutetime_info_data_t task_absolutetime_info;
1848         mach_msg_type_number_t task_absolutetime_info_len;
1849
1850         memset(&pse, '\0', sizeof(pse));
1851         pse.id = task_pid;
1852
1853         task_basic_info_len = TASK_BASIC_INFO_COUNT;
1854         status = task_info(task_list[task], TASK_BASIC_INFO,
1855                            (task_info_t)&task_basic_info, &task_basic_info_len);
1856         if (status != KERN_SUCCESS) {
1857           ERROR("task_info failed: %s", mach_error_string(status));
1858           continue; /* with next thread_list */
1859         }
1860
1861         task_events_info_len = TASK_EVENTS_INFO_COUNT;
1862         status =
1863             task_info(task_list[task], TASK_EVENTS_INFO,
1864                       (task_info_t)&task_events_info, &task_events_info_len);
1865         if (status != KERN_SUCCESS) {
1866           ERROR("task_info failed: %s", mach_error_string(status));
1867           continue; /* with next thread_list */
1868         }
1869
1870         task_absolutetime_info_len = TASK_ABSOLUTETIME_INFO_COUNT;
1871         status = task_info(task_list[task], TASK_ABSOLUTETIME_INFO,
1872                            (task_info_t)&task_absolutetime_info,
1873                            &task_absolutetime_info_len);
1874         if (status != KERN_SUCCESS) {
1875           ERROR("task_info failed: %s", mach_error_string(status));
1876           continue; /* with next thread_list */
1877         }
1878
1879         pse.num_proc++;
1880         pse.vmem_size = task_basic_info.virtual_size;
1881         pse.vmem_rss = task_basic_info.resident_size;
1882         /* Does not seem to be easily exposed */
1883         pse.vmem_data = 0;
1884         pse.vmem_code = 0;
1885
1886         pse.io_rchar = -1;
1887         pse.io_wchar = -1;
1888         pse.io_syscr = -1;
1889         pse.io_syscw = -1;
1890         pse.io_diskr = -1;
1891         pse.io_diskw = -1;
1892
1893         /* File descriptor count not implemented */
1894         pse.num_fd = 0;
1895
1896         /* Number of memory mappings */
1897         pse.num_maps = 0;
1898
1899         pse.vmem_minflt_counter = task_events_info.cow_faults;
1900         pse.vmem_majflt_counter = task_events_info.faults;
1901
1902         pse.cpu_user_counter = task_absolutetime_info.total_user;
1903         pse.cpu_system_counter = task_absolutetime_info.total_system;
1904
1905         /* context switch counters not implemented */
1906         pse.cswitch_vol = -1;
1907         pse.cswitch_invol = -1;
1908       }
1909
1910       status = task_threads(task_list[task], &thread_list, &thread_list_len);
1911       if (status != KERN_SUCCESS) {
1912         /* Apple's `top' treats this case a zombie. It
1913          * makes sense to some extend: A `zombie'
1914          * thread is nonsense, since the task/process
1915          * is dead. */
1916         zombies++;
1917         DEBUG("task_threads failed: %s", mach_error_string(status));
1918         if (task_list[task] != port_task_self)
1919           mach_port_deallocate(port_task_self, task_list[task]);
1920         continue; /* with next task_list */
1921       }
1922
1923       for (mach_msg_type_number_t thread = 0; thread < thread_list_len;
1924            thread++) {
1925         thread_data_len = THREAD_BASIC_INFO_COUNT;
1926         status = thread_info(thread_list[thread], THREAD_BASIC_INFO,
1927                              (thread_info_t)&thread_data, &thread_data_len);
1928         if (status != KERN_SUCCESS) {
1929           ERROR("thread_info failed: %s", mach_error_string(status));
1930           if (task_list[task] != port_task_self)
1931             mach_port_deallocate(port_task_self, thread_list[thread]);
1932           continue; /* with next thread_list */
1933         }
1934
1935         if (ps != NULL)
1936           pse.num_lwp++;
1937
1938         switch (thread_data.run_state) {
1939         case TH_STATE_RUNNING:
1940           running++;
1941           break;
1942         case TH_STATE_STOPPED:
1943         /* What exactly is `halted'? */
1944         case TH_STATE_HALTED:
1945           stopped++;
1946           break;
1947         case TH_STATE_WAITING:
1948           sleeping++;
1949           break;
1950         case TH_STATE_UNINTERRUPTIBLE:
1951           blocked++;
1952           break;
1953         /* There is no `zombie' case here,
1954          * since there are no zombie-threads.
1955          * There's only zombie tasks, which are
1956          * handled above. */
1957         default:
1958           WARNING("Unknown thread status: %i", thread_data.run_state);
1959           break;
1960         } /* switch (thread_data.run_state) */
1961
1962         if (task_list[task] != port_task_self) {
1963           status = mach_port_deallocate(port_task_self, thread_list[thread]);
1964           if (status != KERN_SUCCESS)
1965             ERROR("mach_port_deallocate failed: %s", mach_error_string(status));
1966         }
1967       } /* for (thread_list) */
1968
1969       if ((status = vm_deallocate(port_task_self, (vm_address_t)thread_list,
1970                                   thread_list_len * sizeof(thread_act_t))) !=
1971           KERN_SUCCESS) {
1972         ERROR("vm_deallocate failed: %s", mach_error_string(status));
1973       }
1974       thread_list = NULL;
1975       thread_list_len = 0;
1976
1977       /* Only deallocate the task port, if it isn't our own.
1978        * Don't know what would happen in that case, but this
1979        * is what Apple's top does.. ;) */
1980       if (task_list[task] != port_task_self) {
1981         status = mach_port_deallocate(port_task_self, task_list[task]);
1982         if (status != KERN_SUCCESS)
1983           ERROR("mach_port_deallocate failed: %s", mach_error_string(status));
1984       }
1985
1986       if (ps != NULL)
1987         /* FIXME: cmdline should be here instead of NULL */
1988         ps_list_add(task_name, NULL, &pse);
1989     } /* for (task_list) */
1990
1991     if ((status = vm_deallocate(port_task_self, (vm_address_t)task_list,
1992                                 task_list_len * sizeof(task_t))) !=
1993         KERN_SUCCESS) {
1994       ERROR("vm_deallocate failed: %s", mach_error_string(status));
1995     }
1996     task_list = NULL;
1997     task_list_len = 0;
1998
1999     if ((status = mach_port_deallocate(port_task_self, port_pset_priv)) !=
2000         KERN_SUCCESS) {
2001       ERROR("mach_port_deallocate failed: %s", mach_error_string(status));
2002     }
2003   } /* for (pset_list) */
2004
2005   ps_submit_state("running", running);
2006   ps_submit_state("sleeping", sleeping);
2007   ps_submit_state("zombies", zombies);
2008   ps_submit_state("stopped", stopped);
2009   ps_submit_state("blocked", blocked);
2010
2011   for (ps = list_head_g; ps != NULL; ps = ps->next)
2012     ps_submit_proc_list(ps);
2013 /* #endif HAVE_THREAD_INFO */
2014
2015 #elif KERNEL_LINUX
2016   int running = 0;
2017   int sleeping = 0;
2018   int zombies = 0;
2019   int stopped = 0;
2020   int paging = 0;
2021   int blocked = 0;
2022
2023   struct dirent *ent;
2024   DIR *proc;
2025   long pid;
2026
2027   char cmdline[CMDLINE_BUFFER_SIZE];
2028
2029   int status;
2030   process_entry_t pse;
2031   char state;
2032
2033   running = sleeping = zombies = stopped = paging = blocked = 0;
2034   ps_list_reset();
2035
2036   if ((proc = opendir("/proc")) == NULL) {
2037     ERROR("Cannot open `/proc': %s", STRERRNO);
2038     return -1;
2039   }
2040
2041   while ((ent = readdir(proc)) != NULL) {
2042     if (!isdigit(ent->d_name[0]))
2043       continue;
2044
2045     if ((pid = atol(ent->d_name)) < 1)
2046       continue;
2047
2048     memset(&pse, 0, sizeof(pse));
2049     pse.id = pid;
2050
2051     status = ps_read_process(pid, &pse, &state);
2052     if (status != 0) {
2053       DEBUG("ps_read_process failed: %i", status);
2054       continue;
2055     }
2056
2057     switch (state) {
2058     case 'R':
2059       running++;
2060       break;
2061     case 'S':
2062       sleeping++;
2063       break;
2064     case 'D':
2065       blocked++;
2066       break;
2067     case 'Z':
2068       zombies++;
2069       break;
2070     case 'T':
2071       stopped++;
2072       break;
2073     case 'W':
2074       paging++;
2075       break;
2076     }
2077
2078     ps_list_add(pse.name,
2079                 ps_get_cmdline(pid, pse.name, cmdline, sizeof(cmdline)), &pse);
2080   }
2081
2082   closedir(proc);
2083
2084   ps_submit_state("running", running);
2085   ps_submit_state("sleeping", sleeping);
2086   ps_submit_state("zombies", zombies);
2087   ps_submit_state("stopped", stopped);
2088   ps_submit_state("paging", paging);
2089   ps_submit_state("blocked", blocked);
2090
2091   for (procstat_t *ps_ptr = list_head_g; ps_ptr != NULL; ps_ptr = ps_ptr->next)
2092     ps_submit_proc_list(ps_ptr);
2093
2094   read_fork_rate();
2095 /* #endif KERNEL_LINUX */
2096
2097 #elif HAVE_LIBKVM_GETPROCS && HAVE_STRUCT_KINFO_PROC_FREEBSD
2098   int running = 0;
2099   int sleeping = 0;
2100   int zombies = 0;
2101   int stopped = 0;
2102   int blocked = 0;
2103   int idle = 0;
2104   int wait = 0;
2105
2106   kvm_t *kd;
2107   char errbuf[_POSIX2_LINE_MAX];
2108   struct kinfo_proc *procs; /* array of processes */
2109   struct kinfo_proc *proc_ptr = NULL;
2110   int count; /* returns number of processes */
2111
2112   process_entry_t pse;
2113
2114   ps_list_reset();
2115
2116   /* Open the kvm interface, get a descriptor */
2117   kd = kvm_openfiles(NULL, "/dev/null", NULL, 0, errbuf);
2118   if (kd == NULL) {
2119     ERROR("processes plugin: Cannot open kvm interface: %s", errbuf);
2120     return 0;
2121   }
2122
2123   /* Get the list of processes. */
2124   procs = kvm_getprocs(kd, KERN_PROC_ALL, 0, &count);
2125   if (procs == NULL) {
2126     ERROR("processes plugin: Cannot get kvm processes list: %s",
2127           kvm_geterr(kd));
2128     kvm_close(kd);
2129     return 0;
2130   }
2131
2132   /* Iterate through the processes in kinfo_proc */
2133   for (int i = 0; i < count; i++) {
2134     /* Create only one process list entry per _process_, i.e.
2135      * filter out threads (duplicate PID entries). */
2136     if ((proc_ptr == NULL) || (proc_ptr->ki_pid != procs[i].ki_pid)) {
2137       char cmdline[CMDLINE_BUFFER_SIZE] = "";
2138       _Bool have_cmdline = 0;
2139
2140       proc_ptr = &(procs[i]);
2141       /* Don't probe system processes and processes without arguments */
2142       if (((procs[i].ki_flag & P_SYSTEM) == 0) && (procs[i].ki_args != NULL)) {
2143         char **argv;
2144         int argc;
2145         int status;
2146
2147         /* retrieve the arguments */
2148         argv = kvm_getargv(kd, proc_ptr, /* nchr = */ 0);
2149         argc = 0;
2150         if ((argv != NULL) && (argv[0] != NULL)) {
2151           while (argv[argc] != NULL)
2152             argc++;
2153
2154           status = strjoin(cmdline, sizeof(cmdline), argv, argc, " ");
2155           if (status < 0)
2156             WARNING("processes plugin: Command line did not fit into buffer.");
2157           else
2158             have_cmdline = 1;
2159         }
2160       } /* if (process has argument list) */
2161
2162       memset(&pse, 0, sizeof(pse));
2163       pse.id = procs[i].ki_pid;
2164
2165       pse.num_proc = 1;
2166       pse.num_lwp = procs[i].ki_numthreads;
2167
2168       pse.vmem_size = procs[i].ki_size;
2169       pse.vmem_rss = procs[i].ki_rssize * pagesize;
2170       pse.vmem_data = procs[i].ki_dsize * pagesize;
2171       pse.vmem_code = procs[i].ki_tsize * pagesize;
2172       pse.stack_size = procs[i].ki_ssize * pagesize;
2173       pse.vmem_minflt_counter = procs[i].ki_rusage.ru_minflt;
2174       pse.vmem_majflt_counter = procs[i].ki_rusage.ru_majflt;
2175
2176       pse.cpu_user_counter = 0;
2177       pse.cpu_system_counter = 0;
2178       /*
2179        * The u-area might be swapped out, and we can't get
2180        * at it because we have a crashdump and no swap.
2181        * If it's here fill in these fields, otherwise, just
2182        * leave them 0.
2183        */
2184       if (procs[i].ki_flag & P_INMEM) {
2185         pse.cpu_user_counter = procs[i].ki_rusage.ru_utime.tv_usec +
2186                                (1000000lu * procs[i].ki_rusage.ru_utime.tv_sec);
2187         pse.cpu_system_counter =
2188             procs[i].ki_rusage.ru_stime.tv_usec +
2189             (1000000lu * procs[i].ki_rusage.ru_stime.tv_sec);
2190       }
2191
2192       /* no I/O data */
2193       pse.io_rchar = -1;
2194       pse.io_wchar = -1;
2195       pse.io_syscr = -1;
2196       pse.io_syscw = -1;
2197       pse.io_diskr = -1;
2198       pse.io_diskw = -1;
2199
2200       /* file descriptor count not implemented */
2201       pse.num_fd = 0;
2202
2203       /* Number of memory mappings */
2204       pse.num_maps = 0;
2205
2206       /* context switch counters not implemented */
2207       pse.cswitch_vol = -1;
2208       pse.cswitch_invol = -1;
2209
2210       ps_list_add(procs[i].ki_comm, have_cmdline ? cmdline : NULL, &pse);
2211
2212       switch (procs[i].ki_stat) {
2213       case SSTOP:
2214         stopped++;
2215         break;
2216       case SSLEEP:
2217         sleeping++;
2218         break;
2219       case SRUN:
2220         running++;
2221         break;
2222       case SIDL:
2223         idle++;
2224         break;
2225       case SWAIT:
2226         wait++;
2227         break;
2228       case SLOCK:
2229         blocked++;
2230         break;
2231       case SZOMB:
2232         zombies++;
2233         break;
2234       }
2235     } /* if ((proc_ptr == NULL) || (proc_ptr->ki_pid != procs[i].ki_pid)) */
2236   }
2237
2238   kvm_close(kd);
2239
2240   ps_submit_state("running", running);
2241   ps_submit_state("sleeping", sleeping);
2242   ps_submit_state("zombies", zombies);
2243   ps_submit_state("stopped", stopped);
2244   ps_submit_state("blocked", blocked);
2245   ps_submit_state("idle", idle);
2246   ps_submit_state("wait", wait);
2247
2248   for (procstat_t *ps_ptr = list_head_g; ps_ptr != NULL; ps_ptr = ps_ptr->next)
2249     ps_submit_proc_list(ps_ptr);
2250 /* #endif HAVE_LIBKVM_GETPROCS && HAVE_STRUCT_KINFO_PROC_FREEBSD */
2251
2252 #elif HAVE_LIBKVM_GETPROCS && HAVE_STRUCT_KINFO_PROC_OPENBSD
2253   int running = 0;
2254   int sleeping = 0;
2255   int zombies = 0;
2256   int stopped = 0;
2257   int onproc = 0;
2258   int idle = 0;
2259   int dead = 0;
2260
2261   kvm_t *kd;
2262   char errbuf[1024];
2263   struct kinfo_proc *procs; /* array of processes */
2264   struct kinfo_proc *proc_ptr = NULL;
2265   int count; /* returns number of processes */
2266
2267   process_entry_t pse;
2268
2269   ps_list_reset();
2270
2271   /* Open the kvm interface, get a descriptor */
2272   kd = kvm_openfiles(NULL, NULL, NULL, KVM_NO_FILES, errbuf);
2273   if (kd == NULL) {
2274     ERROR("processes plugin: Cannot open kvm interface: %s", errbuf);
2275     return 0;
2276   }
2277
2278   /* Get the list of processes. */
2279   procs = kvm_getprocs(kd, KERN_PROC_ALL, 0, sizeof(struct kinfo_proc), &count);
2280   if (procs == NULL) {
2281     ERROR("processes plugin: Cannot get kvm processes list: %s",
2282           kvm_geterr(kd));
2283     kvm_close(kd);
2284     return 0;
2285   }
2286
2287   /* Iterate through the processes in kinfo_proc */
2288   for (int i = 0; i < count; i++) {
2289     /* Create only one process list entry per _process_, i.e.
2290      * filter out threads (duplicate PID entries). */
2291     if ((proc_ptr == NULL) || (proc_ptr->p_pid != procs[i].p_pid)) {
2292       char cmdline[CMDLINE_BUFFER_SIZE] = "";
2293       _Bool have_cmdline = 0;
2294
2295       proc_ptr = &(procs[i]);
2296       /* Don't probe zombie processes  */
2297       if (!P_ZOMBIE(proc_ptr)) {
2298         char **argv;
2299         int argc;
2300         int status;
2301
2302         /* retrieve the arguments */
2303         argv = kvm_getargv(kd, proc_ptr, /* nchr = */ 0);
2304         argc = 0;
2305         if ((argv != NULL) && (argv[0] != NULL)) {
2306           while (argv[argc] != NULL)
2307             argc++;
2308
2309           status = strjoin(cmdline, sizeof(cmdline), argv, argc, " ");
2310           if (status < 0)
2311             WARNING("processes plugin: Command line did not fit into buffer.");
2312           else
2313             have_cmdline = 1;
2314         }
2315       } /* if (process has argument list) */
2316
2317       memset(&pse, 0, sizeof(pse));
2318       pse.id = procs[i].p_pid;
2319
2320       pse.num_proc = 1;
2321       pse.num_lwp = 1; /* XXX: accumulate p_tid values for a single p_pid ? */
2322
2323       pse.vmem_rss = procs[i].p_vm_rssize * pagesize;
2324       pse.vmem_data = procs[i].p_vm_dsize * pagesize;
2325       pse.vmem_code = procs[i].p_vm_tsize * pagesize;
2326       pse.stack_size = procs[i].p_vm_ssize * pagesize;
2327       pse.vmem_size = pse.stack_size + pse.vmem_code + pse.vmem_data;
2328       pse.vmem_minflt_counter = procs[i].p_uru_minflt;
2329       pse.vmem_majflt_counter = procs[i].p_uru_majflt;
2330
2331       pse.cpu_user_counter =
2332           procs[i].p_uutime_usec + (1000000lu * procs[i].p_uutime_sec);
2333       pse.cpu_system_counter =
2334           procs[i].p_ustime_usec + (1000000lu * procs[i].p_ustime_sec);
2335
2336       /* no I/O data */
2337       pse.io_rchar = -1;
2338       pse.io_wchar = -1;
2339       pse.io_syscr = -1;
2340       pse.io_syscw = -1;
2341       pse.io_diskr = -1;
2342       pse.io_diskw = -1;
2343
2344       /* file descriptor count not implemented */
2345       pse.num_fd = 0;
2346
2347       /* Number of memory mappings */
2348       pse.num_maps = 0;
2349
2350       /* context switch counters not implemented */
2351       pse.cswitch_vol = -1;
2352       pse.cswitch_invol = -1;
2353
2354       ps_list_add(procs[i].p_comm, have_cmdline ? cmdline : NULL, &pse);
2355
2356       switch (procs[i].p_stat) {
2357       case SSTOP:
2358         stopped++;
2359         break;
2360       case SSLEEP:
2361         sleeping++;
2362         break;
2363       case SRUN:
2364         running++;
2365         break;
2366       case SIDL:
2367         idle++;
2368         break;
2369       case SONPROC:
2370         onproc++;
2371         break;
2372       case SDEAD:
2373         dead++;
2374         break;
2375       case SZOMB:
2376         zombies++;
2377         break;
2378       }
2379     } /* if ((proc_ptr == NULL) || (proc_ptr->p_pid != procs[i].p_pid)) */
2380   }
2381
2382   kvm_close(kd);
2383
2384   ps_submit_state("running", running);
2385   ps_submit_state("sleeping", sleeping);
2386   ps_submit_state("zombies", zombies);
2387   ps_submit_state("stopped", stopped);
2388   ps_submit_state("onproc", onproc);
2389   ps_submit_state("idle", idle);
2390   ps_submit_state("dead", dead);
2391
2392   for (procstat_t *ps_ptr = list_head_g; ps_ptr != NULL; ps_ptr = ps_ptr->next)
2393     ps_submit_proc_list(ps_ptr);
2394 /* #endif HAVE_LIBKVM_GETPROCS && HAVE_STRUCT_KINFO_PROC_OPENBSD */
2395
2396 #elif HAVE_PROCINFO_H
2397   /* AIX */
2398   int running = 0;
2399   int sleeping = 0;
2400   int zombies = 0;
2401   int stopped = 0;
2402   int paging = 0;
2403   int blocked = 0;
2404
2405   pid_t pindex = 0;
2406   int nprocs;
2407
2408   process_entry_t pse;
2409
2410   ps_list_reset();
2411   while ((nprocs = getprocs64(procentry, sizeof(struct procentry64),
2412                               /* fdsinfo = */ NULL, sizeof(struct fdsinfo64),
2413                               &pindex, MAXPROCENTRY)) > 0) {
2414     for (int i = 0; i < nprocs; i++) {
2415       tid64_t thindex;
2416       int nthreads;
2417       char arglist[MAXARGLN + 1];
2418       char *cargs;
2419       char *cmdline;
2420
2421       if (procentry[i].pi_state == SNONE)
2422         continue;
2423       /* if (procentry[i].pi_state == SZOMB)  FIXME */
2424
2425       cmdline = procentry[i].pi_comm;
2426       cargs = procentry[i].pi_comm;
2427       if (procentry[i].pi_flags & SKPROC) {
2428         if (procentry[i].pi_pid == 0)
2429           cmdline = "swapper";
2430         cargs = cmdline;
2431       } else {
2432         if (getargs(&procentry[i], sizeof(struct procentry64), arglist,
2433                     MAXARGLN) >= 0) {
2434           int n;
2435
2436           n = -1;
2437           while (++n < MAXARGLN) {
2438             if (arglist[n] == '\0') {
2439               if (arglist[n + 1] == '\0')
2440                 break;
2441               arglist[n] = ' ';
2442             }
2443           }
2444           cargs = arglist;
2445         }
2446       }
2447
2448       memset(&pse, 0, sizeof(pse));
2449
2450       pse.id = procentry[i].pi_pid;
2451       pse.num_lwp = procentry[i].pi_thcount;
2452       pse.num_proc = 1;
2453
2454       thindex = 0;
2455       while ((nthreads = getthrds64(procentry[i].pi_pid, thrdentry,
2456                                     sizeof(struct thrdentry64), &thindex,
2457                                     MAXTHRDENTRY)) > 0) {
2458         int j;
2459
2460         for (j = 0; j < nthreads; j++) {
2461           switch (thrdentry[j].ti_state) {
2462           /* case TSNONE: break; */
2463           case TSIDL:
2464             blocked++;
2465             break; /* FIXME is really blocked */
2466           case TSRUN:
2467             running++;
2468             break;
2469           case TSSLEEP:
2470             sleeping++;
2471             break;
2472           case TSSWAP:
2473             paging++;
2474             break;
2475           case TSSTOP:
2476             stopped++;
2477             break;
2478           case TSZOMB:
2479             zombies++;
2480             break;
2481           }
2482         }
2483         if (nthreads < MAXTHRDENTRY)
2484           break;
2485       }
2486
2487       /* tv_usec is nanosec ??? */
2488       pse.cpu_user_counter = procentry[i].pi_ru.ru_utime.tv_sec * 1000000 +
2489                              procentry[i].pi_ru.ru_utime.tv_usec / 1000;
2490
2491       /* tv_usec is nanosec ??? */
2492       pse.cpu_system_counter = procentry[i].pi_ru.ru_stime.tv_sec * 1000000 +
2493                                procentry[i].pi_ru.ru_stime.tv_usec / 1000;
2494
2495       pse.vmem_minflt_counter = procentry[i].pi_minflt;
2496       pse.vmem_majflt_counter = procentry[i].pi_majflt;
2497
2498       pse.vmem_size = procentry[i].pi_tsize + procentry[i].pi_dvm * pagesize;
2499       pse.vmem_rss = (procentry[i].pi_drss + procentry[i].pi_trss) * pagesize;
2500       /* Not supported/implemented */
2501       pse.vmem_data = 0;
2502       pse.vmem_code = 0;
2503       pse.stack_size = 0;
2504
2505       pse.io_rchar = -1;
2506       pse.io_wchar = -1;
2507       pse.io_syscr = -1;
2508       pse.io_syscw = -1;
2509       pse.io_diskr = -1;
2510       pse.io_diskw = -1;
2511
2512       pse.num_fd = 0;
2513       pse.num_maps = 0;
2514
2515       pse.cswitch_vol = -1;
2516       pse.cswitch_invol = -1;
2517
2518       ps_list_add(cmdline, cargs, &pse);
2519     } /* for (i = 0 .. nprocs) */
2520
2521     if (nprocs < MAXPROCENTRY)
2522       break;
2523   } /* while (getprocs64() > 0) */
2524   ps_submit_state("running", running);
2525   ps_submit_state("sleeping", sleeping);
2526   ps_submit_state("zombies", zombies);
2527   ps_submit_state("stopped", stopped);
2528   ps_submit_state("paging", paging);
2529   ps_submit_state("blocked", blocked);
2530
2531   for (procstat_t *ps = list_head_g; ps != NULL; ps = ps->next)
2532     ps_submit_proc_list(ps);
2533 /* #endif HAVE_PROCINFO_H */
2534
2535 #elif KERNEL_SOLARIS
2536   /*
2537    * The Solaris section adds a few more process states and removes some
2538    * process states compared to linux. Most notably there is no "PAGING"
2539    * and "BLOCKED" state for a process.  The rest is similar to the linux
2540    * code.
2541    */
2542   int running = 0;
2543   int sleeping = 0;
2544   int zombies = 0;
2545   int stopped = 0;
2546   int detached = 0;
2547   int daemon = 0;
2548   int system = 0;
2549   int orphan = 0;
2550
2551   struct dirent *ent;
2552   DIR *proc;
2553
2554   int status;
2555   char state;
2556
2557   char cmdline[PRARGSZ];
2558
2559   ps_list_reset();
2560
2561   proc = opendir("/proc");
2562   if (proc == NULL)
2563     return -1;
2564
2565   while ((ent = readdir(proc)) != NULL) {
2566     long pid;
2567     process_entry_t pse;
2568     char *endptr;
2569
2570     if (!isdigit((int)ent->d_name[0]))
2571       continue;
2572
2573     pid = strtol(ent->d_name, &endptr, 10);
2574     if (*endptr != 0) /* value didn't completely parse as a number */
2575       continue;
2576
2577     memset(&pse, 0, sizeof(pse));
2578     pse.id = pid;
2579
2580     status = ps_read_process(pid, &pse, &state);
2581     if (status != 0) {
2582       DEBUG("ps_read_process failed: %i", status);
2583       continue;
2584     }
2585
2586     switch (state) {
2587     case 'R':
2588       running++;
2589       break;
2590     case 'S':
2591       sleeping++;
2592       break;
2593     case 'E':
2594       detached++;
2595       break;
2596     case 'Z':
2597       zombies++;
2598       break;
2599     case 'T':
2600       stopped++;
2601       break;
2602     case 'A':
2603       daemon++;
2604       break;
2605     case 'Y':
2606       system++;
2607       break;
2608     case 'O':
2609       orphan++;
2610       break;
2611     }
2612
2613     ps_list_add(pse.name,
2614                 ps_get_cmdline(pid, pse.name, cmdline, sizeof(cmdline)), &pse);
2615   } /* while(readdir) */
2616   closedir(proc);
2617
2618   ps_submit_state("running", running);
2619   ps_submit_state("sleeping", sleeping);
2620   ps_submit_state("zombies", zombies);
2621   ps_submit_state("stopped", stopped);
2622   ps_submit_state("detached", detached);
2623   ps_submit_state("daemon", daemon);
2624   ps_submit_state("system", system);
2625   ps_submit_state("orphan", orphan);
2626
2627   for (procstat_t *ps_ptr = list_head_g; ps_ptr != NULL; ps_ptr = ps_ptr->next)
2628     ps_submit_proc_list(ps_ptr);
2629
2630   read_fork_rate();
2631 #endif /* KERNEL_SOLARIS */
2632
2633   want_init = 0;
2634
2635   return 0;
2636 } /* int ps_read */
2637
2638 void module_register(void) {
2639   plugin_register_complex_config("processes", ps_config);
2640   plugin_register_init("processes", ps_init);
2641   plugin_register_read("processes", ps_read);
2642 } /* void module_register */