xref: /dragonfly/lib/libdevstat/devstat.c (revision 611395e5)
1 /*
2  * Copyright (c) 1997, 1998 Kenneth D. Merry.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. The name of the author may not be used to endorse or promote products
14  *    derived from this software without specific prior written permission.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  *
28  * $FreeBSD: src/lib/libdevstat/devstat.c,v 1.6 1999/08/28 00:04:26 peter Exp $
29  * $DragonFly: src/lib/libdevstat/devstat.c,v 1.3 2004/10/25 19:38:45 drhodus Exp $
30  */
31 
32 #include <sys/types.h>
33 #include <sys/sysctl.h>
34 #include <sys/errno.h>
35 #include <sys/dkstat.h>
36 
37 #include <ctype.h>
38 #include <err.h>
39 #include <stdio.h>
40 #include <stdlib.h>
41 #include <string.h>
42 
43 #include "devstat.h"
44 
45 char devstat_errbuf[DEVSTAT_ERRBUF_SIZE];
46 
47 /*
48  * Table to match descriptive strings with device types.  These are in
49  * order from most common to least common to speed search time.
50  */
51 struct devstat_match_table match_table[] = {
52 	{"da",		DEVSTAT_TYPE_DIRECT,	DEVSTAT_MATCH_TYPE},
53 	{"cd",		DEVSTAT_TYPE_CDROM,	DEVSTAT_MATCH_TYPE},
54 	{"scsi",	DEVSTAT_TYPE_IF_SCSI,	DEVSTAT_MATCH_IF},
55 	{"ide",		DEVSTAT_TYPE_IF_IDE,	DEVSTAT_MATCH_IF},
56 	{"other",	DEVSTAT_TYPE_IF_OTHER,	DEVSTAT_MATCH_IF},
57 	{"worm",	DEVSTAT_TYPE_WORM,	DEVSTAT_MATCH_TYPE},
58 	{"sa",		DEVSTAT_TYPE_SEQUENTIAL,DEVSTAT_MATCH_TYPE},
59 	{"pass",	DEVSTAT_TYPE_PASS,	DEVSTAT_MATCH_PASS},
60 	{"optical",	DEVSTAT_TYPE_OPTICAL,	DEVSTAT_MATCH_TYPE},
61 	{"array",	DEVSTAT_TYPE_STORARRAY,	DEVSTAT_MATCH_TYPE},
62 	{"changer",	DEVSTAT_TYPE_CHANGER,	DEVSTAT_MATCH_TYPE},
63 	{"scanner",	DEVSTAT_TYPE_SCANNER,	DEVSTAT_MATCH_TYPE},
64 	{"printer",	DEVSTAT_TYPE_PRINTER,	DEVSTAT_MATCH_TYPE},
65 	{"floppy",	DEVSTAT_TYPE_FLOPPY,	DEVSTAT_MATCH_TYPE},
66 	{"proc",	DEVSTAT_TYPE_PROCESSOR,	DEVSTAT_MATCH_TYPE},
67 	{"comm",	DEVSTAT_TYPE_COMM,	DEVSTAT_MATCH_TYPE},
68 	{"enclosure",	DEVSTAT_TYPE_ENCLOSURE,	DEVSTAT_MATCH_TYPE},
69 	{NULL,		0,			0}
70 };
71 
72 /*
73  * Local function declarations.
74  */
75 static int compare_select(const void *arg1, const void *arg2);
76 
77 int
78 getnumdevs(void)
79 {
80 	size_t numdevsize;
81 	int numdevs;
82 	char *func_name = "getnumdevs";
83 
84 	numdevsize = sizeof(int);
85 
86 	/*
87 	 * Find out how many devices we have in the system.
88 	 */
89 	if (sysctlbyname("kern.devstat.numdevs", &numdevs,
90 			 &numdevsize, NULL, 0) == -1) {
91 		sprintf(devstat_errbuf, "%s: error getting number of devices\n"
92 			"%s: %s", func_name, func_name, strerror(errno));
93 		return(-1);
94 	} else
95 		return(numdevs);
96 }
97 
98 /*
99  * This is an easy way to get the generation number, but the generation is
100  * supplied in a more atmoic manner by the kern.devstat.all sysctl.
101  * Because this generation sysctl is separate from the statistics sysctl,
102  * the device list and the generation could change between the time that
103  * this function is called and the device list is retreived.
104  */
105 long
106 getgeneration(void)
107 {
108 	size_t gensize;
109 	long generation;
110 	char *func_name = "getgeneration";
111 
112 	gensize = sizeof(long);
113 
114 	/*
115 	 * Get the current generation number.
116 	 */
117 	if (sysctlbyname("kern.devstat.generation", &generation,
118 			 &gensize, NULL, 0) == -1) {
119 		sprintf(devstat_errbuf,"%s: error getting devstat generation\n"
120 			"%s: %s", func_name, func_name, strerror(errno));
121 		return(-1);
122 	} else
123 		return(generation);
124 }
125 
126 /*
127  * Get the current devstat version.  The return value of this function
128  * should be compared with DEVSTAT_VERSION, which is defined in
129  * sys/devicestat.h.  This will enable userland programs to determine
130  * whether they are out of sync with the kernel.
131  */
132 int
133 getversion(void)
134 {
135 	size_t versize;
136 	int version;
137 	char *func_name = "getversion";
138 
139 	versize = sizeof(int);
140 
141 	/*
142 	 * Get the current devstat version.
143 	 */
144 	if (sysctlbyname("kern.devstat.version", &version, &versize,
145 			 NULL, 0) == -1) {
146 		sprintf(devstat_errbuf, "%s: error getting devstat version\n"
147 			"%s: %s", func_name, func_name, strerror(errno));
148 		return(-1);
149 	} else
150 		return(version);
151 }
152 
153 /*
154  * Check the devstat version we know about against the devstat version the
155  * kernel knows about.  If they don't match, print an error into the
156  * devstat error buffer, and return -1.  If they match, return 0.
157  */
158 int
159 checkversion(void)
160 {
161 	int retval = 0;
162 	int errlen = 0;
163 	char *func_name = "checkversion";
164 	int version;
165 
166 	version = getversion();
167 
168 	if (version != DEVSTAT_VERSION) {
169 		int buflen = 0;
170 		char tmpstr[256];
171 
172 		/*
173 		 * This is really pretty silly, but basically the idea is
174 		 * that if getversion() returns an error (i.e. -1), then it
175 		 * has printed an error message in the buffer.  Therefore,
176 		 * we need to add a \n to the end of that message before we
177 		 * print our own message in the buffer.
178 		 */
179 		if (version == -1) {
180 			buflen = strlen(devstat_errbuf);
181 			errlen = snprintf(tmpstr, sizeof(tmpstr), "\n");
182 			strncat(devstat_errbuf, tmpstr,
183 				DEVSTAT_ERRBUF_SIZE - buflen - 1);
184 			buflen += errlen;
185 		}
186 
187 		errlen = snprintf(tmpstr, sizeof(tmpstr),
188 				  "%s: userland devstat version %d is not "
189 				  "the same as the kernel\n%s: devstat "
190 				  "version %d\n", func_name, DEVSTAT_VERSION,
191 				  func_name, version);
192 
193 		if (version == -1) {
194 			strncat(devstat_errbuf, tmpstr,
195 				DEVSTAT_ERRBUF_SIZE - buflen - 1);
196 			buflen += errlen;
197 		} else {
198 			strncpy(devstat_errbuf, tmpstr, DEVSTAT_ERRBUF_SIZE);
199 			devstat_errbuf[DEVSTAT_ERRBUF_SIZE - 1] = '\0';
200 		}
201 
202                 if (version < DEVSTAT_VERSION)
203 			snprintf(tmpstr, sizeof(tmpstr),
204 				 "%s: libdevstat newer than kernel\n",
205 				 func_name);
206                 else
207 			snprintf(tmpstr, sizeof(tmpstr),
208 				 "%s: kernel newer than libdevstat\n",
209 				 func_name);
210 
211 		strncat(devstat_errbuf, tmpstr,
212 			DEVSTAT_ERRBUF_SIZE - buflen - 1);
213 
214 		retval = -1;
215 	}
216 
217 	return(retval);
218 }
219 
220 /*
221  * Get the current list of devices and statistics, and the current
222  * generation number.
223  *
224  * Return values:
225  * -1  -- error
226  *  0  -- device list is unchanged
227  *  1  -- device list has changed
228  */
229 int
230 getdevs(struct statinfo *stats)
231 {
232 	int error;
233 	size_t dssize;
234 	int oldnumdevs;
235 	long oldgeneration;
236 	int retval = 0;
237 	struct devinfo *dinfo;
238 	char *func_name = "getdevs";
239 
240 	dinfo = stats->dinfo;
241 
242 	if (dinfo == NULL) {
243 		sprintf(devstat_errbuf, "%s: stats->dinfo was NULL", func_name);
244 		return(-1);
245 	}
246 
247 	oldnumdevs = dinfo->numdevs;
248 	oldgeneration = dinfo->generation;
249 
250 	/*
251 	 * If this is our first time through, mem_ptr will be null.
252 	 */
253 	if (dinfo->mem_ptr == NULL) {
254 		/*
255 		 * Get the number of devices.  If it's negative, it's an
256 		 * error.  Don't bother setting the error string, since
257 		 * getnumdevs() has already done that for us.
258 		 */
259 		if ((dinfo->numdevs = getnumdevs()) < 0)
260 			return(-1);
261 
262 		/*
263 		 * The kern.devstat.all sysctl returns the current generation
264 		 * number, as well as all the devices.  So we need four
265 		 * bytes more.
266 		 */
267 		dssize =(dinfo->numdevs * sizeof(struct devstat)) +sizeof(long);
268 		dinfo->mem_ptr = (u_int8_t *)malloc(dssize);
269 	} else
270 		dssize =(dinfo->numdevs * sizeof(struct devstat)) +sizeof(long);
271 
272 	/* Get the current time when we get the stats */
273 	gettimeofday(&stats->busy_time, NULL);
274 
275 	/*
276 	 * Request all of the devices.  We only really allow for one
277 	 * ENOMEM failure.  It would, of course, be possible to just go in
278 	 * a loop and keep reallocing the device structure until we don't
279 	 * get ENOMEM back.  I'm not sure it's worth it, though.  If
280 	 * devices are being added to the system that quickly, maybe the
281 	 * user can just wait until all devices are added.
282 	 */
283 	if ((error = sysctlbyname("kern.devstat.all", dinfo->mem_ptr,
284 	     &dssize, NULL, 0)) == -1) {
285 		/*
286 		 * If we get ENOMEM back, that means that there are
287 		 * more devices now, so we need to allocate more
288 		 * space for the device array.
289 		 */
290 		if (errno == ENOMEM) {
291 			/*
292 			 * No need to set the error string here, getnumdevs()
293 			 * will do that if it fails.
294 			 */
295 			if ((dinfo->numdevs = getnumdevs()) < 0)
296 				return(-1);
297 
298 			dssize = (dinfo->numdevs * sizeof(struct devstat)) +
299 				sizeof(long);
300 			dinfo->mem_ptr = (u_int8_t *)realloc(dinfo->mem_ptr,
301 							     dssize);
302 			if ((error = sysctlbyname("kern.devstat.all",
303 			    dinfo->mem_ptr, &dssize, NULL, 0)) == -1) {
304 				sprintf(devstat_errbuf,
305 					"%s: error getting device stats\n"
306 					"%s: %s", func_name, func_name,
307 					strerror(errno));
308 				return(-1);
309 			}
310 		} else {
311 			sprintf(devstat_errbuf,
312 				"%s: error getting device stats\n"
313 				"%s: %s", func_name, func_name,
314 				strerror(errno));
315 			return(-1);
316 		}
317 	}
318 
319 	/*
320 	 * The sysctl spits out the generation as the first four bytes,
321 	 * then all of the device statistics structures.
322 	 */
323 	dinfo->generation = *(long *)dinfo->mem_ptr;
324 
325 	/*
326 	 * If the generation has changed, and if the current number of
327 	 * devices is not the same as the number of devices recorded in the
328 	 * devinfo structure, it is likely that the device list has shrunk.
329 	 * The reason that it is likely that the device list has shrunk in
330 	 * this case is that if the device list has grown, the sysctl above
331 	 * will return an ENOMEM error, and we will reset the number of
332 	 * devices and reallocate the device array.  If the second sysctl
333 	 * fails, we will return an error and therefore never get to this
334 	 * point.  If the device list has shrunk, the sysctl will not
335 	 * return an error since we have more space allocated than is
336 	 * necessary.  So, in the shrinkage case, we catch it here and
337 	 * reallocate the array so that we don't use any more space than is
338 	 * necessary.
339 	 */
340 	if (oldgeneration != dinfo->generation) {
341 		if (getnumdevs() != dinfo->numdevs) {
342 			if ((dinfo->numdevs = getnumdevs()) < 0)
343 				return(-1);
344 			dssize = (dinfo->numdevs * sizeof(struct devstat)) +
345 				sizeof(long);
346 			dinfo->mem_ptr = (u_int8_t *)realloc(dinfo->mem_ptr,
347 							     dssize);
348 		}
349 		retval = 1;
350 	}
351 
352 	dinfo->devices = (struct devstat *)(dinfo->mem_ptr + sizeof(long));
353 
354 	return(retval);
355 }
356 
357 /*
358  * selectdevs():
359  *
360  * Devices are selected/deselected based upon the following criteria:
361  * - devices specified by the user on the command line
362  * - devices matching any device type expressions given on the command line
363  * - devices with the highest I/O, if 'top' mode is enabled
364  * - the first n unselected devices in the device list, if maxshowdevs
365  *   devices haven't already been selected and if the user has not
366  *   specified any devices on the command line and if we're in "add" mode.
367  *
368  * Input parameters:
369  * - device selection list (dev_select)
370  * - current number of devices selected (num_selected)
371  * - total number of devices in the selection list (num_selections)
372  * - devstat generation as of the last time selectdevs() was called
373  *   (select_generation)
374  * - current devstat generation (current_generation)
375  * - current list of devices and statistics (devices)
376  * - number of devices in the current device list (numdevs)
377  * - compiled version of the command line device type arguments (matches)
378  *   - This is optional.  If the number of devices is 0, this will be ignored.
379  *   - The matching code pays attention to the current selection mode.  So
380  *     if you pass in a matching expression, it will be evaluated based
381  *     upon the selection mode that is passed in.  See below for details.
382  * - number of device type matching expressions (num_matches)
383  *   - Set to 0 to disable the matching code.
384  * - list of devices specified on the command line by the user (dev_selections)
385  * - number of devices selected on the command line by the user
386  *   (num_dev_selections)
387  * - Our selection mode.  There are four different selection modes:
388  *      - add mode.  (DS_SELECT_ADD) Any devices matching devices explicitly
389  *        selected by the user or devices matching a pattern given by the
390  *        user will be selected in addition to devices that are already
391  *        selected.  Additional devices will be selected, up to maxshowdevs
392  *        number of devices.
393  *      - only mode. (DS_SELECT_ONLY)  Only devices matching devices
394  *        explicitly given by the user or devices matching a pattern
395  *        given by the user will be selected.  No other devices will be
396  *        selected.
397  *      - addonly mode.  (DS_SELECT_ADDONLY)  This is similar to add and
398  *        only.  Basically, this will not de-select any devices that are
399  *        current selected, as only mode would, but it will also not
400  *        gratuitously select up to maxshowdevs devices as add mode would.
401  *      - remove mode.  (DS_SELECT_REMOVE)  Any devices matching devices
402  *        explicitly selected by the user or devices matching a pattern
403  *        given by the user will be de-selected.
404  * - maximum number of devices we can select (maxshowdevs)
405  * - flag indicating whether or not we're in 'top' mode (perf_select)
406  *
407  * Output data:
408  * - the device selection list may be modified and passed back out
409  * - the number of devices selected and the total number of items in the
410  *   device selection list may be changed
411  * - the selection generation may be changed to match the current generation
412  *
413  * Return values:
414  * -1  -- error
415  *  0  -- selected devices are unchanged
416  *  1  -- selected devices changed
417  */
418 int
419 selectdevs(struct device_selection **dev_select, int *num_selected,
420 	   int *num_selections, long *select_generation,
421 	   long current_generation, struct devstat *devices, int numdevs,
422 	   struct devstat_match *matches, int num_matches,
423 	   char **dev_selections, int num_dev_selections,
424 	   devstat_select_mode select_mode, int maxshowdevs, int perf_select)
425 {
426 	int i, j, k;
427 	int init_selections = 0, init_selected_var = 0;
428 	struct device_selection *old_dev_select = NULL;
429 	int old_num_selections = 0, old_num_selected;
430 	int selection_number = 0;
431 	int changed = 0, found = 0;
432 
433 	if ((dev_select == NULL) || (devices == NULL) || (numdevs <= 0))
434 		return(-1);
435 
436 	/*
437 	 * We always want to make sure that we have as many dev_select
438 	 * entries as there are devices.
439 	 */
440 	/*
441 	 * In this case, we haven't selected devices before.
442 	 */
443 	if (*dev_select == NULL) {
444 		*dev_select = (struct device_selection *)malloc(numdevs *
445 			sizeof(struct device_selection));
446 		*select_generation = current_generation;
447 		init_selections = 1;
448 		changed = 1;
449 	/*
450 	 * In this case, we have selected devices before, but the device
451 	 * list has changed since we last selected devices, so we need to
452 	 * either enlarge or reduce the size of the device selection list.
453 	 */
454 	} else if (*num_selections != numdevs) {
455 		*dev_select = (struct device_selection *)realloc(*dev_select,
456 			numdevs * sizeof(struct device_selection));
457 		*select_generation = current_generation;
458 		init_selections = 1;
459 	/*
460 	 * In this case, we've selected devices before, and the selection
461 	 * list is the same size as it was the last time, but the device
462 	 * list has changed.
463 	 */
464 	} else if (*select_generation < current_generation) {
465 		*select_generation = current_generation;
466 		init_selections = 1;
467 	}
468 
469 	/*
470 	 * If we're in "only" mode, we want to clear out the selected
471 	 * variable since we're going to select exactly what the user wants
472 	 * this time through.
473 	 */
474 	if (select_mode == DS_SELECT_ONLY)
475 		init_selected_var = 1;
476 
477 	/*
478 	 * In all cases, we want to back up the number of selected devices.
479 	 * It is a quick and accurate way to determine whether the selected
480 	 * devices have changed.
481 	 */
482 	old_num_selected = *num_selected;
483 
484 	/*
485 	 * We want to make a backup of the current selection list if
486 	 * the list of devices has changed, or if we're in performance
487 	 * selection mode.  In both cases, we don't want to make a backup
488 	 * if we already know for sure that the list will be different.
489 	 * This is certainly the case if this is our first time through the
490 	 * selection code.
491 	 */
492 	if (((init_selected_var != 0) || (init_selections != 0)
493 	 || (perf_select != 0)) && (changed == 0)){
494 		old_dev_select = (struct device_selection *)malloc(
495 		    *num_selections * sizeof(struct device_selection));
496 		old_num_selections = *num_selections;
497 		bcopy(*dev_select, old_dev_select,
498 		    sizeof(struct device_selection) * *num_selections);
499 	}
500 
501 	if (init_selections != 0) {
502 		bzero(*dev_select, sizeof(struct device_selection) * numdevs);
503 
504 		for (i = 0; i < numdevs; i++) {
505 			(*dev_select)[i].device_number =
506 				devices[i].device_number;
507 			strncpy((*dev_select)[i].device_name,
508 				devices[i].device_name,
509 				DEVSTAT_NAME_LEN);
510 			(*dev_select)[i].device_name[DEVSTAT_NAME_LEN - 1]='\0';
511 			(*dev_select)[i].unit_number = devices[i].unit_number;
512 			(*dev_select)[i].position = i;
513 		}
514 		*num_selections = numdevs;
515 	} else if (init_selected_var != 0) {
516 		for (i = 0; i < numdevs; i++)
517 			(*dev_select)[i].selected = 0;
518 	}
519 
520 	/* we haven't gotten around to selecting anything yet.. */
521 	if ((select_mode == DS_SELECT_ONLY) || (init_selections != 0)
522 	 || (init_selected_var != 0))
523 		*num_selected = 0;
524 
525 	/*
526 	 * Look through any devices the user specified on the command line
527 	 * and see if they match known devices.  If so, select them.
528 	 */
529 	for (i = 0; (i < *num_selections) && (num_dev_selections > 0); i++) {
530 		char tmpstr[80];
531 
532 		snprintf(tmpstr, sizeof(tmpstr), "%s%d",
533 			(*dev_select)[i].device_name,
534 			(*dev_select)[i].unit_number);
535 		for (j = 0; j < num_dev_selections; j++) {
536 			if (strcmp(tmpstr, dev_selections[j]) == 0) {
537 				/*
538 				 * Here we do different things based on the
539 				 * mode we're in.  If we're in add or
540 				 * addonly mode, we only select this device
541 				 * if it hasn't already been selected.
542 				 * Otherwise, we would be unnecessarily
543 				 * changing the selection order and
544 				 * incrementing the selection count.  If
545 				 * we're in only mode, we unconditionally
546 				 * select this device, since in only mode
547 				 * any previous selections are erased and
548 				 * manually specified devices are the first
549 				 * ones to be selected.  If we're in remove
550 				 * mode, we de-select the specified device and
551 				 * decrement the selection count.
552 				 */
553 				switch(select_mode) {
554 				case DS_SELECT_ADD:
555 				case DS_SELECT_ADDONLY:
556 					if ((*dev_select)[i].selected)
557 						break;
558 					/* FALLTHROUGH */
559 				case DS_SELECT_ONLY:
560 					(*dev_select)[i].selected =
561 						++selection_number;
562 					(*num_selected)++;
563 					break;
564 				case DS_SELECT_REMOVE:
565 					(*dev_select)[i].selected = 0;
566 					(*num_selected)--;
567 					/*
568 					 * This isn't passed back out, we
569 					 * just use it to keep track of
570 					 * how many devices we've removed.
571 					 */
572 					num_dev_selections--;
573 					break;
574 				}
575 				break;
576 			}
577 		}
578 	}
579 
580 	/*
581 	 * Go through the user's device type expressions and select devices
582 	 * accordingly.  We only do this if the number of devices already
583 	 * selected is less than the maximum number we can show.
584 	 */
585 	for (i = 0; (i < num_matches) && (*num_selected < maxshowdevs); i++) {
586 		/* We should probably indicate some error here */
587 		if ((matches[i].match_fields == DEVSTAT_MATCH_NONE)
588 		 || (matches[i].num_match_categories <= 0))
589 			continue;
590 
591 		for (j = 0; j < numdevs; j++) {
592 			int num_match_categories;
593 
594 			num_match_categories = matches[i].num_match_categories;
595 
596 			/*
597 			 * Determine whether or not the current device
598 			 * matches the given matching expression.  This if
599 			 * statement consists of three components:
600 			 *   - the device type check
601 			 *   - the device interface check
602 			 *   - the passthrough check
603 			 * If a the matching test is successful, it
604 			 * decrements the number of matching categories,
605 			 * and if we've reached the last element that
606 			 * needed to be matched, the if statement succeeds.
607 			 *
608 			 */
609 			if ((((matches[i].match_fields & DEVSTAT_MATCH_TYPE)!=0)
610 			  && ((devices[j].device_type & DEVSTAT_TYPE_MASK) ==
611 			        (matches[i].device_type & DEVSTAT_TYPE_MASK))
612 			  &&(((matches[i].match_fields & DEVSTAT_MATCH_PASS)!=0)
613 			   || (((matches[i].match_fields &
614 				DEVSTAT_MATCH_PASS) == 0)
615 			    && ((devices[j].device_type &
616 			        DEVSTAT_TYPE_PASS) == 0)))
617 			  && (--num_match_categories == 0))
618 			 || (((matches[i].match_fields & DEVSTAT_MATCH_IF) != 0)
619 			  && ((devices[j].device_type & DEVSTAT_TYPE_IF_MASK) ==
620 			        (matches[i].device_type & DEVSTAT_TYPE_IF_MASK))
621 			  &&(((matches[i].match_fields & DEVSTAT_MATCH_PASS)!=0)
622 			   || (((matches[i].match_fields &
623 				DEVSTAT_MATCH_PASS) == 0)
624 			    && ((devices[j].device_type &
625 				DEVSTAT_TYPE_PASS) == 0)))
626 			  && (--num_match_categories == 0))
627 			 || (((matches[i].match_fields & DEVSTAT_MATCH_PASS)!=0)
628 			  && ((devices[j].device_type & DEVSTAT_TYPE_PASS) != 0)
629 			  && (--num_match_categories == 0))) {
630 
631 				/*
632 				 * This is probably a non-optimal solution
633 				 * to the problem that the devices in the
634 				 * device list will not be in the same
635 				 * order as the devices in the selection
636 				 * array.
637 				 */
638 				for (k = 0; k < numdevs; k++) {
639 					if ((*dev_select)[k].position == j) {
640 						found = 1;
641 						break;
642 					}
643 				}
644 
645 				/*
646 				 * There shouldn't be a case where a device
647 				 * in the device list is not in the
648 				 * selection list...but it could happen.
649 				 */
650 				if (found != 1) {
651 					fprintf(stderr, "selectdevs: couldn't"
652 						" find %s%d in selection "
653 						"list\n",
654 						devices[j].device_name,
655 						devices[j].unit_number);
656 					break;
657 				}
658 
659 				/*
660 				 * We do different things based upon the
661 				 * mode we're in.  If we're in add or only
662 				 * mode, we go ahead and select this device
663 				 * if it hasn't already been selected.  If
664 				 * it has already been selected, we leave
665 				 * it alone so we don't mess up the
666 				 * selection ordering.  Manually specified
667 				 * devices have already been selected, and
668 				 * they have higher priority than pattern
669 				 * matched devices.  If we're in remove
670 				 * mode, we de-select the given device and
671 				 * decrement the selected count.
672 				 */
673 				switch(select_mode) {
674 				case DS_SELECT_ADD:
675 				case DS_SELECT_ADDONLY:
676 				case DS_SELECT_ONLY:
677 					if ((*dev_select)[k].selected != 0)
678 						break;
679 					(*dev_select)[k].selected =
680 						++selection_number;
681 					(*num_selected)++;
682 					break;
683 				case DS_SELECT_REMOVE:
684 					(*dev_select)[k].selected = 0;
685 					(*num_selected)--;
686 					break;
687 				}
688 			}
689 		}
690 	}
691 
692 	/*
693 	 * Here we implement "top" mode.  Devices are sorted in the
694 	 * selection array based on two criteria:  whether or not they are
695 	 * selected (not selection number, just the fact that they are
696 	 * selected!) and the number of bytes in the "bytes" field of the
697 	 * selection structure.  The bytes field generally must be kept up
698 	 * by the user.  In the future, it may be maintained by library
699 	 * functions, but for now the user has to do the work.
700 	 *
701 	 * At first glance, it may seem wrong that we don't go through and
702 	 * select every device in the case where the user hasn't specified
703 	 * any devices or patterns.  In fact, though, it won't make any
704 	 * difference in the device sorting.  In that particular case (i.e.
705 	 * when we're in "add" or "only" mode, and the user hasn't
706 	 * specified anything) the first time through no devices will be
707 	 * selected, so the only criterion used to sort them will be their
708 	 * performance.  The second time through, and every time thereafter,
709 	 * all devices will be selected, so again selection won't matter.
710 	 */
711 	if (perf_select != 0) {
712 
713 		/* Sort the device array by throughput  */
714 		qsort(*dev_select, *num_selections,
715 		      sizeof(struct device_selection),
716 		      compare_select);
717 
718 		if (*num_selected == 0) {
719 			/*
720 			 * Here we select every device in the array, if it
721 			 * isn't already selected.  Because the 'selected'
722 			 * variable in the selection array entries contains
723 			 * the selection order, the devstats routine can show
724 			 * the devices that were selected first.
725 			 */
726 			for (i = 0; i < *num_selections; i++) {
727 				if ((*dev_select)[i].selected == 0) {
728 					(*dev_select)[i].selected =
729 						++selection_number;
730 					(*num_selected)++;
731 				}
732 			}
733 		} else {
734 			selection_number = 0;
735 			for (i = 0; i < *num_selections; i++) {
736 				if ((*dev_select)[i].selected != 0) {
737 					(*dev_select)[i].selected =
738 						++selection_number;
739 				}
740 			}
741 		}
742 	}
743 
744 	/*
745 	 * If we're in the "add" selection mode and if we haven't already
746 	 * selected maxshowdevs number of devices, go through the array and
747 	 * select any unselected devices.  If we're in "only" mode, we
748 	 * obviously don't want to select anything other than what the user
749 	 * specifies.  If we're in "remove" mode, it probably isn't a good
750 	 * idea to go through and select any more devices, since we might
751 	 * end up selecting something that the user wants removed.  Through
752 	 * more complicated logic, we could actually figure this out, but
753 	 * that would probably require combining this loop with the various
754 	 * selections loops above.
755 	 */
756 	if ((select_mode == DS_SELECT_ADD) && (*num_selected < maxshowdevs)) {
757 		for (i = 0; i < *num_selections; i++)
758 			if ((*dev_select)[i].selected == 0) {
759 				(*dev_select)[i].selected = ++selection_number;
760 				(*num_selected)++;
761 			}
762 	}
763 
764 	/*
765 	 * Look at the number of devices that have been selected.  If it
766 	 * has changed, set the changed variable.  Otherwise, if we've
767 	 * made a backup of the selection list, compare it to the current
768 	 * selection list to see if the selected devices have changed.
769 	 */
770 	if ((changed == 0) && (old_num_selected != *num_selected))
771 		changed = 1;
772 	else if ((changed == 0) && (old_dev_select != NULL)) {
773 		/*
774 		 * Now we go through the selection list and we look at
775 		 * it three different ways.
776 		 */
777 		for (i = 0; (i < *num_selections) && (changed == 0) &&
778 		     (i < old_num_selections); i++) {
779 			/*
780 			 * If the device at index i in both the new and old
781 			 * selection arrays has the same device number and
782 			 * selection status, it hasn't changed.  We
783 			 * continue on to the next index.
784 			 */
785 			if (((*dev_select)[i].device_number ==
786 			     old_dev_select[i].device_number)
787 			 && ((*dev_select)[i].selected ==
788 			     old_dev_select[i].selected))
789 				continue;
790 
791 			/*
792 			 * Now, if we're still going through the if
793 			 * statement, the above test wasn't true.  So we
794 			 * check here to see if the device at index i in
795 			 * the current array is the same as the device at
796 			 * index i in the old array.  If it is, that means
797 			 * that its selection number has changed.  Set
798 			 * changed to 1 and exit the loop.
799 			 */
800 			else if ((*dev_select)[i].device_number ==
801 			          old_dev_select[i].device_number) {
802 				changed = 1;
803 				break;
804 			}
805 			/*
806 			 * If we get here, then the device at index i in
807 			 * the current array isn't the same device as the
808 			 * device at index i in the old array.
809 			 */
810 			else {
811 				int found = 0;
812 
813 				/*
814 				 * Search through the old selection array
815 				 * looking for a device with the same
816 				 * device number as the device at index i
817 				 * in the current array.  If the selection
818 				 * status is the same, then we mark it as
819 				 * found.  If the selection status isn't
820 				 * the same, we break out of the loop.
821 				 * Since found isn't set, changed will be
822 				 * set to 1 below.
823 				 */
824 				for (j = 0; j < old_num_selections; j++) {
825 					if (((*dev_select)[i].device_number ==
826 					      old_dev_select[j].device_number)
827 					 && ((*dev_select)[i].selected ==
828 					      old_dev_select[j].selected)){
829 						found = 1;
830 						break;
831 					}
832 					else if ((*dev_select)[i].device_number
833 					    == old_dev_select[j].device_number)
834 						break;
835 				}
836 				if (found == 0)
837 					changed = 1;
838 			}
839 		}
840 	}
841 	if (old_dev_select != NULL)
842 		free(old_dev_select);
843 
844 	return(changed);
845 }
846 
847 /*
848  * Comparison routine for qsort() above.  Note that the comparison here is
849  * backwards -- generally, it should return a value to indicate whether
850  * arg1 is <, =, or > arg2.  Instead, it returns the opposite.  The reason
851  * it returns the opposite is so that the selection array will be sorted in
852  * order of decreasing performance.  We sort on two parameters.  The first
853  * sort key is whether or not one or the other of the devices in question
854  * has been selected.  If one of them has, and the other one has not, the
855  * selected device is automatically more important than the unselected
856  * device.  If neither device is selected, we judge the devices based upon
857  * performance.
858  */
859 static int
860 compare_select(const void *arg1, const void *arg2)
861 {
862 	if ((((struct device_selection *)arg1)->selected)
863 	 && (((struct device_selection *)arg2)->selected == 0))
864 		return(-1);
865 	else if ((((struct device_selection *)arg1)->selected == 0)
866 	      && (((struct device_selection *)arg2)->selected))
867 		return(1);
868 	else if (((struct device_selection *)arg2)->bytes <
869 	         ((struct device_selection *)arg1)->bytes)
870 		return(-1);
871 	else if (((struct device_selection *)arg2)->bytes >
872 		 ((struct device_selection *)arg1)->bytes)
873 		return(1);
874 	else
875 		return(0);
876 }
877 
878 /*
879  * Take a string with the general format "arg1,arg2,arg3", and build a
880  * device matching expression from it.
881  */
882 int
883 buildmatch(char *match_str, struct devstat_match **matches, int *num_matches)
884 {
885 	char *tstr[5];
886 	char **tempstr;
887 	int num_args;
888 	int i, j;
889 	char *func_name = "buildmatch";
890 
891 	/* We can't do much without a string to parse */
892 	if (match_str == NULL) {
893 		sprintf(devstat_errbuf, "%s: no match expression", func_name);
894 		return(-1);
895 	}
896 
897 	/*
898 	 * Break the (comma delimited) input string out into separate strings.
899 	 */
900 	for (tempstr = tstr, num_args  = 0;
901 	     (*tempstr = strsep(&match_str, ",")) != NULL && (num_args < 5);
902 	     num_args++)
903 		if (**tempstr != '\0')
904 			if (++tempstr >= &tstr[5])
905 				break;
906 
907 	/* The user gave us too many type arguments */
908 	if (num_args > 3) {
909 		sprintf(devstat_errbuf, "%s: too many type arguments",
910 			func_name);
911 		return(-1);
912 	}
913 
914 	/*
915 	 * Since you can't realloc a pointer that hasn't been malloced
916 	 * first, we malloc first and then realloc.
917 	 */
918 	if (*num_matches == 0)
919 		*matches = (struct devstat_match *)malloc(
920 			   sizeof(struct devstat_match));
921 	else
922 		*matches = (struct devstat_match *)realloc(*matches,
923 			  sizeof(struct devstat_match) * (*num_matches + 1));
924 
925 	/* Make sure the current entry is clear */
926 	bzero(&matches[0][*num_matches], sizeof(struct devstat_match));
927 
928 	/*
929 	 * Step through the arguments the user gave us and build a device
930 	 * matching expression from them.
931 	 */
932 	for (i = 0; i < num_args; i++) {
933 		char *tempstr2, *tempstr3;
934 
935 		/*
936 		 * Get rid of leading white space.
937 		 */
938 		tempstr2 = tstr[i];
939 		while (isspace(*tempstr2) && (*tempstr2 != '\0'))
940 			tempstr2++;
941 
942 		/*
943 		 * Get rid of trailing white space.
944 		 */
945 		tempstr3 = &tempstr2[strlen(tempstr2) - 1];
946 
947 		while ((*tempstr3 != '\0') && (tempstr3 > tempstr2)
948 		    && (isspace(*tempstr3))) {
949 			*tempstr3 = '\0';
950 			tempstr3--;
951 		}
952 
953 		/*
954 		 * Go through the match table comparing the user's
955 		 * arguments to known device types, interfaces, etc.
956 		 */
957 		for (j = 0; match_table[j].match_str != NULL; j++) {
958 			/*
959 			 * We do case-insensitive matching, in case someone
960 			 * wants to enter "SCSI" instead of "scsi" or
961 			 * something like that.  Only compare as many
962 			 * characters as are in the string in the match
963 			 * table.  This should help if someone tries to use
964 			 * a super-long match expression.
965 			 */
966 			if (strncasecmp(tempstr2, match_table[j].match_str,
967 			    strlen(match_table[j].match_str)) == 0) {
968 				/*
969 				 * Make sure the user hasn't specified two
970 				 * items of the same type, like "da" and
971 				 * "cd".  One device cannot be both.
972 				 */
973 				if (((*matches)[*num_matches].match_fields &
974 				    match_table[j].match_field) != 0) {
975 					sprintf(devstat_errbuf,
976 						"%s: cannot have more than "
977 						"one match item in a single "
978 						"category", func_name);
979 					return(-1);
980 				}
981 				/*
982 				 * If we've gotten this far, we have a
983 				 * winner.  Set the appropriate fields in
984 				 * the match entry.
985 				 */
986 				(*matches)[*num_matches].match_fields |=
987 					match_table[j].match_field;
988 				(*matches)[*num_matches].device_type |=
989 					match_table[j].type;
990 				(*matches)[*num_matches].num_match_categories++;
991 				break;
992 			}
993 		}
994 		/*
995 		 * We should have found a match in the above for loop.  If
996 		 * not, that means the user entered an invalid device type
997 		 * or interface.
998 		 */
999 		if ((*matches)[*num_matches].num_match_categories != (i + 1)) {
1000 			snprintf(devstat_errbuf, sizeof(devstat_errbuf),
1001 				"%s: unknown match item \"%s\"", func_name,
1002 				tstr[i]);
1003 			return(-1);
1004 		}
1005 	}
1006 
1007 	(*num_matches)++;
1008 
1009 	return(0);
1010 }
1011 
1012 /*
1013  * Compute a number of device statistics.  Only one field is mandatory, and
1014  * that is "current".  Everything else is optional.  The caller passes in
1015  * pointers to variables to hold the various statistics he desires.  If he
1016  * doesn't want a particular staistic, he should pass in a NULL pointer.
1017  * Return values:
1018  * 0   -- success
1019  * -1  -- failure
1020  */
1021 int
1022 compute_stats(struct devstat *current, struct devstat *previous,
1023 	      long double etime, u_int64_t *total_bytes,
1024 	      u_int64_t *total_transfers, u_int64_t *total_blocks,
1025 	      long double *kb_per_transfer, long double *transfers_per_second,
1026 	      long double *mb_per_second, long double *blocks_per_second,
1027 	      long double *ms_per_transaction)
1028 {
1029 	u_int64_t totalbytes, totaltransfers, totalblocks;
1030 	char *func_name = "compute_stats";
1031 
1032 	/*
1033 	 * current is the only mandatory field.
1034 	 */
1035 	if (current == NULL) {
1036 		sprintf(devstat_errbuf, "%s: current stats structure was NULL",
1037 			func_name);
1038 		return(-1);
1039 	}
1040 
1041 	totalbytes = (current->bytes_written + current->bytes_read) -
1042 		     ((previous) ? (previous->bytes_written +
1043 				    previous->bytes_read) : 0);
1044 
1045 	if (total_bytes)
1046 		*total_bytes = totalbytes;
1047 
1048 	totaltransfers = (current->num_reads +
1049 			  current->num_writes +
1050 			  current->num_other) -
1051 			 ((previous) ?
1052 			  (previous->num_reads +
1053 			   previous->num_writes +
1054 			   previous->num_other) : 0);
1055 	if (total_transfers)
1056 		*total_transfers = totaltransfers;
1057 
1058 	if (transfers_per_second) {
1059 		if (etime > 0.0) {
1060 			*transfers_per_second = totaltransfers;
1061 			*transfers_per_second /= etime;
1062 		} else
1063 			*transfers_per_second = 0.0;
1064 	}
1065 
1066 	if (kb_per_transfer) {
1067 		*kb_per_transfer = totalbytes;
1068 		*kb_per_transfer /= 1024;
1069 		if (totaltransfers > 0)
1070 			*kb_per_transfer /= totaltransfers;
1071 		else
1072 			*kb_per_transfer = 0.0;
1073 	}
1074 
1075 	if (mb_per_second) {
1076 		*mb_per_second = totalbytes;
1077 		*mb_per_second /= 1024 * 1024;
1078 		if (etime > 0.0)
1079 			*mb_per_second /= etime;
1080 		else
1081 			*mb_per_second = 0.0;
1082 	}
1083 
1084 	totalblocks = totalbytes;
1085 	if (current->block_size > 0)
1086 		totalblocks /= current->block_size;
1087 	else
1088 		totalblocks /= 512;
1089 
1090 	if (total_blocks)
1091 		*total_blocks = totalblocks;
1092 
1093 	if (blocks_per_second) {
1094 		*blocks_per_second = totalblocks;
1095 		if (etime > 0.0)
1096 			*blocks_per_second /= etime;
1097 		else
1098 			*blocks_per_second = 0.0;
1099 	}
1100 
1101 	if (ms_per_transaction) {
1102 		if (totaltransfers > 0) {
1103 			*ms_per_transaction = etime;
1104 			*ms_per_transaction /= totaltransfers;
1105 			*ms_per_transaction *= 1000;
1106 		} else
1107 			*ms_per_transaction = 0.0;
1108 	}
1109 
1110 	return(0);
1111 }
1112 
1113 long double
1114 compute_etime(struct timeval cur_time, struct timeval prev_time)
1115 {
1116 	struct timeval busy_time;
1117 	u_int64_t busy_usec;
1118 	long double etime;
1119 
1120 	timersub(&cur_time, &prev_time, &busy_time);
1121 
1122         busy_usec = busy_time.tv_sec;
1123         busy_usec *= 1000000;
1124         busy_usec += busy_time.tv_usec;
1125         etime = busy_usec;
1126         etime /= 1000000;
1127 
1128 	return(etime);
1129 }
1130