Code

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