xref: /freebsd/lib/libdevstat/devstat.c (revision 6b3455a7665208c366849f0b2b3bc916fb97516e)
1 /*
2  * Copyright (c) 1997, 1998 Kenneth D. Merry.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. The name of the author may not be used to endorse or promote products
14  *    derived from this software without specific prior written permission.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28 
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
31 
32 #include <sys/types.h>
33 #include <sys/sysctl.h>
34 #include <sys/errno.h>
35 #include <sys/resource.h>
36 #include <sys/queue.h>
37 
38 #include <ctype.h>
39 #include <err.h>
40 #include <fcntl.h>
41 #include <limits.h>
42 #include <stdio.h>
43 #include <stdlib.h>
44 #include <string.h>
45 #include <stdarg.h>
46 #include <kvm.h>
47 #include <nlist.h>
48 
49 #include "devstat.h"
50 
51 int
52 compute_stats(struct devstat *current, struct devstat *previous,
53 	      long double etime, u_int64_t *total_bytes,
54 	      u_int64_t *total_transfers, u_int64_t *total_blocks,
55 	      long double *kb_per_transfer, long double *transfers_per_second,
56 	      long double *mb_per_second, long double *blocks_per_second,
57 	      long double *ms_per_transaction);
58 
59 typedef enum {
60 	DEVSTAT_ARG_NOTYPE,
61 	DEVSTAT_ARG_UINT64,
62 	DEVSTAT_ARG_LD,
63 	DEVSTAT_ARG_SKIP
64 } devstat_arg_type;
65 
66 char devstat_errbuf[DEVSTAT_ERRBUF_SIZE];
67 
68 /*
69  * Table to match descriptive strings with device types.  These are in
70  * order from most common to least common to speed search time.
71  */
72 struct devstat_match_table match_table[] = {
73 	{"da",		DEVSTAT_TYPE_DIRECT,	DEVSTAT_MATCH_TYPE},
74 	{"cd",		DEVSTAT_TYPE_CDROM,	DEVSTAT_MATCH_TYPE},
75 	{"scsi",	DEVSTAT_TYPE_IF_SCSI,	DEVSTAT_MATCH_IF},
76 	{"ide",		DEVSTAT_TYPE_IF_IDE,	DEVSTAT_MATCH_IF},
77 	{"other",	DEVSTAT_TYPE_IF_OTHER,	DEVSTAT_MATCH_IF},
78 	{"worm",	DEVSTAT_TYPE_WORM,	DEVSTAT_MATCH_TYPE},
79 	{"sa",		DEVSTAT_TYPE_SEQUENTIAL,DEVSTAT_MATCH_TYPE},
80 	{"pass",	DEVSTAT_TYPE_PASS,	DEVSTAT_MATCH_PASS},
81 	{"optical",	DEVSTAT_TYPE_OPTICAL,	DEVSTAT_MATCH_TYPE},
82 	{"array",	DEVSTAT_TYPE_STORARRAY,	DEVSTAT_MATCH_TYPE},
83 	{"changer",	DEVSTAT_TYPE_CHANGER,	DEVSTAT_MATCH_TYPE},
84 	{"scanner",	DEVSTAT_TYPE_SCANNER,	DEVSTAT_MATCH_TYPE},
85 	{"printer",	DEVSTAT_TYPE_PRINTER,	DEVSTAT_MATCH_TYPE},
86 	{"floppy",	DEVSTAT_TYPE_FLOPPY,	DEVSTAT_MATCH_TYPE},
87 	{"proc",	DEVSTAT_TYPE_PROCESSOR,	DEVSTAT_MATCH_TYPE},
88 	{"comm",	DEVSTAT_TYPE_COMM,	DEVSTAT_MATCH_TYPE},
89 	{"enclosure",	DEVSTAT_TYPE_ENCLOSURE,	DEVSTAT_MATCH_TYPE},
90 	{NULL,		0,			0}
91 };
92 
93 struct devstat_args {
94 	devstat_metric 		metric;
95 	devstat_arg_type	argtype;
96 } devstat_arg_list[] = {
97 	{ DSM_NONE, DEVSTAT_ARG_NOTYPE },
98 	{ DSM_TOTAL_BYTES, DEVSTAT_ARG_UINT64 },
99 	{ DSM_TOTAL_BYTES_READ, DEVSTAT_ARG_UINT64 },
100 	{ DSM_TOTAL_BYTES_WRITE, DEVSTAT_ARG_UINT64 },
101 	{ DSM_TOTAL_TRANSFERS, DEVSTAT_ARG_UINT64 },
102 	{ DSM_TOTAL_TRANSFERS_READ, DEVSTAT_ARG_UINT64 },
103 	{ DSM_TOTAL_TRANSFERS_WRITE, DEVSTAT_ARG_UINT64 },
104 	{ DSM_TOTAL_TRANSFERS_OTHER, DEVSTAT_ARG_UINT64 },
105 	{ DSM_TOTAL_BLOCKS, DEVSTAT_ARG_UINT64 },
106 	{ DSM_TOTAL_BLOCKS_READ, DEVSTAT_ARG_UINT64 },
107 	{ DSM_TOTAL_BLOCKS_WRITE, DEVSTAT_ARG_UINT64 },
108 	{ DSM_KB_PER_TRANSFER, DEVSTAT_ARG_LD },
109 	{ DSM_KB_PER_TRANSFER_READ, DEVSTAT_ARG_LD },
110 	{ DSM_KB_PER_TRANSFER_WRITE, DEVSTAT_ARG_LD },
111 	{ DSM_TRANSFERS_PER_SECOND, DEVSTAT_ARG_LD },
112 	{ DSM_TRANSFERS_PER_SECOND_READ, DEVSTAT_ARG_LD },
113 	{ DSM_TRANSFERS_PER_SECOND_WRITE, DEVSTAT_ARG_LD },
114 	{ DSM_TRANSFERS_PER_SECOND_OTHER, DEVSTAT_ARG_LD },
115 	{ DSM_MB_PER_SECOND, DEVSTAT_ARG_LD },
116 	{ DSM_MB_PER_SECOND_READ, DEVSTAT_ARG_LD },
117 	{ DSM_MB_PER_SECOND_WRITE, DEVSTAT_ARG_LD },
118 	{ DSM_BLOCKS_PER_SECOND, DEVSTAT_ARG_LD },
119 	{ DSM_BLOCKS_PER_SECOND_READ, DEVSTAT_ARG_LD },
120 	{ DSM_BLOCKS_PER_SECOND_WRITE, DEVSTAT_ARG_LD },
121 	{ DSM_MS_PER_TRANSACTION, DEVSTAT_ARG_LD },
122 	{ DSM_MS_PER_TRANSACTION_READ, DEVSTAT_ARG_LD },
123 	{ DSM_MS_PER_TRANSACTION_WRITE, DEVSTAT_ARG_LD },
124 	{ DSM_SKIP, DEVSTAT_ARG_SKIP },
125 	{ DSM_TOTAL_BYTES_FREE, DEVSTAT_ARG_UINT64 },
126 	{ DSM_TOTAL_TRANSFERS_FREE, DEVSTAT_ARG_UINT64 },
127 	{ DSM_TOTAL_BLOCKS_FREE, DEVSTAT_ARG_UINT64 },
128 	{ DSM_KB_PER_TRANSFER_FREE, DEVSTAT_ARG_LD },
129 	{ DSM_MB_PER_SECOND_FREE, DEVSTAT_ARG_LD },
130 	{ DSM_TRANSFERS_PER_SECOND_FREE, DEVSTAT_ARG_LD },
131 	{ DSM_BLOCKS_PER_SECOND_FREE, DEVSTAT_ARG_LD },
132 	{ DSM_MS_PER_TRANSACTION_OTHER, DEVSTAT_ARG_LD },
133 	{ DSM_MS_PER_TRANSACTION_FREE, DEVSTAT_ARG_LD },
134 	{ DSM_BUSY_PCT, DEVSTAT_ARG_LD },
135 	{ DSM_QUEUE_LENGTH, DEVSTAT_ARG_UINT64 },
136 };
137 
138 static const char *namelist[] = {
139 #define X_NUMDEVS	0
140 	"_devstat_num_devs",
141 #define X_GENERATION	1
142 	"_devstat_generation",
143 #define X_VERSION	2
144 	"_devstat_version",
145 #define X_DEVICE_STATQ	3
146 	"_device_statq",
147 #define X_END		4
148 };
149 
150 /*
151  * Local function declarations.
152  */
153 static int compare_select(const void *arg1, const void *arg2);
154 static int readkmem(kvm_t *kd, unsigned long addr, void *buf, size_t nbytes);
155 static int readkmem_nl(kvm_t *kd, const char *name, void *buf, size_t nbytes);
156 static char *get_devstat_kvm(kvm_t *kd);
157 
158 #define KREADNL(kd, var, val) \
159 	readkmem_nl(kd, namelist[var], &val, sizeof(val))
160 
161 int
162 devstat_getnumdevs(kvm_t *kd)
163 {
164 	size_t numdevsize;
165 	int numdevs;
166 	const char *func_name = "devstat_getnumdevs";
167 
168 	numdevsize = sizeof(int);
169 
170 	/*
171 	 * Find out how many devices we have in the system.
172 	 */
173 	if (kd == NULL) {
174 		if (sysctlbyname("kern.devstat.numdevs", &numdevs,
175 				 &numdevsize, NULL, 0) == -1) {
176 			snprintf(devstat_errbuf, sizeof(devstat_errbuf),
177 				 "%s: error getting number of devices\n"
178 				 "%s: %s", func_name, func_name,
179 				 strerror(errno));
180 			return(-1);
181 		} else
182 			return(numdevs);
183 	} else {
184 
185 		if (KREADNL(kd, X_NUMDEVS, numdevs) == -1)
186 			return(-1);
187 		else
188 			return(numdevs);
189 	}
190 }
191 
192 /*
193  * This is an easy way to get the generation number, but the generation is
194  * supplied in a more atmoic manner by the kern.devstat.all sysctl.
195  * Because this generation sysctl is separate from the statistics sysctl,
196  * the device list and the generation could change between the time that
197  * this function is called and the device list is retreived.
198  */
199 long
200 devstat_getgeneration(kvm_t *kd)
201 {
202 	size_t gensize;
203 	long generation;
204 	const char *func_name = "devstat_getgeneration";
205 
206 	gensize = sizeof(long);
207 
208 	/*
209 	 * Get the current generation number.
210 	 */
211 	if (kd == NULL) {
212 		if (sysctlbyname("kern.devstat.generation", &generation,
213 				 &gensize, NULL, 0) == -1) {
214 			snprintf(devstat_errbuf, sizeof(devstat_errbuf),
215 				 "%s: error getting devstat generation\n%s: %s",
216 				 func_name, func_name, strerror(errno));
217 			return(-1);
218 		} else
219 			return(generation);
220 	} else {
221 		if (KREADNL(kd, X_GENERATION, generation) == -1)
222 			return(-1);
223 		else
224 			return(generation);
225 	}
226 }
227 
228 /*
229  * Get the current devstat version.  The return value of this function
230  * should be compared with DEVSTAT_VERSION, which is defined in
231  * sys/devicestat.h.  This will enable userland programs to determine
232  * whether they are out of sync with the kernel.
233  */
234 int
235 devstat_getversion(kvm_t *kd)
236 {
237 	size_t versize;
238 	int version;
239 	const char *func_name = "devstat_getversion";
240 
241 	versize = sizeof(int);
242 
243 	/*
244 	 * Get the current devstat version.
245 	 */
246 	if (kd == NULL) {
247 		if (sysctlbyname("kern.devstat.version", &version, &versize,
248 				 NULL, 0) == -1) {
249 			snprintf(devstat_errbuf, sizeof(devstat_errbuf),
250 				 "%s: error getting devstat version\n%s: %s",
251 				 func_name, func_name, strerror(errno));
252 			return(-1);
253 		} else
254 			return(version);
255 	} else {
256 		if (KREADNL(kd, X_VERSION, version) == -1)
257 			return(-1);
258 		else
259 			return(version);
260 	}
261 }
262 
263 /*
264  * Check the devstat version we know about against the devstat version the
265  * kernel knows about.  If they don't match, print an error into the
266  * devstat error buffer, and return -1.  If they match, return 0.
267  */
268 int
269 devstat_checkversion(kvm_t *kd)
270 {
271 	const char *func_name = "devstat_checkversion";
272 	int buflen, res, retval = 0, version;
273 
274 	version = devstat_getversion(kd);
275 
276 	if (version != DEVSTAT_VERSION) {
277 		/*
278 		 * If getversion() returns an error (i.e. -1), then it
279 		 * has printed an error message in the buffer.  Therefore,
280 		 * we need to add a \n to the end of that message before we
281 		 * print our own message in the buffer.
282 		 */
283 		if (version == -1)
284 			buflen = strlen(devstat_errbuf);
285 		else
286 			buflen = 0;
287 
288 		res = snprintf(devstat_errbuf + buflen,
289 			       DEVSTAT_ERRBUF_SIZE - buflen,
290 			       "%s%s: userland devstat version %d is not "
291 			       "the same as the kernel\n%s: devstat "
292 			       "version %d\n", version == -1 ? "\n" : "",
293 			       func_name, DEVSTAT_VERSION, func_name, version);
294 
295 		if (res < 0)
296 			devstat_errbuf[buflen] = '\0';
297 
298 		buflen = strlen(devstat_errbuf);
299 		if (version < DEVSTAT_VERSION)
300 			res = snprintf(devstat_errbuf + buflen,
301 				       DEVSTAT_ERRBUF_SIZE - buflen,
302 				       "%s: libdevstat newer than kernel\n",
303 				       func_name);
304 		else
305 			res = snprintf(devstat_errbuf + buflen,
306 				       DEVSTAT_ERRBUF_SIZE - buflen,
307 				       "%s: kernel newer than libdevstat\n",
308 				       func_name);
309 
310 		if (res < 0)
311 			devstat_errbuf[buflen] = '\0';
312 
313 		retval = -1;
314 	}
315 
316 	return(retval);
317 }
318 
319 /*
320  * Get the current list of devices and statistics, and the current
321  * generation number.
322  *
323  * Return values:
324  * -1  -- error
325  *  0  -- device list is unchanged
326  *  1  -- device list has changed
327  */
328 int
329 devstat_getdevs(kvm_t *kd, struct statinfo *stats)
330 {
331 	int error;
332 	size_t dssize;
333 	int oldnumdevs;
334 	long oldgeneration;
335 	int retval = 0;
336 	struct devinfo *dinfo;
337 	const char *func_name = "devstat_getdevs";
338 	struct timespec ts;
339 
340 	dinfo = stats->dinfo;
341 
342 	if (dinfo == NULL) {
343 		snprintf(devstat_errbuf, sizeof(devstat_errbuf),
344 			 "%s: stats->dinfo was NULL", func_name);
345 		return(-1);
346 	}
347 
348 	oldnumdevs = dinfo->numdevs;
349 	oldgeneration = dinfo->generation;
350 
351 	clock_gettime(CLOCK_MONOTONIC, &ts);
352 	stats->snap_time = ts.tv_sec + ts.tv_nsec * 1e-9;
353 
354 	if (kd == NULL) {
355 		/* If this is our first time through, mem_ptr will be null. */
356 		if (dinfo->mem_ptr == NULL) {
357 			/*
358 			 * Get the number of devices.  If it's negative, it's an
359 			 * error.  Don't bother setting the error string, since
360 			 * getnumdevs() has already done that for us.
361 			 */
362 			if ((dinfo->numdevs = devstat_getnumdevs(kd)) < 0)
363 				return(-1);
364 
365 			/*
366 			 * The kern.devstat.all sysctl returns the current
367 			 * generation number, as well as all the devices.
368 			 * So we need four bytes more.
369 			 */
370 			dssize = (dinfo->numdevs * sizeof(struct devstat)) +
371 				 sizeof(long);
372 			dinfo->mem_ptr = (u_int8_t *)malloc(dssize);
373 		} else
374 			dssize = (dinfo->numdevs * sizeof(struct devstat)) +
375 				 sizeof(long);
376 
377 		/*
378 		 * Request all of the devices.  We only really allow for one
379 		 * ENOMEM failure.  It would, of course, be possible to just go
380 		 * in a loop and keep reallocing the device structure until we
381 		 * don't get ENOMEM back.  I'm not sure it's worth it, though.
382 		 * If devices are being added to the system that quickly, maybe
383 		 * the user can just wait until all devices are added.
384 		 */
385 		for (;;) {
386 			error = sysctlbyname("kern.devstat.all",
387 					     dinfo->mem_ptr,
388 					     &dssize, NULL, 0);
389 			if (error != -1 || errno != EBUSY)
390 				break;
391 		}
392 		if (error == -1) {
393 			/*
394 			 * If we get ENOMEM back, that means that there are
395 			 * more devices now, so we need to allocate more
396 			 * space for the device array.
397 			 */
398 			if (errno == ENOMEM) {
399 				/*
400 				 * No need to set the error string here,
401 				 * devstat_getnumdevs() will do that if it fails.
402 				 */
403 				if ((dinfo->numdevs = devstat_getnumdevs(kd)) < 0)
404 					return(-1);
405 
406 				dssize = (dinfo->numdevs *
407 					sizeof(struct devstat)) + sizeof(long);
408 				dinfo->mem_ptr = (u_int8_t *)
409 					realloc(dinfo->mem_ptr, dssize);
410 				if ((error = sysctlbyname("kern.devstat.all",
411 				    dinfo->mem_ptr, &dssize, NULL, 0)) == -1) {
412 					snprintf(devstat_errbuf,
413 						 sizeof(devstat_errbuf),
414 					    	 "%s: error getting device "
415 					    	 "stats\n%s: %s", func_name,
416 					    	 func_name, strerror(errno));
417 					return(-1);
418 				}
419 			} else {
420 				snprintf(devstat_errbuf, sizeof(devstat_errbuf),
421 					 "%s: error getting device stats\n"
422 					 "%s: %s", func_name, func_name,
423 					 strerror(errno));
424 				return(-1);
425 			}
426 		}
427 
428 	} else {
429 		/*
430 		 * This is of course non-atomic, but since we are working
431 		 * on a core dump, the generation is unlikely to change
432 		 */
433 		if ((dinfo->numdevs = devstat_getnumdevs(kd)) == -1)
434 			return(-1);
435 		if ((dinfo->mem_ptr = get_devstat_kvm(kd)) == NULL)
436 			return(-1);
437 	}
438 	/*
439 	 * The sysctl spits out the generation as the first four bytes,
440 	 * then all of the device statistics structures.
441 	 */
442 	dinfo->generation = *(long *)dinfo->mem_ptr;
443 
444 	/*
445 	 * If the generation has changed, and if the current number of
446 	 * devices is not the same as the number of devices recorded in the
447 	 * devinfo structure, it is likely that the device list has shrunk.
448 	 * The reason that it is likely that the device list has shrunk in
449 	 * this case is that if the device list has grown, the sysctl above
450 	 * will return an ENOMEM error, and we will reset the number of
451 	 * devices and reallocate the device array.  If the second sysctl
452 	 * fails, we will return an error and therefore never get to this
453 	 * point.  If the device list has shrunk, the sysctl will not
454 	 * return an error since we have more space allocated than is
455 	 * necessary.  So, in the shrinkage case, we catch it here and
456 	 * reallocate the array so that we don't use any more space than is
457 	 * necessary.
458 	 */
459 	if (oldgeneration != dinfo->generation) {
460 		if (devstat_getnumdevs(kd) != dinfo->numdevs) {
461 			if ((dinfo->numdevs = devstat_getnumdevs(kd)) < 0)
462 				return(-1);
463 			dssize = (dinfo->numdevs * sizeof(struct devstat)) +
464 				sizeof(long);
465 			dinfo->mem_ptr = (u_int8_t *)realloc(dinfo->mem_ptr,
466 							     dssize);
467 		}
468 		retval = 1;
469 	}
470 
471 	dinfo->devices = (struct devstat *)(dinfo->mem_ptr + sizeof(long));
472 
473 	return(retval);
474 }
475 
476 /*
477  * selectdevs():
478  *
479  * Devices are selected/deselected based upon the following criteria:
480  * - devices specified by the user on the command line
481  * - devices matching any device type expressions given on the command line
482  * - devices with the highest I/O, if 'top' mode is enabled
483  * - the first n unselected devices in the device list, if maxshowdevs
484  *   devices haven't already been selected and if the user has not
485  *   specified any devices on the command line and if we're in "add" mode.
486  *
487  * Input parameters:
488  * - device selection list (dev_select)
489  * - current number of devices selected (num_selected)
490  * - total number of devices in the selection list (num_selections)
491  * - devstat generation as of the last time selectdevs() was called
492  *   (select_generation)
493  * - current devstat generation (current_generation)
494  * - current list of devices and statistics (devices)
495  * - number of devices in the current device list (numdevs)
496  * - compiled version of the command line device type arguments (matches)
497  *   - This is optional.  If the number of devices is 0, this will be ignored.
498  *   - The matching code pays attention to the current selection mode.  So
499  *     if you pass in a matching expression, it will be evaluated based
500  *     upon the selection mode that is passed in.  See below for details.
501  * - number of device type matching expressions (num_matches)
502  *   - Set to 0 to disable the matching code.
503  * - list of devices specified on the command line by the user (dev_selections)
504  * - number of devices selected on the command line by the user
505  *   (num_dev_selections)
506  * - Our selection mode.  There are four different selection modes:
507  *      - add mode.  (DS_SELECT_ADD) Any devices matching devices explicitly
508  *        selected by the user or devices matching a pattern given by the
509  *        user will be selected in addition to devices that are already
510  *        selected.  Additional devices will be selected, up to maxshowdevs
511  *        number of devices.
512  *      - only mode. (DS_SELECT_ONLY)  Only devices matching devices
513  *        explicitly given by the user or devices matching a pattern
514  *        given by the user will be selected.  No other devices will be
515  *        selected.
516  *      - addonly mode.  (DS_SELECT_ADDONLY)  This is similar to add and
517  *        only.  Basically, this will not de-select any devices that are
518  *        current selected, as only mode would, but it will also not
519  *        gratuitously select up to maxshowdevs devices as add mode would.
520  *      - remove mode.  (DS_SELECT_REMOVE)  Any devices matching devices
521  *        explicitly selected by the user or devices matching a pattern
522  *        given by the user will be de-selected.
523  * - maximum number of devices we can select (maxshowdevs)
524  * - flag indicating whether or not we're in 'top' mode (perf_select)
525  *
526  * Output data:
527  * - the device selection list may be modified and passed back out
528  * - the number of devices selected and the total number of items in the
529  *   device selection list may be changed
530  * - the selection generation may be changed to match the current generation
531  *
532  * Return values:
533  * -1  -- error
534  *  0  -- selected devices are unchanged
535  *  1  -- selected devices changed
536  */
537 int
538 devstat_selectdevs(struct device_selection **dev_select, int *num_selected,
539 		   int *num_selections, long *select_generation,
540 		   long current_generation, struct devstat *devices,
541 		   int numdevs, struct devstat_match *matches, int num_matches,
542 		   char **dev_selections, int num_dev_selections,
543 		   devstat_select_mode select_mode, int maxshowdevs,
544 		   int perf_select)
545 {
546 	int i, j, k;
547 	int init_selections = 0, init_selected_var = 0;
548 	struct device_selection *old_dev_select = NULL;
549 	int old_num_selections = 0, old_num_selected;
550 	int selection_number = 0;
551 	int changed = 0, found = 0;
552 
553 	if ((dev_select == NULL) || (devices == NULL) || (numdevs < 0))
554 		return(-1);
555 
556 	/*
557 	 * We always want to make sure that we have as many dev_select
558 	 * entries as there are devices.
559 	 */
560 	/*
561 	 * In this case, we haven't selected devices before.
562 	 */
563 	if (*dev_select == NULL) {
564 		*dev_select = (struct device_selection *)malloc(numdevs *
565 			sizeof(struct device_selection));
566 		*select_generation = current_generation;
567 		init_selections = 1;
568 		changed = 1;
569 	/*
570 	 * In this case, we have selected devices before, but the device
571 	 * list has changed since we last selected devices, so we need to
572 	 * either enlarge or reduce the size of the device selection list.
573 	 */
574 	} else if (*num_selections != numdevs) {
575 		*dev_select = (struct device_selection *)realloc(*dev_select,
576 			numdevs * sizeof(struct device_selection));
577 		*select_generation = current_generation;
578 		init_selections = 1;
579 	/*
580 	 * In this case, we've selected devices before, and the selection
581 	 * list is the same size as it was the last time, but the device
582 	 * list has changed.
583 	 */
584 	} else if (*select_generation < current_generation) {
585 		*select_generation = current_generation;
586 		init_selections = 1;
587 	}
588 
589 	/*
590 	 * If we're in "only" mode, we want to clear out the selected
591 	 * variable since we're going to select exactly what the user wants
592 	 * this time through.
593 	 */
594 	if (select_mode == DS_SELECT_ONLY)
595 		init_selected_var = 1;
596 
597 	/*
598 	 * In all cases, we want to back up the number of selected devices.
599 	 * It is a quick and accurate way to determine whether the selected
600 	 * devices have changed.
601 	 */
602 	old_num_selected = *num_selected;
603 
604 	/*
605 	 * We want to make a backup of the current selection list if
606 	 * the list of devices has changed, or if we're in performance
607 	 * selection mode.  In both cases, we don't want to make a backup
608 	 * if we already know for sure that the list will be different.
609 	 * This is certainly the case if this is our first time through the
610 	 * selection code.
611 	 */
612 	if (((init_selected_var != 0) || (init_selections != 0)
613 	 || (perf_select != 0)) && (changed == 0)){
614 		old_dev_select = (struct device_selection *)malloc(
615 		    *num_selections * sizeof(struct device_selection));
616 		old_num_selections = *num_selections;
617 		bcopy(*dev_select, old_dev_select,
618 		    sizeof(struct device_selection) * *num_selections);
619 	}
620 
621 	if (init_selections != 0) {
622 		bzero(*dev_select, sizeof(struct device_selection) * numdevs);
623 
624 		for (i = 0; i < numdevs; i++) {
625 			(*dev_select)[i].device_number =
626 				devices[i].device_number;
627 			strncpy((*dev_select)[i].device_name,
628 				devices[i].device_name,
629 				DEVSTAT_NAME_LEN);
630 			(*dev_select)[i].device_name[DEVSTAT_NAME_LEN - 1]='\0';
631 			(*dev_select)[i].unit_number = devices[i].unit_number;
632 			(*dev_select)[i].position = i;
633 		}
634 		*num_selections = numdevs;
635 	} else if (init_selected_var != 0) {
636 		for (i = 0; i < numdevs; i++)
637 			(*dev_select)[i].selected = 0;
638 	}
639 
640 	/* we haven't gotten around to selecting anything yet.. */
641 	if ((select_mode == DS_SELECT_ONLY) || (init_selections != 0)
642 	 || (init_selected_var != 0))
643 		*num_selected = 0;
644 
645 	/*
646 	 * Look through any devices the user specified on the command line
647 	 * and see if they match known devices.  If so, select them.
648 	 */
649 	for (i = 0; (i < *num_selections) && (num_dev_selections > 0); i++) {
650 		char tmpstr[80];
651 
652 		snprintf(tmpstr, sizeof(tmpstr), "%s%d",
653 			 (*dev_select)[i].device_name,
654 			 (*dev_select)[i].unit_number);
655 		for (j = 0; j < num_dev_selections; j++) {
656 			if (strcmp(tmpstr, dev_selections[j]) == 0) {
657 				/*
658 				 * Here we do different things based on the
659 				 * mode we're in.  If we're in add or
660 				 * addonly mode, we only select this device
661 				 * if it hasn't already been selected.
662 				 * Otherwise, we would be unnecessarily
663 				 * changing the selection order and
664 				 * incrementing the selection count.  If
665 				 * we're in only mode, we unconditionally
666 				 * select this device, since in only mode
667 				 * any previous selections are erased and
668 				 * manually specified devices are the first
669 				 * ones to be selected.  If we're in remove
670 				 * mode, we de-select the specified device and
671 				 * decrement the selection count.
672 				 */
673 				switch(select_mode) {
674 				case DS_SELECT_ADD:
675 				case DS_SELECT_ADDONLY:
676 					if ((*dev_select)[i].selected)
677 						break;
678 					/* FALLTHROUGH */
679 				case DS_SELECT_ONLY:
680 					(*dev_select)[i].selected =
681 						++selection_number;
682 					(*num_selected)++;
683 					break;
684 				case DS_SELECT_REMOVE:
685 					(*dev_select)[i].selected = 0;
686 					(*num_selected)--;
687 					/*
688 					 * This isn't passed back out, we
689 					 * just use it to keep track of
690 					 * how many devices we've removed.
691 					 */
692 					num_dev_selections--;
693 					break;
694 				}
695 				break;
696 			}
697 		}
698 	}
699 
700 	/*
701 	 * Go through the user's device type expressions and select devices
702 	 * accordingly.  We only do this if the number of devices already
703 	 * selected is less than the maximum number we can show.
704 	 */
705 	for (i = 0; (i < num_matches) && (*num_selected < maxshowdevs); i++) {
706 		/* We should probably indicate some error here */
707 		if ((matches[i].match_fields == DEVSTAT_MATCH_NONE)
708 		 || (matches[i].num_match_categories <= 0))
709 			continue;
710 
711 		for (j = 0; j < numdevs; j++) {
712 			int num_match_categories;
713 
714 			num_match_categories = matches[i].num_match_categories;
715 
716 			/*
717 			 * Determine whether or not the current device
718 			 * matches the given matching expression.  This if
719 			 * statement consists of three components:
720 			 *   - the device type check
721 			 *   - the device interface check
722 			 *   - the passthrough check
723 			 * If a the matching test is successful, it
724 			 * decrements the number of matching categories,
725 			 * and if we've reached the last element that
726 			 * needed to be matched, the if statement succeeds.
727 			 *
728 			 */
729 			if ((((matches[i].match_fields & DEVSTAT_MATCH_TYPE)!=0)
730 			  && ((devices[j].device_type & DEVSTAT_TYPE_MASK) ==
731 			        (matches[i].device_type & DEVSTAT_TYPE_MASK))
732 			  &&(((matches[i].match_fields & DEVSTAT_MATCH_PASS)!=0)
733 			   || (((matches[i].match_fields &
734 				DEVSTAT_MATCH_PASS) == 0)
735 			    && ((devices[j].device_type &
736 			        DEVSTAT_TYPE_PASS) == 0)))
737 			  && (--num_match_categories == 0))
738 			 || (((matches[i].match_fields & DEVSTAT_MATCH_IF) != 0)
739 			  && ((devices[j].device_type & DEVSTAT_TYPE_IF_MASK) ==
740 			        (matches[i].device_type & DEVSTAT_TYPE_IF_MASK))
741 			  &&(((matches[i].match_fields & DEVSTAT_MATCH_PASS)!=0)
742 			   || (((matches[i].match_fields &
743 				DEVSTAT_MATCH_PASS) == 0)
744 			    && ((devices[j].device_type &
745 				DEVSTAT_TYPE_PASS) == 0)))
746 			  && (--num_match_categories == 0))
747 			 || (((matches[i].match_fields & DEVSTAT_MATCH_PASS)!=0)
748 			  && ((devices[j].device_type & DEVSTAT_TYPE_PASS) != 0)
749 			  && (--num_match_categories == 0))) {
750 
751 				/*
752 				 * This is probably a non-optimal solution
753 				 * to the problem that the devices in the
754 				 * device list will not be in the same
755 				 * order as the devices in the selection
756 				 * array.
757 				 */
758 				for (k = 0; k < numdevs; k++) {
759 					if ((*dev_select)[k].position == j) {
760 						found = 1;
761 						break;
762 					}
763 				}
764 
765 				/*
766 				 * There shouldn't be a case where a device
767 				 * in the device list is not in the
768 				 * selection list...but it could happen.
769 				 */
770 				if (found != 1) {
771 					fprintf(stderr, "selectdevs: couldn't"
772 						" find %s%d in selection "
773 						"list\n",
774 						devices[j].device_name,
775 						devices[j].unit_number);
776 					break;
777 				}
778 
779 				/*
780 				 * We do different things based upon the
781 				 * mode we're in.  If we're in add or only
782 				 * mode, we go ahead and select this device
783 				 * if it hasn't already been selected.  If
784 				 * it has already been selected, we leave
785 				 * it alone so we don't mess up the
786 				 * selection ordering.  Manually specified
787 				 * devices have already been selected, and
788 				 * they have higher priority than pattern
789 				 * matched devices.  If we're in remove
790 				 * mode, we de-select the given device and
791 				 * decrement the selected count.
792 				 */
793 				switch(select_mode) {
794 				case DS_SELECT_ADD:
795 				case DS_SELECT_ADDONLY:
796 				case DS_SELECT_ONLY:
797 					if ((*dev_select)[k].selected != 0)
798 						break;
799 					(*dev_select)[k].selected =
800 						++selection_number;
801 					(*num_selected)++;
802 					break;
803 				case DS_SELECT_REMOVE:
804 					(*dev_select)[k].selected = 0;
805 					(*num_selected)--;
806 					break;
807 				}
808 			}
809 		}
810 	}
811 
812 	/*
813 	 * Here we implement "top" mode.  Devices are sorted in the
814 	 * selection array based on two criteria:  whether or not they are
815 	 * selected (not selection number, just the fact that they are
816 	 * selected!) and the number of bytes in the "bytes" field of the
817 	 * selection structure.  The bytes field generally must be kept up
818 	 * by the user.  In the future, it may be maintained by library
819 	 * functions, but for now the user has to do the work.
820 	 *
821 	 * At first glance, it may seem wrong that we don't go through and
822 	 * select every device in the case where the user hasn't specified
823 	 * any devices or patterns.  In fact, though, it won't make any
824 	 * difference in the device sorting.  In that particular case (i.e.
825 	 * when we're in "add" or "only" mode, and the user hasn't
826 	 * specified anything) the first time through no devices will be
827 	 * selected, so the only criterion used to sort them will be their
828 	 * performance.  The second time through, and every time thereafter,
829 	 * all devices will be selected, so again selection won't matter.
830 	 */
831 	if (perf_select != 0) {
832 
833 		/* Sort the device array by throughput  */
834 		qsort(*dev_select, *num_selections,
835 		      sizeof(struct device_selection),
836 		      compare_select);
837 
838 		if (*num_selected == 0) {
839 			/*
840 			 * Here we select every device in the array, if it
841 			 * isn't already selected.  Because the 'selected'
842 			 * variable in the selection array entries contains
843 			 * the selection order, the devstats routine can show
844 			 * the devices that were selected first.
845 			 */
846 			for (i = 0; i < *num_selections; i++) {
847 				if ((*dev_select)[i].selected == 0) {
848 					(*dev_select)[i].selected =
849 						++selection_number;
850 					(*num_selected)++;
851 				}
852 			}
853 		} else {
854 			selection_number = 0;
855 			for (i = 0; i < *num_selections; i++) {
856 				if ((*dev_select)[i].selected != 0) {
857 					(*dev_select)[i].selected =
858 						++selection_number;
859 				}
860 			}
861 		}
862 	}
863 
864 	/*
865 	 * If we're in the "add" selection mode and if we haven't already
866 	 * selected maxshowdevs number of devices, go through the array and
867 	 * select any unselected devices.  If we're in "only" mode, we
868 	 * obviously don't want to select anything other than what the user
869 	 * specifies.  If we're in "remove" mode, it probably isn't a good
870 	 * idea to go through and select any more devices, since we might
871 	 * end up selecting something that the user wants removed.  Through
872 	 * more complicated logic, we could actually figure this out, but
873 	 * that would probably require combining this loop with the various
874 	 * selections loops above.
875 	 */
876 	if ((select_mode == DS_SELECT_ADD) && (*num_selected < maxshowdevs)) {
877 		for (i = 0; i < *num_selections; i++)
878 			if ((*dev_select)[i].selected == 0) {
879 				(*dev_select)[i].selected = ++selection_number;
880 				(*num_selected)++;
881 			}
882 	}
883 
884 	/*
885 	 * Look at the number of devices that have been selected.  If it
886 	 * has changed, set the changed variable.  Otherwise, if we've
887 	 * made a backup of the selection list, compare it to the current
888 	 * selection list to see if the selected devices have changed.
889 	 */
890 	if ((changed == 0) && (old_num_selected != *num_selected))
891 		changed = 1;
892 	else if ((changed == 0) && (old_dev_select != NULL)) {
893 		/*
894 		 * Now we go through the selection list and we look at
895 		 * it three different ways.
896 		 */
897 		for (i = 0; (i < *num_selections) && (changed == 0) &&
898 		     (i < old_num_selections); i++) {
899 			/*
900 			 * If the device at index i in both the new and old
901 			 * selection arrays has the same device number and
902 			 * selection status, it hasn't changed.  We
903 			 * continue on to the next index.
904 			 */
905 			if (((*dev_select)[i].device_number ==
906 			     old_dev_select[i].device_number)
907 			 && ((*dev_select)[i].selected ==
908 			     old_dev_select[i].selected))
909 				continue;
910 
911 			/*
912 			 * Now, if we're still going through the if
913 			 * statement, the above test wasn't true.  So we
914 			 * check here to see if the device at index i in
915 			 * the current array is the same as the device at
916 			 * index i in the old array.  If it is, that means
917 			 * that its selection number has changed.  Set
918 			 * changed to 1 and exit the loop.
919 			 */
920 			else if ((*dev_select)[i].device_number ==
921 			          old_dev_select[i].device_number) {
922 				changed = 1;
923 				break;
924 			}
925 			/*
926 			 * If we get here, then the device at index i in
927 			 * the current array isn't the same device as the
928 			 * device at index i in the old array.
929 			 */
930 			else {
931 				found = 0;
932 
933 				/*
934 				 * Search through the old selection array
935 				 * looking for a device with the same
936 				 * device number as the device at index i
937 				 * in the current array.  If the selection
938 				 * status is the same, then we mark it as
939 				 * found.  If the selection status isn't
940 				 * the same, we break out of the loop.
941 				 * Since found isn't set, changed will be
942 				 * set to 1 below.
943 				 */
944 				for (j = 0; j < old_num_selections; j++) {
945 					if (((*dev_select)[i].device_number ==
946 					      old_dev_select[j].device_number)
947 					 && ((*dev_select)[i].selected ==
948 					      old_dev_select[j].selected)){
949 						found = 1;
950 						break;
951 					}
952 					else if ((*dev_select)[i].device_number
953 					    == old_dev_select[j].device_number)
954 						break;
955 				}
956 				if (found == 0)
957 					changed = 1;
958 			}
959 		}
960 	}
961 	if (old_dev_select != NULL)
962 		free(old_dev_select);
963 
964 	return(changed);
965 }
966 
967 /*
968  * Comparison routine for qsort() above.  Note that the comparison here is
969  * backwards -- generally, it should return a value to indicate whether
970  * arg1 is <, =, or > arg2.  Instead, it returns the opposite.  The reason
971  * it returns the opposite is so that the selection array will be sorted in
972  * order of decreasing performance.  We sort on two parameters.  The first
973  * sort key is whether or not one or the other of the devices in question
974  * has been selected.  If one of them has, and the other one has not, the
975  * selected device is automatically more important than the unselected
976  * device.  If neither device is selected, we judge the devices based upon
977  * performance.
978  */
979 static int
980 compare_select(const void *arg1, const void *arg2)
981 {
982 	if ((((const struct device_selection *)arg1)->selected)
983 	 && (((const struct device_selection *)arg2)->selected == 0))
984 		return(-1);
985 	else if ((((const struct device_selection *)arg1)->selected == 0)
986 	      && (((const struct device_selection *)arg2)->selected))
987 		return(1);
988 	else if (((const struct device_selection *)arg2)->bytes <
989 	         ((const struct device_selection *)arg1)->bytes)
990 		return(-1);
991 	else if (((const struct device_selection *)arg2)->bytes >
992 		 ((const struct device_selection *)arg1)->bytes)
993 		return(1);
994 	else
995 		return(0);
996 }
997 
998 /*
999  * Take a string with the general format "arg1,arg2,arg3", and build a
1000  * device matching expression from it.
1001  */
1002 int
1003 devstat_buildmatch(char *match_str, struct devstat_match **matches,
1004 		   int *num_matches)
1005 {
1006 	char *tstr[5];
1007 	char **tempstr;
1008 	int num_args;
1009 	int i, j;
1010 	const char *func_name = "devstat_buildmatch";
1011 
1012 	/* We can't do much without a string to parse */
1013 	if (match_str == NULL) {
1014 		snprintf(devstat_errbuf, sizeof(devstat_errbuf),
1015 			 "%s: no match expression", func_name);
1016 		return(-1);
1017 	}
1018 
1019 	/*
1020 	 * Break the (comma delimited) input string out into separate strings.
1021 	 */
1022 	for (tempstr = tstr, num_args  = 0;
1023 	     (*tempstr = strsep(&match_str, ",")) != NULL && (num_args < 5);
1024 	     num_args++)
1025 		if (**tempstr != '\0')
1026 			if (++tempstr >= &tstr[5])
1027 				break;
1028 
1029 	/* The user gave us too many type arguments */
1030 	if (num_args > 3) {
1031 		snprintf(devstat_errbuf, sizeof(devstat_errbuf),
1032 			 "%s: too many type arguments", func_name);
1033 		return(-1);
1034 	}
1035 
1036 	/*
1037 	 * Since you can't realloc a pointer that hasn't been malloced
1038 	 * first, we malloc first and then realloc.
1039 	 */
1040 	if (*num_matches == 0)
1041 		*matches = (struct devstat_match *)malloc(
1042 			   sizeof(struct devstat_match));
1043 	else
1044 		*matches = (struct devstat_match *)realloc(*matches,
1045 			  sizeof(struct devstat_match) * (*num_matches + 1));
1046 
1047 	/* Make sure the current entry is clear */
1048 	bzero(&matches[0][*num_matches], sizeof(struct devstat_match));
1049 
1050 	/*
1051 	 * Step through the arguments the user gave us and build a device
1052 	 * matching expression from them.
1053 	 */
1054 	for (i = 0; i < num_args; i++) {
1055 		char *tempstr2, *tempstr3;
1056 
1057 		/*
1058 		 * Get rid of leading white space.
1059 		 */
1060 		tempstr2 = tstr[i];
1061 		while (isspace(*tempstr2) && (*tempstr2 != '\0'))
1062 			tempstr2++;
1063 
1064 		/*
1065 		 * Get rid of trailing white space.
1066 		 */
1067 		tempstr3 = &tempstr2[strlen(tempstr2) - 1];
1068 
1069 		while ((*tempstr3 != '\0') && (tempstr3 > tempstr2)
1070 		    && (isspace(*tempstr3))) {
1071 			*tempstr3 = '\0';
1072 			tempstr3--;
1073 		}
1074 
1075 		/*
1076 		 * Go through the match table comparing the user's
1077 		 * arguments to known device types, interfaces, etc.
1078 		 */
1079 		for (j = 0; match_table[j].match_str != NULL; j++) {
1080 			/*
1081 			 * We do case-insensitive matching, in case someone
1082 			 * wants to enter "SCSI" instead of "scsi" or
1083 			 * something like that.  Only compare as many
1084 			 * characters as are in the string in the match
1085 			 * table.  This should help if someone tries to use
1086 			 * a super-long match expression.
1087 			 */
1088 			if (strncasecmp(tempstr2, match_table[j].match_str,
1089 			    strlen(match_table[j].match_str)) == 0) {
1090 				/*
1091 				 * Make sure the user hasn't specified two
1092 				 * items of the same type, like "da" and
1093 				 * "cd".  One device cannot be both.
1094 				 */
1095 				if (((*matches)[*num_matches].match_fields &
1096 				    match_table[j].match_field) != 0) {
1097 					snprintf(devstat_errbuf,
1098 						 sizeof(devstat_errbuf),
1099 						 "%s: cannot have more than "
1100 						 "one match item in a single "
1101 						 "category", func_name);
1102 					return(-1);
1103 				}
1104 				/*
1105 				 * If we've gotten this far, we have a
1106 				 * winner.  Set the appropriate fields in
1107 				 * the match entry.
1108 				 */
1109 				(*matches)[*num_matches].match_fields |=
1110 					match_table[j].match_field;
1111 				(*matches)[*num_matches].device_type |=
1112 					match_table[j].type;
1113 				(*matches)[*num_matches].num_match_categories++;
1114 				break;
1115 			}
1116 		}
1117 		/*
1118 		 * We should have found a match in the above for loop.  If
1119 		 * not, that means the user entered an invalid device type
1120 		 * or interface.
1121 		 */
1122 		if ((*matches)[*num_matches].num_match_categories != (i + 1)) {
1123 			snprintf(devstat_errbuf, sizeof(devstat_errbuf),
1124 				 "%s: unknown match item \"%s\"", func_name,
1125 				 tstr[i]);
1126 			return(-1);
1127 		}
1128 	}
1129 
1130 	(*num_matches)++;
1131 
1132 	return(0);
1133 }
1134 
1135 /*
1136  * Compute a number of device statistics.  Only one field is mandatory, and
1137  * that is "current".  Everything else is optional.  The caller passes in
1138  * pointers to variables to hold the various statistics he desires.  If he
1139  * doesn't want a particular staistic, he should pass in a NULL pointer.
1140  * Return values:
1141  * 0   -- success
1142  * -1  -- failure
1143  */
1144 int
1145 compute_stats(struct devstat *current, struct devstat *previous,
1146 	      long double etime, u_int64_t *total_bytes,
1147 	      u_int64_t *total_transfers, u_int64_t *total_blocks,
1148 	      long double *kb_per_transfer, long double *transfers_per_second,
1149 	      long double *mb_per_second, long double *blocks_per_second,
1150 	      long double *ms_per_transaction)
1151 {
1152 	return(devstat_compute_statistics(current, previous, etime,
1153 	       total_bytes ? DSM_TOTAL_BYTES : DSM_SKIP,
1154 	       total_bytes,
1155 	       total_transfers ? DSM_TOTAL_TRANSFERS : DSM_SKIP,
1156 	       total_transfers,
1157 	       total_blocks ? DSM_TOTAL_BLOCKS : DSM_SKIP,
1158 	       total_blocks,
1159 	       kb_per_transfer ? DSM_KB_PER_TRANSFER : DSM_SKIP,
1160 	       kb_per_transfer,
1161 	       transfers_per_second ? DSM_TRANSFERS_PER_SECOND : DSM_SKIP,
1162 	       transfers_per_second,
1163 	       mb_per_second ? DSM_MB_PER_SECOND : DSM_SKIP,
1164 	       mb_per_second,
1165 	       blocks_per_second ? DSM_BLOCKS_PER_SECOND : DSM_SKIP,
1166 	       blocks_per_second,
1167 	       ms_per_transaction ? DSM_MS_PER_TRANSACTION : DSM_SKIP,
1168 	       ms_per_transaction,
1169 	       DSM_NONE));
1170 }
1171 
1172 
1173 /* This is 1/2^64 */
1174 #define BINTIME_SCALE 5.42101086242752217003726400434970855712890625e-20
1175 
1176 long double
1177 devstat_compute_etime(struct bintime *cur_time, struct bintime *prev_time)
1178 {
1179 	long double etime;
1180 
1181 	etime = cur_time->sec;
1182 	etime += cur_time->frac * BINTIME_SCALE;
1183 	if (prev_time != NULL) {
1184 		etime -= prev_time->sec;
1185 		etime -= prev_time->frac * BINTIME_SCALE;
1186 	}
1187 	return(etime);
1188 }
1189 
1190 #define DELTA(field, index)				\
1191 	(current->field[(index)] - (previous ? previous->field[(index)] : 0))
1192 
1193 #define DELTA_T(field)					\
1194 	devstat_compute_etime(&current->field,  	\
1195 	(previous ? &previous->field : NULL))
1196 
1197 int
1198 devstat_compute_statistics(struct devstat *current, struct devstat *previous,
1199 			   long double etime, ...)
1200 {
1201 	const char *func_name = "devstat_compute_statistics";
1202 	u_int64_t totalbytes, totalbytesread, totalbyteswrite, totalbytesfree;
1203 	u_int64_t totaltransfers, totaltransfersread, totaltransferswrite;
1204 	u_int64_t totaltransfersother, totalblocks, totalblocksread;
1205 	u_int64_t totalblockswrite, totaltransfersfree, totalblocksfree;
1206 	va_list ap;
1207 	devstat_metric metric;
1208 	u_int64_t *destu64;
1209 	long double *destld;
1210 	int retval, i;
1211 
1212 	retval = 0;
1213 
1214 	/*
1215 	 * current is the only mandatory field.
1216 	 */
1217 	if (current == NULL) {
1218 		snprintf(devstat_errbuf, sizeof(devstat_errbuf),
1219 			 "%s: current stats structure was NULL", func_name);
1220 		return(-1);
1221 	}
1222 
1223 	totalbytesread = DELTA(bytes, DEVSTAT_READ);
1224 	totalbyteswrite = DELTA(bytes, DEVSTAT_WRITE);
1225 	totalbytesfree = DELTA(bytes, DEVSTAT_FREE);
1226 	totalbytes = totalbytesread + totalbyteswrite + totalbytesfree;
1227 
1228 	totaltransfersread = DELTA(operations, DEVSTAT_READ);
1229 	totaltransferswrite = DELTA(operations, DEVSTAT_WRITE);
1230 	totaltransfersother = DELTA(operations, DEVSTAT_NO_DATA);
1231 	totaltransfersfree = DELTA(operations, DEVSTAT_FREE);
1232 	totaltransfers = totaltransfersread + totaltransferswrite +
1233 			 totaltransfersother + totaltransfersfree;
1234 
1235 	totalblocks = totalbytes;
1236 	totalblocksread = totalbytesread;
1237 	totalblockswrite = totalbyteswrite;
1238 	totalblocksfree = totalbytesfree;
1239 
1240 	if (current->block_size > 0) {
1241 		totalblocks /= current->block_size;
1242 		totalblocksread /= current->block_size;
1243 		totalblockswrite /= current->block_size;
1244 		totalblocksfree /= current->block_size;
1245 	} else {
1246 		totalblocks /= 512;
1247 		totalblocksread /= 512;
1248 		totalblockswrite /= 512;
1249 		totalblocksfree /= 512;
1250 	}
1251 
1252 	va_start(ap, etime);
1253 
1254 	while ((metric = (devstat_metric)va_arg(ap, devstat_metric)) != 0) {
1255 
1256 		if (metric == DSM_NONE)
1257 			break;
1258 
1259 		if (metric >= DSM_MAX) {
1260 			snprintf(devstat_errbuf, sizeof(devstat_errbuf),
1261 				 "%s: metric %d is out of range", func_name,
1262 				 metric);
1263 			retval = -1;
1264 			goto bailout;
1265 		}
1266 
1267 		switch (devstat_arg_list[metric].argtype) {
1268 		case DEVSTAT_ARG_UINT64:
1269 			destu64 = (u_int64_t *)va_arg(ap, u_int64_t *);
1270 			break;
1271 		case DEVSTAT_ARG_LD:
1272 			destld = (long double *)va_arg(ap, long double *);
1273 			break;
1274 		case DEVSTAT_ARG_SKIP:
1275 			destld = (long double *)va_arg(ap, long double *);
1276 			break;
1277 		default:
1278 			retval = -1;
1279 			goto bailout;
1280 			break; /* NOTREACHED */
1281 		}
1282 
1283 		if (devstat_arg_list[metric].argtype == DEVSTAT_ARG_SKIP)
1284 			continue;
1285 
1286 		switch (metric) {
1287 		case DSM_TOTAL_BYTES:
1288 			*destu64 = totalbytes;
1289 			break;
1290 		case DSM_TOTAL_BYTES_READ:
1291 			*destu64 = totalbytesread;
1292 			break;
1293 		case DSM_TOTAL_BYTES_WRITE:
1294 			*destu64 = totalbyteswrite;
1295 			break;
1296 		case DSM_TOTAL_BYTES_FREE:
1297 			*destu64 = totalbytesfree;
1298 			break;
1299 		case DSM_TOTAL_TRANSFERS:
1300 			*destu64 = totaltransfers;
1301 			break;
1302 		case DSM_TOTAL_TRANSFERS_READ:
1303 			*destu64 = totaltransfersread;
1304 			break;
1305 		case DSM_TOTAL_TRANSFERS_WRITE:
1306 			*destu64 = totaltransferswrite;
1307 			break;
1308 		case DSM_TOTAL_TRANSFERS_FREE:
1309 			*destu64 = totaltransfersfree;
1310 			break;
1311 		case DSM_TOTAL_TRANSFERS_OTHER:
1312 			*destu64 = totaltransfersother;
1313 			break;
1314 		case DSM_TOTAL_BLOCKS:
1315 			*destu64 = totalblocks;
1316 			break;
1317 		case DSM_TOTAL_BLOCKS_READ:
1318 			*destu64 = totalblocksread;
1319 			break;
1320 		case DSM_TOTAL_BLOCKS_WRITE:
1321 			*destu64 = totalblockswrite;
1322 			break;
1323 		case DSM_TOTAL_BLOCKS_FREE:
1324 			*destu64 = totalblocksfree;
1325 			break;
1326 		case DSM_KB_PER_TRANSFER:
1327 			*destld = totalbytes;
1328 			*destld /= 1024;
1329 			if (totaltransfers > 0)
1330 				*destld /= totaltransfers;
1331 			else
1332 				*destld = 0.0;
1333 			break;
1334 		case DSM_KB_PER_TRANSFER_READ:
1335 			*destld = totalbytesread;
1336 			*destld /= 1024;
1337 			if (totaltransfersread > 0)
1338 				*destld /= totaltransfersread;
1339 			else
1340 				*destld = 0.0;
1341 			break;
1342 		case DSM_KB_PER_TRANSFER_WRITE:
1343 			*destld = totalbyteswrite;
1344 			*destld /= 1024;
1345 			if (totaltransferswrite > 0)
1346 				*destld /= totaltransferswrite;
1347 			else
1348 				*destld = 0.0;
1349 			break;
1350 		case DSM_KB_PER_TRANSFER_FREE:
1351 			*destld = totalbytesfree;
1352 			*destld /= 1024;
1353 			if (totaltransfersfree > 0)
1354 				*destld /= totaltransfersfree;
1355 			else
1356 				*destld = 0.0;
1357 			break;
1358 		case DSM_TRANSFERS_PER_SECOND:
1359 			if (etime > 0.0) {
1360 				*destld = totaltransfers;
1361 				*destld /= etime;
1362 			} else
1363 				*destld = 0.0;
1364 			break;
1365 		case DSM_TRANSFERS_PER_SECOND_READ:
1366 			if (etime > 0.0) {
1367 				*destld = totaltransfersread;
1368 				*destld /= etime;
1369 			} else
1370 				*destld = 0.0;
1371 			break;
1372 		case DSM_TRANSFERS_PER_SECOND_WRITE:
1373 			if (etime > 0.0) {
1374 				*destld = totaltransferswrite;
1375 				*destld /= etime;
1376 			} else
1377 				*destld = 0.0;
1378 			break;
1379 		case DSM_TRANSFERS_PER_SECOND_FREE:
1380 			if (etime > 0.0) {
1381 				*destld = totaltransfersfree;
1382 				*destld /= etime;
1383 			} else
1384 				*destld = 0.0;
1385 			break;
1386 		case DSM_TRANSFERS_PER_SECOND_OTHER:
1387 			if (etime > 0.0) {
1388 				*destld = totaltransfersother;
1389 				*destld /= etime;
1390 			} else
1391 				*destld = 0.0;
1392 			break;
1393 		case DSM_MB_PER_SECOND:
1394 			*destld = totalbytes;
1395 			*destld /= 1024 * 1024;
1396 			if (etime > 0.0)
1397 				*destld /= etime;
1398 			else
1399 				*destld = 0.0;
1400 			break;
1401 		case DSM_MB_PER_SECOND_READ:
1402 			*destld = totalbytesread;
1403 			*destld /= 1024 * 1024;
1404 			if (etime > 0.0)
1405 				*destld /= etime;
1406 			else
1407 				*destld = 0.0;
1408 			break;
1409 		case DSM_MB_PER_SECOND_WRITE:
1410 			*destld = totalbyteswrite;
1411 			*destld /= 1024 * 1024;
1412 			if (etime > 0.0)
1413 				*destld /= etime;
1414 			else
1415 				*destld = 0.0;
1416 			break;
1417 		case DSM_MB_PER_SECOND_FREE:
1418 			*destld = totalbytesfree;
1419 			*destld /= 1024 * 1024;
1420 			if (etime > 0.0)
1421 				*destld /= etime;
1422 			else
1423 				*destld = 0.0;
1424 			break;
1425 		case DSM_BLOCKS_PER_SECOND:
1426 			*destld = totalblocks;
1427 			if (etime > 0.0)
1428 				*destld /= etime;
1429 			else
1430 				*destld = 0.0;
1431 			break;
1432 		case DSM_BLOCKS_PER_SECOND_READ:
1433 			*destld = totalblocksread;
1434 			if (etime > 0.0)
1435 				*destld /= etime;
1436 			else
1437 				*destld = 0.0;
1438 			break;
1439 		case DSM_BLOCKS_PER_SECOND_WRITE:
1440 			*destld = totalblockswrite;
1441 			if (etime > 0.0)
1442 				*destld /= etime;
1443 			else
1444 				*destld = 0.0;
1445 			break;
1446 		case DSM_BLOCKS_PER_SECOND_FREE:
1447 			*destld = totalblocksfree;
1448 			if (etime > 0.0)
1449 				*destld /= etime;
1450 			else
1451 				*destld = 0.0;
1452 			break;
1453 		/*
1454 		 * This calculation is somewhat bogus.  It simply divides
1455 		 * the elapsed time by the total number of transactions
1456 		 * completed.  While that does give the caller a good
1457 		 * picture of the average rate of transaction completion,
1458 		 * it doesn't necessarily give the caller a good view of
1459 		 * how long transactions took to complete on average.
1460 		 * Those two numbers will be different for a device that
1461 		 * can handle more than one transaction at a time.  e.g.
1462 		 * SCSI disks doing tagged queueing.
1463 		 *
1464 		 * The only way to accurately determine the real average
1465 		 * time per transaction would be to compute and store the
1466 		 * time on a per-transaction basis.  That currently isn't
1467 		 * done in the kernel, and would only be desireable if it
1468 		 * could be implemented in a somewhat non-intrusive and high
1469 		 * performance way.
1470 		 */
1471 		case DSM_MS_PER_TRANSACTION:
1472 			if (totaltransfers > 0) {
1473 				*destld = 0;
1474 				for (i = 0; i < DEVSTAT_N_TRANS_FLAGS; i++)
1475 					*destld += DELTA_T(duration[i]);
1476 				*destld /= totaltransfers;
1477 				*destld *= 1000;
1478 			} else
1479 				*destld = 0.0;
1480 			break;
1481 		/*
1482 		 * As above, these next two really only give the average
1483 		 * rate of completion for read and write transactions, not
1484 		 * the average time the transaction took to complete.
1485 		 */
1486 		case DSM_MS_PER_TRANSACTION_READ:
1487 			if (totaltransfersread > 0) {
1488 				*destld = DELTA_T(duration[DEVSTAT_READ]);
1489 				*destld /= totaltransfersread;
1490 				*destld *= 1000;
1491 			} else
1492 				*destld = 0.0;
1493 			break;
1494 		case DSM_MS_PER_TRANSACTION_WRITE:
1495 			if (totaltransferswrite > 0) {
1496 				*destld = DELTA_T(duration[DEVSTAT_WRITE]);
1497 				*destld /= totaltransferswrite;
1498 				*destld *= 1000;
1499 			} else
1500 				*destld = 0.0;
1501 			break;
1502 		case DSM_MS_PER_TRANSACTION_FREE:
1503 			if (totaltransfersfree > 0) {
1504 				*destld = DELTA_T(duration[DEVSTAT_FREE]);
1505 				*destld /= totaltransfersfree;
1506 				*destld *= 1000;
1507 			} else
1508 				*destld = 0.0;
1509 			break;
1510 		case DSM_MS_PER_TRANSACTION_OTHER:
1511 			if (totaltransfersother > 0) {
1512 				*destld = DELTA_T(duration[DEVSTAT_NO_DATA]);
1513 				*destld /= totaltransfersother;
1514 				*destld *= 1000;
1515 			} else
1516 				*destld = 0.0;
1517 			break;
1518 		case DSM_BUSY_PCT:
1519 			*destld = DELTA_T(busy_time);
1520 			if (*destld < 0)
1521 				*destld = 0;
1522 			*destld /= etime;
1523 			*destld *= 100;
1524 			if (*destld < 0)
1525 				*destld = 0;
1526 			break;
1527 		case DSM_QUEUE_LENGTH:
1528 			*destu64 = current->start_count - current->end_count;
1529 			break;
1530 /*
1531  * XXX: comment out the default block to see if any case's are missing.
1532  */
1533 #if 1
1534 		default:
1535 			/*
1536 			 * This shouldn't happen, since we should have
1537 			 * caught any out of range metrics at the top of
1538 			 * the loop.
1539 			 */
1540 			snprintf(devstat_errbuf, sizeof(devstat_errbuf),
1541 				 "%s: unknown metric %d", func_name, metric);
1542 			retval = -1;
1543 			goto bailout;
1544 			break; /* NOTREACHED */
1545 #endif
1546 		}
1547 	}
1548 
1549 bailout:
1550 
1551 	va_end(ap);
1552 	return(retval);
1553 }
1554 
1555 static int
1556 readkmem(kvm_t *kd, unsigned long addr, void *buf, size_t nbytes)
1557 {
1558 	const char *func_name = "readkmem";
1559 
1560 	if (kvm_read(kd, addr, buf, nbytes) == -1) {
1561 		snprintf(devstat_errbuf, sizeof(devstat_errbuf),
1562 			 "%s: error reading value (kvm_read): %s", func_name,
1563 			 kvm_geterr(kd));
1564 		return(-1);
1565 	}
1566 	return(0);
1567 }
1568 
1569 static int
1570 readkmem_nl(kvm_t *kd, const char *name, void *buf, size_t nbytes)
1571 {
1572 	const char *func_name = "readkmem_nl";
1573 	struct nlist nl[2];
1574 
1575 	nl[0].n_name = (char *)name;
1576 	nl[1].n_name = NULL;
1577 
1578 	if (kvm_nlist(kd, nl) == -1) {
1579 		snprintf(devstat_errbuf, sizeof(devstat_errbuf),
1580 			 "%s: error getting name list (kvm_nlist): %s",
1581 			 func_name, kvm_geterr(kd));
1582 		return(-1);
1583 	}
1584 	return(readkmem(kd, nl[0].n_value, buf, nbytes));
1585 }
1586 
1587 /*
1588  * This duplicates the functionality of the kernel sysctl handler for poking
1589  * through crash dumps.
1590  */
1591 static char *
1592 get_devstat_kvm(kvm_t *kd)
1593 {
1594 	int error, i, wp;
1595 	long gen;
1596 	struct devstat *nds;
1597 	struct devstat ds;
1598 	struct devstatlist dhead;
1599 	int num_devs;
1600 	char *rv = NULL;
1601 	const char *func_name = "get_devstat_kvm";
1602 
1603 	if ((num_devs = devstat_getnumdevs(kd)) <= 0)
1604 		return(NULL);
1605 	error = 0;
1606 	if (KREADNL(kd, X_DEVICE_STATQ, dhead) == -1)
1607 		return(NULL);
1608 
1609 	nds = STAILQ_FIRST(&dhead);
1610 
1611 	if ((rv = malloc(sizeof(gen))) == NULL) {
1612 		snprintf(devstat_errbuf, sizeof(devstat_errbuf),
1613 			 "%s: out of memory (initial malloc failed)",
1614 			 func_name);
1615 		return(NULL);
1616 	}
1617 	gen = devstat_getgeneration(kd);
1618 	memcpy(rv, &gen, sizeof(gen));
1619 	wp = sizeof(gen);
1620 	/*
1621 	 * Now push out all the devices.
1622 	 */
1623 	for (i = 0; (nds != NULL) && (i < num_devs);
1624 	     nds = STAILQ_NEXT(nds, dev_links), i++) {
1625 		if (readkmem(kd, (long)nds, &ds, sizeof(ds)) == -1) {
1626 			free(rv);
1627 			return(NULL);
1628 		}
1629 		nds = &ds;
1630 		rv = (char *)reallocf(rv, sizeof(gen) +
1631 				      sizeof(ds) * (i + 1));
1632 		if (rv == NULL) {
1633 			snprintf(devstat_errbuf, sizeof(devstat_errbuf),
1634 				 "%s: out of memory (malloc failed)",
1635 				 func_name);
1636 			return(NULL);
1637 		}
1638 		memcpy(rv + wp, &ds, sizeof(ds));
1639 		wp += sizeof(ds);
1640 	}
1641 	return(rv);
1642 }
1643