~info-martin-konrad/epics-gateway/putlog

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
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
/*************************************************************************\
* Copyright (c) 2002 The University of Chicago, as Operator of Argonne
* National Laboratory.
* Copyright (c) 2002 Berliner Speicherring-Gesellschaft fuer Synchrotron-
* Strahlung mbH (BESSY).
* Copyright (c) 2002 The Regents of the University of California, as
* Operator of Los Alamos National Laboratory.
* This file is distributed subject to a Software License Agreement found
* in the file LICENSE that is included with this distribution. 
\*************************************************************************/

/*+*********************************************************************
 *
 * File:       gateServer.cc
 * Project:    CA Proxy Gateway
 *
 * Descr.:     Gateway server class
 *             - Provides the CAS virtual interface
 *             - Manages Gateway lists and hashes, cleanup
 *             - Server statistics variables
 *
 * Author(s):  J. Kowalkowski, J. Anderson, K. Evans (APS)
 *             R. Lange (BESSY)
 *
 *********************************************************************-*/

#define DEBUG_FD 0
#define DEBUG_SET_STAT 0
#define DEBUG_PV_CON_LIST 0
#define DEBUG_PV_LIST 0
#define DEBUG_PV_CONNNECT_CLEANUP 0
#define DEBUG_EXIST 0
#define DEBUG_DELAY 0
#define DEBUG_CLOCK 0
#define DEBUG_ACCESS 0
#define DEBUG_DESC 0
#define DEBUG_FDMGR 0
#define DEBUG_HISTORY 0

#if DEBUG_HISTORY
# define HISTNAME "GW:432:S05"
# define HISTNUM 10
#endif

#ifdef __linux__
#undef USE_LINUX_PROC_FOR_CPU
#endif

// DEBUG_TIMES prints a message every minute, which helps determine
// when things happen.
#define DEBUG_TIMES 0
// This is the interval used with DEBUG_TIMES
#define GATE_TIME_STAT_INTERVAL 60 /* sec */

// This causes traces to be printed when exceptions occur.  It
// requires Base 3.15.
#define DEBUG_EXCEPTION 0
// Print only MAX_EXCEPTIONS exceptions unless EXCEPTION_RESET_TIME
// has passed since the last one printed
#define MAX_EXCEPTIONS 100
#define EXCEPTION_RESET_TIME 3600  /* sec */

// Interval for rate statistics in seconds
#define RATE_STATS_INTERVAL 10u

// Number of load elements to get in getloadavg.  Should be 1, unless
// the implementation in the Gateway is changed.
#define N_LOAD 1

#define ULONG_DIFF(n1,n2) (((n1) >= (n2))?((n1)-(n2)):((n1)+(ULONG_MAX-(n2))))

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>


#ifdef SOLARIS
// Is in stdlib.h elsewhere, not available on WIN32
#include <sys/loadavg.h>
#endif

#ifdef WIN32
#else
# include <unistd.h>
#endif

#include <gdd.h>

#if DEBUG_EXCEPTION
#include <epicsThrowTrace.h>
#endif

#include "gateResources.h"
#include "gateServer.h"
#include "gateAs.h"
#include "gateVc.h"
#include "gatePv.h"
#include "gateStat.h"

#ifdef __linux__
# ifdef USE_LINUX_PROC_FOR_CPU
static double linuxCpuTimeDiff(void);
static pid_t gate_pid=0;
# endif
static clock_t mainClock=(clock_t)(-1);
#endif

// extern "C" wrappers needed by CA routines for callbacks
extern "C" {
#ifdef USE_FDS
    // file descriptor callback
	static void fdCB(void* ua, int fd, int opened) {
		gateServer::fdCB(ua, fd, opened);
	}
#endif
	// exception callback
	static void exCB(EXCEPT_ARGS args) {
		gateServer::exCB(args);
	}
	// errlog listener callback
	static void errlogCB(void *userData, const char *message) {
		gateServer::errlogCB(userData,message);
	}
}

// ---------------------------- general main processing function -------------

#ifndef WIN32
extern "C" {

typedef void (*SigFunc)(int);

static SigFunc save_usr1=NULL;
static SigFunc save_usr2=NULL;

static void sig_pipe(int)
{
	fprintf(stderr,"Got SIGPIPE interrupt!");
	signal(SIGPIPE,sig_pipe);
}

static void sig_usr1(int x)
{
	// Call a class function to get access to class variables
	gateServer::sig_usr1(x);
}

static void sig_usr2(int x)
{
	// Call a class function to get access to class variables
	gateServer::sig_usr2(x);
}

} //extern "C"
#endif

// Static initializations
// KE: Volatile because they can be set in signal handlers?
volatile unsigned long gateServer::command_flag = 0;
volatile unsigned long gateServer::report1_flag = 0;
volatile unsigned long gateServer::report2_flag = 0;
volatile unsigned long gateServer::report3_flag = 0;
volatile unsigned long gateServer::newAs_flag = 0;
volatile unsigned long gateServer::quit_flag = 0;
volatile unsigned long gateServer::quitserver_flag = 0;

void gateServer::mainLoop(void)
{
	int not_done=1;
	// KE: ca_poll should be called every 100 ms
	// fdManager::process can block in select for delay time
	// so delay must be less than 100 ms to insure ca_poll gets called
	// if delay = 0.0 select will not block)
	double delay=.010; // (10 ms)

	printf("Statistics PV prefix is %s\n",stat_prefix);

	// Print if too many have been started recently
	printRecentHistory();

#if DEBUG_TIMES
	epicsTime begin, end, lastPrintTime;
	double fdTime, pendTime, cleanTime;
	unsigned long nLoops=0;

	printf("%s gateServer::mainLoop: Starting and printing statistics every %d seconds\n",
	  timeStamp(),GATE_TIME_STAT_INTERVAL);
    printf("  Key: [VcTotal|PvTotal|Active,Inactive|Connecting,Dead,Disconnected]\n");
#endif
#if DEBUG_EXCEPTION
	epicsThrowTraceEnable = true;
#endif

	// Establish an errorLog listener
	errlogAddListener(::errlogCB,NULL);

	// This should create as since this is the first call to getAs()
	as=global_resources->getAs();
	if(!as) {
		printf("%s gateServer::mainLoop: Failed to set up access security\n",
		  timeStamp());
		exit(-1);
	}
	gateAsCa();
	// as->report(stdout);

#ifndef WIN32
	save_usr1=signal(SIGUSR1,::sig_usr1);
	save_usr2=signal(SIGUSR2,::sig_usr2);
#if 0
	// KE: This should be handled in both CA and CAS now using
	// osiSigPipeIgnore. There is no sigignore on Linux, so use
	// osiSigPipeIgnore if it has to be implemented here.
	SigFunc old=signal(SIGPIPE,sig_pipe);
	sigignore(SIGPIPE);
#endif
#endif
	time(&start_time);

	markNoRefreshSuppressed();

#ifdef USE_LINUX_PROC_FOR_CPU
	// Save the pid.  Could put this in a class variable.
	gate_pid=getpid();
	if(!gate_pid) printf("gateServer::mainLoop: Could not get pid\n");
	else printf("gateServer::mainLoop: gate_pid=%d\n",gate_pid);
#endif

	// Initialize stat counters
#if defined(RATE_STATS) || defined(CAS_DIAGNOSTICS)
	// Start a default timer queue (true to use shared queue, false to
	// have a private one)
	epicsTimerQueueActive &queue = 
	  epicsTimerQueueActive::allocate(true);
	gateRateStatsTimer *statTimer = new gateRateStatsTimer(queue,
	  RATE_STATS_INTERVAL, this);
	if(statTimer) {
	  // Call the expire routine to initialize it
	    statTimer->expire(epicsTime::getCurrent());
	  // Then start the timer
	    statTimer->start();
	} else {
	    printf("gateServer::mainLoop: Could not start statistics timer\n");
	}
#endif

#if DEBUG_TIMES
	lastPrintTime=epicsTime::getCurrent();
	fdTime=0.0;
	pendTime=0.0;
	cleanTime=0.0;
#endif

	// Main loop
	while(not_done)	{
#if defined(RATE_STATS) || defined(CAS_DIAGNOSTICS)
		loop_count++;
#endif
#if DEBUG_TIMES
		nLoops++;
		begin=epicsTime::getCurrent();
#endif
		// Process
		fileDescriptorManager.process(delay);
#if DEBUG_TIMES
		end=epicsTime::getCurrent();
		fdTime+=(end-begin);
		begin=end;
#endif
		// Poll
		//  KE: used to be checkEvent();
		ca_poll();
#if DEBUG_TIMES
		end=epicsTime::getCurrent();
		pendTime+=(end-begin);
		begin=end;
#endif
		// Cleanup
		connectCleanup();
		inactiveDeadCleanup();
#if DEBUG_TIMES
		end=epicsTime::getCurrent();
		cleanTime+=(end-begin);
		if((end-lastPrintTime) > GATE_TIME_STAT_INTERVAL) {
#ifdef STAT_PVS
			printf("%s gateServer::mainLoop: [%lu|%lu|%lu,%lu|%lu,%lu,%lu] "
			  "loops: %lu process: %.3f pend: %.3f clean: %.3f\n",
			  timeStamp(),
			  total_vc,total_pv,total_active,total_inactive,
			  total_connecting,total_dead,total_disconnected,
			  nLoops,
			  fdTime/(double)nLoops,
			  pendTime/(double)nLoops,
			  cleanTime/(double)nLoops);
#else
			printf("%s gateServer::mainLoop: "
			  "loops: %lu process: %.3f pend: %.3f clean: %.3f\n",
			  timeStamp(),
			  nLoops,
			  fdTime/(double)nLoops,
			  pendTime/(double)nLoops,
			  cleanTime/(double)nLoops);
#endif
			nLoops=0;
			lastPrintTime=epicsTime::getCurrent();
			fdTime=0.0;
			pendTime=0.0;
			cleanTime=0.0;
		}
#endif
		
		// Make sure messages get out
		fflush(stderr); fflush(stdout);

		// Do flagged reports
		if(command_flag) {
			gateCommands(global_resources->commandFile());
			command_flag=0;
			setStat(statCommandFlag,0ul);
		}
		if(report1_flag) {
			report1();
			report1_flag=0;
			setStat(statReport1Flag,0ul);
		}
		if(report2_flag) {
			report2();
			report2_flag=0;
			setStat(statReport2Flag,0ul);
		}
		if(report3_flag) {
			report3();
			report3_flag=0;
			setStat(statReport3Flag,0ul);
		}
		if(newAs_flag) {
			printf("%s Reading access security files\n",timeStamp());
			newAs();
			newAs_flag=0;
			setStat(statNewAsFlag,0ul);
		}
		if(quit_flag) {
			if(quit_flag == 1) {
				printf("%s Stopping (quitFlag was set to 1)\n",timeStamp());
				fflush(stderr); fflush(stdout);
			}
			quit_flag=0;
			setStat(statQuitFlag,0ul);
			// return here will delete gateServer
			return;
		}
		if(quitserver_flag) {
			printf("%s Stopping server (quitServerFlag was set to 1)\n",
			  timeStamp());
			quitserver_flag=0;
			setStat(statQuitServerFlag,0ul);
			if(global_resources->getServerMode()) {
				// Has a server
#ifndef WIN32
				pid_t parentPid=getppid();
				if(parentPid >= 0) {
					kill(parentPid,SIGTERM);
				} else {
					exit(0);
				}
#endif				
			} else {
				// Doesn't have a server, just quit
				exit(0);
			}
		}

#ifdef __linux__
# ifndef USE_LINUX_PROC_FOR_CPU
		// Get clock for this thread
		mainClock=clock();
# endif
#endif

	}
}

// This is a wrapper around caServer::generateBeaconAnomaly.  Generate
// a beacon anomaly as long as the time since the last one exceeds the
// reconnect inhibit time.  (The server may also prevent too frequent
// beacon anomalies.)  If it is not generated, mark it as suppressed,
// but suppressed is not currently used.  Note that one beacon anomaly
// causes the clients to reissue search request sequences consisting
// of 100 searches over a period of about 8 min.  It is not necessary
// to generate beacon anomalies much more frequently than this.
void gateServer::generateBeaconAnomaly ()
{
	if(timeSinceLastBeacon() >= global_resources->reconnectInhibit()) {
		caServer::generateBeaconAnomaly();
		setFirstReconnectTime();
		markNoRefreshSuppressed();
	} else {
		// KE: Not used
		markRefreshSuppressed();
	}
}

void gateServer::gateCommands(const char* cfile)
{
	FILE* fp;
	char inbuf[200];
	char *cmd,*ptr;
	int r1Flag=0,r2Flag=0,r3Flag=0,asFlag=0;

	if(cfile) {
		printf("%s Reading command file: %s\n",timeStamp(),cfile);

		errno=0;
#ifdef RESERVE_FOPEN_FD
		fp=global_resources->fopen(cfile,"r");
#else
		fp=fopen(cfile,"r");
#endif
		if(fp == NULL)	{
			fprintf(stderr,"%s Failed to open command file: %s\n",
			  timeStamp(),cfile);
			fflush(stderr);
			perror("Reason");
			fflush(stderr);
			return;
		}
	} else {
		return;
	}

	while(fgets(inbuf,sizeof(inbuf),fp)) {
		if((ptr=strchr(inbuf,'#'))) *ptr='\0';
		cmd=strtok(inbuf," \t\n");
		while(cmd) {
			if(strcmp(cmd,"R1")==0) r1Flag=1;
			else if(strcmp(cmd,"R2")==0) r2Flag=1;
			else if(strcmp(cmd,"R3")==0) r3Flag=1;
			else if(strcmp(cmd,"AS")==0) asFlag=1;
			else {
				printf("  Invalid command %s\n",cmd);
				fflush(stdout);
			}
			cmd=strtok(NULL," \t\n");
		}
	}

	// Free the reserved file descriptor before we read access
	// security or write reports
#ifdef RESERVE_FOPEN_FD
	global_resources->fclose(fp);
#else
	fclose(fp);
#endif

	// Now do the commands
	if(r1Flag) {
		report1();
		fflush(stdout);
	}
	if(r2Flag) {
		report2();
		fflush(stdout);
	}
	if(asFlag) {
		printf("%s Reading access security files\n",timeStamp());
		newAs();	
		fflush(stdout);
	}
	// Do the report after the new access security
	if(r3Flag) {
		report3();
		fflush(stdout);
	}
	
	return;
}

// We rely on CAS being non-threaded and CAC not calling our callbacks
// while this routine completes, otherwise it should be locked
void gateServer::newAs(void)
{
	gateAsEntry *pEntry;
	int i;

#if DEBUG_ACCESS
	printf("gateServer::newAs pv_list: %d con_list: %d\n",
	  (int)pv_list.count(),(int)pv_con_list.count());
	int count=0;
#endif	

	// We need to eliminate all the members (gateAsEntry's) and
	// clients (gateAsClient's).  The clients must be removed before
	// the members can be.  This has to be done because the base
	// access security assumes the members (PVs in an IOC) do not
	// change and asInitialize copies the old members back into the
	// new ASBASE.  Out members do change.

	// gatePVData's, gateVCData's, and gateChan's have pointers to
	// gateAsEntry's and gateChan's have gateAsClient's.  First NULL
	// the pointers and delete the gateAsClients.  These items are in
	// the pv_list, pv_con_list, and statTable array.

	//  Treat the pv_list and pv_con_list the same way.  i=0 is
	// pv_list and i=1 is the pv_con_list.
	for(i=0; i < 2; i++) {
		tsDLHashList<gatePvNode> *list;
		if(i == 0) list=&pv_list;
		else list=&pv_con_list;
		tsDLIter<gatePvNode> iter=list->firstIter();
		while(iter.valid())	{
			gatePvNode *pNode=iter.pointer();
			gatePvData *pv=pNode->getData();
			// NULL the entry
			pv->removeEntry();
			// NULL the entry in the gateVcData and its channels and
			// delete the gateAsClients
			gateVcData *vc=pv->VC();
			if(vc) {
				vc->removeEntry();
			}
			iter++;
		}
	}

#if statCount
	// Do the statTable
	for(i=0; i < statCount; i++) {
		// See if the pv has been created
		if(!stat_table[i].pv) {
#if DEBUG_ACCESS
			printf("  i=%d No pv for %s\n",i,stat_table[i].name);
#endif	
		}  else {
			// NULL the entry in the gateStat and its channels and delete
			// the gateAsClients
#if DEBUG_ACCESS
			printf("  i=%d %s %s\n",i,
			  stat_table[i].name,stat_table[i].pv->getName());
#endif
			stat_table[i].pv->removeEntry();
		}
		// See if the desc pv has been created
		if(!stat_table[i].descPv) {
#if DEBUG_ACCESS
			printf("  i=%d No descPv for %s\n",i,stat_table[i].name);
#endif	
		}  else {
			// NULL the entry in the gateStat and its channels and delete
			// the gateAsClients
#if DEBUG_ACCESS
			printf("  i=%d %s %s\n",i,
			  stat_table[i].name,stat_table[i].descPv->getName());
#endif
			stat_table[i].descPv->removeEntry();
		}
	}
#endif // #if statCount

	// Reinitialize access security
	long rc=as->reInitialize(global_resources->accessFile(),
	  global_resources->listFile());
	if(rc) {
		printf("%s gateServer::newAs Failed to remove old entries\n",
		  timeStamp());
		printf("  Suggest restarting this Gateway\n");
	}

	// Now check the access and reinstall all the gateAsEntry's and
	// gateAsClient's.  Remove the PVs if they are now DENY'ed.

	// pv_list and pv_con_list
	for(i=0; i < 2; i++) {
		tsDLHashList<gatePvNode> *list;
		if(i == 0) list=&pv_list;
		else list=&pv_con_list;
		tsDLIter<gatePvNode> iter=list->firstIter();
		while(iter.valid())	{
			gatePvNode *pNode=iter.pointer();
			gatePvData *pv=pNode->getData();
			tsDLIter<gatePvNode> tmpIter = iter;
			tmpIter++;
			
#if DEBUG_ACCESS
			printf("  i=%d count=%d %s\n",i,count,pv->name()?pv->name():"NULL");
#endif	
			// See if it is allowed
			pEntry=getAs()->findEntry(pv->name());
			if(!pEntry) {
#if DEBUG_ACCESS
				printf("    Not allowed\n");
#endif	
				// Denied, kill it (handles statistics) then remove it
				// now, rather than leaving it for inactiveDeadCleanup
				pv->death();
				int status=list->remove(pv->name(),pNode);
				if(status) printf("%s gateServer::newAs: "
				  "Could not remove denied pv: %s.\n",timeStamp(),pv->name());
				pNode->destroy();

			} else {
#if DEBUG_ACCESS
				printf("    Allowed\n");
#endif	
				// Allowed, replace gateAsEntry
				pv->resetEntry(pEntry);
				// Replace the entry in the gateVcData and its channels
				gateVcData *vc=pv->VC();
				if(vc) {
					vc->resetEntry(pEntry);
				}
			}
			iter=tmpIter;
		}
	}

#if statCount
	// Do internal PVs.
	for(i=0; i < statCount; i++) {
		// See if the pv has been created
		if(!stat_table[i].pv) {
#if DEBUG_ACCESS
			printf("  i=%d No pv for %s\n",i,stat_table[i].name);
#endif	
		} else {
			// Replace the entry in the gateStat and its channels
#if DEBUG_ACCESS
			printf("  i=%d %s %s\n",i,
			  stat_table[i].name,stat_table[i].pv->getName());
#endif
			pEntry=getAs()->findEntry(stat_table[i].pv->getName());
			if(!pEntry) {
				// Denied, uncreate it
				delete stat_table[i].pv;
				stat_table[i].pv=NULL;
			} else {
				// Allowed, replace gateAsEntry
				stat_table[i].pv->resetEntry(pEntry);
			}
		}
		// See if the desc pv has been created
		if(!stat_table[i].descPv) {
#if DEBUG_ACCESS
			printf("  i=%d No descPv for %s\n",i,stat_table[i].name);
#endif	
		} else {
			// Replace the entry in the gateStat and its channels
#if DEBUG_ACCESS
			printf("  i=%d %s %s\n",i,
			  stat_table[i].name,stat_table[i].descPv->getName());
#endif
			pEntry=getAs()->findEntry(stat_table[i].descPv->getName());
			if(!pEntry) {
				// Denied, uncreate it
				delete stat_table[i].descPv;
				stat_table[i].descPv=NULL;
			} else {
				// Allowed, replace gateAsEntry
				stat_table[i].descPv->resetEntry(pEntry);
			}
		}
	}
#endif // #if statCount

	// Generate a beacon anomaly since new PVs may have become
	// available
	generateBeaconAnomaly();
}

void gateServer::report1(void)
{
	FILE* fp;
	time_t t;

	printf("%s Starting Report1 (Active Virtual Connection Report)\n",
	  timeStamp());

	time(&t);

	// Open the report file
	const char *filename=global_resources->reportFile();
	if(!filename || !*filename || !strcmp(filename,"NULL")) {
		printf("  Report1: Bad report filename\n");
		return;
	}
#ifdef RESERVE_FOPEN_FD
	fp=global_resources->fopen(filename,"a");
#else
	fp=fopen(filename,"a");
#endif
	if(!fp) {
		printf("  Report1: Cannot open %s for appending\n",filename);
		return;
	}

	fprintf(fp,"---------------------------------------"
	  "------------------------------------\n"
	  "Active Virtual Connection Report: %s",ctime(&t));

#if statCount
	// Stat PVs
	for(int i=0; i < statCount; i++) {
		if(stat_table[i].pv) stat_table[i].pv->report(fp);
		if(stat_table[i].descPv) stat_table[i].descPv->report(fp);
	}
#endif

	// Virtual PVs
	tsDLIter<gateVcData> iter=vc_list.firstIter();
	while(iter.valid()) {
		iter->report(fp);
		iter++;
	}
	fprintf(fp,"---------------------------------------"
	  "------------------------------------\n");
#ifdef RESERVE_FOPEN_FD
	global_resources->fclose(fp);
#else
	fclose(fp);
#endif
	
	printf("  Report1 written to %s\n",filename);
}

void gateServer::report2(void)
{
	FILE* fp;
	gatePvData *pv;
	gateStat *pStat;
	gateAsEntry *pEntry;
	time_t t,diff;
	double rate;
	int tot_dead=0,tot_inactive=0,tot_active=0,tot_connect=0,tot_disconnect=0;
	int tot_stat=0, tot_stat_desc=0;

	printf("%s Starting Report2 (PV Summary Report)\n",
	  timeStamp());

	time(&t);
	diff=t-start_time;
	rate=diff?(double)exist_count/(double)diff:0;

	// Open the report file
	const char *filename=global_resources->reportFile();
	if(!filename || !*filename || !strcmp(filename,"NULL")) {
		printf("  Report2: Bad report filename\n");
		return;
	}
#ifdef RESERVE_FOPEN_FD
	fp=global_resources->fopen(filename,"a");
#else
	fp=fopen(filename,"a");
#endif
	if(!fp) {
		printf("  Report2: Cannot open %s for appending\n",filename);
		return;
	}

	fprintf(fp,"---------------------------------------"
	  "------------------------------------\n");
	fprintf(fp,"PV Summary Report: %s\n",ctime(&t));
	fprintf(fp,"Exist test rate = %f\n",rate);
	fprintf(fp,"Total real PV count = %d\n",(int)pv_list.count());
	fprintf(fp,"Total virtual PV count = %d\n",(int)vc_list.count());
	fprintf(fp,"Total connecting PV count = %d\n",(int)pv_con_list.count());

	tsDLIter<gatePvNode> iter=pv_list.firstIter();
	while(iter.valid())
	{
		switch(iter->getData()->getState())
		{
		case gatePvDead: tot_dead++; break;
		case gatePvInactive: tot_inactive++; break;
		case gatePvActive: tot_active++; break;
		case gatePvConnect: tot_connect++; break;
		case gatePvDisconnect: tot_disconnect++; break;
		}
		iter++;
	}

	fprintf(fp,"Total connecting PVs: %d\n",tot_connect);
	fprintf(fp,"Total dead PVs: %d\n",tot_dead);
	fprintf(fp,"Total disconnected PVs: %d\n",tot_disconnect);
	fprintf(fp,"Total inactive PVs: %d\n",tot_inactive);
	fprintf(fp,"Total active PVs: %d\n",tot_active);

#if statCount
	tot_stat=tot_stat_desc=0;
	for(int i=0; i < statCount; i++) if(stat_table[i].pv) tot_stat++;
	for(int i=0; i < statCount; i++) if(stat_table[i].descPv) tot_stat_desc++;
	fprintf(fp,"Total active stat PVs: %d [of %d]\n",tot_stat,statCount);
	fprintf(fp,"Total active stat DESC PVs: %d [of %d]\n",tot_stat_desc,
	  statCount);

	fprintf(fp,"\nInternal PVs [INT]:\n"
	  " State Name                            Group        Level Pattern\n");
	// Stat PVs
	for(int i=0; i < statCount; i++) {
		pStat=stat_table[i].pv;
		if(pStat && pStat->getName()) {
			fprintf(fp," INT %-33s",pStat->getName());
			pEntry=pStat->getEntry();
			if(pEntry) {
				fprintf(fp," %-16s %d %s\n",
				  pEntry->group?pEntry->group:"None",
				  pEntry->level,
				  pEntry->pattern?pEntry->pattern:"None");
			} else {
				fprintf(fp,"\n");
				
			}
		}
	}
	// Stat PV DESCs
	for(int i=0; i < statCount; i++) {
		pStat=stat_table[i].descPv;
		if(pStat && pStat->getName()) {
			fprintf(fp," INT %-33s",pStat->getName());
			pEntry=pStat->getEntry();
			if(pEntry) {
				fprintf(fp," %-16s %d %s\n",
				  pEntry->group?pEntry->group:"None",
				  pEntry->level,
				  pEntry->pattern?pEntry->pattern:"None");
			} else {
				fprintf(fp,"\n");
			}
		}
	}
#endif

	fprintf(fp,"\nConnecting PVs [CON]:\n"
	  " State Name                            Time         Group        Level Pattern\n");
	iter=pv_list.firstIter();
	while(iter.valid())	{
		pv=iter->getData();
		if(pv && pv->getState() == gatePvConnect && pv->name()) {
			fprintf(fp," CON %-33s %s",pv->name(),
			  timeString(pv->timeConnecting()));
			pEntry=pv->getEntry();
			if(pEntry) {
				fprintf(fp," %-16s %d %s\n",
				  pEntry->group?pEntry->group:"None",
				  pEntry->level,
				  pEntry->pattern?pEntry->pattern:"None");
			} else {
				fprintf(fp,"\n");
			}
		}
		iter++;
	}
	
	fprintf(fp,"\nDead PVs [DEA]:\n"
	  " State Name                            Time         Group        Level Pattern\n");
	iter=pv_list.firstIter();
	while(iter.valid())
	{
		pv=iter->getData();
		if(pv && pv->getState() == gatePvDead && pv->name()) {
			fprintf(fp," DEA %-33s %s",pv->name(),
			  timeString(pv->timeDead()));
			pEntry=pv->getEntry();
			if(pEntry) {
				fprintf(fp," %-16s %d %s\n",
				  pEntry->group?pEntry->group:"None",
				  pEntry->level,
				  pEntry->pattern?pEntry->pattern:"None");
			} else {
				fprintf(fp,"\n");
			}
		}
		iter++;
	}

	fprintf(fp,"\nDisconnected PVs [DIS]:\n"
	  " State Name                            Time         Group        Level Pattern\n");
	iter=pv_list.firstIter();
	while(iter.valid())
	{
		pv=iter->getData();
		if(pv &&  pv->getState() == gatePvDisconnect &&pv->name()) {
			fprintf(fp," DIS %-33s %s",pv->name(),
			  timeString(pv->timeDisconnected()));
			pEntry=pv->getEntry();
			if(pEntry) {
				fprintf(fp," %-16s %d %s\n",
				  pEntry->group?pEntry->group:"None",
				  pEntry->level,
				  pEntry->pattern?pEntry->pattern:"None");
			} else {
				fprintf(fp,"\n");
			}
		}
		iter++;
	}

	fprintf(fp,"\nInactive PVs [INA]:\n"
	  " State Name                            Time         Group        Level Pattern\n");
	iter=pv_list.firstIter();
	while(iter.valid())
	{
		pv=iter->getData();
		if(pv && pv->getState() == gatePvInactive && pv->name()) {
			fprintf(fp," INA %-33s %s",pv->name(),
			  timeString(pv->timeInactive()));
			pEntry=pv->getEntry();
			if(pEntry) {
				fprintf(fp," %-16s %d %s\n",
				  pEntry->group?pEntry->group:"None",
				  pEntry->level,
				  pEntry->pattern?pEntry->pattern:"None");
			} else {
				fprintf(fp,"\n");
			}
		}
		iter++;
	}

	fprintf(fp,"\nActive PVs [ACT]:\n"
	  " State Name                            Time         Group        Level Pattern\n");
	iter=pv_list.firstIter();
	while(iter.valid())
	{
		pv=iter->getData();
		if(pv && pv->getState() == gatePvActive && pv->name()) {
			fprintf(fp," ACT %-33s %s",pv->name(),
			  timeString(pv->timeActive()));
			pEntry=pv->getEntry();
			if(pEntry) {
				fprintf(fp," %-16s %d %s\n",
				  pEntry->group?pEntry->group:"None",
				  pEntry->level,
				  pEntry->pattern?pEntry->pattern:"None");
			} else {
				fprintf(fp,"\n");
			}
		}
		iter++;
	}

	fprintf(fp,"---------------------------------------"
	  "------------------------------------\n");
#ifdef RESERVE_FOPEN_FD
	global_resources->fclose(fp);
#else
	fclose(fp);
#endif
	
	printf("  Report2 written to %s\n",filename);
}

void gateServer::report3(void)
{
	FILE* fp;

	printf("%s Starting Report3 (Access Security Report)\n",
	  timeStamp());

	// Open the report file
	const char *filename=global_resources->reportFile();
	if(!filename || !*filename || !strcmp(filename,"NULL")) {
		printf("  Report3: Bad report filename\n");
		return;
	}
#ifdef RESERVE_FOPEN_FD
	fp=global_resources->fopen(filename,"a");
#else
	fp=fopen(filename,"a");
#endif
	if(!fp) {
		printf("  Report3: Cannot open %s for appending\n",filename);
		return;
	}

	as->report(fp);

#ifdef RESERVE_FOPEN_FD
	global_resources->fclose(fp);
#else
	fclose(fp);
#endif
	
	printf("  Report3 written to %s\n",filename);
}

#ifdef USE_FDS
// ------------------------- file descriptor servicing ----------------------

gateFd::gateFd(const int fdIn,const fdRegType typ,gateServer& s) :
	fdReg(fdIn,typ),server(s)
{
#if DEBUG_TIMES && DEBUG_FD
	printf("%s gateFd::gateFd: fd=%d count=%d\n",timeStamp(),fdIn,++count);
#endif
}

gateFd::~gateFd(void)
{
	gateDebug0(5,"~gateFd()\n");
#if DEBUG_TIMES && DEBUG_FD
	printf("%s gateFd::~gateFd: count=%d\n",timeStamp(),--count);
#endif
}

void gateFd::callBack(void)
{
#if DEBUG_TIMES && 0
    epicsTime begin(epicsTime::getCurrent());
#endif
	gateDebug0(51,"gateFd::callback()\n");
#if 0
	// This causes too many calls to ca_poll, most of which are
	// wasted.  Without it, fdManager exits when there is activity on
	// a file descriptor.  If file descriptors are not managed
	// (USE_FDS not defined), fdManager continues when there is
	// activity on a file descriptor
	ca_poll();
#endif
#if DEBUG_TIMES && 0
	epicsTime end(epicsTime::getCurrent());
	printf("%s gateFd::callBack: pend: %.3f\n",
	  timeStamp(),(double)(end-begin));
#endif
}
#endif

#ifdef USE_FDS
#if DEBUG_TIMES
int gateFd::count(0);
#endif	
#endif	

// ----------------------- server methods --------------------

gateServer::gateServer(char *prefix ) :
	caServer(),
#ifdef STAT_PVS
	total_vc(0u),
	total_pv(0u),
	total_alive(0u),
	total_active(0u),
	total_inactive(0u),
	total_unconnected(0u),
	total_dead(0u),
	total_connecting(0u),
	total_disconnected(0u),
# ifdef USE_FDS
	total_fd(0u),
# endif
#endif
	last_dead_cleanup(time(NULL)),
	last_inactive_cleanup(time(NULL)),
	last_connect_cleanup(time(NULL)),
	last_beacon_time(time(NULL)),
	suppressed_refresh_flag(0)	
{
	gateDebug0(5,"gateServer()\n");

	// Initialize channel access
#ifdef USE_313
	int status=ca_task_initialize();
	if(status != ECA_NORMAL) {
	    fprintf(stderr,"%s gateServer::gateServer: ca_task_initialize failed:\n"
		  " %s\n",timeStamp(),ca_message(status));
	}
#else
	int status=ca_context_create(ca_disable_preemptive_callback);
	if(status != ECA_NORMAL) {
	    fprintf(stderr,"%s gateServer::gateServer: ca_context_create failed:\n"
		  " %s\n",timeStamp(),ca_message(status));
	}
#endif
#ifdef USE_FDS
	status=ca_add_fd_registration(::fdCB,this);
	if(status != ECA_NORMAL) {
	    fprintf(stderr,"%s gateServer::gateServer: ca_add_fd_registration failed:\n"
		  " %s\n",timeStamp(),ca_message(status));
	}
#endif
	status=ca_add_exception_event(::exCB,NULL);
	if(status != ECA_NORMAL) {
	    fprintf(stderr,"%s gateServer::gateServer: ca_add_exception_event failed:\n"
		  " %s\n",timeStamp(),ca_message(status));
	}

	select_mask|=(alarmEventMask()|valueEventMask()|logEventMask());
	alh_mask|=alarmEventMask();

	exist_count=0;
#if statCount
	// Initialize stats
	initStats(prefix);
#ifdef RATE_STATS
	client_event_count=0;
	post_event_count=0;
	loop_count=0;
#endif
#ifdef CAS_DIAGNOSTICS
#if 0
// Jeff did not implement setting counts
	setEventsProcessed(0);
	setEventsPosted(0);	
#endif
#endif
#endif

	setDeadCheckTime();
	setInactiveCheckTime();
	setConnectCheckTime();
}

gateServer::~gateServer(void)
{
	gateDebug0(5,"~gateServer()\n");
	// remove all PVs from my lists
	gateVcData *vc,*old_vc;
	gatePvNode *old_pv,*pv_node;
	gatePvData *pv;

	while((pv_node=pv_list.first()))
	{
		pv_list.remove(pv_node->getData()->name(),old_pv);
		pv=old_pv->getData();     // KE: pv not used?
		pv_node->destroy();
	}

	while((pv_node=pv_con_list.first()))
	{
		pv_con_list.remove(pv_node->getData()->name(),old_pv);
		pv=old_pv->getData();     // KE: pv not used?
		pv_node->destroy();
	}

	while((vc=vc_list.first()))
	{
		vc_list.remove(vc->name(),old_vc);
		vc->markNoList();
		delete vc;
	}

#if statCount
	// remove all server stats
	for(int i=0; i < statCount; i++) {
		if(stat_table[i].pv) {
			delete stat_table[i].pv;
			stat_table[i].pv=NULL;
		}
		if(stat_table[i].descPv) {
			delete stat_table[i].descPv;
			stat_table[i].descPv=NULL;
		}
	}
#endif

	int status=ca_flush_io();
	if(status != ECA_NORMAL) {
	    fprintf(stderr,"%s gateServer::~gateServer: ca_flush_io failed:\n"
		  " %s\n",timeStamp(),ca_message(status));
	}
#ifdef USE_313
	status=ca_task_exit();
	if(status != ECA_NORMAL) {
	    fprintf(stderr,"%s gateServer::~gateServer: ca_task_exit failed:\n"
		  " %s\n",timeStamp(),ca_message(status));
	}
#else
	ca_context_destroy();
#endif
}

void gateServer::checkEvent(void)
{
	gateDebug0(51,"gateServer::checkEvent()\n");
	ca_poll();
	connectCleanup();
	inactiveDeadCleanup();
}

#ifdef USE_FDS
void gateServer::fdCB(void* ua, int fd, int opened)
{
	gateServer* s = (gateServer*)ua;
	fdReg* reg;

	gateDebug3(5,"gateServer::fdCB(gateServer=%p,fd=%d,opened=%d)\n",
		ua,fd,opened);

	if((opened)) {
#ifdef STAT_PVS
		s->setStat(statFd,++(s->total_fd));
#endif
		reg=new gateFd(fd,fdrRead,*s);
	} else {
#ifdef STAT_PVS
		s->setStat(statFd,--(s->total_fd));
#endif
		gateDebug0(5,"gateServer::fdCB() need to delete gateFd\n");
		reg=fileDescriptorManager.lookUpFD(fd,fdrRead);
		delete reg;
	}
}
#endif

double gateServer::delay_quick=.001; // 1 ms
double gateServer::delay_normal=1.0; // 1 sec
double gateServer::delay_current=0;

void gateServer::quickDelay(void)   { delay_current=delay_quick; }
void gateServer::normalDelay(void)  { delay_current=delay_normal; }
double gateServer::currentDelay(void) { return delay_current; }

#if HANDLE_EXCEPTIONS
void gateServer::exCB(EXCEPT_ARGS args)
#else
void gateServer::exCB(EXCEPT_ARGS /*args*/)
#endif
{
	gateDebug0(9,"exCB: -------------------------------\n");
	/*
	gateDebug1(9,"exCB: name=%s\n",ca_name(args.chid));
	gateDebug1(9,"exCB: type=%d\n",ca_field_type(args.chid));
	gateDebug1(9,"exCB: number of elements=%d\n",ca_element_count(args.chid));
	gateDebug1(9,"exCB: host name=%s\n",ca_host_name(args.chid));
	gateDebug1(9,"exCB: read access=%d\n",ca_read_access(args.chid));
	gateDebug1(9,"exCB: write access=%d\n",ca_write_access(args.chid));
	gateDebug1(9,"exCB: state=%d\n",ca_state(args.chid));
	gateDebug0(9,"exCB: -------------------------------\n");
	gateDebug1(9,"exCB: type=%d\n",args.type);
	gateDebug1(9,"exCB: count=%d\n",args.count);
	gateDebug1(9,"exCB: status=%d\n",args.stat);
	*/

	// This is the exception callback - log a message about the PV
#if HANDLE_EXCEPTIONS
	static epicsTime last=epicsTime::getCurrent();
	static int nExceptions=0;
	static int ended=0;

	// Reset counter if EXCEPTION_RESET_TIME has passed since last print
	epicsTime cur=epicsTime::getCurrent();
	double delta=cur-last;
	if(delta > EXCEPTION_RESET_TIME) {
		nExceptions=0;
		ended=0;
	}

	// Handle these cases with less output and no limits since they
	// are common
	
	// Virtual circuit disconnect
	// Virtual circuit unresponsive
	if (args.stat == ECA_DISCONN || args.stat == ECA_UNRESPTMO) {
		fprintf (stderr, "%s Warning: %s %s \n",
				 timeStamp(),
				 ca_message(args.stat)?ca_message(args.stat):"<no message>",
				 args.ctx?args.ctx:"<no context>");
		return;
	}

	// Check if we have exceeded the limits
	if(ended) return;
	if(nExceptions++ > MAX_EXCEPTIONS) {
	    ended=1;
	    fprintf(stderr,"gateServer::exCB: Channel Access Exception:\n"
	      "Too many exceptions [%d]\n"
	      "No more will be printed for %d seconds\n",
	      MAX_EXCEPTIONS,EXCEPTION_RESET_TIME);
	    ca_add_exception_event(NULL, NULL);
	    return;
	}

	last=cur;
	fprintf(stderr,"%s gateServer::exCB: Channel Access Exception:\n"
	  "  Channel Name: %s\n"
	  "  Native Type: %s\n"
	  "  Native Count: %lu\n"
	  "  Access: %s%s\n"
	  "  IOC: %s\n"
	  "  Message: %s\n"
	  "  Context: %s\n"
	  "  Requested Type: %s\n"
	  "  Requested Count: %ld\n"
	  "  Source File: %s\n"
	  "  Line number: %u\n",
	  timeStamp(),
	  args.chid?ca_name(args.chid):"Unavailable",
	  args.chid?dbf_type_to_text(ca_field_type(args.chid)):"Unavailable",
	  args.chid?ca_element_count(args.chid):0,
	  args.chid?(ca_read_access(args.chid)?"R":""):"Unavailable",
	  args.chid?(ca_write_access(args.chid)?"W":""):"",
	  args.chid?ca_host_name(args.chid):"Unavailable",
	  ca_message(args.stat)?ca_message(args.stat):"Unavailable",
	  args.ctx?args.ctx:"Unavailable",
	  dbf_type_to_text(args.type),
	  args.count,
	  args.pFile?args.pFile:"Unavailable",
	  args.pFile?args.lineNo:0);
#endif
}

void gateServer::errlogCB(void * /*userData*/, const char * /*message*/)
{
#if 0
	fflush(stderr); fflush(stdout);
	// The messages are printed via printf.  This is redundant and
	// multiple lines get intermingled.
	fprintf(stderr,"\n%s Errlog message:\n%s\nEnd message\n",
	  timeStamp(),message);
	fflush(stderr); fflush(stdout);
#else
	fflush(stderr); fflush(stdout);
	fprintf(stderr,"\n%s !!! Errlog message received (message is above)\n",
	  timeStamp());
	fflush(stderr); fflush(stdout);
#endif
}

void gateServer::connectCleanup(void)
{
	gateDebug0(51,"gateServer::connectCleanup()\n");
	gatePvData* pv;

	if(global_resources->connectTimeout()>0 && 
	   timeConnectCleanup()<global_resources->connectTimeout())
		return;

#if DEBUG_PV_CON_LIST
	unsigned long pos=1;
	unsigned long total=pv_con_list.count();
#endif
	
#if DEBUG_PV_CONNNECT_CLEANUP 
	printf("\ngateServer::connectCleanup: "
	  "timeConnectCleanup=%ld timeDeadCheck=%ld\n"
	  "  timeInactiveCheck=%ld elapsedTime=%ld\n",
	  timeConnectCleanup(),timeDeadCheck(),
	  timeInactiveCheck(),time(NULL)-start_time);
	printf("  pv_list.count()=%d pv_con_list.count()=%d\n",
	  pv_list.count(),pv_con_list.count());
#endif
	tsDLIter<gatePvNode> iter=pv_con_list.firstIter();
	gatePvNode *pNode;
	while(iter.valid())
	{
		tsDLIter<gatePvNode> tmpIter = iter;
		tmpIter++;

		pNode=iter.pointer();
		pv=pNode->getData();
#if DEBUG_PV_CON_LIST
		printf("  Node %ld: name=%s\n"
		  "  timeConnecting=%ld totalElements=%d getStateName=%s\n",
		  pos,
		  pv->name(),pv->timeConnecting(),pv->totalElements(),
		  pv->getStateName());
		printf("Pointers: iter=%x tmpIter=0x%x\n",
		  iter.pointer(),tmpIter.pointer());
#endif
		if(pv->timeConnecting()>=global_resources->connectTimeout())
		{
			gateDebug1(3,"gateServer::connectCleanup() "

			  "cleaning up PV %s\n",pv->name());
			// clean from connecting list
#if DEBUG_PV_CON_LIST
			printf("  Removing node (0x%x) %ld of %ld [%lu|%lu|%lu,%lu|%lu,%lu,%lu]: name=%s\n"
			  "  timeConnecting=%ld totalElements=%d getStateName=%s\n",
			  pNode,pos,total,
			  total_vc,total_pv,total_active,total_inactive,
			  total_connecting,total_dead,total_disconnected,
			  pv->name(),
			  pv->timeConnecting(),pv->totalElements(),pv->getStateName());
#endif
			int status = pv_con_list.remove(pv->name(),pNode);
			if(status) printf("%s Clean from connecting PV list failed for pvname=%s.\n",
				timeStamp(),pv->name());

			delete pNode;
			if(pv->pendingConnect()) pv->death();
		}
		iter=tmpIter;
#if DEBUG_PV_CON_LIST
		pos++;
		printf("New pointers: iter=%x tmpIter=0x%x\n",
		  iter.pointer(),tmpIter.pointer());
#endif
	}
#if DEBUG_PV_CON_LIST
	printf("gateServer::connectCleanup: After: \n"
	  "  pv_list.count()=%d pv_con_list.count()=%d\n",
	  pv_list.count(),pv_con_list.count());
#endif
	setConnectCheckTime();
}

void gateServer::inactiveDeadCleanup(void)
{
	gateDebug0(51,"gateServer::inactiveDeadCleanup()\n");
	gatePvData *pv;
	int dead_check=0,inactive_check=0;

	// Only do the checks if the smallest of the timeout intervals
	// (usually the dead timeout) has passed since the last check
	if(timeDeadCheck() >= global_resources->deadTimeout())
		dead_check=1;
	if(timeInactiveCheck() >= global_resources->inactiveTimeout())
		inactive_check=1;
	if(dead_check==0 && inactive_check==0) return;

#if DEBUG_PV_LIST
	int ifirst=1;
#endif

	tsDLIter<gatePvNode> iter=pv_list.firstIter();
	gatePvNode *pNode;
	while(iter.valid())
	{
		tsDLIter<gatePvNode> tmpIter = iter;
		tmpIter++;

		pNode=iter.pointer();
		pv=pNode->getData();
		if(pv->dead() &&
		  pv->timeDead()>=global_resources->deadTimeout())
		{
			gateDebug1(3,"gateServer::inactiveDeadCleanup() dead PV %s\n",
				pv->name());
			int status=pv_list.remove(pv->name(),pNode);
#if DEBUG_PV_LIST
			if(ifirst) {
			    ifirst=0;
			}
			printf("%s gateServer::inactiveDeadCleanup(dead): [%lu|%lu|%lu,%lu|%lu,%lu,%lu]: "
			  "name=%s time=%ld count=%d state=%s\n",
			  timeStamp(),
			  total_vc,total_pv,total_active,total_inactive,
			  total_connecting,total_dead,total_disconnected,
			  pv->name(),pv->timeDead(),pv->totalElements(),pv->getStateName());
#endif
			if(status) printf("%s Clean dead PV from PV list failed for pvname=%s.\n",
				timeStamp(),pv->name());
			pNode->destroy();
		}
		else if(pv->inactive() &&
		  pv->timeInactive()>=global_resources->inactiveTimeout())
		{
			gateDebug1(3,"gateServer::inactiveDeadCleanup inactive PV %s\n",
				pv->name());

			int status=pv_list.remove(pv->name(),pNode);
#if DEBUG_PV_LIST
			if(ifirst) {
			    ifirst=0;
			}
			printf("%s gateServer::inactiveDeadCleanup(inactive): [%lu|%lu|%lu,%lu|%lu,%lu,%lu]: "
			  "name=%s time=%ld count=%d state=%s\n",
			  timeStamp(),
			  total_vc,total_pv,total_active,total_inactive,
			  total_connecting,total_dead,total_disconnected,
			  pv->name(),pv->timeInactive(),pv->totalElements(),pv->getStateName());
#endif
			if(status) printf("%s Clean inactive PV from PV list failed for pvname=%s.\n",
				timeStamp(),pv->name());
			pNode->destroy();
		}
		else if(pv->disconnected() &&
		  pv->timeDisconnected()>=global_resources->inactiveTimeout())
		{
			gateDebug1(3,"gateServer::inactiveDeadCleanup disconnected PV %s\n",
				pv->name());

			int status=pv_list.remove(pv->name(),pNode);
#if DEBUG_PV_LIST
			if(ifirst) {
			    ifirst=0;
			}
			printf("%s gateServer::inactiveDeadCleanup(disconnected): [%lu|%lu|%lu,%lu|%lu,%lu,%lu]: "
			  "name=%s time=%ld count=%d state=%s\n",
			  timeStamp(),
			  total_vc,total_pv,total_active,total_inactive,
			  total_connecting,total_dead,total_disconnected,
			  pv->name(),pv->timeInactive(),pv->totalElements(),pv->getStateName());
#endif
			if(status) printf("%s Clean disconnected PV from PV list failed for pvname=%s.\n",
				timeStamp(),pv->name());
			pNode->destroy();
		}

		iter=tmpIter;
	}

	setDeadCheckTime();
	setInactiveCheckTime();
}

#ifdef USE_DENYFROM
pvExistReturn gateServer::pvExistTest(const casCtx& ctx, const caNetAddr& clientAddress,
  const char* pvname)
{

#else
pvExistReturn gateServer::pvExistTest(const casCtx& ctx, const caNetAddr& clientAddress,
  const char* pvname)
{
	return pvExistTest(ctx, pvname);
}

pvExistReturn gateServer::pvExistTest(const casCtx& ctx, const char* pvname)
{
#endif
	gateDebug2(5,"gateServer::pvExistTest(ctx=%p,pv=%s)\n",(void *)&ctx,pvname);
	gatePvData* pv;
	pvExistReturn rc;
	gateAsEntry* pEntry;
	char real_name[GATE_MAX_PVNAME_LENGTH];
#if DEBUG_FDMGR
	static double cumTime=0.0;
	epicsTime startTime, endTime;
#endif

	++exist_count;

#if DEBUG_EXIST
	printf("%s pvExistTest: %s\n",timeStamp(),pvname?pvname:"NULL");
#endif
#if DEBUG_HISTORY
	if(!strncmp(HISTNAME,pvname,HISTNUM)) {
		printf("%s gateServer::pvExistTest: loop_count=%lu %s\n",
		  timeStamp(),loop_count,pvname);
	}
#endif
#if DEBUG_FDMGR
	startTime=epicsTime::getCurrent();
	if(exist_count%1000 == 0) {
		printf("%s pvExistTest: exist_count=%lu cumTime=%.3f\n",
		  timeStamp(),exist_count,cumTime);
	}
#endif

#ifdef USE_DENYFROM
	// Getting the host name is expensive.  Only do it if the
	// deny_from_list is used
	if(getAs()->isDenyFromListUsed()) {
		char hostname[GATE_MAX_HOSTNAME_LENGTH];
		
		// Get the hostname and check if it is allowed
		//getClientHostName(ctx, hostname, sizeof(hostname));
		//clientAddress.stringConvert(hostname, sizeof(hostname))
		
		struct sockaddr_in sockAdd	= clientAddress.getSockIP();
		struct sockaddr_in* pSockAdd;
		pSockAdd = &sockAdd;

		ipAddrToDottedIP(pSockAdd,hostname,sizeof(hostname));
		char * ch;
		ch=strchr(hostname,':');
		if(ch != NULL) hostname[ch-hostname]=0;			
		
				
		// See if requested name is allowed and check for aliases
		if ( !(pEntry = getAs()->findEntry(pvname, hostname)) )
		{
			gateDebug2(1,"gateServer::pvExistTest() %s (from %s) is not allowed\n",
			  pvname, hostname);
#if DEBUG_FDMGR
			endTime=epicsTime::getCurrent();
			cumTime+=(endTime-startTime);
#endif
			return pverDoesNotExistHere;
		}
	} else {
		// See if requested name is allowed and check for aliases.
		// NULL will avoid checking the deny_from_list
		if ( !(pEntry = getAs()->findEntry(pvname, NULL)) )
		{
			gateDebug1(1,"gateServer::pvExistTest() %s is not allowed\n",
			  pvname);
#if DEBUG_FDMGR
			endTime=epicsTime::getCurrent();
			cumTime+=(endTime-startTime);
#endif
			return pverDoesNotExistHere;
		}
	}
#else
	// See if requested name is allowed and check for aliases.  Uses
	// information in .pvlist, not .access.
	if ( !(pEntry = getAs()->findEntry(pvname)) )
	{
		gateDebug1(1,"gateServer::pvExistTest() %s is not allowed\n",
				   pvname);
#if DEBUG_FDMGR
		endTime=epicsTime::getCurrent();
		cumTime+=(endTime-startTime);
#endif
		return pverDoesNotExistHere;
	}
#endif

    pEntry->getRealName(pvname, real_name, sizeof(real_name));

//#ifdef USE_DENYFROM
//    gateDebug3(1,"gateServer::pvExistTest() %s (from %s) real name %s\n",
//	  pvname, hostname, real_name);
//#else
    gateDebug2(1,"gateServer::pvExistTest() %s real name %s\n",
	  pvname, real_name);
//#endif

#if statCount
	// Check internal PVs
	if(!strncmp(stat_prefix,real_name,stat_prefix_len)) {
		for(int i=0; i < statCount; i++) {
			if(strcmp(real_name,stat_table[i].pvName)==0) {
#if DEBUG_DESC
				printf("  pattern=%s alias=%s group=%s\n",
				  pEntry->pattern?pEntry->pattern:"NULL",
				  pEntry->alias?pEntry->alias:"NULL",
				  pEntry->group?pEntry->group:"NULL");
				printf("  pverExistsHere\n"); 
#endif
#if DEBUG_FDMGR
				endTime=epicsTime::getCurrent();
				cumTime+=(endTime-startTime);
#endif
				return pverExistsHere;
			}
			if(strcmp(real_name,stat_table[i].descPvName)==0) {
#if DEBUG_DESC
				printf("  pverExistsHere\n"); 
#endif
#if DEBUG_FDMGR
				endTime=epicsTime::getCurrent();
				cumTime+=(endTime-startTime);
#endif
				return pverExistsHere;
			}
		}
	}
#endif

	// Check if we have it
	if(pvFind(real_name,pv)==0)
	{
		// Is in pv_list
		switch(pv->getState())
		{
		case gatePvInactive:
		case gatePvActive:
			// We are connected to the PV
			gateDebug2(5,"gateServer::pvExistTest() %s exists (%s)\n",
					   real_name,pv->getStateName());
			rc=pverExistsHere;
			break;
		default:
			// We are not currently connected
			gateDebug2(5,"gateServer::pvExistTest() %s is %s\n",
					   real_name,pv->getStateName());
			rc=pverDoesNotExistHere;
			break;
		}
#if DEBUG_DELAY
		if(!strncmp("Xorbit",pvname,6)) {
			printf("%s gateServer::pvExistTest [pvFind]: loop_count=%lu %s\n",
			  timeStamp(),loop_count,pvname);
		}
#endif
#if DEBUG_HISTORY
		if(!strncmp(HISTNAME,pvname,HISTNUM)) {
			printf("%s gateServer::pvExistTest [pvFind]: loop_count=%lu %s\n",
			  timeStamp(),loop_count,pvname);
		}
#endif

	}
	else if(conFind(real_name,pv)==0)
	{
		// Is in pv_con_list -- connect is pending
		gateDebug1(5,"gateServer::pvExistTest() %s Connecting (new async ET)\n",real_name);
		pv->addET(ctx);
#if DEBUG_DELAY
		if(!strncmp("Xorbit",pvname,6)) {
			printf("%s gateServer::pvExistTest [conFind]: loop_count=%lu %s\n",
			  timeStamp(),loop_count,pvname);
		}
#endif
#if DEBUG_HISTORY
		if(!strncmp(HISTNAME,pvname,HISTNUM)) {
			printf("%s gateServer::pvExistTest [conFind]: loop_count=%lu %s\n",
			  timeStamp(),loop_count,pvname);
		}
#endif
		rc=pverAsyncCompletion;
	}
	else
	{
		// We don't have it so make a new gatePvData
		gateDebug1(5,"gateServer::pvExistTest() %s creating new gatePv\n",real_name);
		pv=new gatePvData(this,pEntry,real_name);

#if DEBUG_DELAY
		if(!strncmp("Xorbit",pvname,6)) {
			printf("\n%s gateServer::pvExistTest: loop_count=%lu %s\n",
			  timeStamp(),loop_count,pvname);
		}
#endif
#if DEBUG_HISTORY
		if(!strncmp(HISTNAME,pvname,HISTNUM)) {
			printf("\n%s gateServer::pvExistTest: loop_count=%lu %s\n",
			  timeStamp(),loop_count,pvname);
		}
#endif
		
		switch(pv->getState())
		{
		case gatePvConnect:
			gateDebug2(5,"gateServer::pvExistTest() %s %s (new async ET)\n",
			  real_name,pv->getStateName());
			pv->addET(ctx);
			rc=pverAsyncCompletion;
			break;
		case gatePvInactive:
		case gatePvActive:
			gateDebug2(5,"gateServer::pvExistTest() %s %s ?\n",
			  real_name,pv->getStateName());
			rc=pverExistsHere;
			break;
		default:
			gateDebug2(5,"gateServer::pvExistTest() %s %s ?\n",
			  real_name,pv->getStateName());
			rc=pverDoesNotExistHere;
			break;
		}
	}
	
#if DEBUG_DELAY
	if(rc.getStatus() == pverAsyncCompletion) {
		printf("  pverAsyncCompletion\n");
	} else if(rc.getStatus() == pverExistsHere) {
		printf("  pverExistsHere\n"); 
	} else if(rc.getStatus() == pverDoesNotExistHere) {
		printf("  pverDoesNotExistHere\n"); 
	} else {
		printf("  Other return code\n"); 
	}
#endif
#if DEBUG_HISTORY
	if(!strncmp(HISTNAME,pv->name(),HISTNUM)) {
		if(rc.getStatus() == pverAsyncCompletion) {
			printf("  pverAsyncCompletion\n");
		} else if(rc.getStatus() == pverExistsHere) {
			printf("  pverExistsHere\n"); 
		} else if(rc.getStatus() == pverDoesNotExistHere) {
			printf("  pverDoesNotExistHere\n"); 
		} else {
			printf("  Other return code\n"); 
		}
	}
#endif
	
#if DEBUG_FDMGR
	endTime=epicsTime::getCurrent();
	cumTime+=(endTime-startTime);
#endif
	return rc;
}

pvAttachReturn gateServer::pvAttach(const casCtx& /*c*/,const char* pvname)
{
	gateDebug1(5,"gateServer::pvAttach() PV %s\n",pvname);
	gateVcData* rc;
    gateAsEntry* pEntry;
	char real_name[GATE_MAX_PVNAME_LENGTH];

	// See if requested name is allowed and check for aliases.  Uses
	// information in .pvlist, not .access.
    if ( !(pEntry = getAs()->findEntry(pvname)) )
    {
        gateDebug1(2,"gateServer::pvAttach() called for denied PV %s "
		  " - this should not happen!\n", pvname);
        return pvAttachReturn(S_casApp_pvNotFound);
    }

    pEntry->getRealName(pvname, real_name, sizeof(real_name));

#if statCount
	// Trap (and create if needed) server stats PVs
	if(!strncmp(stat_prefix,real_name,stat_prefix_len)) {
		for(int i=0; i < statCount; i++) {
			if(strcmp(real_name,stat_table[i].pvName) == 0) {
				if(stat_table[i].pv == NULL)
				  stat_table[i].pv=new gateStat(this,pEntry,real_name,i);
#if DEBUG_DESC
				printf("gateServer::pvAttach:  %s\n",stat_table[i].pv->getName());
#endif
				return pvAttachReturn(*stat_table[i].pv);
			}
			if(strcmp(real_name,stat_table[i].descPvName) == 0) {
				if(stat_table[i].descPv == NULL)
				  stat_table[i].descPv=new gateStatDesc(this,pEntry,real_name,i);
#if DEBUG_DESC
				printf("gateServer::pvAttach:  %s\n",stat_table[i].descPv->getName());
#endif
				return pvAttachReturn(*stat_table[i].descPv);
			}
		}
	}
#endif

#if DEBUG_DELAY
	if(!strncmp("Xorbit",real_name,6)) {
		printf("%s gateServer::pvAttach: loop_count=%lu %s\n",
		  timeStamp(),loop_count,real_name);
	}
#endif
	
	// See if we have a gateVcData
	if(vcFind(real_name,rc) < 0)
	{
		// We don't have it, create a new one
		rc=new gateVcData(this,real_name);

		if(rc->getStatus())
		{
			gateDebug1(5,"gateServer::pvAttach() bad PV %s\n",real_name);
			delete rc;
			rc=NULL;
		}
	}

#if DEBUG_HISTORY
	if(!strncmp(HISTNAME,real_name,HISTNUM)) {
		printf("%s gateServer::pvAttach: loop_count=%lu %s %s\n",
		  timeStamp(),loop_count,
		  rc?"Found":"Not Found",
		  real_name);
	}
#endif

	return rc?pvCreateReturn(*rc):pvCreateReturn(S_casApp_pvNotFound);
}

#if statCount
// Routines for gateway internal routines

void gateServer::setStat(int type, double val)
{
	if(stat_table[type].pv) stat_table[type].pv->postData(val);
#if DEBUG_SET_STAT > 1
	printf("setStat(dbl): type=%d val=%g\n",type,val);
#endif
}

void gateServer::setStat(int type, unsigned long val)
{
	if(stat_table[type].pv) stat_table[type].pv->postData(val);
#if DEBUG_SET_STAT
	printf("setStat(ul): type=%d val=%ld\n",type,val);
#endif
}

caStatus gateServer::processStat(int type, double val)
{
	caStatus retVal=S_casApp_success;

    switch(type) {
    case statCommandFlag:
		if(val > 0.0) command_flag=1;
		break;
    case statReport1Flag:
		if(val > 0.0) report1_flag=1;
		break;
    case statReport2Flag:
		if(val > 0.0) report2_flag=1;
		break;
    case statReport3Flag:
		if(val > 0.0) report3_flag=1;
		break;
    case statNewAsFlag:
		if(val > 0.0) newAs_flag=1;
		break;
    case statQuitFlag:
		if(val > 0.0) quit_flag=1;
		break;
    case statQuitServerFlag:
		if(val > 0.0) quitserver_flag=1;
		break;
	default:
		retVal=S_casApp_noSupport;
		break;
    }
	
#if DEBUG_PROCESS_STAT
    print("gateServer::processStat:\n"
      "val=%.2f nCheck=%d nPrint=%d nSigma=%d nLimit=%.2f\n",
      val,nCheck,nPrint,nSigma,nLimit);
#endif
	return retVal;
}

void gateServer::initStats(char *prefix)
{
	int i;
	static unsigned long zero=0u;

	// Define the prefix for the server stats
	if(prefix) {
		// Use the specified one
		stat_prefix=prefix;
	} else {
		// Make one up
		stat_prefix=getComputerName();
		if(!stat_prefix || !stat_prefix[0]) stat_prefix=strDup("gateway");
	}
	stat_prefix_len=strlen(stat_prefix);

	// Set up PV names for server stats and fill them into the
	// stat_table.  Note that initialization is to a pointer to the
	// value.  The value may have changed before the stat pvs are
	// created.  This allows the value at the time of creation to be
	// used.
	for(i=0; i < statCount; i++)
	{
		switch(i) {
#ifdef STAT_PVS
		case statVcTotal:
			stat_table[i].name="vctotal";
			stat_table[i].desc="Total VCs";
			stat_table[i].init_value=&total_vc;
			stat_table[i].units="";
			stat_table[i].precision=0;
			break;
		case statPvTotal:
			stat_table[i].name="pvtotal";
			stat_table[i].desc="Total PVs";
			stat_table[i].init_value=&total_pv;
			stat_table[i].units="";
			stat_table[i].precision=0;
			break;
		case statAlive:
			stat_table[i].name="connected";
			stat_table[i].desc="Connected PVs";
			stat_table[i].init_value=&total_alive;
			stat_table[i].units="";
			stat_table[i].precision=0;
			break;
		case statActive:
			stat_table[i].name="active";
			stat_table[i].desc="Active PVs";
			stat_table[i].init_value=&total_active;
			stat_table[i].units="";
			stat_table[i].precision=0;
			break;
		case statInactive:
			stat_table[i].name="inactive";
			stat_table[i].desc="Inactive PVs";
			stat_table[i].init_value=&total_inactive;
			stat_table[i].units="";
			stat_table[i].precision=0;
			break;
		case statUnconnected:
			stat_table[i].name="unconnected";
			stat_table[i].desc="Unconnected PVs";
			stat_table[i].init_value=&total_unconnected;
			stat_table[i].units="";
			stat_table[i].precision=0;
			break;
		case statDead:
			stat_table[i].name="dead";
			stat_table[i].desc="Dead PVs";
			stat_table[i].init_value=&total_dead;
			stat_table[i].units="";
			stat_table[i].precision=0;
			break;
		case statConnecting:
			stat_table[i].name="connecting";
			stat_table[i].desc="Connecting PVs";
			stat_table[i].init_value=&total_connecting;
			stat_table[i].units="";
			stat_table[i].precision=0;
			break;
		case statDisconnected:
			stat_table[i].name="disconnected";
			stat_table[i].desc="Disconnected PVs";
			stat_table[i].init_value=&total_disconnected;
			stat_table[i].units="";
			stat_table[i].precision=0;
			break;
# ifdef USE_FDS
		case statFd:
			stat_table[i].name="fd";
			stat_table[i].desc="FDs";
			stat_table[i].init_value=&total_fd;
			stat_table[i].units="";
			stat_table[i].precision=0;
			break;
# endif
#endif
#ifdef RATE_STATS
		case statClientEventRate:
			stat_table[i].name="clientEventRate";
			stat_table[i].desc="Client Event Rate";
			stat_table[i].init_value=&zero;
			stat_table[i].units="Hz";
			stat_table[i].precision=2;
			break;
		case statPostEventRate:
			stat_table[i].name="clientPostRate";
			stat_table[i].desc="Client Post Rate";
			stat_table[i].init_value=&zero;
			stat_table[i].units="Hz";
			stat_table[i].precision=2;
			break;
		case statExistTestRate:
			stat_table[i].name="existTestRate";
			stat_table[i].desc="Exist Test Rate";
			stat_table[i].init_value=&zero;
			stat_table[i].units="Hz";
			stat_table[i].precision=2;
			break;
		case statLoopRate:
			stat_table[i].name="loopRate";
			stat_table[i].desc="Loop Rate";
			stat_table[i].init_value=&zero;
			stat_table[i].units="Hz";
			stat_table[i].precision=2;
			break;
		case statCPUFract:
			stat_table[i].name="cpuFract";
			stat_table[i].desc="CPU Fraction";
			stat_table[i].init_value=&zero;
			stat_table[i].units="";
			stat_table[i].precision=3;
			break;
		case statLoad:
			stat_table[i].name="load";
			stat_table[i].desc="Load";
			stat_table[i].init_value=&zero;
			stat_table[i].units="";
			stat_table[i].precision=3;
			break;
#endif
#ifdef CAS_DIAGNOSTICS
		case statServerEventRate:
			stat_table[i].name="serverEventRate";
			stat_table[i].desc="Server Event Rate";
			stat_table[i].init_value=&zero;
			stat_table[i].units="Hz";
			stat_table[i].precision=2;
			break;
		case statServerEventRequestRate:
			stat_table[i].name="serverPostRate";
			stat_table[i].desc="Server Post Rate";
			stat_table[i].init_value=&zero;
			stat_table[i].units="Hz";
			stat_table[i].precision=2;
			break;
#endif
#ifdef CONTROL_PVS
		case statCommandFlag:
			stat_table[i].name="commandFlag";
			stat_table[i].desc="Command Flag";
			stat_table[i].init_value=&command_flag;
			stat_table[i].units="";
			stat_table[i].precision=0;
			break;
		case statReport1Flag:
			stat_table[i].name="report1Flag";
			stat_table[i].desc="Report 1 Flag";
			stat_table[i].init_value=&report1_flag;
			stat_table[i].units="";
			stat_table[i].precision=0;
			break;
		case statReport2Flag:
			stat_table[i].name="report2Flag";
			stat_table[i].desc="Report 2 Flag";
			stat_table[i].init_value=&report2_flag;
			stat_table[i].units="";
			stat_table[i].precision=0;
			break;
		case statReport3Flag:
			stat_table[i].name="report3Flag";
			stat_table[i].desc="Report 3 Flag";
			stat_table[i].init_value=&report3_flag;
			stat_table[i].units="";
			stat_table[i].precision=0;
			break;
		case statNewAsFlag:
			stat_table[i].name="newAsFlag";
			stat_table[i].desc="New AS Flag";
			stat_table[i].init_value=&newAs_flag;
			stat_table[i].units="";
			stat_table[i].precision=0;
			break;
		case statQuitFlag:
			stat_table[i].name="quitFlag";
			stat_table[i].desc="Quit Flag";
			stat_table[i].init_value=&quit_flag;
			stat_table[i].units="";
			stat_table[i].precision=0;
			break;
		case statQuitServerFlag:
			stat_table[i].name="quitServerFlag";
			stat_table[i].desc="Quit Server Flag";
			stat_table[i].init_value=&quitserver_flag;
			stat_table[i].units="";
			stat_table[i].precision=0;
			break;
#endif
		}

		stat_table[i].pvName=new char[stat_prefix_len+1+strlen(stat_table[i].name)+1];
		sprintf(stat_table[i].pvName,"%s:%s",stat_prefix,stat_table[i].name);
		stat_table[i].pv=NULL;
		stat_table[i].descPvName=new char[stat_prefix_len+1+strlen(stat_table[i].name)+6];
		sprintf(stat_table[i].descPvName,"%s:%s.DESC",stat_prefix,stat_table[i].name);
		stat_table[i].descPv=NULL;
	}
}

// KE: Only used in gateStat destructor
void gateServer::clearStat(int type, gateStatType statType)
{
	if(statType == GATE_STAT_TYPE_DESC) {
		stat_table[type].descPv=NULL;
	} else {
		stat_table[type].pv=NULL;
	}
}

#if defined(RATE_STATS) || defined(CAS_DIAGNOSTICS)
// Rate statistics

epicsTimerNotify:: expireStatus
gateRateStatsTimer::expire(const epicsTime &curTime)
{
	static int first=1;
	static epicsTime prevTime;
	double delTime;
#ifdef RATE_STATS
	static unsigned long cePrevCount,etPrevCount,mlPrevCount,pePrevCount ;
	static unsigned long cpuPrevCount;
	unsigned long ceCurCount=mrg->client_event_count;
	unsigned long peCurCount=mrg->post_event_count;
	unsigned long etCurCount=mrg->exist_count;
	unsigned long mlCurCount=mrg->loop_count;
	// clock really returns clock_t, which should be long
#ifdef __linux__
# ifndef USE_LINUX_PROC_FOR_CPU
	// Use clock from main process for Linux
	unsigned long cpuCurCount=mainClock;
# endif
#else
	// Use clock for other systems.  For WIN32, clock returns wall
	// clock so cpuFract always is 1.
	unsigned long cpuCurCount=(unsigned long)clock();
#endif
	double ceRate,peRate,etRate,mlRate,cpuFract;
#endif
#ifdef CAS_DIAGNOSTICS
	static unsigned long sePrevCount,srPrevCount;
	unsigned long seCurCount=mrg->subscriptionEventsProcessed();
	unsigned long srCurCount=mrg->subscriptionEventsPosted();
	double seRate,srRate;
#endif

	// Initialize the first time
	if(first)
	{
		prevTime=curTime;
#ifdef RATE_STATS
		cePrevCount=ceCurCount;
		pePrevCount=peCurCount;
		etPrevCount=etCurCount;
		mlPrevCount=mlCurCount;
		cpuPrevCount=cpuCurCount;
#endif
#ifdef CAS_DIAGNOSTICS
		sePrevCount=seCurCount;
		srPrevCount=srCurCount;
#endif
		first=0;
	}
	delTime=(double)(curTime-prevTime);

#if DEBUG_CLOCK
	static int second=1;
	if(second) {
		if(cpuCurCount > 0 && cpuPrevCount != cpuCurCount) {
			printf("%s %d cpuPrevCount=%lu cpuCurCount=%lu\n",
			  timeStamp(),second++,cpuPrevCount,cpuCurCount);
			if(second > 25) second=0;
		} else if(cpuCurCount == (unsigned long)((clock_t)(-1))) {
			printf("%s %d cpuCurCount=%ld\n",timeStamp(),second++,
			  (clock_t)cpuCurCount);
			if(second > 25) second=0;
		}
	}
#endif

#ifdef RATE_STATS
	// Calculate the client event rate
	ceRate=(delTime > 0)?(double)(ULONG_DIFF(ceCurCount,cePrevCount))/
	  delTime:0.0;
	mrg->setStat(statClientEventRate,ceRate);

	// Calculate the post event rate
	peRate=(delTime > 0)?(double)(ULONG_DIFF(peCurCount,pePrevCount))/
	  delTime:0.0;
	mrg->setStat(statPostEventRate,peRate);

	// Calculate the exist test rate
	etRate=(delTime > 0)?(double)(ULONG_DIFF(etCurCount,etPrevCount))/
	  delTime:0.0;
	mrg->setStat(statExistTestRate,etRate);

	// Calculate the main loop rate
	mlRate=(delTime > 0)?(double)(ULONG_DIFF(mlCurCount,mlPrevCount))/
	  delTime:0.0;
	mrg->setStat(statLoopRate,mlRate);

	// Calculate the CPU Fract
	// Note: clock() returns (long)-1 if it can't find the time;
	// however, we can't distinguish that -1 from a -1 owing to
	// wrapping.  So treat the return value as an unsigned long and
	// don't check the return value.
#ifdef USE_LINUX_PROC_FOR_CPU
	double timeDiff=linuxCpuTimeDiff();
	if(timeDiff < 0.0) {
		// Error
		cpuFract=-1.0;
	} else {
		cpuFract=(delTime > 0)?timeDiff/delTime:0.0;
	}
#else
	cpuFract=(delTime > 0)?(double)(ULONG_DIFF(cpuCurCount,cpuPrevCount))/
	  delTime/CLOCKS_PER_SEC:0.0;
#endif
	mrg->setStat(statCPUFract,cpuFract);

#ifndef WIN32
	// Calculate the load using average over last minute.  Does not
	// exist for WIN32.
	double load[N_LOAD];
	int nProcesses;
	nProcesses=getloadavg(load,N_LOAD);	  
	mrg->setStat(statLoad,load[N_LOAD-1]);
#endif
#endif
	
#ifdef CAS_DIAGNOSTICS
	// Calculate the server event rate
	seRate=(delTime > 0)?(double)(ULONG_DIFF(seCurCount,sePrevCount))/
	  delTime:0.0;
	mrg->setStat(statServerEventRate,seRate);

	// Calculate the server event request rate
	srRate=(delTime > 0)?(double)(ULONG_DIFF(srCurCount,srPrevCount))/
	  delTime:0.0;
	mrg->setStat(statServerEventRequestRate,srRate);
#endif

#if 0
	printf("gateRateStatsTimer::expire(): ceCurCount=%ld cePrevCount=%ld ceRate=%g\n",
	  ceCurCount,cePrevCount,ceRate);
	printf("  deltime=%g etCurCount=%ld etPrevCount=%ld etRate=%g\n",
	  delTime,etCurCount,etPrevCount,etRate);
	fflush(stdout);
#endif

	// Reset the previous values
	prevTime=curTime;
#ifdef RATE_STATS
	cePrevCount=ceCurCount;
	pePrevCount=peCurCount;
	etPrevCount=etCurCount;
	mlPrevCount=mlCurCount;
	cpuPrevCount=cpuCurCount;
#endif
#ifdef CAS_DIAGNOSTICS
	sePrevCount=seCurCount;
	srPrevCount=srCurCount;
#endif

  // Set to continue
    return epicsTimerNotify::expireStatus(restart,interval);
}
#endif  // #if defined(RATE_STATS) || defined(CAS_DIAGNOSTICS)
#endif  // #if stat_count

#ifdef USE_LINUX_PROC_FOR_CPU
// A clock routine for Linux
// From Man pages for Red Hat Linux 8.0 3.2-7
// This data may change
//    pid %d The process id.
//    comm %s
//            The filename of the executable,  in  parentheses.
//            This  is visible whether or not the executable is
//            swapped out.
//    state %c
//            One character from the string "RSDZTW" where R is
//            running,  S is sleeping in an interruptible wait,
//            D is waiting in uninterruptible disk sleep, Z  is
//            zombie, T is traced or stopped (on a signal), and
//            W is paging.
//    ppid %d
//            The PID of the parent.
//    pgrp %d
//            The process group ID of the process.
//    session %d
//            The session ID of the process.
//    tty_nr %d
//            The tty the process uses.
//    tpgid %d
//            The process group ID of the  process  which  cur-
//            rently owns the tty that the process is connected
//            to.
//    flags %lu
//            The flags of the process.  The math bit is  deci-
//            mal 4, and the traced bit is decimal 10.
//    minflt %lu
//            The  number  of minor faults the process has made
//            which have not required  loading  a  memory  page
//            from disk.
//    cminflt %lu
//            The  number  of minor faults that the process and
//            its children have made.
//    majflt %lu
//            The number of major faults the process  has  made
//            which  have  required  loading a memory page from
//            disk.
//    cmajflt %lu
//            The number of major faults that the  process  and
//            its children have made.
//    utime %lu
//            The  number of jiffies that this process has been
//            scheduled in user mode.
//    stime %lu
//            The number of jiffies that this process has  been
//            scheduled in kernel mode.
//    cutime %ld
//            The  number  of jiffies that this process and its
//            children have been scheduled in user mode.
//    cstime %ld
//            The number of jiffies that this process  and  its
//            children have been scheduled in kernel mode.
//    ...
// jiffie is .01 sec
#define SEC_PER_JIFFIE .01
static double linuxCpuTimeDiff(void)
{
	static unsigned long prevutime=0;
	static unsigned long prevstime=0;
	double retVal=-1.0;

	if(gate_pid > 0) {
		static char statfile[80]="";
		// Create the file name once
		if(!*statfile) {
			sprintf(statfile,"/proc/%d/stat",gate_pid);
		}
		FILE *fp=fopen(statfile,"r");
		if(fp) {
			int pid=0;
			char comm[1024];  // Should use MAX_PATH or PATH_MAX
			char state;
			int ppid,pgrp,session,tty_nr,tpgid;
			unsigned long flags,minflt,cminflt,majflt,cmajflt,utime=0,stime=0;
			long cutime=0,cstime=0;
			// Remove cutime and cstime for efficiency
			int count=fscanf(fp,"%d %s %c %d %d %d %d %d "
			  "%lu %lu %lu %lu %lu "
			  "%lu %lu %ld %ld",
			  &pid,comm,&state,&ppid,&pgrp,&session,&tty_nr,&tpgid,
			  &flags,&minflt,&cminflt,&majflt,&cmajflt,
			  &utime,&stime,&cutime,&cstime);
			fclose(fp);
			if(count == 17 ) {
				double utimediff=(double)ULONG_DIFF(utime,prevutime);
				double stimediff=(double)ULONG_DIFF(stime,prevstime);
				retVal=(utimediff+stimediff)*SEC_PER_JIFFIE;
#if DEBUG_CLOCK
				if(prevstime > stime) {
					printf("prevstime=%lu > stime=%lu\n",prevstime,stime);
				}
				if(prevutime > utime) {
					printf("prevutime=%lu > utime=%lu\n",prevutime,utime);
				}
#endif
				prevstime=stime;
				prevutime=utime;
			}
#if DEBUG_CLOCK
			static int nprint=0;
			if(nprint == 0) {
				printf("SEC_PER_JIFFIE=%g ULONG_MAX=%lu\n",
				  SEC_PER_JIFFIE,ULONG_MAX);
			}
			if(nprint < 1000) {
				printf("%2d utime=%lu stime=%lu cutime=%ld cstime=%ld "
				  "retVal=%g\n",
				  ++nprint,utime,stime,cutime,cstime,retVal);
			}
#endif
		}
	}
	return retVal;
}
#endif

#ifndef WIN32
void gateServer::sig_usr1(int /*x*/)
{
	gateServer::command_flag=1;
	signal(SIGUSR1,::sig_usr1);
}

void gateServer::sig_usr2(int /*x*/)
{
	gateServer::report2_flag=1;
	signal(SIGUSR2,::sig_usr2);
}
#endif


/* **************************** Emacs Editing Sequences ***************** */
/* Local Variables: */
/* tab-width: 4 */
/* c-basic-offset: 4 */
/* c-comment-only-line-offset: 0 */
/* c-file-offsets: ((substatement-open . 0) (label . 0)) */
/* End: */