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