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