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