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