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