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