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