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