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