xref: /freebsd/usr.sbin/iostat/iostat.c (revision 63d1fd5970ec814904aa0f4580b10a0d302d08b2)
1 /*
2  * Copyright (c) 1997, 1998, 2000, 2001  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$
29  */
30 /*
31  * Parts of this program are derived from the original FreeBSD iostat
32  * program:
33  */
34 /*-
35  * Copyright (c) 1986, 1991, 1993
36  *	The Regents of the University of California.  All rights reserved.
37  *
38  * Redistribution and use in source and binary forms, with or without
39  * modification, are permitted provided that the following conditions
40  * are met:
41  * 1. Redistributions of source code must retain the above copyright
42  *    notice, this list of conditions and the following disclaimer.
43  * 2. Redistributions in binary form must reproduce the above copyright
44  *    notice, this list of conditions and the following disclaimer in the
45  *    documentation and/or other materials provided with the distribution.
46  * 4. Neither the name of the University nor the names of its contributors
47  *    may be used to endorse or promote products derived from this software
48  *    without specific prior written permission.
49  *
50  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
51  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
52  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
53  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
54  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
55  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
56  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
57  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
58  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
59  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
60  * SUCH DAMAGE.
61  */
62 /*
63  * Ideas for the new iostat statistics output modes taken from the NetBSD
64  * version of iostat:
65  */
66 /*
67  * Copyright (c) 1996 John M. Vinopal
68  * All rights reserved.
69  *
70  * Redistribution and use in source and binary forms, with or without
71  * modification, are permitted provided that the following conditions
72  * are met:
73  * 1. Redistributions of source code must retain the above copyright
74  *    notice, this list of conditions and the following disclaimer.
75  * 2. Redistributions in binary form must reproduce the above copyright
76  *    notice, this list of conditions and the following disclaimer in the
77  *    documentation and/or other materials provided with the distribution.
78  * 3. All advertising materials mentioning features or use of this software
79  *    must display the following acknowledgement:
80  *      This product includes software developed for the NetBSD Project
81  *      by John M. Vinopal.
82  * 4. The name of the author may not be used to endorse or promote products
83  *    derived from this software without specific prior written permission.
84  *
85  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
86  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
87  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
88  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
89  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
90  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
91  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
92  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
93  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
94  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
95  * SUCH DAMAGE.
96  */
97 
98 
99 #include <sys/param.h>
100 #include <sys/errno.h>
101 #include <sys/resource.h>
102 #include <sys/sysctl.h>
103 
104 #include <ctype.h>
105 #include <devstat.h>
106 #include <err.h>
107 #include <fcntl.h>
108 #include <inttypes.h>
109 #include <kvm.h>
110 #include <limits.h>
111 #include <math.h>
112 #include <nlist.h>
113 #include <signal.h>
114 #include <stdio.h>
115 #include <stdlib.h>
116 #include <string.h>
117 #include <termios.h>
118 #include <unistd.h>
119 
120 static struct nlist namelist[] = {
121 #define X_TTY_NIN	0
122 	{ .n_name = "_tty_nin",
123 	  .n_type = 0, .n_other = 0, .n_desc = 0, .n_value = 0 },
124 #define X_TTY_NOUT	1
125 	{ .n_name = "_tty_nout",
126 	  .n_type = 0, .n_other = 0, .n_desc = 0, .n_value = 0 },
127 #define X_BOOTTIME	2
128 	{ .n_name = "_boottime",
129 	  .n_type = 0, .n_other = 0, .n_desc = 0, .n_value = 0 },
130 #define X_END		2
131 	{ .n_name = NULL,
132 	  .n_type = 0, .n_other = 0, .n_desc = 0, .n_value = 0 },
133 };
134 
135 #define	IOSTAT_DEFAULT_ROWS	20	/* Traditional default `wrows' */
136 
137 static struct statinfo cur, last;
138 static int num_devices;
139 static struct device_selection *dev_select;
140 static int maxshowdevs;
141 static volatile sig_atomic_t headercount;
142 static volatile sig_atomic_t wresized;	/* Tty resized, when non-zero. */
143 static volatile sig_atomic_t alarm_rang;
144 static volatile sig_atomic_t return_requested;
145 static unsigned short wrows;		/* Current number of tty rows. */
146 static int dflag = 0, Iflag = 0, Cflag = 0, Tflag = 0, oflag = 0, Kflag = 0;
147 static int xflag = 0, zflag = 0;
148 
149 /* local function declarations */
150 static void usage(void);
151 static void needhdr(int signo);
152 static void needresize(int signo);
153 static void needreturn(int signo);
154 static void alarm_clock(int signo);
155 static void doresize(void);
156 static void phdr(void);
157 static void devstats(int perf_select, long double etime, int havelast);
158 static void cpustats(void);
159 static int readvar(kvm_t *kd, const char *name, int nlid, void *ptr,
160 		   size_t len);
161 
162 static void
163 usage(void)
164 {
165 	/*
166 	 * We also support the following 'traditional' syntax:
167 	 * iostat [drives] [wait [count]]
168 	 * This isn't mentioned in the man page, or the usage statement,
169 	 * but it is supported.
170 	 */
171 	fprintf(stderr, "usage: iostat [-CdhIKoTxz?] [-c count] [-M core]"
172 		" [-n devs] [-N system]\n"
173 		"\t      [-t type,if,pass] [-w wait] [drives]\n");
174 }
175 
176 int
177 main(int argc, char **argv)
178 {
179 	int c, i;
180 	int tflag = 0, hflag = 0, cflag = 0, wflag = 0, nflag = 0;
181 	int count = 0, waittime = 0;
182 	char *memf = NULL, *nlistf = NULL;
183 	struct devstat_match *matches;
184 	struct itimerval alarmspec;
185 	int num_matches = 0;
186 	char errbuf[_POSIX2_LINE_MAX];
187 	kvm_t *kd = NULL;
188 	long generation;
189 	int num_devices_specified;
190 	int num_selected, num_selections;
191 	long select_generation;
192 	char **specified_devices;
193 	devstat_select_mode select_mode;
194 	float f;
195 	int havelast = 0;
196 
197 	matches = NULL;
198 	maxshowdevs = 3;
199 
200 	while ((c = getopt(argc, argv, "c:CdhIKM:n:N:ot:Tw:xz?")) != -1) {
201 		switch(c) {
202 			case 'c':
203 				cflag++;
204 				count = atoi(optarg);
205 				if (count < 1)
206 					errx(1, "count %d is < 1", count);
207 				break;
208 			case 'C':
209 				Cflag++;
210 				break;
211 			case 'd':
212 				dflag++;
213 				break;
214 			case 'h':
215 				hflag++;
216 				break;
217 			case 'I':
218 				Iflag++;
219 				break;
220 			case 'K':
221 				Kflag++;
222 				break;
223 			case 'M':
224 				memf = optarg;
225 				break;
226 			case 'n':
227 				nflag++;
228 				maxshowdevs = atoi(optarg);
229 				if (maxshowdevs < 0)
230 					errx(1, "number of devices %d is < 0",
231 					     maxshowdevs);
232 				break;
233 			case 'N':
234 				nlistf = optarg;
235 				break;
236 			case 'o':
237 				oflag++;
238 				break;
239 			case 't':
240 				tflag++;
241 				if (devstat_buildmatch(optarg, &matches,
242 						       &num_matches) != 0)
243 					errx(1, "%s", devstat_errbuf);
244 				break;
245 			case 'T':
246 				Tflag++;
247 				break;
248 			case 'w':
249 				wflag++;
250 				f = atof(optarg);
251 				waittime = f * 1000;
252 				if (waittime < 1)
253 					errx(1, "wait time is < 1ms");
254 				break;
255 			case 'x':
256 				xflag++;
257 				break;
258 			case 'z':
259 				zflag++;
260 				break;
261 			default:
262 				usage();
263 				exit(1);
264 				break;
265 		}
266 	}
267 
268 	argc -= optind;
269 	argv += optind;
270 
271 	if (nlistf != NULL || memf != NULL) {
272 		kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf);
273 
274 		if (kd == NULL)
275 			errx(1, "kvm_openfiles: %s", errbuf);
276 
277 		if (kvm_nlist(kd, namelist) == -1)
278 			errx(1, "kvm_nlist: %s", kvm_geterr(kd));
279 	}
280 
281 	/*
282 	 * Make sure that the userland devstat version matches the kernel
283 	 * devstat version.  If not, exit and print a message informing
284 	 * the user of his mistake.
285 	 */
286 	if (devstat_checkversion(kd) < 0)
287 		errx(1, "%s", devstat_errbuf);
288 
289 	/*
290 	 * Make sure Tflag and/or Cflag are set if dflag == 0.  If dflag is
291 	 * greater than 0, they may be 0 or non-zero.
292 	 */
293 	if (dflag == 0 && xflag == 0) {
294 		Cflag = 1;
295 		Tflag = 1;
296 	}
297 
298 	/* find out how many devices we have */
299 	if ((num_devices = devstat_getnumdevs(kd)) < 0)
300 		err(1, "can't get number of devices");
301 
302 	/*
303 	 * Figure out how many devices we should display.
304 	 */
305 	if (nflag == 0) {
306 		if (xflag > 0)
307 			maxshowdevs = num_devices;
308 		else if (oflag > 0) {
309 			if ((dflag > 0) && (Cflag == 0) && (Tflag == 0))
310 				maxshowdevs = 5;
311 			else if ((dflag > 0) && (Tflag > 0) && (Cflag == 0))
312 				maxshowdevs = 5;
313 			else
314 				maxshowdevs = 4;
315 		} else {
316 			if ((dflag > 0) && (Cflag == 0))
317 				maxshowdevs = 4;
318 			else
319 				maxshowdevs = 3;
320 		}
321 	}
322 
323 	cur.dinfo = (struct devinfo *)calloc(1, sizeof(struct devinfo));
324 	if (cur.dinfo == NULL)
325 		err(1, "calloc failed");
326 
327 	last.dinfo = (struct devinfo *)calloc(1, sizeof(struct devinfo));
328 	if (last.dinfo == NULL)
329 		err(1, "calloc failed");
330 
331 	/*
332 	 * Grab all the devices.  We don't look to see if the list has
333 	 * changed here, since it almost certainly has.  We only look for
334 	 * errors.
335 	 */
336 	if (devstat_getdevs(kd, &cur) == -1)
337 		errx(1, "%s", devstat_errbuf);
338 
339 	num_devices = cur.dinfo->numdevs;
340 	generation = cur.dinfo->generation;
341 
342 	/*
343 	 * If the user specified any devices on the command line, see if
344 	 * they are in the list of devices we have now.
345 	 */
346 	specified_devices = (char **)malloc(sizeof(char *));
347 	if (specified_devices == NULL)
348 		err(1, "malloc failed");
349 
350 	for (num_devices_specified = 0; *argv; ++argv) {
351 		if (isdigit(**argv))
352 			break;
353 		num_devices_specified++;
354 		specified_devices = (char **)realloc(specified_devices,
355 						     sizeof(char *) *
356 						     num_devices_specified);
357 		if (specified_devices == NULL)
358 			err(1, "realloc failed");
359 
360 		specified_devices[num_devices_specified - 1] = *argv;
361 
362 	}
363 	if (nflag == 0 && maxshowdevs < num_devices_specified)
364 		maxshowdevs = num_devices_specified;
365 
366 	dev_select = NULL;
367 
368 	if ((num_devices_specified == 0) && (num_matches == 0))
369 		select_mode = DS_SELECT_ADD;
370 	else
371 		select_mode = DS_SELECT_ONLY;
372 
373 	/*
374 	 * At this point, selectdevs will almost surely indicate that the
375 	 * device list has changed, so we don't look for return values of 0
376 	 * or 1.  If we get back -1, though, there is an error.
377 	 */
378 	if (devstat_selectdevs(&dev_select, &num_selected,
379 			       &num_selections, &select_generation, generation,
380 			       cur.dinfo->devices, num_devices, matches,
381 			       num_matches, specified_devices,
382 			       num_devices_specified, select_mode, maxshowdevs,
383 			       hflag) == -1)
384 		errx(1, "%s", devstat_errbuf);
385 
386 	/*
387 	 * Look for the traditional wait time and count arguments.
388 	 */
389 	if (*argv) {
390 		f = atof(*argv);
391 		waittime = f * 1000;
392 
393 		/* Let the user know he goofed, but keep going anyway */
394 		if (wflag != 0)
395 			warnx("discarding previous wait interval, using"
396 			      " %g instead", waittime / 1000.0);
397 		wflag++;
398 
399 		if (*++argv) {
400 			count = atoi(*argv);
401 			if (cflag != 0)
402 				warnx("discarding previous count, using %d"
403 				      " instead", count);
404 			cflag++;
405 		} else
406 			count = -1;
407 	}
408 
409 	/*
410 	 * If the user specified a count, but not an interval, we default
411 	 * to an interval of 1 second.
412 	 */
413 	if ((wflag == 0) && (cflag > 0))
414 		waittime = 1 * 1000;
415 
416 	/*
417 	 * If the user specified a wait time, but not a count, we want to
418 	 * go on ad infinitum.  This can be redundant if the user uses the
419 	 * traditional method of specifying the wait, since in that case we
420 	 * already set count = -1 above.  Oh well.
421 	 */
422 	if ((wflag > 0) && (cflag == 0))
423 		count = -1;
424 
425 	bzero(cur.cp_time, sizeof(cur.cp_time));
426 	cur.tk_nout = 0;
427 	cur.tk_nin = 0;
428 
429 	/*
430 	 * Set the snap time to the system boot time (ie: zero), so the
431 	 * stats are calculated since system boot.
432 	 */
433 	cur.snap_time = 0;
434 
435 	/*
436 	 * If the user stops the program (control-Z) and then resumes it,
437 	 * print out the header again.
438 	 */
439 	(void)signal(SIGCONT, needhdr);
440 
441 	/*
442 	 * If our standard output is a tty, then install a SIGWINCH handler
443 	 * and set wresized so that our first iteration through the main
444 	 * iostat loop will peek at the terminal's current rows to find out
445 	 * how many lines can fit in a screenful of output.
446 	 */
447 	if (isatty(fileno(stdout)) != 0) {
448 		wresized = 1;
449 		(void)signal(SIGWINCH, needresize);
450 	} else {
451 		wresized = 0;
452 		wrows = IOSTAT_DEFAULT_ROWS;
453 	}
454 
455 	/*
456 	 * Register a SIGINT handler so that we can print out final statistics
457 	 * when we get that signal
458 	 */
459 	(void)signal(SIGINT, needreturn);
460 
461 	/*
462 	 * Register a SIGALRM handler to implement sleeps if the user uses the
463 	 * -c or -w options
464 	 */
465 	(void)signal(SIGALRM, alarm_clock);
466 	alarmspec.it_interval.tv_sec = waittime / 1000;
467 	alarmspec.it_interval.tv_usec = 1000 * (waittime % 1000);
468 	alarmspec.it_value.tv_sec = waittime / 1000;
469 	alarmspec.it_value.tv_usec = 1000 * (waittime % 1000);
470 	setitimer(ITIMER_REAL, &alarmspec, NULL);
471 
472 	for (headercount = 1;;) {
473 		struct devinfo *tmp_dinfo;
474 		long tmp;
475 		long double etime;
476 		sigset_t sigmask, oldsigmask;
477 
478 		if (Tflag > 0) {
479 			if ((readvar(kd, "kern.tty_nin", X_TTY_NIN, &cur.tk_nin,
480 			     sizeof(cur.tk_nin)) != 0)
481 			 || (readvar(kd, "kern.tty_nout", X_TTY_NOUT,
482 			     &cur.tk_nout, sizeof(cur.tk_nout))!= 0)) {
483 				Tflag = 0;
484 				warnx("disabling TTY statistics");
485 			}
486 		 }
487 
488 		if (Cflag > 0) {
489 			if (kd == NULL) {
490 				if (readvar(kd, "kern.cp_time", 0,
491 				    &cur.cp_time, sizeof(cur.cp_time)) != 0)
492 					Cflag = 0;
493 			} else {
494 				if (kvm_getcptime(kd, cur.cp_time) < 0) {
495 					warnx("kvm_getcptime: %s",
496 					    kvm_geterr(kd));
497 					Cflag = 0;
498 				}
499 			}
500 			if (Cflag == 0)
501 				warnx("disabling CPU time statistics");
502 		}
503 
504 		if (!--headercount) {
505 			phdr();
506 			if (wresized != 0)
507 				doresize();
508 			headercount = wrows;
509 		}
510 
511 		tmp_dinfo = last.dinfo;
512 		last.dinfo = cur.dinfo;
513 		cur.dinfo = tmp_dinfo;
514 
515 		last.snap_time = cur.snap_time;
516 
517 		/*
518 		 * Here what we want to do is refresh our device stats.
519 		 * devstat_getdevs() returns 1 when the device list has changed.
520 		 * If the device list has changed, we want to go through
521 		 * the selection process again, in case a device that we
522 		 * were previously displaying has gone away.
523 		 */
524 		switch (devstat_getdevs(kd, &cur)) {
525 		case -1:
526 			errx(1, "%s", devstat_errbuf);
527 			break;
528 		case 1: {
529 			int retval;
530 
531 			num_devices = cur.dinfo->numdevs;
532 			generation = cur.dinfo->generation;
533 			retval = devstat_selectdevs(&dev_select, &num_selected,
534 						    &num_selections,
535 						    &select_generation,
536 						    generation,
537 						    cur.dinfo->devices,
538 						    num_devices, matches,
539 						    num_matches,
540 						    specified_devices,
541 						    num_devices_specified,
542 						    select_mode, maxshowdevs,
543 						    hflag);
544 			switch(retval) {
545 			case -1:
546 				errx(1, "%s", devstat_errbuf);
547 				break;
548 			case 1:
549 				phdr();
550 				if (wresized != 0)
551 					doresize();
552 				headercount = wrows;
553 				break;
554 			default:
555 				break;
556 			}
557 			break;
558 		}
559 		default:
560 			break;
561 		}
562 
563 		/*
564 		 * We only want to re-select devices if we're in 'top'
565 		 * mode.  This is the only mode where the devices selected
566 		 * could actually change.
567 		 */
568 		if (hflag > 0) {
569 			int retval;
570 			retval = devstat_selectdevs(&dev_select, &num_selected,
571 						    &num_selections,
572 						    &select_generation,
573 						    generation,
574 						    cur.dinfo->devices,
575 						    num_devices, matches,
576 						    num_matches,
577 						    specified_devices,
578 						    num_devices_specified,
579 						    select_mode, maxshowdevs,
580 						    hflag);
581 			switch(retval) {
582 			case -1:
583 				errx(1,"%s", devstat_errbuf);
584 				break;
585 			case 1:
586 				phdr();
587 				if (wresized != 0)
588 					doresize();
589 				headercount = wrows;
590 				break;
591 			default:
592 				break;
593 			}
594 		}
595 
596 		if (Tflag > 0) {
597 			tmp = cur.tk_nin;
598 			cur.tk_nin -= last.tk_nin;
599 			last.tk_nin = tmp;
600 			tmp = cur.tk_nout;
601 			cur.tk_nout -= last.tk_nout;
602 			last.tk_nout = tmp;
603 		}
604 
605 		etime = cur.snap_time - last.snap_time;
606 
607 		if (etime == 0.0)
608 			etime = 1.0;
609 
610 		for (i = 0; i < CPUSTATES; i++) {
611 			tmp = cur.cp_time[i];
612 			cur.cp_time[i] -= last.cp_time[i];
613 			last.cp_time[i] = tmp;
614 		}
615 
616 		if (xflag == 0 && Tflag > 0)
617 			printf("%4.0Lf %5.0Lf", cur.tk_nin / etime,
618 			    cur.tk_nout / etime);
619 
620 		devstats(hflag, etime, havelast);
621 
622 		if (xflag == 0) {
623 			if (Cflag > 0)
624 				cpustats();
625 
626 			printf("\n");
627 		}
628 		fflush(stdout);
629 
630 		if ((count >= 0 && --count <= 0) || return_requested)
631 			break;
632 
633 		/*
634 		 * Use sigsuspend to safely sleep until either signal is
635 		 * received
636 		 */
637 		alarm_rang = 0;
638 		sigemptyset(&sigmask);
639 		sigaddset(&sigmask, SIGINT);
640 		sigaddset(&sigmask, SIGALRM);
641 		sigprocmask(SIG_BLOCK, &sigmask, &oldsigmask);
642 		while (! (alarm_rang || return_requested) ) {
643 			sigsuspend(&oldsigmask);
644 		}
645 		sigprocmask(SIG_UNBLOCK, &sigmask, NULL);
646 
647 		havelast = 1;
648 	}
649 
650 	exit(0);
651 }
652 
653 /*
654  * Force a header to be prepended to the next output.
655  */
656 void
657 needhdr(int signo __unused)
658 {
659 
660 	headercount = 1;
661 }
662 
663 /*
664  * When the terminal is resized, force an update of the maximum number of rows
665  * printed between each header repetition.  Then force a new header to be
666  * prepended to the next output.
667  */
668 void
669 needresize(int signo __unused)
670 {
671 
672 	wresized = 1;
673 	headercount = 1;
674 }
675 
676 /*
677  * Record the alarm so the main loop can break its sleep
678  */
679 void
680 alarm_clock(int signo __unused)
681 {
682 	alarm_rang = 1;
683 }
684 
685 /*
686  * Request that the main loop exit soon
687  */
688 void
689 needreturn(int signo __unused)
690 {
691 	return_requested = 1;
692 }
693 
694 /*
695  * Update the global `wrows' count of terminal rows.
696  */
697 void
698 doresize(void)
699 {
700 	int status;
701 	struct winsize w;
702 
703 	for (;;) {
704 		status = ioctl(fileno(stdout), TIOCGWINSZ, &w);
705 		if (status == -1 && errno == EINTR)
706 			continue;
707 		else if (status == -1)
708 			err(1, "ioctl");
709 		if (w.ws_row > 3)
710 			wrows = w.ws_row - 3;
711 		else
712 			wrows = IOSTAT_DEFAULT_ROWS;
713 		break;
714 	}
715 
716 	/*
717 	 * Inhibit doresize() calls until we are rescheduled by SIGWINCH.
718 	 */
719 	wresized = 0;
720 }
721 
722 static void
723 phdr(void)
724 {
725 	int i, printed;
726 	char devbuf[256];
727 
728 	/*
729 	 * If xflag is set, we need a per-loop header, not a page header, so
730 	 * just return.  We'll print the header in devstats().
731 	 */
732 	if (xflag > 0)
733 		return;
734 
735 	if (Tflag > 0)
736 		(void)printf("       tty");
737 	for (i = 0, printed=0;(i < num_devices) && (printed < maxshowdevs);i++){
738 		int di;
739 		if ((dev_select[i].selected != 0)
740 		 && (dev_select[i].selected <= maxshowdevs)) {
741 			di = dev_select[i].position;
742 			snprintf(devbuf, sizeof(devbuf), "%s%d",
743 					    cur.dinfo->devices[di].device_name,
744 					    cur.dinfo->devices[di].unit_number);
745 			if (oflag > 0)
746 				(void)printf("%13.6s ", devbuf);
747 			else
748 				printf("%16.6s ", devbuf);
749 			printed++;
750 		}
751 	}
752 	if (Cflag > 0)
753 		(void)printf("            cpu\n");
754 	else
755 		(void)printf("\n");
756 
757 	if (Tflag > 0)
758 		(void)printf(" tin  tout");
759 
760 	for (i=0, printed = 0;(i < num_devices) && (printed < maxshowdevs);i++){
761 		if ((dev_select[i].selected != 0)
762 		 && (dev_select[i].selected <= maxshowdevs)) {
763 			if (oflag > 0) {
764 				if (Iflag == 0)
765 					(void)printf(" sps tps msps ");
766 				else
767 					(void)printf(" blk xfr msps ");
768 			} else {
769 				if (Iflag == 0)
770 					printf("  KB/t tps  MB/s ");
771 				else
772 					printf("  KB/t xfrs   MB ");
773 			}
774 			printed++;
775 		}
776 	}
777 	if (Cflag > 0)
778 		(void)printf(" us ni sy in id\n");
779 	else
780 		printf("\n");
781 
782 }
783 
784 static void
785 devstats(int perf_select, long double etime, int havelast)
786 {
787 	int dn;
788 	long double transfers_per_second, transfers_per_second_read;
789 	long double transfers_per_second_write;
790 	long double kb_per_transfer, mb_per_second, mb_per_second_read;
791 	long double mb_per_second_write;
792 	u_int64_t total_bytes, total_transfers, total_blocks;
793 	u_int64_t total_bytes_read, total_transfers_read;
794 	u_int64_t total_bytes_write, total_transfers_write;
795 	long double busy_pct, busy_time;
796 	u_int64_t queue_len;
797 	long double total_mb, blocks_per_second, total_duration;
798 	long double ms_per_other, ms_per_read, ms_per_write, ms_per_transaction;
799 	int firstline = 1;
800 	char *devicename;
801 
802 	if (xflag > 0) {
803 		printf("                        extended device statistics  ");
804 		if (Tflag > 0)
805 			printf("      tty ");
806 		if (Cflag > 0)
807 			printf("           cpu ");
808 		printf("\n");
809 		if (Iflag == 0) {
810 			printf("device       r/s     w/s     kr/s     kw/s "
811 			    " ms/r  ms/w  ms/o  ms/t qlen  %%b  ");
812 		} else {
813 			printf("device           r/i         w/i         kr/i"
814 			    "         kw/i qlen   tsvc_t/i      sb/i  ");
815 		}
816 		if (Tflag > 0)
817 			printf("tin  tout ");
818 		if (Cflag > 0)
819 			printf("us ni sy in id ");
820 		printf("\n");
821 	}
822 
823 	for (dn = 0; dn < num_devices; dn++) {
824 		int di;
825 
826 		if (((perf_select == 0) && (dev_select[dn].selected == 0))
827 		 || (dev_select[dn].selected > maxshowdevs))
828 			continue;
829 
830 		di = dev_select[dn].position;
831 
832 		if (devstat_compute_statistics(&cur.dinfo->devices[di],
833 		    havelast ? &last.dinfo->devices[di] : NULL, etime,
834 		    DSM_TOTAL_BYTES, &total_bytes,
835 		    DSM_TOTAL_BYTES_READ, &total_bytes_read,
836 		    DSM_TOTAL_BYTES_WRITE, &total_bytes_write,
837 		    DSM_TOTAL_TRANSFERS, &total_transfers,
838 		    DSM_TOTAL_TRANSFERS_READ, &total_transfers_read,
839 		    DSM_TOTAL_TRANSFERS_WRITE, &total_transfers_write,
840 		    DSM_TOTAL_BLOCKS, &total_blocks,
841 		    DSM_KB_PER_TRANSFER, &kb_per_transfer,
842 		    DSM_TRANSFERS_PER_SECOND, &transfers_per_second,
843 		    DSM_TRANSFERS_PER_SECOND_READ, &transfers_per_second_read,
844 		    DSM_TRANSFERS_PER_SECOND_WRITE, &transfers_per_second_write,
845 		    DSM_MB_PER_SECOND, &mb_per_second,
846 		    DSM_MB_PER_SECOND_READ, &mb_per_second_read,
847 		    DSM_MB_PER_SECOND_WRITE, &mb_per_second_write,
848 		    DSM_BLOCKS_PER_SECOND, &blocks_per_second,
849 		    DSM_MS_PER_TRANSACTION, &ms_per_transaction,
850 		    DSM_MS_PER_TRANSACTION_READ, &ms_per_read,
851 		    DSM_MS_PER_TRANSACTION_WRITE, &ms_per_write,
852 		    DSM_MS_PER_TRANSACTION_OTHER, &ms_per_other,
853 		    DSM_BUSY_PCT, &busy_pct,
854 		    DSM_QUEUE_LENGTH, &queue_len,
855 		    DSM_TOTAL_DURATION, &total_duration,
856 		    DSM_TOTAL_BUSY_TIME, &busy_time,
857 		    DSM_NONE) != 0)
858 			errx(1, "%s", devstat_errbuf);
859 
860 		if (perf_select != 0) {
861 			dev_select[dn].bytes = total_bytes;
862 			if ((dev_select[dn].selected == 0)
863 			 || (dev_select[dn].selected > maxshowdevs))
864 				continue;
865 		}
866 
867 		if (Kflag > 0 || xflag > 0) {
868 			int block_size = cur.dinfo->devices[di].block_size;
869 			total_blocks = total_blocks * (block_size ?
870 						       block_size : 512) / 1024;
871 		}
872 
873 		if (xflag > 0) {
874 			if (asprintf(&devicename, "%s%d",
875 			    cur.dinfo->devices[di].device_name,
876 			    cur.dinfo->devices[di].unit_number) == -1)
877 				err(1, "asprintf");
878 			/*
879 			 * If zflag is set, skip any devices with zero I/O.
880 			 */
881 			if (zflag == 0 || transfers_per_second_read > 0.05 ||
882 			    transfers_per_second_write > 0.05 ||
883 			    mb_per_second_read > ((long double).0005)/1024 ||
884 			    mb_per_second_write > ((long double).0005)/1024 ||
885 			    busy_pct > 0.5) {
886 				if (Iflag == 0)
887 					printf("%-8.8s %7d %7d %8.1Lf "
888 					    "%8.1Lf %5d %5d %5d %5d "
889 					    "%4" PRIu64 " %3.0Lf ",
890 					    devicename,
891 					    (int)transfers_per_second_read,
892 					    (int)transfers_per_second_write,
893 					    mb_per_second_read * 1024,
894 					    mb_per_second_write * 1024,
895 					    (int)ms_per_read, (int)ms_per_write,
896 					    (int)ms_per_other,
897 					    (int)ms_per_transaction,
898 					    queue_len, busy_pct);
899 				else
900 					printf("%-8.8s %11.1Lf %11.1Lf "
901 					    "%12.1Lf %12.1Lf %4" PRIu64
902 					    " %10.1Lf %9.1Lf ",
903 					    devicename,
904 					    (long double)total_transfers_read,
905 					    (long double)total_transfers_write,
906 					    (long double)
907 					        total_bytes_read / 1024,
908 					    (long double)
909 					        total_bytes_write / 1024,
910 					    queue_len,
911 					    total_duration, busy_time);
912 				if (firstline) {
913 					/*
914 					 * If this is the first device
915 					 * we're printing, also print
916 					 * CPU or TTY stats if requested.
917 					 */
918 					firstline = 0;
919 					if (Tflag > 0)
920 						printf("%4.0Lf%5.0Lf",
921 						    cur.tk_nin / etime,
922 						    cur.tk_nout / etime);
923 					if (Cflag > 0)
924 						cpustats();
925 				}
926 				printf("\n");
927 			}
928 			free(devicename);
929 		} else if (oflag > 0) {
930 			int msdig = (ms_per_transaction < 100.0) ? 1 : 0;
931 
932 			if (Iflag == 0)
933 				printf("%4.0Lf%4.0Lf%5.*Lf ",
934 				       blocks_per_second,
935 				       transfers_per_second,
936 				       msdig,
937 				       ms_per_transaction);
938 			else
939 				printf("%4.1" PRIu64 "%4.1" PRIu64 "%5.*Lf ",
940 				       total_blocks,
941 				       total_transfers,
942 				       msdig,
943 				       ms_per_transaction);
944 		} else {
945 			if (Iflag == 0)
946 				printf(" %5.2Lf %3.0Lf %5.2Lf ",
947 				       kb_per_transfer,
948 				       transfers_per_second,
949 				       mb_per_second);
950 			else {
951 				total_mb = total_bytes;
952 				total_mb /= 1024 * 1024;
953 
954 				printf(" %5.2Lf %3.1" PRIu64 " %5.2Lf ",
955 				       kb_per_transfer,
956 				       total_transfers,
957 				       total_mb);
958 			}
959 		}
960 	}
961 	if (xflag > 0 && zflag > 0 && firstline == 1 &&
962 	    (Tflag > 0 || Cflag > 0)) {
963 		/*
964 		 * If zflag is set and we did not print any device
965 		 * lines I/O because they were all zero,
966 		 * print TTY/CPU stats.
967 		 */
968 		printf("%52s","");
969 		if (Tflag > 0)
970 			printf("%4.0Lf %5.0Lf", cur.tk_nin / etime,
971 			    cur.tk_nout / etime);
972 		if (Cflag > 0)
973 			cpustats();
974 		printf("\n");
975 	}
976 }
977 
978 static void
979 cpustats(void)
980 {
981 	int state;
982 	double cptime;
983 
984 	cptime = 0.0;
985 
986 	for (state = 0; state < CPUSTATES; ++state)
987 		cptime += cur.cp_time[state];
988 	for (state = 0; state < CPUSTATES; ++state)
989 		printf(" %2.0f",
990 		       rint(100. * cur.cp_time[state] / (cptime ? cptime : 1)));
991 }
992 
993 static int
994 readvar(kvm_t *kd, const char *name, int nlid, void *ptr, size_t len)
995 {
996 	if (kd != NULL) {
997 		ssize_t nbytes;
998 
999 		nbytes = kvm_read(kd, namelist[nlid].n_value, ptr, len);
1000 
1001 		if (nbytes < 0) {
1002 			warnx("kvm_read(%s): %s", namelist[nlid].n_name,
1003 			    kvm_geterr(kd));
1004 			return (1);
1005 		} else if ((size_t)nbytes != len) {
1006 			warnx("kvm_read(%s): expected %zu bytes, got %zd bytes",
1007 			      namelist[nlid].n_name, len, nbytes);
1008 			return (1);
1009 		}
1010 	} else {
1011 		size_t nlen = len;
1012 
1013 		if (sysctlbyname(name, ptr, &nlen, NULL, 0) == -1) {
1014 			warn("sysctl(%s...) failed", name);
1015 			return (1);
1016 		}
1017 		if (nlen != len) {
1018 			warnx("sysctl(%s...): expected %lu, got %lu", name,
1019 			      (unsigned long)len, (unsigned long)nlen);
1020 			return (1);
1021 		}
1022 	}
1023 	return (0);
1024 }
1025