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