Various plugins: Change various plugins to use "derive" internally.
[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  *
11  * This program is free software; you can redistribute it and/or modify it
12  * under the terms of the GNU General Public License as published by the
13  * Free Software Foundation; either version 2 of the License, or (at your
14  * option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful, but
17  * WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19  * General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License along
22  * with this program; if not, write to the Free Software Foundation, Inc.,
23  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
24  *
25  * Authors:
26  *   Lyonel Vincent <lyonel at ezix.org>
27  *   Florian octo Forster <octo at verplant.org>
28  *   Oleg King <king2 at kaluga.ru>
29  *   Sebastian Harl <sh at tokkee.org>
30  *   Andrés J. Díaz <ajdiaz at connectical.com>
31  *   Manuel Sanmartin
32  *   Clément Stenac <clement.stenac at diwi.org>
33  **/
34
35 #include "collectd.h"
36 #include "common.h"
37 #include "plugin.h"
38 #include "configfile.h"
39
40 /* Include header files for the mach system, if they exist.. */
41 #if HAVE_THREAD_INFO
42 #  if HAVE_MACH_MACH_INIT_H
43 #    include <mach/mach_init.h>
44 #  endif
45 #  if HAVE_MACH_HOST_PRIV_H
46 #    include <mach/host_priv.h>
47 #  endif
48 #  if HAVE_MACH_MACH_ERROR_H
49 #    include <mach/mach_error.h>
50 #  endif
51 #  if HAVE_MACH_MACH_HOST_H
52 #    include <mach/mach_host.h>
53 #  endif
54 #  if HAVE_MACH_MACH_PORT_H
55 #    include <mach/mach_port.h>
56 #  endif
57 #  if HAVE_MACH_MACH_TYPES_H
58 #    include <mach/mach_types.h>
59 #  endif
60 #  if HAVE_MACH_MESSAGE_H
61 #    include <mach/message.h>
62 #  endif
63 #  if HAVE_MACH_PROCESSOR_SET_H
64 #    include <mach/processor_set.h>
65 #  endif
66 #  if HAVE_MACH_TASK_H
67 #    include <mach/task.h>
68 #  endif
69 #  if HAVE_MACH_THREAD_ACT_H
70 #    include <mach/thread_act.h>
71 #  endif
72 #  if HAVE_MACH_VM_REGION_H
73 #    include <mach/vm_region.h>
74 #  endif
75 #  if HAVE_MACH_VM_MAP_H
76 #    include <mach/vm_map.h>
77 #  endif
78 #  if HAVE_MACH_VM_PROT_H
79 #    include <mach/vm_prot.h>
80 #  endif
81 #  if HAVE_SYS_SYSCTL_H
82 #    include <sys/sysctl.h>
83 #  endif
84 /* #endif HAVE_THREAD_INFO */
85
86 #elif KERNEL_LINUX
87 #  if HAVE_LINUX_CONFIG_H
88 #    include <linux/config.h>
89 #  endif
90 #  ifndef CONFIG_HZ
91 #    define CONFIG_HZ 100
92 #  endif
93 /* #endif KERNEL_LINUX */
94
95 #elif HAVE_LIBKVM_GETPROCS && HAVE_STRUCT_KINFO_PROC_FREEBSD
96 #  include <kvm.h>
97 #  include <sys/param.h>
98 #  include <sys/sysctl.h>
99 #  include <sys/user.h>
100 #  include <sys/proc.h>
101 /* #endif HAVE_LIBKVM_GETPROCS && HAVE_STRUCT_KINFO_PROC_FREEBSD */
102
103 #elif HAVE_PROCINFO_H
104 #  include <procinfo.h>
105 #  include <sys/types.h>
106
107 #define MAXPROCENTRY 32
108 #define MAXTHRDENTRY 16
109 #define MAXARGLN 1024
110 /* #endif HAVE_PROCINFO_H */
111
112 #else
113 # error "No applicable input method."
114 #endif
115
116 #if HAVE_REGEX_H
117 # include <regex.h>
118 #endif
119
120 #ifndef ARG_MAX
121 #  define ARG_MAX 4096
122 #endif
123
124 static const char *config_keys[] =
125 {
126         "Process",
127         "ProcessMatch"
128 };
129 static int config_keys_num = STATIC_ARRAY_SIZE (config_keys);
130
131 typedef struct procstat_entry_s
132 {
133         unsigned long id;
134         unsigned long age;
135
136         unsigned long num_proc;
137         unsigned long num_lwp;
138         unsigned long vmem_size;
139         unsigned long vmem_rss;
140         unsigned long vmem_data;
141         unsigned long vmem_code;
142         unsigned long stack_size;
143
144         unsigned long vmem_minflt;
145         unsigned long vmem_majflt;
146         derive_t      vmem_minflt_counter;
147         derive_t      vmem_majflt_counter;
148
149         unsigned long cpu_user;
150         unsigned long cpu_system;
151         derive_t      cpu_user_counter;
152         derive_t      cpu_system_counter;
153
154         /* io data */
155         derive_t io_rchar;
156         derive_t io_wchar;
157         derive_t io_syscr;
158         derive_t io_syscw;
159
160         struct procstat_entry_s *next;
161 } procstat_entry_t;
162
163 #define PROCSTAT_NAME_LEN 256
164 typedef struct procstat
165 {
166         char          name[PROCSTAT_NAME_LEN];
167 #if HAVE_REGEX_H
168         regex_t *re;
169 #endif
170
171         unsigned long num_proc;
172         unsigned long num_lwp;
173         unsigned long vmem_size;
174         unsigned long vmem_rss;
175         unsigned long vmem_data;
176         unsigned long vmem_code;
177         unsigned long stack_size;
178
179         derive_t vmem_minflt_counter;
180         derive_t vmem_majflt_counter;
181
182         derive_t cpu_user_counter;
183         derive_t cpu_system_counter;
184
185         /* io data */
186         derive_t io_rchar;
187         derive_t io_wchar;
188         derive_t io_syscr;
189         derive_t io_syscw;
190
191         struct procstat   *next;
192         struct procstat_entry_s *instances;
193 } procstat_t;
194
195 static procstat_t *list_head_g = NULL;
196
197 #if HAVE_THREAD_INFO
198 static mach_port_t port_host_self;
199 static mach_port_t port_task_self;
200
201 static processor_set_name_array_t pset_list;
202 static mach_msg_type_number_t     pset_list_len;
203 /* #endif HAVE_THREAD_INFO */
204
205 #elif KERNEL_LINUX
206 static long pagesize_g;
207 /* #endif KERNEL_LINUX */
208
209 #elif HAVE_LIBKVM_GETPROCS && HAVE_STRUCT_KINFO_PROC_FREEBSD
210 /* no global variables */
211 /* #endif HAVE_LIBKVM_GETPROCS && HAVE_STRUCT_KINFO_PROC_FREEBSD */
212
213 #elif HAVE_PROCINFO_H
214 static  struct procentry64 procentry[MAXPROCENTRY];
215 static  struct thrdentry64 thrdentry[MAXTHRDENTRY];
216 static int pagesize;
217
218 #ifndef _AIXVERSION_610
219 int     getprocs64 (void *procsinfo, int sizproc, void *fdsinfo, int sizfd, pid_t *index, int count);
220 int     getthrds64( pid_t, void *, int, tid64_t *, int );
221 #endif
222 int getargs (struct procentry64 *processBuffer, int bufferLen, char *argsBuffer, int argsLen);
223 #endif /* HAVE_PROCINFO_H */
224
225 /* put name of process from config to list_head_g tree
226    list_head_g is a list of 'procstat_t' structs with
227    processes names we want to watch */
228 static void ps_list_register (const char *name, const char *regexp)
229 {
230         procstat_t *new;
231         procstat_t *ptr;
232         int status;
233
234         new = (procstat_t *) malloc (sizeof (procstat_t));
235         if (new == NULL)
236         {
237                 ERROR ("processes plugin: ps_list_register: malloc failed.");
238                 return;
239         }
240         memset (new, 0, sizeof (procstat_t));
241         sstrncpy (new->name, name, sizeof (new->name));
242
243 #if HAVE_REGEX_H
244         if (regexp != NULL)
245         {
246                 DEBUG ("ProcessMatch: adding \"%s\" as criteria to process %s.", regexp, name);
247                 new->re = (regex_t *) malloc (sizeof (regex_t));
248                 if (new->re == NULL)
249                 {
250                         ERROR ("processes plugin: ps_list_register: malloc failed.");
251                         sfree (new);
252                         return;
253                 }
254
255                 status = regcomp (new->re, regexp, REG_EXTENDED | REG_NOSUB);
256                 if (status != 0)
257                 {
258                         DEBUG ("ProcessMatch: compiling the regular expression \"%s\" failed.", regexp);
259                         sfree(new->re);
260                         return;
261                 }
262         }
263 #else
264         if (regexp != NULL)
265         {
266                 ERROR ("processes plugin: ps_list_register: "
267                                 "Regular expression \"%s\" found in config "
268                                 "file, but support for regular expressions "
269                                 "has been disabled at compile time.",
270                                 regexp);
271                 sfree (new);
272                 return;
273         }
274 #endif
275
276         for (ptr = list_head_g; ptr != NULL; ptr = ptr->next)
277         {
278                 if (strcmp (ptr->name, name) == 0)
279                 {
280                         WARNING ("processes plugin: You have configured more "
281                                         "than one `Process' or "
282                                         "`ProcessMatch' with the same name. "
283                                         "All but the first setting will be "
284                                         "ignored.");
285                         sfree (new->re);
286                         sfree (new);
287                         return;
288                 }
289
290                 if (ptr->next == NULL)
291                         break;
292         }
293
294         if (ptr == NULL)
295                 list_head_g = new;
296         else
297                 ptr->next = new;
298 } /* void ps_list_register */
299
300 /* try to match name against entry, returns 1 if success */
301 static int ps_list_match (const char *name, const char *cmdline, procstat_t *ps)
302 {
303 #if HAVE_REGEX_H
304         if (ps->re != NULL)
305         {
306                 int status;
307                 const char *str;
308
309                 str = cmdline;
310                 if ((str == NULL) || (str[0] == 0))
311                         str = name;
312
313                 assert (str != NULL);
314
315                 status = regexec (ps->re, str,
316                                 /* nmatch = */ 0,
317                                 /* pmatch = */ NULL,
318                                 /* eflags = */ 0);
319                 if (status == 0)
320                         return (1);
321         }
322         else
323 #endif
324         if (strcmp (ps->name, name) == 0)
325                 return (1);
326
327         return (0);
328 } /* int ps_list_match */
329
330 /* add process entry to 'instances' of process 'name' (or refresh it) */
331 static void ps_list_add (const char *name, const char *cmdline, procstat_entry_t *entry)
332 {
333         procstat_t *ps;
334         procstat_entry_t *pse;
335
336         if (entry->id == 0)
337                 return;
338
339         for (ps = list_head_g; ps != NULL; ps = ps->next)
340         {
341                 if ((ps_list_match (name, cmdline, ps)) == 0)
342                         continue;
343
344                 for (pse = ps->instances; pse != NULL; pse = pse->next)
345                         if ((pse->id == entry->id) || (pse->next == NULL))
346                                 break;
347
348                 if ((pse == NULL) || (pse->id != entry->id))
349                 {
350                         procstat_entry_t *new;
351
352                         new = (procstat_entry_t *) malloc (sizeof (procstat_entry_t));
353                         if (new == NULL)
354                                 return;
355                         memset (new, 0, sizeof (procstat_entry_t));
356                         new->id = entry->id;
357
358                         if (pse == NULL)
359                                 ps->instances = new;
360                         else
361                                 pse->next = new;
362
363                         pse = new;
364                 }
365
366                 pse->age = 0;
367                 pse->num_proc   = entry->num_proc;
368                 pse->num_lwp    = entry->num_lwp;
369                 pse->vmem_size  = entry->vmem_size;
370                 pse->vmem_rss   = entry->vmem_rss;
371                 pse->vmem_data  = entry->vmem_data;
372                 pse->vmem_code  = entry->vmem_code;
373                 pse->stack_size = entry->stack_size;
374                 pse->io_rchar   = entry->io_rchar;
375                 pse->io_wchar   = entry->io_wchar;
376                 pse->io_syscr   = entry->io_syscr;
377                 pse->io_syscw   = entry->io_syscw;
378
379                 ps->num_proc   += pse->num_proc;
380                 ps->num_lwp    += pse->num_lwp;
381                 ps->vmem_size  += pse->vmem_size;
382                 ps->vmem_rss   += pse->vmem_rss;
383                 ps->vmem_data  += pse->vmem_data;
384                 ps->vmem_code  += pse->vmem_code;
385                 ps->stack_size += pse->stack_size;
386
387                 ps->io_rchar   += ((pse->io_rchar == -1)?0:pse->io_rchar);
388                 ps->io_wchar   += ((pse->io_wchar == -1)?0:pse->io_wchar);
389                 ps->io_syscr   += ((pse->io_syscr == -1)?0:pse->io_syscr);
390                 ps->io_syscw   += ((pse->io_syscw == -1)?0:pse->io_syscw);
391
392                 if ((entry->vmem_minflt_counter == 0)
393                                 && (entry->vmem_majflt_counter == 0))
394                 {
395                         pse->vmem_minflt_counter += entry->vmem_minflt;
396                         pse->vmem_minflt = entry->vmem_minflt;
397
398                         pse->vmem_majflt_counter += entry->vmem_majflt;
399                         pse->vmem_majflt = entry->vmem_majflt;
400                 }
401                 else
402                 {
403                         if (entry->vmem_minflt_counter < pse->vmem_minflt_counter)
404                         {
405                                 pse->vmem_minflt = entry->vmem_minflt_counter
406                                         + (ULONG_MAX - pse->vmem_minflt_counter);
407                         }
408                         else
409                         {
410                                 pse->vmem_minflt = entry->vmem_minflt_counter - pse->vmem_minflt_counter;
411                         }
412                         pse->vmem_minflt_counter = entry->vmem_minflt_counter;
413
414                         if (entry->vmem_majflt_counter < pse->vmem_majflt_counter)
415                         {
416                                 pse->vmem_majflt = entry->vmem_majflt_counter
417                                         + (ULONG_MAX - pse->vmem_majflt_counter);
418                         }
419                         else
420                         {
421                                 pse->vmem_majflt = entry->vmem_majflt_counter - pse->vmem_majflt_counter;
422                         }
423                         pse->vmem_majflt_counter = entry->vmem_majflt_counter;
424                 }
425
426                 ps->vmem_minflt_counter += pse->vmem_minflt;
427                 ps->vmem_majflt_counter += pse->vmem_majflt;
428
429                 if ((entry->cpu_user_counter == 0)
430                                 && (entry->cpu_system_counter == 0))
431                 {
432                         pse->cpu_user_counter += entry->cpu_user;
433                         pse->cpu_user = entry->cpu_user;
434
435                         pse->cpu_system_counter += entry->cpu_system;
436                         pse->cpu_system = entry->cpu_system;
437                 }
438                 else
439                 {
440                         if (entry->cpu_user_counter < pse->cpu_user_counter)
441                         {
442                                 pse->cpu_user = entry->cpu_user_counter
443                                         + (ULONG_MAX - pse->cpu_user_counter);
444                         }
445                         else
446                         {
447                                 pse->cpu_user = entry->cpu_user_counter - pse->cpu_user_counter;
448                         }
449                         pse->cpu_user_counter = entry->cpu_user_counter;
450
451                         if (entry->cpu_system_counter < pse->cpu_system_counter)
452                         {
453                                 pse->cpu_system = entry->cpu_system_counter
454                                         + (ULONG_MAX - pse->cpu_system_counter);
455                         }
456                         else
457                         {
458                                 pse->cpu_system = entry->cpu_system_counter - pse->cpu_system_counter;
459                         }
460                         pse->cpu_system_counter = entry->cpu_system_counter;
461                 }
462
463                 ps->cpu_user_counter   += pse->cpu_user;
464                 ps->cpu_system_counter += pse->cpu_system;
465         }
466 }
467
468 /* remove old entries from instances of processes in list_head_g */
469 static void ps_list_reset (void)
470 {
471         procstat_t *ps;
472         procstat_entry_t *pse;
473         procstat_entry_t *pse_prev;
474
475         for (ps = list_head_g; ps != NULL; ps = ps->next)
476         {
477                 ps->num_proc    = 0;
478                 ps->num_lwp     = 0;
479                 ps->vmem_size   = 0;
480                 ps->vmem_rss    = 0;
481                 ps->vmem_data   = 0;
482                 ps->vmem_code   = 0;
483                 ps->stack_size  = 0;
484                 ps->io_rchar = -1;
485                 ps->io_wchar = -1;
486                 ps->io_syscr = -1;
487                 ps->io_syscw = -1;
488
489                 pse_prev = NULL;
490                 pse = ps->instances;
491                 while (pse != NULL)
492                 {
493                         if (pse->age > 10)
494                         {
495                                 DEBUG ("Removing this procstat entry cause it's too old: "
496                                                 "id = %lu; name = %s;",
497                                                 pse->id, ps->name);
498
499                                 if (pse_prev == NULL)
500                                 {
501                                         ps->instances = pse->next;
502                                         free (pse);
503                                         pse = ps->instances;
504                                 }
505                                 else
506                                 {
507                                         pse_prev->next = pse->next;
508                                         free (pse);
509                                         pse = pse_prev->next;
510                                 }
511                         }
512                         else
513                         {
514                                 pse->age++;
515                                 pse_prev = pse;
516                                 pse = pse->next;
517                         }
518                 } /* while (pse != NULL) */
519         } /* for (ps = list_head_g; ps != NULL; ps = ps->next) */
520 }
521
522 /* put all pre-defined 'Process' names from config to list_head_g tree */
523 static int ps_config (const char *key, const char *value)
524 {
525         if (strcasecmp (key, "Process") == 0)
526         {
527                 ps_list_register (value, NULL);
528         }
529         else if (strcasecmp (key, "ProcessMatch") == 0)
530         {
531                 char *new_val;
532                 char *fields[3];
533                 int fields_num;
534
535                 new_val = strdup (value);
536                 if (new_val == NULL) {
537                         ERROR ("processes plugin: strdup failed when processing "
538                                         "`ProcessMatch %s'.", value);
539                         return (1);
540                 }
541
542                 fields_num = strsplit (new_val, fields,
543                                 STATIC_ARRAY_SIZE (fields));
544                 if (fields_num != 2)
545                 {
546                         ERROR ("processes plugin: `ProcessMatch' needs exactly "
547                                         "two string arguments.");
548                         sfree (new_val);
549                         return (1);
550                 }
551                 ps_list_register (fields[0], fields[1]);
552                 sfree (new_val);
553         }
554         else
555         {
556                 ERROR ("processes plugin: The `%s' configuration option is not "
557                                 "understood and will be ignored.", key);
558                 return (-1);
559         }
560
561         return (0);
562 }
563
564 static int ps_init (void)
565 {
566 #if HAVE_THREAD_INFO
567         kern_return_t status;
568
569         port_host_self = mach_host_self ();
570         port_task_self = mach_task_self ();
571
572         if (pset_list != NULL)
573         {
574                 vm_deallocate (port_task_self,
575                                 (vm_address_t) pset_list,
576                                 pset_list_len * sizeof (processor_set_t));
577                 pset_list = NULL;
578                 pset_list_len = 0;
579         }
580
581         if ((status = host_processor_sets (port_host_self,
582                                         &pset_list,
583                                         &pset_list_len)) != KERN_SUCCESS)
584         {
585                 ERROR ("host_processor_sets failed: %s\n",
586                                 mach_error_string (status));
587                 pset_list = NULL;
588                 pset_list_len = 0;
589                 return (-1);
590         }
591 /* #endif HAVE_THREAD_INFO */
592
593 #elif KERNEL_LINUX
594         pagesize_g = sysconf(_SC_PAGESIZE);
595         DEBUG ("pagesize_g = %li; CONFIG_HZ = %i;",
596                         pagesize_g, CONFIG_HZ);
597 /* #endif KERNEL_LINUX */
598
599 #elif HAVE_LIBKVM_GETPROCS && HAVE_STRUCT_KINFO_PROC_FREEBSD
600 /* no initialization */
601 /* #endif HAVE_LIBKVM_GETPROCS && HAVE_STRUCT_KINFO_PROC_FREEBSD */
602
603 #elif HAVE_PROCINFO_H
604         pagesize = getpagesize();
605 #endif /* HAVE_PROCINFO_H */
606
607         return (0);
608 } /* int ps_init */
609
610 /* submit global state (e.g.: qty of zombies, running, etc..) */
611 static void ps_submit_state (const char *state, double value)
612 {
613         value_t values[1];
614         value_list_t vl = VALUE_LIST_INIT;
615
616         values[0].gauge = value;
617
618         vl.values = values;
619         vl.values_len = 1;
620         sstrncpy (vl.host, hostname_g, sizeof (vl.host));
621         sstrncpy (vl.plugin, "processes", sizeof (vl.plugin));
622         sstrncpy (vl.plugin_instance, "", sizeof (vl.plugin_instance));
623         sstrncpy (vl.type, "ps_state", sizeof (vl.type));
624         sstrncpy (vl.type_instance, state, sizeof (vl.type_instance));
625
626         plugin_dispatch_values (&vl);
627 }
628
629 /* submit info about specific process (e.g.: memory taken, cpu usage, etc..) */
630 static void ps_submit_proc_list (procstat_t *ps)
631 {
632         value_t values[2];
633         value_list_t vl = VALUE_LIST_INIT;
634
635         vl.values = values;
636         vl.values_len = 2;
637         sstrncpy (vl.host, hostname_g, sizeof (vl.host));
638         sstrncpy (vl.plugin, "processes", sizeof (vl.plugin));
639         sstrncpy (vl.plugin_instance, ps->name, sizeof (vl.plugin_instance));
640
641         sstrncpy (vl.type, "ps_vm", sizeof (vl.type));
642         vl.values[0].gauge = ps->vmem_size;
643         vl.values_len = 1;
644         plugin_dispatch_values (&vl);
645
646         sstrncpy (vl.type, "ps_rss", sizeof (vl.type));
647         vl.values[0].gauge = ps->vmem_rss;
648         vl.values_len = 1;
649         plugin_dispatch_values (&vl);
650
651         sstrncpy (vl.type, "ps_data", sizeof (vl.type));
652         vl.values[0].gauge = ps->vmem_data;
653         vl.values_len = 1;
654         plugin_dispatch_values (&vl);
655
656         sstrncpy (vl.type, "ps_code", sizeof (vl.type));
657         vl.values[0].gauge = ps->vmem_code;
658         vl.values_len = 1;
659         plugin_dispatch_values (&vl);
660
661         sstrncpy (vl.type, "ps_stacksize", sizeof (vl.type));
662         vl.values[0].gauge = ps->stack_size;
663         vl.values_len = 1;
664         plugin_dispatch_values (&vl);
665
666         sstrncpy (vl.type, "ps_cputime", sizeof (vl.type));
667         vl.values[0].derive = ps->cpu_user_counter;
668         vl.values[1].derive = ps->cpu_system_counter;
669         vl.values_len = 2;
670         plugin_dispatch_values (&vl);
671
672         sstrncpy (vl.type, "ps_count", sizeof (vl.type));
673         vl.values[0].gauge = ps->num_proc;
674         vl.values[1].gauge = ps->num_lwp;
675         vl.values_len = 2;
676         plugin_dispatch_values (&vl);
677
678         sstrncpy (vl.type, "ps_pagefaults", sizeof (vl.type));
679         vl.values[0].derive = ps->vmem_minflt_counter;
680         vl.values[1].derive = ps->vmem_majflt_counter;
681         vl.values_len = 2;
682         plugin_dispatch_values (&vl);
683
684         if ( (ps->io_rchar != -1) && (ps->io_wchar != -1) )
685         {
686                 sstrncpy (vl.type, "ps_disk_octets", sizeof (vl.type));
687                 vl.values[0].derive = ps->io_rchar;
688                 vl.values[1].derive = ps->io_wchar;
689                 vl.values_len = 2;
690                 plugin_dispatch_values (&vl);
691         }
692
693         if ( (ps->io_syscr != -1) && (ps->io_syscw != -1) )
694         {
695                 sstrncpy (vl.type, "ps_disk_ops", sizeof (vl.type));
696                 vl.values[0].derive = ps->io_syscr;
697                 vl.values[1].derive = ps->io_syscw;
698                 vl.values_len = 2;
699                 plugin_dispatch_values (&vl);
700         }
701
702         DEBUG ("name = %s; num_proc = %lu; num_lwp = %lu; "
703                         "vmem_size = %lu; vmem_rss = %lu; vmem_data = %lu; "
704                         "vmem_code = %lu; "
705                         "vmem_minflt_counter = %"PRIi64"; vmem_majflt_counter = %"PRIi64"; "
706                         "cpu_user_counter = %"PRIi64"; cpu_system_counter = %"PRIi64"; "
707                         "io_rchar = %"PRIi64"; io_wchar = %"PRIi64"; "
708                         "io_syscr = %"PRIi64"; io_syscw = %"PRIi64";",
709                         ps->name, ps->num_proc, ps->num_lwp,
710                         ps->vmem_size, ps->vmem_rss,
711                         ps->vmem_data, ps->vmem_code,
712                         ps->vmem_minflt_counter, ps->vmem_majflt_counter,
713                         ps->cpu_user_counter, ps->cpu_system_counter,
714                         ps->io_rchar, ps->io_wchar, ps->io_syscr, ps->io_syscw);
715 } /* void ps_submit_proc_list */
716
717 /* ------- additional functions for KERNEL_LINUX/HAVE_THREAD_INFO ------- */
718 #if KERNEL_LINUX
719 static int ps_read_tasks (int pid)
720 {
721         char           dirname[64];
722         DIR           *dh;
723         struct dirent *ent;
724         int count = 0;
725
726         ssnprintf (dirname, sizeof (dirname), "/proc/%i/task", pid);
727
728         if ((dh = opendir (dirname)) == NULL)
729         {
730                 DEBUG ("Failed to open directory `%s'", dirname);
731                 return (-1);
732         }
733
734         while ((ent = readdir (dh)) != NULL)
735         {
736                 if (!isdigit ((int) ent->d_name[0]))
737                         continue;
738                 else
739                         count++;
740         }
741         closedir (dh);
742
743         return ((count >= 1) ? count : 1);
744 } /* int *ps_read_tasks */
745
746 /* Read advanced virtual memory data from /proc/pid/status */
747 static procstat_t *ps_read_vmem (int pid, procstat_t *ps)
748 {
749         FILE *fh;
750         char buffer[1024];
751         char filename[64];
752         unsigned long long lib = 0;
753         unsigned long long exe = 0;
754         unsigned long long data = 0;
755         char *fields[8];
756         int numfields;
757
758         ssnprintf (filename, sizeof (filename), "/proc/%i/status", pid);
759         if ((fh = fopen (filename, "r")) == NULL)
760                 return (NULL);
761
762         while (fgets (buffer, sizeof(buffer), fh) != NULL)
763         {
764                 long long tmp;
765                 char *endptr;
766
767                 if (strncmp (buffer, "Vm", 2) != 0)
768                         continue;
769
770                 numfields = strsplit (buffer, fields,
771                                       STATIC_ARRAY_SIZE (fields));
772
773                 if (numfields < 2)
774                         continue;
775
776                 errno = 0;
777                 endptr = NULL;
778                 tmp = strtoll (fields[1], &endptr, /* base = */ 10);
779                 if ((errno == 0) && (endptr != fields[1]))
780                 {
781                         if (strncmp (buffer, "VmData", 6) == 0) 
782                         {
783                                 data = tmp;
784                         }
785                         else if (strncmp (buffer, "VmLib", 5) == 0)
786                         {
787                                 lib = tmp;
788                         }
789                         else if  (strncmp(buffer, "VmExe", 5) == 0)
790                         {
791                                 exe = tmp;
792                         }
793                 }
794         } /* while (fgets) */
795
796         if (fclose (fh))
797         {
798                 char errbuf[1024];
799                 WARNING ("processes: fclose: %s",
800                                 sstrerror (errno, errbuf, sizeof (errbuf)));
801         }
802
803         ps->vmem_data = data * 1024;
804         ps->vmem_code = (exe + lib) * 1024;
805
806         return (ps);
807 } /* procstat_t *ps_read_vmem */
808
809 static procstat_t *ps_read_io (int pid, procstat_t *ps)
810 {
811         FILE *fh;
812         char buffer[1024];
813         char filename[64];
814
815         char *fields[8];
816         int numfields;
817
818         ssnprintf (filename, sizeof (filename), "/proc/%i/io", pid);
819         if ((fh = fopen (filename, "r")) == NULL)
820                 return (NULL);
821
822         while (fgets (buffer, sizeof (buffer), fh) != NULL)
823         {
824                 derive_t *val = NULL;
825                 long long tmp;
826                 char *endptr;
827
828                 if (strncasecmp (buffer, "rchar:", 6) == 0)
829                         val = &(ps->io_rchar);
830                 else if (strncasecmp (buffer, "wchar:", 6) == 0)
831                         val = &(ps->io_wchar);
832                 else if (strncasecmp (buffer, "syscr:", 6) == 0)
833                         val = &(ps->io_syscr);
834                 else if (strncasecmp (buffer, "syscw:", 6) == 0)
835                         val = &(ps->io_syscw);
836                 else
837                         continue;
838
839                 numfields = strsplit (buffer, fields,
840                                 STATIC_ARRAY_SIZE (fields));
841
842                 if (numfields < 2)
843                         continue;
844
845                 errno = 0;
846                 endptr = NULL;
847                 tmp = strtoll (fields[1], &endptr, /* base = */ 10);
848                 if ((errno != 0) || (endptr == fields[1]))
849                         *val = -1;
850                 else
851                         *val = (derive_t) tmp;
852         } /* while (fgets) */
853
854         if (fclose (fh))
855         {
856                 char errbuf[1024];
857                 WARNING ("processes: fclose: %s",
858                                 sstrerror (errno, errbuf, sizeof (errbuf)));
859         }
860
861         return (ps);
862 } /* procstat_t *ps_read_io */
863
864 int ps_read_process (int pid, procstat_t *ps, char *state)
865 {
866         char  filename[64];
867         char  buffer[1024];
868
869         char *fields[64];
870         char  fields_len;
871
872         int   i;
873
874         int   ppid;
875         int   name_len;
876
877         derive_t cpu_user_counter;
878         derive_t cpu_system_counter;
879         long long unsigned vmem_size;
880         long long unsigned vmem_rss;
881         long long unsigned stack_size;
882
883         memset (ps, 0, sizeof (procstat_t));
884
885         ssnprintf (filename, sizeof (filename), "/proc/%i/stat", pid);
886
887         i = read_file_contents (filename, buffer, sizeof(buffer) - 1);
888         if (i <= 0)
889                 return (-1);
890         buffer[i] = 0;
891
892         fields_len = strsplit (buffer, fields, STATIC_ARRAY_SIZE (fields));
893         if (fields_len < 24)
894         {
895                 DEBUG ("processes plugin: ps_read_process (pid = %i):"
896                                 " `%s' has only %i fields..",
897                                 (int) pid, filename, fields_len);
898                 return (-1);
899         }
900
901         /* copy the name, strip brackets in the process */
902         name_len = strlen (fields[1]) - 2;
903         if ((fields[1][0] != '(') || (fields[1][name_len + 1] != ')'))
904         {
905                 DEBUG ("No brackets found in process name: `%s'", fields[1]);
906                 return (-1);
907         }
908         fields[1] = fields[1] + 1;
909         fields[1][name_len] = '\0';
910         strncpy (ps->name, fields[1], PROCSTAT_NAME_LEN);
911
912         ppid = atoi (fields[3]);
913
914         *state = fields[2][0];
915
916         if (*state == 'Z')
917         {
918                 ps->num_lwp  = 0;
919                 ps->num_proc = 0;
920         }
921         else
922         {
923                 if ( (ps->num_lwp = ps_read_tasks (pid)) == -1 )
924                 {
925                         /* returns -1 => kernel 2.4 */
926                         ps->num_lwp = 1;
927                 }
928                 ps->num_proc = 1;
929         }
930
931         /* Leave the rest at zero if this is only a zombi */
932         if (ps->num_proc == 0)
933         {
934                 DEBUG ("processes plugin: This is only a zombi: pid = %i; "
935                                 "name = %s;", pid, ps->name);
936                 return (0);
937         }
938
939         cpu_user_counter   = atoll (fields[13]);
940         cpu_system_counter = atoll (fields[14]);
941         vmem_size          = atoll (fields[22]);
942         vmem_rss           = atoll (fields[23]);
943         ps->vmem_minflt_counter = atoll (fields[9]);
944         ps->vmem_majflt_counter = atoll (fields[11]);
945
946         {
947                 unsigned long long stack_start = atoll (fields[27]);
948                 unsigned long long stack_ptr   = atoll (fields[28]);
949
950                 stack_size = (stack_start > stack_ptr)
951                         ? stack_start - stack_ptr
952                         : stack_ptr - stack_start;
953         }
954
955         /* Convert jiffies to useconds */
956         cpu_user_counter   = cpu_user_counter   * 1000000 / CONFIG_HZ;
957         cpu_system_counter = cpu_system_counter * 1000000 / CONFIG_HZ;
958         vmem_rss = vmem_rss * pagesize_g;
959
960         if ( (ps_read_vmem(pid, ps)) == NULL)
961         {
962                 /* No VMem data */
963                 ps->vmem_data = -1;
964                 ps->vmem_code = -1;
965                 DEBUG("ps_read_process: did not get vmem data for pid %i",pid);
966         }
967
968         ps->cpu_user_counter = cpu_user_counter;
969         ps->cpu_system_counter = cpu_system_counter;
970         ps->vmem_size = (unsigned long) vmem_size;
971         ps->vmem_rss = (unsigned long) vmem_rss;
972         ps->stack_size = (unsigned long) stack_size;
973
974         if ( (ps_read_io (pid, ps)) == NULL)
975         {
976                 /* no io data */
977                 ps->io_rchar = -1;
978                 ps->io_wchar = -1;
979                 ps->io_syscr = -1;
980                 ps->io_syscw = -1;
981
982                 DEBUG("ps_read_process: not get io data for pid %i",pid);
983         }
984
985         /* success */
986         return (0);
987 } /* int ps_read_process (...) */
988
989 static char *ps_get_cmdline (pid_t pid, char *name, char *buf, size_t buf_len)
990 {
991         char  *buf_ptr;
992         size_t len;
993
994         char file[PATH_MAX];
995         int  fd;
996
997         size_t n;
998
999         if ((pid < 1) || (NULL == buf) || (buf_len < 2))
1000                 return NULL;
1001
1002         ssnprintf (file, sizeof (file), "/proc/%u/cmdline",
1003                         (unsigned int) pid);
1004
1005         errno = 0;
1006         fd = open (file, O_RDONLY);
1007         if (fd < 0) {
1008                 char errbuf[4096];
1009                 /* ENOENT means the process exited while we were handling it.
1010                  * Don't complain about this, it only fills the logs. */
1011                 if (errno != ENOENT)
1012                         WARNING ("processes plugin: Failed to open `%s': %s.", file,
1013                                         sstrerror (errno, errbuf, sizeof (errbuf)));
1014                 return NULL;
1015         }
1016
1017         buf_ptr = buf;
1018         len     = buf_len;
1019
1020         n = 0;
1021
1022         while (42) {
1023                 ssize_t status;
1024
1025                 status = read (fd, (void *)buf_ptr, len);
1026
1027                 if (status < 0) {
1028                         char errbuf[1024];
1029
1030                         if ((EAGAIN == errno) || (EINTR == errno))
1031                                 continue;
1032
1033                         WARNING ("processes plugin: Failed to read from `%s': %s.", file,
1034                                         sstrerror (errno, errbuf, sizeof (errbuf)));
1035                         close (fd);
1036                         return NULL;
1037                 }
1038
1039                 n += status;
1040
1041                 if (status == 0)
1042                         break;
1043
1044                 buf_ptr += status;
1045                 len     -= status;
1046
1047                 if (len <= 0)
1048                         break;
1049         }
1050
1051         close (fd);
1052
1053         if (0 == n) {
1054                 /* cmdline not available; e.g. kernel thread, zombie */
1055                 if (NULL == name)
1056                         return NULL;
1057
1058                 ssnprintf (buf, buf_len, "[%s]", name);
1059                 return buf;
1060         }
1061
1062         assert (n <= buf_len);
1063
1064         if (n == buf_len)
1065                 --n;
1066         buf[n] = '\0';
1067
1068         --n;
1069         /* remove trailing whitespace */
1070         while ((n > 0) && (isspace (buf[n]) || ('\0' == buf[n]))) {
1071                 buf[n] = '\0';
1072                 --n;
1073         }
1074
1075         /* arguments are separated by '\0' in /proc/<pid>/cmdline */
1076         while (n > 0) {
1077                 if ('\0' == buf[n])
1078                         buf[n] = ' ';
1079                 --n;
1080         }
1081         return buf;
1082 } /* char *ps_get_cmdline (...) */
1083
1084 static unsigned long read_fork_rate ()
1085 {
1086         FILE *proc_stat;
1087         char buf[1024];
1088         unsigned long result = 0;
1089         int numfields;
1090         char *fields[3];
1091
1092         proc_stat = fopen("/proc/stat", "r");
1093         if (proc_stat == NULL) {
1094                 char errbuf[1024];
1095                 ERROR ("processes plugin: fopen (/proc/stat) failed: %s",
1096                                 sstrerror (errno, errbuf, sizeof (errbuf)));
1097                 return ULONG_MAX;
1098         }
1099
1100         while (fgets (buf, sizeof(buf), proc_stat) != NULL)
1101         {
1102                 char *endptr;
1103
1104                 numfields = strsplit(buf, fields, STATIC_ARRAY_SIZE (fields));
1105                 if (numfields != 2)
1106                         continue;
1107
1108                 if (strcmp ("processes", fields[0]) != 0)
1109                         continue;
1110
1111                 errno = 0;
1112                 endptr = NULL;
1113                 result = strtoul(fields[1], &endptr, /* base = */ 10);
1114                 if ((endptr == fields[1]) || (errno != 0)) {
1115                         ERROR ("processes plugin: Cannot parse fork rate: %s",
1116                                         fields[1]);
1117                         result = ULONG_MAX;
1118                         break;
1119                 }
1120
1121                 break;
1122         }
1123
1124         fclose(proc_stat);
1125
1126         return result;
1127 }
1128
1129 static void ps_submit_fork_rate (unsigned long value)
1130 {
1131         value_t values[1];
1132         value_list_t vl = VALUE_LIST_INIT;
1133
1134         values[0].derive = (derive_t) value;
1135
1136         vl.values = values;
1137         vl.values_len = 1;
1138         sstrncpy (vl.host, hostname_g, sizeof (vl.host));
1139         sstrncpy (vl.plugin, "processes", sizeof (vl.plugin));
1140         sstrncpy (vl.plugin_instance, "", sizeof (vl.plugin_instance));
1141         sstrncpy (vl.type, "fork_rate", sizeof (vl.type));
1142         sstrncpy (vl.type_instance, "", sizeof (vl.type_instance));
1143
1144         plugin_dispatch_values (&vl);
1145 }
1146
1147 #endif /* KERNEL_LINUX */
1148
1149 #if HAVE_THREAD_INFO
1150 static int mach_get_task_name (task_t t, int *pid, char *name, size_t name_max_len)
1151 {
1152         int mib[4];
1153
1154         struct kinfo_proc kp;
1155         size_t            kp_size;
1156
1157         mib[0] = CTL_KERN;
1158         mib[1] = KERN_PROC;
1159         mib[2] = KERN_PROC_PID;
1160
1161         if (pid_for_task (t, pid) != KERN_SUCCESS)
1162                 return (-1);
1163         mib[3] = *pid;
1164
1165         kp_size = sizeof (kp);
1166         if (sysctl (mib, 4, &kp, &kp_size, NULL, 0) != 0)
1167                 return (-1);
1168
1169         if (name_max_len > (MAXCOMLEN + 1))
1170                 name_max_len = MAXCOMLEN + 1;
1171
1172         strncpy (name, kp.kp_proc.p_comm, name_max_len - 1);
1173         name[name_max_len - 1] = '\0';
1174
1175         DEBUG ("pid = %i; name = %s;", *pid, name);
1176
1177         /* We don't do the special handling for `p_comm == "LaunchCFMApp"' as
1178          * `top' does it, because it is a lot of work and only used when
1179          * debugging. -octo */
1180
1181         return (0);
1182 }
1183 #endif /* HAVE_THREAD_INFO */
1184 /* ------- end of additional functions for KERNEL_LINUX/HAVE_THREAD_INFO ------- */
1185
1186 /* do actual readings from kernel */
1187 static int ps_read (void)
1188 {
1189 #if HAVE_THREAD_INFO
1190         kern_return_t            status;
1191
1192         int                      pset;
1193         processor_set_t          port_pset_priv;
1194
1195         int                      task;
1196         task_array_t             task_list;
1197         mach_msg_type_number_t   task_list_len;
1198
1199         int                      task_pid;
1200         char                     task_name[MAXCOMLEN + 1];
1201
1202         int                      thread;
1203         thread_act_array_t       thread_list;
1204         mach_msg_type_number_t   thread_list_len;
1205         thread_basic_info_data_t thread_data;
1206         mach_msg_type_number_t   thread_data_len;
1207
1208         int running  = 0;
1209         int sleeping = 0;
1210         int zombies  = 0;
1211         int stopped  = 0;
1212         int blocked  = 0;
1213
1214         procstat_t *ps;
1215         procstat_entry_t pse;
1216
1217         ps_list_reset ();
1218
1219         /*
1220          * The Mach-concept is a little different from the traditional UNIX
1221          * concept: All the work is done in threads. Threads are contained in
1222          * `tasks'. Therefore, `task status' doesn't make much sense, since
1223          * it's actually a `thread status'.
1224          * Tasks are assigned to sets of processors, so that's where you go to
1225          * get a list.
1226          */
1227         for (pset = 0; pset < pset_list_len; pset++)
1228         {
1229                 if ((status = host_processor_set_priv (port_host_self,
1230                                                 pset_list[pset],
1231                                                 &port_pset_priv)) != KERN_SUCCESS)
1232                 {
1233                         ERROR ("host_processor_set_priv failed: %s\n",
1234                                         mach_error_string (status));
1235                         continue;
1236                 }
1237
1238                 if ((status = processor_set_tasks (port_pset_priv,
1239                                                 &task_list,
1240                                                 &task_list_len)) != KERN_SUCCESS)
1241                 {
1242                         ERROR ("processor_set_tasks failed: %s\n",
1243                                         mach_error_string (status));
1244                         mach_port_deallocate (port_task_self, port_pset_priv);
1245                         continue;
1246                 }
1247
1248                 for (task = 0; task < task_list_len; task++)
1249                 {
1250                         ps = NULL;
1251                         if (mach_get_task_name (task_list[task],
1252                                                 &task_pid,
1253                                                 task_name, PROCSTAT_NAME_LEN) == 0)
1254                         {
1255                                 /* search for at least one match */
1256                                 for (ps = list_head_g; ps != NULL; ps = ps->next)
1257                                         /* FIXME: cmdline should be here instead of NULL */
1258                                         if (ps_list_match (task_name, NULL, ps) == 1)
1259                                                 break;
1260                         }
1261
1262                         /* Collect more detailed statistics for this process */
1263                         if (ps != NULL)
1264                         {
1265                                 task_basic_info_data_t        task_basic_info;
1266                                 mach_msg_type_number_t        task_basic_info_len;
1267                                 task_events_info_data_t       task_events_info;
1268                                 mach_msg_type_number_t        task_events_info_len;
1269                                 task_absolutetime_info_data_t task_absolutetime_info;
1270                                 mach_msg_type_number_t        task_absolutetime_info_len;
1271
1272                                 memset (&pse, '\0', sizeof (pse));
1273                                 pse.id = task_pid;
1274
1275                                 task_basic_info_len = TASK_BASIC_INFO_COUNT;
1276                                 status = task_info (task_list[task],
1277                                                 TASK_BASIC_INFO,
1278                                                 (task_info_t) &task_basic_info,
1279                                                 &task_basic_info_len);
1280                                 if (status != KERN_SUCCESS)
1281                                 {
1282                                         ERROR ("task_info failed: %s",
1283                                                         mach_error_string (status));
1284                                         continue; /* with next thread_list */
1285                                 }
1286
1287                                 task_events_info_len = TASK_EVENTS_INFO_COUNT;
1288                                 status = task_info (task_list[task],
1289                                                 TASK_EVENTS_INFO,
1290                                                 (task_info_t) &task_events_info,
1291                                                 &task_events_info_len);
1292                                 if (status != KERN_SUCCESS)
1293                                 {
1294                                         ERROR ("task_info failed: %s",
1295                                                         mach_error_string (status));
1296                                         continue; /* with next thread_list */
1297                                 }
1298
1299                                 task_absolutetime_info_len = TASK_ABSOLUTETIME_INFO_COUNT;
1300                                 status = task_info (task_list[task],
1301                                                 TASK_ABSOLUTETIME_INFO,
1302                                                 (task_info_t) &task_absolutetime_info,
1303                                                 &task_absolutetime_info_len);
1304                                 if (status != KERN_SUCCESS)
1305                                 {
1306                                         ERROR ("task_info failed: %s",
1307                                                         mach_error_string (status));
1308                                         continue; /* with next thread_list */
1309                                 }
1310
1311                                 pse.num_proc++;
1312                                 pse.vmem_size = task_basic_info.virtual_size;
1313                                 pse.vmem_rss = task_basic_info.resident_size;
1314                                 /* Does not seem to be easily exposed */
1315                                 pse.vmem_data = 0;
1316                                 pse.vmem_code = 0;
1317
1318                                 pse.vmem_minflt_counter = task_events_info.cow_faults;
1319                                 pse.vmem_majflt_counter = task_events_info.faults;
1320
1321                                 pse.cpu_user_counter = task_absolutetime_info.total_user;
1322                                 pse.cpu_system_counter = task_absolutetime_info.total_system;
1323                         }
1324
1325                         status = task_threads (task_list[task], &thread_list,
1326                                         &thread_list_len);
1327                         if (status != KERN_SUCCESS)
1328                         {
1329                                 /* Apple's `top' treats this case a zombie. It
1330                                  * makes sense to some extend: A `zombie'
1331                                  * thread is nonsense, since the task/process
1332                                  * is dead. */
1333                                 zombies++;
1334                                 DEBUG ("task_threads failed: %s",
1335                                                 mach_error_string (status));
1336                                 if (task_list[task] != port_task_self)
1337                                         mach_port_deallocate (port_task_self,
1338                                                         task_list[task]);
1339                                 continue; /* with next task_list */
1340                         }
1341
1342                         for (thread = 0; thread < thread_list_len; thread++)
1343                         {
1344                                 thread_data_len = THREAD_BASIC_INFO_COUNT;
1345                                 status = thread_info (thread_list[thread],
1346                                                 THREAD_BASIC_INFO,
1347                                                 (thread_info_t) &thread_data,
1348                                                 &thread_data_len);
1349                                 if (status != KERN_SUCCESS)
1350                                 {
1351                                         ERROR ("thread_info failed: %s",
1352                                                         mach_error_string (status));
1353                                         if (task_list[task] != port_task_self)
1354                                                 mach_port_deallocate (port_task_self,
1355                                                                 thread_list[thread]);
1356                                         continue; /* with next thread_list */
1357                                 }
1358
1359                                 if (ps != NULL)
1360                                         pse.num_lwp++;
1361
1362                                 switch (thread_data.run_state)
1363                                 {
1364                                         case TH_STATE_RUNNING:
1365                                                 running++;
1366                                                 break;
1367                                         case TH_STATE_STOPPED:
1368                                         /* What exactly is `halted'? */
1369                                         case TH_STATE_HALTED:
1370                                                 stopped++;
1371                                                 break;
1372                                         case TH_STATE_WAITING:
1373                                                 sleeping++;
1374                                                 break;
1375                                         case TH_STATE_UNINTERRUPTIBLE:
1376                                                 blocked++;
1377                                                 break;
1378                                         /* There is no `zombie' case here,
1379                                          * since there are no zombie-threads.
1380                                          * There's only zombie tasks, which are
1381                                          * handled above. */
1382                                         default:
1383                                                 WARNING ("Unknown thread status: %i",
1384                                                                 thread_data.run_state);
1385                                                 break;
1386                                 } /* switch (thread_data.run_state) */
1387
1388                                 if (task_list[task] != port_task_self)
1389                                 {
1390                                         status = mach_port_deallocate (port_task_self,
1391                                                         thread_list[thread]);
1392                                         if (status != KERN_SUCCESS)
1393                                                 ERROR ("mach_port_deallocate failed: %s",
1394                                                                 mach_error_string (status));
1395                                 }
1396                         } /* for (thread_list) */
1397
1398                         if ((status = vm_deallocate (port_task_self,
1399                                                         (vm_address_t) thread_list,
1400                                                         thread_list_len * sizeof (thread_act_t)))
1401                                         != KERN_SUCCESS)
1402                         {
1403                                 ERROR ("vm_deallocate failed: %s",
1404                                                 mach_error_string (status));
1405                         }
1406                         thread_list = NULL;
1407                         thread_list_len = 0;
1408
1409                         /* Only deallocate the task port, if it isn't our own.
1410                          * Don't know what would happen in that case, but this
1411                          * is what Apple's top does.. ;) */
1412                         if (task_list[task] != port_task_self)
1413                         {
1414                                 status = mach_port_deallocate (port_task_self,
1415                                                 task_list[task]);
1416                                 if (status != KERN_SUCCESS)
1417                                         ERROR ("mach_port_deallocate failed: %s",
1418                                                         mach_error_string (status));
1419                         }
1420
1421                         if (ps != NULL)
1422                                 /* FIXME: cmdline should be here instead of NULL */
1423                                 ps_list_add (task_name, NULL, &pse);
1424                 } /* for (task_list) */
1425
1426                 if ((status = vm_deallocate (port_task_self,
1427                                 (vm_address_t) task_list,
1428                                 task_list_len * sizeof (task_t))) != KERN_SUCCESS)
1429                 {
1430                         ERROR ("vm_deallocate failed: %s",
1431                                         mach_error_string (status));
1432                 }
1433                 task_list = NULL;
1434                 task_list_len = 0;
1435
1436                 if ((status = mach_port_deallocate (port_task_self, port_pset_priv))
1437                                 != KERN_SUCCESS)
1438                 {
1439                         ERROR ("mach_port_deallocate failed: %s",
1440                                         mach_error_string (status));
1441                 }
1442         } /* for (pset_list) */
1443
1444         ps_submit_state ("running", running);
1445         ps_submit_state ("sleeping", sleeping);
1446         ps_submit_state ("zombies", zombies);
1447         ps_submit_state ("stopped", stopped);
1448         ps_submit_state ("blocked", blocked);
1449
1450         for (ps = list_head_g; ps != NULL; ps = ps->next)
1451                 ps_submit_proc_list (ps);
1452 /* #endif HAVE_THREAD_INFO */
1453
1454 #elif KERNEL_LINUX
1455         int running  = 0;
1456         int sleeping = 0;
1457         int zombies  = 0;
1458         int stopped  = 0;
1459         int paging   = 0;
1460         int blocked  = 0;
1461
1462         struct dirent *ent;
1463         DIR           *proc;
1464         int            pid;
1465
1466         char cmdline[ARG_MAX];
1467
1468         int        status;
1469         procstat_t ps;
1470         procstat_entry_t pse;
1471         char       state;
1472
1473         unsigned long fork_rate;
1474
1475         procstat_t *ps_ptr;
1476
1477         running = sleeping = zombies = stopped = paging = blocked = 0;
1478         ps_list_reset ();
1479
1480         if ((proc = opendir ("/proc")) == NULL)
1481         {
1482                 char errbuf[1024];
1483                 ERROR ("Cannot open `/proc': %s",
1484                                 sstrerror (errno, errbuf, sizeof (errbuf)));
1485                 return (-1);
1486         }
1487
1488         while ((ent = readdir (proc)) != NULL)
1489         {
1490                 if (!isdigit (ent->d_name[0]))
1491                         continue;
1492
1493                 if ((pid = atoi (ent->d_name)) < 1)
1494                         continue;
1495
1496                 status = ps_read_process (pid, &ps, &state);
1497                 if (status != 0)
1498                 {
1499                         DEBUG ("ps_read_process failed: %i", status);
1500                         continue;
1501                 }
1502
1503                 pse.id       = pid;
1504                 pse.age      = 0;
1505
1506                 pse.num_proc   = ps.num_proc;
1507                 pse.num_lwp    = ps.num_lwp;
1508                 pse.vmem_size  = ps.vmem_size;
1509                 pse.vmem_rss   = ps.vmem_rss;
1510                 pse.vmem_data  = ps.vmem_data;
1511                 pse.vmem_code  = ps.vmem_code;
1512                 pse.stack_size = ps.stack_size;
1513
1514                 pse.vmem_minflt = 0;
1515                 pse.vmem_minflt_counter = ps.vmem_minflt_counter;
1516                 pse.vmem_majflt = 0;
1517                 pse.vmem_majflt_counter = ps.vmem_majflt_counter;
1518
1519                 pse.cpu_user = 0;
1520                 pse.cpu_user_counter = ps.cpu_user_counter;
1521                 pse.cpu_system = 0;
1522                 pse.cpu_system_counter = ps.cpu_system_counter;
1523
1524                 pse.io_rchar = ps.io_rchar;
1525                 pse.io_wchar = ps.io_wchar;
1526                 pse.io_syscr = ps.io_syscr;
1527                 pse.io_syscw = ps.io_syscw;
1528
1529                 switch (state)
1530                 {
1531                         case 'R': running++;  break;
1532                         case 'S': sleeping++; break;
1533                         case 'D': blocked++;  break;
1534                         case 'Z': zombies++;  break;
1535                         case 'T': stopped++;  break;
1536                         case 'W': paging++;   break;
1537                 }
1538
1539                 ps_list_add (ps.name,
1540                                 ps_get_cmdline (pid, ps.name, cmdline, sizeof (cmdline)),
1541                                 &pse);
1542         }
1543
1544         closedir (proc);
1545
1546         ps_submit_state ("running",  running);
1547         ps_submit_state ("sleeping", sleeping);
1548         ps_submit_state ("zombies",  zombies);
1549         ps_submit_state ("stopped",  stopped);
1550         ps_submit_state ("paging",   paging);
1551         ps_submit_state ("blocked",  blocked);
1552
1553         for (ps_ptr = list_head_g; ps_ptr != NULL; ps_ptr = ps_ptr->next)
1554                 ps_submit_proc_list (ps_ptr);
1555
1556         fork_rate = read_fork_rate();
1557         if (fork_rate != ULONG_MAX)
1558                 ps_submit_fork_rate(fork_rate);
1559 /* #endif KERNEL_LINUX */
1560
1561 #elif HAVE_LIBKVM_GETPROCS && HAVE_STRUCT_KINFO_PROC_FREEBSD
1562         int running  = 0;
1563         int sleeping = 0;
1564         int zombies  = 0;
1565         int stopped  = 0;
1566         int blocked  = 0;
1567         int idle     = 0;
1568         int wait     = 0;
1569
1570         kvm_t *kd;
1571         char errbuf[1024];
1572         char cmdline[ARG_MAX];
1573         char *cmdline_ptr;
1574         struct kinfo_proc *procs;          /* array of processes */
1575         char **argv;
1576         int count;                         /* returns number of processes */
1577         int i;
1578
1579         procstat_t *ps_ptr;
1580         procstat_entry_t pse;
1581
1582         ps_list_reset ();
1583
1584         /* Open the kvm interface, get a descriptor */
1585         kd = kvm_open (NULL, NULL, NULL, 0, errbuf);
1586         if (kd == NULL)
1587         {
1588                 ERROR ("processes plugin: Cannot open kvm interface: %s",
1589                                 errbuf);
1590                 return (0);
1591         }
1592
1593         /* Get the list of processes. */
1594         procs = kvm_getprocs(kd, KERN_PROC_ALL, 0, &count);
1595         if (procs == NULL)
1596         {
1597                 kvm_close (kd);
1598                 ERROR ("processes plugin: Cannot get kvm processes list: %s",
1599                                 kvm_geterr(kd));
1600                 return (0);
1601         }
1602
1603         /* Iterate through the processes in kinfo_proc */
1604         for (i = 0; i < count; i++)
1605         {
1606                 /* retrieve the arguments */
1607                 cmdline[0] = 0;
1608                 cmdline_ptr = NULL;
1609
1610                 argv = kvm_getargv (kd, (const struct kinfo_proc *) &(procs[i]), 0);
1611                 if (argv != NULL)
1612                 {
1613                         int status;
1614                         int argc;
1615
1616                         argc = 0;
1617                         while (argv[argc] != NULL)
1618                                 argc++;
1619
1620                         status = strjoin (cmdline, sizeof (cmdline),
1621                                         argv, argc, " ");
1622
1623                         if (status < 0)
1624                         {
1625                                 WARNING ("processes plugin: Command line did "
1626                                                 "not fit into buffer.");
1627                         }
1628                         else
1629                         {
1630                                 cmdline_ptr = &cmdline[0];
1631                         }
1632                 }
1633
1634                 pse.id       = procs[i].ki_pid;
1635                 pse.age      = 0;
1636
1637                 pse.num_proc = 1;
1638                 pse.num_lwp  = procs[i].ki_numthreads;
1639
1640                 pse.vmem_size = procs[i].ki_size;
1641                 pse.vmem_rss = procs[i].ki_rssize * getpagesize();
1642                 pse.vmem_data = procs[i].ki_dsize * getpagesize();
1643                 pse.vmem_code = procs[i].ki_tsize * getpagesize();
1644                 pse.stack_size = procs[i].ki_ssize * getpagesize();
1645                 pse.vmem_minflt = 0;
1646                 pse.vmem_minflt_counter = procs[i].ki_rusage.ru_minflt;
1647                 pse.vmem_majflt = 0;
1648                 pse.vmem_majflt_counter = procs[i].ki_rusage.ru_majflt;
1649
1650                 pse.cpu_user = 0;
1651                 pse.cpu_user_counter = procs[i].ki_rusage.ru_utime.tv_sec
1652                         * 1000
1653                         + procs[i].ki_rusage.ru_utime.tv_usec;
1654                 pse.cpu_system = 0;
1655                 pse.cpu_system_counter = procs[i].ki_rusage.ru_stime.tv_sec
1656                         * 1000
1657                         + procs[i].ki_rusage.ru_stime.tv_usec;
1658
1659                 /* no io data */
1660                 pse.io_rchar = -1;
1661                 pse.io_wchar = -1;
1662                 pse.io_syscr = -1;
1663                 pse.io_syscw = -1;
1664
1665                 switch (procs[i].ki_stat)
1666                 {
1667                         case SSTOP:     stopped++;      break;
1668                         case SSLEEP:    sleeping++;     break;
1669                         case SRUN:      running++;      break;
1670                         case SIDL:      idle++;         break;
1671                         case SWAIT:     wait++;         break;
1672                         case SLOCK:     blocked++;      break;
1673                         case SZOMB:     zombies++;      break;
1674                 }
1675
1676                 ps_list_add (procs[i].ki_comm, cmdline_ptr, &pse);
1677         }
1678
1679         kvm_close(kd);
1680
1681         ps_submit_state ("running",  running);
1682         ps_submit_state ("sleeping", sleeping);
1683         ps_submit_state ("zombies",  zombies);
1684         ps_submit_state ("stopped",  stopped);
1685         ps_submit_state ("blocked",  blocked);
1686         ps_submit_state ("idle",     idle);
1687         ps_submit_state ("wait",     wait);
1688
1689         for (ps_ptr = list_head_g; ps_ptr != NULL; ps_ptr = ps_ptr->next)
1690                 ps_submit_proc_list (ps_ptr);
1691 /* #endif HAVE_LIBKVM_GETPROCS && HAVE_STRUCT_KINFO_PROC_FREEBSD */
1692
1693 #elif HAVE_PROCINFO_H
1694         /* AIX */
1695         int running  = 0;
1696         int sleeping = 0;
1697         int zombies  = 0;
1698         int stopped  = 0;
1699         int paging   = 0;
1700         int blocked  = 0;
1701
1702         pid_t pindex = 0;
1703         int nprocs;
1704
1705         procstat_t *ps;
1706         procstat_entry_t pse;
1707
1708         ps_list_reset ();
1709         while ((nprocs = getprocs64 (procentry, sizeof(struct procentry64),
1710                                         /* fdsinfo = */ NULL, sizeof(struct fdsinfo64),
1711                                         &pindex, MAXPROCENTRY)) > 0)
1712         {
1713                 int i;
1714
1715                 for (i = 0; i < nprocs; i++)
1716                 {
1717                         tid64_t thindex;
1718                         int nthreads;
1719                         char arglist[MAXARGLN+1];
1720                         char *cargs;
1721                         char *cmdline;
1722
1723                         if (procentry[i].pi_state == SNONE) continue;
1724                         /* if (procentry[i].pi_state == SZOMB)  FIXME */
1725
1726                         cmdline = procentry[i].pi_comm;
1727                         cargs = procentry[i].pi_comm;
1728                         if ( procentry[i].pi_flags & SKPROC )
1729                         {
1730                                 if (procentry[i].pi_pid == 0)
1731                                         cmdline = "swapper";
1732                                 cargs = cmdline;
1733                         }
1734                         else
1735                         {
1736                                 if (getargs(&procentry[i], sizeof(struct procentry64), arglist, MAXARGLN) >= 0)
1737                                 {
1738                                         int n;
1739
1740                                         n = -1;
1741                                         while (++n < MAXARGLN)
1742                                         {
1743                                                 if (arglist[n] == '\0')
1744                                                 {
1745                                                         if (arglist[n+1] == '\0')
1746                                                                 break;
1747                                                         arglist[n] = ' ';
1748                                                 }
1749                                         }
1750                                         cargs = arglist;
1751                                 }
1752                         }
1753
1754                         pse.id       = procentry[i].pi_pid;
1755                         pse.age      = 0;
1756                         pse.num_lwp  = procentry[i].pi_thcount;
1757                         pse.num_proc = 1;
1758
1759                         thindex=0;
1760                         while ((nthreads = getthrds64(procentry[i].pi_pid,
1761                                                         thrdentry, sizeof(struct thrdentry64),
1762                                                         &thindex, MAXTHRDENTRY)) > 0)
1763                         {
1764                                 int j;
1765
1766                                 for (j=0; j< nthreads; j++)
1767                                 {
1768                                         switch (thrdentry[j].ti_state)
1769                                         {
1770                                                 /* case TSNONE: break; */
1771                                                 case TSIDL:     blocked++;      break; /* FIXME is really blocked */
1772                                                 case TSRUN:     running++;      break;
1773                                                 case TSSLEEP:   sleeping++;     break;
1774                                                 case TSSWAP:    paging++;       break;
1775                                                 case TSSTOP:    stopped++;      break;
1776                                                 case TSZOMB:    zombies++;      break;
1777                                         }
1778                                 }
1779                                 if (nthreads < MAXTHRDENTRY)
1780                                         break;
1781                         }
1782
1783                         pse.cpu_user = 0;
1784                         /* tv_usec is nanosec ??? */
1785                         pse.cpu_user_counter = procentry[i].pi_ru.ru_utime.tv_sec * 1000000 +
1786                                 procentry[i].pi_ru.ru_utime.tv_usec / 1000;
1787
1788                         pse.cpu_system = 0;
1789                         /* tv_usec is nanosec ??? */
1790                         pse.cpu_system_counter = procentry[i].pi_ru.ru_stime.tv_sec * 1000000 +
1791                                 procentry[i].pi_ru.ru_stime.tv_usec / 1000;
1792
1793                         pse.vmem_minflt = 0;
1794                         pse.vmem_minflt_counter = procentry[i].pi_minflt;
1795                         pse.vmem_majflt = 0;
1796                         pse.vmem_majflt_counter = procentry[i].pi_majflt;
1797
1798                         pse.vmem_size = procentry[i].pi_tsize + procentry[i].pi_dvm * pagesize;
1799                         pse.vmem_rss = (procentry[i].pi_drss + procentry[i].pi_trss) * pagesize;
1800                         /* Not supported */
1801                         pse.vmem_data = 0;
1802                         pse.vmem_code = 0;
1803                         pse.stack_size =  0;
1804
1805                         pse.io_rchar = -1;
1806                         pse.io_wchar = -1;
1807                         pse.io_syscr = -1;
1808                         pse.io_syscw = -1;
1809
1810                         ps_list_add (cmdline, cargs, &pse);
1811                 } /* for (i = 0 .. nprocs) */
1812
1813                 if (nprocs < MAXPROCENTRY)
1814                         break;
1815         } /* while (getprocs64() > 0) */
1816         ps_submit_state ("running",  running);
1817         ps_submit_state ("sleeping", sleeping);
1818         ps_submit_state ("zombies",  zombies);
1819         ps_submit_state ("stopped",  stopped);
1820         ps_submit_state ("paging",   paging);
1821         ps_submit_state ("blocked",  blocked);
1822
1823         for (ps = list_head_g; ps != NULL; ps = ps->next)
1824                 ps_submit_proc_list (ps);
1825 #endif /* HAVE_PROCINFO_H */
1826
1827         return (0);
1828 } /* int ps_read */
1829
1830 void module_register (void)
1831 {
1832         plugin_register_config ("processes", ps_config,
1833                         config_keys, config_keys_num);
1834         plugin_register_init ("processes", ps_init);
1835         plugin_register_read ("processes", ps_read);
1836 } /* void module_register */