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
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
use std::collections::HashSet;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use crate::error::{CaError, CaResult};
use crate::runtime::sync::RwLock;
use crate::server::record::{NotifyWaitSet, RecordInstance};
use crate::types::EpicsValue;
use super::{PvDatabase, apply_timestamp};
/// A cancellable, generation-gated handle that re-enters an async record's
/// `process()` exactly once.
///
/// C parity: epics-base `callbackRequest` / `callbackRequestDelayed`
/// (`callback.c`) post a one-shot callback that later runs the record's
/// `(*prset->process)(precord)` directly, bypassing `dbProcess`'s PACT
/// entry guard. Here, firing the token re-enters via
/// [`PvDatabase::process_record_continuation`] (the owner-driven
/// continuation that also bypasses the PACT guard).
///
/// # Cancellation is structural, not a runtime check
///
/// The record owns a monotonic generation counter (`reprocess_generation`).
/// Minting a token snapshots that counter as the token's `epoch` *after*
/// bumping it, so:
///
/// - minting a newer token for the same record (C `callbackRequestDelayed`
/// replacing an outstanding delayed callback), or
/// - [`PvDatabase::cancel_async_reentry`] (C `callbackCancelDelayed`),
///
/// each advance the counter past every outstanding token's `epoch`. A
/// stale token therefore re-enters *nothing*: [`AsyncToken::fire`] is the
/// sole re-entry path, the epoch comparison is owned in one place, and the
/// token is consumed (`self` by value) so it cannot fire twice. A consumer
/// never writes an `if generation == ...` guard — it holds the token and
/// calls `fire`; the no-op-when-stale is guaranteed by construction.
pub struct AsyncToken {
/// Canonical record name to re-enter.
name: String,
/// Shared generation counter owned by the record
/// (`RecordInstance::reprocess_generation`).
generation: Arc<AtomicU64>,
/// Generation value captured at mint time. The token is current iff
/// `generation == epoch`.
epoch: u64,
}
impl AsyncToken {
/// The record this token re-enters.
pub fn record_name(&self) -> &str {
&self.name
}
/// True iff this token is still the current generation — no newer
/// token was minted and no [`PvDatabase::cancel_async_reentry`] has
/// run for the record since this token was minted. Read-only.
pub fn is_current(&self) -> bool {
self.generation.load(Ordering::Acquire) == self.epoch
}
/// Cancel this token (C `callbackCancelDelayed` for the holder's own
/// pending re-entry): advance the generation so this and any other
/// outstanding token for the record become stale, then consume the
/// token. Use when the holder itself decides not to re-enter; use
/// [`PvDatabase::cancel_async_reentry`] to cancel a token already
/// handed to a timer / notify task.
pub fn cancel(self) {
self.generation.fetch_add(1, Ordering::AcqRel);
}
/// Fire the continuation: if still current, re-enter the record's
/// `process()` via [`PvDatabase::process_record_continuation`]. A
/// stale (superseded / cancelled) token is a no-op. Consumes the
/// token so it cannot fire twice.
pub async fn fire(self, db: &PvDatabase) -> CaResult<()> {
if self.generation.load(Ordering::Acquire) != self.epoch {
return Ok(());
}
let mut visited = HashSet::new();
db.process_record_continuation(&self.name, &mut visited, 0)
.await
}
}
/// A cycle-free handle for driving async-side database updates from
/// OUTSIDE a record's `process()` cycle.
///
/// Wraps a [`std::sync::Weak`] reference to the database: a record stashes
/// it (via [`crate::server::record::Record::set_async_context`]) without
/// creating an ownership cycle — the database owns the record, so a strong
/// `Arc<PvDatabaseInner>` stored on the record would leak the whole
/// database. Every call upgrades the `Weak` to a temporary [`PvDatabase`];
/// once the last strong owner drops, the upgrade fails and the call is a
/// no-op (nothing is stranded).
///
/// This is the out-of-band counterpart to the in-band re-entry
/// [`crate::server::record::ProcessAction`]s: a driver / callback thread
/// (asyn TRACE post, AQR cancel, motor intermediate readback) holds the
/// handle and pushes field updates or wires a completion-driven re-entry
/// without going through `process()`. It exposes exactly the c401e2f0
/// PACT primitive surface, each call guarded by the live-database check.
#[derive(Clone)]
pub struct AsyncDbHandle {
inner: std::sync::Weak<super::PvDatabaseInner>,
}
impl AsyncDbHandle {
/// Upgrade to a temporary owning [`PvDatabase`], or `None` if the
/// database has been dropped.
fn db(&self) -> Option<PvDatabase> {
self.inner.upgrade().map(|inner| PvDatabase { inner })
}
/// True while the backing database is still alive.
pub fn is_alive(&self) -> bool {
self.inner.strong_count() > 0
}
/// Out-of-band field post — see [`PvDatabase::post_fields`]. Returns an
/// empty `Vec` (no-op) if the database has been dropped.
pub async fn post_fields(
&self,
name: &str,
fields: Vec<(String, EpicsValue)>,
) -> CaResult<Vec<String>> {
match self.db() {
Some(db) => db.post_fields(name, fields).await,
None => Ok(Vec::new()),
}
}
/// Resolve a link's target field type for the sseq link-status
/// diagnostics — see [`PvDatabase::link_target_field_type`]. `None` if
/// the link is constant / external / unresolvable, or the database is
/// gone. (Distinct from the free `server::record::link_field_type`,
/// which returns the link *class* `LinkType`, not the target's type.)
pub async fn link_target_field_type(&self, link: &str) -> Option<crate::types::DbFieldType> {
match self.db() {
Some(db) => db.link_target_field_type(link).await,
None => None,
}
}
/// Mint an async re-entry token — see [`PvDatabase::mint_async_token`].
/// `None` if the record is absent or the database has been dropped.
pub async fn mint_async_token(&self, name: &str) -> Option<AsyncToken> {
match self.db() {
Some(db) => db.mint_async_token(name).await,
None => None,
}
}
/// Cancel an outstanding async re-entry — see
/// [`PvDatabase::cancel_async_reentry`]. No-op if the database is gone.
pub async fn cancel_async_reentry(&self, name: &str) {
if let Some(db) = self.db() {
db.cancel_async_reentry(name).await;
}
}
/// Arm a put-notify wait-set — see [`PvDatabase::new_put_notify`].
/// Database-independent (re-exported associated fn).
pub fn new_put_notify() -> (
Arc<NotifyWaitSet>,
crate::runtime::sync::oneshot::Receiver<()>,
) {
PvDatabase::new_put_notify()
}
/// Wire a completion oneshot to an async re-entry — see
/// [`PvDatabase::reprocess_on_notify`]. `None` if the database is gone
/// (the `completion` receiver is dropped, stranding nothing).
pub fn reprocess_on_notify(
&self,
token: AsyncToken,
completion: crate::runtime::sync::oneshot::Receiver<()>,
) -> Option<tokio::task::JoinHandle<()>> {
self.db()
.map(|db| db.reprocess_on_notify(token, completion))
}
/// Issue a non-blocking put-with-completion to an OUT link — see
/// [`PvDatabase::put_link_notify`]. `None` if the database is gone or
/// the source record is missing.
pub async fn put_link_notify(
&self,
record_name: &str,
link_str: &str,
value: EpicsValue,
) -> Option<crate::runtime::sync::oneshot::Receiver<()>> {
match self.db() {
Some(db) => db.put_link_notify(record_name, link_str, value).await,
None => None,
}
}
}
/// C `dbNotifyAdd`: a will-process PP target (FLNK / OUT) joins the active
/// put-notify wait-set exactly once, so the completion waits for it. Called
/// only on the `!pact` (will-process) branch — a busy target sets RPRO and
/// does not join (matching the pre-fix drop behaviour), and the
/// `notify.is_none()` guard prevents a double-join when a record is reached
/// again within the same chain.
pub(super) fn join_put_notify(
target: &mut RecordInstance,
src_notify: Option<&Arc<NotifyWaitSet>>,
) {
if target.notify.is_none() {
if let Some(ws) = src_notify {
target.notify = Some(ws.clone());
ws.enter();
}
}
}
/// C `dbNotifyCompletion`: this record finished its contribution to the
/// put-notify (sync completion, async completion, or SDIS-disable bail).
/// Take its wait-set membership and leave — the completion oneshot fires on
/// the `leave` that empties the set. Idempotent: a record not in any
/// put-notify is a no-op.
fn complete_put_notify(inst: &mut RecordInstance) {
if let Some(ws) = inst.notify.take() {
ws.leave();
}
}
/// If a CA TSEL link's pvname targets a record's `.TIME` field, return
/// the record name with the `.TIME` suffix stripped; otherwise `None`.
///
/// Mirrors C `TSEL_modified` (dbLink.c:80-86): a `PV_LINK` tsel whose
/// pvname contains `.TIME` is flagged `DBLINK_FLAG_TSELisTIME` and the
/// name is truncated at `.TIME` to address the record. Matched on the
/// `.TIME` suffix (the realistic spelling) case-insensitively, to stay
/// consistent with the DB branch's `field.eq_ignore_ascii_case("TIME")`.
fn ca_tsel_time_record(pv: &str) -> Option<&str> {
let idx = pv.len().checked_sub(".TIME".len())?;
pv[idx..]
.eq_ignore_ascii_case(".TIME")
.then_some(&pv[..idx])
}
/// Convert an lset `(seconds_past_epoch, nanos, userTag)` timestamp
/// triple into the record-side `(SystemTime, userTag)` pair, clamping
/// seconds/nanos to the valid `Duration` range. Shared by the TSEL
/// `.TIME` Ca arm and the non-local Db arm — both read a `ca://` `.TIME`
/// source through `external_link_time` and adopt the result identically.
fn ext_time_pair((secs, ns, utag): (i64, i32, u64)) -> (std::time::SystemTime, u64) {
let secs = secs.max(0) as u64;
let ns = (ns.max(0) as u32).min(999_999_999);
(
std::time::UNIX_EPOCH + std::time::Duration::new(secs, ns),
utag,
)
}
/// The source record's put-propagation context for the forward-link tail.
/// C `processTarget` (dbDbLink.c:460-474) carries `psrc->putf` and
/// `psrc->ppn` to each target as a unit — the PUTF bit and the put-notify
/// wait-set always travel together. Bundled so the tail threads one
/// snapshot instead of a `(putf, notify)` pair.
#[derive(Clone, Copy)]
struct PutNotifyCtx<'a> {
putf: bool,
notify: Option<&'a Arc<NotifyWaitSet>>,
}
/// Result of the simulation-mode check.
///
/// C `aiRecord.c:151-168` handles simulation entirely inside
/// `readValue()`; `process()` then ALWAYS runs `convert`/`checkAlarms`/
/// `monitor`/`recGblFwdLink(prec)`. A simulated record therefore must
/// NOT skip the forward-link / CP / RPRO tail — only the device read
/// and record-support body are replaced by the SIOL round-trip.
enum SimOutcome {
/// SIMM disabled / no simulation link configured: run the record
/// body normally.
NotSimulated,
/// Simulation handled the record value (SIOL read/write done).
/// The caller must still run the forward-link / CP / RPRO tail
/// exactly as `recGblFwdLink` does for a real process cycle.
Simulated,
}
impl PvDatabase {
/// Process a record by name (process_local + notify).
/// Alias-aware (epics-base PR #336).
pub async fn process_record(&self, name: &str) -> CaResult<()> {
self.process_record_inner(name, true).await
}
/// `process_record` variant for a caller that already
/// owns the record's advisory write gate — the QSRV atomic group
/// PUT applying a `+proc` member. The gate `Mutex` is not
/// reentrant; the atomic group path MUST use this entry. See
/// [`crate::server::database::PvDatabase::lock_records`].
pub async fn process_record_already_locked(&self, name: &str) -> CaResult<()> {
self.process_record_inner(name, false).await
}
async fn process_record_inner(&self, name: &str, acquire_gate: bool) -> CaResult<()> {
let rec = self.get_record(name).await;
if let Some(rec) = rec {
// advisory write gate (`dbScanLock` analogue). A
// QSRV atomic group with a `+proc` member holds this
// record's gate via `lock_records`; a direct
// `process_record` on the same backing record must block
// until the atomic group transaction completes. Skipped
// when the caller already owns the gate.
let _record_gate = if acquire_gate {
let canonical = self
.resolve_alias(name)
.await
.unwrap_or_else(|| name.to_string());
Some(self.lock_record(&canonical).await)
} else {
None
};
let (snapshot, alarm_posts) = {
let mut instance = rec.write().await;
instance.process_local()?
};
// Notify outside lock
let instance = rec.read().await;
instance.notify_from_snapshot(&snapshot);
// Post the alarm fields (SEVR/STAT/ACKS) with their
// individual C masks — see `process_local` / recGblResetAlarms.
for &(field, mask) in &alarm_posts {
instance.notify_field(field, mask);
}
Ok(())
} else {
Err(CaError::ChannelNotFound(name.to_string()))
}
}
/// Process a record with full link handling (INP -> process -> alarms -> OUT -> FLNK).
/// Uses visited set for cycle detection and depth limit.
///
/// Foreign-caller entry: FLNK dispatch, scan loop, scan_event, CA put,
/// process(PROC=1) etc. Hits the PACT entry guard (mirrors C `dbProcess`
/// at `dbAccess.c:537-559`) when the record is mid-async.
///
/// this is a *foreign* full-processing entry, so it acquires
/// the record's advisory write gate (`dbScanLock` analogue) for the
/// entry record before processing. A QSRV atomic group or pvalink
/// atomic scan-on-update epoch that holds `lock_records` over the
/// same record blocks a foreign scan/event/FLNK-dispatch caller
/// here, and vice versa — restoring the `DBManyLock` exclusion. The
/// recursive FLNK / OUT / CP fan-out within one chain does NOT
/// re-acquire the gate (`process_record_with_links_recursive`),
/// mirroring C `processTarget` (`dbDbLink.c:436`) which asserts the
/// target's lock set is already owned by the calling thread; the
/// `visited` cycle guard prevents re-processing the entry record.
pub fn process_record_with_links<'a>(
&'a self,
name: &'a str,
visited: &'a mut HashSet<String>,
depth: usize,
) -> std::pin::Pin<Box<dyn std::future::Future<Output = CaResult<()>> + Send + 'a>> {
Box::pin(async move {
self.process_record_with_links_inner(name, visited, depth, false, true)
.await
})
}
/// full-processing entry for a caller that already owns the
/// record's advisory write gate via [`PvDatabase::lock_records`] —
/// the QSRV atomic group GET/PUT and the pvalink atomic
/// scan-on-update epoch. The advisory gate `Mutex` is not
/// reentrant; a transaction owner holding `lock_records` over the
/// member set MUST use this entry to scan a member record, or it
/// would deadlock against its own epoch guard. Foreign (non-owner)
/// callers must use [`Self::process_record_with_links`] so the gate
/// is taken.
pub fn process_record_with_links_already_locked<'a>(
&'a self,
name: &'a str,
visited: &'a mut HashSet<String>,
depth: usize,
) -> std::pin::Pin<Box<dyn std::future::Future<Output = CaResult<()>> + Send + 'a>> {
Box::pin(async move {
self.process_record_with_links_inner(name, visited, depth, false, false)
.await
})
}
/// recursive FLNK / OUT / CP fan-out entry within a single
/// processing chain. Does NOT re-acquire the advisory write gate:
/// the chain is one transaction whose entry record's gate is
/// already held by the foreign entry, and C `processTarget`
/// (`dbDbLink.c:436`) processes a link target under the lock set
/// already owned by the calling thread. Re-acquiring per chain
/// member would also create a lock-ordering deadlock between
/// reverse FLNK chains.
pub(crate) fn process_record_with_links_recursive<'a>(
&'a self,
name: &'a str,
visited: &'a mut HashSet<String>,
depth: usize,
) -> std::pin::Pin<Box<dyn std::future::Future<Output = CaResult<()>> + Send + 'a>> {
Box::pin(async move {
self.process_record_with_links_inner(name, visited, depth, false, false)
.await
})
}
/// Owner-driven continuation re-entry — bypasses the PACT entry guard.
///
/// Used by `ProcessAction::ReprocessAfter` timer fires: the spawned
/// re-entry task IS the owner of the async cycle, equivalent to C
/// `callbackRequestDelayed`'s direct call to the record's `process()`
/// (which bypasses `dbProcess`). Foreign callers must still go through
/// `process_record_with_links` so FLNK / scan / CA put cannot race
/// during the wait window.
///
/// the timer fire is a fresh task — the original cycle's
/// advisory gate was released when `process_record_with_links`
/// returned async-pending. In C, `callbackRequestDelayed` dispatches
/// through a callback that re-takes `dbScanLock(precord)` for the
/// completion `process()`. This entry therefore re-acquires the
/// advisory write gate, so the continuation cannot interleave with a
/// QSRV atomic group or another foreign scan of the same record.
pub fn process_record_continuation<'a>(
&'a self,
name: &'a str,
visited: &'a mut HashSet<String>,
depth: usize,
) -> std::pin::Pin<Box<dyn std::future::Future<Output = CaResult<()>> + Send + 'a>> {
Box::pin(async move {
self.process_record_with_links_inner(name, visited, depth, true, true)
.await
})
}
/// A cycle-free [`AsyncDbHandle`] for this database, handed to each
/// record via [`crate::server::record::Record::set_async_context`] at
/// registration. Holds only a `Weak` reference, so a record stashing
/// it never keeps the database alive.
pub fn async_handle(&self) -> AsyncDbHandle {
AsyncDbHandle {
inner: Arc::downgrade(&self.inner),
}
}
/// Mint a fresh async re-entry [`AsyncToken`] for `name`.
///
/// Minting advances the record's generation counter, so any
/// previously-minted token for the same record is superseded — its
/// [`AsyncToken::fire`] becomes a structural no-op. This mirrors C
/// `callbackRequestDelayed` replacing an outstanding delayed callback
/// for a record. `name` must be the canonical record name (the value
/// of `RecordInstance::name`). Returns `None` if the record is absent.
pub async fn mint_async_token(&self, name: &str) -> Option<AsyncToken> {
let records = self.inner.records.read().await;
let rec = records.get(name)?;
let generation = rec.read().await.reprocess_generation.clone();
let epoch = generation.fetch_add(1, Ordering::AcqRel) + 1;
Some(AsyncToken {
name: name.to_string(),
generation,
epoch,
})
}
/// Cancel any outstanding async re-entry token for `name` (C
/// `callbackCancelDelayed`): advance the record's generation counter so
/// every previously-minted [`AsyncToken`] for it becomes stale and its
/// `fire` is a no-op. A subsequent [`Self::mint_async_token`] produces a
/// fresh, current token. No-op if the record is absent.
pub async fn cancel_async_reentry(&self, name: &str) {
let records = self.inner.records.read().await;
if let Some(rec) = records.get(name) {
rec.read()
.await
.reprocess_generation
.fetch_add(1, Ordering::AcqRel);
}
}
/// Post an async-side field update for `name` — the C `db_post_events`
/// analogue called from device-support / async-callback context.
///
/// Each `(field, value)` is written through the internal put (bypassing
/// the read-only field gate, like a record's own `process()` writes)
/// and a monitor event is posted with `DBE_VALUE | DBE_LOG` — the mask C
/// device support uses for an out-of-process value post
/// (`db_post_events(precord, &prec->field, DBE_VALUE | DBE_LOG)`).
/// Metadata-class writes invalidate the metadata cache via
/// `notify_field_written`, honouring the snapshot-cache contract.
///
/// Unlike [`Self::complete_async_record`], this runs *no* alarm /
/// timestamp / FLNK tail: it is the immediate "push these fields to
/// monitors now" primitive (e.g. asyn TRACE info, motor intermediate
/// readback) that is independent of any process cycle. Returns the
/// field names actually posted, or [`CaError::ChannelNotFound`] if the
/// record is absent.
pub async fn post_fields(
&self,
name: &str,
fields: Vec<(String, EpicsValue)>,
) -> CaResult<Vec<String>> {
self.post_fields_with_mask(
name,
fields,
crate::server::recgbl::EventMask::VALUE | crate::server::recgbl::EventMask::LOG,
)
.await
}
/// Out-of-band PROPERTY-class field post — the C
/// `db_post_events(precord, &precord->val, DBE_PROPERTY)` analogue used
/// for enum-string table re-propagation (asyn `callbackEnum`,
/// devAsynInt32.c:711-762). Writes each `(field, value)` through the
/// internal put, invalidates the metadata cache, and posts a
/// `DBE_PROPERTY` event so subscribers re-read enum choices / control
/// metadata.
///
/// Unlike [`Self::post_fields`] (which posts `DBE_VALUE | DBE_LOG`) this
/// signals a *property* change, not a value change: a driver that re-keys
/// its enum strings has not produced a new reading, only new choice
/// labels. Returns the field names actually posted.
pub async fn post_property_fields(
&self,
name: &str,
fields: Vec<(String, EpicsValue)>,
) -> CaResult<Vec<String>> {
self.post_fields_with_mask(name, fields, crate::server::recgbl::EventMask::PROPERTY)
.await
}
/// Shared body of [`Self::post_fields`] / [`Self::post_property_fields`]:
/// write+notify each field under one record-write lock, posting `mask`.
async fn post_fields_with_mask(
&self,
name: &str,
fields: Vec<(String, EpicsValue)>,
mask: crate::server::recgbl::EventMask,
) -> CaResult<Vec<String>> {
let rec = {
let records = self.inner.records.read().await;
records.get(name).cloned()
};
let rec = rec.ok_or_else(|| CaError::ChannelNotFound(name.to_string()))?;
let mut inst = rec.write().await;
let mut posted = Vec::with_capacity(fields.len());
for (field, value) in fields {
inst.record.put_field_internal(&field, value)?;
// Snapshot-cache contract: a metadata-class write must
// invalidate the cache before the monitor snapshot is built.
inst.notify_field_written(&field);
inst.notify_field(&field, mask);
posted.push(field);
}
Ok(posted)
}
/// Resolve a link's target field [`DbFieldType`] for a LOCAL `DB_LINK`,
/// or `None` for a constant / external / unresolvable link.
///
/// Parity of C `dbGetLinkDBFtype` as `sseqRecord.c:checkLinks`
/// (sseqRecord.c:884-941) uses it to fill the `DTn`/`LTn` diagnostics:
/// a `DB_LINK` whose target record is on this IOC reports its addressed
/// field's type (C `dbNameToAddr` → `pAddr->field_type`). A constant or
/// `CA`/`PVA` (external) link returns `None` — epics-base-rs has no
/// client-side introspection of a remote field's type, so the caller
/// renders those as the `DBF_unknown` sentinel.
pub(crate) async fn link_target_field_type(
&self,
link: &str,
) -> Option<crate::types::DbFieldType> {
let db = match crate::server::record::parse_link_v2(link) {
crate::server::record::ParsedLink::Db(db) => db,
_ => return None,
};
let rec = self.get_record(&db.record).await?;
let inst = rec.read().await;
let field = if db.field.is_empty() {
"VAL"
} else {
db.field.as_str()
};
inst.record
.field_list()
.iter()
.find(|f| f.name.eq_ignore_ascii_case(field))
.map(|f| f.dbf_type)
}
/// Create a put-notify wait-set for a downstream operation a record is
/// about to drive, returning the wait-set (to attach to the downstream
/// target instance's `notify`) and the completion receiver.
///
/// C `dbNotify.c` `processNotify`: the set arms `pending = 1` for the
/// downstream operation and fires the oneshot when that slot (plus any
/// FLNK/OUT chain members that `enter` it) drains to zero — i.e. on
/// `dbNotifyCompletion`. Pair with [`Self::reprocess_on_notify`] to
/// re-enter a waiting record when the downstream completes (SSEQ
/// `WAITn`).
pub fn new_put_notify() -> (
Arc<NotifyWaitSet>,
crate::runtime::sync::oneshot::Receiver<()>,
) {
let (tx, rx) = crate::runtime::sync::oneshot::channel();
(NotifyWaitSet::new(tx), rx)
}
/// Wire a downstream put-notify completion to an async re-entry: spawn a
/// task that awaits `completion` (the oneshot from
/// [`Self::new_put_notify`], fired on `dbNotifyCompletion`) and then
/// `token.fire`s, re-entering the waiting record's `process()`. A
/// superseded / cancelled token re-enters nothing. Returns the spawned
/// task handle; fire-and-forget callers may drop it.
pub fn reprocess_on_notify(
&self,
token: AsyncToken,
completion: crate::runtime::sync::oneshot::Receiver<()>,
) -> tokio::task::JoinHandle<()> {
let db = self.clone();
tokio::spawn(async move {
// `Err` means the sender was dropped without firing (the
// downstream op vanished); treat it the same as completion so a
// waiting record is never stranded — `fire` is a no-op if the
// token was meanwhile superseded.
let _ = completion.await;
let _ = token.fire(&db).await;
})
}
/// Issue a put-WITH-completion to an OUT link and hand the caller only
/// the completion receiver — the non-blocking sibling of
/// [`Self::reprocess_on_notify`].
///
/// Each call mints its own put-notify wait-set (C `dbProcessNotify`),
/// writes the link through it with the source record's committed PUTF /
/// alarm propagated (C `recGblInheritSevrMsg`), releases the initiator
/// count, and returns the oneshot that fires on `dbNotifyCompletion`.
/// The caller owns when (and whether) to await each receiver, so several
/// puts can be outstanding at once — unlike
/// [`ProcessAction::WriteDbLinkNotify`], which wires the completion
/// straight to a single superseding async re-entry token and so allows
/// only one outstanding put per record. This is the seam C
/// `calcApp/src/sseqRecord.c` needs to run multiple `WAITn` put-callbacks
/// concurrently in flight (`processNextLink`).
///
/// `record_name` is the source whose PUTF/alarm propagate into the
/// target, `link_str` the already-resolved OUT link spelling, `value`
/// the value to write. `None` if the source record is gone; an empty
/// `link_str` returns a receiver that fires immediately (nothing joined
/// the set).
pub async fn put_link_notify(
&self,
record_name: &str,
link_str: &str,
value: EpicsValue,
) -> Option<crate::runtime::sync::oneshot::Receiver<()>> {
let (src_putf, src_alarm) = {
let rec = {
let records = self.inner.records.read().await;
records.get(record_name)?.clone()
};
let instance = rec.read().await;
(
instance.common.putf,
super::links::LinkAlarm {
stat: instance.common.stat,
sevr: instance.common.sevr,
amsg: instance.common.amsg.clone(),
},
)
};
let (waitset, completion) = Self::new_put_notify();
if !link_str.is_empty() {
let parsed = crate::server::record::parse_link_v2(link_str);
// Seed the cycle-guard with the source so a target linking back
// does not re-process it, exactly as a top-level OUT-link write
// does (`process_record_with_links_inner` inserts its own name).
let mut visited = HashSet::new();
visited.insert(record_name.to_string());
self.write_out_link_value(
&parsed,
value,
super::links::OutLinkSrc {
putf: src_putf,
notify: Some(&waitset),
alarm: &src_alarm,
},
&mut visited,
0,
)
.await;
}
// Release the initiator's own count (C `dbProcessNotify` holds one
// count for the requester and drops it after issuing the put). The
// set then drains — firing `completion` — when the downstream
// target(s) that joined via `join_put_notify` finish, or immediately
// when the link was empty / the target completed synchronously.
waitset.leave();
Some(completion)
}
async fn process_record_with_links_inner(
&self,
name: &str,
visited: &mut HashSet<String>,
depth: usize,
is_continuation: bool,
acquire_gate: bool,
) -> CaResult<()> {
const MAX_LINK_DEPTH: usize = 16;
const MAX_LINK_OPS: usize = 256;
// Normalise to the canonical record name once at entry — both
// for cycle-detection (`visited` would otherwise treat alias
// and canonical as distinct entries) and for the records-map
// lookup below. Mirrors epics-base PR #336.
let canonical_owned;
let name: &str = if let Some(target) = self.resolve_alias(name).await {
canonical_owned = target;
&canonical_owned
} else {
name
};
if depth >= MAX_LINK_DEPTH {
eprintln!("link chain depth limit reached at record {name}");
return Ok(());
}
if visited.len() >= MAX_LINK_OPS {
eprintln!("link chain ops budget exhausted at record {name}");
return Ok(());
}
if !visited.insert(name.to_string()) {
return Ok(()); // Cycle detected, skip
}
let rec = {
let records = self.inner.records.read().await;
records.get(name).cloned()
};
let rec = match rec {
Some(r) => r,
None => return Err(CaError::ChannelNotFound(name.to_string())),
};
// advisory write gate (`dbScanLock(precord)` analogue).
// A foreign full-processing entry (scan loop, scan_event, FLNK
// dispatch from another chain, CA put, PINI/startup) acquires
// the entry record's gate so it cannot interleave with a QSRV
// atomic group or a pvalink atomic scan epoch holding
// `lock_records` over the same record. `name` is already the
// alias-resolved canonical name, the same key `lock_records`
// uses. Not acquired when `acquire_gate` is false: either a
// transaction owner already holds the gate via `lock_records`
// (`process_record_with_links_already_locked`), or this is a
// recursive FLNK/OUT/CP call within one chain
// (`process_record_with_links_recursive`) — C `processTarget`
// processes a link target under the lock set the caller already
// owns, and re-acquiring would deadlock the non-reentrant gate.
let _record_gate = if acquire_gate {
Some(self.lock_record(name).await)
} else {
None
};
// 0a. PACT entry guard — mirrors C `dbProcess` (dbAccess.c:537-559).
// If the record is currently mid-async (PACT=true), do NOT re-enter
// the body. Instead increment LCNT; after MAX_LOCK=10 consecutive
// attempts raise SCAN_ALARM/INVALID with "Async in progress" and
// post a monitor on VAL (DBE_VALUE|DBE_LOG). Up to MAX_LOCK we just
// bail out silently so transient back-to-back scans don't immediately
// alarm the record.
//
// Without this guard, FLNK / scan-loop / event scans dispatched onto
// a record whose first cycle is still pending (async device support,
// CA put_notify on PUTF) would re-enter `record.process()` while the
// device's first response is still in flight — corrupting the
// record's internal state machine and bypassing the C-parity
// contract that callers see for `dbProcess`. The pre-existing
// `dispatch_cp_targets` path already did this check (sets RPRO=true
// and skips); the main entry was missing it.
if !is_continuation {
const MAX_LOCK: i16 = 10;
let mut instance = rec.write().await;
if instance.is_processing() {
// C `dbAccess.c:539-541` — when TPRO is set on a record
// whose PACT is true, print the diagnostic line before
// the bail decision. The C path emits:
// "%s: dbProcess of Active '%s' with RPRO=%d"
// mirroring the same context format the regular trace
// path below uses (thread/client name + record name +
// current RPRO bit). Without this, an operator
// debugging a stuck async record sees NO sign that the
// entry guard is firing — they only notice the
// eventual SCAN_ALARM after MAX_LOCK=10 attempts.
if instance.common.tpro {
eprintln!(
"[TPRO] {}: dbProcess of Active '{}' with RPRO={}",
instance.name,
instance.name,
if instance.common.rpro { 1 } else { 0 },
);
}
let stat = instance.common.stat;
let already_invalid =
instance.common.sevr >= crate::server::record::AlarmSeverity::Invalid;
let already_scan_alarm = stat == crate::server::recgbl::alarm_status::SCAN_ALARM;
let lcnt_before = instance.common.lcnt;
instance.common.lcnt = lcnt_before.saturating_add(1);
if already_scan_alarm || lcnt_before < MAX_LOCK || already_invalid {
// Bail out without raising alarm yet.
return Ok(());
}
// Raise SCAN_ALARM/INVALID, reset alarm transition,
// and post VAL monitor (DBE_VALUE | DBE_LOG).
crate::server::recgbl::rec_gbl_set_sevr_msg(
&mut instance.common,
crate::server::recgbl::alarm_status::SCAN_ALARM,
crate::server::record::AlarmSeverity::Invalid,
"Async in progress",
);
let _ = crate::server::recgbl::rec_gbl_reset_alarms(&mut instance.common);
// Post VAL with VALUE|LOG|ALARM (C `db_post_events(prec,
// &VAL, DBE_VALUE|DBE_LOG)` plus recGblResetAlarms'
// `val_mask = DBE_ALARM` for the fresh transition). The
// alarm fields carry their C per-field masks
// (recGbl.c:201-220): this guard only runs on a fresh
// SCAN_ALARM/INVALID raise, so sevr AND stat both moved —
// SEVR posts DBE_VALUE, STAT/AMSG post the shared
// `stat_mask` = DBE_ALARM|DBE_VALUE.
use crate::server::recgbl::EventMask;
let stat_mask = EventMask::ALARM | EventMask::VALUE;
let mut changed_fields = Vec::new();
if let Some(val) = instance.record.val() {
changed_fields.push((
"VAL".to_string(),
val,
EventMask::VALUE | EventMask::LOG | EventMask::ALARM,
));
}
changed_fields.push((
"SEVR".to_string(),
EpicsValue::Short(instance.common.sevr as i16),
EventMask::VALUE,
));
changed_fields.push((
"STAT".to_string(),
EpicsValue::Short(instance.common.stat as i16),
stat_mask,
));
// Include AMSG so subscribers reading the alarm text
// observe "Async in progress" alongside the SCAN_ALARM
// transition (C `recGbl.c:210-211` posts STAT and AMSG
// together when `stat_mask` is non-zero).
changed_fields.push((
"AMSG".to_string(),
EpicsValue::String(instance.common.amsg.clone().into()),
stat_mask,
));
let snapshot = crate::server::record::ProcessSnapshot { changed_fields };
drop(instance);
let inst = rec.read().await;
inst.notify_from_snapshot(&snapshot);
return Ok(());
}
// Not pact: reset lcnt (mirrors C `else { precord->lcnt = 0; }`
// at dbAccess.c:559) so the next async cycle starts clean.
instance.common.lcnt = 0;
}
// 0. SDIS disable check — C parity dbAccess.c:562-592.
//
// When the SDIS link evaluates to a value equal to DISV, the
// record is disabled and bails before record support runs. C
// ALWAYS clears rpro/putf and triggers dbNotifyCompletion at
// this point — regardless of whether the alarm transition
// fires — because a disabled record must not leave behind
// pending reprocess requests or stranded put_notify completion
// callbacks. Pre-fix the Rust port only reset
// nsta/nsev and updated the alarm state, leaking rpro/putf
// into the next cycle and stalling CA WRITE_NOTIFY callers
// (the put_notify_tx never fired so the CA dispatcher waited
// until socket disconnect to release the operation).
{
let (sdis_link, disv, diss) = {
let instance = rec.read().await;
(
instance.parsed_sdis.clone(),
instance.common.disv,
instance.common.diss,
)
};
// C `dbGetLink(&precord->sdis, DBR_SHORT, &precord->disa, 0, 0)`
// reads the SDIS link regardless of its type (DB / CA / PVA /
// constant) via the lset. The pre-fix port only refreshed
// `disa` from a `ParsedLink::Db` SDIS, so a remote-sourced
// (CA/PVA) or constant enable/disable was silently ignored.
if let Some(val) = self.read_link_value_no_process(&sdis_link).await {
let disa_val = val.to_f64().unwrap_or(0.0) as i16;
let mut instance = rec.write().await;
instance.common.disa = disa_val;
}
let disa = rec.read().await.common.disa;
if disa == disv {
let notify = {
let mut instance = rec.write().await;
// C `dbAccess.c:575-577` — clear rpro/putf and arm
// notifyCompletion BEFORE the alarm check. Disabled
// records skip processing entirely, so any pending
// reprocess request is dropped (the next non-
// disabled cycle will pick up fresh state) and the
// CA put-notify caller must be released. A disabled
// record drives no FLNK/OUT chain, so leaving the
// wait-set here is its whole contribution.
instance.common.rpro = false;
instance.common.putf = false;
let notify = instance.notify.take();
// Reset nsta/nsev so stale alarm state doesn't bleed
// into a subsequent (re-enabled) cycle. C resets
// them after the sevr/stat transition; doing it
// first here is observationally identical because
// the SDIS bail short-circuits any record-support
// path that could read them.
instance.common.nsta = 0;
instance.common.nsev = crate::server::record::AlarmSeverity::NoAlarm;
// C `dbAccess.c:580-581` — if already in
// DISABLE_ALARM, the alarm post is skipped entirely
// (the alarm cycle is debounced). The rpro/putf
// clear above still ran, matching C's pre-`goto
// all_done` ordering.
if instance.common.stat != crate::server::recgbl::alarm_status::DISABLE_ALARM {
use crate::server::recgbl::EventMask;
instance.common.sevr = diss;
instance.common.stat = crate::server::recgbl::alarm_status::DISABLE_ALARM;
// C `dbAccess.c:586-593` posts each field with
// its own mask:
// db_post_events(&stat, DBE_VALUE);
// db_post_events(&sevr, DBE_VALUE);
// db_post_events(&val, DBE_VALUE|DBE_ALARM);
// STAT/SEVR get DBE_VALUE only — a DBE_ALARM-only
// subscriber on `.STAT`/`.SEVR` must NOT receive
// this disable event. Only the value field
// carries DBE_ALARM.
instance.notify_field("STAT", EventMask::VALUE);
instance.notify_field("SEVR", EventMask::VALUE);
instance.notify_field("VAL", EventMask::VALUE | EventMask::ALARM);
}
notify
};
// Fire dbNotifyCompletion outside the record lock —
// C `dbAccess.c:622-623` runs it at `all_done` after
// the disable bail. Without this, a CA WRITE_NOTIFY
// landing on a disabled record stalls until socket
// disconnect. `leave` fires the completion oneshot when
// this empties the wait-set.
if let Some(ws) = notify {
ws.leave();
}
return Ok(());
}
}
// 0.3. TSEL link: C `recGblGetTimeStampSimm` (recGbl.c:310-323).
//
// When `TSEL` is a non-constant link, C distinguishes two
// cases by the link target field:
// * the link points at another record's `.TIME` field
// (`DBLINK_FLAG_TSELisTIME`) — copy that record's
// timestamp directly into `prec->time`;
// * otherwise `dbGetLink(&tsel, DBR_SHORT, &prec->tse)` —
// load `TSE` from the link before the event lookup.
{
let tsel_link = {
let instance = rec.read().await;
instance.parsed_tsel.clone()
};
// A TSEL link pointing at a `.TIME` field copies that record's
// timestamp+utag into `time`/`utag` and marks TSE=-2 so
// `apply_timestamp` leaves them alone. C `TSEL_modified`
// (dbLink.c:71-87) sets `DBLINK_FLAG_TSELisTIME` for ANY
// `PV_LINK` tsel whose pvname contains `.TIME`, set BEFORE the
// DB-vs-CA decision (dbLink.c:118) — so a local-DB link AND a
// CA link both qualify. `recGblGetTimeStampSimm`
// (recGbl.c:316-321) then copies the link's time+utag via
// `dbGetTimeStampTag` and RETURNS, never loading TSE from the
// value (even when the read fails). A pva link is a
// `JSON_LINK` and returns early from `dbInitLink`
// (dbLink.c:107) before `TSEL_modified`, so C never flags it;
// pva TSEL `.TIME` is intentionally excluded here.
let tsel_is_time = match &tsel_link {
crate::server::record::ParsedLink::Db(link) => {
link.field.eq_ignore_ascii_case("TIME")
}
crate::server::record::ParsedLink::Ca(ca) => ca_tsel_time_record(&ca.pv).is_some(),
_ => false,
};
if tsel_is_time {
// C `dbGetTimeStampTag(plink, &prec->time, &prec->utag)`
// (recGbl.c:317) copies BOTH the link's time AND utag.
// Read the pair as one consistent snapshot per source.
let src_time = match &tsel_link {
crate::server::record::ParsedLink::Db(link) => {
// C `dbInitLink` locality (`dbLink.c:115-130`):
// `TSEL_modified` sets the `TSELisTIME` flag and
// strips `.TIME` BEFORE the DB-vs-CA decision
// (dbLink.c:115-118), so a TSEL `.TIME` link whose
// record is not local still becomes a CA link and
// reads its remote `.TIME` via the CA lset
// `getTimeStampTag`. Local arm reads the source
// record's `(time, utag)`; the non-local arm routes
// `ca://REC` through `external_link_time` (CA
// carries no userTag, so utag is 0) — uniform with
// the `Ca` arm below and the `read_db_link_value`
// read-locality fallback.
if self.has_name_no_resolve(&link.record).await {
match self.get_record(&link.record).await {
Some(src) => {
let g = src.read().await;
Some((g.common.time, g.common.utag))
}
None => None,
}
} else {
self.external_link_time(&format!("ca://{}", link.record))
.await
.map(ext_time_pair)
}
}
crate::server::record::ParsedLink::Ca(ca) => {
// Strip `.TIME` (C dbLink.c:82-84) and read the CA
// link's cached timestamp. `external_link_time`
// routes `ca://` to the ungated CA lset
// `time_stamp` (CA has no `time=` option; gated
// only on `connected`, like C `dbGetTimeStamp`
// failing on a disconnected link). CA wire carries
// no userTag, so the source contributes utag 0.
match ca_tsel_time_record(&ca.pv) {
Some(rec_name) => self
.external_link_time(&format!("ca://{rec_name}"))
.await
.map(ext_time_pair),
None => None,
}
}
_ => None,
};
// C returns after the TSELisTIME branch even when the read
// fails (recGbl.c:317-320): keep the record's current time
// rather than falling through to load TSE from the value.
if let Some((src_time, src_utag)) = src_time {
let mut instance = rec.write().await;
instance.common.time = src_time;
instance.common.utag = src_utag;
instance.common.tse = -2;
}
} else if let Some(val) = self.read_link_value_no_process(&tsel_link).await {
// Non-`.TIME` TSEL: C `dbGetLink(&tsel, DBR_SHORT,
// &prec->tse)` loads TSE from the link regardless of its
// type. The pre-fix port only read a `ParsedLink::Db`
// TSEL, ignoring a CA/PVA/constant TSE source.
let tse_val = val.to_f64().unwrap_or(0.0) as i16;
let mut instance = rec.write().await;
instance.common.tse = tse_val;
}
}
// 0.5. Simulation mode check.
//
// C `aiRecord.c:151-168`: simulation is handled inside
// `readValue()`, then `process()` ALWAYS runs `convert` /
// `checkAlarms` / `monitor` / `recGblFwdLink(prec)`. A
// simulated record therefore must still run the forward-link /
// CP / RPRO tail — only the device read and record-support
// body are replaced by the SIOL round-trip. Returning early
// here would silently break every FLNK / CP chain downstream
// of any record in SIMM mode.
match self.check_simulation_mode(&rec).await {
SimOutcome::NotSimulated => {}
SimOutcome::Simulated => {
self.run_forward_link_tail(name, &rec, visited, depth).await;
return Ok(());
}
}
// 1. Read INP link value and DOL link (outside lock)
let (inp_parsed, is_soft, dol_info) = {
let instance = rec.read().await;
let rtype = instance.record.record_type();
let inp = instance.parsed_inp.clone();
let is_soft = crate::server::device_support::is_soft_dtyp(&instance.common.dtyp);
// DOL link info for output records with OMSL=CLOSED_LOOP.
//
// C parity: every record type whose DBD declares both an
// OMSL `menuOmsl` field AND a DOL link field must honour
// the closed-loop binding. `dfanoutRecord.c:115-122` shows
// dfanout doing this directly via `dbGetLink(&prec->dol,
// DBR_DOUBLE, &prec->val, ...)` when `omsl ==
// menuOmslclosed_loop`. The Rust port previously omitted
// `dfanout`, so a dfanout configured with OMSL=closed_loop
// never sourced VAL from DOL — every cycle silently used
// the previously-cached VAL, breaking any cascaded
// setpoint-distribution chain that relied on dfanout to
// re-read the input.
//
// The `aao` (array analog output) record is the only other
// OMSL-bearing C record; the Rust port does not implement
// aao (confirmed: no `crates/epics-base-rs/src/server/records/aao*.rs`),
// so it is a future gap, not a same-defect-not-fixed site.
let dol = match rtype {
"ao" | "longout" | "int64out" | "bo" | "mbbo" | "mbboDirect" | "stringout"
| "lso" | "dfanout" => {
let omsl = instance
.record
.get_field("OMSL")
.and_then(|v| {
if let EpicsValue::Short(s) = v {
Some(s)
} else {
None
}
})
.unwrap_or(0);
let oif = instance
.record
.get_field("OIF")
.and_then(|v| {
if let EpicsValue::Short(s) = v {
Some(s)
} else {
None
}
})
.unwrap_or(0);
if omsl == 1 {
let dol_parsed = instance
.record
.get_field("DOL")
.and_then(|v| {
if let EpicsValue::String(s) = v {
Some(s)
} else {
None
}
})
.map(|s| {
crate::server::record::parse_link_v2(s.as_str_lossy().as_ref())
})
.unwrap_or(crate::server::record::ParsedLink::None);
Some((dol_parsed, oif))
} else {
None
}
}
_ => None,
};
(inp, is_soft, dol)
};
// 1.1. Pre-input-link actions: actions a record needs the
// framework to execute BEFORE any input-link fetch this cycle.
//
// C `devEpidSoftCallback.c:120-151`: a DB-type readback-trigger
// (TRIG) link is written with `dbPutLink` — which synchronously
// processes the triggered source — and only then does
// `dbGetLink(&pepid->inp, ...)` read CVAL. The trigger write
// must land before the `INP -> CVAL` fetch, in the same pass.
// `pre_process_actions` runs too late (after the input-link
// fetch below), so `pre_input_link_actions` is a strictly
// earlier hook. The record needs `dtyp` to decide whether the
// callback DSET is active, so push the process context first.
{
let pre_input_actions = {
let mut instance = rec.write().await;
let ctx = instance.common.process_context();
instance.record.set_process_context(&ctx);
instance.record.pre_input_link_actions()
};
if !pre_input_actions.is_empty() {
self.execute_process_actions(name, &rec, pre_input_actions, visited, depth)
.await;
}
}
// Read INP value
let inp_value = self
.read_link_value_soft(&inp_parsed, is_soft, visited, depth)
.await;
// epics-base PR #d0cf47c: single-INP MS-class link must also
// propagate the source record's STAT/SEVR/AMSG just like the
// multi-input fetch loop below does. Previously the INPA..L
// path (calc/sub/aSub/sel) propagated alarms but plain single
// INP (ai/bi/longin/mbbi/stringin) silently dropped them —
// downstream MSS readers saw NoAlarm even when the source was
// INVALID. Only fires for soft-channel records: hardware-driver
// alarms travel through device-support's own last_alarm path.
//
// B2: a soft INP that is an external `pva://` / `ca://` link
// also propagates the lset's alarm. The link string carries
// no `MonitorSwitch` (the `?sevr=MS` modifier is stripped by
// the parser before epics-base-rs sees it), so the lset has
// already applied the MS/NMS/MSI gate — a `Some` LinkAlarm
// here is one the lset decided to propagate. We fold it in as
// `MaximizeStatus` so the gated severity AND message both
// reach `LINK_ALARM`, matching pvxs `pvalink_lset.cpp`
// `recGblSetSevrMsg`.
let inp_link_alarm: Option<(
crate::server::record::MonitorSwitch,
super::links::LinkAlarm,
)> = if is_soft {
match inp_parsed {
crate::server::record::ParsedLink::Db(ref db) => {
let (_v, alarm) = self.read_link_with_alarm(&inp_parsed).await;
alarm.map(|a| (db.monitor_switch, a))
}
crate::server::record::ParsedLink::Pva(_)
| crate::server::record::ParsedLink::PvaJson(_) => {
// PVA: the lset already applied the MS/NMS/MSI gate,
// so the returned severity is final — fold it as
// MaximizeStatus to preserve the remote stat+msg
// (pvxs `pvalink_lset.cpp`).
let (_v, alarm) = self.read_link_with_alarm(&inp_parsed).await;
alarm.map(|a| (crate::server::record::MonitorSwitch::MaximizeStatus, a))
}
crate::server::record::ParsedLink::Ca(ref ca) => {
// CA: apply the link's own
// MS/NMS/MSI/MSS gate at the fold boundary, uniform
// with the Db arm above — the resolver returned the
// *raw* remote alarm, not a gated one.
let (_v, alarm) = self.read_link_with_alarm(&inp_parsed).await;
alarm.map(|a| (ca.monitor_switch, a))
}
_ => None,
}
} else {
None
};
// if the single-INP link is an external `pva://` /
// `ca://` link configured with `time=true`, the lset returns
// the latched upstream NT timestamp here and we adopt it
// into the owning record's `common.time` and `common.utag`. The
// lset gates the option internally (returns `None` unless
// `time=true`), so a bare connected link without the flag still
// produces local processing time. Mirrors pvxs
// `pvalink_lset.cpp:427`.
let inp_link_remote_time: Option<(i64, i32, u64)> = match inp_parsed.external_pv_name() {
Some(name) => self.external_link_time(&name).await,
None => None,
};
// Read DOL value
let dol_value = if let Some((ref dol_parsed, _oif)) = dol_info {
self.read_link_value(dol_parsed, visited, depth).await
} else {
None
};
// 1.5. Multi-input link fetch (calc/calcout/sel/sub)
// Also collect alarm info from source records for MS/NMS propagation.
let multi_input_values: Vec<(String, EpicsValue)>;
let mut link_alarms: Vec<(
crate::server::record::MonitorSwitch,
super::links::LinkAlarm,
)> = Vec::new();
// Link fields (the `multi_input_links` first element) whose
// fetch actually produced a value this cycle — pushed to the
// record via `set_resolved_input_links` so its `process()` can
// observe link-fetch success (C `RTN_SUCCESS(dbGetLink(...))`).
let mut resolved_link_fields: Vec<&'static str> = Vec::new();
{
let link_info: Vec<(String, &'static str, String)> = {
let instance = rec.read().await;
instance
.record
.multi_input_links()
.iter()
.map(|(lf, vf)| {
let link_str = instance
.record
.get_field(lf)
.and_then(|v| {
if let EpicsValue::String(s) = v {
Some(s)
} else {
None
}
})
.unwrap_or_default();
(link_str.as_str_lossy().into_owned(), *lf, vf.to_string())
})
.collect()
}; // read lock dropped
let mut results = Vec::new();
for (link_str, link_field, val_field) in &link_info {
if !link_str.is_empty() {
let parsed = crate::server::record::parse_link_v2(link_str);
// C `dbGetLink`: a `ProcessPassive` DB input link
// processes its passive source record before the
// value is read. `read_link_with_alarm` does a bare
// `get_pv`, so process the source here first —
// matching the single-INP `read_link_value_soft`
// path. Without this, calc/sel/sub/aSub INPA..INPL
// PP links read a stale source value.
if let crate::server::record::ParsedLink::Db(ref db) = parsed {
self.process_passive_db_source(db, visited, depth).await;
}
let (value, alarm) = self.read_link_with_alarm(&parsed).await;
if let Some(value) = value {
results.push((val_field.clone(), value));
resolved_link_fields.push(link_field);
}
// B2 / multi-input alarm propagation
// covers external links too. `Db` and `Ca` carry an
// explicit `MonitorSwitch` (CA's was parsed from its
// `MS`/`NMS`/`MSI`/`MSS` modifier); `Pva` is gated by
// its lset, so its already-final severity folds as
// `MaximizeStatus` (preserving remote stat+msg).
if let Some(alarm) = alarm {
match &parsed {
crate::server::record::ParsedLink::Db(db) => {
link_alarms.push((db.monitor_switch, alarm));
}
crate::server::record::ParsedLink::Ca(ca) => {
link_alarms.push((ca.monitor_switch, alarm));
}
crate::server::record::ParsedLink::Pva(_)
| crate::server::record::ParsedLink::PvaJson(_) => {
link_alarms.push((
crate::server::record::MonitorSwitch::MaximizeStatus,
alarm,
));
}
_ => {}
}
}
}
}
multi_input_values = results;
}
// PR #d0cf47c continued: feed the INP alarm (if any) into the
// same `link_alarms` list the lock-section iterates over. Order
// doesn't matter — `rec_gbl_set_sevr_msg` takes the maximum
// severity across all sources.
if let Some(pair) = inp_link_alarm {
link_alarms.push(pair);
}
// 1.6. Sel NVL link: resolve NVL -> SELN
let sel_nvl_value: Option<EpicsValue> = {
let instance = rec.read().await;
if instance.record.record_type() == "sel" {
let nvl_str = instance
.record
.get_field("NVL")
.and_then(|v| {
if let EpicsValue::String(s) = v {
Some(s)
} else {
None
}
})
.unwrap_or_default();
if !nvl_str.is_empty() {
drop(instance); // release read lock before async read
let parsed =
crate::server::record::parse_link_v2(nvl_str.as_str_lossy().as_ref());
self.read_link_value(&parsed, visited, depth).await
} else {
None
}
} else {
None
}
};
// 2. Lock record, apply INP/DOL, process, evaluate alarms, build snapshot
let (snapshot, out_info, flnk_name, process_actions, alarm_posts) = {
let mut instance = rec.write().await;
// Apply DOL value for output records (OMSL=CLOSED_LOOP)
if let Some(dol_val) = dol_value {
let oif = dol_info.as_ref().map(|(_, oif)| *oif).unwrap_or(0);
if oif == 1 {
// Incremental: VAL += DOL value
if let (Some(cur), Some(dol_f)) = (
instance.record.val().and_then(|v| v.to_f64()),
dol_val.to_f64(),
) {
let _ = instance.record.set_val(EpicsValue::Double(cur + dol_f));
}
} else {
// Full: VAL = DOL value
let _ = instance.record.set_val(dol_val);
}
}
// Apply INP value. "Soft Channel" sets VAL directly
// (C `read_xxx` return 2, skip RVAL→VAL conversion).
// "Raw Soft Channel" routes the value into RVAL and lets
// the record's RVAL→VAL convert run (epics-base
// f2fe9d12: devBiSoftRaw applies MASK after the read).
// Records opt into the raw path via
// `Record::accepts_raw_soft_input` so DTYPs on records
// that haven't wired raw soft channel stay on the legacy
// VAL-direct path.
let is_raw_soft = instance.common.dtyp == "Raw Soft Channel"
&& instance.record.accepts_raw_soft_input();
let soft_inp_applied = inp_value.is_some() && !is_raw_soft;
if let Some(inp_val) = inp_value {
if is_raw_soft {
let _ = instance.record.apply_raw_input(inp_val);
} else {
let _ = instance.record.set_val(inp_val);
}
} else if is_soft
&& matches!(
inp_parsed,
crate::server::record::ParsedLink::Db(_)
| crate::server::record::ParsedLink::Ca(_)
| crate::server::record::ParsedLink::Pva(_)
| crate::server::record::ParsedLink::PvaJson(_)
)
{
// epics-base PR #4737901: soft-channel `read_xxx` must
// surface link-read failures via the alarm tree, not
// silently succeed. When the INP link is a real
// Db/Ca/Pva link (i.e. operator expected a value) and
// the read returned None, attach LINK_ALARM/INVALID
// so downstream consumers can react. ParsedLink::None
// and Constant don't fall into this branch — the
// former is "no link configured", the latter has its
// own None-as-no-value semantics.
use crate::server::recgbl::{alarm_status, rec_gbl_set_sevr};
rec_gbl_set_sevr(
&mut instance.common,
alarm_status::LINK_ALARM,
crate::server::record::AlarmSeverity::Invalid,
);
}
// Apply multi-input values (INPA..INPL -> A..L).
//
// Uses `put_field_internal`, not `put_field`: this is the
// framework writing a resolved input-link value into a
// record field, exactly like the `ReadDbLink` apply
// (`execute_read_db_links` / `execute_process_actions`),
// which already routes through `put_field_internal`. Some
// records map an input link to a normally read-only field
// — e.g. the epid record's `INP -> CVAL` — and `put_field`
// rejects those with `ReadOnlyField`, silently dropping the
// value. `put_field_internal` defaults to `put_field`, so
// records with writable targets (calc/sub `A..L`) are
// unaffected.
for (val_field, value) in &multi_input_values {
if let Some(f) = value.to_f64() {
let _ = instance
.record
.put_field_internal(val_field, EpicsValue::Double(f));
}
}
// The set_resolved_input_links report is deferred until after
// the pre-process ReadDbLink reads below, so the record sees
// ONE per-cycle resolution list covering both fetch paths —
// records reset per-cycle resolution state in that hook, so
// it must not run twice with partial lists.
// Apply sel NVL -> SELN. SELN is DBF_USHORT (selRecord.dbd.pod:295),
// an unsigned 0..65535 index. Carry the native unsigned value so a
// link value in 32768..65535 is not lost to f64->i16 saturation
// before it reaches the field's put.
if let Some(nvl_val) = sel_nvl_value {
if let Some(f) = nvl_val.to_f64() {
let _ = instance
.record
.put_field("SELN", EpicsValue::UShort(f as u16));
}
}
// Device support read (input records only, not output records)
let is_soft = instance.common.dtyp.is_empty() || instance.common.dtyp == "Soft Channel";
let is_output = instance.record.can_device_write();
let mut device_actions: Vec<crate::server::record::ProcessAction> = Vec::new();
// C `devAiSoft.c:65` `read_ai` (and the other soft-channel
// input `read_xxx`) ALWAYS returns 2 ("don't convert") for a
// Soft-Channel input record — whether the value arrived via
// an INP link or the INP link is constant/unset
// (`dbLinkIsConstant` → `return 2`). Only `aiRecord.c:158`'s
// `if (status==0) convert(prec)` runs RVAL→VAL conversion, so
// for a plain Soft-Channel input record `convert()` must be
// skipped unconditionally. Without this, a soft ai with no
// INP would run `convert()` and clobber a preset VAL — e.g.
// a preset NaN would be rewritten to 0.0, then the framework
// UDF check (`value_is_undefined()`) would see a defined 0.0
// and wrongly clear UDF. `is_raw_soft`
// (Raw Soft Channel, `devAiSoftRaw` returns 0) is excluded —
// it deliberately wants the RVAL→VAL convert.
//
// Gated on `soft_channel_skips_convert()` so this only
// suppresses an `RVAL → VAL` convert step. Records such as
// `epid` also override `set_device_did_compute` but treat it
// as "skip the whole built-in compute" (the PID loop); they
// return `false` here so a Soft-Channel `epid` still runs
// `do_pid()` in `process()`.
let soft_input_skips_convert = is_soft
&& !is_output
&& !is_raw_soft
&& instance.record.soft_channel_skips_convert();
let mut device_did_compute = (soft_inp_applied && is_soft) || soft_input_skips_convert;
if !is_soft && !is_output {
if let Some(mut dev) = instance.device.take() {
// Push framework-owned common state (PHAS/TSE/TSEL/
// UDF) so device support's read() can see it — C
// device support reads `dbCommon` directly
// (`devTimeOfDay.c:122` uses `psi->phas`).
dev.set_process_context(&instance.common.process_context());
match dev.read(&mut *instance.record) {
Ok(read_outcome) => {
device_did_compute = read_outcome.did_compute;
device_actions = read_outcome.actions;
}
Err(e) => {
eprintln!("device read error on {}: {e}", instance.name);
use crate::server::recgbl::{alarm_status, rec_gbl_set_sevr};
rec_gbl_set_sevr(
&mut instance.common,
alarm_status::READ_ALARM,
crate::server::record::AlarmSeverity::Invalid,
);
}
}
instance.device = Some(dev);
}
}
// Pre-process actions: execute ReadDbLink from device support and
// record's pre_process_actions() BEFORE process() so the values
// are immediately available. Matches C dbGetLink() semantics.
let mut pre_actions = instance.record.pre_process_actions();
// Also collect ReadDbLink from device actions
let mut deferred_device_actions = Vec::new();
for action in device_actions {
if matches!(
action,
crate::server::record::ProcessAction::ReadDbLink { .. }
) {
pre_actions.push(action);
} else {
deferred_device_actions.push(action);
}
}
if !pre_actions.is_empty() {
let rec_name = instance.name.clone();
drop(instance);
let pre_resolved = self
.execute_read_db_links(&rec_name, &rec, &pre_actions, visited, depth)
.await;
instance = rec.write().await;
resolved_link_fields.extend(pre_resolved);
}
// Tell the record which input link fields actually resolved
// a value this cycle — the union of the multi-input fetch and
// the pre-process ReadDbLink reads; the framework analogue of
// C device support inspecting `RTN_SUCCESS(dbGetLink(...))`
// (`epidRecord.c:191-193`, `motorRecord.cc:3687-3698`).
instance
.record
.set_resolved_input_links(&resolved_link_fields);
// Note: C EPICS LCNT prevents reentrant processing of the same
// record within a single processing chain. In Rust, this is handled
// by the `visited` HashSet (cycle detection) and the `processing`
// AtomicBool guard. LCNT is not needed as a separate mechanism
// because async processing with visited sets already prevents
// the runaway loops that LCNT guards against in C.
// Tell the record whether device support already computed.
// Records that override set_device_did_compute() use this to
// skip their built-in computation (e.g., ai skips RVAL->VAL).
// Note: field_io.rs may have already called set_device_did_compute(true)
// for CA puts to VAL. We only set true here, never reset to false.
if device_did_compute {
instance.record.set_device_did_compute(true);
}
// TPRO: trace processing (C EPICS dbProcess prints context when TPRO>0)
if instance.common.tpro {
eprintln!(
"[TPRO] {}: process (SCAN={:?}, PACT={})",
instance.name,
instance.common.scan,
instance
.processing
.load(std::sync::atomic::Ordering::Relaxed)
);
}
// Push framework-owned common state (UDF/PHAS/TSE/TSEL) so
// the record's process() can see it — C records read
// `dbCommon` directly (`epidRecord.c:195` checks
// `pepid->udf`, `timestampRecord.c:90` checks `tse`).
{
let ctx = instance.common.process_context();
instance.record.set_process_context(&ctx);
}
// Process
let mut outcome = instance.record.process()?;
// Merge deferred device actions into process outcome actions
outcome.actions.extend(deferred_device_actions);
let process_result = outcome.result;
let process_actions = outcome.actions;
if process_result == crate::server::record::RecordProcessResult::AsyncPending {
// C `dbProcess` contract: when device support / record body
// signals "async pending", `pact` MUST be true so subsequent
// dbProcess attempts on the same record bail at the entry
// guard. Previous Rust port assumed `process_local` had
// already set it via the swap-true at function entry, but
// this main path bypasses `process_local` and calls
// `record.process()` directly — leaving `processing=false`.
// Mirrors `aiRecord.c:122` and similar: `prec->pact = TRUE;
// return 0;` before async work.
instance
.processing
.store(true, std::sync::atomic::Ordering::Release);
// PACT stays set; skip alarm/timestamp/snapshot/OUT/FLNK.
// But still execute any actions (e.g., ReprocessAfter for delayed re-entry).
let rec_name = instance.name.clone();
drop(instance);
self.execute_process_actions(&rec_name, &rec, process_actions, visited, depth)
.await;
return Ok(());
}
if let crate::server::record::RecordProcessResult::AsyncPendingNotify(fields) =
process_result
{
// Intermediate notification (e.g. DMOV=0 at move start).
// Execute device write first so the move command reaches the
// driver, then fire the record's link writes, then flush
// DMOV=0 etc. to monitors. This mirrors the C ordering on an
// async (pact=1) pass: `motorRecord.cc:1491` runs `do_work`
// (the device move), `motorRecord.cc:1495` then fires
// `dbPutLink(&pmr->rlnk, ...)` UNCONDITIONALLY — on every pass
// including the move-start pass where DMOV just went 0 — and
// only `motorRecord.cc:1507` afterwards calls `monitor()`. So
// the requested `WriteDbLink`/`WriteDbLinkNotify` actions must
// run on the pending cycle as well; a put processes a PP target
// even when the value is unchanged, so dropping them changes
// downstream process counts (motor RLNK, asyn async writes).
// The forward link stays deferred: C runs `recGblFwdLink` only
// when `pmr->dmov != 0` (motorRecord.cc:1509), i.e. on async
// completion, not on this pending pass.
if !is_soft {
if let Some(mut dev) = instance.device.take() {
let _ = dev.write(&mut *instance.record);
instance.device = Some(dev);
}
}
apply_timestamp(&mut instance.common, is_soft);
// Filter out fields that haven't changed, update MLST/last_posted.
// Each intermediate post carries DBE_VALUE|DBE_LOG — C motor's
// mid-move `db_post_events` calls use `DBE_VAL_LOG`
// (motorRecord.cc:2606 DMOV, and every other do_work post);
// no alarm transition ran on this pending pass, so no
// DBE_ALARM bit.
let mut changed_fields = Vec::new();
for (name, val) in fields {
let changed = match instance.last_posted.get(&name) {
Some(prev) => prev != &val,
None => true,
};
if changed {
if name == "VAL" {
if let Some(f) = val.to_f64() {
instance.put_coerced("MLST", f);
instance.common.mlst = Some(f);
}
}
instance.last_posted.insert(name.clone(), val.clone());
changed_fields.push((
name,
val,
crate::server::recgbl::EventMask::VALUE
| crate::server::recgbl::EventMask::LOG,
));
}
}
let snapshot = crate::server::record::ProcessSnapshot { changed_fields };
let rec_name = instance.name.clone();
let rec_clone = rec.clone();
drop(instance);
// Partition exactly as the synchronous Complete path: link
// writes fire here (C `dbPutLink` precedes `monitor()`);
// delayed-reprocess / device-command actions run after the
// notify (the Complete path runs them after the FLNK tail,
// which is deferred to async completion on this pending pass).
let (link_writes, deferred_actions): (Vec<_>, Vec<_>) =
process_actions.into_iter().partition(|a| {
matches!(
a,
crate::server::record::ProcessAction::WriteDbLink { .. }
| crate::server::record::ProcessAction::WriteDbLinkNotify { .. }
)
});
self.execute_process_actions(&rec_name, &rec, link_writes, visited, depth)
.await;
{
let inst = rec_clone.read().await;
inst.notify_from_snapshot(&snapshot);
}
self.execute_process_actions(&rec_name, &rec, deferred_actions, visited, depth)
.await;
return Ok(());
}
// Async-completion PACT clear for the `ReprocessAfter`
// continuation path. C parity `dbAccess.c:583` —
// `prset->process(precord)` for a record whose first cycle
// returned async-pending is the *completion* re-entry; the
// record support clears `pact` itself inside `process()`
// (e.g. `aiRecord.c` second pass sets `prec->pact = FALSE`).
//
// A record that returns `AsyncPending` AND emits a
// `ProcessAction::ReprocessAfter` is re-entered here via
// `process_record_continuation` (`is_continuation == true`,
// PACT entry guard skipped). Reaching this point means the
// continuation's `process()` did NOT return async-pending
// again (both async branches above return early), so the
// async cycle is genuinely complete. The non-continuation
// async-device path clears `processing` in
// `complete_async_record_inner`; the continuation path has
// no such callback, so without this clear `processing`
// stays `true` forever — every later foreign
// `process_record_with_links` then trips the PACT entry
// guard, counts to MAX_LOCK, and raises a spurious
// SCAN_ALARM. Clearing here (record still write-locked,
// before the OUT/FLNK tail) mirrors the C ordering where
// `pact` is already `FALSE` when `recGblFwdLink` runs.
if is_continuation {
instance
.processing
.store(false, std::sync::atomic::Ordering::Release);
}
// MS-class alarm propagation from input links. Mirrors C
// `recGblInheritSevrMsg` (recGbl.c::260):
//
// * NMS — do nothing.
// * MS — DEST gets `LINK_ALARM` (NOT the source stat),
// max-raised sevr, NO amsg propagation.
// * MSI — same as MS, but only when source.sevr == INVALID.
// * MSS — DEST gets source stat, max-raised sevr, source amsg
// (PR d0cf47c is the only branch that propagates msg).
//
// Previous version treated Maximize and MaximizeStatus
// identically, propagating source stat + amsg through both
// — that matches MSS but is wrong for MS (and MSI), which
// C says should always surface as LINK_ALARM with no msg.
// The per-mode switch is shared with the DB OUT-link write
// path via `inherit_sevr_msg` so the two sides cannot drift.
for (ms, alarm) in &link_alarms {
super::links::inherit_sevr_msg(&mut instance.common, *ms, alarm);
}
// UDF update — C parity (aiRecord.c:285, calcRecord.c
// checkAlarms, int64inRecord.c:144): clear UDF only when
// this cycle produced a *defined* value. A NaN computed
// value (calc divide-by-zero) or a failed link read that
// left VAL un-updated must keep UDF true so the following
// `recGblCheckUDF` raises UDF_ALARM at severity UDFS.
//
// This MUST run before `evaluate_alarms()` (which calls
// `rec_gbl_check_udf`): C records set `prec->udf` inside
// `process()` before `checkAlarms()` runs.
if instance.record.clears_udf() {
instance.common.udf = instance.record.value_is_undefined();
}
// Per-record alarm hook — record-type-specific STATE / COS
// / limit / SOFT alarms (C `checkAlarms()`). Records that
// have migrated their alarm logic here raise into
// `nsta`/`nsev`; the rest fall back to the framework's
// centralised `evaluate_alarms` match below.
{
let inst = &mut *instance;
inst.record.check_alarms(&mut inst.common);
}
// Evaluate alarms (accumulates into nsta/nsev)
instance.evaluate_alarms();
// Device support alarm/timestamp override
if !is_soft {
let (dev_alarm, dev_ts, dev_utag) = if let Some(ref dev) = instance.device {
(dev.last_alarm(), dev.last_timestamp(), dev.last_utag())
} else {
(None, None, None)
};
if let Some((stat, sevr)) = dev_alarm {
use crate::server::recgbl::rec_gbl_set_sevr;
rec_gbl_set_sevr(
&mut instance.common,
stat,
crate::server::record::AlarmSeverity::from_u16(sevr),
);
}
if let Some(ts) = dev_ts {
instance.common.time = ts;
}
// C device support writes `prec->utag` directly during
// `read()` — the event-system pulse-id path, since
// `epicsTimeStamp` carries no tag. Adopt the device's
// userTag when it supplies one; read in the same `dev`
// borrow as the timestamp above so the time/tag pair is a
// single consistent device snapshot.
if let Some(utag) = dev_utag {
instance.common.utag = utag;
}
}
// pvalink `time=true` adopts the latched upstream timestamp
// into the owning record. `external_link_time` returned
// `None` unless the lset signalled the option, so a `Some`
// here is the operator-requested remote timestamp: the remote
// NT `timeStamp` while connected, or the disconnect-event time
// while the subscription is down (pvxs `snap_time = e.time`,
// adopted on the invalid read — `pvalink_lset.cpp:268-270`).
// Apply BEFORE `apply_timestamp` so the upstream value
// survives the soft-channel TSE=0 default (`apply_timestamp`
// would otherwise stamp wall-clock-now on top).
if let Some((secs, ns, utag)) = inp_link_remote_time {
let secs = secs.max(0) as u64;
let ns = ns.max(0) as u32;
instance.common.time =
std::time::UNIX_EPOCH + std::time::Duration::new(secs, ns.min(999_999_999));
// adopt the upstream `timeStamp.userTag` alongside the
// time, mirroring pvxs PR-added `precord->utag = snap_tag`
// next to `precord->time = snap_time` in the `time=true`
// branch. The tag is already widened without sign
// extension by the lset; `0` when the source carries
// none. `apply_timestamp` never touches `utag`, so this
// survives regardless of the TSE branch below.
instance.common.utag = utag;
// TSE=-2 marks "device-set time" — `apply_timestamp`
// honours this by leaving `common.time` untouched,
// mirroring the device-support timestamp branch above.
instance.common.tse = -2;
}
// Transfer nsta/nsev -> sevr/stat, detect alarm change
let alarm_result = crate::server::recgbl::rec_gbl_reset_alarms(&mut instance.common);
// Apply timestamp based on TSE
apply_timestamp(&mut instance.common, is_soft);
// NOTE: UDF was already updated before `evaluate_alarms`
// above — keyed on `value_is_undefined()` so a NaN result
// keeps UDF true and UDF_ALARM is raised this cycle. Do
// NOT clear UDF unconditionally here.
// IVOA check for output records with INVALID alarm
let skip_out = if instance.common.sevr == crate::server::record::AlarmSeverity::Invalid
{
let ivoa = instance
.record
.get_field("IVOA")
.and_then(|v| {
if let EpicsValue::Short(s) = v {
Some(s)
} else {
None
}
})
.unwrap_or(0);
match ivoa {
1 => true, // Don't drive outputs
2 => {
// Set output to IVOV. Each record type knows
// which field its OUT writeback consumes — see
// [`Record::apply_invalid_output_value`]. The
// earlier path special-cased `calcout`
// (OVAL) and fell back to `set_val` (VAL) for
// every other record. That hid a real bug:
// ao/lso/bo/mbbo/busy left their OVAL/RVAL
// staging field stale, so the OUT writeback —
// which reads `OVAL.or(VAL)` — sent the
// pre-IVOA value to the linked record. Per-type
// overrides now apply IVOV to the field that
// matches the C convention.
if let Some(ivov) = instance.record.get_field("IVOV") {
let _ = instance.record.apply_invalid_output_value(ivov);
}
false
}
_ => false, // Continue normally
}
} else {
false
};
// OUT stage: soft channel -> link put, non-soft -> device.write()
// Must run BEFORE check_deadband_ext so MLST is not prematurely
// updated for async writes that return early.
let can_dev_write = instance.record.can_device_write();
let is_soft_out =
instance.common.dtyp.is_empty() || instance.common.dtyp == "Soft Channel";
let record_should_output = instance.record.should_output();
let out_info = if skip_out {
None
} else if !can_dev_write {
// Non-output records (calcout, etc.) may still have a
// soft OUT link (DB or external ca://`/`pva://`).
// Write OVAL to OUT when the record says should_output().
if record_should_output && instance.parsed_out.is_writable_out_link() {
let oval = instance.record.get_field("OVAL");
let val = instance.record.val();
let out_val = oval.or(val);
out_val.map(|v| (instance.parsed_out.clone(), v))
} else {
None
}
} else if is_soft_out {
if !record_should_output {
// epics-base 7.0.8 OOPT: gate the soft OUT-link
// write on the record's `should_output()`. For
// longout/calcout with OOPT != 0 this lets a
// condition-not-met cycle silently skip the link
// write without disturbing alarms / monitors.
None
} else if instance.parsed_out.is_writable_out_link() {
let out_val = instance
.record
.get_field("OVAL")
.or_else(|| instance.record.val());
out_val.map(|v| (instance.parsed_out.clone(), v))
} else {
None
}
} else if !record_should_output {
// OOPT gating for hardware outputs (longout DTYP=...).
// Skip the device write when the OOPT predicate is
// not satisfied; the record's val/timestamp/snapshot
// path still runs so monitor consumers see the value
// change even on a non-output cycle.
None
} else {
if let Some(mut dev) = instance.device.take() {
// Try async write_begin() first
match dev.write_begin(&mut *instance.record) {
Ok(Some(completion)) => {
// Async write submitted -- set PACT, return early.
// complete_async_record will handle deadband, snapshot,
// notification, and FLNK when the write completes.
instance
.processing
.store(true, std::sync::atomic::Ordering::Release);
instance.device = Some(dev);
let rec_name = instance.name.clone();
let timeout = std::time::Duration::from_secs(5);
let db = self.clone();
tokio::spawn(async move {
let _ =
tokio::task::spawn_blocking(move || completion.wait(timeout))
.await;
let _ = db.complete_async_record(&rec_name).await;
});
return Ok(());
}
Ok(None) => {
// No async support -- fall back to synchronous write
if let Err(e) = dev.write(&mut *instance.record) {
eprintln!("device write error on {}: {e}", instance.name);
instance.common.stat =
crate::server::recgbl::alarm_status::WRITE_ALARM;
instance.common.sevr =
crate::server::record::AlarmSeverity::Invalid;
} else {
// OOPT 7.0.8: notify the record so it can
// latch transition state (e.g. longout.pval)
// for the next cycle.
instance.record.on_output_complete();
}
}
Err(e) => {
eprintln!("device write_begin error on {}: {e}", instance.name);
instance.common.stat = crate::server::recgbl::alarm_status::WRITE_ALARM;
instance.common.sevr = crate::server::record::AlarmSeverity::Invalid;
}
}
instance.device = Some(dev);
}
None
};
// Compute per-field posting masks (after OUT stage so async
// writes don't update MLST/ALST prematurely before returning
// early)
use crate::server::recgbl::EventMask;
let (include_val, include_archive) = match instance.record.monitor_value_changed() {
// lsi/lso post VALUE|LOG only when the string actually
// changed (C `lsiRecord.c`/`lsoRecord.c` monitor: `len !=
// olen || memcmp(oval, val, len)`); they have no MDEL/ADEL
// deadband to express that, so the gate is explicit. The
// MPST/APST `menuPost` "Always" override OR-adds DBE_VALUE /
// DBE_LOG even on an unchanged cycle (C monitor: `if (mpst ==
// menuPost_Always) events |= DBE_VALUE; if (apst ==
// menuPost_Always) events |= DBE_LOG;`).
Some(changed) => {
let (val_always, archive_always) = instance.record.monitor_always_post();
(changed || val_always, changed || archive_always)
}
None => {
if instance.record.uses_monitor_deadband() {
instance.check_deadband_ext()
} else {
// Binary records (bi/bo/busy/mbbi/mbbo): always post monitors
(true, true)
}
}
};
// C `recGblResetAlarms` returns `val_mask = DBE_ALARM`
// (recGbl.c:194/203/212) when the severity/status OR the
// alarm message moved — every monitored-value post this
// cycle carries DBE_ALARM so a `DBE_ALARM`-only subscriber
// sees the value at the moment the alarm changed.
let alarm_bits = if alarm_result.alarm_changed || alarm_result.amsg_changed {
EventMask::ALARM
} else {
EventMask::NONE
};
// Build snapshot
let mut changed_fields = Vec::new();
// The deadband-tracked field posts with the classes that
// actually fired: MDEL crossing → DBE_VALUE, ADEL crossing
// → DBE_LOG, alarm movement → DBE_ALARM — and nothing else
// (C `monitor()` per-field masks: motorRecord.cc:3477-3507
// RBV, aiRecord.c VAL). For most records the tracked field
// IS the primary value; a record like motor deadbands its
// readback, and its VAL routes through the generic
// change-detection loop below — an unchanged setpoint is
// not re-posted on every readback poll.
let deadband_field = instance.record.monitor_deadband_field();
let deadband_mask = {
let mut m = alarm_bits;
if include_val {
m |= EventMask::VALUE;
}
if include_archive {
m |= EventMask::LOG;
}
m
};
if !deadband_mask.is_empty() {
let dval = if deadband_field == "VAL" {
instance.record.val()
} else {
instance.resolve_field(deadband_field)
};
if let Some(val) = dval {
changed_fields.push((deadband_field.to_string(), val, deadband_mask));
}
}
// Add subscribed fields that actually changed since last
// notification. The deadband-gated field is excluded — it is
// delivered by the trigger branch above, never by raw
// change-detection (for the default `deadband_field ==
// "VAL"` this is the same VAL exclusion as before). Each
// carries DBE_VALUE|DBE_LOG plus the cycle's alarm bits —
// the C convention for change-detected auxiliary posts
// (`monitor_mask | DBE_VALUE | DBE_LOG`, calcRecord.c:420,
// subRecord.c:400; motor `DBE_VAL_LOG` for marked fields,
// motorRecord.cc:3522-3645).
//
// On a cycle whose alarm transition fired, fields named by
// `alarm_cycle_monitored_fields` post even when unchanged,
// with the alarm bits alone — C motor `monitor()`
// (motorRecord.cc:3513-3645) posts every listed field once
// `monitor_mask != 0`, so a `DBE_ALARM`-only subscriber
// observes the alarm moment on any of them.
let aux_mask = alarm_bits | EventMask::VALUE | EventMask::LOG;
let alarm_fanout: &[&str] = if alarm_bits.is_empty() {
&[]
} else {
instance.record.alarm_cycle_monitored_fields()
};
// Fields the record force-posts every cycle it recomputed them
// (C unconditional MARK + DBE_VAL_LOG), even when unchanged —
// see `Record::force_posted_fields`. Empty for most records.
let force_fields = instance.record.force_posted_fields();
// Fields re-posted with DBE_LOG only every cycle, regardless
// of change — see `Record::log_swept_fields` (scaler idle Sn
// sweep). Empty for most records.
let log_swept = instance.record.log_swept_fields();
let mut sub_updates: Vec<(String, EpicsValue, EventMask)> = Vec::new();
for (field, subs) in &instance.subscribers {
if !subs.is_empty()
&& field != deadband_field
&& field != "SEVR"
&& field != "STAT"
&& field != "AMSG"
&& field != "UDF"
{
if let Some(val) = instance.resolve_field(field) {
let changed = match instance.last_posted.get(field) {
Some(prev) => prev != &val,
None => true,
};
if changed {
sub_updates.push((field.clone(), val, aux_mask));
} else if force_fields.contains(&field.as_str()) {
// C `monitor()` posts a re-marked field with
// `monitor_mask | DBE_VAL_LOG` even when unchanged.
sub_updates.push((field.clone(), val, aux_mask));
} else if alarm_fanout.contains(&field.as_str()) {
sub_updates.push((field.clone(), val, alarm_bits));
} else if log_swept.contains(&field.as_str()) {
// C scalerRecord.c:770-787 `monitor()`: every
// idle process re-posts each S1..Snch with a
// literal DBE_LOG regardless of change. A
// changed field is already delivered above
// with DBE_VALUE|DBE_LOG (covering the LOG
// subscriber), so only the unchanged sweep
// lands here — no double post.
sub_updates.push((field.clone(), val, EventMask::LOG));
}
}
}
}
if !sub_updates.is_empty() {
for (field, val, _) in &sub_updates {
instance.last_posted.insert(field.clone(), val.clone());
}
changed_fields.extend(sub_updates);
}
// C `recGblResetAlarms` (recGbl.c:201-220) posts each
// alarm field with its own per-field mask:
// * SEVR — DBE_VALUE, ONLY when `prev_sevr != new_sevr`.
// * STAT/AMSG — `stat_mask` = DBE_ALARM (on sevr- or
// amsg-change) | DBE_VALUE (on stat-change).
// * ACKS — DBE_VALUE when `stat_mask != 0`.
// The pre-fix port pushed SEVR + STAT together on any
// `alarm_changed`, over-posting SEVR on a stat-only
// transition and collapsing the per-field mask into one
// record-wide mask. Posting these via `notify_field` with
// their individual masks restores C's granularity.
let sevr_changed = instance.common.sevr != alarm_result.prev_sevr;
let stat_changed = instance.common.stat != alarm_result.prev_stat;
let stat_mask = {
let mut m = EventMask::NONE;
if sevr_changed || alarm_result.amsg_changed {
m |= EventMask::ALARM;
}
if stat_changed {
m |= EventMask::VALUE;
}
m
};
// Defer the SEVR/STAT/AMSG/ACKS posts to dedicated
// `notify_field` calls (collected here, fired after the
// snapshot notify below) so each gets its exact C mask.
let mut alarm_posts: Vec<(&'static str, EventMask)> = Vec::new();
if sevr_changed {
alarm_posts.push(("SEVR", EventMask::VALUE));
}
if !stat_mask.is_empty() {
alarm_posts.push(("STAT", stat_mask));
alarm_posts.push(("AMSG", stat_mask));
}
// C parity (recGbl.c:216): ACKS is posted (DBE_VALUE) only
// when `stat_mask != 0` AND recGblResetAlarms raised it.
if alarm_result.acks_changed && !stat_mask.is_empty() {
alarm_posts.push(("ACKS", EventMask::VALUE));
}
// UDF rides along whenever any monitored post fired this
// cycle, carrying the union of the cycle's posted classes.
let cycle_mask = changed_fields
.iter()
.fold(EventMask::NONE, |m, (_, _, fm)| m | *fm);
if !cycle_mask.is_empty() {
changed_fields.push((
"UDF".to_string(),
EpicsValue::Char(if instance.common.udf { 1 } else { 0 }),
cycle_mask,
));
}
let snapshot = crate::server::record::ProcessSnapshot { changed_fields };
let flnk_name = if instance.record.should_fire_forward_link() {
if let crate::server::record::ParsedLink::Db(ref l) = instance.parsed_flnk {
Some(l.record.clone())
} else {
None
}
} else {
None
};
// Put-notify completion is NOT fired here. Firing before the
// OUT/FLNK/process-action tail (below) would report the
// WRITE_NOTIFY done while the chain it triggers — including
// an async FLNK target — is still running (C `dbNotify.c`
// keeps the originating record in the waitList until the
// chain settles). The originating record instead `leave`s
// the wait-set at the END of this function, after every PP
// target it drives has joined. See `complete_put_notify`
// at the tail.
(snapshot, out_info, flnk_name, process_actions, alarm_posts)
};
// 3. Notify subscribers (outside lock)
{
let instance = rec.read().await;
instance.notify_from_snapshot(&snapshot);
// Post the alarm fields (SEVR/STAT/AMSG/ACKS) with their
// individual C masks — see recGblResetAlarms above.
for &(field, mask) in &alarm_posts {
instance.notify_field(field, mask);
}
}
// Snapshot source PUTF + put-notify wait-set for the C
// `processTarget` / `dbNotifyAdd` invariants (see
// `write_db_link_value` doc). Captured once here so every OUT /
// multi-OUT / FLNK dispatch in this cycle propagates the same
// bit and joins the same wait-set. The committed alarm is
// captured the same way for `recGblInheritSevrMsg` MS-class
// propagation into the OUT-link target.
let (src_putf, src_notify, src_alarm) = {
let guard = rec.read().await;
(
guard.common.putf,
guard.notify.clone(),
super::links::LinkAlarm {
stat: guard.common.stat,
sevr: guard.common.sevr,
amsg: guard.common.amsg.clone(),
},
)
};
// 4. OUT link — DB *or* external `ca://`/`pva://`. C
// `dbLink.c::dbPutLink` (dbLink.c:434-448) routes every link
// write through the link set's `putValue`, so the OUTPUT side
// dispatches by scheme exactly as the INPUT side does (B
// `resolve_external_pv`). An external link with no registered
// lset fails gracefully inside `write_out_link_value`.
if let Some((ref link, ref out_val)) = out_info {
self.write_out_link_value(
link,
out_val.clone(),
super::links::OutLinkSrc {
putf: src_putf,
notify: src_notify.as_ref(),
alarm: &src_alarm,
},
visited,
depth,
)
.await;
// OOPT 7.0.8: latch the record's post-output state so the
// next cycle's `should_output` sees the right pval.
{
let mut instance = rec.write().await;
instance.record.on_output_complete();
}
}
// 7b. C record support performs a record's OUT/link writes BEFORE
// its forward link: `transformRecord` calls `dbPutLink()`
// (transformRecord.c:608-619) before `monitor()` +
// `recGblFwdLink()`, `scalerRecord` writes COUT/COUTP
// (scalerRecord.c:457-480) before its FLNK block, `throttleRecord`
// writes the selected OUT link (throttleRecord.c:562-580) before
// `recGblFwdLink()`, and `tableRecord` drives speed/drive links
// (tableRecord.c:573-597) before its final FLNK. The
// `ProcessAction::WriteDbLink` contract is documented as "before
// FLNK", so split the requested actions: link writes run now;
// delayed/reprocess and device-command actions (whose timing must
// stay after the FLNK tail) run afterward. A downstream FLNK
// target therefore reads the freshly written value, matching C.
let (link_writes, deferred_actions): (Vec<_>, Vec<_>) =
process_actions.into_iter().partition(|a| {
matches!(
a,
crate::server::record::ProcessAction::WriteDbLink { .. }
| crate::server::record::ProcessAction::WriteDbLinkNotify { .. }
)
});
self.execute_process_actions(name, &rec, link_writes, visited, depth)
.await;
// 4.5 - 7. Multi-output / event / generic-multi-out / FLNK /
// CP / RPRO tail. Shared with the simulation-mode path so a
// simulated record runs the exact same `recGblFwdLink`
// equivalent (C `aiRecord.c:168`).
self.run_forward_link_tail_with_putf(
name,
&rec,
flnk_name.as_deref(),
PutNotifyCtx {
putf: src_putf,
notify: src_notify.as_ref(),
},
visited,
depth,
)
.await;
// 8. Execute the deferred ProcessActions after the FLNK tail:
// `ReprocessAfter` schedules a later reprocess (the current
// cycle's FLNK must proceed first) and `DeviceCommand` posts its
// own monitors after this cycle's snapshot.
self.execute_process_actions(name, &rec, deferred_actions, visited, depth)
.await;
// 9. C `recGbl.c::recGblFwdLink:302` clears `putf = FALSE` at the
// tail of every synchronous process cycle, NOT just on the
// foreign-entry path. When this record was driven through an
// OUT-link propagation (write_db_link_value set our putf), the
// target record's own process cycle must clear it before
// returning — same lifecycle as the source record's PUTF
// (which `put_record_field_from_ca` separately clears at the
// foreign-entry boundary, and the async branch clears in
// `complete_async_record_inner`). Async-pending records skip
// this clear: their FLNK / putf-clear happens later in
// `complete_async_record_inner` once the device round-trip
// completes.
{
let guard = rec.read().await;
if !guard.is_processing() {
drop(guard);
let mut guard = rec.write().await;
guard.common.putf = false;
}
}
// Put-notify completion: the record `leave`s the wait-set only
// here, after its full OUT/FLNK/process-action tail has run — so
// every PP target it drove has already joined (`enter`ed). Gated
// on `is_put_complete`: a record reporting more work (e.g. motor
// mid-move via `is_put_complete()==false`) keeps its membership
// and leaves on the later cycle that completes the put — matching
// the old fire site's gate. An async-pending record returned
// earlier and is handled in `complete_async_record_inner`. The
// completion oneshot fires on the `leave` that empties the set.
{
let mut guard = rec.write().await;
if guard.record.is_put_complete() {
complete_put_notify(&mut guard);
}
}
Ok(())
}
/// Forward-link / CP / RPRO tail for the simulation-mode path.
///
/// C `aiRecord.c:151-168`: a record in SIMM mode handles the value
/// inside `readValue()`, then `process()` still runs `monitor` +
/// `recGblFwdLink(prec)`. The simulation path in
/// `process_record_with_links_inner` does its own monitor posting,
/// so this drives the forward-link / CP / RPRO tail that
/// `recGblFwdLink` would. `flnk_name` and `src_putf` are derived
/// fresh from the record (a simulated cycle does not change FLNK,
/// and SIOL reads/writes do not carry a foreign PUTF into the
/// chain).
async fn run_forward_link_tail(
&self,
name: &str,
rec: &Arc<RwLock<RecordInstance>>,
visited: &mut std::collections::HashSet<String>,
depth: usize,
) {
let (flnk_name, src_putf, src_notify) = {
let instance = rec.read().await;
let flnk = if instance.record.should_fire_forward_link() {
if let crate::server::record::ParsedLink::Db(ref l) = instance.parsed_flnk {
Some(l.record.clone())
} else {
None
}
} else {
None
};
(flnk, instance.common.putf, instance.notify.clone())
};
self.run_forward_link_tail_with_putf(
name,
rec,
flnk_name.as_deref(),
PutNotifyCtx {
putf: src_putf,
notify: src_notify.as_ref(),
},
visited,
depth,
)
.await;
}
/// Steps 4.5 - 7 of the process chain: multi-output dispatch,
/// event-record posting, generic OUTA..OUTP links, FLNK forward
/// link, CP-target dispatch, and RPRO reprocess. Shared by the
/// main process path and the simulation-mode path so both run the
/// identical `recGblFwdLink` equivalent.
async fn run_forward_link_tail_with_putf(
&self,
name: &str,
rec: &Arc<RwLock<RecordInstance>>,
flnk_name: Option<&str>,
src: PutNotifyCtx<'_>,
visited: &mut std::collections::HashSet<String>,
depth: usize,
) {
// 4.5. Multi-output dispatch (fanout/dfanout/seq)
self.dispatch_multi_output(rec, visited, depth).await;
// 4.55. event record: post the named software event.
self.dispatch_event_record(rec).await;
// 4.6. Generic multi-output links (transform OUTA..OUTP -> A..P,
// scalcout OUT->OVAL, epid OUTL).
//
// SINGLE-OWNER INVARIANT: a record type whose link groups are
// dispatched by `dispatch_multi_output` (§4.5 above) MUST be
// skipped here — otherwise its `LNKn`/`OUTn` would be written
// twice per cycle. `sseq` previously also implemented the
// `Record::multi_output_links` trait method, so this block
// re-dispatched every selected `LNKn` after §4.5 already drove
// it. The `multi_output_dispatch_owned` gate makes the
// double-dispatch structurally impossible — not just removed
// at the `SseqRecord` call site.
{
let multi_out = {
let instance = rec.read().await;
let links =
if super::links::multi_output_dispatch_owned(instance.record.record_type()) {
&[][..]
} else {
instance.record.multi_output_links()
};
if links.is_empty() {
None
} else {
let mut pairs = Vec::new();
for &(link_field, val_field) in links {
let link_str = instance
.record
.get_field(link_field)
.and_then(|v| {
if let EpicsValue::String(s) = v {
Some(s)
} else {
None
}
})
.unwrap_or_default();
if link_str.is_empty() {
continue;
}
if let Some(val) = instance.record.get_field(val_field) {
pairs.push((link_str, val));
}
}
if pairs.is_empty() { None } else { Some(pairs) }
}
};
if let Some(pairs) = multi_out {
// Source committed alarm for `recGblInheritSevrMsg`
// MS-class propagation into each OUT-link target —
// captured once, same lifecycle as `src.putf`.
let src_alarm = {
let guard = rec.read().await;
super::links::LinkAlarm {
stat: guard.common.stat,
sevr: guard.common.sevr,
amsg: guard.common.amsg.clone(),
}
};
for (link_str, val) in pairs {
// `multi_output_links` carries record OUT links
// (sseq `LNKn`, scalcout `OUTn` — all `DBF_OUTLINK`)
// driven via `dbPutLink` → `dbDbPutValue`
// (`dbDbLink.c:388`): a bare DB link is NPP, the
// value is written but the target is NOT processed.
// `parse_output_link_v2` applies the
// OUT-link-correct NPP default; `parse_link_v2` would
// wrongly default a bare link to ProcessPassive and
// re-process the target. An external `ca://`/`pva://`
// OUT link is routed through the link set's
// `putValue` (C `dbLink.c::dbPutLink`,
// dbLink.c:434-448).
let parsed = crate::server::record::parse_output_link_v2(
link_str.as_str_lossy().as_ref(),
);
self.write_out_link_value(
&parsed,
val,
super::links::OutLinkSrc {
putf: src.putf,
notify: src.notify,
alarm: &src_alarm,
},
visited,
depth,
)
.await;
}
}
}
// 5. FLNK -- only process if target is Passive (like C dbScanFwdLink).
// FLNK goes through C `dbScanPassive` -> `processTarget`, which
// propagates `src.putf` to the target the same way OUT links do.
if let Some(flnk) = flnk_name {
if let Some(target_rec) = self.get_record(flnk).await {
let (target_scan, should_process) = {
let mut tg = target_rec.write().await;
let pact = tg.is_processing();
let on_chain = visited.contains(flnk);
let scan = tg.common.scan;
if !pact {
tg.common.putf = src.putf;
// C `dbNotifyAdd` (dbDbLink.c:460) lives inside
// `processTarget`, which `dbScanPassive` reaches
// ONLY for a passive target (it returns early for
// non-passive — dbDbLink.c:431). Gate the join on
// the same passive condition as the process call
// below: a non-passive FLNK target is dropped here
// and must NOT join, or it would `enter` the
// wait-set without ever processing to `leave` it,
// hanging the completion forever.
if scan == crate::server::record::ScanType::Passive {
join_put_notify(&mut tg, src.notify);
}
} else if src.putf && !on_chain {
tg.common.rpro = true;
tg.common.putf = false;
}
(scan, !pact)
};
if should_process && target_scan == crate::server::record::ScanType::Passive {
// recursive FLNK within one chain — gate
// already held by the foreign entry record.
let _ = self
.process_record_with_links_recursive(flnk, visited, depth + 1)
.await;
}
}
}
// 5b. FLNK whose target is external (`pva://`/`ca://`): C
// `dbScanFwdLink` dispatches it through the link set's
// `scanForward` (pvalink `pvaScanForward`), a process-only trigger
// of the remote target. The `flnk_name` above only ever names a
// local DB target, so a non-DB FLNK is forwarded here through the
// single owner.
self.dispatch_external_forward_link(rec).await;
// 6. CP link targets -- process records that have CP input links from this record
self.dispatch_cp_targets(name, visited, depth).await;
// 7. RPRO: if reprocess requested, clear flag and queue a
// fresh process pass.
//
// C `recGblFwdLink` (recGbl.c:296-300) consumes RPRO via
// `scanOnce(pdbc)` — the record is QUEUED on the scanOnce ring
// buffer and reprocessed in a separate pass with a fresh lock
// cycle AFTER the current process chain fully unwinds. It does
// NOT recurse inline within the current link chain.
//
// Spawning a detached task is the Rust equivalent of the
// scanOnce queue: the reprocess runs with a clean (empty)
// `visited` set and starts at depth 0, so it cannot be
// silently skipped by the current chain's cycle guard nor hit
// the MAX_LINK_DEPTH / MAX_LINK_OPS budget the current chain
// has already consumed.
{
let needs_rpro = {
let mut instance = rec.write().await;
if instance.common.rpro {
instance.common.rpro = false;
true
} else {
false
}
};
if needs_rpro {
let db = self.clone();
let rpro_name = name.to_string();
crate::runtime::task::spawn(async move {
let mut fresh_visited = std::collections::HashSet::new();
let _ = db
.process_record_with_links(&rpro_name, &mut fresh_visited, 0)
.await;
});
}
}
}
/// Fire a non-DB (external `pva://`/`ca://`) forward link (FLNK).
///
/// C `recGblFwdLink` → `dbScanFwdLink` (`dbLink.c:475-480`) dispatches
/// every FLNK uniformly through `plink->lset->scanForward`: a DB lset
/// runs `scanOnce(target)` — handled directly by the local FLNK §5
/// path — while the pvalink/calink lset runs `pvaScanForward`, a
/// process-only trigger of the remote target. The DB-only `flnk_name`
/// filter at the three `should_fire_forward_link` sites dropped every
/// external FLNK; this is the single owner that forwards them, so the
/// dispatch is not open-coded per site (each FLNK tail calls only
/// this).
///
/// On a non-retry, disconnected link the lset returns `Err`; pvxs
/// raises `recGblSetSevrMsg(LINK_ALARM, INVALID_ALARM, "Disconn")` on
/// the owning record (`pvxs/ioc/pvalink_lset.cpp:677-679`). This raises
/// the same *pending* LINK/INVALID alarm via [`rec_gbl_set_sevr_msg`],
/// promoted by the next `recGblResetAlarms` — exactly as the C late-set
/// inside `recGblFwdLink` (after the record's own alarm/monitor stage)
/// is.
async fn dispatch_external_forward_link(&self, rec: &Arc<RwLock<RecordInstance>>) {
let target = {
let instance = rec.read().await;
if !instance.record.should_fire_forward_link() {
return;
}
match &instance.parsed_flnk {
crate::server::record::ParsedLink::Pva(_)
| crate::server::record::ParsedLink::PvaJson(_)
| crate::server::record::ParsedLink::Ca(_) => instance
.parsed_flnk
.external_pv_name()
.map(|s| s.to_string()),
// A DB FLNK is processed by the local §5 scanOnce path;
// every other kind (Constant/Hw/Calc/None) carries no
// forward action.
_ => None,
}
};
let Some(target) = target else {
return;
};
if let Err(e) = self.scan_forward_external_pv(&target).await {
let _ = e;
let mut instance = rec.write().await;
crate::server::recgbl::rec_gbl_set_sevr_msg(
&mut instance.common,
crate::server::recgbl::alarm_status::LINK_ALARM,
crate::server::record::AlarmSeverity::Invalid,
"Disconn",
);
}
}
/// Execute ReadDbLink actions before process().
/// Reads linked PV values and writes them into record fields via put_field_internal.
/// Returns the `link_field` names whose read produced a value, so the
/// caller can fold them into the per-cycle `set_resolved_input_links`
/// report (C `RTN_SUCCESS(dbGetLink(...))`). An empty link is skipped
/// and NOT reported — it is a CONSTANT link in C, which records must
/// not treat as a failed fetch.
async fn execute_read_db_links(
&self,
_record_name: &str,
rec: &Arc<crate::runtime::sync::RwLock<RecordInstance>>,
actions: &[crate::server::record::ProcessAction],
visited: &mut HashSet<String>,
depth: usize,
) -> Vec<&'static str> {
use crate::server::record::ProcessAction;
let mut resolved = Vec::new();
for action in actions {
if let ProcessAction::ReadDbLink {
link_field,
target_field,
} = action
{
let link_str = {
let instance = rec.read().await;
instance
.record
.get_field(link_field)
.and_then(|v| {
if let EpicsValue::String(s) = v {
Some(s)
} else {
None
}
})
.unwrap_or_default()
};
if link_str.is_empty() {
continue;
}
let parsed = crate::server::record::parse_link_v2(link_str.as_str_lossy().as_ref());
if let Some(value) = self.read_link_value(&parsed, visited, depth).await {
let mut instance = rec.write().await;
let _ = instance.record.put_field_internal(target_field, value);
resolved.push(*link_field);
}
}
}
resolved
}
/// Execute ProcessActions returned by a record's process() call.
///
/// Actions are executed in order:
/// - ReadDbLink: reads a linked PV value and writes it into a record field
/// (bypasses read-only checks via put_field_internal)
/// - WriteDbLink: writes a value to a linked PV
/// - ReprocessAfter: schedules a delayed re-process via tokio::spawn
async fn execute_process_actions(
&self,
record_name: &str,
rec: &Arc<crate::runtime::sync::RwLock<RecordInstance>>,
actions: Vec<crate::server::record::ProcessAction>,
visited: &mut HashSet<String>,
depth: usize,
) {
use crate::server::record::ProcessAction;
for action in actions {
match action {
ProcessAction::ReadDbLink {
link_field,
target_field,
} => {
// 1. Get the link string from the record
let link_str = {
let instance = rec.read().await;
instance
.record
.get_field(link_field)
.and_then(|v| {
if let EpicsValue::String(s) = v {
Some(s)
} else {
None
}
})
.unwrap_or_default()
};
if link_str.is_empty() {
continue;
}
// 2. Parse and read the linked PV
let parsed =
crate::server::record::parse_link_v2(link_str.as_str_lossy().as_ref());
if let Some(value) = self.read_link_value(&parsed, visited, depth).await {
// 3. Write into the record field (internal put bypasses read-only)
let mut instance = rec.write().await;
let _ = instance.record.put_field_internal(target_field, value);
}
}
ProcessAction::WriteDbLink { link_field, value } => {
// 1. Get the link string (record fields → common fields)
// and the source PUTF for processTarget propagation,
// plus the committed alarm for `recGblInheritSevrMsg`
// MS-class propagation into the OUT-link target.
let (link_str, src_putf, src_notify, src_alarm) = {
let instance = rec.read().await;
let link = instance
.resolve_field(link_field)
.and_then(|v| {
if let EpicsValue::String(s) = v {
Some(s)
} else {
None
}
})
.unwrap_or_default();
(
link,
instance.common.putf,
instance.notify.clone(),
super::links::LinkAlarm {
stat: instance.common.stat,
sevr: instance.common.sevr,
amsg: instance.common.amsg.clone(),
},
)
};
if link_str.is_empty() {
continue;
}
// 2. Parse and write to the linked PV — DB *or*
// external `ca://`/`pva://`. A record's `process()`
// emits `WriteDbLink` to drive an OUT-link field
// (transform `OUTn`, throttle/scaler `COUTP`, epid
// `TRIG`/`OUTL`); that field may resolve to a CA/PVA
// link, which C `dbPutLink` routes through the link
// set's `putValue` identically to a DB link
// (dbLink.c:434-448).
let parsed =
crate::server::record::parse_link_v2(link_str.as_str_lossy().as_ref());
self.write_out_link_value(
&parsed,
value,
super::links::OutLinkSrc {
putf: src_putf,
notify: src_notify.as_ref(),
alarm: &src_alarm,
},
visited,
depth,
)
.await;
}
ProcessAction::DeviceCommand { command, ref args } => {
let mut instance = rec.write().await;
if let Some(mut dev) = instance.device.take() {
// `handle_command` runs after the process snapshot
// was already built/notified, so any record field
// it mutated needs an explicit monitor post. The
// returned field names are posted with DBE_VALUE,
// mirroring the C record's `db_post_events` calls
// from inside `process()` (scalerRecord.c:425-430).
let changed = dev
.handle_command(&mut *instance.record, command, args)
.unwrap_or_default();
instance.device = Some(dev);
for field in changed {
instance.notify_field(field, crate::server::recgbl::EventMask::VALUE);
}
}
}
ProcessAction::ReprocessAfter(delay) => {
// Owner-driven delayed re-entry, mirroring C
// `callbackRequestDelayed` dispatching to
// `(*prset->process)(prec)` directly (callback.c). Mint
// a fresh token — which advances the record's generation
// and so supersedes any prior pending re-entry for this
// record (a newer ReprocessAfter replaces the older
// timer) — then fire it after the delay. A newer mint or
// an explicit `cancel_async_reentry` makes this fire a
// structural no-op: the gate lives entirely in
// `AsyncToken`, not in an inline generation compare here.
let token = match self.mint_async_token(record_name).await {
Some(t) => t,
None => continue,
};
let db = self.clone();
tokio::spawn(async move {
tokio::time::sleep(delay).await;
let _ = token.fire(&db).await;
});
}
ProcessAction::WriteDbLinkNotify { link_field, value } => {
// C `sseqRecord.c` WAITn put-callback dependency: write
// the OUT link as a put-WITH-completion and re-enter THIS
// record's process() once the downstream record (plus its
// FLNK/OUT chain) finishes. Same OUT-link write a plain
// WriteDbLink performs, wrapped in the c401e2f0 put-notify
// wait-set + async re-entry primitive.
let (link_str, src_putf, src_alarm) = {
let instance = rec.read().await;
let link = instance
.resolve_field(link_field)
.and_then(|v| {
if let EpicsValue::String(s) = v {
Some(s)
} else {
None
}
})
.unwrap_or_default();
(
link,
instance.common.putf,
super::links::LinkAlarm {
stat: instance.common.stat,
sevr: instance.common.sevr,
amsg: instance.common.amsg.clone(),
},
)
};
// Mint the re-entry token BEFORE issuing the put so a
// synchronous downstream completion cannot fire the
// oneshot before the waiter is wired. The mint supersedes
// any prior pending re-entry for this record (newer
// token), exactly like ReprocessAfter.
let token = match self.mint_async_token(record_name).await {
Some(t) => t,
None => continue,
};
let (waitset, completion) = Self::new_put_notify();
if !link_str.is_empty() {
let parsed =
crate::server::record::parse_link_v2(link_str.as_str_lossy().as_ref());
self.write_out_link_value(
&parsed,
value,
super::links::OutLinkSrc {
putf: src_putf,
notify: Some(&waitset),
alarm: &src_alarm,
},
visited,
depth,
)
.await;
}
// Release the initiator's own wait-set count (C
// `dbProcessNotify` holds one count for the requester and
// drops it after issuing the put). The set then drains —
// and fires the completion — when the downstream
// target(s) that joined via `join_put_notify` finish, or
// immediately when the link was empty / the target
// completed synchronously.
waitset.leave();
self.reprocess_on_notify(token, completion);
}
ProcessAction::CancelReprocess => {
// C `callbackCancelDelayed` for `sseq` ABORT: advance the
// record's re-entry generation so any pending DLYn timer
// or WAITn notify re-entry becomes a structural no-op (the
// AsyncToken gate), with no runtime is-aborted check on
// the re-entry path.
self.cancel_async_reentry(record_name).await;
}
}
}
}
/// Complete an asynchronous record's post-process steps.
/// Call after device support signals completion (clears PACT, runs alarms, snapshot, OUT, FLNK).
pub fn complete_async_record<'a>(
&'a self,
name: &'a str,
) -> std::pin::Pin<Box<dyn std::future::Future<Output = CaResult<()>> + Send + 'a>> {
Box::pin(async move {
let mut visited = HashSet::new();
self.complete_async_record_inner(name, &mut visited, 0)
.await
})
}
async fn complete_async_record_inner(
&self,
name: &str,
visited: &mut HashSet<String>,
depth: usize,
) -> CaResult<()> {
// Alias-aware entry — same pattern as
// `process_record_with_links_inner`. `name` may arrive as an
// alias from an async device-support callback that captured
// the original record name; normalise to canonical so the
// records-map lookup, the `visited` cycle set, and downstream
// FLNK/OUT dispatches all see the same canonical name.
let canonical_owned;
let name: &str = if let Some(target) = self.resolve_alias(name).await {
canonical_owned = target;
&canonical_owned
} else {
name
};
let rec = {
let records = self.inner.records.read().await;
records
.get(name)
.cloned()
.ok_or_else(|| CaError::ChannelNotFound(name.to_string()))?
};
// Seed the cycle guard with this record's own name — mirrors
// the synchronous main path (`process_record_with_links_inner`
// does `visited.insert(name)` before the body). Without this
// the async-completion FLNK / OUT / CP dispatch can re-enter
// the just-completed record: an async FLNK chain that loops
// back (A async -> completes -> FLNK -> B -> FLNK -> A) would
// re-process A unbounded, because PACT is cleared below before
// the FLNK dispatch and nothing else blocks the re-entry.
if !visited.insert(name.to_string()) {
return Ok(()); // Cycle detected, skip
}
let (snapshot, out_info, flnk_name, alarm_posts) = {
let mut instance = rec.write().await;
// UDF update before alarm evaluation (C parity — see the
// sync process path). A NaN/undefined value keeps UDF true
// so `recGblCheckUDF` raises UDF_ALARM this cycle.
if instance.record.clears_udf() {
instance.common.udf = instance.record.value_is_undefined();
}
// Per-record alarm hook (C `checkAlarms()`).
{
let inst = &mut *instance;
inst.record.check_alarms(&mut inst.common);
}
// Evaluate alarms
instance.evaluate_alarms();
let is_soft = instance.common.dtyp.is_empty() || instance.common.dtyp == "Soft Channel";
// Device support alarm/timestamp override
if !is_soft {
let (dev_alarm, dev_ts, dev_utag) = if let Some(ref dev) = instance.device {
(dev.last_alarm(), dev.last_timestamp(), dev.last_utag())
} else {
(None, None, None)
};
if let Some((stat, sevr)) = dev_alarm {
crate::server::recgbl::rec_gbl_set_sevr(
&mut instance.common,
stat,
crate::server::record::AlarmSeverity::from_u16(sevr),
);
}
if let Some(ts) = dev_ts {
instance.common.time = ts;
}
// C device support writes `prec->utag` directly during
// `read()` — the event-system pulse-id path, since
// `epicsTimeStamp` carries no tag. Adopt the device's
// userTag when it supplies one; read in the same `dev`
// borrow as the timestamp above so the time/tag pair is a
// single consistent device snapshot.
if let Some(utag) = dev_utag {
instance.common.utag = utag;
}
}
let alarm_result = crate::server::recgbl::rec_gbl_reset_alarms(&mut instance.common);
apply_timestamp(&mut instance.common, is_soft);
// UDF was already updated before `evaluate_alarms` above.
// Clear PACT
instance
.processing
.store(false, std::sync::atomic::Ordering::Release);
// Put-notify completion is NOT fired here. The async device
// round-trip has finished, but the OUT/FLNK/process-action
// tail it drives (below) may itself reach an async target;
// firing now would report WRITE_NOTIFY done while that chain
// still runs. The originating record `leave`s the wait-set at
// the END of this function, after every PP target it drives
// has joined. See `complete_put_notify` at the tail.
use crate::server::recgbl::EventMask;
let (include_val, include_archive) = match instance.record.monitor_value_changed() {
// lsi/lso post VALUE|LOG only when the string actually
// changed (C `lsiRecord.c`/`lsoRecord.c` monitor: `len !=
// olen || memcmp(oval, val, len)`); they have no MDEL/ADEL
// deadband to express that, so the gate is explicit. The
// MPST/APST `menuPost` "Always" override OR-adds DBE_VALUE /
// DBE_LOG even on an unchanged cycle (C monitor: `if (mpst ==
// menuPost_Always) events |= DBE_VALUE; if (apst ==
// menuPost_Always) events |= DBE_LOG;`).
Some(changed) => {
let (val_always, archive_always) = instance.record.monitor_always_post();
(changed || val_always, changed || archive_always)
}
None => {
if instance.record.uses_monitor_deadband() {
instance.check_deadband_ext()
} else {
// Binary records (bi/bo/busy/mbbi/mbbo): always post monitors
(true, true)
}
}
};
// C `recGblResetAlarms` `val_mask = DBE_ALARM`
// (recGbl.c:194/203/212) — same parity rule as the main
// process path above (see comment there).
let alarm_bits = if alarm_result.alarm_changed || alarm_result.amsg_changed {
EventMask::ALARM
} else {
EventMask::NONE
};
let mut changed_fields = Vec::new();
// Same deadband-field routing and per-field mask as the main
// process path: the tracked field posts the classes that
// actually fired (MDEL → DBE_VALUE, ADEL → DBE_LOG, alarm
// movement → DBE_ALARM); a non-primary deadband field
// (motor RBV) leaves VAL to the generic change-detection
// loop below.
let deadband_field = instance.record.monitor_deadband_field();
let deadband_mask = {
let mut m = alarm_bits;
if include_val {
m |= EventMask::VALUE;
}
if include_archive {
m |= EventMask::LOG;
}
m
};
if !deadband_mask.is_empty() {
let dval = if deadband_field == "VAL" {
instance.record.val()
} else {
instance.resolve_field(deadband_field)
};
if let Some(val) = dval {
changed_fields.push((deadband_field.to_string(), val, deadband_mask));
}
}
// C `recGblResetAlarms` (recGbl.c:201-220) posts each alarm
// field with its OWN per-field mask. Mirror the synchronous
// link path (`process_record_with_links_inner`) and
// `process_local` exactly: SEVR=DBE_VALUE on a sevr change;
// STAT/AMSG share `stat_mask` which carries DBE_ALARM when
// sevr OR amsg moved and DBE_VALUE on a stat change;
// ACKS=DBE_VALUE only when an alarm field moved AND
// recGblResetAlarms raised it. Collapsing these into
// `changed_fields` would post them all on one shared mask —
// losing C's per-field granularity for `.SEVR`/`.STAT`-only
// subscribers.
let sevr_changed = instance.common.sevr != alarm_result.prev_sevr;
let stat_changed = instance.common.stat != alarm_result.prev_stat;
let stat_mask = {
let mut m = EventMask::NONE;
if sevr_changed || alarm_result.amsg_changed {
m |= EventMask::ALARM;
}
if stat_changed {
m |= EventMask::VALUE;
}
m
};
let mut alarm_posts: Vec<(&'static str, EventMask)> = Vec::new();
if sevr_changed {
alarm_posts.push(("SEVR", EventMask::VALUE));
}
if !stat_mask.is_empty() {
alarm_posts.push(("STAT", stat_mask));
alarm_posts.push(("AMSG", stat_mask));
}
// C parity (recGbl.c:216): ACKS is posted (DBE_VALUE) only
// when an alarm field moved AND recGblResetAlarms raised it.
if alarm_result.acks_changed && !stat_mask.is_empty() {
alarm_posts.push(("ACKS", EventMask::VALUE));
}
// Add subscribed non-{deadband-field,SEVR,STAT,AMSG,UDF}
// fields that actually changed since last notification —
// mirrors the main-path snapshot gate
// (process_record_with_links_inner L794-820). Without this,
// every async-completion cycle re-sends every subscribed
// auxiliary field even when its value is unchanged,
// multiplying the monitor traffic for any record that pairs
// an async write with a sticky metadata field. The
// deadband-gated field (default VAL) is delivered by the
// trigger branch above, never by raw change-detection. Each
// carries DBE_VALUE|DBE_LOG plus the cycle's alarm bits (C
// `monitor_mask | DBE_VALUE | DBE_LOG` for change-detected
// auxiliary posts). On a cycle whose alarm transition
// fired, fields named by `alarm_cycle_monitored_fields`
// post even when unchanged, with the alarm bits alone — C
// motor `monitor()` (motorRecord.cc:3513-3645) posts every
// listed field once `monitor_mask != 0`.
let aux_mask = alarm_bits | EventMask::VALUE | EventMask::LOG;
let alarm_fanout: &[&str] = if alarm_bits.is_empty() {
&[]
} else {
instance.record.alarm_cycle_monitored_fields()
};
// Fields the record force-posts every cycle it recomputed them
// (C unconditional MARK + DBE_VAL_LOG), even when unchanged —
// see `Record::force_posted_fields`. Empty for most records.
let force_fields = instance.record.force_posted_fields();
// Fields re-posted with DBE_LOG only every cycle, regardless
// of change — see `Record::log_swept_fields` (scaler idle Sn
// sweep). Empty for most records.
let log_swept = instance.record.log_swept_fields();
let mut sub_updates: Vec<(String, EpicsValue, EventMask)> = Vec::new();
for (field, subs) in &instance.subscribers {
if !subs.is_empty()
&& field != deadband_field
&& field != "SEVR"
&& field != "STAT"
&& field != "AMSG"
&& field != "UDF"
{
if let Some(val) = instance.resolve_field(field) {
let changed = match instance.last_posted.get(field) {
Some(prev) => prev != &val,
None => true,
};
if changed {
sub_updates.push((field.clone(), val, aux_mask));
} else if force_fields.contains(&field.as_str()) {
// C `monitor()` posts a re-marked field with
// `monitor_mask | DBE_VAL_LOG` even when unchanged.
sub_updates.push((field.clone(), val, aux_mask));
} else if alarm_fanout.contains(&field.as_str()) {
sub_updates.push((field.clone(), val, alarm_bits));
} else if log_swept.contains(&field.as_str()) {
// C scalerRecord.c:770-787 `monitor()`: every
// idle process re-posts each S1..Snch with a
// literal DBE_LOG regardless of change. A
// changed field is already delivered above
// with DBE_VALUE|DBE_LOG (covering the LOG
// subscriber), so only the unchanged sweep
// lands here — no double post.
sub_updates.push((field.clone(), val, EventMask::LOG));
}
}
}
}
if !sub_updates.is_empty() {
for (field, val, _) in &sub_updates {
instance.last_posted.insert(field.clone(), val.clone());
}
changed_fields.extend(sub_updates);
}
// UDF rides along whenever any monitored post fired this
// cycle, carrying the union of the cycle's posted classes —
// same rule as the main process path.
let cycle_mask = changed_fields
.iter()
.fold(EventMask::NONE, |m, (_, _, fm)| m | *fm);
if !cycle_mask.is_empty() {
changed_fields.push((
"UDF".to_string(),
EpicsValue::Char(if instance.common.udf { 1 } else { 0 }),
cycle_mask,
));
}
let snapshot = crate::server::record::ProcessSnapshot { changed_fields };
// IVOA check
let skip_out = if instance.common.sevr == crate::server::record::AlarmSeverity::Invalid
{
let ivoa = instance
.record
.get_field("IVOA")
.and_then(|v| {
if let EpicsValue::Short(s) = v {
Some(s)
} else {
None
}
})
.unwrap_or(0);
match ivoa {
1 => true,
2 => {
// See the IVOA=2 comment in
// `process_record_with_links_inner` — IVOA=2
// delegates to the per-record
// `apply_invalid_output_value` so OVAL/RVAL/VAL
// get the C-convention values.
if let Some(ivov) = instance.record.get_field("IVOV") {
let _ = instance.record.apply_invalid_output_value(ivov);
}
false
}
_ => false,
}
} else {
false
};
let can_dev_write = instance.record.can_device_write();
let is_soft_out =
instance.common.dtyp.is_empty() || instance.common.dtyp == "Soft Channel";
let record_should_output = instance.record.should_output();
let out_info = if skip_out {
None
} else if !can_dev_write {
// Non-output records (calcout, etc.) with soft OUT link
// (DB or external `ca://`/`pva://`).
if record_should_output && instance.parsed_out.is_writable_out_link() {
let out_val = instance
.record
.get_field("OVAL")
.or_else(|| instance.record.val());
out_val.map(|v| (instance.parsed_out.clone(), v))
} else {
None
}
} else if is_soft_out {
if instance.parsed_out.is_writable_out_link() {
let out_val = instance
.record
.get_field("OVAL")
.or_else(|| instance.record.val());
out_val.map(|v| (instance.parsed_out.clone(), v))
} else {
None
}
} else {
// Non-soft output: the async device write already completed
// (that's why we're in complete_async_record). Don't re-do
// write_begin -- it would start another async cycle.
None
};
let flnk_name = if instance.record.should_fire_forward_link() {
if let crate::server::record::ParsedLink::Db(ref l) = instance.parsed_flnk {
Some(l.record.clone())
} else {
None
}
} else {
None
};
(snapshot, out_info, flnk_name, alarm_posts)
};
// Notify subscribers
{
let instance = rec.read().await;
instance.notify_from_snapshot(&snapshot);
// Post the alarm fields (SEVR/STAT/AMSG/ACKS) with their
// individual C masks — see recGblResetAlarms above.
for &(field, mask) in &alarm_posts {
instance.notify_field(field, mask);
}
}
// Snapshot source PUTF + put-notify wait-set for processTarget /
// dbNotifyAdd propagation (see `write_db_link_value` doc). For the
// async-completion path PUTF would have been set when the put
// landed on the record; it (and wait-set membership) must
// propagate through the (now-completing) OUT / FLNK chain so an
// async target reached here also defers WRITE_NOTIFY completion.
// The committed alarm propagates the same way for
// `recGblInheritSevrMsg` MS-class inheritance.
let (src_putf, src_notify, src_alarm) = {
let guard = rec.read().await;
(
guard.common.putf,
guard.notify.clone(),
super::links::LinkAlarm {
stat: guard.common.stat,
sevr: guard.common.sevr,
amsg: guard.common.amsg.clone(),
},
)
};
// OUT link — DB *or* external `ca://`/`pva://`. Same scheme
// dispatch as the sync path (C `dbLink.c::dbPutLink`,
// dbLink.c:434-448).
if let Some((link, out_val)) = out_info {
self.write_out_link_value(
&link,
out_val,
super::links::OutLinkSrc {
putf: src_putf,
notify: src_notify.as_ref(),
alarm: &src_alarm,
},
visited,
depth,
)
.await;
}
// Multi-output dispatch (fanout/dfanout/seq/sseq)
self.dispatch_multi_output(&rec, visited, depth).await;
// event record: post the named software event.
self.dispatch_event_record(&rec).await;
// Generic multi-output links (transform OUTA..OUTP -> A..P,
// scalcout OUT->OVAL, epid OUTL).
//
// SINGLE-OWNER INVARIANT: skip any record type owned by
// `dispatch_multi_output` (called above) so its `LNKn`/`OUTn`
// is not dispatched twice — see the sync-path twin in
// `run_forward_link_tail_with_putf` §4.6.
{
let multi_out = {
let instance = rec.read().await;
let links =
if super::links::multi_output_dispatch_owned(instance.record.record_type()) {
&[][..]
} else {
instance.record.multi_output_links()
};
if links.is_empty() {
None
} else {
let mut pairs = Vec::new();
for &(link_field, val_field) in links {
let link_str = instance
.record
.get_field(link_field)
.and_then(|v| {
if let EpicsValue::String(s) = v {
Some(s)
} else {
None
}
})
.unwrap_or_default();
if link_str.is_empty() {
continue;
}
if let Some(val) = instance.record.get_field(val_field) {
pairs.push((link_str, val));
}
}
if pairs.is_empty() { None } else { Some(pairs) }
}
};
if let Some(pairs) = multi_out {
for (link_str, val) in pairs {
// `multi_output_links` carries record OUT links
// (sseq `LNKn`, scalcout `OUTn` — all `DBF_OUTLINK`):
// a bare DB link is NPP (`dbDbLink.c:388`).
// `parse_output_link_v2` applies the OUT-link-correct
// NPP default; an external `ca://`/`pva://` link is
// routed through the link set's `putValue` — see the
// sync-path twin above.
let parsed = crate::server::record::parse_output_link_v2(
link_str.as_str_lossy().as_ref(),
);
self.write_out_link_value(
&parsed,
val,
super::links::OutLinkSrc {
putf: src_putf,
notify: src_notify.as_ref(),
alarm: &src_alarm,
},
visited,
depth,
)
.await;
}
}
}
// FLNK -- only process if target is Passive (C `dbScanFwdLink` ->
// `dbScanPassive` -> `processTarget` propagates PUTF the same way
// OUT links do).
if let Some(ref flnk) = flnk_name {
if let Some(target_rec) = self.get_record(flnk).await {
let (target_scan, should_process) = {
let mut tg = target_rec.write().await;
let pact = tg.is_processing();
let on_chain = visited.contains(flnk);
let scan = tg.common.scan;
if !pact {
tg.common.putf = src_putf;
// C `dbNotifyAdd` (dbDbLink.c:460) is reached only
// inside `processTarget`, which `dbScanPassive`
// calls solely for a passive target. Gate the join
// on the same passive condition as the process
// call below so a dropped (non-passive) target
// never `enter`s the wait-set without `leave`ing.
if scan == crate::server::record::ScanType::Passive {
join_put_notify(&mut tg, src_notify.as_ref());
}
} else if src_putf && !on_chain {
tg.common.rpro = true;
tg.common.putf = false;
}
(scan, !pact)
};
if should_process && target_scan == crate::server::record::ScanType::Passive {
// recursive FLNK within one chain — gate
// already held by the foreign entry record.
let _ = self
.process_record_with_links_recursive(flnk, visited, depth + 1)
.await;
}
}
}
// FLNK whose target is external (`pva://`/`ca://`): forwarded
// through the same single owner as the synchronous tail (C
// `dbScanFwdLink` → lset `scanForward`). `flnk_name` above only
// names a local DB target.
self.dispatch_external_forward_link(&rec).await;
// CP link targets
self.dispatch_cp_targets(name, visited, depth).await;
// RPRO: C `recGblFwdLink` consumes a pending reprocess via
// `scanOnce` — queued, not recursed. Mirror the synchronous
// path: spawn a fresh process pass (clean `visited`, depth 0).
{
let needs_rpro = {
let mut guard = rec.write().await;
if guard.common.rpro {
guard.common.rpro = false;
true
} else {
false
}
};
if needs_rpro {
let db = self.clone();
let rpro_name = name.to_string();
crate::runtime::task::spawn(async move {
let mut fresh_visited = std::collections::HashSet::new();
let _ = db
.process_record_with_links(&rpro_name, &mut fresh_visited, 0)
.await;
});
}
}
// C `recGbl.c::recGblFwdLink:302` clears `putf = FALSE` after
// the forward-link dispatch. The same clearing must happen
// at the tail of the async-completion path (this is the moral
// equivalent of the synchronous completion path in
// `put_record_field_from_ca` which clears after
// `process_record_with_links` returns). Without this, a
// record that completed an async write triggered by a
// CA put would keep `putf=1` forever, leaking into every
// subsequent scan-driven process cycle.
{
let mut guard = rec.write().await;
guard.common.putf = false;
}
// Put-notify completion: the async device round-trip is done and
// the full OUT/FLNK/process-action tail above has run, so every PP
// target it drove has joined the wait-set. The originating record
// now `leave`s; the completion oneshot fires on the `leave` that
// empties the set (i.e. once every joined async target has also
// completed). `complete_put_notify` `take`s the membership, so a
// motor re-entering `complete_async_record_inner` over several
// device cycles leaves exactly once — matching the old fire site,
// which `take`d its oneshot.
{
let mut guard = rec.write().await;
complete_put_notify(&mut guard);
}
Ok(())
}
/// Dispatch CP-link targets that take a CP/CPP input link from `name`.
///
/// C parity (a4bc0db): the CP-driven dispatch is the moral equivalent of
/// dbCaTask's CA_DBPROCESS handler invoking `db_process(prec)`. Before
/// processing each target, set PUTF=true; if the target is already
/// processing (async record mid-flight), set RPRO=true instead so the
/// in-flight pass reprocesses on completion. Already-visited targets
/// (current process chain) are skipped via the `visited` cycle guard.
async fn dispatch_cp_targets(
&self,
name: &str,
visited: &mut std::collections::HashSet<String>,
depth: usize,
) {
let cp_targets = self.get_cp_targets(name).await;
for target in cp_targets {
self.process_one_cp_target(&target, visited, depth).await;
}
}
/// Process a single CP/CPP target edge, applying the CPP passive gate
/// and the PACT/RPRO pre-check. This is the single owner of the
/// scan-time CP-dispatch decision, shared by the local-source path
/// ([`Self::dispatch_cp_targets`]) and the cross-IOC path
/// ([`Self::dispatch_external_cp_targets`]) so both honour the same
/// `dbCa.c` semantics.
async fn process_one_cp_target(
&self,
target: &super::CpTarget,
visited: &mut std::collections::HashSet<String>,
depth: usize,
) {
if visited.contains(&target.record) {
return;
}
let target_rec = {
let records = self.inner.records.read().await;
records.get(&target.record).cloned()
};
let mut skip = false;
if let Some(ref t) = target_rec {
let mut tg = t.write().await;
if target.passive_only && tg.common.scan != crate::server::record::ScanType::Passive {
// CPP gate (`dbCa.c:854,994,1072`): a CPP link adds
// `CA_DBPROCESS` only when the link-holder's SCAN is
// Passive. A non-Passive target is reached by its own
// periodic/event scan, so skip it here — no process,
// no RPRO. A CP link (`passive_only == false`) never
// takes this branch and always processes.
skip = true;
} else if tg.processing.load(std::sync::atomic::Ordering::Acquire) {
tg.common.rpro = true;
skip = true;
}
// else (not processing): fall through and process below.
// epics-base PR #3fb10b6: PUTF must remain false on
// CP-driven targets — only the record directly receiving
// the dbPut reports PUTF=1 to dbNotify/onChange observers,
// so we deliberately do NOT set PUTF here.
}
if skip {
return;
}
// recursive CP-target fan-out within one chain —
// gate already held by the foreign entry record.
let _ = self
.process_record_with_links_recursive(&target.record, visited, depth + 1)
.await;
}
/// Process every holder of an EXTERNAL CP/CPP link to `external_pv` —
/// the cross-IOC twin of [`Self::dispatch_cp_targets`]. Called by the
/// calink/pvalink CA monitor callback on every remote change, this is
/// the Rust equivalent of C `dbCa.c eventCallback` adding
/// `CA_DBPROCESS` for a CP (or Passive CPP) link (`dbCa.c:993-994`)
/// and the worker thread running `db_process(prec)` (`dbCa.c:1295`).
/// A cross-IOC source never processes locally, so this callback is the
/// only trigger; without it a `CP`/`CPP` link's holder never processes
/// on a remote change.
///
/// A fresh `visited` set and `depth = 0` start a new process chain —
/// the monitor event is an independent external trigger, like a scan,
/// not a continuation of an in-flight local chain.
pub async fn dispatch_external_cp_targets(&self, external_pv: &str) {
let targets = self.get_external_cp_targets(external_pv).await;
if targets.is_empty() {
return;
}
let mut visited = std::collections::HashSet::new();
for target in targets {
self.process_one_cp_target(&target, &mut visited, 0).await;
}
}
/// Write a simulation value to an output record's SIOL link,
/// dispatching by link type and locality exactly as C `dbPutLink`
/// (reached from `writeValue` for a SIMM-mode output record):
///
/// - a **local DB** target uses the already-locked write — writing
/// VAL is an internal step of this record's processing chain,
/// which already holds the entry record's advisory write gate, so
/// a SIOL pointing back at a chain record must not re-acquire the
/// non-reentrant gate (same reasoning as `write_db_link_value`);
/// - a **non-local DB** target (`dbInitLink` made it a CA link) and
/// an explicit **`Ca`/`Pva`** link route through the lset put path;
/// - constant / hardware / none SIOL targets are not writable — no-op
/// (C `dbPutLink` -> `S_db_noLSET`).
async fn write_sim_siol_value(
&self,
siol: &crate::server::record::ParsedLink,
value: EpicsValue,
) {
match siol {
crate::server::record::ParsedLink::Db(link) => {
let pv_name = if link.field == "VAL" {
link.record.clone()
} else {
format!("{}.{}", link.record, link.field)
};
if self.has_name_no_resolve(&link.record).await {
let _ = self.put_pv_already_locked(&pv_name, value).await;
} else if let Err(e) = self
.write_external_pv(&pv_name, value, crate::server::database::LinkPutOp::Plain)
.await
{
eprintln!("SIOL simulation write to external PV '{pv_name}' failed: {e}");
}
}
crate::server::record::ParsedLink::Ca(_)
| crate::server::record::ParsedLink::Pva(_)
| crate::server::record::ParsedLink::PvaJson(_) => {
let name = siol
.external_pv_name()
.expect("Ca/Pva/PvaJson link carries a PV name");
if let Err(e) = self
.write_external_pv(&name, value, crate::server::database::LinkPutOp::Plain)
.await
{
eprintln!("SIOL simulation write to external PV '{name}' failed: {e}");
}
}
_ => {}
}
}
/// Check simulation mode for a record. Returns
/// `SimOutcome::Simulated` when simulation handled the value (the
/// caller must still run the forward-link tail), or
/// `SimOutcome::NotSimulated` when normal processing should proceed.
async fn check_simulation_mode(&self, rec: &Arc<RwLock<RecordInstance>>) -> SimOutcome {
// Read SIML, SIMM, SIOL, SIMS from the record
let (siml_link, siol_link, sims, _rtype, is_input) = {
let instance = rec.read().await;
let rtype = instance.record.record_type().to_string();
// Every input record whose DBD declares SIML/SIOL/SIMM/SIMS.
// `mbbi`/`mbbiDirect` are input records: `mbbiRecord.c:125-126`
// (and mbbiDirectRecord.c) declare SIML+SIOL, and
// `mbbiRecord.c:388-394` reads `dbGetLink(&prec->siol,
// DBR_ULONG, &prec->sval)` then `rval = sval` — input
// semantics. Omitting them sent a simulated mbbi down the
// OUTPUT branch, which writes VAL out to SIOL instead of
// reading the value in from it.
let is_input = matches!(
rtype.as_str(),
"ai" | "bi"
| "mbbi"
| "mbbiDirect"
| "longin"
| "int64in"
| "stringin"
| "lsi"
| "event"
);
let siml = instance
.record
.get_field("SIML")
.and_then(|v| {
if let EpicsValue::String(s) = v {
Some(s)
} else {
None
}
})
.unwrap_or_default();
let siol = instance
.record
.get_field("SIOL")
.and_then(|v| {
if let EpicsValue::String(s) = v {
Some(s)
} else {
None
}
})
.unwrap_or_default();
let sims = instance
.record
.get_field("SIMS")
.and_then(|v| {
if let EpicsValue::Short(s) = v {
Some(s)
} else {
None
}
})
.unwrap_or(0);
if siml.is_empty() && siol.is_empty() {
return SimOutcome::NotSimulated; // No simulation configured
}
let siml_parsed = crate::server::record::parse_link_v2(siml.as_str_lossy().as_ref());
let siol_parsed = crate::server::record::parse_link_v2(siol.as_str_lossy().as_ref());
(siml_parsed, siol_parsed, sims, rtype, is_input)
};
// Read SIML -> update SIMM. C `dbGetLink(&prec->siml, DBR_USHORT,
// &prec->simm, 0, 0)` reads the SIML link for any type; the
// pre-fix port only read a `ParsedLink::Db` SIML, ignoring a
// CA/PVA/constant simulation-mode source.
if let Some(val) = self.read_link_value_no_process(&siml_link).await {
let simm_val = val.to_f64().unwrap_or(0.0) as i16;
let mut instance = rec.write().await;
let _ = instance
.record
.put_field("SIMM", EpicsValue::Short(simm_val));
}
// Check SIMM
let simm = {
let instance = rec.read().await;
instance
.record
.get_field("SIMM")
.and_then(|v| {
if let EpicsValue::Short(s) = v {
Some(s)
} else {
None
}
})
.unwrap_or(0)
};
if simm == 0 {
return SimOutcome::NotSimulated; // NO simulation, proceed normally
}
// epics-base 7.0.7 (SIMM menu):
// 1 = YES — read/write via SIOL using the cooked VAL
// 2 = RAW — read/write via SIOL using the raw RVAL when the
// record carries one (ai/ao only); falls back to
// VAL when no RVAL is present. Mirrors the C
// implementation, which treats records lacking
// a raw value as "YES" since there's nothing
// else to copy.
let raw_mode = simm == 2;
let raw_field = if raw_mode { "RVAL" } else { "VAL" };
// SIMM=YES(1) / SIMM=RAW(2): read/write the SIOL link. C
// `readValue`/`writeValue` for a SIMM-mode record go through
// `dbGetLink`/`dbPutLink`, which dispatch by link type — a local
// DB target, a CA target (a bare non-local name or an explicit
// `CA`/`ca://` link), or a constant. The pre-fix port special-
// cased a local `ParsedLink::Db` SIOL only, so a non-local or
// external SIOL neither read nor wrote yet still returned
// `Simulated` — the record froze with no value and no alarm.
// Dispatch uniformly through the same link read/write owners as
// every other link; the alarm/timestamp/notify tail below now
// runs for every SIOL link type.
{
if is_input {
// Input record: read from SIOL -> set VAL/RVAL. Uniform
// across Db (with locality fallback) / Ca / Pva / constant
// via `read_link_value_no_process` (C `dbGetLink`).
if let Some(siol_val) = self.read_link_value_no_process(&siol_link).await {
let mut instance = rec.write().await;
let target_supports_raw =
raw_mode && instance.record.get_field("RVAL").is_some();
if target_supports_raw {
// PR #ac92e3e follow-up: SIMM=RAW on records
// with RVAL (ai/ao/etc.) writes the raw value
// into RVAL and runs the record's own
// process() so the LINR / ESLO / EOFF / ASLO
// / AOFF conversion chain computes VAL. The
// pre-fix path additionally called set_val
// here, which overwrote VAL with the raw
// count and silently bypassed conversion —
// the visible failure mode was "SIMM=RAW
// simulation returns counts instead of EGU".
//
// Coerce to RVAL's native DBR type before
// put_field — ai.RVAL is Long, but SIOL on a
// soft channel typically yields Double. Without
// the coerce step the put_field rejects with
// TypeMismatch and leaves RVAL at 0, so
// process() computes VAL = 0*ESLO + EOFF
// (the offset only), not the intended
// RAW*ESLO + EOFF.
let rval_type = instance
.record
.field_list()
.iter()
.find(|f| f.name == "RVAL")
.map(|f| f.dbf_type)
.unwrap_or(crate::types::DbFieldType::Long);
// C parity (aiRecord.c:495): `rval = (long)floor(sval)`.
// Rust `convert_to(Long)` truncates toward zero,
// diverging for negative bipolar-ADC raw values
// (sval=-1.5 → C: -2, Rust as-cast: -1).
// Floor explicitly when narrowing a float to
// an integer RVAL.
let coerced = match (&siol_val, rval_type) {
(EpicsValue::Double(d), crate::types::DbFieldType::Long) => {
EpicsValue::Long(d.floor() as i32)
}
(EpicsValue::Double(d), crate::types::DbFieldType::Int64) => {
EpicsValue::Int64(d.floor() as i64)
}
(EpicsValue::Float(d), crate::types::DbFieldType::Long) => {
EpicsValue::Long((*d as f64).floor() as i32)
}
(EpicsValue::Float(d), crate::types::DbFieldType::Int64) => {
EpicsValue::Int64((*d as f64).floor() as i64)
}
_ if siol_val.db_field_type() != rval_type => {
siol_val.convert_to(rval_type)
}
_ => siol_val,
};
let _ = instance.record.put_field("RVAL", coerced);
let ctx = instance.common.process_context();
instance.record.set_process_context(&ctx);
let _ = instance.record.process();
} else {
// Records without RVAL fall back to SIMM=YES
// semantics: the SIOL value goes straight into
// VAL; no conversion to run.
let _ = instance.record.set_val(siol_val);
}
// Simulation alarm + per-field monitor tail — see
// `sim_process_tail`.
sim_process_tail(&mut instance, sims);
}
} else {
// Output record: write VAL (or RVAL for SIMM=RAW) to
// SIOL (skip device write).
let out_val = {
let instance = rec.read().await;
if raw_mode {
// RAW path: prefer RVAL when the record has
// one. Otherwise fall through to VAL.
instance
.record
.get_field(raw_field)
.or_else(|| instance.record.val())
} else {
instance.record.val()
}
};
if let Some(val) = out_val {
// Write VAL to the SIOL target, dispatching by link
// type/locality (C `dbPutLink`). A local DB target
// uses the `_already_locked` write — writing VAL is an
// internal step of this record's processing chain,
// which already holds the entry record's advisory
// write gate, so a SIOL that points back at a chain
// record cannot dead-lock on a non-reentrant gate
// (same reasoning as the OUT-link write in
// `write_db_link_value`). A non-local or external
// SIOL routes through the lset put path.
self.write_sim_siol_value(&siol_link, val).await;
}
let mut instance = rec.write().await;
// Simulation alarm + per-field monitor tail — see
// `sim_process_tail`.
sim_process_tail(&mut instance, sims);
}
}
SimOutcome::Simulated
}
}
/// Shared tail of a simulated (`SIMM` != NO) process cycle — the part of
/// C `process()` that still runs when `readValue`/`writeValue` divert to
/// the SIOL (`aiRecord.c` and every SIML/SIMM-bearing record):
/// `recGblSetSevr(prec, SIMM_ALARM, prec->sims)` — a MAXIMIZE into the
/// pending nsta/nsev raised first so it wins severity ties (C order:
/// readValue before checkAlarms) — then `checkAlarms`,
/// `recGblResetAlarms`, and `monitor()`, so the simulated value still
/// trips its own limit/state alarms and the SIMM severity maximizes
/// against them.
///
/// The posting masks are per-field, identical to the async-completion
/// path (`complete_async_record`) and `process_local`:
///
/// * the deadband-tracked field (default `VAL`) posts the classes that
/// actually fired — MDEL → `DBE_VALUE`, ADEL → `DBE_LOG`, alarm
/// movement → `DBE_ALARM` (C `recGblResetAlarms` `val_mask`); the
/// lsi/lso explicit change gate, MPST/APST always-post override, and
/// binary always-post route through the same hooks as those paths;
/// * `SEVR` posts `DBE_VALUE` only on a sevr change; `STAT`/`AMSG`
/// share a mask carrying `DBE_ALARM` (sevr/amsg moved) and/or
/// `DBE_VALUE` (stat moved); `ACKS` posts `DBE_VALUE` when the reset
/// raised it (recGbl.c:201-220);
/// * subscribed auxiliary fields post on value change with
/// `DBE_VALUE|DBE_LOG` plus the cycle's alarm bits (C change-detected
/// posts in each record's `monitor()`, e.g. ai `oraw != rval`), and
/// `UDF` rides along with the union of the cycle's posted classes.
///
/// The pre-fix tails (duplicated across the input and output SIMM
/// branches) pushed `VAL`/`SEVR`/`STAT` unconditionally with one shared
/// `DBE_VALUE|DBE_ALARM` mask and discarded the `rec_gbl_reset_alarms`
/// result — every simulated cycle re-sent unchanged alarm fields,
/// stamped `DBE_ALARM` on cycles whose alarm state never moved, and
/// bypassed the MDEL/ADEL deadband entirely.
fn sim_process_tail(instance: &mut RecordInstance, sims: i16) {
use crate::server::recgbl::EventMask;
apply_timestamp(&mut instance.common, true);
instance.common.udf = false;
let sev = crate::server::record::AlarmSeverity::from_u16(sims as u16);
crate::server::recgbl::rec_gbl_set_sevr(
&mut instance.common,
crate::server::recgbl::alarm_status::SIMM_ALARM,
sev,
);
{
let inst = &mut *instance;
inst.record.check_alarms(&mut inst.common);
}
instance.evaluate_alarms();
let alarm_result = crate::server::recgbl::rec_gbl_reset_alarms(&mut instance.common);
let alarm_bits = if alarm_result.alarm_changed || alarm_result.amsg_changed {
EventMask::ALARM
} else {
EventMask::NONE
};
let (include_val, include_archive) = match instance.record.monitor_value_changed() {
Some(changed) => {
let (val_always, archive_always) = instance.record.monitor_always_post();
(changed || val_always, changed || archive_always)
}
None => {
if instance.record.uses_monitor_deadband() {
instance.check_deadband_ext()
} else {
(true, true)
}
}
};
let deadband_field = instance.record.monitor_deadband_field();
let deadband_mask = {
let mut m = alarm_bits;
if include_val {
m |= EventMask::VALUE;
}
if include_archive {
m |= EventMask::LOG;
}
m
};
let mut changed_fields = Vec::new();
if !deadband_mask.is_empty() {
let dval = if deadband_field == "VAL" {
instance.record.val()
} else {
instance.resolve_field(deadband_field)
};
if let Some(val) = dval {
changed_fields.push((deadband_field.to_string(), val, deadband_mask));
}
}
let sevr_changed = instance.common.sevr != alarm_result.prev_sevr;
let stat_changed = instance.common.stat != alarm_result.prev_stat;
let stat_mask = {
let mut m = EventMask::NONE;
if sevr_changed || alarm_result.amsg_changed {
m |= EventMask::ALARM;
}
if stat_changed {
m |= EventMask::VALUE;
}
m
};
let aux_mask = alarm_bits | EventMask::VALUE | EventMask::LOG;
let alarm_fanout: &[&str] = if alarm_bits.is_empty() {
&[]
} else {
instance.record.alarm_cycle_monitored_fields()
};
// Fields the record force-posts every cycle it recomputed them
// (C unconditional MARK + DBE_VAL_LOG), even when unchanged —
// see `Record::force_posted_fields`. Empty for most records.
let force_fields = instance.record.force_posted_fields();
// Fields re-posted with DBE_LOG only every cycle, regardless of
// change — see `Record::log_swept_fields` (scaler idle Sn sweep).
// Empty for most records.
let log_swept = instance.record.log_swept_fields();
let mut sub_updates: Vec<(String, EpicsValue, EventMask)> = Vec::new();
for (field, subs) in &instance.subscribers {
if !subs.is_empty()
&& field != deadband_field
&& field != "SEVR"
&& field != "STAT"
&& field != "AMSG"
&& field != "UDF"
{
if let Some(val) = instance.resolve_field(field) {
let changed = match instance.last_posted.get(field) {
Some(prev) => prev != &val,
None => true,
};
if changed {
sub_updates.push((field.clone(), val, aux_mask));
} else if force_fields.contains(&field.as_str()) {
// C `monitor()` posts a re-marked field with
// `monitor_mask | DBE_VAL_LOG` even when unchanged.
sub_updates.push((field.clone(), val, aux_mask));
} else if alarm_fanout.contains(&field.as_str()) {
sub_updates.push((field.clone(), val, alarm_bits));
} else if log_swept.contains(&field.as_str()) {
// C scalerRecord.c:770-787 `monitor()`: every idle
// process re-posts each S1..Snch with a literal
// DBE_LOG regardless of change. A changed field is
// already delivered above with DBE_VALUE|DBE_LOG
// (covering the LOG subscriber), so only the unchanged
// sweep lands here — no double post.
sub_updates.push((field.clone(), val, EventMask::LOG));
}
}
}
}
if !sub_updates.is_empty() {
for (field, val, _) in &sub_updates {
instance.last_posted.insert(field.clone(), val.clone());
}
changed_fields.extend(sub_updates);
}
let cycle_mask = changed_fields
.iter()
.fold(EventMask::NONE, |m, (_, _, fm)| m | *fm);
if !cycle_mask.is_empty() {
changed_fields.push((
"UDF".to_string(),
EpicsValue::Char(if instance.common.udf { 1 } else { 0 }),
cycle_mask,
));
}
let snapshot = crate::server::record::ProcessSnapshot { changed_fields };
instance.notify_from_snapshot(&snapshot);
if sevr_changed {
instance.notify_field("SEVR", EventMask::VALUE);
}
if !stat_mask.is_empty() {
instance.notify_field("STAT", stat_mask);
instance.notify_field("AMSG", stat_mask);
}
if alarm_result.acks_changed && !stat_mask.is_empty() {
instance.notify_field("ACKS", EventMask::VALUE);
}
}