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