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