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