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
120static struct nlist namelist[] = {
121#define X_TK_NIN	0
122	{ .n_name = "_tk_nin",
123	  .n_type = 0, .n_other = 0, .n_desc = 0, .n_value = 0 },
124#define X_TK_NOUT	1
125	{ .n_name = "_tk_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
137static struct statinfo cur, last;
138static int num_devices;
139static struct device_selection *dev_select;
140static int maxshowdevs;
141static volatile sig_atomic_t headercount;
142static volatile sig_atomic_t wresized;	/* Tty resized, when non-zero. */
143static volatile sig_atomic_t alarm_rang;
144static volatile sig_atomic_t return_requested;
145static unsigned short wrows;		/* Current number of tty rows. */
146static int dflag = 0, Iflag = 0, Cflag = 0, Tflag = 0, oflag = 0, Kflag = 0;
147static int xflag = 0, zflag = 0;
148
149/* local function declarations */
150static void usage(void);
151static void needhdr(int signo);
152static void needresize(int signo);
153static void needreturn(int signo);
154static void alarm_clock(int signo);
155static void doresize(void);
156static void phdr(void);
157static void devstats(int perf_select, long double etime, int havelast);
158static void cpustats(void);
159static int readvar(kvm_t *kd, const char *name, int nlid, void *ptr,
160		   size_t len);
161
162static void
163usage(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
176int
177main(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_TK_NIN, &cur.tk_nin,
480			     sizeof(cur.tk_nin)) != 0)
481			 || (readvar(kd, "kern.tty_nout", X_TK_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 */
656void
657needhdr(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 */
668void
669needresize(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 */
679void
680alarm_clock(int signo __unused)
681{
682	alarm_rang = 1;
683}
684
685/*
686 * Request that the main loop exit soon
687 */
688void
689needreturn(int signo __unused)
690{
691	return_requested = 1;
692}
693
694/*
695 * Update the global `wrows' count of terminal rows.
696 */
697void
698doresize(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
722static void
723phdr(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
784static void
785devstats(int perf_select, long double etime, int havelast)
786{
787	int dn;
788	long double transfers_per_second, transfers_per_second_read, transfers_per_second_write;
789	long double kb_per_transfer, mb_per_second, mb_per_second_read, mb_per_second_write;
790	u_int64_t total_bytes, total_transfers, total_blocks;
791	u_int64_t total_bytes_read, total_transfers_read;
792	u_int64_t total_bytes_write, total_transfers_write;
793	long double busy_pct, busy_time;
794	u_int64_t queue_len;
795	long double total_mb;
796	long double blocks_per_second, ms_per_transaction, total_duration;
797	int firstline = 1;
798	char *devicename;
799
800	if (xflag > 0) {
801		printf("                        extended device statistics  ");
802		if (Tflag > 0)
803			printf("      tty ");
804		if (Cflag > 0)
805			printf("           cpu ");
806		printf("\n");
807		if (Iflag == 0) {
808			printf("device     r/s   w/s    kr/s    kw/s qlen "
809			    "svc_t  %%b  ");
810		} else {
811			printf("device           r/i         w/i         kr/i"
812			    "         kw/i qlen   tsvc_t/i      sb/i  ");
813		}
814		if (Tflag > 0)
815			printf("tin  tout ");
816		if (Cflag > 0)
817			printf("us ni sy in id ");
818		printf("\n");
819	}
820
821	for (dn = 0; dn < num_devices; dn++) {
822		int di;
823
824		if (((perf_select == 0) && (dev_select[dn].selected == 0))
825		 || (dev_select[dn].selected > maxshowdevs))
826			continue;
827
828		di = dev_select[dn].position;
829
830		if (devstat_compute_statistics(&cur.dinfo->devices[di],
831		    havelast ? &last.dinfo->devices[di] : NULL, etime,
832		    DSM_TOTAL_BYTES, &total_bytes,
833		    DSM_TOTAL_BYTES_READ, &total_bytes_read,
834		    DSM_TOTAL_BYTES_WRITE, &total_bytes_write,
835		    DSM_TOTAL_TRANSFERS, &total_transfers,
836		    DSM_TOTAL_TRANSFERS_READ, &total_transfers_read,
837		    DSM_TOTAL_TRANSFERS_WRITE, &total_transfers_write,
838		    DSM_TOTAL_BLOCKS, &total_blocks,
839		    DSM_KB_PER_TRANSFER, &kb_per_transfer,
840		    DSM_TRANSFERS_PER_SECOND, &transfers_per_second,
841		    DSM_TRANSFERS_PER_SECOND_READ, &transfers_per_second_read,
842		    DSM_TRANSFERS_PER_SECOND_WRITE, &transfers_per_second_write,
843		    DSM_MB_PER_SECOND, &mb_per_second,
844		    DSM_MB_PER_SECOND_READ, &mb_per_second_read,
845		    DSM_MB_PER_SECOND_WRITE, &mb_per_second_write,
846		    DSM_BLOCKS_PER_SECOND, &blocks_per_second,
847		    DSM_MS_PER_TRANSACTION, &ms_per_transaction,
848		    DSM_BUSY_PCT, &busy_pct,
849		    DSM_QUEUE_LENGTH, &queue_len,
850		    DSM_TOTAL_DURATION, &total_duration,
851		    DSM_TOTAL_BUSY_TIME, &busy_time,
852		    DSM_NONE) != 0)
853			errx(1, "%s", devstat_errbuf);
854
855		if (perf_select != 0) {
856			dev_select[dn].bytes = total_bytes;
857			if ((dev_select[dn].selected == 0)
858			 || (dev_select[dn].selected > maxshowdevs))
859				continue;
860		}
861
862		if (Kflag > 0 || xflag > 0) {
863			int block_size = cur.dinfo->devices[di].block_size;
864			total_blocks = total_blocks * (block_size ?
865						       block_size : 512) / 1024;
866		}
867
868		if (xflag > 0) {
869			if (asprintf(&devicename, "%s%d",
870			    cur.dinfo->devices[di].device_name,
871			    cur.dinfo->devices[di].unit_number) == -1)
872				err(1, "asprintf");
873			/*
874			 * If zflag is set, skip any devices with zero I/O.
875			 */
876			if (zflag == 0 || transfers_per_second_read > 0.05 ||
877			    transfers_per_second_write > 0.05 ||
878			    mb_per_second_read > ((long double).0005)/1024 ||
879			    mb_per_second_write > ((long double).0005)/1024 ||
880			    busy_pct > 0.5) {
881				if (Iflag == 0)
882					printf("%-8.8s %5.1Lf %5.1Lf %7.1Lf %7.1Lf %4" PRIu64 " %5.1Lf %3.0Lf ",
883					    devicename,
884					    transfers_per_second_read,
885					    transfers_per_second_write,
886					    mb_per_second_read * 1024,
887					    mb_per_second_write * 1024,
888					    queue_len,
889					    ms_per_transaction, busy_pct);
890				else
891					printf("%-8.8s %11.1Lf %11.1Lf "
892					    "%12.1Lf %12.1Lf %4" PRIu64
893					    " %10.1Lf %9.1Lf ",
894					    devicename,
895					    (long double)total_transfers_read,
896					    (long double)total_transfers_write,
897					    (long double)
898					        total_bytes_read / 1024,
899					    (long double)
900					        total_bytes_write / 1024,
901					    queue_len,
902					    total_duration, busy_time);
903				if (firstline) {
904					/*
905					 * If this is the first device
906					 * we're printing, also print
907					 * CPU or TTY stats if requested.
908					 */
909					firstline = 0;
910					if (Tflag > 0)
911						printf("%4.0Lf%5.0Lf",
912						    cur.tk_nin / etime,
913						    cur.tk_nout / etime);
914					if (Cflag > 0)
915						cpustats();
916				}
917				printf("\n");
918			}
919			free(devicename);
920		} else if (oflag > 0) {
921			int msdig = (ms_per_transaction < 100.0) ? 1 : 0;
922
923			if (Iflag == 0)
924				printf("%4.0Lf%4.0Lf%5.*Lf ",
925				       blocks_per_second,
926				       transfers_per_second,
927				       msdig,
928				       ms_per_transaction);
929			else
930				printf("%4.1" PRIu64 "%4.1" PRIu64 "%5.*Lf ",
931				       total_blocks,
932				       total_transfers,
933				       msdig,
934				       ms_per_transaction);
935		} else {
936			if (Iflag == 0)
937				printf(" %5.2Lf %3.0Lf %5.2Lf ",
938				       kb_per_transfer,
939				       transfers_per_second,
940				       mb_per_second);
941			else {
942				total_mb = total_bytes;
943				total_mb /= 1024 * 1024;
944
945				printf(" %5.2Lf %3.1" PRIu64 " %5.2Lf ",
946				       kb_per_transfer,
947				       total_transfers,
948				       total_mb);
949			}
950		}
951	}
952	if (xflag > 0 && zflag > 0 && firstline == 1 &&
953	    (Tflag > 0 || Cflag > 0)) {
954		/*
955		 * If zflag is set and we did not print any device
956		 * lines I/O because they were all zero,
957		 * print TTY/CPU stats.
958		 */
959		printf("%52s","");
960		if (Tflag > 0)
961			printf("%4.0Lf %5.0Lf", cur.tk_nin / etime,
962			    cur.tk_nout / etime);
963		if (Cflag > 0)
964			cpustats();
965		printf("\n");
966	}
967}
968
969static void
970cpustats(void)
971{
972	int state;
973	double cptime;
974
975	cptime = 0.0;
976
977	for (state = 0; state < CPUSTATES; ++state)
978		cptime += cur.cp_time[state];
979	for (state = 0; state < CPUSTATES; ++state)
980		printf(" %2.0f",
981		       rint(100. * cur.cp_time[state] / (cptime ? cptime : 1)));
982}
983
984static int
985readvar(kvm_t *kd, const char *name, int nlid, void *ptr, size_t len)
986{
987	if (kd != NULL) {
988		ssize_t nbytes;
989
990		nbytes = kvm_read(kd, namelist[nlid].n_value, ptr, len);
991
992		if (nbytes < 0) {
993			warnx("kvm_read(%s): %s", namelist[nlid].n_name,
994			    kvm_geterr(kd));
995			return (1);
996		} else if ((size_t)nbytes != len) {
997			warnx("kvm_read(%s): expected %zu bytes, got %zd bytes",
998			      namelist[nlid].n_name, len, nbytes);
999			return (1);
1000		}
1001	} else {
1002		size_t nlen = len;
1003
1004		if (sysctlbyname(name, ptr, &nlen, NULL, 0) == -1) {
1005			warn("sysctl(%s...) failed", name);
1006			return (1);
1007		}
1008		if (nlen != len) {
1009			warnx("sysctl(%s...): expected %lu, got %lu", name,
1010			      (unsigned long)len, (unsigned long)nlen);
1011			return (1);
1012		}
1013	}
1014	return (0);
1015}
1016