xref: /freebsd/usr.bin/ctlstat/ctlstat.c (revision 97cb52fa9aefd90fad38790fded50905aeeb9b9e)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2004, 2008, 2009 Silicon Graphics International Corp.
5  * Copyright (c) 2017 Alexander Motin <mav@FreeBSD.org>
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions, and the following disclaimer,
13  *    without modification.
14  * 2. Redistributions in binary form must reproduce at minimum a disclaimer
15  *    substantially similar to the "NO WARRANTY" disclaimer below
16  *    ("Disclaimer") and any redistribution must be conditioned upon
17  *    including a substantially similar Disclaimer requirement for further
18  *    binary redistribution.
19  *
20  * NO WARRANTY
21  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
24  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25  * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
29  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
30  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
31  * POSSIBILITY OF SUCH DAMAGES.
32  *
33  * $Id: //depot/users/kenm/FreeBSD-test2/usr.bin/ctlstat/ctlstat.c#4 $
34  */
35 /*
36  * CAM Target Layer statistics program
37  *
38  * Authors: Ken Merry <ken@FreeBSD.org>, Will Andrews <will@FreeBSD.org>
39  */
40 
41 #include <sys/cdefs.h>
42 __FBSDID("$FreeBSD$");
43 
44 #include <sys/ioctl.h>
45 #include <sys/types.h>
46 #include <sys/param.h>
47 #include <sys/time.h>
48 #include <sys/sysctl.h>
49 #include <sys/resource.h>
50 #include <sys/queue.h>
51 #include <sys/callout.h>
52 #include <stdint.h>
53 #include <stdio.h>
54 #include <stdlib.h>
55 #include <unistd.h>
56 #include <fcntl.h>
57 #include <getopt.h>
58 #include <string.h>
59 #include <errno.h>
60 #include <err.h>
61 #include <ctype.h>
62 #include <bitstring.h>
63 #include <cam/scsi/scsi_all.h>
64 #include <cam/ctl/ctl.h>
65 #include <cam/ctl/ctl_io.h>
66 #include <cam/ctl/ctl_scsi_all.h>
67 #include <cam/ctl/ctl_util.h>
68 #include <cam/ctl/ctl_backend.h>
69 #include <cam/ctl/ctl_ioctl.h>
70 
71 /*
72  * The default amount of space we allocate for stats storage space.
73  * We dynamically allocate more if needed.
74  */
75 #define	CTL_STAT_NUM_ITEMS	256
76 
77 /*
78  * The default number of LUN selection bits we allocate.  This is large
79  * because we don't currently increase it if the user specifies a LUN
80  * number of 1024 or larger.
81  */
82 #define	CTL_STAT_BITS		1024L
83 
84 static const char *ctlstat_opts = "Cc:Ddhjl:n:p:tw:";
85 static const char *ctlstat_usage = "Usage:  ctlstat [-CDdjht] [-l lunnum]"
86 				   "[-c count] [-n numdevs] [-w wait]\n";
87 
88 struct ctl_cpu_stats {
89 	uint64_t user;
90 	uint64_t nice;
91 	uint64_t system;
92 	uint64_t intr;
93 	uint64_t idle;
94 };
95 
96 typedef enum {
97 	CTLSTAT_MODE_STANDARD,
98 	CTLSTAT_MODE_DUMP,
99 	CTLSTAT_MODE_JSON,
100 } ctlstat_mode_types;
101 
102 #define	CTLSTAT_FLAG_CPU		(1 << 0)
103 #define	CTLSTAT_FLAG_HEADER		(1 << 1)
104 #define	CTLSTAT_FLAG_FIRST_RUN		(1 << 2)
105 #define	CTLSTAT_FLAG_TOTALS		(1 << 3)
106 #define	CTLSTAT_FLAG_DMA_TIME		(1 << 4)
107 #define	CTLSTAT_FLAG_TIME_VALID		(1 << 5)
108 #define	CTLSTAT_FLAG_MASK		(1 << 6)
109 #define	CTLSTAT_FLAG_LUNS		(1 << 7)
110 #define	CTLSTAT_FLAG_PORTS		(1 << 8)
111 #define	F_CPU(ctx) ((ctx)->flags & CTLSTAT_FLAG_CPU)
112 #define	F_HDR(ctx) ((ctx)->flags & CTLSTAT_FLAG_HEADER)
113 #define	F_FIRST(ctx) ((ctx)->flags & CTLSTAT_FLAG_FIRST_RUN)
114 #define	F_TOTALS(ctx) ((ctx)->flags & CTLSTAT_FLAG_TOTALS)
115 #define	F_DMA(ctx) ((ctx)->flags & CTLSTAT_FLAG_DMA_TIME)
116 #define	F_TIMEVAL(ctx) ((ctx)->flags & CTLSTAT_FLAG_TIME_VALID)
117 #define	F_MASK(ctx) ((ctx)->flags & CTLSTAT_FLAG_MASK)
118 #define	F_LUNS(ctx) ((ctx)->flags & CTLSTAT_FLAG_LUNS)
119 #define	F_PORTS(ctx) ((ctx)->flags & CTLSTAT_FLAG_PORTS)
120 
121 struct ctlstat_context {
122 	ctlstat_mode_types mode;
123 	int flags;
124 	struct ctl_io_stats *cur_stats, *prev_stats;
125 	struct ctl_io_stats cur_total_stats[3], prev_total_stats[3];
126 	struct timespec cur_time, prev_time;
127 	struct ctl_cpu_stats cur_cpu, prev_cpu;
128 	uint64_t cur_total_jiffies, prev_total_jiffies;
129 	uint64_t cur_idle, prev_idle;
130 	bitstr_t bit_decl(item_mask, CTL_STAT_BITS);
131 	int cur_items, prev_items;
132 	int cur_alloc, prev_alloc;
133 	int numdevs;
134 	int header_interval;
135 };
136 
137 #ifndef min
138 #define	min(x,y)	(((x) < (y)) ? (x) : (y))
139 #endif
140 
141 static void usage(int error);
142 static int getstats(int fd, int *alloc_items, int *num_items,
143     struct ctl_io_stats **xstats, struct timespec *cur_time, int *time_valid);
144 static int getcpu(struct ctl_cpu_stats *cpu_stats);
145 static void compute_stats(struct ctl_io_stats *cur_stats,
146 			  struct ctl_io_stats *prev_stats,
147 			  long double etime, long double *mbsec,
148 			  long double *kb_per_transfer,
149 			  long double *transfers_per_second,
150 			  long double *ms_per_transfer,
151 			  long double *ms_per_dma,
152 			  long double *dmas_per_second);
153 
154 static void
155 usage(int error)
156 {
157 	fputs(ctlstat_usage, error ? stderr : stdout);
158 }
159 
160 static int
161 getstats(int fd, int *alloc_items, int *num_items, struct ctl_io_stats **stats,
162 	 struct timespec *cur_time, int *flags)
163 {
164 	struct ctl_get_io_stats get_stats;
165 	int more_space_count = 0;
166 
167 	if (*alloc_items == 0)
168 		*alloc_items = CTL_STAT_NUM_ITEMS;
169 retry:
170 	if (*stats == NULL)
171 		*stats = malloc(sizeof(**stats) * *alloc_items);
172 
173 	memset(&get_stats, 0, sizeof(get_stats));
174 	get_stats.alloc_len = *alloc_items * sizeof(**stats);
175 	memset(*stats, 0, get_stats.alloc_len);
176 	get_stats.stats = *stats;
177 
178 	if (ioctl(fd, (*flags & CTLSTAT_FLAG_PORTS) ? CTL_GET_PORT_STATS :
179 	    CTL_GET_LUN_STATS, &get_stats) == -1)
180 		err(1, "CTL_GET_*_STATS ioctl returned error");
181 
182 	switch (get_stats.status) {
183 	case CTL_SS_OK:
184 		break;
185 	case CTL_SS_ERROR:
186 		err(1, "CTL_GET_*_STATS ioctl returned CTL_SS_ERROR");
187 		break;
188 	case CTL_SS_NEED_MORE_SPACE:
189 		if (more_space_count >= 2)
190 			errx(1, "CTL_GET_*_STATS returned NEED_MORE_SPACE again");
191 		*alloc_items = get_stats.num_items * 5 / 4;
192 		free(*stats);
193 		*stats = NULL;
194 		more_space_count++;
195 		goto retry;
196 		break; /* NOTREACHED */
197 	default:
198 		errx(1, "CTL_GET_*_STATS ioctl returned unknown status %d",
199 		     get_stats.status);
200 		break;
201 	}
202 
203 	*num_items = get_stats.fill_len / sizeof(**stats);
204 	cur_time->tv_sec = get_stats.timestamp.tv_sec;
205 	cur_time->tv_nsec = get_stats.timestamp.tv_nsec;
206 	if (get_stats.flags & CTL_STATS_FLAG_TIME_VALID)
207 		*flags |= CTLSTAT_FLAG_TIME_VALID;
208 	else
209 		*flags &= ~CTLSTAT_FLAG_TIME_VALID;
210 
211 	return (0);
212 }
213 
214 static int
215 getcpu(struct ctl_cpu_stats *cpu_stats)
216 {
217 	long cp_time[CPUSTATES];
218 	size_t cplen;
219 
220 	cplen = sizeof(cp_time);
221 
222 	if (sysctlbyname("kern.cp_time", &cp_time, &cplen, NULL, 0) == -1) {
223 		warn("sysctlbyname(kern.cp_time...) failed");
224 		return (1);
225 	}
226 
227 	cpu_stats->user = cp_time[CP_USER];
228 	cpu_stats->nice = cp_time[CP_NICE];
229 	cpu_stats->system = cp_time[CP_SYS];
230 	cpu_stats->intr = cp_time[CP_INTR];
231 	cpu_stats->idle = cp_time[CP_IDLE];
232 
233 	return (0);
234 }
235 
236 static void
237 compute_stats(struct ctl_io_stats *cur_stats,
238 	      struct ctl_io_stats *prev_stats, long double etime,
239 	      long double *mbsec, long double *kb_per_transfer,
240 	      long double *transfers_per_second, long double *ms_per_transfer,
241 	      long double *ms_per_dma, long double *dmas_per_second)
242 {
243 	uint64_t total_bytes = 0, total_operations = 0, total_dmas = 0;
244 	struct bintime total_time_bt, total_dma_bt;
245 	struct timespec total_time_ts, total_dma_ts;
246 	int i;
247 
248 	bzero(&total_time_bt, sizeof(total_time_bt));
249 	bzero(&total_dma_bt, sizeof(total_dma_bt));
250 	bzero(&total_time_ts, sizeof(total_time_ts));
251 	bzero(&total_dma_ts, sizeof(total_dma_ts));
252 	for (i = 0; i < CTL_STATS_NUM_TYPES; i++) {
253 		total_bytes += cur_stats->bytes[i];
254 		total_operations += cur_stats->operations[i];
255 		total_dmas += cur_stats->dmas[i];
256 		bintime_add(&total_time_bt, &cur_stats->time[i]);
257 		bintime_add(&total_dma_bt, &cur_stats->dma_time[i]);
258 		if (prev_stats != NULL) {
259 			total_bytes -= prev_stats->bytes[i];
260 			total_operations -= prev_stats->operations[i];
261 			total_dmas -= prev_stats->dmas[i];
262 			bintime_sub(&total_time_bt, &prev_stats->time[i]);
263 			bintime_sub(&total_dma_bt, &prev_stats->dma_time[i]);
264 		}
265 	}
266 
267 	*mbsec = total_bytes;
268 	*mbsec /= 1024 * 1024;
269 	if (etime > 0.0)
270 		*mbsec /= etime;
271 	else
272 		*mbsec = 0;
273 	*kb_per_transfer = total_bytes;
274 	*kb_per_transfer /= 1024;
275 	if (total_operations > 0)
276 		*kb_per_transfer /= total_operations;
277 	else
278 		*kb_per_transfer = 0;
279 	*transfers_per_second = total_operations;
280 	*dmas_per_second = total_dmas;
281 	if (etime > 0.0) {
282 		*transfers_per_second /= etime;
283 		*dmas_per_second /= etime;
284 	} else {
285 		*transfers_per_second = 0;
286 		*dmas_per_second = 0;
287 	}
288 
289 	bintime2timespec(&total_time_bt, &total_time_ts);
290 	bintime2timespec(&total_dma_bt, &total_dma_ts);
291 	if (total_operations > 0) {
292 		/*
293 		 * Convert the timespec to milliseconds.
294 		 */
295 		*ms_per_transfer = total_time_ts.tv_sec * 1000;
296 		*ms_per_transfer += total_time_ts.tv_nsec / 1000000;
297 		*ms_per_transfer /= total_operations;
298 	} else
299 		*ms_per_transfer = 0;
300 
301 	if (total_dmas > 0) {
302 		/*
303 		 * Convert the timespec to milliseconds.
304 		 */
305 		*ms_per_dma = total_dma_ts.tv_sec * 1000;
306 		*ms_per_dma += total_dma_ts.tv_nsec / 1000000;
307 		*ms_per_dma /= total_dmas;
308 	} else
309 		*ms_per_dma = 0;
310 }
311 
312 /* The dump_stats() and json_stats() functions perform essentially the same
313  * purpose, but dump the statistics in different formats.  JSON is more
314  * conducive to programming, however.
315  */
316 
317 #define	PRINT_BINTIME(bt) \
318 	printf("%jd.%06ju", (intmax_t)(bt).sec, \
319 	       (uintmax_t)(((bt).frac >> 32) * 1000000 >> 32))
320 static const char *iotypes[] = {"NO IO", "READ", "WRITE"};
321 
322 static void
323 ctlstat_dump(struct ctlstat_context *ctx)
324 {
325 	int iotype, i, n;
326 	struct ctl_io_stats *stats = ctx->cur_stats;
327 
328 	for (i = n = 0; i < ctx->cur_items;i++) {
329 		if (F_MASK(ctx) && bit_test(ctx->item_mask,
330 		    (int)stats[i].item) == 0)
331 			continue;
332 		printf("%s %d\n", F_PORTS(ctx) ? "port" : "lun", stats[i].item);
333 		for (iotype = 0; iotype < CTL_STATS_NUM_TYPES; iotype++) {
334 			printf("  io type %d (%s)\n", iotype, iotypes[iotype]);
335 			printf("   bytes %ju\n", (uintmax_t)
336 			    stats[i].bytes[iotype]);
337 			printf("   operations %ju\n", (uintmax_t)
338 			    stats[i].operations[iotype]);
339 			printf("   dmas %ju\n", (uintmax_t)
340 			    stats[i].dmas[iotype]);
341 			printf("   io time ");
342 			PRINT_BINTIME(stats[i].time[iotype]);
343 			printf("\n   dma time ");
344 			PRINT_BINTIME(stats[i].dma_time[iotype]);
345 			printf("\n");
346 		}
347 		if (++n >= ctx->numdevs)
348 			break;
349 	}
350 }
351 
352 static void
353 ctlstat_json(struct ctlstat_context *ctx) {
354 	int iotype, i, n;
355 	struct ctl_io_stats *stats = ctx->cur_stats;
356 
357 	printf("{\"%s\":[", F_PORTS(ctx) ? "ports" : "luns");
358 	for (i = n = 0; i < ctx->cur_items; i++) {
359 		if (F_MASK(ctx) && bit_test(ctx->item_mask,
360 		    (int)stats[i].item) == 0)
361 			continue;
362 		printf("{\"num\":%d,\"io\":[",
363 		    stats[i].item);
364 		for (iotype = 0; iotype < CTL_STATS_NUM_TYPES; iotype++) {
365 			printf("{\"type\":\"%s\",", iotypes[iotype]);
366 			printf("\"bytes\":%ju,", (uintmax_t)
367 			    stats[i].bytes[iotype]);
368 			printf("\"operations\":%ju,", (uintmax_t)
369 			    stats[i].operations[iotype]);
370 			printf("\"dmas\":%ju,", (uintmax_t)
371 			    stats[i].dmas[iotype]);
372 			printf("\"io time\":");
373 			PRINT_BINTIME(stats[i].time[iotype]);
374 			printf(",\"dma time\":");
375 			PRINT_BINTIME(stats[i].dma_time[iotype]);
376 			printf("}");
377 			if (iotype < (CTL_STATS_NUM_TYPES - 1))
378 				printf(","); /* continue io array */
379 		}
380 		printf("]}");
381 		if (++n >= ctx->numdevs)
382 			break;
383 		if (i < (ctx->cur_items - 1))
384 			printf(","); /* continue lun array */
385 	}
386 	printf("]}");
387 }
388 
389 static void
390 ctlstat_standard(struct ctlstat_context *ctx) {
391 	long double etime;
392 	uint64_t delta_jiffies, delta_idle;
393 	long double cpu_percentage;
394 	int i, j, n;
395 
396 	cpu_percentage = 0;
397 
398 	if (F_CPU(ctx) && (getcpu(&ctx->cur_cpu) != 0))
399 		errx(1, "error returned from getcpu()");
400 
401 	etime = ctx->cur_time.tv_sec - ctx->prev_time.tv_sec +
402 	    (ctx->prev_time.tv_nsec - ctx->cur_time.tv_nsec) * 1e-9;
403 
404 	if (F_CPU(ctx)) {
405 		ctx->prev_total_jiffies = ctx->cur_total_jiffies;
406 		ctx->cur_total_jiffies = ctx->cur_cpu.user +
407 		    ctx->cur_cpu.nice + ctx->cur_cpu.system +
408 		    ctx->cur_cpu.intr + ctx->cur_cpu.idle;
409 		delta_jiffies = ctx->cur_total_jiffies;
410 		if (F_FIRST(ctx) == 0)
411 			delta_jiffies -= ctx->prev_total_jiffies;
412 		ctx->prev_idle = ctx->cur_idle;
413 		ctx->cur_idle = ctx->cur_cpu.idle;
414 		delta_idle = ctx->cur_idle - ctx->prev_idle;
415 
416 		cpu_percentage = delta_jiffies - delta_idle;
417 		cpu_percentage /= delta_jiffies;
418 		cpu_percentage *= 100;
419 	}
420 
421 	if (F_HDR(ctx)) {
422 		ctx->header_interval--;
423 		if (ctx->header_interval <= 0) {
424 			if (F_CPU(ctx))
425 				fprintf(stdout, " CPU");
426 			if (F_TOTALS(ctx)) {
427 				fprintf(stdout, "%s     Read       %s"
428 					"    Write       %s    Total\n",
429 					(F_TIMEVAL(ctx) != 0) ? "      " : "",
430 					(F_TIMEVAL(ctx) != 0) ? "      " : "",
431 					(F_TIMEVAL(ctx) != 0) ? "      " : "");
432 				n = 3;
433 			} else {
434 				for (i = n = 0; i < min(CTL_STAT_BITS,
435 				     ctx->cur_items); i++) {
436 					int item;
437 
438 					/*
439 					 * Obviously this won't work with
440 					 * LUN numbers greater than a signed
441 					 * integer.
442 					 */
443 					item = (int)ctx->cur_stats[i].item;
444 
445 					if (F_MASK(ctx) &&
446 					    bit_test(ctx->item_mask, item) == 0)
447 						continue;
448 					fprintf(stdout, "%15.6s%d %s",
449 					    F_PORTS(ctx) ? "port" : "lun", item,
450 					    (F_TIMEVAL(ctx) != 0) ? "     " : "");
451 					if (++n >= ctx->numdevs)
452 						break;
453 				}
454 				fprintf(stdout, "\n");
455 			}
456 			if (F_CPU(ctx))
457 				fprintf(stdout, "    ");
458 			for (i = 0; i < n; i++)
459 				fprintf(stdout, "%s KB/t   %s MB/s",
460 					(F_TIMEVAL(ctx) != 0) ? "    ms" : "",
461 					(F_DMA(ctx) == 0) ? "tps" : "dps");
462 			fprintf(stdout, "\n");
463 			ctx->header_interval = 20;
464 		}
465 	}
466 
467 	if (F_CPU(ctx))
468 		fprintf(stdout, "%3.0Lf%%", cpu_percentage);
469 	if (F_TOTALS(ctx) != 0) {
470 		long double mbsec[3];
471 		long double kb_per_transfer[3];
472 		long double transfers_per_sec[3];
473 		long double ms_per_transfer[3];
474 		long double ms_per_dma[3];
475 		long double dmas_per_sec[3];
476 
477 		for (i = 0; i < 3; i++)
478 			ctx->prev_total_stats[i] = ctx->cur_total_stats[i];
479 
480 		memset(&ctx->cur_total_stats, 0, sizeof(ctx->cur_total_stats));
481 
482 		/* Use macros to make the next loop more readable. */
483 #define	ADD_STATS_BYTES(st, i, j) \
484 	ctx->cur_total_stats[st].bytes[j] += \
485 	    ctx->cur_stats[i].bytes[j]
486 #define	ADD_STATS_OPERATIONS(st, i, j) \
487 	ctx->cur_total_stats[st].operations[j] += \
488 	    ctx->cur_stats[i].operations[j]
489 #define	ADD_STATS_DMAS(st, i, j) \
490 	ctx->cur_total_stats[st].dmas[j] += \
491 	    ctx->cur_stats[i].dmas[j]
492 #define	ADD_STATS_TIME(st, i, j) \
493 	bintime_add(&ctx->cur_total_stats[st].time[j], \
494 	    &ctx->cur_stats[i].time[j])
495 #define	ADD_STATS_DMA_TIME(st, i, j) \
496 	bintime_add(&ctx->cur_total_stats[st].dma_time[j], \
497 	    &ctx->cur_stats[i].dma_time[j])
498 
499 		for (i = 0; i < ctx->cur_items; i++) {
500 			if (F_MASK(ctx) && bit_test(ctx->item_mask,
501 			    (int)ctx->cur_stats[i].item) == 0)
502 				continue;
503 			for (j = 0; j < CTL_STATS_NUM_TYPES; j++) {
504 				ADD_STATS_BYTES(2, i, j);
505 				ADD_STATS_OPERATIONS(2, i, j);
506 				ADD_STATS_DMAS(2, i, j);
507 				ADD_STATS_TIME(2, i, j);
508 				ADD_STATS_DMA_TIME(2, i, j);
509 			}
510 			ADD_STATS_BYTES(0, i, CTL_STATS_READ);
511 			ADD_STATS_OPERATIONS(0, i, CTL_STATS_READ);
512 			ADD_STATS_DMAS(0, i, CTL_STATS_READ);
513 			ADD_STATS_TIME(0, i, CTL_STATS_READ);
514 			ADD_STATS_DMA_TIME(0, i, CTL_STATS_READ);
515 
516 			ADD_STATS_BYTES(1, i, CTL_STATS_WRITE);
517 			ADD_STATS_OPERATIONS(1, i, CTL_STATS_WRITE);
518 			ADD_STATS_DMAS(1, i, CTL_STATS_WRITE);
519 			ADD_STATS_TIME(1, i, CTL_STATS_WRITE);
520 			ADD_STATS_DMA_TIME(1, i, CTL_STATS_WRITE);
521 		}
522 
523 		for (i = 0; i < 3; i++) {
524 			compute_stats(&ctx->cur_total_stats[i],
525 				F_FIRST(ctx) ? NULL : &ctx->prev_total_stats[i],
526 				etime, &mbsec[i], &kb_per_transfer[i],
527 				&transfers_per_sec[i],
528 				&ms_per_transfer[i], &ms_per_dma[i],
529 				&dmas_per_sec[i]);
530 			if (F_DMA(ctx) != 0)
531 				fprintf(stdout, " %5.1Lf",
532 					ms_per_dma[i]);
533 			else if (F_TIMEVAL(ctx) != 0)
534 				fprintf(stdout, " %5.1Lf",
535 					ms_per_transfer[i]);
536 			fprintf(stdout, " %4.0Lf %5.0Lf %4.0Lf",
537 				kb_per_transfer[i],
538 				(F_DMA(ctx) == 0) ? transfers_per_sec[i] :
539 				dmas_per_sec[i], mbsec[i]);
540 		}
541 	} else {
542 		for (i = n = 0; i < min(CTL_STAT_BITS, ctx->cur_items); i++) {
543 			long double mbsec, kb_per_transfer;
544 			long double transfers_per_sec;
545 			long double ms_per_transfer;
546 			long double ms_per_dma;
547 			long double dmas_per_sec;
548 
549 			if (F_MASK(ctx) && bit_test(ctx->item_mask,
550 			    (int)ctx->cur_stats[i].item) == 0)
551 				continue;
552 			for (j = 0; j < ctx->prev_items; j++) {
553 				if (ctx->prev_stats[j].item ==
554 				    ctx->cur_stats[i].item)
555 					break;
556 			}
557 			if (j >= ctx->prev_items)
558 				j = -1;
559 			compute_stats(&ctx->cur_stats[i],
560 			    j >= 0 ? &ctx->prev_stats[j] : NULL,
561 			    etime, &mbsec, &kb_per_transfer,
562 			    &transfers_per_sec, &ms_per_transfer,
563 			    &ms_per_dma, &dmas_per_sec);
564 			if (F_DMA(ctx))
565 				fprintf(stdout, " %5.1Lf",
566 					ms_per_dma);
567 			else if (F_TIMEVAL(ctx) != 0)
568 				fprintf(stdout, " %5.1Lf",
569 					ms_per_transfer);
570 			fprintf(stdout, " %4.0Lf %5.0Lf %4.0Lf",
571 				kb_per_transfer, (F_DMA(ctx) == 0) ?
572 				transfers_per_sec : dmas_per_sec, mbsec);
573 			if (++n >= ctx->numdevs)
574 				break;
575 		}
576 	}
577 }
578 
579 int
580 main(int argc, char **argv)
581 {
582 	int c;
583 	int count, waittime;
584 	int fd, retval;
585 	struct ctlstat_context ctx;
586 	struct ctl_io_stats *tmp_stats;
587 
588 	/* default values */
589 	retval = 0;
590 	waittime = 1;
591 	count = -1;
592 	memset(&ctx, 0, sizeof(ctx));
593 	ctx.numdevs = 3;
594 	ctx.mode = CTLSTAT_MODE_STANDARD;
595 	ctx.flags |= CTLSTAT_FLAG_CPU;
596 	ctx.flags |= CTLSTAT_FLAG_FIRST_RUN;
597 	ctx.flags |= CTLSTAT_FLAG_HEADER;
598 
599 	while ((c = getopt(argc, argv, ctlstat_opts)) != -1) {
600 		switch (c) {
601 		case 'C':
602 			ctx.flags &= ~CTLSTAT_FLAG_CPU;
603 			break;
604 		case 'c':
605 			count = atoi(optarg);
606 			break;
607 		case 'd':
608 			ctx.flags |= CTLSTAT_FLAG_DMA_TIME;
609 			break;
610 		case 'D':
611 			ctx.mode = CTLSTAT_MODE_DUMP;
612 			waittime = 30;
613 			break;
614 		case 'h':
615 			ctx.flags &= ~CTLSTAT_FLAG_HEADER;
616 			break;
617 		case 'j':
618 			ctx.mode = CTLSTAT_MODE_JSON;
619 			waittime = 30;
620 			break;
621 		case 'l': {
622 			int cur_lun;
623 
624 			cur_lun = atoi(optarg);
625 			if (cur_lun > CTL_STAT_BITS)
626 				errx(1, "Invalid LUN number %d", cur_lun);
627 
628 			if (!F_MASK(&ctx))
629 				ctx.numdevs = 1;
630 			else
631 				ctx.numdevs++;
632 			bit_set(ctx.item_mask, cur_lun);
633 			ctx.flags |= CTLSTAT_FLAG_MASK;
634 			ctx.flags |= CTLSTAT_FLAG_LUNS;
635 			break;
636 		}
637 		case 'n':
638 			ctx.numdevs = atoi(optarg);
639 			break;
640 		case 'p': {
641 			int cur_port;
642 
643 			cur_port = atoi(optarg);
644 			if (cur_port > CTL_STAT_BITS)
645 				errx(1, "Invalid port number %d", cur_port);
646 
647 			if (!F_MASK(&ctx))
648 				ctx.numdevs = 1;
649 			else
650 				ctx.numdevs++;
651 			bit_set(ctx.item_mask, cur_port);
652 			ctx.flags |= CTLSTAT_FLAG_MASK;
653 			ctx.flags |= CTLSTAT_FLAG_PORTS;
654 			break;
655 		}
656 		case 't':
657 			ctx.flags |= CTLSTAT_FLAG_TOTALS;
658 			break;
659 		case 'w':
660 			waittime = atoi(optarg);
661 			break;
662 		default:
663 			retval = 1;
664 			usage(retval);
665 			exit(retval);
666 			break;
667 		}
668 	}
669 
670 	if (F_LUNS(&ctx) && F_PORTS(&ctx))
671 		errx(1, "Options -p and -l are exclusive.");
672 
673 	if (!F_LUNS(&ctx) && !F_PORTS(&ctx)) {
674 		if (F_TOTALS(&ctx))
675 			ctx.flags |= CTLSTAT_FLAG_PORTS;
676 		else
677 			ctx.flags |= CTLSTAT_FLAG_LUNS;
678 	}
679 
680 	if ((fd = open(CTL_DEFAULT_DEV, O_RDWR)) == -1)
681 		err(1, "cannot open %s", CTL_DEFAULT_DEV);
682 
683 	for (;count != 0;) {
684 		tmp_stats = ctx.prev_stats;
685 		ctx.prev_stats = ctx.cur_stats;
686 		ctx.cur_stats = tmp_stats;
687 		c = ctx.prev_alloc;
688 		ctx.prev_alloc = ctx.cur_alloc;
689 		ctx.cur_alloc = c;
690 		c = ctx.prev_items;
691 		ctx.prev_items = ctx.cur_items;
692 		ctx.cur_items = c;
693 		ctx.prev_time = ctx.cur_time;
694 		ctx.prev_cpu = ctx.cur_cpu;
695 		if (getstats(fd, &ctx.cur_alloc, &ctx.cur_items,
696 		    &ctx.cur_stats, &ctx.cur_time, &ctx.flags) != 0)
697 			errx(1, "error returned from getstats()");
698 
699 		switch(ctx.mode) {
700 		case CTLSTAT_MODE_STANDARD:
701 			ctlstat_standard(&ctx);
702 			break;
703 		case CTLSTAT_MODE_DUMP:
704 			ctlstat_dump(&ctx);
705 			break;
706 		case CTLSTAT_MODE_JSON:
707 			ctlstat_json(&ctx);
708 			break;
709 		default:
710 			break;
711 		}
712 
713 		fprintf(stdout, "\n");
714 		ctx.flags &= ~CTLSTAT_FLAG_FIRST_RUN;
715 		if (count != 1)
716 			sleep(waittime);
717 		if (count > 0)
718 			count--;
719 	}
720 
721 	exit (retval);
722 }
723 
724 /*
725  * vim: ts=8
726  */
727