Buffer and memory allocation related bug fixes and 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 /* ------- additional functions for KERNEL_LINUX/HAVE_THREAD_INFO ------- */
741 #if KERNEL_LINUX
742 static int ps_read_tasks (int pid)
743 {
744         char           dirname[64];
745         DIR           *dh;
746         struct dirent *ent;
747         int count = 0;
748
749         ssnprintf (dirname, sizeof (dirname), "/proc/%i/task", pid);
750
751         if ((dh = opendir (dirname)) == NULL)
752         {
753                 DEBUG ("Failed to open directory `%s'", dirname);
754                 return (-1);
755         }
756
757         while ((ent = readdir (dh)) != NULL)
758         {
759                 if (!isdigit ((int) ent->d_name[0]))
760                         continue;
761                 else
762                         count++;
763         }
764         closedir (dh);
765
766         return ((count >= 1) ? count : 1);
767 } /* int *ps_read_tasks */
768
769 /* Read advanced virtual memory data from /proc/pid/status */
770 static procstat_t *ps_read_vmem (int pid, procstat_t *ps)
771 {
772         FILE *fh;
773         char buffer[1024];
774         char filename[64];
775         unsigned long long lib = 0;
776         unsigned long long exe = 0;
777         unsigned long long data = 0;
778         char *fields[8];
779         int numfields;
780
781         ssnprintf (filename, sizeof (filename), "/proc/%i/status", pid);
782         if ((fh = fopen (filename, "r")) == NULL)
783                 return (NULL);
784
785         while (fgets (buffer, sizeof(buffer), fh) != NULL)
786         {
787                 long long tmp;
788                 char *endptr;
789
790                 if (strncmp (buffer, "Vm", 2) != 0)
791                         continue;
792
793                 numfields = strsplit (buffer, fields,
794                                       STATIC_ARRAY_SIZE (fields));
795
796                 if (numfields < 2)
797                         continue;
798
799                 errno = 0;
800                 endptr = NULL;
801                 tmp = strtoll (fields[1], &endptr, /* base = */ 10);
802                 if ((errno == 0) && (endptr != fields[1]))
803                 {
804                         if (strncmp (buffer, "VmData", 6) == 0)
805                         {
806                                 data = tmp;
807                         }
808                         else if (strncmp (buffer, "VmLib", 5) == 0)
809                         {
810                                 lib = tmp;
811                         }
812                         else if  (strncmp(buffer, "VmExe", 5) == 0)
813                         {
814                                 exe = tmp;
815                         }
816                 }
817         } /* while (fgets) */
818
819         if (fclose (fh))
820         {
821                 char errbuf[1024];
822                 WARNING ("processes: fclose: %s",
823                                 sstrerror (errno, errbuf, sizeof (errbuf)));
824         }
825
826         ps->vmem_data = data * 1024;
827         ps->vmem_code = (exe + lib) * 1024;
828
829         return (ps);
830 } /* procstat_t *ps_read_vmem */
831
832 static procstat_t *ps_read_io (int pid, procstat_t *ps)
833 {
834         FILE *fh;
835         char buffer[1024];
836         char filename[64];
837
838         char *fields[8];
839         int numfields;
840
841         ssnprintf (filename, sizeof (filename), "/proc/%i/io", pid);
842         if ((fh = fopen (filename, "r")) == NULL)
843                 return (NULL);
844
845         while (fgets (buffer, sizeof (buffer), fh) != NULL)
846         {
847                 derive_t *val = NULL;
848                 long long tmp;
849                 char *endptr;
850
851                 if (strncasecmp (buffer, "rchar:", 6) == 0)
852                         val = &(ps->io_rchar);
853                 else if (strncasecmp (buffer, "wchar:", 6) == 0)
854                         val = &(ps->io_wchar);
855                 else if (strncasecmp (buffer, "syscr:", 6) == 0)
856                         val = &(ps->io_syscr);
857                 else if (strncasecmp (buffer, "syscw:", 6) == 0)
858                         val = &(ps->io_syscw);
859                 else
860                         continue;
861
862                 numfields = strsplit (buffer, fields,
863                                 STATIC_ARRAY_SIZE (fields));
864
865                 if (numfields < 2)
866                         continue;
867
868                 errno = 0;
869                 endptr = NULL;
870                 tmp = strtoll (fields[1], &endptr, /* base = */ 10);
871                 if ((errno != 0) || (endptr == fields[1]))
872                         *val = -1;
873                 else
874                         *val = (derive_t) tmp;
875         } /* while (fgets) */
876
877         if (fclose (fh))
878         {
879                 char errbuf[1024];
880                 WARNING ("processes: fclose: %s",
881                                 sstrerror (errno, errbuf, sizeof (errbuf)));
882         }
883
884         return (ps);
885 } /* procstat_t *ps_read_io */
886
887 int ps_read_process (int pid, procstat_t *ps, char *state)
888 {
889         char  filename[64];
890         char  buffer[1024];
891
892         char *fields[64];
893         char  fields_len;
894
895         int   buffer_len;
896
897         char *buffer_ptr;
898         size_t name_start_pos;
899         size_t name_end_pos;
900         size_t name_len;
901
902         derive_t cpu_user_counter;
903         derive_t cpu_system_counter;
904         long long unsigned vmem_size;
905         long long unsigned vmem_rss;
906         long long unsigned stack_size;
907
908         memset (ps, 0, sizeof (procstat_t));
909
910         ssnprintf (filename, sizeof (filename), "/proc/%i/stat", pid);
911
912         buffer_len = read_file_contents (filename,
913                         buffer, sizeof(buffer) - 1);
914         if (buffer_len <= 0)
915                 return (-1);
916         buffer[buffer_len] = 0;
917
918         /* The name of the process is enclosed in parens. Since the name can
919          * contain parens itself, spaces, numbers and pretty much everything
920          * else, use these to determine the process name. We don't use
921          * strchr(3) and strrchr(3) to avoid pointer arithmetic which would
922          * otherwise be required to determine name_len. */
923         name_start_pos = 0;
924         while ((buffer[name_start_pos] != '(')
925                         && (name_start_pos < buffer_len))
926                 name_start_pos++;
927
928         name_end_pos = buffer_len;
929         while ((buffer[name_end_pos] != ')')
930                         && (name_end_pos > 0))
931                 name_end_pos--;
932
933         /* Either '(' or ')' is not found or they are in the wrong order.
934          * Anyway, something weird that shouldn't happen ever. */
935         if (name_start_pos >= name_end_pos)
936         {
937                 ERROR ("processes plugin: name_start_pos = %zu >= name_end_pos = %zu",
938                                 name_start_pos, name_end_pos);
939                 return (-1);
940         }
941
942         name_len = (name_end_pos - name_start_pos) - 1;
943         if (name_len >= sizeof (ps->name))
944                 name_len = sizeof (ps->name) - 1;
945
946         sstrncpy (ps->name, &buffer[name_start_pos + 1], name_len + 1);
947
948         if ((buffer_len - name_end_pos) < 2)
949                 return (-1);
950         buffer_ptr = &buffer[name_end_pos + 2];
951
952         fields_len = strsplit (buffer_ptr, fields, STATIC_ARRAY_SIZE (fields));
953         if (fields_len < 22)
954         {
955                 DEBUG ("processes plugin: ps_read_process (pid = %i):"
956                                 " `%s' has only %i fields..",
957                                 (int) pid, filename, fields_len);
958                 return (-1);
959         }
960
961         *state = fields[0][0];
962
963         if (*state == 'Z')
964         {
965                 ps->num_lwp  = 0;
966                 ps->num_proc = 0;
967         }
968         else
969         {
970                 if ( (ps->num_lwp = ps_read_tasks (pid)) == -1 )
971                 {
972                         /* returns -1 => kernel 2.4 */
973                         ps->num_lwp = 1;
974                 }
975                 ps->num_proc = 1;
976         }
977
978         /* Leave the rest at zero if this is only a zombi */
979         if (ps->num_proc == 0)
980         {
981                 DEBUG ("processes plugin: This is only a zombi: pid = %i; "
982                                 "name = %s;", pid, ps->name);
983                 return (0);
984         }
985
986         cpu_user_counter   = atoll (fields[11]);
987         cpu_system_counter = atoll (fields[12]);
988         vmem_size          = atoll (fields[20]);
989         vmem_rss           = atoll (fields[21]);
990         ps->vmem_minflt_counter = atol (fields[7]);
991         ps->vmem_majflt_counter = atol (fields[9]);
992
993         {
994                 unsigned long long stack_start = atoll (fields[25]);
995                 unsigned long long stack_ptr   = atoll (fields[26]);
996
997                 stack_size = (stack_start > stack_ptr)
998                         ? stack_start - stack_ptr
999                         : stack_ptr - stack_start;
1000         }
1001
1002         /* Convert jiffies to useconds */
1003         cpu_user_counter   = cpu_user_counter   * 1000000 / CONFIG_HZ;
1004         cpu_system_counter = cpu_system_counter * 1000000 / CONFIG_HZ;
1005         vmem_rss = vmem_rss * pagesize_g;
1006
1007         if ( (ps_read_vmem(pid, ps)) == NULL)
1008         {
1009                 /* No VMem data */
1010                 ps->vmem_data = -1;
1011                 ps->vmem_code = -1;
1012                 DEBUG("ps_read_process: did not get vmem data for pid %i",pid);
1013         }
1014
1015         ps->cpu_user_counter = cpu_user_counter;
1016         ps->cpu_system_counter = cpu_system_counter;
1017         ps->vmem_size = (unsigned long) vmem_size;
1018         ps->vmem_rss = (unsigned long) vmem_rss;
1019         ps->stack_size = (unsigned long) stack_size;
1020
1021         if ( (ps_read_io (pid, ps)) == NULL)
1022         {
1023                 /* no io data */
1024                 ps->io_rchar = -1;
1025                 ps->io_wchar = -1;
1026                 ps->io_syscr = -1;
1027                 ps->io_syscw = -1;
1028
1029                 DEBUG("ps_read_process: not get io data for pid %i",pid);
1030         }
1031
1032         /* success */
1033         return (0);
1034 } /* int ps_read_process (...) */
1035
1036 static char *ps_get_cmdline (pid_t pid, char *name, char *buf, size_t buf_len)
1037 {
1038         char  *buf_ptr;
1039         size_t len;
1040
1041         char file[PATH_MAX];
1042         int  fd;
1043
1044         size_t n;
1045
1046         if ((pid < 1) || (NULL == buf) || (buf_len < 2))
1047                 return NULL;
1048
1049         ssnprintf (file, sizeof (file), "/proc/%u/cmdline",
1050                         (unsigned int) pid);
1051
1052         errno = 0;
1053         fd = open (file, O_RDONLY);
1054         if (fd < 0) {
1055                 char errbuf[4096];
1056                 /* ENOENT means the process exited while we were handling it.
1057                  * Don't complain about this, it only fills the logs. */
1058                 if (errno != ENOENT)
1059                         WARNING ("processes plugin: Failed to open `%s': %s.", file,
1060                                         sstrerror (errno, errbuf, sizeof (errbuf)));
1061                 return NULL;
1062         }
1063
1064         buf_ptr = buf;
1065         len     = buf_len;
1066
1067         n = 0;
1068
1069         while (42) {
1070                 ssize_t status;
1071
1072                 status = read (fd, (void *)buf_ptr, len);
1073
1074                 if (status < 0) {
1075                         char errbuf[1024];
1076
1077                         if ((EAGAIN == errno) || (EINTR == errno))
1078                                 continue;
1079
1080                         WARNING ("processes plugin: Failed to read from `%s': %s.", file,
1081                                         sstrerror (errno, errbuf, sizeof (errbuf)));
1082                         close (fd);
1083                         return NULL;
1084                 }
1085
1086                 n += status;
1087
1088                 if (status == 0)
1089                         break;
1090
1091                 buf_ptr += status;
1092                 len     -= status;
1093
1094                 if (len <= 0)
1095                         break;
1096         }
1097
1098         close (fd);
1099
1100         if (0 == n) {
1101                 /* cmdline not available; e.g. kernel thread, zombie */
1102                 if (NULL == name)
1103                         return NULL;
1104
1105                 ssnprintf (buf, buf_len, "[%s]", name);
1106                 return buf;
1107         }
1108
1109         assert (n <= buf_len);
1110
1111         if (n == buf_len)
1112                 --n;
1113         buf[n] = '\0';
1114
1115         --n;
1116         /* remove trailing whitespace */
1117         while ((n > 0) && (isspace (buf[n]) || ('\0' == buf[n]))) {
1118                 buf[n] = '\0';
1119                 --n;
1120         }
1121
1122         /* arguments are separated by '\0' in /proc/<pid>/cmdline */
1123         while (n > 0) {
1124                 if ('\0' == buf[n])
1125                         buf[n] = ' ';
1126                 --n;
1127         }
1128         return buf;
1129 } /* char *ps_get_cmdline (...) */
1130
1131 static unsigned long read_fork_rate ()
1132 {
1133         FILE *proc_stat;
1134         char buf[1024];
1135         unsigned long result = 0;
1136         int numfields;
1137         char *fields[3];
1138
1139         proc_stat = fopen("/proc/stat", "r");
1140         if (proc_stat == NULL) {
1141                 char errbuf[1024];
1142                 ERROR ("processes plugin: fopen (/proc/stat) failed: %s",
1143                                 sstrerror (errno, errbuf, sizeof (errbuf)));
1144                 return ULONG_MAX;
1145         }
1146
1147         while (fgets (buf, sizeof(buf), proc_stat) != NULL)
1148         {
1149                 char *endptr;
1150
1151                 numfields = strsplit(buf, fields, STATIC_ARRAY_SIZE (fields));
1152                 if (numfields != 2)
1153                         continue;
1154
1155                 if (strcmp ("processes", fields[0]) != 0)
1156                         continue;
1157
1158                 errno = 0;
1159                 endptr = NULL;
1160                 result = strtoul(fields[1], &endptr, /* base = */ 10);
1161                 if ((endptr == fields[1]) || (errno != 0)) {
1162                         ERROR ("processes plugin: Cannot parse fork rate: %s",
1163                                         fields[1]);
1164                         result = ULONG_MAX;
1165                         break;
1166                 }
1167
1168                 break;
1169         }
1170
1171         fclose(proc_stat);
1172
1173         return result;
1174 }
1175 #endif /*KERNEL_LINUX */
1176
1177 #if KERNEL_LINUX || KERNEL_SOLARIS
1178 static void ps_submit_fork_rate (unsigned long value)
1179 {
1180         value_t values[1];
1181         value_list_t vl = VALUE_LIST_INIT;
1182
1183         values[0].derive = (derive_t) value;
1184
1185         vl.values = values;
1186         vl.values_len = 1;
1187         sstrncpy(vl.host, hostname_g, sizeof (vl.host));
1188         sstrncpy(vl.plugin, "processes", sizeof (vl.plugin));
1189         sstrncpy(vl.plugin_instance, "", sizeof (vl.plugin_instance));
1190         sstrncpy(vl.type, "fork_rate", sizeof (vl.type));
1191         sstrncpy(vl.type_instance, "", sizeof (vl.type_instance));
1192
1193         plugin_dispatch_values(&vl);
1194 }
1195 #endif /* KERNEL_LINUX || KERNEL_SOLARIS*/
1196
1197 #if KERNEL_SOLARIS
1198 static char *ps_get_cmdline(pid_t pid)
1199 {
1200         char f_psinfo[64];
1201         char cmdline[80];
1202         char *buffer = NULL;
1203         psinfo_t *myInfo;
1204
1205         snprintf(f_psinfo, sizeof (f_psinfo), "/proc/%i/psinfo", pid);
1206
1207         buffer = (char *)malloc(sizeof (psinfo_t));
1208         memset(buffer, 0, sizeof(psinfo_t));
1209         read_file_contents(f_psinfo, buffer, sizeof (psinfo_t));
1210         myInfo = (psinfo_t *) buffer;
1211
1212         sstrncpy(cmdline, myInfo->pr_psargs, sizeof (myInfo->pr_psargs));
1213
1214         sfree(myInfo);
1215         return strtok(cmdline, " ");
1216 }
1217
1218 /*
1219  * Reads process information on the Solaris OS. The information comes mainly from
1220  * /proc/PID/status, /proc/PID/psinfo and /proc/PID/usage
1221  * The values for input and ouput chars are calculated "by hand"
1222  * Added a few "solaris" specific process states as well
1223  */
1224 static int ps_read_process(int pid, procstat_t *ps, char *state)
1225 {
1226
1227         char filename[64];
1228         char f_psinfo[64], f_usage[64];
1229         int i;
1230         char *buffer;
1231
1232
1233         pstatus_t *myStatus;
1234         psinfo_t *myInfo;
1235         prusage_t *myUsage;
1236
1237         snprintf(filename, sizeof (filename), "/proc/%i/status", pid);
1238         snprintf(f_psinfo, sizeof (f_psinfo), "/proc/%i/psinfo", pid);
1239         snprintf(f_usage, sizeof (f_usage), "/proc/%i/usage", pid);
1240
1241
1242         buffer = malloc(sizeof (pstatus_t));
1243         memset(buffer, 0, sizeof (pstatus_t));
1244         read_file_contents(filename, buffer, sizeof (pstatus_t));
1245         myStatus = (pstatus_t *) buffer;
1246
1247         buffer = malloc(sizeof (psinfo_t));
1248         memset(buffer, 0, sizeof(psinfo_t));
1249         read_file_contents(f_psinfo, buffer, sizeof (psinfo_t));
1250         myInfo = (psinfo_t *) buffer;
1251
1252         buffer = malloc(sizeof (prusage_t));
1253         memset(buffer, 0, sizeof(prusage_t));
1254         read_file_contents(f_usage, buffer, sizeof (prusage_t));
1255         myUsage = (prusage_t *) buffer;
1256
1257         sstrncpy(ps->name, myInfo->pr_fname, sizeof (myInfo->pr_fname));
1258         ps->num_lwp = myStatus->pr_nlwp;
1259         if (myInfo->pr_wstat != 0) {
1260                 ps->num_proc = 0;
1261                 ps->num_lwp = 0;
1262                 *state = (char) 'Z';
1263                 return (0);
1264         } else {
1265                 ps->num_proc = 1;
1266                 ps->num_lwp = myInfo->pr_nlwp;
1267         }
1268
1269         /*
1270          * Convert system time and user time from nanoseconds to microseconds
1271          * for compatibility with the linux module
1272          */
1273         ps->cpu_system_counter = myStatus -> pr_stime.tv_nsec / 1000;
1274         ps->cpu_user_counter = myStatus -> pr_utime.tv_nsec / 1000;
1275
1276         /*
1277          * Convert rssize from KB to bytes to be consistent w/ the linux module
1278          */
1279         ps->vmem_rss = myInfo->pr_rssize * 1024;
1280         ps->vmem_size = myInfo->pr_size * 1024;
1281         ps->vmem_minflt_counter = myUsage->pr_minf;
1282         ps->vmem_majflt_counter = myUsage->pr_majf;
1283
1284         /*
1285          * TODO: Data and code segment calculations for Solaris
1286          */
1287
1288         ps->vmem_data = -1;
1289         ps->vmem_code = -1;
1290         ps->stack_size = myStatus->pr_stksize;
1291
1292         /*
1293          * Calculating input/ouput chars
1294          * Formula used is total chars / total blocks => chars/block
1295          * then convert input/output blocks to chars
1296          */
1297         ulong_t tot_chars = myUsage->pr_ioch;
1298         ulong_t tot_blocks = myUsage->pr_inblk + myUsage->pr_oublk;
1299         ulong_t chars_per_block = 1;
1300         if (tot_blocks != 0)
1301                 chars_per_block = tot_chars / tot_blocks;
1302         ps->io_rchar = myUsage->pr_inblk * chars_per_block;
1303         ps->io_wchar = myUsage->pr_oublk * chars_per_block;
1304         ps->io_syscr = myUsage->pr_sysc;
1305         ps->io_syscw = myUsage->pr_sysc;
1306
1307
1308         /*
1309          * TODO: Find way of setting BLOCKED and PAGING status
1310          */
1311
1312         *state = (char) 'R';
1313         if (myStatus->pr_flags & PR_ASLEEP)
1314                 *state = (char) 'S';
1315         else if (myStatus->pr_flags & PR_STOPPED)
1316                 *state = (char) 'T';
1317         else if (myStatus->pr_flags & PR_DETACH)
1318                 *state = (char) 'E';
1319         else if (myStatus->pr_flags & PR_DAEMON)
1320                 *state = (char) 'A';
1321         else if (myStatus->pr_flags & PR_ISSYS)
1322                 *state = (char) 'Y';
1323         else if (myStatus->pr_flags & PR_ORPHAN)
1324                 *state = (char) 'O';
1325
1326         sfree(myStatus);
1327         sfree(myInfo);
1328         sfree(myUsage);
1329
1330         return (0);
1331 }
1332
1333 /*
1334  * Reads the number of threads created since the last reboot. On Solaris these
1335  * are retrieved from kstat (module cpu, name sys, class misc, stat nthreads).
1336  * The result is the sum for all the threads created on each cpu
1337  */
1338 static unsigned long read_fork_rate()
1339 {
1340         extern kstat_ctl_t *kc;
1341         kstat_t *ksp_chain = NULL;
1342         unsigned long result = 0;
1343
1344         if (kc == NULL)
1345                 return ULONG_MAX;
1346
1347         for (ksp_chain = kc->kc_chain; ksp_chain != NULL;
1348              ksp_chain = ksp_chain->ks_next) {
1349                 if ((strncmp(ksp_chain->ks_module, "cpu", 3) == 0) &&
1350                     (strncmp(ksp_chain->ks_name, "sys", 3) == 0) &&
1351                     (strncmp(ksp_chain->ks_class, "misc", 4) == 0)) {
1352                         kstat_read(kc, ksp_chain, NULL);
1353                         result += get_kstat_value(ksp_chain, "nthreads");
1354                 }
1355         }
1356         return result;
1357 }
1358 #endif /* KERNEL_SOLARIS */
1359
1360 #if HAVE_THREAD_INFO
1361 static int mach_get_task_name (task_t t, int *pid, char *name, size_t name_max_len)
1362 {
1363         int mib[4];
1364
1365         struct kinfo_proc kp;
1366         size_t            kp_size;
1367
1368         mib[0] = CTL_KERN;
1369         mib[1] = KERN_PROC;
1370         mib[2] = KERN_PROC_PID;
1371
1372         if (pid_for_task (t, pid) != KERN_SUCCESS)
1373                 return (-1);
1374         mib[3] = *pid;
1375
1376         kp_size = sizeof (kp);
1377         if (sysctl (mib, 4, &kp, &kp_size, NULL, 0) != 0)
1378                 return (-1);
1379
1380         if (name_max_len > (MAXCOMLEN + 1))
1381                 name_max_len = MAXCOMLEN + 1;
1382
1383         strncpy (name, kp.kp_proc.p_comm, name_max_len - 1);
1384         name[name_max_len - 1] = '\0';
1385
1386         DEBUG ("pid = %i; name = %s;", *pid, name);
1387
1388         /* We don't do the special handling for `p_comm == "LaunchCFMApp"' as
1389          * `top' does it, because it is a lot of work and only used when
1390          * debugging. -octo */
1391
1392         return (0);
1393 }
1394 #endif /* HAVE_THREAD_INFO */
1395 /* ------- end of additional functions for KERNEL_LINUX/HAVE_THREAD_INFO ------- */
1396
1397 /* do actual readings from kernel */
1398 static int ps_read (void)
1399 {
1400 #if HAVE_THREAD_INFO
1401         kern_return_t            status;
1402
1403         int                      pset;
1404         processor_set_t          port_pset_priv;
1405
1406         int                      task;
1407         task_array_t             task_list;
1408         mach_msg_type_number_t   task_list_len;
1409
1410         int                      task_pid;
1411         char                     task_name[MAXCOMLEN + 1];
1412
1413         int                      thread;
1414         thread_act_array_t       thread_list;
1415         mach_msg_type_number_t   thread_list_len;
1416         thread_basic_info_data_t thread_data;
1417         mach_msg_type_number_t   thread_data_len;
1418
1419         int running  = 0;
1420         int sleeping = 0;
1421         int zombies  = 0;
1422         int stopped  = 0;
1423         int blocked  = 0;
1424
1425         procstat_t *ps;
1426         procstat_entry_t pse;
1427
1428         ps_list_reset ();
1429
1430         /*
1431          * The Mach-concept is a little different from the traditional UNIX
1432          * concept: All the work is done in threads. Threads are contained in
1433          * `tasks'. Therefore, `task status' doesn't make much sense, since
1434          * it's actually a `thread status'.
1435          * Tasks are assigned to sets of processors, so that's where you go to
1436          * get a list.
1437          */
1438         for (pset = 0; pset < pset_list_len; pset++)
1439         {
1440                 if ((status = host_processor_set_priv (port_host_self,
1441                                                 pset_list[pset],
1442                                                 &port_pset_priv)) != KERN_SUCCESS)
1443                 {
1444                         ERROR ("host_processor_set_priv failed: %s\n",
1445                                         mach_error_string (status));
1446                         continue;
1447                 }
1448
1449                 if ((status = processor_set_tasks (port_pset_priv,
1450                                                 &task_list,
1451                                                 &task_list_len)) != KERN_SUCCESS)
1452                 {
1453                         ERROR ("processor_set_tasks failed: %s\n",
1454                                         mach_error_string (status));
1455                         mach_port_deallocate (port_task_self, port_pset_priv);
1456                         continue;
1457                 }
1458
1459                 for (task = 0; task < task_list_len; task++)
1460                 {
1461                         ps = NULL;
1462                         if (mach_get_task_name (task_list[task],
1463                                                 &task_pid,
1464                                                 task_name, PROCSTAT_NAME_LEN) == 0)
1465                         {
1466                                 /* search for at least one match */
1467                                 for (ps = list_head_g; ps != NULL; ps = ps->next)
1468                                         /* FIXME: cmdline should be here instead of NULL */
1469                                         if (ps_list_match (task_name, NULL, ps) == 1)
1470                                                 break;
1471                         }
1472
1473                         /* Collect more detailed statistics for this process */
1474                         if (ps != NULL)
1475                         {
1476                                 task_basic_info_data_t        task_basic_info;
1477                                 mach_msg_type_number_t        task_basic_info_len;
1478                                 task_events_info_data_t       task_events_info;
1479                                 mach_msg_type_number_t        task_events_info_len;
1480                                 task_absolutetime_info_data_t task_absolutetime_info;
1481                                 mach_msg_type_number_t        task_absolutetime_info_len;
1482
1483                                 memset (&pse, '\0', sizeof (pse));
1484                                 pse.id = task_pid;
1485
1486                                 task_basic_info_len = TASK_BASIC_INFO_COUNT;
1487                                 status = task_info (task_list[task],
1488                                                 TASK_BASIC_INFO,
1489                                                 (task_info_t) &task_basic_info,
1490                                                 &task_basic_info_len);
1491                                 if (status != KERN_SUCCESS)
1492                                 {
1493                                         ERROR ("task_info failed: %s",
1494                                                         mach_error_string (status));
1495                                         continue; /* with next thread_list */
1496                                 }
1497
1498                                 task_events_info_len = TASK_EVENTS_INFO_COUNT;
1499                                 status = task_info (task_list[task],
1500                                                 TASK_EVENTS_INFO,
1501                                                 (task_info_t) &task_events_info,
1502                                                 &task_events_info_len);
1503                                 if (status != KERN_SUCCESS)
1504                                 {
1505                                         ERROR ("task_info failed: %s",
1506                                                         mach_error_string (status));
1507                                         continue; /* with next thread_list */
1508                                 }
1509
1510                                 task_absolutetime_info_len = TASK_ABSOLUTETIME_INFO_COUNT;
1511                                 status = task_info (task_list[task],
1512                                                 TASK_ABSOLUTETIME_INFO,
1513                                                 (task_info_t) &task_absolutetime_info,
1514                                                 &task_absolutetime_info_len);
1515                                 if (status != KERN_SUCCESS)
1516                                 {
1517                                         ERROR ("task_info failed: %s",
1518                                                         mach_error_string (status));
1519                                         continue; /* with next thread_list */
1520                                 }
1521
1522                                 pse.num_proc++;
1523                                 pse.vmem_size = task_basic_info.virtual_size;
1524                                 pse.vmem_rss = task_basic_info.resident_size;
1525                                 /* Does not seem to be easily exposed */
1526                                 pse.vmem_data = 0;
1527                                 pse.vmem_code = 0;
1528
1529                                 pse.vmem_minflt_counter = task_events_info.cow_faults;
1530                                 pse.vmem_majflt_counter = task_events_info.faults;
1531
1532                                 pse.cpu_user_counter = task_absolutetime_info.total_user;
1533                                 pse.cpu_system_counter = task_absolutetime_info.total_system;
1534                         }
1535
1536                         status = task_threads (task_list[task], &thread_list,
1537                                         &thread_list_len);
1538                         if (status != KERN_SUCCESS)
1539                         {
1540                                 /* Apple's `top' treats this case a zombie. It
1541                                  * makes sense to some extend: A `zombie'
1542                                  * thread is nonsense, since the task/process
1543                                  * is dead. */
1544                                 zombies++;
1545                                 DEBUG ("task_threads failed: %s",
1546                                                 mach_error_string (status));
1547                                 if (task_list[task] != port_task_self)
1548                                         mach_port_deallocate (port_task_self,
1549                                                         task_list[task]);
1550                                 continue; /* with next task_list */
1551                         }
1552
1553                         for (thread = 0; thread < thread_list_len; thread++)
1554                         {
1555                                 thread_data_len = THREAD_BASIC_INFO_COUNT;
1556                                 status = thread_info (thread_list[thread],
1557                                                 THREAD_BASIC_INFO,
1558                                                 (thread_info_t) &thread_data,
1559                                                 &thread_data_len);
1560                                 if (status != KERN_SUCCESS)
1561                                 {
1562                                         ERROR ("thread_info failed: %s",
1563                                                         mach_error_string (status));
1564                                         if (task_list[task] != port_task_self)
1565                                                 mach_port_deallocate (port_task_self,
1566                                                                 thread_list[thread]);
1567                                         continue; /* with next thread_list */
1568                                 }
1569
1570                                 if (ps != NULL)
1571                                         pse.num_lwp++;
1572
1573                                 switch (thread_data.run_state)
1574                                 {
1575                                         case TH_STATE_RUNNING:
1576                                                 running++;
1577                                                 break;
1578                                         case TH_STATE_STOPPED:
1579                                         /* What exactly is `halted'? */
1580                                         case TH_STATE_HALTED:
1581                                                 stopped++;
1582                                                 break;
1583                                         case TH_STATE_WAITING:
1584                                                 sleeping++;
1585                                                 break;
1586                                         case TH_STATE_UNINTERRUPTIBLE:
1587                                                 blocked++;
1588                                                 break;
1589                                         /* There is no `zombie' case here,
1590                                          * since there are no zombie-threads.
1591                                          * There's only zombie tasks, which are
1592                                          * handled above. */
1593                                         default:
1594                                                 WARNING ("Unknown thread status: %i",
1595                                                                 thread_data.run_state);
1596                                                 break;
1597                                 } /* switch (thread_data.run_state) */
1598
1599                                 if (task_list[task] != port_task_self)
1600                                 {
1601                                         status = mach_port_deallocate (port_task_self,
1602                                                         thread_list[thread]);
1603                                         if (status != KERN_SUCCESS)
1604                                                 ERROR ("mach_port_deallocate failed: %s",
1605                                                                 mach_error_string (status));
1606                                 }
1607                         } /* for (thread_list) */
1608
1609                         if ((status = vm_deallocate (port_task_self,
1610                                                         (vm_address_t) thread_list,
1611                                                         thread_list_len * sizeof (thread_act_t)))
1612                                         != KERN_SUCCESS)
1613                         {
1614                                 ERROR ("vm_deallocate failed: %s",
1615                                                 mach_error_string (status));
1616                         }
1617                         thread_list = NULL;
1618                         thread_list_len = 0;
1619
1620                         /* Only deallocate the task port, if it isn't our own.
1621                          * Don't know what would happen in that case, but this
1622                          * is what Apple's top does.. ;) */
1623                         if (task_list[task] != port_task_self)
1624                         {
1625                                 status = mach_port_deallocate (port_task_self,
1626                                                 task_list[task]);
1627                                 if (status != KERN_SUCCESS)
1628                                         ERROR ("mach_port_deallocate failed: %s",
1629                                                         mach_error_string (status));
1630                         }
1631
1632                         if (ps != NULL)
1633                                 /* FIXME: cmdline should be here instead of NULL */
1634                                 ps_list_add (task_name, NULL, &pse);
1635                 } /* for (task_list) */
1636
1637                 if ((status = vm_deallocate (port_task_self,
1638                                 (vm_address_t) task_list,
1639                                 task_list_len * sizeof (task_t))) != KERN_SUCCESS)
1640                 {
1641                         ERROR ("vm_deallocate failed: %s",
1642                                         mach_error_string (status));
1643                 }
1644                 task_list = NULL;
1645                 task_list_len = 0;
1646
1647                 if ((status = mach_port_deallocate (port_task_self, port_pset_priv))
1648                                 != KERN_SUCCESS)
1649                 {
1650                         ERROR ("mach_port_deallocate failed: %s",
1651                                         mach_error_string (status));
1652                 }
1653         } /* for (pset_list) */
1654
1655         ps_submit_state ("running", running);
1656         ps_submit_state ("sleeping", sleeping);
1657         ps_submit_state ("zombies", zombies);
1658         ps_submit_state ("stopped", stopped);
1659         ps_submit_state ("blocked", blocked);
1660
1661         for (ps = list_head_g; ps != NULL; ps = ps->next)
1662                 ps_submit_proc_list (ps);
1663 /* #endif HAVE_THREAD_INFO */
1664
1665 #elif KERNEL_LINUX
1666         int running  = 0;
1667         int sleeping = 0;
1668         int zombies  = 0;
1669         int stopped  = 0;
1670         int paging   = 0;
1671         int blocked  = 0;
1672
1673         struct dirent *ent;
1674         DIR           *proc;
1675         int            pid;
1676
1677         char cmdline[ARG_MAX];
1678
1679         int        status;
1680         procstat_t ps;
1681         procstat_entry_t pse;
1682         char       state;
1683
1684         unsigned long fork_rate;
1685
1686         procstat_t *ps_ptr;
1687
1688         running = sleeping = zombies = stopped = paging = blocked = 0;
1689         ps_list_reset ();
1690
1691         if ((proc = opendir ("/proc")) == NULL)
1692         {
1693                 char errbuf[1024];
1694                 ERROR ("Cannot open `/proc': %s",
1695                                 sstrerror (errno, errbuf, sizeof (errbuf)));
1696                 return (-1);
1697         }
1698
1699         while ((ent = readdir (proc)) != NULL)
1700         {
1701                 if (!isdigit (ent->d_name[0]))
1702                         continue;
1703
1704                 if ((pid = atoi (ent->d_name)) < 1)
1705                         continue;
1706
1707                 status = ps_read_process (pid, &ps, &state);
1708                 if (status != 0)
1709                 {
1710                         DEBUG ("ps_read_process failed: %i", status);
1711                         continue;
1712                 }
1713
1714                 pse.id       = pid;
1715                 pse.age      = 0;
1716
1717                 pse.num_proc   = ps.num_proc;
1718                 pse.num_lwp    = ps.num_lwp;
1719                 pse.vmem_size  = ps.vmem_size;
1720                 pse.vmem_rss   = ps.vmem_rss;
1721                 pse.vmem_data  = ps.vmem_data;
1722                 pse.vmem_code  = ps.vmem_code;
1723                 pse.stack_size = ps.stack_size;
1724
1725                 pse.vmem_minflt = 0;
1726                 pse.vmem_minflt_counter = ps.vmem_minflt_counter;
1727                 pse.vmem_majflt = 0;
1728                 pse.vmem_majflt_counter = ps.vmem_majflt_counter;
1729
1730                 pse.cpu_user = 0;
1731                 pse.cpu_user_counter = ps.cpu_user_counter;
1732                 pse.cpu_system = 0;
1733                 pse.cpu_system_counter = ps.cpu_system_counter;
1734
1735                 pse.io_rchar = ps.io_rchar;
1736                 pse.io_wchar = ps.io_wchar;
1737                 pse.io_syscr = ps.io_syscr;
1738                 pse.io_syscw = ps.io_syscw;
1739
1740                 switch (state)
1741                 {
1742                         case 'R': running++;  break;
1743                         case 'S': sleeping++; break;
1744                         case 'D': blocked++;  break;
1745                         case 'Z': zombies++;  break;
1746                         case 'T': stopped++;  break;
1747                         case 'W': paging++;   break;
1748                 }
1749
1750                 ps_list_add (ps.name,
1751                                 ps_get_cmdline (pid, ps.name, cmdline, sizeof (cmdline)),
1752                                 &pse);
1753         }
1754
1755         closedir (proc);
1756
1757         ps_submit_state ("running",  running);
1758         ps_submit_state ("sleeping", sleeping);
1759         ps_submit_state ("zombies",  zombies);
1760         ps_submit_state ("stopped",  stopped);
1761         ps_submit_state ("paging",   paging);
1762         ps_submit_state ("blocked",  blocked);
1763
1764         for (ps_ptr = list_head_g; ps_ptr != NULL; ps_ptr = ps_ptr->next)
1765                 ps_submit_proc_list (ps_ptr);
1766
1767         fork_rate = read_fork_rate();
1768         if (fork_rate != ULONG_MAX)
1769                 ps_submit_fork_rate(fork_rate);
1770 /* #endif KERNEL_LINUX */
1771
1772 #elif HAVE_LIBKVM_GETPROCS && HAVE_STRUCT_KINFO_PROC_FREEBSD
1773         int running  = 0;
1774         int sleeping = 0;
1775         int zombies  = 0;
1776         int stopped  = 0;
1777         int blocked  = 0;
1778         int idle     = 0;
1779         int wait     = 0;
1780
1781         kvm_t *kd;
1782         char errbuf[1024];
1783         struct kinfo_proc *procs;          /* array of processes */
1784         struct kinfo_proc *proc_ptr = NULL;
1785         int count;                         /* returns number of processes */
1786         int i;
1787
1788         procstat_t *ps_ptr;
1789         procstat_entry_t pse;
1790
1791         ps_list_reset ();
1792
1793         /* Open the kvm interface, get a descriptor */
1794         kd = kvm_open (NULL, NULL, NULL, 0, errbuf);
1795         if (kd == NULL)
1796         {
1797                 ERROR ("processes plugin: Cannot open kvm interface: %s",
1798                                 errbuf);
1799                 return (0);
1800         }
1801
1802         /* Get the list of processes. */
1803         procs = kvm_getprocs(kd, KERN_PROC_ALL, 0, &count);
1804         if (procs == NULL)
1805         {
1806                 ERROR ("processes plugin: Cannot get kvm processes list: %s",
1807                                 kvm_geterr(kd));
1808                 kvm_close (kd);
1809                 return (0);
1810         }
1811
1812         /* Iterate through the processes in kinfo_proc */
1813         for (i = 0; i < count; i++)
1814         {
1815                 /* Create only one process list entry per _process_, i.e.
1816                  * filter out threads (duplicate PID entries). */
1817                 if ((proc_ptr == NULL) || (proc_ptr->ki_pid != procs[i].ki_pid))
1818                 {
1819                         char cmdline[ARG_MAX] = "";
1820                         _Bool have_cmdline = 0;
1821
1822                         proc_ptr = &(procs[i]);
1823                         /* Don't probe system processes and processes without arguments */
1824                         if (((procs[i].ki_flag & P_SYSTEM) == 0)
1825                                         && (procs[i].ki_args != NULL))
1826                         {
1827                                 char **argv;
1828                                 int argc;
1829                                 int status;
1830
1831                                 /* retrieve the arguments */
1832                                 argv = kvm_getargv (kd, proc_ptr, /* nchr = */ 0);
1833                                 argc = 0;
1834                                 if ((argv != NULL) && (argv[0] != NULL))
1835                                 {
1836                                         while (argv[argc] != NULL)
1837                                                 argc++;
1838
1839                                         status = strjoin (cmdline, sizeof (cmdline), argv, argc, " ");
1840                                         if (status < 0)
1841                                                 WARNING ("processes plugin: Command line did not fit into buffer.");
1842                                         else
1843                                                 have_cmdline = 1;
1844                                 }
1845                         } /* if (process has argument list) */
1846
1847                         pse.id       = procs[i].ki_pid;
1848                         pse.age      = 0;
1849
1850                         pse.num_proc = 1;
1851                         pse.num_lwp  = procs[i].ki_numthreads;
1852
1853                         pse.vmem_size = procs[i].ki_size;
1854                         pse.vmem_rss = procs[i].ki_rssize * pagesize;
1855                         pse.vmem_data = procs[i].ki_dsize * pagesize;
1856                         pse.vmem_code = procs[i].ki_tsize * pagesize;
1857                         pse.stack_size = procs[i].ki_ssize * pagesize;
1858                         pse.vmem_minflt = 0;
1859                         pse.vmem_minflt_counter = procs[i].ki_rusage.ru_minflt;
1860                         pse.vmem_majflt = 0;
1861                         pse.vmem_majflt_counter = procs[i].ki_rusage.ru_majflt;
1862
1863                         pse.cpu_user = 0;
1864                         pse.cpu_system = 0;
1865                         pse.cpu_user_counter = 0;
1866                         pse.cpu_system_counter = 0;
1867                         /*
1868                          * The u-area might be swapped out, and we can't get
1869                          * at it because we have a crashdump and no swap.
1870                          * If it's here fill in these fields, otherwise, just
1871                          * leave them 0.
1872                          */
1873                         if (procs[i].ki_flag & P_INMEM)
1874                         {
1875                                 pse.cpu_user_counter = procs[i].ki_rusage.ru_utime.tv_usec
1876                                         + (1000000lu * procs[i].ki_rusage.ru_utime.tv_sec);
1877                                 pse.cpu_system_counter = procs[i].ki_rusage.ru_stime.tv_usec
1878                                         + (1000000lu * procs[i].ki_rusage.ru_stime.tv_sec);
1879                         }
1880
1881                         /* no I/O data */
1882                         pse.io_rchar = -1;
1883                         pse.io_wchar = -1;
1884                         pse.io_syscr = -1;
1885                         pse.io_syscw = -1;
1886
1887                         ps_list_add (procs[i].ki_comm, have_cmdline ? cmdline : NULL, &pse);
1888                 } /* if ((proc_ptr == NULL) || (proc_ptr->ki_pid != procs[i].ki_pid)) */
1889
1890                 switch (procs[i].ki_stat)
1891                 {
1892                         case SSTOP:     stopped++;      break;
1893                         case SSLEEP:    sleeping++;     break;
1894                         case SRUN:      running++;      break;
1895                         case SIDL:      idle++;         break;
1896                         case SWAIT:     wait++;         break;
1897                         case SLOCK:     blocked++;      break;
1898                         case SZOMB:     zombies++;      break;
1899                 }
1900         }
1901
1902         kvm_close(kd);
1903
1904         ps_submit_state ("running",  running);
1905         ps_submit_state ("sleeping", sleeping);
1906         ps_submit_state ("zombies",  zombies);
1907         ps_submit_state ("stopped",  stopped);
1908         ps_submit_state ("blocked",  blocked);
1909         ps_submit_state ("idle",     idle);
1910         ps_submit_state ("wait",     wait);
1911
1912         for (ps_ptr = list_head_g; ps_ptr != NULL; ps_ptr = ps_ptr->next)
1913                 ps_submit_proc_list (ps_ptr);
1914 /* #endif HAVE_LIBKVM_GETPROCS && HAVE_STRUCT_KINFO_PROC_FREEBSD */
1915
1916 #elif HAVE_PROCINFO_H
1917         /* AIX */
1918         int running  = 0;
1919         int sleeping = 0;
1920         int zombies  = 0;
1921         int stopped  = 0;
1922         int paging   = 0;
1923         int blocked  = 0;
1924
1925         pid_t pindex = 0;
1926         int nprocs;
1927
1928         procstat_t *ps;
1929         procstat_entry_t pse;
1930
1931         ps_list_reset ();
1932         while ((nprocs = getprocs64 (procentry, sizeof(struct procentry64),
1933                                         /* fdsinfo = */ NULL, sizeof(struct fdsinfo64),
1934                                         &pindex, MAXPROCENTRY)) > 0)
1935         {
1936                 int i;
1937
1938                 for (i = 0; i < nprocs; i++)
1939                 {
1940                         tid64_t thindex;
1941                         int nthreads;
1942                         char arglist[MAXARGLN+1];
1943                         char *cargs;
1944                         char *cmdline;
1945
1946                         if (procentry[i].pi_state == SNONE) continue;
1947                         /* if (procentry[i].pi_state == SZOMB)  FIXME */
1948
1949                         cmdline = procentry[i].pi_comm;
1950                         cargs = procentry[i].pi_comm;
1951                         if ( procentry[i].pi_flags & SKPROC )
1952                         {
1953                                 if (procentry[i].pi_pid == 0)
1954                                         cmdline = "swapper";
1955                                 cargs = cmdline;
1956                         }
1957                         else
1958                         {
1959                                 if (getargs(&procentry[i], sizeof(struct procentry64), arglist, MAXARGLN) >= 0)
1960                                 {
1961                                         int n;
1962
1963                                         n = -1;
1964                                         while (++n < MAXARGLN)
1965                                         {
1966                                                 if (arglist[n] == '\0')
1967                                                 {
1968                                                         if (arglist[n+1] == '\0')
1969                                                                 break;
1970                                                         arglist[n] = ' ';
1971                                                 }
1972                                         }
1973                                         cargs = arglist;
1974                                 }
1975                         }
1976
1977                         pse.id       = procentry[i].pi_pid;
1978                         pse.age      = 0;
1979                         pse.num_lwp  = procentry[i].pi_thcount;
1980                         pse.num_proc = 1;
1981
1982                         thindex=0;
1983                         while ((nthreads = getthrds64(procentry[i].pi_pid,
1984                                                         thrdentry, sizeof(struct thrdentry64),
1985                                                         &thindex, MAXTHRDENTRY)) > 0)
1986                         {
1987                                 int j;
1988
1989                                 for (j=0; j< nthreads; j++)
1990                                 {
1991                                         switch (thrdentry[j].ti_state)
1992                                         {
1993                                                 /* case TSNONE: break; */
1994                                                 case TSIDL:     blocked++;      break; /* FIXME is really blocked */
1995                                                 case TSRUN:     running++;      break;
1996                                                 case TSSLEEP:   sleeping++;     break;
1997                                                 case TSSWAP:    paging++;       break;
1998                                                 case TSSTOP:    stopped++;      break;
1999                                                 case TSZOMB:    zombies++;      break;
2000                                         }
2001                                 }
2002                                 if (nthreads < MAXTHRDENTRY)
2003                                         break;
2004                         }
2005
2006                         pse.cpu_user = 0;
2007                         /* tv_usec is nanosec ??? */
2008                         pse.cpu_user_counter = procentry[i].pi_ru.ru_utime.tv_sec * 1000000 +
2009                                 procentry[i].pi_ru.ru_utime.tv_usec / 1000;
2010
2011                         pse.cpu_system = 0;
2012                         /* tv_usec is nanosec ??? */
2013                         pse.cpu_system_counter = procentry[i].pi_ru.ru_stime.tv_sec * 1000000 +
2014                                 procentry[i].pi_ru.ru_stime.tv_usec / 1000;
2015
2016                         pse.vmem_minflt = 0;
2017                         pse.vmem_minflt_counter = procentry[i].pi_minflt;
2018                         pse.vmem_majflt = 0;
2019                         pse.vmem_majflt_counter = procentry[i].pi_majflt;
2020
2021                         pse.vmem_size = procentry[i].pi_tsize + procentry[i].pi_dvm * pagesize;
2022                         pse.vmem_rss = (procentry[i].pi_drss + procentry[i].pi_trss) * pagesize;
2023                         /* Not supported */
2024                         pse.vmem_data = 0;
2025                         pse.vmem_code = 0;
2026                         pse.stack_size =  0;
2027
2028                         pse.io_rchar = -1;
2029                         pse.io_wchar = -1;
2030                         pse.io_syscr = -1;
2031                         pse.io_syscw = -1;
2032
2033                         ps_list_add (cmdline, cargs, &pse);
2034                 } /* for (i = 0 .. nprocs) */
2035
2036                 if (nprocs < MAXPROCENTRY)
2037                         break;
2038         } /* while (getprocs64() > 0) */
2039         ps_submit_state ("running",  running);
2040         ps_submit_state ("sleeping", sleeping);
2041         ps_submit_state ("zombies",  zombies);
2042         ps_submit_state ("stopped",  stopped);
2043         ps_submit_state ("paging",   paging);
2044         ps_submit_state ("blocked",  blocked);
2045
2046         for (ps = list_head_g; ps != NULL; ps = ps->next)
2047                 ps_submit_proc_list (ps);
2048 /* #endif HAVE_PROCINFO_H */
2049
2050 #elif KERNEL_SOLARIS
2051         /*
2052          * The Solaris section adds a few more process states and removes some
2053          * process states compared to linux. Most notably there is no "PAGING"
2054          * and "BLOCKED" state for a process.  The rest is similar to the linux
2055          * code.
2056          */
2057         int running = 0;
2058         int sleeping = 0;
2059         int zombies = 0;
2060         int stopped = 0;
2061         int detached = 0;
2062         int daemon = 0;
2063         int system = 0;
2064         int orphan = 0;
2065         unsigned long fork_rate;
2066         struct dirent *ent;
2067         DIR *proc;
2068         int pid;
2069
2070         int status;
2071         struct procstat ps;
2072         procstat_entry_t pse;
2073         procstat_t *ps_ptr;
2074         char state;
2075
2076         ps_list_reset();
2077
2078
2079         proc = opendir("/proc");
2080         if (proc == NULL) {
2081                 return (-1);
2082         }
2083
2084         while ((ent = readdir(proc)) != NULL) {
2085                 if (!isdigit(ent->d_name[0]))
2086                         continue;
2087
2088                 if ((pid = atoi(ent->d_name)) < 1)
2089                         continue;
2090
2091                 status = ps_read_process(pid, &ps, &state);
2092                 if (status != 0) {
2093                         DEBUG("ps_read_process failed: %i", status);
2094                         continue;
2095                 }
2096                 pse.id = pid;
2097                 pse.age = 0;
2098
2099                 pse.num_proc = ps.num_proc;
2100                 pse.num_lwp = ps.num_lwp;
2101                 pse.vmem_size = ps.vmem_size;
2102                 pse.vmem_rss = ps.vmem_rss;
2103                 pse.vmem_data = ps.vmem_data;
2104                 pse.vmem_code = ps.vmem_code;
2105                 pse.stack_size = ps.stack_size;
2106
2107                 pse.vmem_minflt = 0;
2108                 pse.vmem_minflt_counter = ps.vmem_minflt_counter;
2109                 pse.vmem_majflt = 0;
2110                 pse.vmem_majflt_counter = ps.vmem_majflt_counter;
2111
2112                 pse.cpu_user = 0;
2113                 pse.cpu_user_counter = ps.cpu_user_counter;
2114                 pse.cpu_system = 0;
2115                 pse.cpu_system_counter = ps.cpu_system_counter;
2116
2117                 pse.io_rchar = ps.io_rchar;
2118                 pse.io_wchar = ps.io_wchar;
2119                 pse.io_syscr = ps.io_syscr;
2120                 pse.io_syscw = ps.io_syscw;
2121
2122                 switch (state) {
2123                 case 'R': running++;
2124                         break;
2125                 case 'S': sleeping++;
2126                         break;
2127                 case 'E': detached++;
2128                         break;
2129                 case 'Z': zombies++;
2130                         break;
2131                 case 'T': stopped++;
2132                         break;
2133                 case 'A': daemon++;
2134                         break;
2135                 case 'Y': system++;
2136                         break;
2137                 case 'O': orphan++;
2138                         break;
2139                 }
2140
2141                 ps_list_add(ps.name, ps_get_cmdline(pid), &pse);
2142
2143         } // while()
2144         closedir(proc);
2145
2146         ps_submit_state("running", running);
2147         ps_submit_state("sleeping", sleeping);
2148         ps_submit_state("zombies", zombies);
2149         ps_submit_state("stopped", stopped);
2150         ps_submit_state("detached", detached);
2151         ps_submit_state("daemon", daemon);
2152         ps_submit_state("system", system);
2153         ps_submit_state("orphan", orphan);
2154
2155         for (ps_ptr = list_head_g; ps_ptr != NULL; ps_ptr = ps_ptr->next)
2156                 ps_submit_proc_list(ps_ptr);
2157
2158
2159         fork_rate = read_fork_rate();
2160         if (fork_rate != ULONG_MAX) {
2161                 ps_submit_fork_rate(fork_rate);
2162         }
2163
2164 #endif /* KERNEL_SOLARIS */
2165
2166         return (0);
2167 } /* int ps_read */
2168
2169 void module_register (void)
2170 {
2171         plugin_register_complex_config ("processes", ps_config);
2172         plugin_register_init ("processes", ps_init);
2173         plugin_register_read ("processes", ps_read);
2174 } /* void module_register */