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