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