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