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