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