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