]> git.saurik.com Git - apple/system_cmds.git/blob - iostat.tproj/iostat.c
system_cmds-230.tar.gz
[apple/system_cmds.git] / iostat.tproj / iostat.c
1 /*
2 * Copyright (c) 1999 Apple Computer, Inc. All rights reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
6 * "Portions Copyright (c) 1999 Apple Computer, Inc. All Rights
7 * Reserved. This file contains Original Code and/or Modifications of
8 * Original Code as defined in and that are subject to the Apple Public
9 * Source License Version 1.0 (the 'License'). You may not use this file
10 * except in compliance with the License. Please obtain a copy of the
11 * License at http://www.apple.com/publicsource and read it before using
12 * this file.
13 *
14 * The Original Code and all software distributed under the License are
15 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
16 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
17 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT. Please see the
19 * License for the specific language governing rights and limitations
20 * under the License."
21 *
22 * @APPLE_LICENSE_HEADER_END@
23 */
24 /*
25 * Copyright (c) 1997, 1998, 2000, 2001 Kenneth D. Merry
26 * All rights reserved.
27 *
28 * Redistribution and use in source and binary forms, with or without
29 * modification, are permitted provided that the following conditions
30 * are met:
31 * 1. Redistributions of source code must retain the above copyright
32 * notice, this list of conditions and the following disclaimer.
33 * 2. Redistributions in binary form must reproduce the above copyright
34 * notice, this list of conditions and the following disclaimer in the
35 * documentation and/or other materials provided with the distribution.
36 * 3. The name of the author may not be used to endorse or promote products
37 * derived from this software without specific prior written permission.
38 *
39 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
40 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
41 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
42 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
43 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
44 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
45 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
46 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
47 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
48 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
49 * SUCH DAMAGE.
50 *
51 * $FreeBSD: src/usr.sbin/iostat/iostat.c,v 1.22 2001/09/01 07:40:19 kris Exp $
52 */
53 /*
54 * Parts of this program are derived from the original FreeBSD iostat
55 * program:
56 */
57 /*-
58 * Copyright (c) 1986, 1991, 1993
59 * The Regents of the University of California. All rights reserved.
60 *
61 * Redistribution and use in source and binary forms, with or without
62 * modification, are permitted provided that the following conditions
63 * are met:
64 * 1. Redistributions of source code must retain the above copyright
65 * notice, this list of conditions and the following disclaimer.
66 * 2. Redistributions in binary form must reproduce the above copyright
67 * notice, this list of conditions and the following disclaimer in the
68 * documentation and/or other materials provided with the distribution.
69 * 3. All advertising materials mentioning features or use of this software
70 * must display the following acknowledgement:
71 * This product includes software developed by the University of
72 * California, Berkeley and its contributors.
73 * 4. Neither the name of the University nor the names of its contributors
74 * may be used to endorse or promote products derived from this software
75 * without specific prior written permission.
76 *
77 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
78 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
79 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
80 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
81 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
82 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
83 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
84 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
85 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
86 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
87 * SUCH DAMAGE.
88 */
89 /*
90 * Ideas for the new iostat statistics output modes taken from the NetBSD
91 * version of iostat:
92 */
93 /*
94 * Copyright (c) 1996 John M. Vinopal
95 * All rights reserved.
96 *
97 * Redistribution and use in source and binary forms, with or without
98 * modification, are permitted provided that the following conditions
99 * are met:
100 * 1. Redistributions of source code must retain the above copyright
101 * notice, this list of conditions and the following disclaimer.
102 * 2. Redistributions in binary form must reproduce the above copyright
103 * notice, this list of conditions and the following disclaimer in the
104 * documentation and/or other materials provided with the distribution.
105 * 3. All advertising materials mentioning features or use of this software
106 * must display the following acknowledgement:
107 * This product includes software developed for the NetBSD Project
108 * by John M. Vinopal.
109 * 4. The name of the author may not be used to endorse or promote products
110 * derived from this software without specific prior written permission.
111 *
112 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
113 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
114 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
115 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
116 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
117 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
118 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
119 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
120 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
121 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
122 * SUCH DAMAGE.
123 */
124
125 #define IOKIT 1 /* to get io_name_t in device_types.h */
126
127 #include <sys/param.h>
128 #include <sys/sysctl.h>
129
130 #include <CoreFoundation/CoreFoundation.h>
131 #include <IOKit/IOKitLib.h>
132 #include <IOKit/storage/IOBlockStorageDriver.h>
133 #include <IOKit/storage/IOMedia.h>
134 #include <IOKit/IOBSD.h>
135
136 #include <err.h>
137 #include <signal.h>
138 #include <stdio.h>
139 #include <stdlib.h>
140 #include <string.h>
141 #include <unistd.h>
142
143 #define MAXDRIVES 16 /* most drives we will record */
144 #define MAXDRIVENAME 31 /* largest drive name we allow */
145
146 struct drivestats {
147 io_registry_entry_t driver;
148 char name[MAXDRIVENAME + 1];
149 u_int64_t blocksize;
150 u_int64_t total_bytes;
151 u_int64_t total_transfers;
152 u_int64_t total_time;
153 };
154
155 static struct drivestats drivestat[MAXDRIVES];
156
157 static struct timeval cur_time, last_time;
158
159 struct statinfo {
160 long tk_nin;
161 long tk_nout;
162 host_cpu_load_info_data_t load;
163 };
164
165 static struct statinfo cur, last;
166
167 static mach_port_t host_priv_port;
168 static mach_port_t masterPort;
169
170 static int num_devices;
171 static int maxshowdevs;
172 static int dflag = 0, Iflag = 0, Cflag = 0, Tflag = 0, oflag = 0, Kflag = 0;
173 static volatile sig_atomic_t phdr_flag = 0;
174
175 /* local function declarations */
176 static void usage(void);
177 static void phdr(int signo);
178 static void do_phdr();
179 static void devstats(int perf_select, long double etime, int havelast);
180 static void cpustats(void);
181 static int readvar(const char *name, void *ptr, size_t len);
182
183 static int record_all_devices(void);
184 static int record_one_device(char *name);
185 static int record_device(io_registry_entry_t drive);
186
187 static long double compute_etime(struct timeval cur_time,
188 struct timeval prev_time);
189
190 static void
191 usage(void)
192 {
193 /*
194 * We also support the following 'traditional' syntax:
195 * iostat [drives] [wait [count]]
196 * This isn't mentioned in the man page, or the usage statement,
197 * but it is supported.
198 */
199 fprintf(stderr, "usage: iostat [-CdIKoT?] [-c count] [-n devs]\n"
200 "\t [-w wait] [drives]\n");
201 }
202
203 int
204 main(int argc, char **argv)
205 {
206 int c;
207 int hflag = 0, cflag = 0, wflag = 0, nflag = 0;
208 int count = 0, waittime = 0;
209 int headercount;
210 int num_devices_specified;
211 int havelast = 0;
212
213 maxshowdevs = 3;
214
215 while ((c = getopt(argc, argv, "c:CdIKM:n:oTw:?")) != -1) {
216 switch(c) {
217 case 'c':
218 cflag++;
219 count = atoi(optarg);
220 if (count < 1)
221 errx(1, "count %d is < 1", count);
222 break;
223 case 'C':
224 Cflag++;
225 break;
226 case 'd':
227 dflag++;
228 break;
229 case 'I':
230 Iflag++;
231 break;
232 case 'K':
233 Kflag++;
234 break;
235 case 'n':
236 nflag++;
237 maxshowdevs = atoi(optarg);
238 if (maxshowdevs < 0)
239 errx(1, "number of devices %d is < 0",
240 maxshowdevs);
241 break;
242 case 'o':
243 oflag++;
244 break;
245 case 'T':
246 Tflag++;
247 break;
248 case 'w':
249 wflag++;
250 waittime = atoi(optarg);
251 if (waittime < 1)
252 errx(1, "wait time is < 1");
253 break;
254 default:
255 usage();
256 exit(1);
257 break;
258 }
259 }
260
261 argc -= optind;
262 argv += optind;
263
264 /*
265 * Get the Mach private port.
266 */
267 host_priv_port = mach_host_self();
268
269 /*
270 * Get the I/O Kit communication handle.
271 */
272 IOMasterPort(bootstrap_port, &masterPort);
273
274 /*
275 * Make sure Tflag and/or Cflag are set if dflag == 0. If dflag is
276 * greater than 0, they may be 0 or non-zero.
277 */
278 if (dflag == 0) {
279 Cflag = 1;
280 Tflag = 1;
281 }
282
283 /*
284 * Figure out how many devices we should display if not given
285 * an explicit value.
286 */
287 if (nflag == 0) {
288 if (oflag > 0) {
289 if ((dflag > 0) && (Cflag == 0) && (Tflag == 0))
290 maxshowdevs = 5;
291 else if ((dflag > 0) && (Tflag > 0) && (Cflag == 0))
292 maxshowdevs = 5;
293 else
294 maxshowdevs = 4;
295 } else {
296 if ((dflag > 0) && (Cflag == 0))
297 maxshowdevs = 4;
298 else
299 maxshowdevs = 3;
300 }
301 }
302
303 /*
304 * If the user specified any devices on the command line, record
305 * them for monitoring.
306 */
307 for (num_devices_specified = 0; *argv; ++argv) {
308 if (isdigit(**argv))
309 break;
310 if (record_one_device(*argv))
311 errx(1, "can't record '%s' for monitoring");
312 num_devices_specified++;
313 }
314 if (nflag == 0 && maxshowdevs < num_devices_specified)
315 maxshowdevs = num_devices_specified;
316
317 /* if no devices were specified, pick them ourselves */
318 if ((num_devices_specified == 0) && record_all_devices())
319 err(1, "can't find any devices to display");
320
321 /*
322 * Look for the traditional wait time and count arguments.
323 */
324 if (*argv) {
325 waittime = atoi(*argv);
326
327 /* Let the user know he goofed, but keep going anyway */
328 if (wflag != 0)
329 warnx("discarding previous wait interval, using"
330 " %d instead", waittime);
331 wflag++;
332
333 if (*++argv) {
334 count = atoi(*argv);
335 if (cflag != 0)
336 warnx("discarding previous count, using %d"
337 " instead", count);
338 cflag++;
339 } else
340 count = -1;
341 }
342
343 /*
344 * If the user specified a count, but not an interval, we default
345 * to an interval of 1 second.
346 */
347 if ((wflag == 0) && (cflag > 0))
348 waittime = 1;
349
350 /*
351 * If the user specified a wait time, but not a count, we want to
352 * go on ad infinitum. This can be redundant if the user uses the
353 * traditional method of specifying the wait, since in that case we
354 * already set count = -1 above. Oh well.
355 */
356 if ((wflag > 0) && (cflag == 0))
357 count = -1;
358
359 cur.tk_nout = 0;
360 cur.tk_nin = 0;
361
362 /*
363 * Set the busy time to the system boot time, so the stats are
364 * calculated since system boot.
365 */
366 if (readvar("kern.boottime", &cur_time, sizeof(cur_time)) != 0)
367 exit(1);
368
369 /*
370 * If the user stops the program (control-Z) and then resumes it,
371 * print out the header again.
372 */
373 (void)signal(SIGCONT, phdr);
374
375 for (headercount = 1;;) {
376 long tmp;
377 long double etime;
378
379 if (Tflag > 0) {
380 if ((readvar("kern.tty_nin", &cur.tk_nin,
381 sizeof(cur.tk_nin)) != 0)
382 || (readvar("kern.tty_nout",
383 &cur.tk_nout, sizeof(cur.tk_nout))!= 0)) {
384 Tflag = 0;
385 warnx("disabling TTY statistics");
386 }
387 }
388
389 if (phdr_flag) {
390 phdr_flag = 0;
391 do_phdr();
392 }
393
394 if (!--headercount) {
395 do_phdr();
396 headercount = 20;
397 }
398
399 last_time = cur_time;
400 gettimeofday(&cur_time, NULL);
401
402 if (Tflag > 0) {
403 tmp = cur.tk_nin;
404 cur.tk_nin -= last.tk_nin;
405 last.tk_nin = tmp;
406 tmp = cur.tk_nout;
407 cur.tk_nout -= last.tk_nout;
408 last.tk_nout = tmp;
409 }
410
411 etime = compute_etime(cur_time, last_time);
412
413 if (etime == 0.0)
414 etime = 1.0;
415
416 if (Tflag > 0)
417 printf("%4.0Lf%5.0Lf", cur.tk_nin / etime,
418 cur.tk_nout / etime);
419
420 devstats(hflag, etime, havelast);
421
422 if (Cflag > 0)
423 cpustats();
424
425 printf("\n");
426 fflush(stdout);
427
428 if (count >= 0 && --count <= 0)
429 break;
430
431 sleep(waittime);
432 havelast = 1;
433 }
434
435 exit(0);
436 }
437
438 static void
439 phdr(int signo)
440 {
441
442 phdr_flag = 1;
443 }
444
445 static void
446 do_phdr()
447 {
448 register int i;
449
450 if (Tflag > 0)
451 (void)printf(" tty");
452
453 for (i = 0; (i < num_devices); i++){
454 if (oflag > 0)
455 (void)printf("%12.6s ", drivestat[i].name);
456 else
457 printf("%15.6s ", drivestat[i].name);
458 }
459
460 if (Cflag > 0)
461 (void)printf(" cpu\n");
462 else
463 (void)printf("\n");
464
465 if (Tflag > 0)
466 (void)printf(" tin tout");
467
468 for (i=0; i < num_devices; i++){
469 if (oflag > 0) {
470 if (Iflag == 0)
471 (void)printf(" sps tps msps ");
472 else
473 (void)printf(" blk xfr msps ");
474 } else {
475 if (Iflag == 0)
476 printf(" KB/t tps MB/s ");
477 else
478 printf(" KB/t xfrs MB ");
479 }
480 }
481
482 if (Cflag > 0)
483 (void)printf(" us sy id\n");
484 else
485 printf("\n");
486 }
487
488 static void
489 devstats(int perf_select, long double etime, int havelast)
490 {
491 CFNumberRef number;
492 CFDictionaryRef properties;
493 CFDictionaryRef statistics;
494 long double transfers_per_second;
495 long double kb_per_transfer, mb_per_second;
496 u_int64_t value;
497 u_int64_t total_bytes, total_transfers, total_blocks, total_time;
498 u_int64_t interval_bytes, interval_transfers, interval_blocks;
499 u_int64_t interval_time;
500 long double interval_mb;
501 long double blocks_per_second, ms_per_transaction;
502 kern_return_t status;
503 int i;
504
505 for (i = 0; i < num_devices; i++) {
506
507 /*
508 * If the drive goes away, we may not get any properties
509 * for it. So take some defaults.
510 */
511 total_bytes = 0;
512 total_transfers = 0;
513 total_time = 0;
514
515 /* get drive properties */
516 status = IORegistryEntryCreateCFProperties(drivestat[i].driver,
517 (CFMutableDictionaryRef *)&properties,
518 kCFAllocatorDefault,
519 kNilOptions);
520 if (status != KERN_SUCCESS)
521 err(1, "device has no properties");
522
523 /* get statistics from properties */
524 statistics = (CFDictionaryRef)CFDictionaryGetValue(properties,
525 CFSTR(kIOBlockStorageDriverStatisticsKey));
526 if (statistics) {
527
528 /*
529 * Get I/O volume.
530 */
531 if ((number = (CFNumberRef)CFDictionaryGetValue(statistics,
532 CFSTR(kIOBlockStorageDriverStatisticsBytesReadKey)))) {
533 CFNumberGetValue(number, kCFNumberSInt64Type, &value);
534 total_bytes += value;
535 }
536 if ((number = (CFNumberRef)CFDictionaryGetValue(statistics,
537 CFSTR(kIOBlockStorageDriverStatisticsBytesWrittenKey)))) {
538 CFNumberGetValue(number, kCFNumberSInt64Type, &value);
539 total_bytes += value;
540 }
541
542 /*
543 * Get I/O counts.
544 */
545 if ((number = (CFNumberRef)CFDictionaryGetValue(statistics,
546 CFSTR(kIOBlockStorageDriverStatisticsReadsKey)))) {
547 CFNumberGetValue(number, kCFNumberSInt64Type, &value);
548 total_transfers += value;
549 }
550 if ((number = (CFNumberRef)CFDictionaryGetValue(statistics,
551 CFSTR(kIOBlockStorageDriverStatisticsWritesKey)))) {
552 CFNumberGetValue(number, kCFNumberSInt64Type, &value);
553 total_transfers += value;
554 }
555
556 /*
557 * Get I/O time.
558 */
559 if ((number = (CFNumberRef)CFDictionaryGetValue(statistics,
560 CFSTR(kIOBlockStorageDriverStatisticsLatentReadTimeKey)))) {
561 CFNumberGetValue(number, kCFNumberSInt64Type, &value);
562 total_time += value;
563 }
564 if ((number = (CFNumberRef)CFDictionaryGetValue(statistics,
565 CFSTR(kIOBlockStorageDriverStatisticsLatentWriteTimeKey)))) {
566 CFNumberGetValue(number, kCFNumberSInt64Type, &value);
567 total_time += value;
568 }
569
570 }
571 CFRelease(properties);
572
573 /*
574 * Compute delta values and stats.
575 */
576 interval_bytes = total_bytes - drivestat[i].total_bytes;
577 interval_transfers = total_transfers
578 - drivestat[i].total_transfers;
579 interval_time = total_time - drivestat[i].total_time;
580
581 /* update running totals, only once for -I */
582 if ((Iflag == 0) || (drivestat[i].total_bytes == 0)) {
583 drivestat[i].total_bytes = total_bytes;
584 drivestat[i].total_transfers = total_transfers;
585 drivestat[i].total_time = total_time;
586 }
587
588 interval_blocks = interval_bytes / drivestat[i].blocksize;
589 total_blocks = total_bytes / drivestat[i].blocksize;
590
591 blocks_per_second = interval_blocks / etime;
592 transfers_per_second = interval_transfers / etime;
593 mb_per_second = (interval_bytes / etime) / (1024 * 1024);
594
595 kb_per_transfer = (interval_transfers > 0) ?
596 ((long double)interval_bytes / interval_transfers)
597 / 1024 : 0;
598
599 /* times are in nanoseconds, convert to milliseconds */
600 ms_per_transaction = (interval_transfers > 0) ?
601 ((long double)interval_time / interval_transfers)
602 / 1000 : 0;
603
604 if (Kflag)
605 total_blocks = total_blocks * drivestat[i].blocksize
606 / 1024;
607
608 if (oflag > 0) {
609 int msdig = (ms_per_transaction < 100.0) ? 1 : 0;
610
611 if (Iflag == 0)
612 printf("%4.0Lf%4.0Lf%5.*Lf ",
613 blocks_per_second,
614 transfers_per_second,
615 msdig,
616 ms_per_transaction);
617 else
618 printf("%4.1qu%4.1qu%5.*Lf ",
619 interval_blocks,
620 interval_transfers,
621 msdig,
622 ms_per_transaction);
623 } else {
624 if (Iflag == 0)
625 printf(" %5.2Lf %3.0Lf %5.2Lf ",
626 kb_per_transfer,
627 transfers_per_second,
628 mb_per_second);
629 else {
630 interval_mb = interval_bytes;
631 interval_mb /= 1024 * 1024;
632
633 printf(" %5.2Lf %3.1qu %5.2Lf ",
634 kb_per_transfer,
635 interval_transfers,
636 interval_mb);
637 }
638 }
639 }
640 }
641
642 static void
643 cpustats(void)
644 {
645 mach_msg_type_number_t count;
646 kern_return_t status;
647 double time;
648
649 /*
650 * Get CPU usage counters.
651 */
652 count = HOST_CPU_LOAD_INFO_COUNT;
653 status = host_statistics(host_priv_port, HOST_CPU_LOAD_INFO,
654 (host_info_t)&cur.load, &count);
655 if (status != KERN_SUCCESS)
656 errx(1, "couldn't fetch CPU stats");
657
658 /*
659 * Make 'cur' fields relative, update 'last' fields to current values,
660 * calculate total elapsed time.
661 */
662 time = 0.0;
663 cur.load.cpu_ticks[CPU_STATE_USER]
664 -= last.load.cpu_ticks[CPU_STATE_USER];
665 last.load.cpu_ticks[CPU_STATE_USER]
666 += cur.load.cpu_ticks[CPU_STATE_USER];
667 time += cur.load.cpu_ticks[CPU_STATE_USER];
668 cur.load.cpu_ticks[CPU_STATE_SYSTEM]
669 -= last.load.cpu_ticks[CPU_STATE_SYSTEM];
670 last.load.cpu_ticks[CPU_STATE_SYSTEM]
671 += cur.load.cpu_ticks[CPU_STATE_SYSTEM];
672 time += cur.load.cpu_ticks[CPU_STATE_SYSTEM];
673 cur.load.cpu_ticks[CPU_STATE_IDLE]
674 -= last.load.cpu_ticks[CPU_STATE_IDLE];
675 last.load.cpu_ticks[CPU_STATE_IDLE]
676 += cur.load.cpu_ticks[CPU_STATE_IDLE];
677 time += cur.load.cpu_ticks[CPU_STATE_IDLE];
678
679 /*
680 * Print times.
681 */
682 printf("%3.0f",
683 rint(100. * cur.load.cpu_ticks[CPU_STATE_USER]
684 / (time ? time : 1)));
685 printf("%3.0f",
686 rint(100. * cur.load.cpu_ticks[CPU_STATE_SYSTEM]
687 / (time ? time : 1)));
688 printf("%3.0f",
689 rint(100. * cur.load.cpu_ticks[CPU_STATE_IDLE]
690 / (time ? time : 1)));
691 }
692
693 static int
694 readvar(const char *name, void *ptr, size_t len)
695 {
696 int oid[4];
697 int oidlen;
698
699 size_t nlen = len;
700
701 if (sysctlbyname(name, ptr, &nlen, NULL, 0) == -1) {
702 if (errno != ENOENT) {
703 warn("sysctl(%s) failed", name);
704 return (1);
705 }
706 /*
707 * XXX fallback code to deal with systems where
708 * sysctlbyname can't find "old" OIDs, should be removed.
709 */
710 if (!strcmp(name, "kern.boottime")) {
711 oid[0] = CTL_KERN;
712 oid[1] = KERN_BOOTTIME;
713 oidlen = 2;
714 } else {
715 warn("sysctl(%s) failed", name);
716 return (1);
717 }
718
719 nlen = len;
720 if (sysctl(oid, oidlen, ptr, &nlen, NULL, 0) == -1) {
721 warn("sysctl(%s) failed", name);
722 return (1);
723 }
724 }
725 if (nlen != len) {
726 warnx("sysctl(%s): expected %lu, got %lu", name,
727 (unsigned long)len, (unsigned long)nlen);
728 return (1);
729 }
730 return (0);
731 }
732
733 static long double
734 compute_etime(struct timeval cur_time, struct timeval prev_time)
735 {
736 struct timeval busy_time;
737 u_int64_t busy_usec;
738 long double etime;
739
740 timersub(&cur_time, &prev_time, &busy_time);
741
742 busy_usec = busy_time.tv_sec;
743 busy_usec *= 1000000;
744 busy_usec += busy_time.tv_usec;
745 etime = busy_usec;
746 etime /= 1000000;
747
748 return(etime);
749 }
750
751 /*
752 * Record all "whole" IOMedia objects as being interesting.
753 */
754 static int
755 record_all_devices(void)
756 {
757 io_iterator_t drivelist;
758 io_registry_entry_t drive;
759 CFMutableDictionaryRef match;
760 int error, ndrives;
761 kern_return_t status;
762
763 /*
764 * Get an iterator for IOMedia objects.
765 */
766 match = IOServiceMatching("IOMedia");
767 CFDictionaryAddValue(match, CFSTR(kIOMediaWholeKey), kCFBooleanTrue);
768 status = IOServiceGetMatchingServices(masterPort, match, &drivelist);
769 if (status != KERN_SUCCESS)
770 errx(1, "couldn't match whole IOMedia devices");
771
772 /*
773 * Scan all of the IOMedia objects, and for each
774 * object that has a parent IOBlockStorageDriver, save
775 * the object's name and the parent (from which we can
776 * fetch statistics).
777 *
778 * XXX What about RAID devices?
779 */
780 error = 1;
781 ndrives = 0;
782 while ((drive = IOIteratorNext(drivelist))
783 && (ndrives < maxshowdevs)) {
784 if (!record_device(drive)) {
785 error = 0;
786 ndrives++;
787 }
788 IOObjectRelease(drive);
789 }
790 IOObjectRelease(drivelist);
791
792 return(error);
793 }
794
795 /*
796 * Try to record the named device as interesting. It
797 * must be an IOMedia device.
798 */
799 static int
800 record_one_device(char *name)
801 {
802 io_iterator_t drivelist;
803 io_registry_entry_t drive;
804 kern_return_t status;
805
806 /*
807 * Find the device.
808 */
809 status = IOServiceGetMatchingServices(masterPort,
810 IOBSDNameMatching(masterPort, kNilOptions, name),
811 &drivelist);
812 if (status != KERN_SUCCESS)
813 errx(1, "couldn't match '%s'", name);
814
815 /*
816 * Get the first match (should only be one)
817 */
818 if ((drive = IOIteratorNext(drivelist)) == NULL)
819 errx(1, "'%s' not found", name);
820 if (!IOObjectConformsTo(drive, "IOMedia"))
821 errx(1, "'%s' is not a storage device", name);
822
823 /*
824 * Record the device.
825 */
826 if (record_device(drive))
827 errx(1, "could not record '%s' for monitoring", name);
828
829 IOObjectRelease(drive);
830 IOObjectRelease(drivelist);
831
832 return(0);
833 }
834
835 /*
836 * Determine whether an IORegistryEntry refers to a valid
837 * I/O device, and if so, record it.
838 */
839 static int
840 record_device(io_registry_entry_t drive)
841 {
842 io_registry_entry_t parent;
843 CFDictionaryRef properties;
844 CFStringRef name;
845 CFNumberRef number;
846 kern_return_t status;
847
848 /* get drive's parent */
849 status = IORegistryEntryGetParentEntry(drive,
850 kIOServicePlane, &parent);
851 if (status != KERN_SUCCESS)
852 errx(1, "device has no parent");
853 if (IOObjectConformsTo(parent, "IOBlockStorageDriver")) {
854 drivestat[num_devices].driver = parent;
855
856 /* get drive properties */
857 status = IORegistryEntryCreateCFProperties(drive,
858 (CFMutableDictionaryRef *)&properties,
859 kCFAllocatorDefault,
860 kNilOptions);
861 if (status != KERN_SUCCESS)
862 errx(1, "device has no properties");
863
864 /* get name from properties */
865 name = (CFStringRef)CFDictionaryGetValue(properties,
866 CFSTR(kIOBSDNameKey));
867 CFStringGetCString(name, drivestat[num_devices].name,
868 MAXDRIVENAME, CFStringGetSystemEncoding());
869
870 /* get blocksize from properties */
871 number = (CFNumberRef)CFDictionaryGetValue(properties,
872 CFSTR(kIOMediaPreferredBlockSizeKey));
873 CFNumberGetValue(number, kCFNumberSInt64Type,
874 &drivestat[num_devices].blocksize);
875
876 /* clean up, return success */
877 CFRelease(properties);
878 num_devices++;
879 return(0);
880 }
881
882 /* failed, don't keep parent */
883 IOObjectRelease(parent);
884 return(1);
885 }