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