Merge branch 'collectd-5.5'
[collectd.git] / src / disk.c
1 /**
2  * collectd - src/disk.c
3  * Copyright (C) 2005-2012  Florian octo Forster
4  * Copyright (C) 2009       Manuel Sanmartin
5  *
6  * This program is free software; you can redistribute it and/or modify it
7  * under the terms of the GNU General Public License as published by the
8  * Free Software Foundation; only version 2 of the License is applicable.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License along
16  * with this program; if not, write to the Free Software Foundation, Inc.,
17  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
18  *
19  * Authors:
20  *   Florian octo Forster <octo at collectd.org>
21  *   Manuel Sanmartin
22  **/
23
24 #include "collectd.h"
25 #include "common.h"
26 #include "plugin.h"
27 #include "utils_ignorelist.h"
28
29 #if HAVE_MACH_MACH_TYPES_H
30 #  include <mach/mach_types.h>
31 #endif
32 #if HAVE_MACH_MACH_INIT_H
33 #  include <mach/mach_init.h>
34 #endif
35 #if HAVE_MACH_MACH_ERROR_H
36 #  include <mach/mach_error.h>
37 #endif
38 #if HAVE_MACH_MACH_PORT_H
39 #  include <mach/mach_port.h>
40 #endif
41 #if HAVE_COREFOUNDATION_COREFOUNDATION_H
42 #  include <CoreFoundation/CoreFoundation.h>
43 #endif
44 #if HAVE_IOKIT_IOKITLIB_H
45 #  include <IOKit/IOKitLib.h>
46 #endif
47 #if HAVE_IOKIT_IOTYPES_H
48 #  include <IOKit/IOTypes.h>
49 #endif
50 #if HAVE_IOKIT_STORAGE_IOBLOCKSTORAGEDRIVER_H
51 #  include <IOKit/storage/IOBlockStorageDriver.h>
52 #endif
53 #if HAVE_IOKIT_IOBSD_H
54 #  include <IOKit/IOBSD.h>
55 #endif
56 #if KERNEL_FREEBSD
57 #include <devstat.h>
58 #include <libgeom.h>
59 #endif
60
61 #if HAVE_LIMITS_H
62 # include <limits.h>
63 #endif
64 #ifndef UINT_MAX
65 #  define UINT_MAX 4294967295U
66 #endif
67
68 #if HAVE_STATGRAB_H
69 # include <statgrab.h>
70 #endif
71
72 #if HAVE_PERFSTAT
73 # ifndef _AIXVERSION_610
74 # include <sys/systemcfg.h>
75 # endif
76 # include <sys/protosw.h>
77 # include <libperfstat.h>
78 #endif
79
80 #if HAVE_IOKIT_IOKITLIB_H
81 static mach_port_t io_master_port = MACH_PORT_NULL;
82 /* This defaults to false for backwards compatibility. Please fix in the next
83  * major version. */
84 static _Bool use_bsd_name = 0;
85 /* #endif HAVE_IOKIT_IOKITLIB_H */
86
87 #elif KERNEL_LINUX
88 typedef struct diskstats
89 {
90         char *name;
91
92         /* This overflows in roughly 1361 years */
93         unsigned int poll_count;
94
95         derive_t read_sectors;
96         derive_t write_sectors;
97
98         derive_t read_bytes;
99         derive_t write_bytes;
100
101         derive_t read_ops;
102         derive_t write_ops;
103         derive_t read_time;
104         derive_t write_time;
105
106         derive_t avg_read_time;
107         derive_t avg_write_time;
108
109         _Bool has_merged;
110         _Bool has_in_progress;
111         _Bool has_io_time;
112
113         struct diskstats *next;
114 } diskstats_t;
115
116 static diskstats_t *disklist;
117 /* #endif KERNEL_LINUX */
118 #elif KERNEL_FREEBSD
119 static struct gmesh geom_tree;
120 /* #endif KERNEL_FREEBSD */
121
122 #elif HAVE_LIBKSTAT
123 #define MAX_NUMDISK 1024
124 extern kstat_ctl_t *kc;
125 static kstat_t *ksp[MAX_NUMDISK];
126 static int numdisk = 0;
127 /* #endif HAVE_LIBKSTAT */
128
129 #elif defined(HAVE_LIBSTATGRAB)
130 /* #endif HAVE_LIBKSTATGRAB */
131
132 #elif HAVE_PERFSTAT
133 static perfstat_disk_t * stat_disk;
134 static int numdisk;
135 static int pnumdisk;
136 /* #endif HAVE_PERFSTAT */
137
138 #else
139 # error "No applicable input method."
140 #endif
141
142 #if HAVE_LIBUDEV
143 #include <libudev.h>
144
145 static char *conf_udev_name_attr = NULL;
146 static struct udev *handle_udev;
147 #endif
148
149 static const char *config_keys[] =
150 {
151         "Disk",
152         "UseBSDName",
153         "IgnoreSelected",
154         "UdevNameAttr"
155 };
156 static int config_keys_num = STATIC_ARRAY_SIZE (config_keys);
157
158 static ignorelist_t *ignorelist = NULL;
159
160 static int disk_config (const char *key, const char *value)
161 {
162   if (ignorelist == NULL)
163     ignorelist = ignorelist_create (/* invert = */ 1);
164   if (ignorelist == NULL)
165     return (1);
166
167   if (strcasecmp ("Disk", key) == 0)
168   {
169     ignorelist_add (ignorelist, value);
170   }
171   else if (strcasecmp ("IgnoreSelected", key) == 0)
172   {
173     int invert = 1;
174     if (IS_TRUE (value))
175       invert = 0;
176     ignorelist_set_invert (ignorelist, invert);
177   }
178   else if (strcasecmp ("UseBSDName", key) == 0)
179   {
180 #if HAVE_IOKIT_IOKITLIB_H
181     use_bsd_name = IS_TRUE (value) ? 1 : 0;
182 #else
183     WARNING ("disk plugin: The \"UseBSDName\" option is only supported "
184         "on Mach / Mac OS X and will be ignored.");
185 #endif
186   }
187   else if (strcasecmp ("UdevNameAttr", key) == 0)
188   {
189 #if HAVE_LIBUDEV
190     if (conf_udev_name_attr != NULL)
191     {
192       free (conf_udev_name_attr);
193       conf_udev_name_attr = NULL;
194     }
195     if ((conf_udev_name_attr = strdup (value)) == NULL)
196       return (1);
197 #else
198     WARNING ("disk plugin: The \"UdevNameAttr\" option is only supported "
199         "if collectd is built with libudev support");
200 #endif
201   }
202   else
203   {
204     return (-1);
205   }
206
207   return (0);
208 } /* int disk_config */
209
210 static int disk_init (void)
211 {
212 #if HAVE_IOKIT_IOKITLIB_H
213         kern_return_t status;
214
215         if (io_master_port != MACH_PORT_NULL)
216         {
217                 mach_port_deallocate (mach_task_self (),
218                                 io_master_port);
219                 io_master_port = MACH_PORT_NULL;
220         }
221
222         status = IOMasterPort (MACH_PORT_NULL, &io_master_port);
223         if (status != kIOReturnSuccess)
224         {
225                 ERROR ("IOMasterPort failed: %s",
226                                 mach_error_string (status));
227                 io_master_port = MACH_PORT_NULL;
228                 return (-1);
229         }
230 /* #endif HAVE_IOKIT_IOKITLIB_H */
231
232 #elif KERNEL_LINUX
233         /* do nothing */
234 /* #endif KERNEL_LINUX */
235
236 #elif KERNEL_FREEBSD
237         int rv;
238
239         rv = geom_gettree(&geom_tree);
240         if (rv != 0) {
241                 ERROR ("geom_gettree() failed, returned %d", rv);
242                 return (-1);
243         }
244         rv = geom_stats_open();
245         if (rv != 0) {
246                 ERROR ("geom_stats_open() failed, returned %d", rv);
247                 return (-1);
248         }
249 /* #endif KERNEL_FREEBSD */
250
251 #elif HAVE_LIBKSTAT
252         kstat_t *ksp_chain;
253
254         numdisk = 0;
255
256         if (kc == NULL)
257                 return (-1);
258
259         for (numdisk = 0, ksp_chain = kc->kc_chain;
260                         (numdisk < MAX_NUMDISK) && (ksp_chain != NULL);
261                         ksp_chain = ksp_chain->ks_next)
262         {
263                 if (strncmp (ksp_chain->ks_class, "disk", 4)
264                                 && strncmp (ksp_chain->ks_class, "partition", 9))
265                         continue;
266                 if (ksp_chain->ks_type != KSTAT_TYPE_IO)
267                         continue;
268                 ksp[numdisk++] = ksp_chain;
269         }
270 #endif /* HAVE_LIBKSTAT */
271
272         return (0);
273 } /* int disk_init */
274
275 static void disk_submit (const char *plugin_instance,
276                 const char *type,
277                 derive_t read, derive_t write)
278 {
279         value_t values[2];
280         value_list_t vl = VALUE_LIST_INIT;
281
282         values[0].derive = read;
283         values[1].derive = write;
284
285         vl.values = values;
286         vl.values_len = 2;
287         sstrncpy (vl.host, hostname_g, sizeof (vl.host));
288         sstrncpy (vl.plugin, "disk", sizeof (vl.plugin));
289         sstrncpy (vl.plugin_instance, plugin_instance,
290                         sizeof (vl.plugin_instance));
291         sstrncpy (vl.type, type, sizeof (vl.type));
292
293         plugin_dispatch_values (&vl);
294 } /* void disk_submit */
295
296 #if KERNEL_FREEBSD || KERNEL_LINUX
297 static void submit_io_time (char const *plugin_instance, derive_t io_time, derive_t weighted_time)
298 {
299         value_t values[2];
300         value_list_t vl = VALUE_LIST_INIT;
301
302         values[0].derive = io_time;
303         values[1].derive = weighted_time;
304
305         vl.values = values;
306         vl.values_len = 2;
307         sstrncpy (vl.host, hostname_g, sizeof (vl.host));
308         sstrncpy (vl.plugin, "disk", sizeof (vl.plugin));
309         sstrncpy (vl.plugin_instance, plugin_instance, sizeof (vl.plugin_instance));
310         sstrncpy (vl.type, "disk_io_time", sizeof (vl.type));
311
312         plugin_dispatch_values (&vl);
313 } /* void submit_io_time */
314 #endif /* KERNEL_FREEBSD || KERNEL_LINUX */
315
316 #if KERNEL_LINUX
317 static void submit_in_progress (char const *disk_name, gauge_t in_progress)
318 {
319         value_t v;
320         value_list_t vl = VALUE_LIST_INIT;
321
322         v.gauge = in_progress;
323
324         vl.values = &v;
325         vl.values_len = 1;
326         sstrncpy (vl.host, hostname_g, sizeof (vl.host));
327         sstrncpy (vl.plugin, "disk", sizeof (vl.plugin));
328         sstrncpy (vl.plugin_instance, disk_name, sizeof (vl.plugin_instance));
329         sstrncpy (vl.type, "pending_operations", sizeof (vl.type));
330
331         plugin_dispatch_values (&vl);
332 }
333
334
335 static counter_t disk_calc_time_incr (counter_t delta_time, counter_t delta_ops)
336 {
337         double interval = CDTIME_T_TO_DOUBLE (plugin_get_interval ());
338         double avg_time = ((double) delta_time) / ((double) delta_ops);
339         double avg_time_incr = interval * avg_time;
340
341         return ((counter_t) (avg_time_incr + .5));
342 }
343 #endif
344
345 #if HAVE_LIBUDEV
346 /**
347  * Attempt to provide an rename disk instance from an assigned udev attribute.
348  *
349  * On success, it returns a strduped char* to the desired attribute value.
350  * Otherwise it returns NULL.
351  */
352
353 static char *disk_udev_attr_name (struct udev *udev, char *disk_name, const char *attr)
354 {
355         struct udev_device *dev;
356         const char *prop;
357         char *output = NULL;
358
359         dev = udev_device_new_from_subsystem_sysname (udev, "block", disk_name);
360         if (dev != NULL)
361         {
362                 prop = udev_device_get_property_value (dev, attr);
363                 if (prop) {
364                         output = strdup (prop);
365                         DEBUG ("disk plugin: renaming %s => %s", disk_name, output);
366                 }
367                 udev_device_unref (dev);
368         }
369         return output;
370 }
371 #endif
372
373 #if HAVE_IOKIT_IOKITLIB_H
374 static signed long long dict_get_value (CFDictionaryRef dict, const char *key)
375 {
376         signed long long val_int;
377         CFNumberRef      val_obj;
378         CFStringRef      key_obj;
379
380         /* `key_obj' needs to be released. */
381         key_obj = CFStringCreateWithCString (kCFAllocatorDefault, key,
382                         kCFStringEncodingASCII);
383         if (key_obj == NULL)
384         {
385                 DEBUG ("CFStringCreateWithCString (%s) failed.", key);
386                 return (-1LL);
387         }
388
389         /* get => we don't need to release (== free) the object */
390         val_obj = (CFNumberRef) CFDictionaryGetValue (dict, key_obj);
391
392         CFRelease (key_obj);
393
394         if (val_obj == NULL)
395         {
396                 DEBUG ("CFDictionaryGetValue (%s) failed.", key);
397                 return (-1LL);
398         }
399
400         if (!CFNumberGetValue (val_obj, kCFNumberSInt64Type, &val_int))
401         {
402                 DEBUG ("CFNumberGetValue (%s) failed.", key);
403                 return (-1LL);
404         }
405
406         return (val_int);
407 }
408 #endif /* HAVE_IOKIT_IOKITLIB_H */
409
410 static int disk_read (void)
411 {
412 #if HAVE_IOKIT_IOKITLIB_H
413         io_registry_entry_t     disk;
414         io_registry_entry_t     disk_child;
415         io_iterator_t           disk_list;
416         CFMutableDictionaryRef  props_dict, child_dict;
417         CFDictionaryRef         stats_dict;
418         CFStringRef             tmp_cf_string_ref;
419         kern_return_t           status;
420
421         signed long long read_ops, read_byt, read_tme;
422         signed long long write_ops, write_byt, write_tme;
423
424         int  disk_major, disk_minor;
425         char disk_name[DATA_MAX_NAME_LEN];
426         char child_disk_name_bsd[DATA_MAX_NAME_LEN], props_disk_name_bsd[DATA_MAX_NAME_LEN];
427
428         /* Get the list of all disk objects. */
429         if (IOServiceGetMatchingServices (io_master_port, IOServiceMatching (kIOBlockStorageDriverClass), &disk_list) != kIOReturnSuccess) {
430                 ERROR ("disk plugin: IOServiceGetMatchingServices failed.");
431                 return (-1);
432         }
433
434         while ((disk = IOIteratorNext (disk_list)) != 0) {
435                 props_dict = NULL;
436                 stats_dict = NULL;
437                 child_dict = NULL;
438
439                 /* get child of disk entry and corresponding property dictionary */
440                 if ((status = IORegistryEntryGetChildEntry (disk, kIOServicePlane, &disk_child)) != kIOReturnSuccess) {
441                         /* This fails for example for DVD/CD drives, which we want to ignore anyway */
442                         DEBUG ("IORegistryEntryGetChildEntry (disk) failed: 0x%08x", status);
443                         IOObjectRelease (disk);
444                         continue;
445                 }
446                 if (IORegistryEntryCreateCFProperties (disk_child, (CFMutableDictionaryRef *) &child_dict, kCFAllocatorDefault, kNilOptions) != kIOReturnSuccess || child_dict == NULL) {
447                         ERROR ("disk plugin: IORegistryEntryCreateCFProperties (disk_child) failed.");
448                         IOObjectRelease (disk_child);
449                         IOObjectRelease (disk);
450                         continue;
451                 }
452
453                 /* extract name and major/minor numbers */
454                 memset (child_disk_name_bsd, 0, sizeof (child_disk_name_bsd));
455                 tmp_cf_string_ref = (CFStringRef) CFDictionaryGetValue (child_dict, CFSTR(kIOBSDNameKey));
456                 if (tmp_cf_string_ref) {
457                         assert (CFGetTypeID (tmp_cf_string_ref) == CFStringGetTypeID ());
458                         CFStringGetCString (tmp_cf_string_ref, child_disk_name_bsd, sizeof (child_disk_name_bsd), kCFStringEncodingUTF8);
459                 }
460                 disk_major = (int) dict_get_value (child_dict, kIOBSDMajorKey);
461                 disk_minor = (int) dict_get_value (child_dict, kIOBSDMinorKey);
462                 DEBUG ("disk plugin: child_disk_name_bsd=\"%s\" major=%d minor=%d", child_disk_name_bsd, disk_major, disk_minor);
463                 CFRelease (child_dict);
464                 IOObjectRelease (disk_child);
465
466                 /* get property dictionary of the disk entry itself */
467                 if (IORegistryEntryCreateCFProperties (disk, (CFMutableDictionaryRef *) &props_dict, kCFAllocatorDefault, kNilOptions) != kIOReturnSuccess || props_dict == NULL) {
468                         ERROR ("disk-plugin: IORegistryEntryCreateCFProperties failed.");
469                         IOObjectRelease (disk);
470                         continue;
471                 }
472
473                 /* extract name and stats dictionary */
474                 memset (props_disk_name_bsd, 0, sizeof (props_disk_name_bsd));
475                 tmp_cf_string_ref = (CFStringRef) CFDictionaryGetValue (props_dict, CFSTR(kIOBSDNameKey));
476                 if (tmp_cf_string_ref) {
477                         assert (CFGetTypeID (tmp_cf_string_ref) == CFStringGetTypeID ());
478                         CFStringGetCString (tmp_cf_string_ref, props_disk_name_bsd, sizeof (props_disk_name_bsd), kCFStringEncodingUTF8);
479                 }
480                 stats_dict = (CFDictionaryRef) CFDictionaryGetValue (props_dict, CFSTR (kIOBlockStorageDriverStatisticsKey));
481                 if (stats_dict == NULL) {
482                         ERROR ("disk plugin: CFDictionaryGetValue (%s) failed.", kIOBlockStorageDriverStatisticsKey);
483                         CFRelease (props_dict);
484                         IOObjectRelease (disk);
485                         continue;
486                 }
487                 DEBUG ("disk plugin: props_disk_name_bsd=\"%s\"", props_disk_name_bsd);
488
489                 /* choose name */
490                 if (use_bsd_name) {
491                         if (child_disk_name_bsd[0] != 0)
492                                 sstrncpy (disk_name, child_disk_name_bsd, sizeof (disk_name));
493                         else if (props_disk_name_bsd[0] != 0)
494                                 sstrncpy (disk_name, props_disk_name_bsd, sizeof (disk_name));
495                         else {
496                                 ERROR ("disk plugin: can't find bsd disk name.");
497                                 ssnprintf (disk_name, sizeof (disk_name), "%i-%i", disk_major, disk_minor);
498                         }
499                 }
500                 else
501                         ssnprintf (disk_name, sizeof (disk_name), "%i-%i", disk_major, disk_minor);
502
503                 DEBUG ("disk plugin: disk_name = \"%s\"", disk_name);
504
505                 /* check the name against ignore list */
506                 if (ignorelist_match (ignorelist, disk_name) != 0) {
507                         CFRelease (props_dict);
508                         IOObjectRelease (disk);
509                         continue;
510                 }
511
512                 /* extract the stats */
513                 read_ops  = dict_get_value (stats_dict, kIOBlockStorageDriverStatisticsReadsKey);
514                 read_byt  = dict_get_value (stats_dict, kIOBlockStorageDriverStatisticsBytesReadKey);
515                 read_tme  = dict_get_value (stats_dict, kIOBlockStorageDriverStatisticsTotalReadTimeKey);
516                 write_ops = dict_get_value (stats_dict, kIOBlockStorageDriverStatisticsWritesKey);
517                 write_byt = dict_get_value (stats_dict, kIOBlockStorageDriverStatisticsBytesWrittenKey);
518                 write_tme = dict_get_value (stats_dict, kIOBlockStorageDriverStatisticsTotalWriteTimeKey);
519                 CFRelease (props_dict);
520                 IOObjectRelease (disk);
521
522                 /* and submit */
523                 if ((read_byt != -1LL) || (write_byt != -1LL))
524                         disk_submit (disk_name, "disk_octets", read_byt, write_byt);
525                 if ((read_ops != -1LL) || (write_ops != -1LL))
526                         disk_submit (disk_name, "disk_ops", read_ops, write_ops);
527                 if ((read_tme != -1LL) || (write_tme != -1LL))
528                         disk_submit (disk_name, "disk_time", read_tme / 1000, write_tme / 1000);
529
530         }
531         IOObjectRelease (disk_list);
532 /* #endif HAVE_IOKIT_IOKITLIB_H */
533
534 #elif KERNEL_FREEBSD
535         int retry, dirty;
536
537         void *snap = NULL;
538         struct devstat *snap_iter;
539
540         struct gident *geom_id;
541
542         const char *disk_name;
543         long double read_time, write_time, busy_time, total_duration;
544
545         for (retry = 0, dirty = 1; retry < 5 && dirty == 1; retry++) {
546                 if (snap != NULL)
547                         geom_stats_snapshot_free(snap);
548
549                 /* Get a fresh copy of stats snapshot */
550                 snap = geom_stats_snapshot_get();
551                 if (snap == NULL) {
552                         ERROR("disk plugin: geom_stats_snapshot_get() failed.");
553                         return (-1);
554                 }
555
556                 /* Check if we have dirty read from this snapshot */
557                 dirty = 0;
558                 geom_stats_snapshot_reset(snap);
559                 while ((snap_iter = geom_stats_snapshot_next(snap)) != NULL) {
560                         if (snap_iter->id == NULL)
561                                 continue;
562                         geom_id = geom_lookupid(&geom_tree, snap_iter->id);
563
564                         /* New device? refresh GEOM tree */
565                         if (geom_id == NULL) {
566                                 geom_deletetree(&geom_tree);
567                                 if (geom_gettree(&geom_tree) != 0) {
568                                         ERROR("disk plugin: geom_gettree() failed");
569                                         geom_stats_snapshot_free(snap);
570                                         return (-1);
571                                 }
572                                 geom_id = geom_lookupid(&geom_tree, snap_iter->id);
573                         }
574                         /*
575                          * This should be rare: the device come right before we take the
576                          * snapshot and went away right after it.  We will handle this
577                          * case later, so don't mark dirty but silently ignore it.
578                          */
579                         if (geom_id == NULL)
580                                 continue;
581
582                         /* Only collect PROVIDER data */
583                         if (geom_id->lg_what != ISPROVIDER)
584                                 continue;
585
586                         /* Only collect data when rank is 1 (physical devices) */
587                         if (((struct gprovider *)(geom_id->lg_ptr))->lg_geom->lg_rank != 1)
588                                 continue;
589
590                         /* Check if this is a dirty read quit for another try */
591                         if (snap_iter->sequence0 != snap_iter->sequence1) {
592                                 dirty = 1;
593                                 break;
594                         }
595                 }
596         }
597
598         /* Reset iterator */
599         geom_stats_snapshot_reset(snap);
600         for (;;) {
601                 snap_iter = geom_stats_snapshot_next(snap);
602                 if (snap_iter == NULL)
603                         break;
604
605                 if (snap_iter->id == NULL)
606                         continue;
607                 geom_id = geom_lookupid(&geom_tree, snap_iter->id);
608                 if (geom_id == NULL)
609                         continue;
610                 if (geom_id->lg_what != ISPROVIDER)
611                         continue;
612                 if (((struct gprovider *)(geom_id->lg_ptr))->lg_geom->lg_rank != 1)
613                         continue;
614                 /* Skip dirty reads, if present */
615                 if (dirty && (snap_iter->sequence0 != snap_iter->sequence1))
616                         continue;
617
618                 disk_name = ((struct gprovider *)geom_id->lg_ptr)->lg_name;
619
620                 if (ignorelist_match (ignorelist, disk_name) != 0)
621                         continue;
622
623                 if ((snap_iter->bytes[DEVSTAT_READ] != 0) || (snap_iter->bytes[DEVSTAT_WRITE] != 0)) {
624                         disk_submit(disk_name, "disk_octets",
625                                         (derive_t)snap_iter->bytes[DEVSTAT_READ],
626                                         (derive_t)snap_iter->bytes[DEVSTAT_WRITE]);
627                 }
628
629                 if ((snap_iter->operations[DEVSTAT_READ] != 0) || (snap_iter->operations[DEVSTAT_WRITE] != 0)) {
630                         disk_submit(disk_name, "disk_ops",
631                                         (derive_t)snap_iter->operations[DEVSTAT_READ],
632                                         (derive_t)snap_iter->operations[DEVSTAT_WRITE]);
633                 }
634
635                 read_time = devstat_compute_etime(&snap_iter->duration[DEVSTAT_READ], NULL);
636                 write_time = devstat_compute_etime(&snap_iter->duration[DEVSTAT_WRITE], NULL);
637                 if ((read_time != 0) || (write_time != 0)) {
638                         disk_submit (disk_name, "disk_time",
639                                         (derive_t)(read_time*1000), (derive_t)(write_time*1000));
640                 }
641                 if (devstat_compute_statistics(snap_iter, NULL, 1.0,
642                     DSM_TOTAL_BUSY_TIME, &busy_time,
643                     DSM_TOTAL_DURATION, &total_duration,
644                     DSM_NONE) != 0) {
645                         WARNING("%s", devstat_errbuf);
646                 }
647                 else
648                 {
649                         submit_io_time(disk_name, busy_time, total_duration);
650                 }
651         }
652         geom_stats_snapshot_free(snap);
653
654 #elif KERNEL_LINUX
655         FILE *fh;
656         char buffer[1024];
657
658         char *fields[32];
659         int numfields;
660         int fieldshift = 0;
661
662         int minor = 0;
663
664         derive_t read_sectors  = 0;
665         derive_t write_sectors = 0;
666
667         derive_t read_ops      = 0;
668         derive_t read_merged   = 0;
669         derive_t read_time     = 0;
670         derive_t write_ops     = 0;
671         derive_t write_merged  = 0;
672         derive_t write_time    = 0;
673         gauge_t in_progress    = NAN;
674         derive_t io_time       = 0;
675         derive_t weighted_time = 0;
676         int is_disk = 0;
677
678         diskstats_t *ds, *pre_ds;
679
680         if ((fh = fopen ("/proc/diskstats", "r")) == NULL)
681         {
682                 fh = fopen ("/proc/partitions", "r");
683                 if (fh == NULL)
684                 {
685                         ERROR ("disk plugin: fopen (/proc/{diskstats,partitions}) failed.");
686                         return (-1);
687                 }
688
689                 /* Kernel is 2.4.* */
690                 fieldshift = 1;
691         }
692
693 #if HAVE_LIBUDEV
694         handle_udev = udev_new();
695 #endif
696
697         while (fgets (buffer, sizeof (buffer), fh) != NULL)
698         {
699                 char *disk_name;
700                 char *output_name;
701
702                 numfields = strsplit (buffer, fields, 32);
703
704                 if ((numfields != (14 + fieldshift)) && (numfields != 7))
705                         continue;
706
707                 minor = atoll (fields[1]);
708
709                 disk_name = fields[2 + fieldshift];
710
711                 for (ds = disklist, pre_ds = disklist; ds != NULL; pre_ds = ds, ds = ds->next)
712                         if (strcmp (disk_name, ds->name) == 0)
713                                 break;
714
715                 if (ds == NULL)
716                 {
717                         if ((ds = (diskstats_t *) calloc (1, sizeof (diskstats_t))) == NULL)
718                                 continue;
719
720                         if ((ds->name = strdup (disk_name)) == NULL)
721                         {
722                                 free (ds);
723                                 continue;
724                         }
725
726                         if (pre_ds == NULL)
727                                 disklist = ds;
728                         else
729                                 pre_ds->next = ds;
730                 }
731
732                 is_disk = 0;
733                 if (numfields == 7)
734                 {
735                         /* Kernel 2.6, Partition */
736                         read_ops      = atoll (fields[3]);
737                         read_sectors  = atoll (fields[4]);
738                         write_ops     = atoll (fields[5]);
739                         write_sectors = atoll (fields[6]);
740                 }
741                 else if (numfields == (14 + fieldshift))
742                 {
743                         read_ops  =  atoll (fields[3 + fieldshift]);
744                         write_ops =  atoll (fields[7 + fieldshift]);
745
746                         read_sectors  = atoll (fields[5 + fieldshift]);
747                         write_sectors = atoll (fields[9 + fieldshift]);
748
749                         if ((fieldshift == 0) || (minor == 0))
750                         {
751                                 is_disk = 1;
752                                 read_merged  = atoll (fields[4 + fieldshift]);
753                                 read_time    = atoll (fields[6 + fieldshift]);
754                                 write_merged = atoll (fields[8 + fieldshift]);
755                                 write_time   = atoll (fields[10+ fieldshift]);
756
757                                 in_progress = atof (fields[11 + fieldshift]);
758
759                                 io_time       = atof (fields[12 + fieldshift]);
760                                 weighted_time = atof (fields[13 + fieldshift]);
761                         }
762                 }
763                 else
764                 {
765                         DEBUG ("numfields = %i; => unknown file format.", numfields);
766                         continue;
767                 }
768
769                 {
770                         derive_t diff_read_sectors;
771                         derive_t diff_write_sectors;
772
773                 /* If the counter wraps around, it's only 32 bits.. */
774                         if (read_sectors < ds->read_sectors)
775                                 diff_read_sectors = 1 + read_sectors
776                                         + (UINT_MAX - ds->read_sectors);
777                         else
778                                 diff_read_sectors = read_sectors - ds->read_sectors;
779                         if (write_sectors < ds->write_sectors)
780                                 diff_write_sectors = 1 + write_sectors
781                                         + (UINT_MAX - ds->write_sectors);
782                         else
783                                 diff_write_sectors = write_sectors - ds->write_sectors;
784
785                         ds->read_bytes += 512 * diff_read_sectors;
786                         ds->write_bytes += 512 * diff_write_sectors;
787                         ds->read_sectors = read_sectors;
788                         ds->write_sectors = write_sectors;
789                 }
790
791                 /* Calculate the average time an io-op needs to complete */
792                 if (is_disk)
793                 {
794                         derive_t diff_read_ops;
795                         derive_t diff_write_ops;
796                         derive_t diff_read_time;
797                         derive_t diff_write_time;
798
799                         if (read_ops < ds->read_ops)
800                                 diff_read_ops = 1 + read_ops
801                                         + (UINT_MAX - ds->read_ops);
802                         else
803                                 diff_read_ops = read_ops - ds->read_ops;
804                         DEBUG ("disk plugin: disk_name = %s; read_ops = %"PRIi64"; "
805                                         "ds->read_ops = %"PRIi64"; diff_read_ops = %"PRIi64";",
806                                         disk_name,
807                                         read_ops, ds->read_ops, diff_read_ops);
808
809                         if (write_ops < ds->write_ops)
810                                 diff_write_ops = 1 + write_ops
811                                         + (UINT_MAX - ds->write_ops);
812                         else
813                                 diff_write_ops = write_ops - ds->write_ops;
814
815                         if (read_time < ds->read_time)
816                                 diff_read_time = 1 + read_time
817                                         + (UINT_MAX - ds->read_time);
818                         else
819                                 diff_read_time = read_time - ds->read_time;
820
821                         if (write_time < ds->write_time)
822                                 diff_write_time = 1 + write_time
823                                         + (UINT_MAX - ds->write_time);
824                         else
825                                 diff_write_time = write_time - ds->write_time;
826
827                         if (diff_read_ops != 0)
828                                 ds->avg_read_time += disk_calc_time_incr (
829                                                 diff_read_time, diff_read_ops);
830                         if (diff_write_ops != 0)
831                                 ds->avg_write_time += disk_calc_time_incr (
832                                                 diff_write_time, diff_write_ops);
833
834                         ds->read_ops = read_ops;
835                         ds->read_time = read_time;
836                         ds->write_ops = write_ops;
837                         ds->write_time = write_time;
838
839                         if (read_merged || write_merged)
840                                 ds->has_merged = 1;
841
842                         if (in_progress)
843                                 ds->has_in_progress = 1;
844
845                         if (io_time)
846                                 ds->has_io_time = 1;
847                 
848                 } /* if (is_disk) */
849
850                 /* Don't write to the RRDs if we've just started.. */
851                 ds->poll_count++;
852                 if (ds->poll_count <= 2)
853                 {
854                         DEBUG ("disk plugin: (ds->poll_count = %i) <= "
855                                         "(min_poll_count = 2); => Not writing.",
856                                         ds->poll_count);
857                         continue;
858                 }
859
860                 if ((read_ops == 0) && (write_ops == 0))
861                 {
862                         DEBUG ("disk plugin: ((read_ops == 0) && "
863                                         "(write_ops == 0)); => Not writing.");
864                         continue;
865                 }
866
867                 output_name = disk_name;
868
869 #if HAVE_LIBUDEV
870                 char *alt_name = disk_udev_attr_name (handle_udev, disk_name, conf_udev_name_attr);
871                 if (alt_name != NULL)
872                         output_name = alt_name;
873 #endif
874
875                 if (ignorelist_match (ignorelist, output_name) != 0)
876                         continue;
877
878                 if ((ds->read_bytes != 0) || (ds->write_bytes != 0))
879                         disk_submit (output_name, "disk_octets",
880                                         ds->read_bytes, ds->write_bytes);
881
882                 if ((ds->read_ops != 0) || (ds->write_ops != 0))
883                         disk_submit (output_name, "disk_ops",
884                                         read_ops, write_ops);
885
886                 if ((ds->avg_read_time != 0) || (ds->avg_write_time != 0))
887                         disk_submit (output_name, "disk_time",
888                                         ds->avg_read_time, ds->avg_write_time);
889
890                 if (is_disk)
891                 {
892                         if (ds->has_merged)
893                                 disk_submit (output_name, "disk_merged",
894                                         read_merged, write_merged);
895                         if (ds->has_in_progress)
896                                 submit_in_progress (output_name, in_progress);
897                         if (ds->has_io_time)
898                                 submit_io_time (output_name, io_time, weighted_time);
899                 } /* if (is_disk) */
900
901 #if HAVE_LIBUDEV
902                 /* release udev-based alternate name, if allocated */
903                 sfree (alt_name);
904 #endif
905         } /* while (fgets (buffer, sizeof (buffer), fh) != NULL) */
906
907 #if HAVE_LIBUDEV
908         udev_unref(handle_udev);
909 #endif
910
911         fclose (fh);
912 /* #endif defined(KERNEL_LINUX) */
913
914 #elif HAVE_LIBKSTAT
915 # if HAVE_KSTAT_IO_T_WRITES && HAVE_KSTAT_IO_T_NWRITES && HAVE_KSTAT_IO_T_WTIME
916 #  define KIO_ROCTETS reads
917 #  define KIO_WOCTETS writes
918 #  define KIO_ROPS    nreads
919 #  define KIO_WOPS    nwrites
920 #  define KIO_RTIME   rtime
921 #  define KIO_WTIME   wtime
922 # elif HAVE_KSTAT_IO_T_NWRITTEN && HAVE_KSTAT_IO_T_WRITES && HAVE_KSTAT_IO_T_WTIME
923 #  define KIO_ROCTETS nread
924 #  define KIO_WOCTETS nwritten
925 #  define KIO_ROPS    reads
926 #  define KIO_WOPS    writes
927 #  define KIO_RTIME   rtime
928 #  define KIO_WTIME   wtime
929 # else
930 #  error "kstat_io_t does not have the required members"
931 # endif
932         static kstat_io_t kio;
933         int i;
934
935         if (kc == NULL)
936                 return (-1);
937
938         for (i = 0; i < numdisk; i++)
939         {
940                 if (kstat_read (kc, ksp[i], &kio) == -1)
941                         continue;
942
943                 if (strncmp (ksp[i]->ks_class, "disk", 4) == 0)
944                 {
945                         if (ignorelist_match (ignorelist, ksp[i]->ks_name) != 0)
946                                 continue;
947
948                         disk_submit (ksp[i]->ks_name, "disk_octets",
949                                         kio.KIO_ROCTETS, kio.KIO_WOCTETS);
950                         disk_submit (ksp[i]->ks_name, "disk_ops",
951                                         kio.KIO_ROPS, kio.KIO_WOPS);
952                         /* FIXME: Convert this to microseconds if necessary */
953                         disk_submit (ksp[i]->ks_name, "disk_time",
954                                         kio.KIO_RTIME, kio.KIO_WTIME);
955                 }
956                 else if (strncmp (ksp[i]->ks_class, "partition", 9) == 0)
957                 {
958                         if (ignorelist_match (ignorelist, ksp[i]->ks_name) != 0)
959                                 continue;
960
961                         disk_submit (ksp[i]->ks_name, "disk_octets",
962                                         kio.KIO_ROCTETS, kio.KIO_WOCTETS);
963                         disk_submit (ksp[i]->ks_name, "disk_ops",
964                                         kio.KIO_ROPS, kio.KIO_WOPS);
965                 }
966         }
967 /* #endif defined(HAVE_LIBKSTAT) */
968
969 #elif defined(HAVE_LIBSTATGRAB)
970         sg_disk_io_stats *ds;
971 # if HAVE_LIBSTATGRAB_0_90
972         size_t disks;
973 # else
974         int disks;
975 #endif
976         int counter;
977         char name[DATA_MAX_NAME_LEN];
978
979         if ((ds = sg_get_disk_io_stats(&disks)) == NULL)
980                 return (0);
981
982         for (counter=0; counter < disks; counter++) {
983                 strncpy(name, ds->disk_name, sizeof(name));
984                 name[sizeof(name)-1] = '\0'; /* strncpy doesn't terminate longer strings */
985
986                 if (ignorelist_match (ignorelist, name) != 0) {
987                         ds++;
988                         continue;
989                 }
990
991                 disk_submit (name, "disk_octets", ds->read_bytes, ds->write_bytes);
992                 ds++;
993         }
994 /* #endif defined(HAVE_LIBSTATGRAB) */
995
996 #elif defined(HAVE_PERFSTAT)
997         derive_t read_sectors;
998         derive_t write_sectors;
999         derive_t read_time;
1000         derive_t write_time;
1001         derive_t read_ops;
1002         derive_t write_ops;
1003         perfstat_id_t firstpath;
1004         int rnumdisk;
1005         int i;
1006
1007         if ((numdisk = perfstat_disk(NULL, NULL, sizeof(perfstat_disk_t), 0)) < 0)
1008         {
1009                 char errbuf[1024];
1010                 WARNING ("disk plugin: perfstat_disk: %s",
1011                                 sstrerror (errno, errbuf, sizeof (errbuf)));
1012                 return (-1);
1013         }
1014
1015         if (numdisk != pnumdisk || stat_disk==NULL) {
1016                 if (stat_disk!=NULL)
1017                         free(stat_disk);
1018                 stat_disk = (perfstat_disk_t *)calloc(numdisk, sizeof(perfstat_disk_t));
1019         }
1020         pnumdisk = numdisk;
1021
1022         firstpath.name[0]='\0';
1023         if ((rnumdisk = perfstat_disk(&firstpath, stat_disk, sizeof(perfstat_disk_t), numdisk)) < 0)
1024         {
1025                 char errbuf[1024];
1026                 WARNING ("disk plugin: perfstat_disk : %s",
1027                                 sstrerror (errno, errbuf, sizeof (errbuf)));
1028                 return (-1);
1029         }
1030
1031         for (i = 0; i < rnumdisk; i++)
1032         {
1033                 if (ignorelist_match (ignorelist, stat_disk[i].name) != 0)
1034                         continue;
1035
1036                 read_sectors = stat_disk[i].rblks*stat_disk[i].bsize;
1037                 write_sectors = stat_disk[i].wblks*stat_disk[i].bsize;
1038                 disk_submit (stat_disk[i].name, "disk_octets", read_sectors, write_sectors);
1039
1040                 read_ops = stat_disk[i].xrate;
1041                 write_ops = stat_disk[i].xfers - stat_disk[i].xrate;
1042                 disk_submit (stat_disk[i].name, "disk_ops", read_ops, write_ops);
1043
1044                 read_time = stat_disk[i].rserv;
1045                 read_time *= ((double)(_system_configuration.Xint)/(double)(_system_configuration.Xfrac)) / 1000000.0;
1046                 write_time = stat_disk[i].wserv;
1047                 write_time *= ((double)(_system_configuration.Xint)/(double)(_system_configuration.Xfrac)) / 1000000.0;
1048                 disk_submit (stat_disk[i].name, "disk_time", read_time, write_time);
1049         }
1050 #endif /* defined(HAVE_PERFSTAT) */
1051
1052         return (0);
1053 } /* int disk_read */
1054
1055 void module_register (void)
1056 {
1057   plugin_register_config ("disk", disk_config,
1058       config_keys, config_keys_num);
1059   plugin_register_init ("disk", disk_init);
1060   plugin_register_read ("disk", disk_read);
1061 } /* void module_register */