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