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