summaryrefslogtreecommitdiff
path: root/usr/src/cmd/sa/sar.c
blob: 64f8cbdb84b0f5d77b96106d4abf779dcf18e119 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

/*	Copyright (c) 1984, 1986, 1987, 1988, 1989 AT&T	*/
/*	  All Rights Reserved  	*/


#pragma ident	"%Z%%M%	%I%	%E% SMI"

/*
 * sar generates a report either from an input data file or by invoking sadc to
 * read system activity counters at the specified intervals.
 *
 * usage:  sar [-ubdycwaqvmpgrkA] [-o file] t [n]
 *	   sar [-ubdycwaqvmpgrkA][-s hh:mm][-e hh:mm][-i ss][-f file]
 */

#include <sys/param.h>
#include <sys/stat.h>
#include <sys/sysinfo.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/utsname.h>
#include <sys/wait.h>

#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <signal.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>

#include "sa.h"

#define	PGTOBLK(x)	((x) * (pagesize >> 9))
#define	BLKTOPG(x)	((x) / (pagesize >> 9))
#define	BLKS(x)		((x) >> 9)

static void	prpass(int);
static void	prtopt(void);
static void	prtavg(void);
static void	prttim(void);
static void	prtmachid(void);
static void	prthdg(void);
static void	tsttab(void);
static void	update_counters(void);
static void	usage(void);
static void	fail(int, char *, ...);
static void	safe_zalloc(void **, int, int);
static int	safe_read(int, void *, size_t);
static void	safe_write(int, void *, size_t);
static int	safe_strtoi(char const *, char *);
static void	ulong_delta(uint64_t *, uint64_t *, uint64_t *, uint64_t *,
	int, int);
static float	denom(float);
static float	freq(float, float);

static struct sa64	nx, ox, ax, dx;
static iodevinfo_t	*nxio, *oxio, *axio, *dxio;
static struct tm	*curt, args, arge;

static int	sflg, eflg, iflg, oflg, fflg;
static int	realtime, passno = 0, do_disk;
static int	t = 0, n = 0, lines = 0;
static int	hz;
static int	niodevs;
static int	tabflg;
static char	options[30], fopt[30];
static float	tdiff, sec_diff, totsec_diff = 0.0, percent;
static float	start_time, end_time, isec;
static int 	fin, fout;
static pid_t	childid;
static int	pipedes[2];
static char	arg1[10], arg2[10];
static int	pagesize;

/*
 * To avoid overflow in the kmem allocation data, declare a copy of the
 * main kmeminfo_t type with larger data types. Use this for storing
 * the data held to display average values
 */
static struct kmeminfo_l
{
	u_longlong_t	km_mem[KMEM_NCLASS];
	u_longlong_t	km_alloc[KMEM_NCLASS];
	u_longlong_t	km_fail[KMEM_NCLASS];
} kmi;

int
main(int argc, char **argv)
{
	char    flnm[PATH_MAX], ofile[PATH_MAX];
	char	ccc;
	time_t	temp;
	int	i, jj = 0;

	pagesize = sysconf(_SC_PAGESIZE);

	/*
	 * Process options with arguments and pack options
	 * without arguments.
	 */
	while ((i = getopt(argc, argv, "ubdycwaqvmpgrkAo:s:e:i:f:")) != EOF)
		switch (ccc = (char)i) {
		    case 'o':
			oflg++;
			if (strlcpy(ofile, optarg, sizeof (ofile)) >=
			    sizeof (ofile)) {
				fail(2, "-o filename is too long: %s", optarg);
			}
			break;
		    case 's':
			if (sscanf(optarg, "%d:%d:%d",
			    &args.tm_hour, &args.tm_min, &args.tm_sec) < 1)
				fail(0, "-%c %s -- illegal option argument",
				    ccc, optarg);
			else {
				sflg++,
				start_time = args.tm_hour*3600.0 +
				    args.tm_min*60.0 +
				    args.tm_sec;
			}
			break;
		    case 'e':
			if (sscanf(optarg, "%d:%d:%d",
			    &arge.tm_hour, &arge.tm_min, &arge.tm_sec) < 1)
				fail(0, "-%c %s -- illegal option argument",
				    ccc, optarg);
			else {
				eflg++;
				end_time = arge.tm_hour*3600.0 +
				    arge.tm_min*60.0 +
				    arge.tm_sec;
			}
			break;
		    case 'i':
			if (sscanf(optarg, "%f", &isec) < 1)
				fail(0, "-%c %s -- illegal option argument",
				    ccc, optarg);
			else {
				if (isec > 0.0)
					iflg++;
			}
			break;
		    case 'f':
			fflg++;
			if (strlcpy(flnm, optarg, sizeof (flnm)) >=
			    sizeof (ofile)) {
				fail(2, "-f filename is too long: %s", optarg);
			}
			break;
		    case '?':
			usage();
			exit(1);
			break;
		default:

			/*
			 * Check for repeated options. To make sure
			 * that options[30] does not overflow.
			 */
			if (strchr(options, ccc) == NULL)
				(void) strncat(options, &ccc, 1);
			break;
		}

	/*
	 * Are starting and ending times consistent?
	 */
	if ((sflg) && (eflg) && (end_time <= start_time))
		fail(0, "ending time <= starting time");

	/*
	 * Determine if t and n arguments are given, and whether to run in real
	 * time or from a file.
	 */
	switch (argc - optind) {
	    case 0:		/*   Get input data from file   */
		if (fflg == 0) {
			temp = time(NULL);
			curt = localtime(&temp);
			(void) snprintf(flnm, PATH_MAX, "/var/adm/sa/sa%.2d",
			    curt->tm_mday);
		}
		if ((fin = open(flnm, 0)) == -1)
			fail(1, "can't open %s", flnm);
		break;
	    case 1:		/*   Real time data; one cycle   */
		realtime++;
		t = safe_strtoi(argv[optind], "invalid sampling interval");
		n = 2;
		break;
	    case 2:		/*   Real time data; specified cycles   */
	default:
		realtime++;
		t = safe_strtoi(argv[optind], "invalid sampling interval");
		n = 1 + safe_strtoi(argv[optind+1], "invalid sample count");
		break;
	}

	/*
	 * "u" is the default option, which displays CPU utilization.
	 */
	if (strlen(options) == 0)
		(void) strcpy(options, "u");

	/*
	 * "A" means all data options.
	 */
	if (strchr(options, 'A') != NULL)
		(void) strcpy(options, "udqbwcayvmpgrk");

	if (realtime) {
		/*
		 * Get input data from sadc via pipe.
		 */
		if (t <= 0)
			fail(0, "sampling interval t <= 0 sec");
		if (n < 2)
			fail(0, "number of sample intervals n <= 0");
		(void) sprintf(arg1, "%d", t);
		(void) sprintf(arg2, "%d", n);
		if (pipe(pipedes) == -1)
			fail(1, "pipe failed");
		if ((childid = fork()) == 0) {
			/*
			 * Child:  shift pipedes[write] to stdout,
			 * and close the pipe entries.
			 */
			(void) dup2(pipedes[1], 1);
			if (pipedes[0] != 1)
				(void) close(pipedes[0]);
			if (pipedes[1] != 1)
				(void) close(pipedes[1]);

			if (execlp("/usr/lib/sa/sadc",
			    "/usr/lib/sa/sadc", arg1, arg2, 0) == -1)
				fail(1, "exec of /usr/lib/sa/sadc failed");
		} else if (childid == -1) {
			fail(1, "Could not fork to exec sadc");
		}
		/*
		 * Parent:  close unused output.
		 */
		fin = pipedes[0];
		(void) close(pipedes[1]);
	}

	if (oflg) {
		if (strcmp(ofile, flnm) == 0)
			fail(0, "output file name same as input file name");
		fout = creat(ofile, 00644);
	}

	hz = sysconf(_SC_CLK_TCK);

	nxio = oxio = dxio = axio = NULL;

	if (realtime) {
		/*
		 * Make single pass, processing all options.
		 */
		(void) strcpy(fopt, options);
		passno++;
		prpass(realtime);
		(void) kill(childid, SIGINT);
		(void) wait(NULL);
	} else {
		/*
		 * Make multiple passes, one for each option.
		 */
		while (strlen(strncpy(fopt, &options[jj++], 1))) {
			if (lseek(fin, 0, SEEK_SET) == (off_t)-1)
				fail(0, "lseek failed");
			passno++;
			prpass(realtime);
		}
	}

	return (0);
}

/*
 * Convert array of 32-bit uints to 64-bit uints
 */
static void
convert_32to64(uint64_t *dst, uint_t *src, int size)
{
	for (; size > 0; size--)
		*dst++ = (uint64_t)(*src++);
}

/*
 * Read records from input, classify, and decide on printing.
 */
static void
prpass(int input_pipe)
{
	size_t size;
	int i, j, state_change, recno = 0;
	kid_t kid;
	float trec, tnext = 0;
	ulong_t old_niodevs = 0, prev_niodevs = 0;
	iodevinfo_t *aio, *dio, *oio;
	struct stat in_stat;
	struct sa tx;
	uint64_t ts, te; /* time interval start and end */

	do_disk = (strchr(fopt, 'd') != NULL);
	if (!input_pipe && fstat(fin, &in_stat) == -1)
		fail(1, "unable to stat data file");

	if (sflg)
		tnext = start_time;

	while (safe_read(fin, &tx, sizeof (struct sa))) {
		/*
		 * First, we convert 32bit tx to 64bit nx structure
		 * which is used later. Conversion could be done
		 * after initial operations, right before calculations,
		 * but it would introduce additional juggling with vars.
		 * Thus, we convert all data now, and don't care about
		 * tx any further.
		 */
		nx.valid = tx.valid;
		nx.ts = tx.ts;
		convert_32to64((uint64_t *)&nx.csi, (uint_t *)&tx.csi,
		    sizeof (tx.csi) / sizeof (uint_t));
		convert_32to64((uint64_t *)&nx.cvmi, (uint_t *)&tx.cvmi,
		    sizeof (tx.cvmi) / sizeof (uint_t));
		convert_32to64((uint64_t *)&nx.si, (uint_t *)&tx.si,
		    sizeof (tx.si) / sizeof (uint_t));
		(void) memcpy(&nx.vmi, &tx.vmi,
		    sizeof (tx) - (((char *)&tx.vmi) - ((char *)&tx)));
		/*
		 * sadc is the only utility used to generate sar data
		 * and it uses the valid field as follows:
		 * 0 - dummy record
		 * 1 - data record
		 * We can use this fact to improve sar's ability to detect
		 * bad data, since any value apart from 0 or 1 can be
		 * interpreted as invalid data.
		 */
		if (nx.valid != 0 && nx.valid != 1)
			fail(2, "data file not in sar format");
		state_change = 0;
		niodevs = nx.niodevs;
		/*
		 * niodevs has the value of current number of devices
		 * from nx structure.
		 *
		 * The following 'if' condition is to decide whether memory
		 * has to be allocated or not if already allocated memory is
		 * bigger or smaller than memory needed to store the current
		 * niodevs details in memory.
		 *
		 * when first while loop starts, pre_niodevs has 0 and then
		 * always get initialized to the current number of devices
		 * from nx.niodevs if it is different from previously read
		 * niodevs.
		 *
		 * if the current niodevs has the same value of previously
		 * allocated memory i.e, for prev_niodevs, it skips the
		 * following  'if' loop or otherwise it allocates memory for
		 * current devises (niodevs) and stores that value in
		 * prev_niodevs for next time when loop continues to read
		 * from the file.
		 */
		if (niodevs != prev_niodevs) {
			off_t curr_pos;
			/*
			 * The required buffer size must fit in a size_t.
			 */
			if (SIZE_MAX / sizeof (iodevinfo_t) < niodevs)
				fail(2, "insufficient address space to hold "
				    "%lu device records", niodevs);
			size = niodevs * sizeof (iodevinfo_t);
			prev_niodevs = niodevs;
			/*
			 * The data file must exceed this size to be valid.
			 */
			if (!input_pipe) {
			    if ((curr_pos = lseek(fin, 0, SEEK_CUR)) ==
				(off_t)-1)
				    fail(1, "lseek failed");
			    if (in_stat.st_size < curr_pos ||
				size > in_stat.st_size - curr_pos)
				    fail(2, "data file corrupt; specified size"
					"exceeds actual");
			}

			safe_zalloc((void **)&nxio, size, 1);
		}
		if (niodevs != old_niodevs)
			state_change = 1;
		for (i = 0; i < niodevs; i++) {
			if (safe_read(fin, &nxio[i], sizeof (iodevinfo_t)) == 0)
				fail(1, "premature end-of-file seen");
			if (i < old_niodevs &&
			    nxio[i].ks.ks_kid != oxio[i].ks.ks_kid)
				state_change = 1;
		}
		curt = localtime(&nx.ts);
		trec = curt->tm_hour * 3600.0 +
		    curt->tm_min * 60.0 +
		    curt->tm_sec;
		if ((recno == 0) && (trec < start_time))
			continue;
		if ((eflg) && (trec > end_time))
			break;
		if ((oflg) && (passno == 1)) {
			safe_write(fout, &nx, sizeof (struct sa));
			for (i = 0; i < niodevs; i++)
				safe_write(fout, &nxio[i],
				    sizeof (iodevinfo_t));
		}

		if (recno == 0) {
			if (passno == 1)
				prtmachid();

			prthdg();
			recno = 1;
			if ((iflg) && (tnext == 0))
				tnext = trec;
		}

		if (nx.valid == 0) {
			/*
			 * This dummy record signifies system restart
			 * New initial values of counters follow in next
			 * record.
			 */
			if (!realtime) {
				prttim();
				(void) printf("\tunix restarts\n");
				recno = 1;
				continue;
			}
		}
		if ((iflg) && (trec < tnext))
			continue;

		if (state_change) {
			/*
			 * Either the number of devices or the ordering of
			 * the kstats has changed.  We need to re-organise
			 * the layout of our avg/delta arrays so that we
			 * can cope with this in update_counters().
			 */
			size = niodevs * sizeof (iodevinfo_t);
			safe_zalloc((void *)&aio, size, 0);
			safe_zalloc((void *)&dio, size, 0);
			safe_zalloc((void *)&oio, size, 0);

			/*
			 * Loop through all the newly read iodev's, locate
			 * the corresponding entry in the old arrays and
			 * copy the entries into the same bucket of the
			 * new arrays.
			 */
			for (i = 0; i < niodevs; i++) {
				kid = nxio[i].ks.ks_kid;
				for (j = 0; j < old_niodevs; j++) {
					if (oxio[j].ks.ks_kid == kid) {
						oio[i] = oxio[j];
						aio[i] = axio[j];
						dio[i] = dxio[j];
					}
				}
			}

			free(axio);
			free(oxio);
			free(dxio);

			axio = aio;
			oxio = oio;
			dxio = dio;

			old_niodevs = niodevs;
		}

		if (recno++ > 1) {
			ts = ox.csi.cpu[0] + ox.csi.cpu[1] +
				ox.csi.cpu[2] + ox.csi.cpu[3];
			te = nx.csi.cpu[0] + nx.csi.cpu[1] +
				nx.csi.cpu[2] + nx.csi.cpu[3];
			tdiff = (float)(te - ts);
			sec_diff = tdiff / hz;
			percent = 100.0 / tdiff;

			/*
			 * If the CPU stat counters have rolled
			 * backward, this is our best indication that
			 * a CPU has been offlined.  We don't have
			 * enough data to compute a sensible delta, so
			 * toss out this interval, but compute the next
			 * interval's delta from these values.
			 */
			if (tdiff <= 0) {
				ox = nx;
				continue;
			}
			update_counters();
			prtopt();
			lines++;
			if (passno == 1)
				totsec_diff += sec_diff;
		}
		ox = nx;		/*  Age the data	*/
		(void) memcpy(oxio, nxio, niodevs * sizeof (iodevinfo_t));
		if (isec > 0)
			while (tnext <= trec)
				tnext += isec;
	}
	/*
	 * After this place, all functions are using niodevs to access the
	 * memory for device details. Here, old_niodevs has the correct value
	 * of memory allocated for storing device information. Since niodevs
	 * doesn't have correct value, sometimes, it was corrupting memory.
	 */
	niodevs = old_niodevs;
	if (lines > 1)
		prtavg();
	(void) memset(&ax, 0, sizeof (ax));	/* Zero out the accumulators. */
	(void) memset(&kmi, 0, sizeof (kmi));
	lines = 0;
	/*
	 * axio will not be allocated if the user specified -e or -s, and
	 * no records in the file fell inside the specified time range.
	 */
	if (axio) {
		(void) memset(axio, 0, niodevs * sizeof (iodevinfo_t));
	}
}

/*
 * Print time label routine.
 */
static void
prttim(void)
{
	curt = localtime(&nx.ts);
	(void) printf("%.2d:%.2d:%.2d", curt->tm_hour, curt->tm_min,
	    curt->tm_sec);
	tabflg = 1;
}

/*
 * Test if 8-spaces to be added routine.
 */
static void
tsttab(void)
{
	if (tabflg == 0)
		(void) printf("        ");
	else
		tabflg = 0;
}

/*
 * Print machine identification.
 */
static void
prtmachid(void)
{
	struct utsname name;

	(void) uname(&name);
	(void) printf("\n%s %s %s %s %s    %.2d/%.2d/%.4d\n",
	    name.sysname, name.nodename, name.release, name.version,
	    name.machine, curt->tm_mon + 1, curt->tm_mday,
	    curt->tm_year + 1900);
}

/*
 * Print report heading routine.
 */
static void
prthdg(void)
{
	int	jj = 0;
	char	ccc;

	(void) printf("\n");
	prttim();
	while ((ccc = fopt[jj++]) != NULL) {
		tsttab();
		switch (ccc) {
		    case 'u':
			(void) printf(" %7s %7s %7s %7s\n",
				"%usr",
				"%sys",
				"%wio",
				"%idle");
			break;
		    case 'b':
			(void) printf(" %7s %7s %7s %7s %7s %7s %7s %7s\n",
				"bread/s",
				"lread/s",
				"%rcache",
				"bwrit/s",
				"lwrit/s",
				"%wcache",
				"pread/s",
				"pwrit/s");
			break;
		    case 'd':
			(void) printf("   %-8.8s    %7s %7s %7s %7s %7s %7s\n",
				"device",
				"%busy",
				"avque",
				"r+w/s",
				"blks/s",
				"avwait",
				"avserv");
			break;
		    case 'y':
			(void) printf(" %7s %7s %7s %7s %7s %7s\n",
				"rawch/s",
				"canch/s",
				"outch/s",
				"rcvin/s",
				"xmtin/s",
				"mdmin/s");
			break;
		    case 'c':
			(void) printf(" %7s %7s %7s %7s %7s %7s %7s\n",
				"scall/s",
				"sread/s",
				"swrit/s",
				"fork/s",
				"exec/s",
				"rchar/s",
				"wchar/s");
			break;
		    case 'w':
			(void) printf(" %7s %7s %7s %7s %7s\n",
				"swpin/s",
				"bswin/s",
				"swpot/s",
				"bswot/s",
				"pswch/s");
			break;
		    case 'a':
			(void) printf(" %7s %7s %7s\n",
				"iget/s",
				"namei/s",
				"dirbk/s");
			break;
		    case 'q':
			(void) printf(" %7s %7s %7s %7s\n",
				"runq-sz",
				"%runocc",
				"swpq-sz",
				"%swpocc");
			break;
		    case 'v':
			(void) printf("  %s  %s  %s   %s\n",
				"proc-sz    ov",
				"inod-sz    ov",
				"file-sz    ov",
				"lock-sz");
			break;
		    case 'm':
			(void) printf(" %7s %7s\n",
				"msg/s",
				"sema/s");
			break;
		    case 'p':
			(void) printf(" %7s %7s %7s %7s %7s %7s\n",
				"atch/s",
				"pgin/s",
				"ppgin/s",
				"pflt/s",
				"vflt/s",
				"slock/s");
			break;
		    case 'g':
			(void) printf(" %8s %8s %8s %8s %8s\n",
				"pgout/s",
				"ppgout/s",
				"pgfree/s",
				"pgscan/s",
				"%ufs_ipf");
			break;
		    case 'r':
			(void) printf(" %7s %8s\n",
				"freemem",
				"freeswap");
			break;
		    case 'k':
			(void) printf(" %7s %7s %5s %7s %7s %5s %11s %5s\n",
				"sml_mem",
				"alloc",
				"fail",
				"lg_mem",
				"alloc",
				"fail",
				"ovsz_alloc",
				"fail");
			break;
		}
	}
	if (jj > 2 || do_disk)
		(void) printf("\n");
}

/*
 * compute deltas and update accumulators
 */
static void
update_counters(void)
{
	int i;
	iodevinfo_t *nio, *oio, *aio, *dio;

	ulong_delta((uint64_t *)&nx.csi, (uint64_t *)&ox.csi,
		(uint64_t *)&dx.csi, (uint64_t *)&ax.csi, 0, sizeof (ax.csi));
	ulong_delta((uint64_t *)&nx.si, (uint64_t *)&ox.si,
		(uint64_t *)&dx.si, (uint64_t *)&ax.si, 0, sizeof (ax.si));
	ulong_delta((uint64_t *)&nx.cvmi, (uint64_t *)&ox.cvmi,
		(uint64_t *)&dx.cvmi, (uint64_t *)&ax.cvmi, 0,
		sizeof (ax.cvmi));

	ax.vmi.freemem += dx.vmi.freemem = nx.vmi.freemem - ox.vmi.freemem;
	ax.vmi.swap_avail += dx.vmi.swap_avail =
		nx.vmi.swap_avail - ox.vmi.swap_avail;

	nio = nxio;
	oio = oxio;
	aio = axio;
	dio = dxio;
	for (i = 0; i < niodevs; i++) {
		aio->kios.wlastupdate += dio->kios.wlastupdate
			= nio->kios.wlastupdate - oio->kios.wlastupdate;
		aio->kios.reads += dio->kios.reads
			= nio->kios.reads - oio->kios.reads;
		aio->kios.writes += dio->kios.writes
			= nio->kios.writes - oio->kios.writes;
		aio->kios.nread += dio->kios.nread
			= nio->kios.nread - oio->kios.nread;
		aio->kios.nwritten += dio->kios.nwritten
			= nio->kios.nwritten - oio->kios.nwritten;
		aio->kios.wlentime += dio->kios.wlentime
			= nio->kios.wlentime - oio->kios.wlentime;
		aio->kios.rlentime += dio->kios.rlentime
			= nio->kios.rlentime - oio->kios.rlentime;
		aio->kios.wtime += dio->kios.wtime
			= nio->kios.wtime - oio->kios.wtime;
		aio->kios.rtime += dio->kios.rtime
			= nio->kios.rtime - oio->kios.rtime;
		nio++;
		oio++;
		aio++;
		dio++;
	}
}

static void
prt_u_opt(struct sa64 *xx)
{
	(void) printf(" %7.0f %7.0f %7.0f %7.0f\n",
		(float)xx->csi.cpu[1] * percent,
		(float)xx->csi.cpu[2] * percent,
		(float)xx->csi.cpu[3] * percent,
		(float)xx->csi.cpu[0] * percent);
}

static void
prt_b_opt(struct sa64 *xx)
{
	(void) printf(" %7.0f %7.0f %7.0f %7.0f %7.0f %7.0f %7.0f %7.0f\n",
		(float)xx->csi.bread / sec_diff,
		(float)xx->csi.lread / sec_diff,
		freq((float)xx->csi.lread, (float)xx->csi.bread),
		(float)xx->csi.bwrite / sec_diff,
		(float)xx->csi.lwrite / sec_diff,
		freq((float)xx->csi.lwrite, (float)xx->csi.bwrite),
		(float)xx->csi.phread / sec_diff,
		(float)xx->csi.phwrite / sec_diff);
}

static void
prt_d_opt(int ii, iodevinfo_t *xio)
{
	double etime, hr_etime, tps, avq, avs;

	tsttab();

	hr_etime = (double)xio[ii].kios.wlastupdate;
	if (hr_etime == 0.0)
		hr_etime = (double)NANOSEC;
	etime = hr_etime / (double)NANOSEC;
	tps = (double)(xio[ii].kios.reads + xio[ii].kios.writes) / etime;
	avq = (double)xio[ii].kios.wlentime / hr_etime;
	avs = (double)xio[ii].kios.rlentime / hr_etime;

	(void) printf("   %-8.8s    ", nxio[ii].ks.ks_name);
	(void) printf("%7.0f %7.1f %7.0f %7.0f %7.1f %7.1f\n",
		(double)xio[ii].kios.rtime * 100.0 / hr_etime,
		avq + avs,
		tps,
		BLKS(xio[ii].kios.nread + xio[ii].kios.nwritten) / etime,
		(tps > 0 ? avq / tps * 1000.0 : 0.0),
		(tps > 0 ? avs / tps * 1000.0 : 0.0));
}

static void
prt_y_opt(struct sa64 *xx)
{
	(void) printf(" %7.0f %7.0f %7.0f %7.0f %7.0f %7.0f\n",
		(float)xx->csi.rawch / sec_diff,
		(float)xx->csi.canch / sec_diff,
		(float)xx->csi.outch / sec_diff,
		(float)xx->csi.rcvint / sec_diff,
		(float)xx->csi.xmtint / sec_diff,
		(float)xx->csi.mdmint / sec_diff);
}

static void
prt_c_opt(struct sa64 *xx)
{
	(void) printf(" %7.0f %7.0f %7.0f %7.2f %7.2f %7.0f %7.0f\n",
		(float)xx->csi.syscall / sec_diff,
		(float)xx->csi.sysread / sec_diff,
		(float)xx->csi.syswrite / sec_diff,
		(float)(xx->csi.sysfork + xx->csi.sysvfork) / sec_diff,
		(float)xx->csi.sysexec / sec_diff,
		(float)xx->csi.readch / sec_diff,
		(float)xx->csi.writech / sec_diff);
}

static void
prt_w_opt(struct sa64 *xx)
{
	(void) printf(" %7.2f %7.1f %7.2f %7.1f %7.0f\n",
		(float)xx->cvmi.swapin / sec_diff,
		(float)PGTOBLK(xx->cvmi.pgswapin) / sec_diff,
		(float)xx->cvmi.swapout / sec_diff,
		(float)PGTOBLK(xx->cvmi.pgswapout) / sec_diff,
		(float)xx->csi.pswitch / sec_diff);
}

static void
prt_a_opt(struct sa64 *xx)
{
	(void) printf(" %7.0f %7.0f %7.0f\n",
		(float)xx->csi.ufsiget / sec_diff,
		(float)xx->csi.namei / sec_diff,
		(float)xx->csi.ufsdirblk / sec_diff);
}

static void
prt_q_opt(struct sa64 *xx)
{
	if (xx->si.runocc == 0 || xx->si.updates == 0)
		(void) printf(" %7.1f %7.0f", 0., 0.);
	else {
		(void) printf(" %7.1f %7.0f",
		    (float)xx->si.runque / (float)xx->si.runocc,
		    (float)xx->si.runocc / (float)xx->si.updates * 100.0);
	}
	if (xx->si.swpocc == 0 || xx->si.updates == 0)
		(void) printf(" %7.1f %7.0f\n", 0., 0.);
	else {
		(void) printf(" %7.1f %7.0f\n",
		    (float)xx->si.swpque / (float)xx->si.swpocc,
		    (float)xx->si.swpocc / (float)xx->si.updates * 100.0);
	}
}

static void
prt_v_opt(struct sa64 *xx)
{
	(void) printf(" %4lu/%-4lu %4llu %4lu/%-4lu %4llu %4lu/%-4lu "
	    "%4llu %4lu/%-4lu\n",
	    nx.szproc, nx.mszproc, xx->csi.procovf,
	    nx.szinode, nx.mszinode, xx->csi.inodeovf,
	    nx.szfile, nx.mszfile, xx->csi.fileovf,
	    nx.szlckr, nx.mszlckr);
}

static void
prt_m_opt(struct sa64 *xx)
{
	(void) printf(" %7.2f %7.2f\n",
		(float)xx->csi.msg / sec_diff,
		(float)xx->csi.sema / sec_diff);
}

static void
prt_p_opt(struct sa64 *xx)
{
	(void) printf(" %7.2f %7.2f %7.2f %7.2f %7.2f %7.2f\n",
		(float)xx->cvmi.pgfrec / sec_diff,
		(float)xx->cvmi.pgin / sec_diff,
		(float)xx->cvmi.pgpgin / sec_diff,
		(float)(xx->cvmi.prot_fault + xx->cvmi.cow_fault) / sec_diff,
		(float)(xx->cvmi.hat_fault + xx->cvmi.as_fault) / sec_diff,
		(float)xx->cvmi.softlock / sec_diff);
}

static void
prt_g_opt(struct sa64 *xx)
{
	(void) printf(" %8.2f %8.2f %8.2f %8.2f %8.2f\n",
		(float)xx->cvmi.pgout / sec_diff,
		(float)xx->cvmi.pgpgout / sec_diff,
		(float)xx->cvmi.dfree / sec_diff,
		(float)xx->cvmi.scan / sec_diff,
		(float)xx->csi.ufsipage * 100.0 /
			denom((float)xx->csi.ufsipage +
			(float)xx->csi.ufsinopage));
}

static void
prt_r_opt(struct sa64 *xx)
{
	/* Avoid divide by Zero - Should never happen */
	if (xx->si.updates == 0)
		(void) printf(" %7.0f %8.0f\n", 0., 0.);
	else {
		(void) printf(" %7.0f %8.0f\n",
		    (double)xx->vmi.freemem / (float)xx->si.updates,
		    (double)PGTOBLK(xx->vmi.swap_avail) /
			(float)xx->si.updates);
	}
}

static void
prt_k_opt(struct sa64 *xx, int n)
{
	if (n != 1) {
		(void) printf(" %7.0f %7.0f %5.0f %7.0f %7.0f %5.0f %11.0f"
		    " %5.0f\n",
		    (float)kmi.km_mem[KMEM_SMALL] / n,
		    (float)kmi.km_alloc[KMEM_SMALL] / n,
		    (float)kmi.km_fail[KMEM_SMALL] / n,
		    (float)kmi.km_mem[KMEM_LARGE] / n,
		    (float)kmi.km_alloc[KMEM_LARGE] / n,
		    (float)kmi.km_fail[KMEM_LARGE] / n,
		    (float)kmi.km_alloc[KMEM_OSIZE] / n,
		    (float)kmi.km_fail[KMEM_OSIZE] / n);
	} else {
		/*
		 * If we are not reporting averages, use the read values
		 * directly.
		 */
		(void) printf(" %7.0f %7.0f %5.0f %7.0f %7.0f %5.0f %11.0f"
		    " %5.0f\n",
		    (float)xx->kmi.km_mem[KMEM_SMALL],
		    (float)xx->kmi.km_alloc[KMEM_SMALL],
		    (float)xx->kmi.km_fail[KMEM_SMALL],
		    (float)xx->kmi.km_mem[KMEM_LARGE],
		    (float)xx->kmi.km_alloc[KMEM_LARGE],
		    (float)xx->kmi.km_fail[KMEM_LARGE],
		    (float)xx->kmi.km_alloc[KMEM_OSIZE],
		    (float)xx->kmi.km_fail[KMEM_OSIZE]);
	}
}

/*
 * Print options routine.
 */
static void
prtopt(void)
{
	int	ii, jj = 0;
	char	ccc;

	prttim();

	while ((ccc = fopt[jj++]) != NULL) {
		if (ccc != 'd')
			tsttab();
		switch (ccc) {
		    case 'u':
			prt_u_opt(&dx);
			break;
		    case 'b':
			prt_b_opt(&dx);
			break;
		    case 'd':
			for (ii = 0; ii < niodevs; ii++)
				prt_d_opt(ii, dxio);
			break;
		    case 'y':
			prt_y_opt(&dx);
			break;
		    case 'c':
			prt_c_opt(&dx);
			break;
		    case 'w':
			prt_w_opt(&dx);
			break;
		    case 'a':
			prt_a_opt(&dx);
			break;
		    case 'q':
			prt_q_opt(&dx);
			break;
		    case 'v':
			prt_v_opt(&dx);
			break;
		    case 'm':
			prt_m_opt(&dx);
			break;
		    case 'p':
			prt_p_opt(&dx);
			break;
		    case 'g':
			prt_g_opt(&dx);
			break;
		    case 'r':
			prt_r_opt(&dx);
			break;
		    case 'k':
			prt_k_opt(&nx, 1);
			/*
			 * To avoid overflow, copy the data from the sa record
			 * into a struct kmeminfo_l which has members with
			 * larger data types.
			 */
			kmi.km_mem[KMEM_SMALL] += nx.kmi.km_mem[KMEM_SMALL];
			kmi.km_alloc[KMEM_SMALL] += nx.kmi.km_alloc[KMEM_SMALL];
			kmi.km_fail[KMEM_SMALL] += nx.kmi.km_fail[KMEM_SMALL];
			kmi.km_mem[KMEM_LARGE] += nx.kmi.km_mem[KMEM_LARGE];
			kmi.km_alloc[KMEM_LARGE] += nx.kmi.km_alloc[KMEM_LARGE];
			kmi.km_fail[KMEM_LARGE] += nx.kmi.km_fail[KMEM_LARGE];
			kmi.km_alloc[KMEM_OSIZE] += nx.kmi.km_alloc[KMEM_OSIZE];
			kmi.km_fail[KMEM_OSIZE] += nx.kmi.km_fail[KMEM_OSIZE];
			break;
		}
	}
	if (jj > 2 || do_disk)
		(void) printf("\n");
	if (realtime)
		(void) fflush(stdout);
}

/*
 * Print average routine.
 */
static void
prtavg(void)
{
	int	ii, jj = 0;
	char	ccc;

	tdiff = ax.csi.cpu[0] + ax.csi.cpu[1] + ax.csi.cpu[2] + ax.csi.cpu[3];
	if (tdiff <= 0.0)
		return;

	sec_diff = tdiff / hz;
	percent = 100.0 / tdiff;
	(void) printf("\n");

	while ((ccc = fopt[jj++]) != NULL) {
		if (ccc != 'v')
			(void) printf("Average ");
		switch (ccc) {
		    case 'u':
			prt_u_opt(&ax);
			break;
		    case 'b':
			prt_b_opt(&ax);
			break;
		    case 'd':
			tabflg = 1;
			for (ii = 0; ii < niodevs; ii++)
				prt_d_opt(ii, axio);
			break;
		    case 'y':
			prt_y_opt(&ax);
			break;
		    case 'c':
			prt_c_opt(&ax);
			break;
		    case 'w':
			prt_w_opt(&ax);
			break;
		    case 'a':
			prt_a_opt(&ax);
			break;
		    case 'q':
			prt_q_opt(&ax);
			break;
		    case 'v':
			break;
		    case 'm':
			prt_m_opt(&ax);
			break;
		    case 'p':
			prt_p_opt(&ax);
			break;
		    case 'g':
			prt_g_opt(&ax);
			break;
		    case 'r':
			prt_r_opt(&ax);
			break;
		    case 'k':
			prt_k_opt(&ax, lines);
			break;
		}
	}
}

static void
ulong_delta(uint64_t *new, uint64_t *old, uint64_t *delta, uint64_t *accum,
	int begin, int end)
{
	int i;
	uint64_t n, o, d;

	for (i = begin; i < end; i += sizeof (uint64_t)) {
		n = *new++;
		o = *old++;
		if (o > n) {
			d = n + 0x100000000LL - o;
		} else {
			d = n - o;
		}
		*accum++ += *delta++ = d;
	}
}

/*
 * used to prevent zero denominators
 */
static float
denom(float x)
{
	return ((x > 0.5) ? x : 1.0);
}

/*
 * a little calculation that comes up often when computing frequency
 * of one operation relative to another
 */
static float
freq(float x, float y)
{
	return ((x < 0.5) ? 100.0 : (x - y) / x * 100.0);
}

static void
usage(void)
{
	(void) fprintf(stderr,
	    "usage: sar [-ubdycwaqvmpgrkA][-o file] t [n]\n"
	    "\tsar [-ubdycwaqvmpgrkA] [-s hh:mm][-e hh:mm][-i ss][-f file]\n");
}

static void
fail(int do_perror, char *message, ...)
{
	va_list args;

	va_start(args, message);
	(void) fprintf(stderr, "sar: ");
	(void) vfprintf(stderr, message, args);
	va_end(args);
	(void) fprintf(stderr, "\n");
	switch (do_perror) {
	case 0:				/* usage message */
		usage();
		break;
	case 1:				/* perror output */
		perror("");
		break;
	case 2:				/* no further output */
		break;
	default:			/* error */
		(void) fprintf(stderr, "unsupported failure mode\n");
		break;
	}
	exit(2);
}

static int
safe_strtoi(char const *val, char *errmsg)
{
	char *end;
	long tmp;

	errno = 0;
	tmp = strtol(val, &end, 10);
	if (*end != '\0' || errno)
		fail(0, "%s %s", errmsg, val);
	return ((int)tmp);
}

static void
safe_zalloc(void **ptr, int size, int free_first)
{
	if (free_first && *ptr != NULL)
		free(*ptr);
	if ((*ptr = malloc(size)) == NULL)
		fail(1, "malloc failed");
	(void) memset(*ptr, 0, size);
}

static int
safe_read(int fd, void *buf, size_t size)
{
	size_t rsize = read(fd, buf, size);

	if (rsize == 0)
		return (0);

	if (rsize != size)
		fail(1, "read failed");

	return (1);
}

static void
safe_write(int fd, void *buf, size_t size)
{
	if (write(fd, buf, size) != size)
		fail(1, "write failed");
}