aboutsummaryrefslogtreecommitdiff
path: root/lib/libdevstat/devstat.c
blob: 09524cc717475dc05d3f748df657b5a1ad558783 (plain) (blame)
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
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
/*
 * Copyright (c) 1997, 1998 Kenneth D. Merry.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#include <sys/cdefs.h>
__FBSDID("$FreeBSD$");

#include <sys/types.h>
#include <sys/sysctl.h>
#include <sys/errno.h>
#include <sys/dkstat.h>
#include <sys/queue.h>

#include <ctype.h>
#include <err.h>
#include <fcntl.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <kvm.h>

#include "devstat.h"

typedef enum {
	DEVSTAT_ARG_NOTYPE,
	DEVSTAT_ARG_UINT64,
	DEVSTAT_ARG_LD,
	DEVSTAT_ARG_SKIP
} devstat_arg_type;

char devstat_errbuf[DEVSTAT_ERRBUF_SIZE];

/*
 * Table to match descriptive strings with device types.  These are in
 * order from most common to least common to speed search time.
 */
struct devstat_match_table match_table[] = {
	{"da",		DEVSTAT_TYPE_DIRECT,	DEVSTAT_MATCH_TYPE},
	{"cd",		DEVSTAT_TYPE_CDROM,	DEVSTAT_MATCH_TYPE},
	{"scsi",	DEVSTAT_TYPE_IF_SCSI,	DEVSTAT_MATCH_IF},
	{"ide",		DEVSTAT_TYPE_IF_IDE,	DEVSTAT_MATCH_IF},
	{"other",	DEVSTAT_TYPE_IF_OTHER,	DEVSTAT_MATCH_IF},
	{"worm",	DEVSTAT_TYPE_WORM,	DEVSTAT_MATCH_TYPE},
	{"sa",		DEVSTAT_TYPE_SEQUENTIAL,DEVSTAT_MATCH_TYPE},
	{"pass",	DEVSTAT_TYPE_PASS,	DEVSTAT_MATCH_PASS},
	{"optical",	DEVSTAT_TYPE_OPTICAL,	DEVSTAT_MATCH_TYPE},
	{"array",	DEVSTAT_TYPE_STORARRAY,	DEVSTAT_MATCH_TYPE},
	{"changer",	DEVSTAT_TYPE_CHANGER,	DEVSTAT_MATCH_TYPE},
	{"scanner",	DEVSTAT_TYPE_SCANNER,	DEVSTAT_MATCH_TYPE},
	{"printer",	DEVSTAT_TYPE_PRINTER,	DEVSTAT_MATCH_TYPE},
	{"floppy",	DEVSTAT_TYPE_FLOPPY,	DEVSTAT_MATCH_TYPE},
	{"proc",	DEVSTAT_TYPE_PROCESSOR,	DEVSTAT_MATCH_TYPE},
	{"comm",	DEVSTAT_TYPE_COMM,	DEVSTAT_MATCH_TYPE},
	{"enclosure",	DEVSTAT_TYPE_ENCLOSURE,	DEVSTAT_MATCH_TYPE},
	{NULL,		0,			0}
};

struct devstat_args {
	devstat_metric 		metric;
	devstat_arg_type	argtype;
} devstat_arg_list[] = {
	{ DSM_NONE, DEVSTAT_ARG_NOTYPE },
	{ DSM_TOTAL_BYTES, DEVSTAT_ARG_UINT64 },
	{ DSM_TOTAL_BYTES_READ, DEVSTAT_ARG_UINT64 },
	{ DSM_TOTAL_BYTES_WRITE, DEVSTAT_ARG_UINT64 },
	{ DSM_TOTAL_TRANSFERS, DEVSTAT_ARG_UINT64 },
	{ DSM_TOTAL_TRANSFERS_READ, DEVSTAT_ARG_UINT64 },
	{ DSM_TOTAL_TRANSFERS_WRITE, DEVSTAT_ARG_UINT64 },
	{ DSM_TOTAL_TRANSFERS_OTHER, DEVSTAT_ARG_UINT64 },
	{ DSM_TOTAL_BLOCKS, DEVSTAT_ARG_UINT64 },
	{ DSM_TOTAL_BLOCKS_READ, DEVSTAT_ARG_UINT64 },
	{ DSM_TOTAL_BLOCKS_WRITE, DEVSTAT_ARG_UINT64 },
	{ DSM_KB_PER_TRANSFER, DEVSTAT_ARG_LD },
	{ DSM_KB_PER_TRANSFER_READ, DEVSTAT_ARG_LD },
	{ DSM_KB_PER_TRANSFER_WRITE, DEVSTAT_ARG_LD },
	{ DSM_TRANSFERS_PER_SECOND, DEVSTAT_ARG_LD },
	{ DSM_TRANSFERS_PER_SECOND_READ, DEVSTAT_ARG_LD },
	{ DSM_TRANSFERS_PER_SECOND_WRITE, DEVSTAT_ARG_LD },
	{ DSM_TRANSFERS_PER_SECOND_OTHER, DEVSTAT_ARG_LD },
	{ DSM_MB_PER_SECOND, DEVSTAT_ARG_LD },
	{ DSM_MB_PER_SECOND_READ, DEVSTAT_ARG_LD },
	{ DSM_MB_PER_SECOND_WRITE, DEVSTAT_ARG_LD },
	{ DSM_BLOCKS_PER_SECOND, DEVSTAT_ARG_LD },
	{ DSM_BLOCKS_PER_SECOND_READ, DEVSTAT_ARG_LD },
	{ DSM_BLOCKS_PER_SECOND_WRITE, DEVSTAT_ARG_LD },
	{ DSM_MS_PER_TRANSACTION, DEVSTAT_ARG_LD },
	{ DSM_MS_PER_TRANSACTION_READ, DEVSTAT_ARG_LD },
	{ DSM_MS_PER_TRANSACTION_WRITE, DEVSTAT_ARG_LD },
	{ DSM_SKIP, DEVSTAT_ARG_SKIP }
};

static const char *namelist[] = {
#define X_NUMDEVS	0
	"_devstat_num_devs",
#define X_GENERATION	1
	"_devstat_generation",
#define X_VERSION	2
	"_devstat_version",
#define X_DEVICE_STATQ	3
	"_device_statq",
#define X_END		4
};

/*
 * Local function declarations.
 */
static int compare_select(const void *arg1, const void *arg2);
static int readkmem(kvm_t *kd, unsigned long addr, void *buf, size_t nbytes);
static int readkmem_nl(kvm_t *kd, const char *name, void *buf, size_t nbytes);
static char *get_devstat_kvm(kvm_t *kd);

#define KREADNL(kd, var, val) \
	readkmem_nl(kd, namelist[var], &val, sizeof(val))

int
devstat_getnumdevs(kvm_t *kd)
{
	size_t numdevsize;
	int numdevs;
	const char *func_name = "devstat_getnumdevs";

	numdevsize = sizeof(int);

	/*
	 * Find out how many devices we have in the system.
	 */
	if (kd == NULL) {
		if (sysctlbyname("kern.devstat.numdevs", &numdevs,
				 &numdevsize, NULL, 0) == -1) {
			snprintf(devstat_errbuf, sizeof(devstat_errbuf),
				 "%s: error getting number of devices\n"
				 "%s: %s", func_name, func_name, 
				 strerror(errno));
			return(-1);
		} else
			return(numdevs);
	} else {

		if (KREADNL(kd, X_NUMDEVS, numdevs) == -1)
			return(-1);
		else
			return(numdevs);
	}
}

/*
 * This is an easy way to get the generation number, but the generation is
 * supplied in a more atmoic manner by the kern.devstat.all sysctl.
 * Because this generation sysctl is separate from the statistics sysctl,
 * the device list and the generation could change between the time that
 * this function is called and the device list is retreived.
 */
long
devstat_getgeneration(kvm_t *kd)
{
	size_t gensize;
	long generation;
	const char *func_name = "devstat_getgeneration";

	gensize = sizeof(long);

	/*
	 * Get the current generation number.
	 */
	if (kd == NULL) {
		if (sysctlbyname("kern.devstat.generation", &generation, 
				 &gensize, NULL, 0) == -1) {
			snprintf(devstat_errbuf, sizeof(devstat_errbuf),
				 "%s: error getting devstat generation\n%s: %s",
				 func_name, func_name, strerror(errno));
			return(-1);
		} else
			return(generation);
	} else {
		if (KREADNL(kd, X_GENERATION, generation) == -1)
			return(-1);
		else
			return(generation);
	}
}

/*
 * Get the current devstat version.  The return value of this function
 * should be compared with DEVSTAT_VERSION, which is defined in
 * sys/devicestat.h.  This will enable userland programs to determine
 * whether they are out of sync with the kernel.
 */
int
devstat_getversion(kvm_t *kd)
{
	size_t versize;
	int version;
	const char *func_name = "devstat_getversion";

	versize = sizeof(int);

	/*
	 * Get the current devstat version.
	 */
	if (kd == NULL) {
		if (sysctlbyname("kern.devstat.version", &version, &versize,
				 NULL, 0) == -1) {
			snprintf(devstat_errbuf, sizeof(devstat_errbuf),
				 "%s: error getting devstat version\n%s: %s",
				 func_name, func_name, strerror(errno));
			return(-1);
		} else
			return(version);
	} else {
		if (KREADNL(kd, X_VERSION, version) == -1)
			return(-1);
		else
			return(version);
	}
}

/*
 * Check the devstat version we know about against the devstat version the
 * kernel knows about.  If they don't match, print an error into the
 * devstat error buffer, and return -1.  If they match, return 0.
 */
int
devstat_checkversion(kvm_t *kd)
{
	const char *func_name = "devstat_checkversion";
	int buflen, res, retval = 0, version;

	version = devstat_getversion(kd);

	if (version != DEVSTAT_VERSION) {
		/*
		 * If getversion() returns an error (i.e. -1), then it
		 * has printed an error message in the buffer.  Therefore,
		 * we need to add a \n to the end of that message before we
		 * print our own message in the buffer.
		 */
		if (version == -1)
			buflen = strlen(devstat_errbuf);
		else
			buflen = 0;

		res = snprintf(devstat_errbuf + buflen,
			       DEVSTAT_ERRBUF_SIZE - buflen,
			       "%s%s: userland devstat version %d is not "
			       "the same as the kernel\n%s: devstat "
			       "version %d\n", version == -1 ? "\n" : "",
			       func_name, DEVSTAT_VERSION, func_name, version);

		if (res < 0)
			devstat_errbuf[buflen] = '\0';

		buflen = strlen(devstat_errbuf);
		if (version < DEVSTAT_VERSION)
			res = snprintf(devstat_errbuf + buflen,
				       DEVSTAT_ERRBUF_SIZE - buflen,
				       "%s: libdevstat newer than kernel\n",
				       func_name);
		else
			res = snprintf(devstat_errbuf + buflen,
				       DEVSTAT_ERRBUF_SIZE - buflen,
				       "%s: kernel newer than libdevstat\n",
				       func_name);

		if (res < 0)
			devstat_errbuf[buflen] = '\0';

		retval = -1;
	}

	return(retval);
}

/*
 * Get the current list of devices and statistics, and the current
 * generation number.
 * 
 * Return values:
 * -1  -- error
 *  0  -- device list is unchanged
 *  1  -- device list has changed
 */
int
devstat_getdevs(kvm_t *kd, struct statinfo *stats)
{
	int error;
	size_t dssize;
	int oldnumdevs;
	long oldgeneration;
	int retval = 0;
	struct devinfo *dinfo;
	const char *func_name = "devstat_getdevs";

	dinfo = stats->dinfo;

	if (dinfo == NULL) {
		snprintf(devstat_errbuf, sizeof(devstat_errbuf),
			 "%s: stats->dinfo was NULL", func_name);
		return(-1);
	}

	oldnumdevs = dinfo->numdevs;
	oldgeneration = dinfo->generation;

	/* Get the current time when we get the stats */
	gettimeofday(&stats->busy_time, NULL);

	if (kd == NULL) {
		/* If this is our first time through, mem_ptr will be null. */
		if (dinfo->mem_ptr == NULL) {
			/*
			 * Get the number of devices.  If it's negative, it's an
			 * error.  Don't bother setting the error string, since
			 * getnumdevs() has already done that for us.
			 */
			if ((dinfo->numdevs = getnumdevs()) < 0)
				return(-1);
			
			/*
			 * The kern.devstat.all sysctl returns the current 
			 * generation number, as well as all the devices.  
			 * So we need four bytes more.
			 */
			dssize = (dinfo->numdevs * sizeof(struct devstat)) +
				 sizeof(long);
			dinfo->mem_ptr = (u_int8_t *)malloc(dssize);
		} else
			dssize = (dinfo->numdevs * sizeof(struct devstat)) +
				 sizeof(long);

		/*
		 * Request all of the devices.  We only really allow for one
		 * ENOMEM failure.  It would, of course, be possible to just go
		 * in a loop and keep reallocing the device structure until we
		 * don't get ENOMEM back.  I'm not sure it's worth it, though.
		 * If devices are being added to the system that quickly, maybe
		 * the user can just wait until all devices are added.
		 */
		if ((error = sysctlbyname("kern.devstat.all", dinfo->mem_ptr, 
					  &dssize, NULL, 0)) == -1) {
			/*
			 * If we get ENOMEM back, that means that there are 
			 * more devices now, so we need to allocate more 
			 * space for the device array.
			 */
			if (errno == ENOMEM) {
				/*
				 * No need to set the error string here, 
				 * getnumdevs() will do that if it fails.
				 */
				if ((dinfo->numdevs = getnumdevs()) < 0)
					return(-1);

				dssize = (dinfo->numdevs * 
					sizeof(struct devstat)) + sizeof(long);
				dinfo->mem_ptr = (u_int8_t *)
					realloc(dinfo->mem_ptr, dssize);
				if ((error = sysctlbyname("kern.devstat.all", 
				    dinfo->mem_ptr, &dssize, NULL, 0)) == -1) {
					snprintf(devstat_errbuf,
						 sizeof(devstat_errbuf),
					    	 "%s: error getting device "
					    	 "stats\n%s: %s", func_name,
					    	 func_name, strerror(errno));
					return(-1);
				}
			} else {
				snprintf(devstat_errbuf, sizeof(devstat_errbuf),
					 "%s: error getting device stats\n"
					 "%s: %s", func_name, func_name,
					 strerror(errno));
				return(-1);
			}
		} 

	} else {
		/* 
		 * This is of course non-atomic, but since we are working
		 * on a core dump, the generation is unlikely to change
		 */
		if ((dinfo->numdevs = getnumdevs()) == -1)
			return(-1);
		if ((dinfo->mem_ptr = get_devstat_kvm(kd)) == NULL)
			return(-1);
	}
	/*
	 * The sysctl spits out the generation as the first four bytes,
	 * then all of the device statistics structures.
	 */
	dinfo->generation = *(long *)dinfo->mem_ptr;

	/*
	 * If the generation has changed, and if the current number of
	 * devices is not the same as the number of devices recorded in the
	 * devinfo structure, it is likely that the device list has shrunk.
	 * The reason that it is likely that the device list has shrunk in
	 * this case is that if the device list has grown, the sysctl above
	 * will return an ENOMEM error, and we will reset the number of
	 * devices and reallocate the device array.  If the second sysctl
	 * fails, we will return an error and therefore never get to this
	 * point.  If the device list has shrunk, the sysctl will not
	 * return an error since we have more space allocated than is
	 * necessary.  So, in the shrinkage case, we catch it here and
	 * reallocate the array so that we don't use any more space than is
	 * necessary.
	 */
	if (oldgeneration != dinfo->generation) {
		if (getnumdevs() != dinfo->numdevs) {
			if ((dinfo->numdevs = getnumdevs()) < 0)
				return(-1);
			dssize = (dinfo->numdevs * sizeof(struct devstat)) +
				sizeof(long);
			dinfo->mem_ptr = (u_int8_t *)realloc(dinfo->mem_ptr,
							     dssize);
		}
		retval = 1;
	}

	dinfo->devices = (struct devstat *)(dinfo->mem_ptr + sizeof(long));

	return(retval);
}

/*
 * selectdevs():
 *
 * Devices are selected/deselected based upon the following criteria:
 * - devices specified by the user on the command line
 * - devices matching any device type expressions given on the command line
 * - devices with the highest I/O, if 'top' mode is enabled
 * - the first n unselected devices in the device list, if maxshowdevs
 *   devices haven't already been selected and if the user has not
 *   specified any devices on the command line and if we're in "add" mode.
 *
 * Input parameters:
 * - device selection list (dev_select)
 * - current number of devices selected (num_selected)
 * - total number of devices in the selection list (num_selections)
 * - devstat generation as of the last time selectdevs() was called
 *   (select_generation)
 * - current devstat generation (current_generation)
 * - current list of devices and statistics (devices)
 * - number of devices in the current device list (numdevs)
 * - compiled version of the command line device type arguments (matches)
 *   - This is optional.  If the number of devices is 0, this will be ignored.
 *   - The matching code pays attention to the current selection mode.  So
 *     if you pass in a matching expression, it will be evaluated based
 *     upon the selection mode that is passed in.  See below for details.
 * - number of device type matching expressions (num_matches)
 *   - Set to 0 to disable the matching code.
 * - list of devices specified on the command line by the user (dev_selections)
 * - number of devices selected on the command line by the user
 *   (num_dev_selections)
 * - Our selection mode.  There are four different selection modes:
 *      - add mode.  (DS_SELECT_ADD) Any devices matching devices explicitly
 *        selected by the user or devices matching a pattern given by the
 *        user will be selected in addition to devices that are already
 *        selected.  Additional devices will be selected, up to maxshowdevs
 *        number of devices. 
 *      - only mode. (DS_SELECT_ONLY)  Only devices matching devices
 *        explicitly given by the user or devices matching a pattern
 *        given by the user will be selected.  No other devices will be
 *        selected.
 *      - addonly mode.  (DS_SELECT_ADDONLY)  This is similar to add and
 *        only.  Basically, this will not de-select any devices that are
 *        current selected, as only mode would, but it will also not
 *        gratuitously select up to maxshowdevs devices as add mode would.
 *      - remove mode.  (DS_SELECT_REMOVE)  Any devices matching devices
 *        explicitly selected by the user or devices matching a pattern
 *        given by the user will be de-selected.
 * - maximum number of devices we can select (maxshowdevs)
 * - flag indicating whether or not we're in 'top' mode (perf_select)
 *
 * Output data:
 * - the device selection list may be modified and passed back out
 * - the number of devices selected and the total number of items in the
 *   device selection list may be changed
 * - the selection generation may be changed to match the current generation
 * 
 * Return values:
 * -1  -- error
 *  0  -- selected devices are unchanged
 *  1  -- selected devices changed
 */
int
devstat_selectdevs(struct device_selection **dev_select, int *num_selected,
		   int *num_selections, long *select_generation, 
		   long current_generation, struct devstat *devices,
		   int numdevs, struct devstat_match *matches, int num_matches,
		   char **dev_selections, int num_dev_selections,
		   devstat_select_mode select_mode, int maxshowdevs,
		   int perf_select)
{
	int i, j, k;
	int init_selections = 0, init_selected_var = 0;
	struct device_selection *old_dev_select = NULL;
	int old_num_selections = 0, old_num_selected;
	int selection_number = 0;
	int changed = 0, found = 0;

	if ((dev_select == NULL) || (devices == NULL) || (numdevs <= 0))
		return(-1);

	/*
	 * We always want to make sure that we have as many dev_select
	 * entries as there are devices. 
	 */
	/*
	 * In this case, we haven't selected devices before.
	 */
	if (*dev_select == NULL) {
		*dev_select = (struct device_selection *)malloc(numdevs *
			sizeof(struct device_selection));
		*select_generation = current_generation;
		init_selections = 1;
		changed = 1;
	/*
	 * In this case, we have selected devices before, but the device
	 * list has changed since we last selected devices, so we need to
	 * either enlarge or reduce the size of the device selection list.
	 */
	} else if (*num_selections != numdevs) {
		*dev_select = (struct device_selection *)realloc(*dev_select,
			numdevs * sizeof(struct device_selection));
		*select_generation = current_generation;
		init_selections = 1;
	/*
	 * In this case, we've selected devices before, and the selection
	 * list is the same size as it was the last time, but the device
	 * list has changed.
	 */
	} else if (*select_generation < current_generation) {
		*select_generation = current_generation;
		init_selections = 1;
	}

	/*
	 * If we're in "only" mode, we want to clear out the selected
	 * variable since we're going to select exactly what the user wants
	 * this time through.
	 */
	if (select_mode == DS_SELECT_ONLY)
		init_selected_var = 1;

	/*
	 * In all cases, we want to back up the number of selected devices.
	 * It is a quick and accurate way to determine whether the selected
	 * devices have changed.
	 */
	old_num_selected = *num_selected;

	/*
	 * We want to make a backup of the current selection list if 
	 * the list of devices has changed, or if we're in performance 
	 * selection mode.  In both cases, we don't want to make a backup
	 * if we already know for sure that the list will be different.
	 * This is certainly the case if this is our first time through the
	 * selection code.
	 */
	if (((init_selected_var != 0) || (init_selections != 0)
	 || (perf_select != 0)) && (changed == 0)){
		old_dev_select = (struct device_selection *)malloc(
		    *num_selections * sizeof(struct device_selection));
		old_num_selections = *num_selections;
		bcopy(*dev_select, old_dev_select, 
		    sizeof(struct device_selection) * *num_selections);
	}

	if (init_selections != 0) {
		bzero(*dev_select, sizeof(struct device_selection) * numdevs);

		for (i = 0; i < numdevs; i++) {
			(*dev_select)[i].device_number = 
				devices[i].device_number;
			strncpy((*dev_select)[i].device_name,
				devices[i].device_name,
				DEVSTAT_NAME_LEN);
			(*dev_select)[i].device_name[DEVSTAT_NAME_LEN - 1]='\0';
			(*dev_select)[i].unit_number = devices[i].unit_number;
			(*dev_select)[i].position = i;
		}
		*num_selections = numdevs;
	} else if (init_selected_var != 0) {
		for (i = 0; i < numdevs; i++) 
			(*dev_select)[i].selected = 0;
	}

	/* we haven't gotten around to selecting anything yet.. */
	if ((select_mode == DS_SELECT_ONLY) || (init_selections != 0)
	 || (init_selected_var != 0))
		*num_selected = 0;

	/*
	 * Look through any devices the user specified on the command line
	 * and see if they match known devices.  If so, select them.
	 */
	for (i = 0; (i < *num_selections) && (num_dev_selections > 0); i++) {
		char tmpstr[80];

		snprintf(tmpstr, sizeof(tmpstr), "%s%d",
			 (*dev_select)[i].device_name,
			 (*dev_select)[i].unit_number);
		for (j = 0; j < num_dev_selections; j++) {
			if (strcmp(tmpstr, dev_selections[j]) == 0) {
				/*
				 * Here we do different things based on the
				 * mode we're in.  If we're in add or
				 * addonly mode, we only select this device
				 * if it hasn't already been selected.
				 * Otherwise, we would be unnecessarily
				 * changing the selection order and
				 * incrementing the selection count.  If
				 * we're in only mode, we unconditionally
				 * select this device, since in only mode
				 * any previous selections are erased and
				 * manually specified devices are the first
				 * ones to be selected.  If we're in remove
				 * mode, we de-select the specified device and
				 * decrement the selection count.
				 */
				switch(select_mode) {
				case DS_SELECT_ADD:
				case DS_SELECT_ADDONLY:
					if ((*dev_select)[i].selected)
						break;
					/* FALLTHROUGH */
				case DS_SELECT_ONLY:
					(*dev_select)[i].selected =
						++selection_number;
					(*num_selected)++;
					break;
				case DS_SELECT_REMOVE:
					(*dev_select)[i].selected = 0;
					(*num_selected)--;
					/*
					 * This isn't passed back out, we
					 * just use it to keep track of
					 * how many devices we've removed.
					 */
					num_dev_selections--;
					break;
				}
				break;
			}
		}
	}

	/*
	 * Go through the user's device type expressions and select devices
	 * accordingly.  We only do this if the number of devices already
	 * selected is less than the maximum number we can show.
	 */
	for (i = 0; (i < num_matches) && (*num_selected < maxshowdevs); i++) {
		/* We should probably indicate some error here */
		if ((matches[i].match_fields == DEVSTAT_MATCH_NONE)
		 || (matches[i].num_match_categories <= 0))
			continue;

		for (j = 0; j < numdevs; j++) {
			int num_match_categories;

			num_match_categories = matches[i].num_match_categories;

			/*
			 * Determine whether or not the current device
			 * matches the given matching expression.  This if
			 * statement consists of three components:
			 *   - the device type check
			 *   - the device interface check
			 *   - the passthrough check
			 * If a the matching test is successful, it 
			 * decrements the number of matching categories,
			 * and if we've reached the last element that
			 * needed to be matched, the if statement succeeds.
			 * 
			 */
			if ((((matches[i].match_fields & DEVSTAT_MATCH_TYPE)!=0)
			  && ((devices[j].device_type & DEVSTAT_TYPE_MASK) ==
			        (matches[i].device_type & DEVSTAT_TYPE_MASK))
			  &&(((matches[i].match_fields & DEVSTAT_MATCH_PASS)!=0)
			   || (((matches[i].match_fields & 
				DEVSTAT_MATCH_PASS) == 0)
			    && ((devices[j].device_type &
			        DEVSTAT_TYPE_PASS) == 0)))
			  && (--num_match_categories == 0)) 
			 || (((matches[i].match_fields & DEVSTAT_MATCH_IF) != 0)
			  && ((devices[j].device_type & DEVSTAT_TYPE_IF_MASK) ==
			        (matches[i].device_type & DEVSTAT_TYPE_IF_MASK))
			  &&(((matches[i].match_fields & DEVSTAT_MATCH_PASS)!=0)
			   || (((matches[i].match_fields &
				DEVSTAT_MATCH_PASS) == 0)
			    && ((devices[j].device_type & 
				DEVSTAT_TYPE_PASS) == 0)))
			  && (--num_match_categories == 0))
			 || (((matches[i].match_fields & DEVSTAT_MATCH_PASS)!=0)
			  && ((devices[j].device_type & DEVSTAT_TYPE_PASS) != 0)
			  && (--num_match_categories == 0))) {

				/*
				 * This is probably a non-optimal solution
				 * to the problem that the devices in the
				 * device list will not be in the same
				 * order as the devices in the selection
				 * array.
				 */
				for (k = 0; k < numdevs; k++) {
					if ((*dev_select)[k].position == j) {
						found = 1;
						break;
					}
				}

				/*
				 * There shouldn't be a case where a device
				 * in the device list is not in the
				 * selection list...but it could happen.
				 */
				if (found != 1) {
					fprintf(stderr, "selectdevs: couldn't"
						" find %s%d in selection "
						"list\n",
						devices[j].device_name,
						devices[j].unit_number);
					break;
				}

				/*
				 * We do different things based upon the
				 * mode we're in.  If we're in add or only
				 * mode, we go ahead and select this device
				 * if it hasn't already been selected.  If
				 * it has already been selected, we leave
				 * it alone so we don't mess up the
				 * selection ordering.  Manually specified
				 * devices have already been selected, and
				 * they have higher priority than pattern
				 * matched devices.  If we're in remove
				 * mode, we de-select the given device and
				 * decrement the selected count.
				 */
				switch(select_mode) {
				case DS_SELECT_ADD:
				case DS_SELECT_ADDONLY:
				case DS_SELECT_ONLY:
					if ((*dev_select)[k].selected != 0)
						break;
					(*dev_select)[k].selected =
						++selection_number;
					(*num_selected)++;
					break;
				case DS_SELECT_REMOVE:
					(*dev_select)[k].selected = 0;
					(*num_selected)--;
					break;
				}
			}
		}
	}

	/*
	 * Here we implement "top" mode.  Devices are sorted in the
	 * selection array based on two criteria:  whether or not they are
	 * selected (not selection number, just the fact that they are
	 * selected!) and the number of bytes in the "bytes" field of the
	 * selection structure.  The bytes field generally must be kept up
	 * by the user.  In the future, it may be maintained by library
	 * functions, but for now the user has to do the work.
	 *
	 * At first glance, it may seem wrong that we don't go through and
	 * select every device in the case where the user hasn't specified
	 * any devices or patterns.  In fact, though, it won't make any
	 * difference in the device sorting.  In that particular case (i.e.
	 * when we're in "add" or "only" mode, and the user hasn't
	 * specified anything) the first time through no devices will be
	 * selected, so the only criterion used to sort them will be their
	 * performance.  The second time through, and every time thereafter,
	 * all devices will be selected, so again selection won't matter.
	 */
	if (perf_select != 0) {

		/* Sort the device array by throughput  */
		qsort(*dev_select, *num_selections,
		      sizeof(struct device_selection),
		      compare_select);

		if (*num_selected == 0) {
			/*
			 * Here we select every device in the array, if it
			 * isn't already selected.  Because the 'selected'
			 * variable in the selection array entries contains
			 * the selection order, the devstats routine can show
			 * the devices that were selected first.
			 */
			for (i = 0; i < *num_selections; i++) {
				if ((*dev_select)[i].selected == 0) {
					(*dev_select)[i].selected =
						++selection_number;
					(*num_selected)++;
				}
			}
		} else {
			selection_number = 0;
			for (i = 0; i < *num_selections; i++) {
				if ((*dev_select)[i].selected != 0) {
					(*dev_select)[i].selected =
						++selection_number;
				}
			}
		}
	}

	/*
	 * If we're in the "add" selection mode and if we haven't already
	 * selected maxshowdevs number of devices, go through the array and
	 * select any unselected devices.  If we're in "only" mode, we
	 * obviously don't want to select anything other than what the user
	 * specifies.  If we're in "remove" mode, it probably isn't a good
	 * idea to go through and select any more devices, since we might
	 * end up selecting something that the user wants removed.  Through
	 * more complicated logic, we could actually figure this out, but
	 * that would probably require combining this loop with the various
	 * selections loops above.
	 */
	if ((select_mode == DS_SELECT_ADD) && (*num_selected < maxshowdevs)) {
		for (i = 0; i < *num_selections; i++)
			if ((*dev_select)[i].selected == 0) {
				(*dev_select)[i].selected = ++selection_number;
				(*num_selected)++;
			}
	}

	/*
	 * Look at the number of devices that have been selected.  If it
	 * has changed, set the changed variable.  Otherwise, if we've
	 * made a backup of the selection list, compare it to the current
	 * selection list to see if the selected devices have changed.
	 */
	if ((changed == 0) && (old_num_selected != *num_selected))
		changed = 1;
	else if ((changed == 0) && (old_dev_select != NULL)) {
		/*
		 * Now we go through the selection list and we look at
		 * it three different ways.
		 */
		for (i = 0; (i < *num_selections) && (changed == 0) && 
		     (i < old_num_selections); i++) {
			/*
			 * If the device at index i in both the new and old
			 * selection arrays has the same device number and
			 * selection status, it hasn't changed.  We
			 * continue on to the next index.
			 */
			if (((*dev_select)[i].device_number ==
			     old_dev_select[i].device_number)
			 && ((*dev_select)[i].selected == 
			     old_dev_select[i].selected))
				continue;

			/*
			 * Now, if we're still going through the if
			 * statement, the above test wasn't true.  So we
			 * check here to see if the device at index i in
			 * the current array is the same as the device at
			 * index i in the old array.  If it is, that means
			 * that its selection number has changed.  Set
			 * changed to 1 and exit the loop.
			 */
			else if ((*dev_select)[i].device_number ==
			          old_dev_select[i].device_number) {
				changed = 1;
				break;
			}
			/*
			 * If we get here, then the device at index i in
			 * the current array isn't the same device as the
			 * device at index i in the old array.
			 */
			else {
				found = 0;

				/*
				 * Search through the old selection array
				 * looking for a device with the same
				 * device number as the device at index i
				 * in the current array.  If the selection
				 * status is the same, then we mark it as
				 * found.  If the selection status isn't
				 * the same, we break out of the loop.
				 * Since found isn't set, changed will be
				 * set to 1 below.
				 */
				for (j = 0; j < old_num_selections; j++) {
					if (((*dev_select)[i].device_number ==
					      old_dev_select[j].device_number)
					 && ((*dev_select)[i].selected ==
					      old_dev_select[j].selected)){
						found = 1;
						break;
					}
					else if ((*dev_select)[i].device_number
					    == old_dev_select[j].device_number)
						break;
				}
				if (found == 0)
					changed = 1;
			}
		}
	}
	if (old_dev_select != NULL)
		free(old_dev_select);

	return(changed);
}

/*
 * Comparison routine for qsort() above.  Note that the comparison here is
 * backwards -- generally, it should return a value to indicate whether
 * arg1 is <, =, or > arg2.  Instead, it returns the opposite.  The reason
 * it returns the opposite is so that the selection array will be sorted in
 * order of decreasing performance.  We sort on two parameters.  The first
 * sort key is whether or not one or the other of the devices in question
 * has been selected.  If one of them has, and the other one has not, the
 * selected device is automatically more important than the unselected
 * device.  If neither device is selected, we judge the devices based upon
 * performance.
 */
static int
compare_select(const void *arg1, const void *arg2)
{
	if ((((const struct device_selection *)arg1)->selected)
	 && (((const struct device_selection *)arg2)->selected == 0))
		return(-1);
	else if ((((const struct device_selection *)arg1)->selected == 0)
	      && (((const struct device_selection *)arg2)->selected))
		return(1);
	else if (((const struct device_selection *)arg2)->bytes <
	         ((const struct device_selection *)arg1)->bytes)
		return(-1);
	else if (((const struct device_selection *)arg2)->bytes >
		 ((const struct device_selection *)arg1)->bytes)
		return(1);
	else
		return(0);
}

/*
 * Take a string with the general format "arg1,arg2,arg3", and build a
 * device matching expression from it.
 */
int
devstat_buildmatch(char *match_str, struct devstat_match **matches,
		   int *num_matches)
{
	char *tstr[5];
	char **tempstr;
	int num_args;
	int i, j;
	const char *func_name = "devstat_buildmatch";

	/* We can't do much without a string to parse */
	if (match_str == NULL) {
		snprintf(devstat_errbuf, sizeof(devstat_errbuf),
			 "%s: no match expression", func_name);
		return(-1);
	}

	/*
	 * Break the (comma delimited) input string out into separate strings.
	 */
	for (tempstr = tstr, num_args  = 0; 
	     (*tempstr = strsep(&match_str, ",")) != NULL && (num_args < 5); 
	     num_args++)
		if (**tempstr != '\0')
			if (++tempstr >= &tstr[5])
				break;

	/* The user gave us too many type arguments */
	if (num_args > 3) {
		snprintf(devstat_errbuf, sizeof(devstat_errbuf),
			 "%s: too many type arguments", func_name);
		return(-1);
	}

	/*
	 * Since you can't realloc a pointer that hasn't been malloced
	 * first, we malloc first and then realloc.
	 */
	if (*num_matches == 0)
		*matches = (struct devstat_match *)malloc(
			   sizeof(struct devstat_match));
	else
		*matches = (struct devstat_match *)realloc(*matches,
			  sizeof(struct devstat_match) * (*num_matches + 1));
			  
	/* Make sure the current entry is clear */
	bzero(&matches[0][*num_matches], sizeof(struct devstat_match));

	/*
	 * Step through the arguments the user gave us and build a device
	 * matching expression from them.
	 */
	for (i = 0; i < num_args; i++) {
		char *tempstr2, *tempstr3;

		/*
		 * Get rid of leading white space.
		 */
		tempstr2 = tstr[i];
		while (isspace(*tempstr2) && (*tempstr2 != '\0'))
			tempstr2++;

		/*
		 * Get rid of trailing white space.
		 */
		tempstr3 = &tempstr2[strlen(tempstr2) - 1];

		while ((*tempstr3 != '\0') && (tempstr3 > tempstr2)
		    && (isspace(*tempstr3))) {
			*tempstr3 = '\0';
			tempstr3--;
		}

		/*
		 * Go through the match table comparing the user's
		 * arguments to known device types, interfaces, etc.  
		 */
		for (j = 0; match_table[j].match_str != NULL; j++) {
			/*
			 * We do case-insensitive matching, in case someone
			 * wants to enter "SCSI" instead of "scsi" or
			 * something like that.  Only compare as many 
			 * characters as are in the string in the match 
			 * table.  This should help if someone tries to use 
			 * a super-long match expression.  
			 */
			if (strncasecmp(tempstr2, match_table[j].match_str,
			    strlen(match_table[j].match_str)) == 0) {
				/*
				 * Make sure the user hasn't specified two
				 * items of the same type, like "da" and
				 * "cd".  One device cannot be both.
				 */
				if (((*matches)[*num_matches].match_fields &
				    match_table[j].match_field) != 0) {
					snprintf(devstat_errbuf,
						 sizeof(devstat_errbuf),
						 "%s: cannot have more than "
						 "one match item in a single "
						 "category", func_name);
					return(-1);
				}
				/*
				 * If we've gotten this far, we have a
				 * winner.  Set the appropriate fields in
				 * the match entry.
				 */
				(*matches)[*num_matches].match_fields |=
					match_table[j].match_field;
				(*matches)[*num_matches].device_type |=
					match_table[j].type;
				(*matches)[*num_matches].num_match_categories++;
				break;
			}
		}
		/*
		 * We should have found a match in the above for loop.  If
		 * not, that means the user entered an invalid device type
		 * or interface.
		 */
		if ((*matches)[*num_matches].num_match_categories != (i + 1)) {
			snprintf(devstat_errbuf, sizeof(devstat_errbuf),
				 "%s: unknown match item \"%s\"", func_name,
				 tstr[i]);
			return(-1);
		}
	}

	(*num_matches)++;

	return(0);
}

/*
 * Compute a number of device statistics.  Only one field is mandatory, and
 * that is "current".  Everything else is optional.  The caller passes in
 * pointers to variables to hold the various statistics he desires.  If he
 * doesn't want a particular staistic, he should pass in a NULL pointer.
 * Return values:
 * 0   -- success
 * -1  -- failure
 */
int
compute_stats(struct devstat *current, struct devstat *previous,
	      long double etime, u_int64_t *total_bytes,
	      u_int64_t *total_transfers, u_int64_t *total_blocks,
	      long double *kb_per_transfer, long double *transfers_per_second,
	      long double *mb_per_second, long double *blocks_per_second,
	      long double *ms_per_transaction)
{
	return(devstat_compute_statistics(current, previous, etime,
	       total_bytes ? DSM_TOTAL_BYTES : DSM_SKIP,
	       total_bytes,
	       total_transfers ? DSM_TOTAL_TRANSFERS : DSM_SKIP,
	       total_transfers,
	       total_blocks ? DSM_TOTAL_BLOCKS : DSM_SKIP,
	       total_blocks,
	       kb_per_transfer ? DSM_KB_PER_TRANSFER : DSM_SKIP,
	       kb_per_transfer,
	       transfers_per_second ? DSM_TRANSFERS_PER_SECOND : DSM_SKIP,
	       transfers_per_second,
	       mb_per_second ? DSM_MB_PER_SECOND : DSM_SKIP,
	       mb_per_second,
	       blocks_per_second ? DSM_BLOCKS_PER_SECOND : DSM_SKIP,
	       blocks_per_second,
	       ms_per_transaction ? DSM_MS_PER_TRANSACTION : DSM_SKIP,
	       ms_per_transaction,
	       DSM_NONE));
}

long double
devstat_compute_etime(struct timeval cur_time, struct timeval prev_time)
{
	struct timeval busy_time;
	u_int64_t busy_usec;
	long double etime;

	timersub(&cur_time, &prev_time, &busy_time);

        busy_usec = busy_time.tv_sec;  
        busy_usec *= 1000000;          
        busy_usec += busy_time.tv_usec;
        etime = busy_usec;
        etime /= 1000000;

	return(etime);
}

int
devstat_compute_statistics(struct devstat *current, struct devstat *previous,
			   long double etime, ...)
{
	const char *func_name = "devstat_compute_statistics";
	u_int64_t totalbytes, totalbytesread, totalbyteswrite;
	u_int64_t totaltransfers, totaltransfersread, totaltransferswrite;
	u_int64_t totaltransfersother, totalblocks, totalblocksread;
	u_int64_t totalblockswrite;
	va_list ap;
	devstat_metric metric;
	u_int64_t *destu64;
	long double *destld;
	int retval;

	retval = 0;

	/*
	 * current is the only mandatory field.
	 */
	if (current == NULL) {
		snprintf(devstat_errbuf, sizeof(devstat_errbuf),
			 "%s: current stats structure was NULL", func_name);
		return(-1);
	}

	totalbytesread = current->bytes_read -
			 ((previous) ? previous->bytes_read : 0);
	totalbyteswrite = current->bytes_written -
			    ((previous) ? previous->bytes_written : 0);

	totalbytes = totalbytesread + totalbyteswrite;

	totaltransfersread = current->num_reads -
			     ((previous) ? previous->num_reads : 0);

	totaltransferswrite = current->num_writes -
			      ((previous) ? previous->num_writes : 0);

	totaltransfersother = current->num_other -
			      ((previous) ? previous->num_other : 0);

	totaltransfers = totaltransfersread + totaltransferswrite +
			 totaltransfersother;

	totalblocks = totalbytes;
	totalblocksread = totalbytesread;
	totalblockswrite = totalbyteswrite;

	if (current->block_size > 0) {
		totalblocks /= current->block_size;
		totalblocksread /= current->block_size;
		totalblockswrite /= current->block_size;
	} else {
		totalblocks /= 512;
		totalblocksread /= 512;
		totalblockswrite /= 512;
	}

	va_start(ap, etime);

	while ((metric = (devstat_metric)va_arg(ap, devstat_metric)) != 0) {

		if (metric == DSM_NONE)
			break;

		if (metric >= DSM_MAX) {
			snprintf(devstat_errbuf, sizeof(devstat_errbuf),
				 "%s: metric %d is out of range", func_name,
				 metric);
			retval = -1;
			goto bailout;
		}

		switch (devstat_arg_list[metric].argtype) {
		case DEVSTAT_ARG_UINT64:
			destu64 = (u_int64_t *)va_arg(ap, u_int64_t *);
			break;
		case DEVSTAT_ARG_LD:
			destld = (long double *)va_arg(ap, long double *);
			break;
		case DEVSTAT_ARG_SKIP:
			destld = (long double *)va_arg(ap, long double *);
			break;
		default:
			retval = -1;
			goto bailout;
			break; /* NOTREACHED */
		}

		if (devstat_arg_list[metric].argtype == DEVSTAT_ARG_SKIP)
			continue;

		switch (metric) {
		case DSM_TOTAL_BYTES:
			*destu64 = totalbytes;
			break;
		case DSM_TOTAL_BYTES_READ:
			*destu64 = totalbytesread;
			break;
		case DSM_TOTAL_BYTES_WRITE:
			*destu64 = totalbyteswrite;
			break;
		case DSM_TOTAL_TRANSFERS:
			*destu64 = totaltransfers;
			break;
		case DSM_TOTAL_TRANSFERS_READ:
			*destu64 = totaltransfersread;
			break;
		case DSM_TOTAL_TRANSFERS_WRITE:
			*destu64 = totaltransferswrite;
			break;
		case DSM_TOTAL_TRANSFERS_OTHER:
			*destu64 = totaltransfersother;
			break;
		case DSM_TOTAL_BLOCKS:
			*destu64 = totalblocks;
			break;
		case DSM_TOTAL_BLOCKS_READ:
			*destu64 = totalblocksread;
			break;
		case DSM_TOTAL_BLOCKS_WRITE:
			*destu64 = totalblockswrite;
			break;
		case DSM_KB_PER_TRANSFER:
			*destld = totalbytes;
			*destld /= 1024;
			if (totaltransfers > 0)
				*destld /= totaltransfers;
			else
				*destld = 0.0;
			break;
		case DSM_KB_PER_TRANSFER_READ:
			*destld = totalbytesread;
			*destld /= 1024;
			if (totaltransfersread > 0)
				*destld /= totaltransfersread;
			else
				*destld = 0.0;
			break;
		case DSM_KB_PER_TRANSFER_WRITE:
			*destld = totalbyteswrite;
			*destld /= 1024;
			if (totaltransferswrite > 0)
				*destld /= totaltransferswrite;
			else
				*destld = 0.0;
			break;
		case DSM_TRANSFERS_PER_SECOND:
			if (etime > 0.0) {
				*destld = totaltransfers;
				*destld /= etime;
			} else
				*destld = 0.0;
			break;
		case DSM_TRANSFERS_PER_SECOND_READ:
			if (etime > 0.0) {
				*destld = totaltransfersread;
				*destld /= etime;
			} else
				*destld = 0.0;
			break;
		case DSM_TRANSFERS_PER_SECOND_WRITE:
			if (etime > 0.0) {
				*destld = totaltransferswrite;
				*destld /= etime;
			} else
				*destld = 0.0;
			break;
		case DSM_TRANSFERS_PER_SECOND_OTHER:
			if (etime > 0.0) {
				*destld = totaltransfersother;
				*destld /= etime;
			} else
				*destld = 0.0;
			break;
		case DSM_MB_PER_SECOND:
			*destld = totalbytes;
			*destld /= 1024 * 1024;
			if (etime > 0.0)
				*destld /= etime;
			else
				*destld = 0.0;
			break;
		case DSM_MB_PER_SECOND_READ:
			*destld = totalbytesread;
			*destld /= 1024 * 1024;
			if (etime > 0.0)
				*destld /= etime;
			else
				*destld = 0.0;
			break;
		case DSM_MB_PER_SECOND_WRITE:
			*destld = totalbyteswrite;
			*destld /= 1024 * 1024;
			if (etime > 0.0)
				*destld /= etime;
			else
				*destld = 0.0;
			break;
		case DSM_BLOCKS_PER_SECOND:
			*destld = totalblocks;
			if (etime > 0.0)
				*destld /= etime;
			else
				*destld = 0.0;
			break;
		case DSM_BLOCKS_PER_SECOND_READ:
			*destld = totalblocksread;
			if (etime > 0.0)
				*destld /= etime;
			else
				*destld = 0.0;
			break;
		case DSM_BLOCKS_PER_SECOND_WRITE:
			*destld = totalblockswrite;
			if (etime > 0.0)
				*destld /= etime;
			else
				*destld = 0.0;
			break;
		/*
		 * This calculation is somewhat bogus.  It simply divides
		 * the elapsed time by the total number of transactions
		 * completed.  While that does give the caller a good
		 * picture of the average rate of transaction completion,
		 * it doesn't necessarily give the caller a good view of
		 * how long transactions took to complete on average.
		 * Those two numbers will be different for a device that
		 * can handle more than one transaction at a time.  e.g.
		 * SCSI disks doing tagged queueing.
		 *
		 * The only way to accurately determine the real average
		 * time per transaction would be to compute and store the
		 * time on a per-transaction basis.  That currently isn't
		 * done in the kernel, and would only be desireable if it
		 * could be implemented in a somewhat non-intrusive and high
		 * performance way.
		 */
		case DSM_MS_PER_TRANSACTION:
			if (totaltransfers > 0) {
				*destld = etime;
				*destld /= totaltransfers;
				*destld *= 1000;
			} else
				*destld = 0.0;
			break;
		/*
		 * As above, these next two really only give the average
		 * rate of completion for read and write transactions, not
		 * the average time the transaction took to complete.
		 */
		case DSM_MS_PER_TRANSACTION_READ:
			if (totaltransfersread > 0) {
				*destld = etime;
				*destld /= totaltransfersread;
				*destld *= 1000;
			} else
				*destld = 0.0;
			break;
		case DSM_MS_PER_TRANSACTION_WRITE:
			if (totaltransferswrite > 0) {
				*destld = etime;
				*destld /= totaltransferswrite;
				*destld *= 1000;
			} else
				*destld = 0.0;
			break;
		default:
			/*
			 * This shouldn't happen, since we should have
			 * caught any out of range metrics at the top of
			 * the loop.
			 */
			snprintf(devstat_errbuf, sizeof(devstat_errbuf),
				 "%s: unknown metric %d", func_name, metric);
			retval = -1;
			goto bailout;
			break; /* NOTREACHED */
		}
	}

bailout:

	va_end(ap);
	return(retval);
}

static int 
readkmem(kvm_t *kd, unsigned long addr, void *buf, size_t nbytes)
{
	const char *func_name = "readkmem";

	if (kvm_read(kd, addr, buf, nbytes) == -1) {
		snprintf(devstat_errbuf, sizeof(devstat_errbuf),
			 "%s: error reading value (kvm_read): %s", func_name,
			 kvm_geterr(kd));
		return(-1);
	}
	return(0);
}

static int
readkmem_nl(kvm_t *kd, const char *name, void *buf, size_t nbytes)
{
	const char *func_name = "readkmem_nl";
	struct nlist nl[2];

	(const char *)nl[0].n_name = name;
	nl[1].n_name = NULL;

	if (kvm_nlist(kd, nl) == -1) {
		snprintf(devstat_errbuf, sizeof(devstat_errbuf),
			 "%s: error getting name list (kvm_nlist): %s",
			 func_name, kvm_geterr(kd));
		return(-1);
	}
	return(readkmem(kd, nl[0].n_value, buf, nbytes));
}

/*
 * This duplicates the functionality of the kernel sysctl handler for poking
 * through crash dumps.
 */
static char *
get_devstat_kvm(kvm_t *kd)
{
	int error, i, wp;
	long gen;
	struct devstat *nds;
	struct devstat ds;
	struct devstatlist dhead;
	int num_devs;
	char *rv = NULL;
	const char *func_name = "get_devstat_kvm";

	if ((num_devs = getnumdevs()) <= 0)
		return(NULL);
	error = 0;
	if (KREADNL(kd, X_DEVICE_STATQ, dhead) == -1)
		return(NULL);

	nds = STAILQ_FIRST(&dhead);
	
	if ((rv = malloc(sizeof(gen))) == NULL) {
		snprintf(devstat_errbuf, sizeof(devstat_errbuf), 
			 "%s: out of memory (initial malloc failed)",
			 func_name);
		return(NULL);
	}
	gen = getgeneration();
	memcpy(rv, &gen, sizeof(gen));
	wp = sizeof(gen);
	/*
	 * Now push out all the devices.
	 */
	for (i = 0; (nds != NULL) && (i < num_devs);  
	     nds = STAILQ_NEXT(nds, dev_links), i++) {
		if (readkmem(kd, (long)nds, &ds, sizeof(ds)) == -1) {
			free(rv);
			return(NULL);
		}
		nds = &ds;
		rv = (char *)reallocf(rv, sizeof(gen) + 
				      sizeof(ds) * (i + 1));
		if (rv == NULL) {
			snprintf(devstat_errbuf, sizeof(devstat_errbuf), 
				 "%s: out of memory (malloc failed)",
				 func_name);
			return(NULL);
		}
		memcpy(rv + wp, &ds, sizeof(ds));
		wp += sizeof(ds);
	}
	return(rv);
}

/*
 * Compatability functions for libdevstat 2. These are deprecated and may
 * eventually be removed.
 */
int
getnumdevs(void)
{
	return(devstat_getnumdevs(NULL));
}

long
getgeneration(void)
{
	return(devstat_getgeneration(NULL));
}

int
getversion(void)
{
	return(devstat_getversion(NULL));
}

int
checkversion(void)
{
	return(devstat_checkversion(NULL));
}

int
getdevs(struct statinfo *stats)
{
	return(devstat_getdevs(NULL, stats));
}

int
selectdevs(struct device_selection **dev_select, int *num_selected,
	   int *num_selections, long *select_generation, 
	   long current_generation, struct devstat *devices, int numdevs,
	   struct devstat_match *matches, int num_matches,
	   char **dev_selections, int num_dev_selections,
	   devstat_select_mode select_mode, int maxshowdevs,
	   int perf_select)
{

	return(devstat_selectdevs(dev_select, num_selected, num_selections,
	       select_generation, current_generation, devices, numdevs,
	       matches, num_matches, dev_selections, num_dev_selections,
	       select_mode, maxshowdevs, perf_select));
}

int
buildmatch(char *match_str, struct devstat_match **matches,
	   int *num_matches)
{
	return(devstat_buildmatch(match_str, matches, num_matches));
}

long double
compute_etime(struct timeval cur_time, struct timeval prev_time)
{
	return(devstat_compute_etime(cur_time, prev_time));
}