Исходный код СУБД RuDB — свободной СУБД с открытым исходным кодом на базе PostgreSQL
rudb
3 days ago bd039d1e92813358c5c5a1e346b49074baf513f2
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
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
/*-------------------------------------------------------------------------
 * cfs_shmem.c
 *    Compressed File Store (CFS) - shared-memory map cache, statistics
 *    and synchronisation.
 *
 * Implements the partitioned shared-memory page-map cache, per-relation
 * statistics and the cached read/write helpers declared in cfs_shmem.h.
 *
 * Locking discipline:
 *
 *   * The map cache and relation metadata share one set of partition locks
 *     (cfs_map_locks); statistics has its own (cfs_stats_locks).
 *   * Lookups take LW_SHARED; insertions / updates take LW_EXCLUSIVE.
 *   * Compression, decompression, FileRead/FileWrite, fsync and XLogFlush
 *     are never performed while a CFS partition lock is held - only the
 *     (cheap) CfsMapEntry copy / slot update happens inside the lock.
 *   * The only nested lock ordering that may occur is map-lock -> stats-lock
 *     (e.g. while accounting dead bytes); the reverse never happens, so the
 *     ordering is deadlock-free.
 *
 * Copyright (c) 2026, Kirillov Vyacheslav by AI, QDB Development Group
 *
 * IDENTIFICATION
 *    src/backend/storage/cfs/cfs_shmem.c
 *
 *-------------------------------------------------------------------------
 */
#include "postgres.h"
 
#include "access/twophase_rmgr.h"
#include "access/xact.h"
#include "catalog/storage.h"
#include "common/hashfn.h"
#include "common/relpath.h"
#include "miscadmin.h"
#include "storage/aio.h"
#include "storage/cfs/cfs_cfp.h"
#include "storage/cfs/cfs_format.h"
#include "storage/cfs/cfs_guc.h"
#include "storage/cfs/cfs_journal.h"
#include "storage/cfs/cfs_map_file.h"
#include "storage/cfs/cfs_recovery.h"
#include "storage/cfs/cfs_rel.h"
#include "storage/cfs/cfs_shmem.h"
#include "storage/cfs/cfs_shmem_internal.h"
#include "storage/cfs/cfs_smgr.h"
#include "storage/cfs/cfs_state.h"
#include "storage/cfs/cfs_storage.h"
#include "storage/fd.h"
#include "storage/lwlock.h"
#include "storage/proc.h"
#include "storage/procarray.h"
#include "storage/shmem.h"
#include "utils/hsearch.h"
#include "utils/memutils.h"
#include "utils/palloc.h"
#include "utils/timestamp.h"
 
/* Mask for selecting a partition from a hash (NUM_PARTITIONS is a power of 2). */
 
/*
 * Retry interval for the dead-pin reaper after a sweep that reaped
 * nothing: a fresh dead owner can only appear when some backend dies, so
 * a short TTL delays the rescue but never loses it.
 */
#define CFS_PIN_REAP_EMPTY_RETRY_USECS (10 * USECS_PER_SEC)
 
/* ================================================================
 * Shared-memory pointers (initialised by CfsShmemInit)
 * ================================================================ */
 
CfsShmemControl *cfs_control = NULL;
static LWLockPadded *cfs_map_locks = NULL;
 
/*
 * Sidecar-open guard implementation (QDB-1514), installed into the state
 * judge by CfsShmemInit(); defined near the compaction mark helpers below.
 */
static bool cfs_open_guard_acquire_impl(RelFileLocatorBackend rlocator,
                                        ForkNumber forknum);
static void cfs_open_guard_release_impl(RelFileLocatorBackend rlocator,
                                        ForkNumber forknum, bool after_error);
 
/*
 * Relation-metadata slots, stored as a flat array of NUM_PARTITIONS *
 * cfs_map_cache_rels_per_partition entries (the per-partition count is a
 * PGC_POSTMASTER GUC, so the second dimension is not a compile-time
 * constant).  Use cfs_rel_meta_slot() to index it.
 */
static CfsRelMetaSlot *cfs_rel_meta = NULL;
 
/* Map-domain per-partition access clock (see cfs_shmem_internal.h). */
uint64     *cfs_map_clocks = NULL;
 
/*
 * Per-partition bucket heads for the metadata hash chains (QDB-1516 Д2):
 * a flat array of NUM_PARTITIONS * cfs_map_cache_rels_per_partition
 * entries, -1 = empty head / end of chain.  Use cfs_meta_head() to index.
 */
static int32 *cfs_map_bucket_heads = NULL;
 
/* cfs_stats_locks / cfs_stats_slots moved to cfs_stats.c. */
 
/* Background compaction worker control block + its dedicated lock. */
static CfsBgControl *cfs_bg_control = NULL;
static LWLockPadded *cfs_bg_lock = NULL;
 
/*
 * Shared block-map segment pool.  NULL (and cfs_map_seg_count == 0) when
 * cfs_map_memory is 0: the pool is simply absent and every consumer must
 * fall back to the authoritative miss path.
 *
 * Lock ordering invariant (deadlock-free by construction, the buffer
 * mapping model):
 *
 *      append_lock -> index lock -> mapping partition lock -> segment lock
 *
 * A mapping (hash-table) partition lock may be held together with a segment
 * lock — acquire reserves the descriptor and inserts the mapping under both
 * — but only in that order: partition lock first, segment lock second,
 * never the reverse.  The hash lookup/insert runs under the partition lock,
 * and the segment key is re-validated under the segment lock to catch a
 * concurrent eviction.  The append lock precedes all three on every writing
 * path, and nothing takes the append lock while holding a mapping or
 * segment lock.  Compression, decompression, disk I/O and journal replay
 * are never performed while a segment lock is held: under it only
 * single-entry copies/stores happen (segment loads read .cfsmap into a
 * private buffer first, and the journal incarnation is sampled before the
 * locks for the same reason).
 *
 * Pinning is relation-level for the metadata slot: an open CFS handle
 * pins the slot (refcount), which keeps the slot's identity, nblocks
 * and append lock alive — but it deliberately does NOT protect the
 * slot's resident pool segments from eviction.  A per-segment pin (the
 * bufmgr BufferDesc.refcount model) would remove the reservation table
 * and part of the epoch/ghost logic, but the working set does not need
 * it: usage_count is bumped by every lookup and store, so the segments
 * under an active scan stay hot and survive the clock sweep, while cold
 * segments — even of an open relation — are evictable.  Skipping the
 * segments of open relations instead (the earlier policy) let a single
 * relation larger than the pool exhaust it forever: no victim could be
 * found, evictions stayed zero and every further read paid the
 * authoritative fallback on every scan.
 */
static CfsMapSegmentDesc *cfs_map_seg_descs = NULL;
static CfsMapEntry (*cfs_map_seg_data)[CFS_MAP_SEGMENT_BLOCKS] = NULL;
static LWLockPadded *cfs_map_seg_locks = NULL;
static int  cfs_map_seg_count = 0;
 
/*
 * Process-local clock-sweep hand.  A plain uint32 is enough: a torn advance
 * only re-scans, never misassigns (the bufmgr nextVictimBuffer model).
 */
static uint32 cfs_map_seg_hand = 0;
 
/*
 * Process-local memo of a failed pool attempt: while the shared churn
 * counter stays where the failure left it, nothing has been published,
 * evicted or unpinned, so the pool cannot have become usable again.  The
 * read path then skips the sweep entirely and takes the authoritative
 * scratch fallback, instead of paying a locked clock-sweep revolution per
 * page while every segment stays reserved or hot (the only states that
 * can keep a full pool without a victim now that pinned relations no
 * longer protect their segments).
 */
static bool cfs_map_pool_exhausted = false;
static uint64 cfs_map_pool_exhausted_churn = 0;
 
/*
 * The (key -> segment id) lookup table: a shared partitioned dynahash,
 * guarded by the same cfs_map_locks partition array as the map cache
 * (the vanilla SharedBufHash pattern; one tranche serves both, the
 * critical sections never overlap).
 */
static HTAB *cfs_map_seg_hash = NULL;
 
/* (key -> reserved descriptor) for in-flight acquisitions. */
static HTAB *cfs_map_seg_live = NULL;
 
/*
 * Per-relation index over the pool: (relation, fork) -> list of segment
 * descriptors.  Publishing a segment links it here, eviction unlinks it,
 * and cfs_shared_map_invalidate_relation() walks only the segments of the
 * requested relation instead of scanning the whole pool (the pool may hold
 * more than a million descriptors at the documented sizing limit).
 *
 * Lock order: relation index -> mapping partition -> segment.  The index
 * lock is only ever held together with a segment lock (to sample or move a
 * node); eviction never takes it while the mapping lock is held.
 */
typedef struct CfsMapSegmentRelKey
{
    RelFileLocatorBackend rlocator;
    ForkNumber  forknum;
} CfsMapSegmentRelKey;
 
typedef struct CfsMapSegmentRelEnt
{
    CfsMapSegmentRelKey key;
    dlist_head  head;
    int         count;
} CfsMapSegmentRelEnt;
 
static HTAB *cfs_map_rel_index = NULL;
static LWLockPadded *cfs_map_rel_index_lock = NULL;
 
/*
 * Pin-owner registry for metadata slots.  A hard process
 * death (kill -9, FATAL) skips every unpin this backend owed, so a slot's
 * refcount would stay elevated forever and a series of such deaths could
 * exhaust a partition.  Every pin is therefore also recorded here under
 * the pinning process's (procno, pid, epoch) identity; when a partition
 * runs out of reclaimable slots, dead owners are reaped exactly like
 * dead segment reservations.  Guarded by the same cfs_map_locks
 * partition as the slot itself, which cfs_map_pin_hash() makes safe for
 * the shared dynahash: keys in one bucket always share that lock.
 */
typedef struct CfsMapPinKey
{
    RelFileLocatorBackend rlocator;
    ForkNumber  forknum;
    int         procno;
}           CfsMapPinKey;
 
typedef struct CfsMapPinOwner
{
    CfsMapPinKey key;
    int         owner_pid;
    uint64      owner_epoch;
    int         pin_count;
}           CfsMapPinOwner;
 
static HTAB *cfs_map_pin_live = NULL;
 
/* One-shot log flag for a full pin-owner registry (see cfs_map_pin_track). */
static bool cfs_pin_registry_overflow_logged = false;
 
/*
 * Per-process epochs used by segment reservations.  A ProcNumber is
 * recycled by a new backend, so (pid, ProcNumber) alone could look alive
 * after PID reuse; the epoch in the process's slot changes on first CFS
 * use by the new owner and makes the old reservation provably stale.
 */
static pg_atomic_uint64 *cfs_proc_epochs = NULL;
static int  cfs_proc_epochs_count = 0;
static uint64 cfs_owner_epoch = 0;
 
/*
 * Test-only switch for the I4 merge race, consumed by
 * cfs_shared_map_ensure().  Compiled only in assert-enabled builds.
 */
#ifdef USE_ASSERT_CHECKING
static bool cfs_test_merge_race_pending = false;
#endif
 
/*
 * Test-only switch (always compiled; see cfs_shmem.h): forces victim
 * selection to report an exhausted pool so the authoritative fallback
 * stays deterministically coverable in every build.
 */
bool        cfs_test_pool_block_victim = false;
 
/* Shared dynahash of the per-relation compaction history. */
static HTAB *cfs_bg_history_hash = NULL;
 
/* One-time-per-process overflow notice for the history hash. */
static bool cfs_bg_history_overflow_logged = false;
 
/*
 * Read scratch arena (QDB-1513 P4-2).  Slot descriptors, span buffers
 * and the control block live in one contiguous pair of arrays plus a
 * small header; see cfs_shmem.h for the state machine.  All pointers
 * stay NULL with cfs_read_scratch_slots_count == 0 when the GUCs buy no
 * slot, and every consumer then takes the inline read path.
 */
static CfsReadScratchSlot *cfs_read_scratch_slots = NULL;
static int  cfs_read_scratch_slots_count = 0;
static Size cfs_read_scratch_span_bytes = 0;
static char *cfs_read_scratch_spans = NULL;
 
typedef struct CfsReadScratchCtl
{
    pg_atomic_uint32 cursor;    /* round-robin acquisition hint         */
    pg_atomic_uint64 exhaustions;   /* acquisitions that found no free
                                     * slot and degraded to inline      */
} CfsReadScratchCtl;
 
static CfsReadScratchCtl *cfs_read_scratch_ctl = NULL;
 
/* ================================================================
 * Internal helpers
 * ================================================================ */
 
/* Index the flat relation-metadata array by (partition, slot). */
static inline CfsRelMetaSlot *
cfs_rel_meta_slot(int part, int i)
{
    return &cfs_rel_meta[part * cfs_map_cache_rels_per_partition + i];
}
 
/*
 * Forward declaration: cfs_meta_find is used by cfs_append_lock_find_slot
 * (append serialization section) and defined in the relation-metadata
 * section.  cfs_stats_get_or_create moved to cfs_stats.c.
 */
static CfsRelMetaSlot *cfs_meta_find(uint32 rel_hash,
                                     RelFileLocatorBackend rlocator,
                                     ForkNumber forknum);
 
/*
 * Hash of a pin-owner registry key.  The lock-manager pattern (see
 * LockTagHashCode / LockHashPartitionLock): the partition lock a caller
 * holds while touching the registry is cfs_map_locks[rel part], and any
 * two keys dynahash places in one bucket must always share that lock.
 * Keep tag_hash's bits but force the low CFS_PART_MASK bits to the
 * relation's metadata partition - nbuckets is never below the partition
 * count (dynahash.c), so the bucket address bits always include these.
 * Every registry access must go through this function - never a plain
 * hash_search(), which computes a different value for the same key and
 * would miss the record.
 */
static inline uint32
cfs_map_pin_hash(const CfsMapPinKey * key, uint32 rel_hash)
{
    uint32      h;
 
    h = (tag_hash(key, sizeof(*key)) & ~CFS_PART_MASK) |
        (rel_hash & CFS_PART_MASK);
 
    /*
     * A zero hashvalue is not special to dynahash, but 0 is kept out of the
     * table for symmetry with cfs_map_segment_hash().  The fixup bit is above
     * every bucket address bit, so the forced partition bits survive it.
     */
    return h ? h : 0x80000000;
}
 
/*
 * Fill *key and return the hash value for one registry access.  track,
 * untrack and the test hook must all build the key and the hash through
 * this single helper: drifting copies would look in different buckets and
 * silently miss each other's records.
 */
static inline uint32
cfs_map_pin_key_hash(RelFileLocatorBackend rlocator, ForkNumber forknum,
                     int procno, CfsMapPinKey * key, uint32 rel_hash)
{
    key->rlocator = rlocator;
    key->forknum = forknum;
    key->procno = procno;
    return cfs_map_pin_hash(key, rel_hash);
}
 
/* ================================================================
 * Shared-memory lifecycle
 * ================================================================ */
 
/*
 * Number of block-map segments the cfs_map_memory GUC buys.  One segment
 * is CFS_MAP_SEGMENT_BLOCKS entries (768 KiB today).  1 MB already covers
 * one segment, so any positive GUC yields at least one segment.
 */
int
cfs_map_pool_segments(void)
{
    uint64      seg_bytes = (uint64) CFS_MAP_SEGMENT_BLOCKS * sizeof(CfsMapEntry);
    uint64      nsegs;
 
    if (cfs_map_memory <= 0)
        return 0;
 
    nsegs = ((uint64) cfs_map_memory * 1024 * 1024) / seg_bytes;
    if (nsegs > INT_MAX)
        nsegs = INT_MAX;
 
    return (int) nsegs;
}
 
/*
 * Capacity of the pin-owner registry: the same relation budget the
 * metadata-slot pool offers (one row per pinned relation, fork and
 * process), so the registry cannot run out before the slots it protects.
 */
static int
cfs_map_pin_registry_size(void)
{
    return CFS_MAP_CACHE_NUM_PARTITIONS * cfs_map_cache_rels_per_partition;
}
 
bool
cfs_map_memory_effective(void)
{
    return cfs_map_pool_segments() > 0;
}
 
/*
 * Read scratch arena sizing (QDB-1513 P4-2).
 *
 * The slot budget covers one in-flight offloaded read per AIO handle the
 * backend may hold, doubled so completed-but-not-yet-reclaimed IOs never
 * starve new submissions (the handles themselves allow the same overlap).
 * The cfs_read_scratch_mb GUC caps the total arena memory; whichever
 * bound is smaller wins, and a budget below one slot disables the arena
 * entirely (0 included) — reads then stay on the inline path.
 */
int
cfs_read_scratch_slot_count(void)
{
    uint64      slot_bytes;
    uint64      by_concurrency;
    uint64      by_budget;
    uint64      nslots;
 
    if (cfs_read_scratch_mb <= 0 || io_max_concurrency <= 0)
        return 0;
 
    slot_bytes = sizeof(CfsReadScratchSlot) + cfs_read_span_capacity();
 
    by_concurrency = 2 * (uint64) io_max_concurrency;
    by_budget = ((uint64) cfs_read_scratch_mb * 1024 * 1024) / slot_bytes;
 
    nslots = Min(by_concurrency, by_budget);
    if (nslots > INT_MAX)
        nslots = INT_MAX;
 
    return (int) nslots;
}
 
bool
cfs_read_scratch_effective(void)
{
    /*
     * The slot count depends only on postmaster-time GUCs, so the value
     * computed once in the shmem startup is authoritative for the whole
     * cluster lifetime; avoid re-doing the budget arithmetic on every
     * readv gate check.
     */
    return cfs_read_scratch_slots_count > 0;
}
 
Size
cfs_read_span_capacity(void)
{
    /*
     * No IO carries more than io_max_combine_limit blocks, and no valid
     * record is longer than a stored-raw page plus its header
     * (CFS_RECORD_SIZE aligned; the read path rejects a larger
     * compressed_size as corruption), so the product bounds every
     * offloadable span.  Degradation to the inline path is therefore
     * driven by arena exhaustion and span contiguity, never by capacity.
     */
    return (Size) io_max_combine_limit * CFS_RECORD_SIZE(CFS_BLCKSZ);
}
 
/*
 * cfs_read_scratch_acquire — claim a slot with a single CAS and reset its
 * bookkeeping.  The round-robin hint spreads the search start so that
 * concurrent backends do not all hammer slot 0; a full failed sweep
 * counts one exhaustion and returns NULL — the caller must degrade to
 * the inline path, never wait.
 */
CfsReadScratchSlot *
cfs_read_scratch_acquire(void)
{
    int         nslots = cfs_read_scratch_slots_count;
    uint32      hint;
 
    if (nslots <= 0)
        return NULL;
 
    hint = pg_atomic_fetch_add_u32(&cfs_read_scratch_ctl->cursor, 1);
 
    for (int k = 0; k < nslots; k++)
    {
        int         i = (int) ((hint + k) % (uint32) nslots);
        CfsReadScratchSlot *slot = &cfs_read_scratch_slots[i];
        uint32      expected = CFS_READ_SCRATCH_FREE;
 
        if (pg_atomic_compare_exchange_u32(&slot->state, &expected,
                                           CFS_READ_SCRATCH_BUILDING))
        {
            slot->owner_procno = MyProcNumber;
            slot->plan_len = 0;
            slot->span_len = 0;
            return slot;
        }
    }
 
    pg_atomic_fetch_add_u64(&cfs_read_scratch_ctl->exhaustions, 1);
    return NULL;
}
 
void
cfs_read_scratch_publish(CfsReadScratchSlot *slot)
{
    Assert(pg_atomic_read_u32(&slot->state) == CFS_READ_SCRATCH_BUILDING);
    Assert(slot->plan_len <= CFS_READ_PLAN_MAX);
 
    /*
     * The plan and the span bookkeeping must be visible before the state
     * transition: once the executor observes INFLIGHT it is entitled to
     * read both without further synchronisation of its own with this
     * backend.
     */
    pg_write_barrier();
    pg_atomic_write_u32(&slot->state, CFS_READ_SCRATCH_INFLIGHT);
}
 
void
cfs_read_scratch_release(CfsReadScratchSlot *slot)
{
    Assert(pg_atomic_read_u32(&slot->state) != CFS_READ_SCRATCH_FREE);
 
    /*
     * Order the diagnostics reset before the FREE transition so the next
     * acquirer never observes a stale owner once the slot looks free.
     */
    pg_write_barrier();
    slot->owner_procno = INVALID_PROC_NUMBER;
    pg_atomic_write_u32(&slot->state, CFS_READ_SCRATCH_FREE);
}
 
char *
cfs_read_scratch_span(const CfsReadScratchSlot *slot)
{
    int         idx = slot - cfs_read_scratch_slots;
 
    Assert(idx >= 0 && idx < cfs_read_scratch_slots_count);
    return cfs_read_scratch_spans + (Size) idx * cfs_read_scratch_span_bytes;
}
 
uint32
cfs_read_scratch_slot_index(const CfsReadScratchSlot *slot)
{
    int         idx = slot - cfs_read_scratch_slots;
 
    Assert(idx >= 0 && idx < cfs_read_scratch_slots_count);
    return (uint32) idx;
}
 
CfsReadScratchSlot *
cfs_read_scratch_slot(uint32 slot_id)
{
    Assert(slot_id < (uint32) cfs_read_scratch_slots_count);
    return &cfs_read_scratch_slots[slot_id];
}
 
uint64
cfs_read_scratch_exhaustions(void)
{
    if (cfs_read_scratch_ctl == NULL)
        return 0;
    return pg_atomic_read_u64(&cfs_read_scratch_ctl->exhaustions);
}
 
Size
CfsShmemSize(void)
{
    Size        size = 0;
 
    size = add_size(size, sizeof(CfsShmemControl));
    size = add_size(size, mul_size(sizeof(LWLockPadded),
                                   CFS_MAP_CACHE_NUM_PARTITIONS));
    size = add_size(size, mul_size(sizeof(CfsRelMetaSlot),
                                   mul_size(CFS_MAP_CACHE_NUM_PARTITIONS,
                                            cfs_map_cache_rels_per_partition)));
    size = add_size(size, mul_size(sizeof(LWLockPadded),
                                   CFS_MAP_CACHE_NUM_PARTITIONS));
    size = add_size(size, mul_size(sizeof(CfsRelationStats),
                                   mul_size(CFS_MAP_CACHE_NUM_PARTITIONS,
                                            cfs_stats_slots_per_partition)));
 
    /*
     * Per-partition access clocks (QDB-1516 Д1), one per domain.  Each
     * array is cacheline-padded so it shares no cache line with the lock
     * arrays or with the other domain's clocks.
     */
    size = add_size(size, CACHELINEALIGN((Size) CFS_MAP_CACHE_NUM_PARTITIONS *
                                         sizeof(uint64)));
    size = add_size(size, CACHELINEALIGN((Size) CFS_MAP_CACHE_NUM_PARTITIONS *
                                         sizeof(pg_atomic_uint64)));
 
    /*
     * Per-partition hash-chain bucket heads (QDB-1516 Д2), one entry per
     * slot of each domain's table.
     */
    size = add_size(size, mul_size(sizeof(int32),
                                  mul_size(CFS_MAP_CACHE_NUM_PARTITIONS,
                                           cfs_map_cache_rels_per_partition)));
    size = add_size(size, mul_size(sizeof(int32),
                                  mul_size(CFS_MAP_CACHE_NUM_PARTITIONS,
                                           cfs_stats_slots_per_partition)));
    size = add_size(size, sizeof(CfsBgControl));
    size = add_size(size, sizeof(LWLockPadded));    /* bgworker control lock */
    size = add_size(size, hash_estimate_size(CFS_BG_HISTORY_MAX,
                                             sizeof(CfsBgHistoryEntry)));
 
    /* Block-map segment pool (descriptors + data + one lock per segment). */
    {
        int         nsegs = cfs_map_pool_segments();
 
        if (nsegs > 0)
        {
            size = add_size(size, mul_size(sizeof(CfsMapSegmentDesc), nsegs));
            size = add_size(size, mul_size((Size) CFS_MAP_SEGMENT_BLOCKS *
                                           sizeof(CfsMapEntry), nsegs));
            size = add_size(size, mul_size(sizeof(LWLockPadded), nsegs));
            size = add_size(size, hash_estimate_size(nsegs,
                                                     sizeof(CfsMapSegmentHashEnt)));
            size = add_size(size, hash_estimate_size(nsegs,
                                                     sizeof(CfsMapSegmentReservation)));
            size = add_size(size,
                            mul_size(sizeof(pg_atomic_uint64),
                                     MaxBackends + NUM_AUXILIARY_PROCS));
            /* Per-relation segment index and its single lock. */
            size = add_size(size, sizeof(LWLockPadded));
            size = add_size(size, hash_estimate_size(nsegs,
                                                     sizeof(CfsMapSegmentRelEnt)));
        }
    }
 
    /*
     * Pin-owner registry for metadata slots: needed for every pool size
     * (cfs_map_memory = 0 included), one row per (relation, fork, process)
     * pin owner.
     */
    size = add_size(size, hash_estimate_size(cfs_map_pin_registry_size(),
                                             sizeof(CfsMapPinOwner)));
 
    /* Read scratch arena (QDB-1513 P4-2): control, descriptors, spans. */
    {
        int         nscratch = cfs_read_scratch_slot_count();
 
        if (nscratch > 0)
        {
            size = add_size(size, sizeof(CfsReadScratchCtl));
            size = add_size(size,
                            mul_size(sizeof(CfsReadScratchSlot), nscratch));
            size = add_size(size,
                            mul_size(cfs_read_span_capacity(), nscratch));
        }
    }
    return size;
}
 
void
CfsShmemInit(void)
{
    bool        found;
    int         i;
 
    /* Control block. */
    cfs_control = ShmemInitStruct("CFS Control",
                                  sizeof(CfsShmemControl), &found);
    if (!found)
    {
        /*
         * Postmaster: assign dynamic tranche ids for our lock families. The
         * counter lives just before MainLWLockArray and is already
         * initialised by CreateLWLocks(), which runs earlier in this path.
         */
        cfs_control->map_tranche_id = LWLockNewTrancheId("cfs_map");
        cfs_control->stats_tranche_id = LWLockNewTrancheId("cfs_stats");
        cfs_control->append_tranche_id = LWLockNewTrancheId("cfs_append");
        cfs_control->bg_tranche_id = LWLockNewTrancheId("cfs_bg");
        cfs_control->map_seg_tranche_id = LWLockNewTrancheId("cfs_map_seg");
 
        /*
         * Freeze the statistics slot count (the cfs_stats_slots_per_partition
         * GUC) for the attach-time consistency check in
         * cfs_stats_shmem_init(): EXEC_BACKEND children re-parse their own
         * configuration, and a different value would index the shared arrays
         * out of their layout.
         */
        cfs_control->stats_slots_per_part = cfs_stats_slots_per_partition;
 
        pg_atomic_init_u64(&cfs_control->evictions, 0);
        pg_atomic_init_u64(&cfs_control->map_segment_loads, 0);
        pg_atomic_init_u64(&cfs_control->map_segment_evictions, 0);
        pg_atomic_init_u64(&cfs_control->map_segments_in_use, 0);
        pg_atomic_init_u64(&cfs_control->map_fallback_reads, 0);
        pg_atomic_init_u64(&cfs_control->map_pool_churn, 0);
        pg_atomic_init_u64(&cfs_control->map_pin_reap_empty_at, 0);
        pg_atomic_init_u64(&cfs_control->owner_epoch_next, 0);
        pg_atomic_init_u64(&cfs_control->full_map_opens, 0);
    }
 
    /*
     * [PG19 adaptation] Tranche names are registered for wait-event display
     * by LWLockNewTrancheId(name) at id assignment time above; PG19 removed
     * the separate LWLockRegisterTranche() registration pass.
     */
 
    /*
     * Publish the generation lookup to the ownership-state judge: the storage
     * layer tags freshly opened handles through the provider instead of
     * calling into this layer (the storage -> shmem edge the review cycle was
     * feeding on; see cfs_state.h).
     */
    cfs_state_set_generation_provider(cfs_map_cache_get_generation);
 
    /*
     * Publish the authoritative .cfp tail operations the same way: the
     * storage layer's append path consults and maintains the shared tail
     * through the state judge's hooks (see cfs_shmem.h for the protocol).
     */
    {
        static const CfsCfpTailOps cfp_tail_ops = {
            .tail_fetch = cfs_cfp_tail_fetch,
            .tail_begin = cfs_cfp_tail_begin,
            .tail_commit = cfs_cfp_tail_commit,
            .tail_dirty = cfs_cfp_tail_dirty,
        };
 
        cfs_state_set_cfp_tail_ops(&cfp_tail_ops);
    }
 
    /*
     * Publish the online-compaction liveness answer the same way: the open
     * path consults it to decide whether the interrupted-swap recovery may
     * run over this relation's candidate files (QDB-1514; see cfs_swap.c
     * for the invariant).
     */
    cfs_state_set_compaction_provider(cfs_map_cache_compaction_active);
 
    /*
     * Publish the sidecar-open guard the same way: the lock-free opens
     * take a shared hold of the append lock so an online compaction's swap
     * phase cannot interleave with the descriptor resolution and the
     * generation tagging (QDB-1514).
     */
    {
        static const CfsOpenGuardOps open_guard_ops = {
            .open_guard_acquire = cfs_open_guard_acquire_impl,
            .open_guard_release = cfs_open_guard_release_impl,
        };
 
        cfs_state_set_open_guard_ops(&open_guard_ops);
    }
 
    ereport(DEBUG1,
            (errmsg("CFS: shared memory initialised (map tranche=%d, stats tranche=%d, append tranche=%d)",
                    cfs_control->map_tranche_id, cfs_control->stats_tranche_id,
                    cfs_control->append_tranche_id)));
    /* Map-cache / metadata partition locks. */
    cfs_map_locks = ShmemInitStruct("CFS Map Locks",
                                    mul_size(sizeof(LWLockPadded),
                                             CFS_MAP_CACHE_NUM_PARTITIONS),
                                    &found);
    if (!found)
    {
        for (i = 0; i < CFS_MAP_CACHE_NUM_PARTITIONS; i++)
            LWLockInitialize(&cfs_map_locks[i].lock, cfs_control->map_tranche_id);
    }
 
    /*
     * Map-domain per-partition access clock (QDB-1516 Д1).  Its own
     * CACHELINEALIGN-ed allocation keeps the clock off the partition locks'
     * cache lines; the plain uint64 cells are updated only under the
     * partition lock held exclusively (see cfs_map_clock_tick).
     */
    cfs_map_clocks =
        ShmemInitStruct("CFS Map Clocks",
                        CACHELINEALIGN((Size) CFS_MAP_CACHE_NUM_PARTITIONS *
                                       sizeof(uint64)),
                        &found);
    if (!found)
        MemSet(cfs_map_clocks, 0,
               CACHELINEALIGN((Size) CFS_MAP_CACHE_NUM_PARTITIONS *
                              sizeof(uint64)));
 
    /* Relation-metadata slots (flat array, see cfs_rel_meta_slot()). */
    cfs_rel_meta = ShmemInitStruct("CFS Rel Meta",
                                   mul_size(sizeof(CfsRelMetaSlot),
                                            mul_size(CFS_MAP_CACHE_NUM_PARTITIONS,
                                                     cfs_map_cache_rels_per_partition)),
                                   &found);
    if (!found)
        MemSet(cfs_rel_meta, 0, mul_size(sizeof(CfsRelMetaSlot),
                                         mul_size(CFS_MAP_CACHE_NUM_PARTITIONS,
                                                  cfs_map_cache_rels_per_partition)));
 
    /*
     * Bucket heads of the metadata hash chains (QDB-1516 Д2): all heads
     * start empty (-1), matching the zeroed (all-free) slot array.
     */
    cfs_map_bucket_heads =
        ShmemInitStruct("CFS Map Buckets",
                        mul_size(sizeof(int32),
                                 mul_size(CFS_MAP_CACHE_NUM_PARTITIONS,
                                          cfs_map_cache_rels_per_partition)),
                        &found);
    if (!found)
        MemSet(cfs_map_bucket_heads, 0xFF,
               mul_size(sizeof(int32),
                        mul_size(CFS_MAP_CACHE_NUM_PARTITIONS,
                                 cfs_map_cache_rels_per_partition)));
 
    /* Statistics locks and slots: allocated by the stats module. */
    cfs_stats_shmem_init();
 
    /* Background compaction worker control block. */
    cfs_bg_control = ShmemInitStruct("CFS BgWorker Control",
                                     sizeof(CfsBgControl), &found);
    if (!found)
        MemSet(cfs_bg_control, 0, sizeof(CfsBgControl));
 
    cfs_bg_lock = ShmemInitStruct("CFS BgWorker Lock",
                                  sizeof(LWLockPadded), &found);
    if (!found)
        LWLockInitialize(&cfs_bg_lock->lock, cfs_control->bg_tranche_id);
 
    /*
     * Per-relation compaction history: a shared dynahash sized for
     * CFS_BG_HISTORY_MAX fixed-size entries, grown once here (the
     * lock-manager pattern: shared hashes in vanilla are created once with
     * their full capacity).  Entries expire by age, not by count.
     */
    {
        HASHCTL     ctl;
 
        MemSet(&ctl, 0, sizeof(ctl));
        ctl.keysize = sizeof(CfsBgHistoryKey);
        ctl.entrysize = sizeof(CfsBgHistoryEntry);
        cfs_bg_history_hash = ShmemInitHash("CFS BgWorker History",
                                            CFS_BG_HISTORY_MAX,
                                            &ctl,
                                            HASH_ELEM | HASH_BLOBS);
    }
 
    /*
     * Restore the persisted per-relation statistics.  This runs in the
     * postmaster before any child exists (EXEC builds attach to already
     * initialised memory with IsUnderPostmaster set and skip it).
     */
    if (!IsUnderPostmaster)
        cfs_stats_restore_statsfile();
 
    /*
     * QDB-1507 U1: consume the persistent resync marker written by a
     * clean shutdown that overtook the crash-boot sweep - the restored
     * values are still unresynced, so this boot must keep the sweep
     * armed.  Must run before StartupXLOG's crash/clean decision.
     */
    if (!IsUnderPostmaster)
        cfs_stats_boot_restore_marker();
 
    /*
     * Block-map segment pool: descriptors, data and one lock per segment.
     * Allocated only when cfs_map_memory > 0; otherwise the pointers stay
     * NULL and cfs_map_seg_count 0, and all consumers take the fallback.
     */
    cfs_map_seg_count = cfs_map_pool_segments();
 
    /*
     * Per-process epochs are needed for segment reservations (pool > 0) and
     * for metadata-slot pin reaping (always) - allocate both unconditionally.
     */
    cfs_proc_epochs_count = MaxBackends + NUM_AUXILIARY_PROCS;
    cfs_proc_epochs = ShmemInitStruct("CFS Proc Epochs",
                                      mul_size(sizeof(pg_atomic_uint64),
                                               cfs_proc_epochs_count),
                                      &found);
    if (!found)
    {
        for (i = 0; i < cfs_proc_epochs_count; i++)
            pg_atomic_init_u64(&cfs_proc_epochs[i], 0);
    }
 
    /*
     * Pin-owner registry for metadata slots.  Created for every pool size:
     * metadata slots (and their pins) exist even when the segment pool is
     * off, and the reaper must be able to return a dead process's pins then
     * too.  The lock-manager pattern: every access goes through
     * cfs_map_pin_hash() under the relation's cfs_map_locks partition.
     */
    {
        HASHCTL     pin_ctl;
 
        MemSet(&pin_ctl, 0, sizeof(pin_ctl));
        pin_ctl.keysize = sizeof(CfsMapPinKey);
        pin_ctl.entrysize = sizeof(CfsMapPinOwner);
        pin_ctl.num_partitions = CFS_MAP_CACHE_NUM_PARTITIONS;
        cfs_map_pin_live = ShmemInitHash("CFS Map Pin Live",
                                         cfs_map_pin_registry_size(),
                                         &pin_ctl,
                                         HASH_ELEM | HASH_BLOBS | HASH_PARTITION);
    }
 
    if (cfs_map_seg_count > 0)
    {
        cfs_map_seg_descs = ShmemInitStruct("CFS Map Pool Descs",
                                            mul_size(sizeof(CfsMapSegmentDesc),
                                                     cfs_map_seg_count),
                                            &found);
        if (!found)
        {
            MemSet(cfs_map_seg_descs, 0,
                   mul_size(sizeof(CfsMapSegmentDesc), cfs_map_seg_count));
            for (i = 0; i < cfs_map_seg_count; i++)
                pg_atomic_init_u32(&cfs_map_seg_descs[i].usage_count, 0);
        }
 
        cfs_map_seg_data = ShmemInitStruct("CFS Map Pool Data",
                                           mul_size((Size) CFS_MAP_SEGMENT_BLOCKS *
                                                    sizeof(CfsMapEntry),
                                                    cfs_map_seg_count),
                                           &found);
        if (!found)
            MemSet(cfs_map_seg_data, 0,
                   mul_size((Size) CFS_MAP_SEGMENT_BLOCKS *
                            sizeof(CfsMapEntry), cfs_map_seg_count));
 
        cfs_map_seg_locks = ShmemInitStruct("CFS Map Pool Locks",
                                            mul_size(sizeof(LWLockPadded),
                                                     cfs_map_seg_count),
                                            &found);
        if (!found)
        {
            for (i = 0; i < cfs_map_seg_count; i++)
                LWLockInitialize(&cfs_map_seg_locks[i].lock,
                                 cfs_control->map_seg_tranche_id);
        }
 
        /* The (key -> segment id) lookup table over the pool. */
        {
            HASHCTL     ctl;
 
            MemSet(&ctl, 0, sizeof(ctl));
            ctl.keysize = sizeof(CfsMapSegmentKey);
            ctl.entrysize = sizeof(CfsMapSegmentHashEnt);
            ctl.num_partitions = CFS_MAP_CACHE_NUM_PARTITIONS;
            cfs_map_seg_hash = ShmemInitHash("CFS Map Segment Hash",
                                             cfs_map_seg_count,
                                             &ctl,
                                             HASH_ELEM | HASH_BLOBS | HASH_PARTITION);
 
            MemSet(&ctl, 0, sizeof(ctl));
            ctl.keysize = sizeof(CfsMapSegmentKey);
            ctl.entrysize = sizeof(CfsMapSegmentReservation);
            ctl.num_partitions = CFS_MAP_CACHE_NUM_PARTITIONS;
            cfs_map_seg_live = ShmemInitHash("CFS Map Segment Live",
                                             cfs_map_seg_count,
                                             &ctl,
                                             HASH_ELEM | HASH_BLOBS | HASH_PARTITION);
        }
 
        /* Per-relation segment index: one list head per (relation, fork). */
        cfs_map_rel_index_lock = ShmemInitStruct("CFS Map Rel Index Lock",
                                                 sizeof(LWLockPadded),
                                                 &found);
        if (!found)
            LWLockInitialize(&cfs_map_rel_index_lock->lock,
                             cfs_control->map_seg_tranche_id);
 
        {
            HASHCTL     ctl;
 
            MemSet(&ctl, 0, sizeof(ctl));
            ctl.keysize = sizeof(CfsMapSegmentRelKey);
            ctl.entrysize = sizeof(CfsMapSegmentRelEnt);
            cfs_map_rel_index = ShmemInitHash("CFS Map Rel Index",
                                              cfs_map_seg_count,
                                              &ctl,
                                              HASH_ELEM | HASH_BLOBS);
        }
    }
 
    /*
     * Read scratch arena (QDB-1513 P4-2): control block, slot descriptors
     * and span buffers.  Allocated only when the GUCs buy at least one
     * slot; otherwise the pointers stay NULL, the count 0, and every read
     * takes the inline path.
     */
    cfs_read_scratch_slots_count = cfs_read_scratch_slot_count();
    if (cfs_read_scratch_slots_count > 0)
    {
        cfs_read_scratch_span_bytes = cfs_read_span_capacity();
 
        cfs_read_scratch_ctl = ShmemInitStruct("CFS Read Scratch Ctl",
                                               sizeof(CfsReadScratchCtl),
                                               &found);
        if (!found)
        {
            pg_atomic_init_u32(&cfs_read_scratch_ctl->cursor, 0);
            pg_atomic_init_u64(&cfs_read_scratch_ctl->exhaustions, 0);
        }
 
        cfs_read_scratch_slots =
            ShmemInitStruct("CFS Read Scratch Descs",
                            mul_size(sizeof(CfsReadScratchSlot),
                                     cfs_read_scratch_slots_count),
                            &found);
        if (!found)
        {
            MemSet(cfs_read_scratch_slots, 0,
                   mul_size(sizeof(CfsReadScratchSlot),
                            cfs_read_scratch_slots_count));
            for (i = 0; i < cfs_read_scratch_slots_count; i++)
                pg_atomic_init_u32(&cfs_read_scratch_slots[i].state,
                                   CFS_READ_SCRATCH_FREE);
        }
 
        cfs_read_scratch_spans =
            ShmemInitStruct("CFS Read Scratch Spans",
                            mul_size(cfs_read_scratch_span_bytes,
                                     cfs_read_scratch_slots_count),
                            &found);
        /* Raw pread destination: no initialisation needed. */
 
        ereport(DEBUG1,
                (errmsg("CFS: read scratch arena: %d slots of %zu bytes "
                        "(%d MB budget)",
                        cfs_read_scratch_slots_count,
                        (Size) sizeof(CfsReadScratchSlot) +
                        cfs_read_scratch_span_bytes,
                        cfs_read_scratch_mb)));
    }
 
    ereport(DEBUG1,
            (errmsg("CFS: block-map segment pool: %d segments (%d MB)",
                    cfs_map_seg_count, cfs_map_memory)));
}
 
/*
 * cfs_map_clock_tick — advance and return the map-domain access clock of a
 * partition (QDB-1516 Д1).  Every map-domain touch point holds
 * cfs_map_locks[part] in LW_EXCLUSIVE mode, so a plain increment is
 * race-free and the tick is strictly increasing within the partition;
 * no atomic RMW is needed on the hot path.
 */
uint64
cfs_map_clock_tick(int part)
{
    Assert(cfs_map_clocks != NULL);
    Assert(LWLockHeldByMeInMode(&cfs_map_locks[part].lock, LW_EXCLUSIVE));
    return ++cfs_map_clocks[part];
}
 
/* ================================================================
 * Shared block-map segment pool API
 * ================================================================
 */
 
/* Hash of a segment key; 0 is reserved for "free segment". */
static inline uint32
cfs_map_segment_hash(RelFileLocatorBackend rlocator, ForkNumber forknum,
                     BlockNumber first_block)
{
    CfsMapSegmentKey key;
    uint32      h;
 
    key.rlocator = rlocator;
    key.forknum = forknum;
    key.first_block = first_block;
    h = tag_hash(&key, sizeof(key));
    return (h == 0) ? 1 : h;
}
 
/* Does the descriptor still describe this key (it may have been evicted)? */
static inline bool
cfs_map_segment_valid(const CfsMapSegmentDesc *desc, uint32 hash,
                      RelFileLocatorBackend rlocator, ForkNumber forknum,
                      BlockNumber first_block)
{
    return desc->hash == hash &&
        cfs_rlbe_eq(desc->rlocator, rlocator) &&
        desc->forknum == forknum &&
        desc->first_block == first_block;
}
 
/*
 * cfs_seg_tag_matches — does a map-generation tag (a segment descriptor's
 * or the one a lookup returns) still name the sidecar-pair epoch this
 * handle works on?  This is the single definition of segment-vs-handle
 * epoch agreement: no call site compares the generation fields by hand
 * (the CFS review rules (README.md, "Review rules") reject a new one).
 * Exported (cfs_shmem.h) for the smgr bridges that resolve pool entries
 * outside this module (cfs_smgr.c).
 */
bool
cfs_seg_tag_matches(uint64 seg_generation, const CfsRelation *cfs)
{
    return seg_generation == cfs->open_generation;
}
 
/*
 * cfs_seg_matches — the cached segment still describes this key AND still
 * belongs to this handle's file-pair epoch.
 */
static inline bool
cfs_seg_matches(const CfsMapSegmentDesc *desc, uint32 hash,
                RelFileLocatorBackend rlocator, ForkNumber forknum,
                BlockNumber first_block, const CfsRelation *cfs)
{
    return cfs_map_segment_valid(desc, hash, rlocator, forknum,
                                 first_block) &&
        cfs_seg_tag_matches(desc->rel_generation, cfs);
}
 
static void cfs_map_segment_evict_one(int id, uint32 hash,
                                      BlockNumber first_block, uint64 epoch,
                                      bool unlink_rel);
static void cfs_map_segment_rel_link_locked(int id);
static void cfs_seg_unhealed_clear(CfsMapSegmentDesc *desc, uint32 off);
static bool cfs_map_segment_unhealed_at(int id, uint32 hash,
                                        RelFileLocatorBackend rlocator,
                                        ForkNumber forknum,
                                        BlockNumber first_block,
                                        BlockNumber blocknum);
static int  cfs_shared_map_sync_segment(CfsRelation *cfs,
                                        BlockNumber blocknum,
                                        char *corrupt_mask);
static bool cfs_map_segment_acquire(const CfsMapSegmentKey *key, uint32 hash,
                                    uint64 generation,
                                    int *id_out, bool *fresh_out);
static void cfs_map_segment_clear_reservation(const CfsMapSegmentKey *key,
                                              uint32 hash);
static void cfs_map_pin_track(RelFileLocatorBackend rlocator,
                              ForkNumber forknum, uint32 rel_hash);
static void cfs_map_pin_untrack(RelFileLocatorBackend rlocator,
                                ForkNumber forknum, uint32 rel_hash);
static bool cfs_map_slot_reap_dead_pins(bool force);
 
/*
 * Per-process scratch buffer for one segment's worth of .cfsmap entries
 * (768 kB), allocated lazily in TopMemoryContext and reused across loads
 * (the XLogReader model).  The callers use it strictly sequentially —
 * segment loading never nests within itself in one backend — and re-zero
 * it before each load, since the loader only overwrites the blocks the
 * snapshot covers.
 */
static CfsMapEntry *cfs_map_seg_scratch = NULL;
 
static CfsMapEntry *
cfs_map_segment_scratch(void)
{
    if (cfs_map_seg_scratch == NULL)
        cfs_map_seg_scratch = (CfsMapEntry *)
            MemoryContextAllocZero(TopMemoryContext,
                                   (Size) CFS_MAP_SEGMENT_BLOCKS *
                                   sizeof(CfsMapEntry));
    return cfs_map_seg_scratch;
}
 
/*
 * Fill the INVALID slots of a segment from a loaded .cfsmap range.  Entries
 * the segment already holds came from the journal (store) and are newer
 * than the snapshot, so they win.  The caller holds the segment lock.
 */
static void
cfs_map_segment_merge_invalid_locked(int id, const CfsMapEntry *buf)
{
    int         off;
 
    for (off = 0; off < CFS_MAP_SEGMENT_BLOCKS; off++)
    {
        if (cfs_map_seg_data[id][off].physical_offset ==
            CFS_ENTRY_INVALID_OFFSET &&
            buf[off].physical_offset != CFS_ENTRY_INVALID_OFFSET)
            cfs_map_seg_data[id][off] = buf[off];
    }
}
 
/*
 * Load the .cfsmap snapshot entries of one segment range into 'buf'
 * (pre-zeroed by the caller, so blocks the snapshot does not cover stay
 * INVALID).  A missing/empty snapshot (a young relation before its first
 * checkpoint) leaves the buffer all-INVALID: an empty snapshot is the whole
 * truth from the .cfsmap side.  A corrupt prologue raises the shared hard
 * ERROR of cfs_map_file_prologue_read() directly - the single policy point
 * for every loader.  'corrupt_mask' is mandatory (one byte per block of the
 * range) and records the rows whose entry_crc failed.  Returns -2 on an I/O
 * failure of the snapshot read; 0 otherwise.
 */
static int
cfs_map_segment_load_buf(CfsRelation *cfs, BlockNumber first_block,
                         CfsMapEntry *buf, Size seg_bytes,
                         char *corrupt_mask)
{
    uint64      nblocks;
    uint64      end_block;
    int         rc;
 
    Assert(corrupt_mask != NULL);
 
    /*
     * A checkpoint (or a compaction that did not bump the generation this
     * caller observed) may have replaced the .cfsmap inode.  Reading the
     * range through the old descriptor would mix the old snapshot with the
     * new, already truncated journal and publish an incomplete segment as
     * authoritative.  The caller holds the append lock, so the identity is
     * stable between this check and the read.
     */
    (void) cfs_reopen_if_map_swapped(cfs);
 
    rc = cfs_map_file_prologue_read(cfs, &nblocks);
    if (rc == CFS_STORAGE_ERROR)
        return -2;
    if (rc == CFS_STORAGE_NOENT)
        return 0;               /* empty snapshot */
 
    end_block = Min(first_block + CFS_MAP_SEGMENT_BLOCKS, nblocks);
    if (end_block > first_block)
    {
        /*
         * A short range means the snapshot is unreadable, not that the
         * uncovered blocks are unwritten: publishing zeroed entries would
         * silently fabricate a map.  The caller turns this into an ERROR.
         * Rows are classified by the shared range reader: a corrupt row
         * plants INVALID and is remembered in the mask so the caller's
         * journal replay can heal it; a hole stays INVALID.
         */
        rc = cfs_map_file_read_range(cfs->map_fd, first_block,
                                     end_block - first_block, buf,
                                     &corrupt_mask,
                                     CFS_MAP_SEGMENT_BLOCKS);
        if (rc != CFS_STORAGE_OK)
            return -2;
    }
    return 0;
}
 
/*
 * Merge the .cfsmap snapshot into a RESIDENT segment: load the range into a
 * private buffer (outside every lock) and fill only the INVALID slots under
 * the segment lock, then mark the snapshot part loaded.  Used by the
 * authoritative resync of cfs_shared_map_sync_segment after a journal reset
 * invalidated the segment's merge state.  Returns false when the segment
 * vanished (eviction race) — the caller treats that as "nothing more to do".
 */
static bool
cfs_map_segment_merge_snapshot(CfsRelation *cfs, int id, uint32 hash,
                               RelFileLocatorBackend rlocator,
                               ForkNumber forknum, BlockNumber first_block,
                               char *corrupt_mask)
{
    CfsMapEntry *buf;
    Size        seg_bytes = (Size) CFS_MAP_SEGMENT_BLOCKS * sizeof(CfsMapEntry);
    bool        merged = false;
 
    buf = cfs_map_segment_scratch();
    MemSet(buf, 0, seg_bytes);
    {
        int         load_rc;
 
        load_rc = cfs_map_segment_load_buf(cfs, first_block, buf,
                                           seg_bytes, corrupt_mask);
        if (load_rc == -2)
            ereport(ERROR,
                    (errcode_for_file_access(),
                     errmsg("CFS: could not read map segment from \"%s\"",
                            cfs->map_path)));
    }
 
    LWLockAcquire(&cfs_map_seg_locks[id].lock, LW_EXCLUSIVE);
    if (cfs_map_segment_valid(&cfs_map_seg_descs[id], hash, rlocator,
                              forknum, first_block))
    {
        if (!cfs_map_seg_descs[id].snapshot_loaded)
        {
            /*
             * The freshly loaded snapshot is the new authority: drop bits
             * derived from the previous residency before the caller's sync
             * re-detects the rows that are still torn.
             */
            MemSet(cfs_map_seg_descs[id].unhealed_mask, 0,
                   sizeof(cfs_map_seg_descs[id].unhealed_mask));
            cfs_map_segment_merge_invalid_locked(id, buf);
            cfs_map_seg_descs[id].snapshot_loaded = true;
            cfs_map_seg_descs[id].journal_synced = false;
            pg_atomic_fetch_add_u64(&cfs_control->map_segment_loads, 1);
        }
        merged = true;
    }
    LWLockRelease(&cfs_map_seg_locks[id].lock);
    return merged;
}
 
/*
 * Current on-disk journal incarnation of 'cfs'.  0 when the header is
 * momentarily unreadable; a segment stamped 0 never matches a real
 * incarnation (they start at 1), so its first sync resyncs once — fail
 * safe.
 */
static uint16
cfs_map_segment_journal_incarnation(CfsRelation *cfs)
{
    CfsJournalFileHeader jhdr;
 
    if (cfs_journal_read_header(cfs->jrn_fd, &jhdr))
        return jhdr.incarnation;
    return 0;
}
 
/*
 * Roll back a fresh acquire that could not load its data: drop the mapping
 * entry and leave the descriptor hash == 0 (free), so no reader can ever
 * observe a published-but-empty segment.
 */
static void
cfs_map_segment_release_reservation(const CfsMapSegmentKey *key, uint32 hash,
                                    int id)
{
    int         part = hash & CFS_PART_MASK;
    CfsMapSegmentHashEnt *ent;
 
    /*
     * Remove the mapping first, then clear 'reserved'.  The reverse order
     * exposed a ghost (hash == 0 && !reserved) to a competitor, which could
     * recreate the mapping and then have it removed by our HASH_REMOVE.
     */
    LWLockAcquire(&cfs_map_locks[part].lock, LW_EXCLUSIVE);
    ent = (CfsMapSegmentHashEnt *)
        hash_search_with_hash_value(cfs_map_seg_hash, key, hash,
                                    HASH_FIND, NULL);
    if (ent != NULL && ent->segment_id == id)
        hash_search_with_hash_value(cfs_map_seg_hash, key, hash,
                                    HASH_REMOVE, NULL);
    LWLockRelease(&cfs_map_locks[part].lock);
 
    cfs_map_segment_clear_reservation(key, hash);
 
    LWLockAcquire(&cfs_map_seg_locks[id].lock, LW_EXCLUSIVE);
    if (cfs_map_seg_descs[id].hash == 0 &&
        cfs_map_seg_descs[id].reserved)
        cfs_map_seg_descs[id].reserved = false;
    LWLockRelease(&cfs_map_seg_locks[id].lock);
}
static void cfs_map_segment_invalidate_block(RelFileLocatorBackend rlocator,
                                             ForkNumber forknum,
                                             BlockNumber blocknum);
static void cfs_map_segment_rel_link_locked(int id);
 
/*
 * Publish a segment: copy in the snapshot range (or zero it for a store
 * publication), stamp the descriptor and link it into the relation index.
 * The caller holds the index lock and the segment lock, has checked that
 * the descriptor is free (or, for the test hook, is ours), and has already
 * retired the in-flight reservation.
 *
 * 'snapshot' is the loaded .cfsmap range; NULL publishes a segment that
 * holds only journaled (store) entries and must still merge the snapshot
 * on its first read.  'journal_synced' states whether the published
 * contents already include the journal delta.  'jrn_incarnation' is the
 * value sampled by the caller before taking any pool lock; a store
 * publication passes 0 so the first sync sees a mismatching incarnation
 * and re-baselines the segment (snapshot merge + full replay).
 *
 * Having one function for all publications keeps the invariants (epoch,
 * reservation flag, index link, in-use counter) in one place: the three
 * call sites used to duplicate them with subtly different flags.
 */
static void
cfs_map_segment_publish_locked(int id, uint32 hash,
                               RelFileLocatorBackend rlocator,
                               ForkNumber forknum, BlockNumber first_block,
                               uint64 rel_generation,
                               const CfsMapEntry *snapshot,
                               bool journal_synced, uint16 jrn_incarnation)
{
    CfsMapSegmentDesc *desc = &cfs_map_seg_descs[id];
    Size        seg_bytes = (Size) CFS_MAP_SEGMENT_BLOCKS * sizeof(CfsMapEntry);
    bool        newly_used = (desc->hash == 0);
 
    if (snapshot != NULL)
        memcpy(cfs_map_seg_data[id], snapshot, seg_bytes);
    else
        MemSet(cfs_map_seg_data[id], 0, seg_bytes);
 
    desc->hash = hash;
    desc->rlocator = rlocator;
    desc->forknum = forknum;
    desc->first_block = first_block;
    desc->rel_generation = rel_generation;
    desc->snapshot_loaded = (snapshot != NULL);
    desc->journal_synced = journal_synced;
    MemSet(desc->unhealed_mask, 0, sizeof(desc->unhealed_mask));
    desc->jrn_synced_off = 0;
    desc->jrn_incarnation = jrn_incarnation;
    desc->seg_epoch++;
    desc->reserved = false;
 
    if (newly_used)
    {
        pg_atomic_write_u32(&desc->usage_count, 0);
        cfs_map_segment_rel_link_locked(id);
        pg_atomic_fetch_add_u64(&cfs_control->map_segments_in_use, 1);
        pg_atomic_fetch_add_u64(&cfs_control->map_pool_churn, 1);
    }
}
 
/*
 * Find the id of the pool segment mapped to 'key' and validate the range.
 * Takes the mapping partition lock in the requested mode, copies the id out
 * under the lock (the hash entry may be freed as soon as it is released)
 * and reports an out-of-range id as a plain miss: a mapping entry can
 * outlive its descriptor (a ghost), and an id outside the pool is never
 * usable.  The caller must still validate the descriptor under the segment
 * lock — the id may be recycled between the two steps.
 */
static int
cfs_map_segment_find(const CfsMapSegmentKey *key, uint32 hash, LWLockMode mode)
{
    CfsMapSegmentHashEnt *ent;
    int         part = hash & CFS_PART_MASK;
    int         id;
 
    LWLockAcquire(&cfs_map_locks[part].lock, mode);
    ent = (CfsMapSegmentHashEnt *)
        hash_search_with_hash_value(cfs_map_seg_hash, key, hash,
                                    HASH_FIND, NULL);
    id = (ent != NULL) ? ent->segment_id : -1;
    LWLockRelease(&cfs_map_locks[part].lock);
 
    if (id < 0 || id >= cfs_map_seg_count)
        return -1;
    return id;
}
 
/*
 * Per-process epoch for segment reservations.  The epoch is taken lazily on
 * first use and written into this process's ProcNumber slot; a recycled
 * ProcNumber gets a new value when its new owner first touches CFS.
 */
static uint64
cfs_map_owner_epoch_get(void)
{
    if (cfs_owner_epoch == 0)
    {
        cfs_owner_epoch =
            pg_atomic_add_fetch_u64(&cfs_control->owner_epoch_next, 1);
        if (cfs_proc_epochs != NULL && MyProcNumber >= 0 &&
            MyProcNumber < cfs_proc_epochs_count)
            pg_atomic_write_u64(&cfs_proc_epochs[MyProcNumber],
                                cfs_owner_epoch);
    }
    return cfs_owner_epoch;
}
 
/* Is (procno, pid, epoch) still the same live process? */
static bool
cfs_map_owner_alive(int procno, int pid, uint64 epoch)
{
    PGPROC     *proc;
 
    if (cfs_proc_epochs == NULL ||
        procno < 0 ||
        procno >= cfs_proc_epochs_count)
        return false;
 
    proc = ProcNumberGetProc(procno);
    if (proc == NULL || proc->pid != pid)
        return false;
 
    return pg_atomic_read_u64(&cfs_proc_epochs[procno]) == epoch;
}
 
/* Is the owner recorded in a reservation still the same live process? */
static bool
cfs_map_reservation_owner_alive(const CfsMapSegmentReservation *live)
{
    return cfs_map_owner_alive(live->owner_procno, live->owner_pid,
                               live->owner_epoch);
}
 
/*
 * Classify the in-flight reservation for this key/id pair: missing, live
 * or dead.  A missing entry means either no reservation at all or the short
 * window between clear_reservation() and publication; both must not be
 * reaped.
 */
#define CFS_RESERVATION_MISSING 0
#define CFS_RESERVATION_LIVE    1
#define CFS_RESERVATION_DEAD    2
 
static int
cfs_map_segment_reservation_state(const CfsMapSegmentKey *key, int id)
{
    int         part = cfs_map_segment_hash(key->rlocator, key->forknum,
                                            key->first_block) & CFS_PART_MASK;
    CfsMapSegmentReservation *live;
    int         state;
 
    if (cfs_map_seg_live == NULL)
        return CFS_RESERVATION_MISSING;
 
    LWLockAcquire(&cfs_map_locks[part].lock, LW_SHARED);
    live = (CfsMapSegmentReservation *)
        hash_search(cfs_map_seg_live, key, HASH_FIND, NULL);
    if (live == NULL || live->segment_id != id)
        state = CFS_RESERVATION_MISSING;
    else if (cfs_map_reservation_owner_alive(live))
        state = CFS_RESERVATION_LIVE;
    else
        state = CFS_RESERVATION_DEAD;
    LWLockRelease(&cfs_map_locks[part].lock);
 
    return state;
}
 
/*
 * Reap a reservation whose owner died before publishing.  The descriptor
 * still has 'reserved' set and a ghost mapping may exist, so reuse the
 * normal rollback path.  A live owner is never touched.
 */
static bool
cfs_map_segment_reap_if_dead(const CfsMapSegmentKey *key, uint32 hash, int id)
{
    if (cfs_map_segment_reservation_state(key, id) != CFS_RESERVATION_DEAD)
        return false;
 
    cfs_map_segment_release_reservation(key, hash, id);
    return true;
}
 
/* Drop an in-flight reservation after publication or on failure. */
static void
cfs_map_segment_clear_reservation(const CfsMapSegmentKey *key, uint32 hash)
{
    int         part = hash & CFS_PART_MASK;
 
    if (cfs_map_seg_live == NULL)
        return;
 
    LWLockAcquire(&cfs_map_locks[part].lock, LW_EXCLUSIVE);
    hash_search_with_hash_value(cfs_map_seg_live, key, hash,
                                HASH_REMOVE, NULL);
    LWLockRelease(&cfs_map_locks[part].lock);
}
 
/*
 * Bump the clock-sweep usage counter with saturation.  Called on a lookup
 * hit and on a successful store, while the segment lock is held.
 */
static inline void
cfs_map_segment_bump_usage(CfsMapSegmentDesc *desc)
{
    uint32      old;
 
    old = pg_atomic_fetch_add_u32(&desc->usage_count, 1);
    if (old >= CFS_MAP_SEG_USAGE_MAX)
        pg_atomic_write_u32(&desc->usage_count, CFS_MAP_SEG_USAGE_MAX);
}
 
/*
 * Decrement the clock-sweep usage counter only when it is positive.  A plain
 * fetch_sub after a shared-lock read of 1 lets two sweepers underflow the
 * counter to UINT32_MAX, which makes the segment effectively unevictable;
 * the CAS loop is the bufmgr-style "decrement if nonzero" rule.
 */
static bool
cfs_map_segment_dec_usage(CfsMapSegmentDesc *desc)
{
    for (;;)
    {
        uint32      old = pg_atomic_read_u32(&desc->usage_count);
 
        if (old == 0)
            return false;
        if (pg_atomic_compare_exchange_u32(&desc->usage_count, &old, old - 1))
            return true;
    }
}
 
/*
 * Clock-sweep victim selection, modelled on bufmgr's ClockSweepTick:
 * advance the shared hand one segment per tick, decrement a nonzero usage
 * count and move on, and choose the first segment whose count reached zero.
 * A free segment wins immediately.  Reserved segments and segments whose
 * relation is still pinned are skipped.  The key and epoch are sampled under
 * the segment lock and re-validated by cfs_map_segment_evict_one(), so a
 * recycle of the same id/key cannot be evicted by mistake.
 *
 * Returns the victim id (or -1 when a full sweep found no candidate);
 * out_free tells the caller whether it must evict or may insert directly.
 */
static int
cfs_map_segment_select_victim(uint32 *out_hash, BlockNumber *out_first,
                              uint64 *out_epoch, bool *out_free)
{
    int         ticks;
    int         max_ticks = cfs_map_seg_count * (CFS_MAP_SEG_USAGE_MAX + 1);
 
    int         since_progress = 0;
 
    /* Test-only: simulate a pool with no allocatable victim. */
    if (cfs_test_pool_block_victim)
        return -1;
 
    for (ticks = 0; ticks < max_ticks; ticks++)
    {
        uint32      tick = cfs_map_seg_hand++;
        int         id = tick % cfs_map_seg_count;
        CfsMapSegmentDesc *desc = &cfs_map_seg_descs[id];
        uint32      hash;
        uint32      usage;
        bool        reserved;
        RelFileLocatorBackend rlocator;
        ForkNumber  forknum;
        BlockNumber first_block;
        uint64      epoch;
        CfsMapSegmentKey key;
 
        LWLockAcquire(&cfs_map_seg_locks[id].lock, LW_SHARED);
        hash = desc->hash;
        reserved = desc->reserved;
        rlocator = desc->rlocator;
        forknum = desc->forknum;
        first_block = desc->first_block;
        epoch = desc->seg_epoch;
        usage = pg_atomic_read_u32(&desc->usage_count);
        LWLockRelease(&cfs_map_seg_locks[id].lock);
 
        key.rlocator = rlocator;
        key.forknum = forknum;
        key.first_block = first_block;
 
        /*
         * A skipped tick is no progress: a full revolution without a single
         * usage decrement (or a free hit) means every segment is reserved,
         * mid-acquisition or pinned, so no number of further passes can find
         * a victim.  Bail out after that revolution instead of sweeping
         * CFS_MAP_SEG_USAGE_MAX + 1 times, each tick taking a segment lock.
         */
        if (reserved)
        {
            uint32      key_hash;
 
            key_hash = cfs_map_segment_hash(rlocator, forknum, first_block);
            if (cfs_map_segment_reap_if_dead(&key, key_hash, id))
            {
                since_progress = 0;
                continue;
            }
            if (++since_progress >= cfs_map_seg_count)
                return -1;
            continue;
        }
 
        if (hash == 0)
        {
            int         res_state;
 
            res_state = cfs_map_segment_reservation_state(&key, id);
            if (res_state == CFS_RESERVATION_DEAD)
            {
                uint32      key_hash;
 
                key_hash = cfs_map_segment_hash(rlocator, forknum,
                                                first_block);
                (void) cfs_map_segment_reap_if_dead(&key, key_hash, id);
                since_progress = 0;
            }
            else if (res_state == CFS_RESERVATION_LIVE)
            {
                if (++since_progress >= cfs_map_seg_count)
                    return -1;
                continue;
            }
 
            *out_hash = 0;
            *out_first = 0;
            *out_epoch = epoch;
            *out_free = true;
            return id;
        }
 
        /*
         * A pinned relation does not protect its segments here: the slot pin
         * guards the metadata slot, and the working set is protected by
         * usage_count alone (bumped by every lookup/store).  Skipping the
         * segments of open relations would let one relation larger than the
         * pool keep it exhausted forever, with every further read paying the
         * authoritative fallback (measured: a 12x oversize degraded every
         * scan linearly, evictions stayed 0).
         */
        if (usage > 0)
        {
            (void) cfs_map_segment_dec_usage(desc);
            since_progress = 0;
            continue;
        }
 
        *out_hash = hash;
        *out_first = first_block;
        *out_epoch = epoch;
        *out_free = false;
        return id;
    }
    return -1;
}
 
int
cfs_shared_map_ensure(CfsRelation *cfs, BlockNumber blocknum)
{
    RelFileLocatorBackend rlocator = cfs->rlocator;
    ForkNumber  forknum = cfs->forknum;
    CfsMapSegmentKey key;
    uint32      hash;
    int         id;
    int         attempt;
    bool        fresh_segment = false;
    CfsMapEntry *buf = NULL;
    Size        seg_bytes = (Size) CFS_MAP_SEGMENT_BLOCKS * sizeof(CfsMapEntry);
    bool        merge_only = false;
    uint16      jrn_incarnation = 0;
    volatile bool reservation_held = false;
    char       *corrupt_mask = NULL;
    int         sync_rc;
 
    if (cfs_map_seg_count == 0)
        return CFS_STORAGE_ERROR;
 
    if (cfs_map_pool_exhausted &&
        pg_atomic_read_u64(&cfs_control->map_pool_churn) ==
        cfs_map_pool_exhausted_churn)
        return CFS_STORAGE_ERROR;
 
    key.rlocator = rlocator;
    key.forknum = forknum;
    key.first_block = blocknum & ~(BlockNumber) (CFS_MAP_SEGMENT_BLOCKS - 1);
    hash = cfs_map_segment_hash(rlocator, forknum, key.first_block);
 
    /*
     * A segment of an older relation generation may hold offsets tagged with
     * the pre-truncate/pre-compaction sidecar pair; it must never satisfy a
     * read through the new handle.  Evict it and try again: the retry either
     * reloads the segment under the current generation or loses the race and
     * reports a miss to the caller, which then falls back to the
     * authoritative path.
     */
    for (attempt = 0; attempt < 2; attempt++)
    {
        bool        stale_generation = false;
        uint64      stale_epoch = 0;
 
        merge_only = false;
        fresh_segment = false;
        buf = NULL;
 
        /* Fast path: the segment is resident AND snapshot-complete. */
        id = cfs_map_segment_find(&key, hash, LW_SHARED);
        if (id >= 0)
        {
            int         lock_id = id;
 
            LWLockAcquire(&cfs_map_seg_locks[lock_id].lock, LW_SHARED);
            if (cfs_map_segment_valid(&cfs_map_seg_descs[lock_id], hash, rlocator,
                                      forknum, key.first_block))
            {
                if (!cfs_seg_tag_matches(cfs_map_seg_descs[lock_id].rel_generation,
                                         cfs))
                {
                    stale_generation = true;
                    stale_epoch = cfs_map_seg_descs[lock_id].seg_epoch;
                }
                else
                {
                    merge_only = !cfs_map_seg_descs[lock_id].snapshot_loaded;
                    if (!merge_only)
                    {
                        bool        unhealed =
                            cfs_map_segment_unhealed_at(lock_id, hash,
                                                        rlocator, forknum,
                                                        key.first_block,
                                                        blocknum);
 
                        LWLockRelease(&cfs_map_seg_locks[lock_id].lock);
 
                        /*
                         * Only the requested block decides this call: other
                         * torn blocks of the same segment stay in the bitmap
                         * and fail their own reads through the corruption
                         * report.
                         */
                        return unhealed ? CFS_STORAGE_CORRUPT : CFS_STORAGE_OK;
                    }
                }
            }
            else
                id = -1;
            LWLockRelease(&cfs_map_seg_locks[lock_id].lock);
        }
 
        if (stale_generation)
        {
            cfs_map_segment_evict_one(id, hash, key.first_block, stale_epoch,
                                      true);
            continue;
        }
 
        /*
         * A resident segment that only holds journaled (store) entries needs
         * the .cfsmap snapshot merged into its INVALID slots before its
         * entries can be trusted by lookups; take the acquire path, which
         * re-recognises the resident segment, and merge below (never
         * overwriting the fresher journaled entries).
         */
        if (merge_only)
        {
            /*
             * Re-lookup only: a shared lock suffices — the search modifies
             * nothing, and a vanished entry is caught by the acquire/validate
             * steps below.
             */
            id = cfs_map_segment_find(&key, hash, LW_SHARED);
            if (id < 0)
                merge_only = false; /* vanished: full ensure below */
        }
 
        /*
         * Allocate (or find) the segment, evicting a clock-sweep victim when
         * the pool is full.  A competitor may be allocating the same segment
         * right now: its mapping entry exists while desc->hash is still 0
         * until the loader publishes the data, and a shared acquisition does
         * not wait for that load (the I/O happens outside the lock).  The
         * validation below therefore sees an unpublished descriptor and
         * reports a miss, which the caller retries or resolves through the
         * authoritative path — it never accepts an "ensured" segment whose
         * entries are not there yet.
         */
        if (!merge_only)
        {
            if (!cfs_map_segment_acquire(&key, hash, cfs->open_generation,
                                         &id, &fresh_segment))
                continue;
            if (!fresh_segment)
            {
                LWLockAcquire(&cfs_map_seg_locks[id].lock, LW_SHARED);
                if (!cfs_map_segment_valid(&cfs_map_seg_descs[id], hash,
                                           rlocator, forknum, key.first_block))
                {
                    /* The id was re-used by another key meanwhile: miss. */
                    LWLockRelease(&cfs_map_seg_locks[id].lock);
                    continue;
                }
                if (!cfs_seg_tag_matches(cfs_map_seg_descs[id].rel_generation,
                                         cfs))
                {
                    stale_epoch = cfs_map_seg_descs[id].seg_epoch;
                    LWLockRelease(&cfs_map_seg_locks[id].lock);
                    cfs_map_segment_evict_one(id, hash, key.first_block,
                                              stale_epoch, true);
                    continue;
                }
                merge_only = !cfs_map_seg_descs[id].snapshot_loaded;
                if (!merge_only)
                {
                    bool        unhealed =
                        cfs_map_segment_unhealed_at(id, hash, rlocator,
                                                    forknum, key.first_block,
                                                    blocknum);
 
                    LWLockRelease(&cfs_map_seg_locks[id].lock);
                    return unhealed ? CFS_STORAGE_CORRUPT : CFS_STORAGE_OK;
                }
                LWLockRelease(&cfs_map_seg_locks[id].lock);
            }
        }
 
        /*
         * Load the segment from the .cfsmap snapshot into a private buffer,
         * outside every lock.  Blocks the snapshot does not cover yet stay
         * zeroed (the INVALID sentinel) — the journal delta replay of the
         * authoritative miss path fills them in and advances jrn_synced_off.
         * The load starts at journal offset 0 on purpose: a snapshot written
         * by smgrimmedsync() does not truncate the journal, so replaying from
         * the journal header after every snapshot load is the norm, not a
         * corner case (the offset is not worth optimising: immedsync is
         * rare).
         *
         * A missing/empty snapshot (a young relation before its first
         * checkpoint) means an empty snapshot is the whole truth from the
         * .cfsmap side: the zeroed buffer is published/merged as-is and the
         * journal replay that the authoritative miss path always runs right
         * after ensure fills in the written blocks from the journal header.
         */
        if (fresh_segment)
            reservation_held = true;
 
        PG_TRY();
        {
            buf = cfs_map_segment_scratch();
            MemSet(buf, 0, seg_bytes);
            if (corrupt_mask != NULL)
                pfree(corrupt_mask);
            corrupt_mask = palloc0(CFS_MAP_SEGMENT_BLOCKS);
            {
                int         load_rc;
 
                load_rc = cfs_map_segment_load_buf(cfs, key.first_block, buf,
                                                   seg_bytes, corrupt_mask);
                if (load_rc < 0)
                {
                    /*
                     * The snapshot is a synchronisation point (see
                     * cfs_map_file_prologue_read): no fallback source exists.
                     * PG_FINALLY releases the reservation, or the reserved
                     * descriptor stays unpublished forever.
                     */
                    ereport(ERROR,
                            (errcode_for_file_access(),
                             errmsg("CFS: could not read map segment from \"%s\"",
                                    cfs->map_path)));
                }
            }
 
            /*
             * Sample the journal incarnation before any pool lock is taken:
             * it costs a pread of the journal header, and performing that
             * under the index/segment locks would stall every publisher for
             * the duration of the disk read.  Under the append lock (which
             * every production caller of ensure holds) the journal header is
             * stable, so the early sample equals what a later read would
             * return; a caller without the lock can only race a checkpoint
             * into an incarnation mismatch, which the segment's first sync
             * turns into a harmless resync.
             */
            jrn_incarnation = cfs_map_segment_journal_incarnation(cfs);
 
#ifdef USE_ASSERT_CHECKING
 
            /*
             * Test-only I4 race: a competitor merged the snapshot between our
             * load above and the segment phase below.  The merge helper
             * reloads the same per-backend scratch buffer, so 'buf' is no
             * longer ours; the segment phase then takes the "already merged"
             * branch anyway, which is exactly the behaviour under test.
             */
            if (cfs_test_merge_race_pending)
            {
                cfs_test_merge_race_pending = false;
                if (!fresh_segment)
                {
                    char       *race_mask = palloc0(CFS_MAP_SEGMENT_BLOCKS);
 
                    (void) cfs_map_segment_merge_snapshot(cfs, id, hash,
                                                          rlocator, forknum,
                                                          key.first_block,
                                                          race_mask);
                    pfree(race_mask);
                }
            }
#endif
 
            if (fresh_segment)
            {
                cfs_map_segment_clear_reservation(&key, hash);
                reservation_held = false;
            }
        }
        PG_FINALLY();
        {
            if (reservation_held)
                cfs_map_segment_release_reservation(&key, hash, id);
        }
        PG_END_TRY();
 
        /*
         * Segment phase: publish the loaded data under the segment lock.  A
         * concurrent eviction may have freed the id while we were reading:
         * for a fresh allocation the hash == 0 re-check turns that into a
         * plain miss; a concurrent eviction/re-use of an existing id is
         * caught by the key re-validation.  Fresh allocation: publish the
         * loaded snapshot wholesale (desc->hash == 0 still marks our
         * reservation).  Merge into a store-created segment: fill only the
         * INVALID slots — the journaled entries it already holds are newer
         * than the snapshot — and mark the snapshot part loaded.
         */
        LWLockAcquire(&cfs_map_rel_index_lock->lock, LW_EXCLUSIVE);
        LWLockAcquire(&cfs_map_seg_locks[id].lock, LW_EXCLUSIVE);
        if (cfs_map_seg_descs[id].hash == 0)
        {
            cfs_map_segment_publish_locked(id, hash, rlocator, forknum,
                                           key.first_block,
                                           cfs->open_generation, buf, false,
                                           jrn_incarnation);
            pg_atomic_fetch_add_u64(&cfs_control->map_segment_loads, 1);
            LWLockRelease(&cfs_map_seg_locks[id].lock);
            LWLockRelease(&cfs_map_rel_index_lock->lock);
 
            /*
             * The published snapshot may be staler than the journal (a
             * truncate journals RESIZE long before the next checkpoint
             * rewrites .cfsmap): replay the journal into the segment now, so
             * no reader can hit an entry the journal has since deleted. The
             * replay also decides the freshly loaded corrupt rows: a row the
             * journal does not heal fails the read (CORRUPT) instead of ever
             * serving as a zero page.
             */
            sync_rc = cfs_shared_map_sync_segment(cfs, blocknum,
                                                  corrupt_mask);
            pfree(corrupt_mask);
 
            /*
             * CORRUPT propagates; a transient sync failure (0) must not read
             * as ensured - the follow-up sync of the read path runs without a
             * mask and would grant journal_synced unchecked. The caller's
             * authoritative fallback re-validates instead.
             */
            return (sync_rc == 1) ? CFS_STORAGE_OK :
                (sync_rc == CFS_STORAGE_CORRUPT ? CFS_STORAGE_CORRUPT :
                 CFS_STORAGE_ERROR);
        }
        if (cfs_seg_matches(&cfs_map_seg_descs[id], hash, rlocator,
                            forknum, key.first_block, cfs))
        {
            if (!cfs_map_seg_descs[id].snapshot_loaded)
            {
                cfs_map_segment_merge_invalid_locked(id, buf);
                cfs_map_seg_descs[id].snapshot_loaded = true;
                cfs_map_seg_descs[id].journal_synced = false;
                MemSet(cfs_map_seg_descs[id].unhealed_mask, 0,
                       sizeof(cfs_map_seg_descs[id].unhealed_mask));
                cfs_map_seg_descs[id].jrn_incarnation = jrn_incarnation;
 
                /*
                 * The merged snapshot may predate journal records
                 * (RESIZE/DELETE) the segment has not consumed; rebaseline
                 * the replay cursor so the full journal replay below
                 * re-applies them AFTER the merge, clearing whatever the
                 * stale snapshot resurrected.
                 */
                cfs_map_seg_descs[id].jrn_synced_off = 0;
                pg_atomic_fetch_add_u64(&cfs_control->map_segment_loads, 1);
                LWLockRelease(&cfs_map_seg_locks[id].lock);
                LWLockRelease(&cfs_map_rel_index_lock->lock);
                sync_rc = cfs_shared_map_sync_segment(cfs, blocknum,
                                                      corrupt_mask);
                pfree(corrupt_mask);
                return (sync_rc == 1) ? CFS_STORAGE_OK :
                    (sync_rc == CFS_STORAGE_CORRUPT ? CFS_STORAGE_CORRUPT :
                     CFS_STORAGE_ERROR);
            }
            {
                bool        unhealed =
                    cfs_map_segment_unhealed_at(id, hash, rlocator, forknum,
                                                key.first_block, blocknum);
 
                LWLockRelease(&cfs_map_seg_locks[id].lock);
                LWLockRelease(&cfs_map_rel_index_lock->lock);
                pfree(corrupt_mask);
                return unhealed ? CFS_STORAGE_CORRUPT : CFS_STORAGE_OK;
            }
        }
        LWLockRelease(&cfs_map_seg_locks[id].lock);
        LWLockRelease(&cfs_map_rel_index_lock->lock);
    }
 
    /*
     * The pool could not serve us: remember the churn value so the next miss
     * of this backend goes straight to the authoritative fallback until
     * something changes.  The fallback is always correct, so a stale memo
     * only costs a scratch load, never data.
     */
    cfs_map_pool_exhausted = true;
    cfs_map_pool_exhausted_churn =
        pg_atomic_read_u64(&cfs_control->map_pool_churn);
    if (corrupt_mask != NULL)
        pfree(corrupt_mask);
    return CFS_STORAGE_ERROR;
}
 
bool
cfs_shared_map_lookup(RelFileLocatorBackend rlocator, ForkNumber forknum,
                      BlockNumber blocknum, CfsMapEntry *out_entry,
                      uint64 *out_generation)
{
    CfsMapSegmentKey key;
    uint32      hash;
    int         id;
    bool        found = false;
    uint64      nblocks;
 
    if (cfs_map_seg_count == 0)
        return false;
 
    /*
     * Serve only blocks below the metadata slot's current logical size .
     * Today the .cfsmap file is always exactly nblocks rows, so resident rows
     * beyond nblocks can only appear transiently - a truncate shrinks the
     * slot (and journals RESIZE) under the append lock but drops the segments
     * outside it.  With deferred truncation and sparse maps this gate becomes
     * load-bearing.  An absent or zero-size slot imposes no restriction: its
     * size is simply not published yet.
     */
    if (cfs_map_cache_get_nblocks(rlocator, forknum, &nblocks) &&
        nblocks > 0 && (uint64) blocknum >= nblocks)
        return false;
 
    key.rlocator = rlocator;
    key.forknum = forknum;
    key.first_block = blocknum & ~(BlockNumber) (CFS_MAP_SEGMENT_BLOCKS - 1);
    hash = cfs_map_segment_hash(rlocator, forknum, key.first_block);
 
    id = cfs_map_segment_find(&key, hash, LW_SHARED);
    if (id < 0)
        return false;
 
    /*
     * The segment may have been evicted and its id re-used between the hash
     * lookup and here; the descriptor check under the segment lock catches
     * that and turns it into a plain miss.
     */
    LWLockAcquire(&cfs_map_seg_locks[id].lock, LW_SHARED);
    if (cfs_map_segment_valid(&cfs_map_seg_descs[id], hash, rlocator,
                              forknum, key.first_block) &&
        cfs_map_seg_descs[id].journal_synced &&
        !cfs_map_segment_unhealed_at(id, hash, rlocator, forknum,
                                     key.first_block, blocknum))
    {
        CfsMapEntry *entry;
 
        entry = &cfs_map_seg_data[id][blocknum - key.first_block];
        if (entry->physical_offset != CFS_ENTRY_INVALID_OFFSET)
        {
            *out_entry = *entry;
            if (out_generation != NULL)
                *out_generation = cfs_map_seg_descs[id].rel_generation;
            cfs_map_segment_bump_usage(&cfs_map_seg_descs[id]);
            found = true;
        }
    }
    LWLockRelease(&cfs_map_seg_locks[id].lock);
 
    return found;
}
 
/*
 * cfs_map_segment_acquire — make sure the pool holds a (possibly fresh,
 * still invisible) segment for 'key', evicting a clock-sweep victim when
 * the pool is full.  'generation' tags the allocation with the relation map
 * generation its offsets will belong to (captured by the caller before
 * any locks: a stale tag costs one extra handle reopen, never incorrect
 * data).  On success *id_out is the segment id and *fresh_out tells
 * whether WE allocated it (and must zero its data and publish desc->hash
 * in the segment phase).  Returns false when no victim can be found
 * (every segment pinned) or a race lost three times in a row — the
 * caller then degrades to the authoritative path, which is always
 * correct without a resident segment.
 */
static bool
cfs_map_segment_acquire(const CfsMapSegmentKey *key, uint32 hash,
                        uint64 generation,
                        int *id_out, bool *fresh_out)
{
    int         part = hash & CFS_PART_MASK;
    CfsMapSegmentHashEnt *ent;
    int         id;
    int         candidate;
    int         tries;
 
    *fresh_out = false;
 
    for (tries = 0; tries < 3; tries++)
    {
        bool        candidate_ready = false;
 
        /*
         * Look the key up before choosing a victim.  A repeated store of an
         * already resident segment is a plain update: scanning for (and
         * evicting) a victim first threw an unrelated resident segment out of
         * a full pool for no reason.
         */
        id = cfs_map_segment_find(key, hash, LW_SHARED);
        if (id >= 0)
        {
            bool        ghost;
            bool        reserved;
 
            /*
             * A mapping entry may point at a descriptor an invalidation has
             * meanwhile freed (a "ghost" mapping); an entry whose descriptor
             * is reserved belongs to an acquirer still publishing it and is
             * returned so the caller can wait for/validate the publication. A
             * reserved descriptor whose owner died is reaped here: the
             * segment lock is released first because the reaper needs the
             * mapping lock.
             */
            LWLockAcquire(&cfs_map_seg_locks[id].lock, LW_SHARED);
            ghost = (cfs_map_seg_descs[id].hash == 0 &&
                     !cfs_map_seg_descs[id].reserved);
            reserved = cfs_map_seg_descs[id].reserved;
            LWLockRelease(&cfs_map_seg_locks[id].lock);
 
            if (reserved)
            {
                if (cfs_map_segment_reap_if_dead(key, hash, id))
                {
                    /*
                     * The reaped descriptor is free again: reuse exactly this
                     * id instead of sweeping for another one.
                     */
                    candidate = id;
                    candidate_ready = true;
                }
                else
                {
                    *id_out = id;
                    return true;
                }
            }
            if (!reserved && !ghost)
            {
                *id_out = id;
                return true;
            }
        }
 
        /*
         * Pick a segment with the clock sweep.  Both the sweep and the
         * eviction take segment/mapping locks themselves, so they run before
         * we take the mapping partition lock below.
         */
        if (!candidate_ready)
        {
            uint32      victim_hash;
            BlockNumber victim_first;
            uint64      victim_epoch;
            bool        victim_free;
 
            candidate = cfs_map_segment_select_victim(&victim_hash,
                                                      &victim_first,
                                                      &victim_epoch,
                                                      &victim_free);
            if (candidate < 0)
                return false;   /* every segment is pinned */
            if (!victim_free)
                cfs_map_segment_evict_one(candidate, victim_hash,
                                          victim_first, victim_epoch, true);
        }
 
        LWLockAcquire(&cfs_map_locks[part].lock, LW_EXCLUSIVE);
        ent = (CfsMapSegmentHashEnt *)
            hash_search_with_hash_value(cfs_map_seg_hash, key, hash,
                                        HASH_FIND, NULL);
        id = (ent != NULL) ? ent->segment_id : -1;
 
        /*
         * A concurrent eviction can leave a ghost mapping between the lookup
         * above and this exclusive re-check; drop it before allocating.
         */
        if (id >= 0 && id < cfs_map_seg_count)
        {
            bool        ghost;
 
            LWLockAcquire(&cfs_map_seg_locks[id].lock, LW_SHARED);
            ghost = (cfs_map_seg_descs[id].hash == 0 &&
                     !cfs_map_seg_descs[id].reserved);
            LWLockRelease(&cfs_map_seg_locks[id].lock);
            if (ghost)
            {
                hash_search_with_hash_value(cfs_map_seg_hash, key, hash,
                                            HASH_REMOVE, NULL);
                id = -1;
            }
        }
 
        if (id >= 0 && id < cfs_map_seg_count)
        {
            /* Resident (or a competitor's fresh allocation). */
            LWLockRelease(&cfs_map_locks[part].lock);
            *id_out = id;
            return true;
        }
 
        /*
         * The exclusive re-lookup above overwrote 'id'; go back to the
         * candidate the clock sweep chose (free or just evicted).
         */
        id = candidate;
 
        /*
         * Reserve the descriptor under the segment lock: 'reserved' makes the
         * sweep skip the id while we initialise its fields and publish the
         * mapping entry (the buffer-manager pin-before-publish model —
         * without it a competitor could allocate the same "free" descriptor
         * and leave two mapping entries pointing at one descriptor).
         * desc->hash stays 0: the descriptor remains invisible to readers
         * until the owner's segment phase publishes initialised data.
         */
        {
            CfsMapSegmentDesc *desc = &cfs_map_seg_descs[id];
            bool        found;
 
            LWLockAcquire(&cfs_map_seg_locks[id].lock, LW_EXCLUSIVE);
            if (desc->hash != 0 || desc->reserved)
            {
                /* Lost the candidate between the sweep and here; retry. */
                LWLockRelease(&cfs_map_seg_locks[id].lock);
                LWLockRelease(&cfs_map_locks[part].lock);
                continue;
            }
            desc->rlocator = key->rlocator;
            desc->forknum = key->forknum;
            desc->first_block = key->first_block;
            desc->jrn_synced_off = 0;
            desc->jrn_incarnation = 0;
            desc->rel_generation = generation;
            desc->snapshot_loaded = false;
            desc->journal_synced = false;
            desc->seg_epoch++;
            desc->reserved = true;
            LWLockRelease(&cfs_map_seg_locks[id].lock);
 
            ent = (CfsMapSegmentHashEnt *)
                hash_search_with_hash_value(cfs_map_seg_hash, key, hash,
                                            HASH_ENTER, &found);
            if (!found)
            {
                CfsMapSegmentReservation *live;
 
                ent->segment_id = id;
                live = (CfsMapSegmentReservation *)
                    hash_search_with_hash_value(cfs_map_seg_live, key, hash,
                                                HASH_ENTER, NULL);
                live->segment_id = id;
                live->owner_pid = MyProcPid;
                live->owner_procno = MyProcNumber;
                live->owner_epoch = cfs_map_owner_epoch_get();
                *id_out = id;
                *fresh_out = true;
                LWLockRelease(&cfs_map_locks[part].lock);
                return true;
            }
 
            /*
             * A concurrent insert won the race; its segment is ours.  Copy
             * the id while the partition lock is still held: 'ent' may be
             * freed as soon as the lock is released.
             */
            {
                int         winner_id = ent->segment_id;
 
                LWLockRelease(&cfs_map_locks[part].lock);
                LWLockAcquire(&cfs_map_seg_locks[id].lock, LW_EXCLUSIVE);
                desc->reserved = false;
                LWLockRelease(&cfs_map_seg_locks[id].lock);
                *id_out = winner_id;
                return true;
            }
        }
    }
    return false;
}
 
bool
cfs_shared_map_store(RelFileLocatorBackend rlocator, ForkNumber forknum,
                     BlockNumber blocknum, const CfsMapEntry *entry,
                     uint64 generation)
{
    CfsMapSegmentKey key;
    uint32      hash;
    int         id;
    bool        fresh_segment = false;
 
    if (cfs_map_seg_count == 0)
        return false;
 
    key.rlocator = rlocator;
    key.forknum = forknum;
    key.first_block = blocknum & ~(BlockNumber) (CFS_MAP_SEGMENT_BLOCKS - 1);
    hash = cfs_map_segment_hash(rlocator, forknum, key.first_block);
 
    /*
     * The caller (cfs_write_page_cached) holds the append lock and has just
     * refreshed a stale handle, so the generation it passes is its open
     * generation, naming the sidecar pair the new entry's offset belongs to.
     * A racing compaction is excluded by that same lock.
     */
 
    if (!cfs_map_segment_acquire(&key, hash, generation,
                                 &id, &fresh_segment))
        return false;
 
    /*
     * Segment phase: for a fresh allocation zero the data first and only then
     * publish desc->hash; for an existing segment validate the key (the id
     * may have been evicted and re-used while we waited).  The in-flight
     * reservation is retired just before publication, while 'reserved' still
     * keeps the victim sweep away from the descriptor.
     */
    if (fresh_segment)
        cfs_map_segment_clear_reservation(&key, hash);
 
    /*
     * A fresh publication must also be linked into the per-relation index,
     * which requires the index lock outside the segment lock.  Updates of an
     * already resident segment (the common per-block case) skip it.
     */
    if (fresh_segment)
        LWLockAcquire(&cfs_map_rel_index_lock->lock, LW_EXCLUSIVE);
    LWLockAcquire(&cfs_map_seg_locks[id].lock, LW_EXCLUSIVE);
    if (fresh_segment && cfs_map_seg_descs[id].hash == 0)
        cfs_map_segment_publish_locked(id, hash, rlocator, forknum,
                                       key.first_block, generation, NULL,
                                       true, 0);
    if (cfs_map_segment_valid(&cfs_map_seg_descs[id], hash, rlocator,
                              forknum, key.first_block))
    {
        uint32      off = blocknum - key.first_block;
 
        cfs_map_seg_data[id][off] = *entry;
 
        /*
         * A freshly written version resolves the block: any earlier torn
         * snapshot row for it is superseded, so the block may serve again.
         */
        cfs_seg_unhealed_clear(&cfs_map_seg_descs[id], off);
        cfs_map_segment_bump_usage(&cfs_map_seg_descs[id]);
        LWLockRelease(&cfs_map_seg_locks[id].lock);
        if (fresh_segment)
            LWLockRelease(&cfs_map_rel_index_lock->lock);
        return true;
    }
    LWLockRelease(&cfs_map_seg_locks[id].lock);
    if (fresh_segment)
        LWLockRelease(&cfs_map_rel_index_lock->lock);
    return false;
}
 
/*
 * The index key is compared bytewise (HASH_BLOBS), so clear the tail
 * padding that a struct assignment would leave uninitialised.
 */
static void
cfs_map_segment_rel_key(CfsMapSegmentRelKey *key,
                        RelFileLocatorBackend rlocator, ForkNumber forknum)
{
    MemSet(key, 0, sizeof(*key));
    key->rlocator = rlocator;
    key->forknum = forknum;
}
 
/*
 * Link a freshly published descriptor into its relation's segment list.
 * The caller holds the index lock and the segment lock (so the descriptor's
 * key fields cannot change underneath).
 */
static void
cfs_map_segment_rel_link_locked(int id)
{
    CfsMapSegmentDesc *desc = &cfs_map_seg_descs[id];
    CfsMapSegmentRelKey key;
    CfsMapSegmentRelEnt *ent;
    bool        found;
 
    Assert(!desc->rel_linked);
 
    cfs_map_segment_rel_key(&key, desc->rlocator, desc->forknum);
    ent = hash_search(cfs_map_rel_index, &key, HASH_ENTER, &found);
    if (!found)
    {
        dlist_init(&ent->head);
        ent->count = 0;
    }
    dlist_push_head(&ent->head, &desc->rel_node);
    desc->rel_linked = true;
    ent->count++;
}
 
/*
 * Unlink a published descriptor from its relation's segment list.  The
 * caller holds the index lock and the segment lock.  A descriptor that is
 * already detached (the invalidation path detaches before it evicts) is
 * left alone, which keeps the call idempotent.
 */
static void
cfs_map_segment_rel_unlink_locked(int id)
{
    CfsMapSegmentDesc *desc = &cfs_map_seg_descs[id];
    CfsMapSegmentRelKey key;
    CfsMapSegmentRelEnt *ent;
 
    if (!desc->rel_linked)
        return;
 
    cfs_map_segment_rel_key(&key, desc->rlocator, desc->forknum);
    ent = hash_search(cfs_map_rel_index, &key, HASH_FIND, NULL);
    Assert(ent != NULL);
    dlist_delete_thoroughly(&desc->rel_node);
    desc->rel_linked = false;
    ent->count--;
    Assert(desc->rel_node.prev == NULL && desc->rel_node.next == NULL);
    if (ent->count == 0)
    {
        Assert(dlist_is_empty(&ent->head));
        hash_search(cfs_map_rel_index, &key, HASH_REMOVE, NULL);
    }
}
 
/*
 * Drop the hash-table entry and free the descriptor of one segment.  The
 * caller has verified under the segment lock that the descriptor matches
 * 'hash'/'first_block'; we re-check under the segment lock after the hash
 * removal so that a concurrent re-use of the id by another key is never
 * freed by mistake.  'unlink_rel' tells whether the descriptor still sits
 * in the per-relation index (the invalidation path detaches its nodes
 * itself, under the index lock, before calling here).
 */
static void
cfs_map_segment_evict_one(int id, uint32 hash, BlockNumber first_block,
                          uint64 epoch, bool unlink_rel)
{
    CfsMapSegmentDesc *desc = &cfs_map_seg_descs[id];
    int         part = hash & CFS_PART_MASK;
    CfsMapSegmentKey key;
    bool        still_victim = false;
 
    /*
     * Sample the victim key under the segment lock: reading the descriptor
     * fields before taking it could race a re-use of the id for another
     * relation and remove the wrong mapping entry.  hash + first_block +
     * epoch are enough to identify the victim exactly: every publication and
     * every release bumps the epoch in the same critical section that
     * rewrites the key fields, so a descriptor recycled for another
     * rlocator/forknum must carry a different epoch even if the id, hash and
     * first_block happen to repeat (the rlocator/forknum fields are therefore
     * not compared separately).  The index lock is the outer one (index ->
     * segment), and the node is detached in the same critical section that
     * samples it.
     */
    if (unlink_rel)
        LWLockAcquire(&cfs_map_rel_index_lock->lock, LW_EXCLUSIVE);
    LWLockAcquire(&cfs_map_seg_locks[id].lock, LW_SHARED);
    if (desc->hash == hash && desc->first_block == first_block &&
        desc->seg_epoch == epoch && !desc->reserved)
    {
        key.rlocator = desc->rlocator;
        key.forknum = desc->forknum;
        key.first_block = first_block;
        still_victim = true;
        if (unlink_rel)
            cfs_map_segment_rel_unlink_locked(id);
    }
    LWLockRelease(&cfs_map_seg_locks[id].lock);
    if (unlink_rel)
        LWLockRelease(&cfs_map_rel_index_lock->lock);
    if (!still_victim)
        return;
 
    LWLockAcquire(&cfs_map_locks[part].lock, LW_EXCLUSIVE);
    hash_search_with_hash_value(cfs_map_seg_hash, &key, hash,
                                HASH_REMOVE, NULL);
    LWLockRelease(&cfs_map_locks[part].lock);
 
    LWLockAcquire(&cfs_map_seg_locks[id].lock, LW_EXCLUSIVE);
    if (desc->hash == hash && desc->first_block == first_block &&
        desc->seg_epoch == epoch)
    {
        desc->hash = 0;
        pg_atomic_write_u32(&desc->usage_count, 0);
        desc->snapshot_loaded = false;
        desc->journal_synced = false;
        desc->seg_epoch++;
        pg_atomic_fetch_sub_u64(&cfs_control->map_segments_in_use, 1);
        pg_atomic_fetch_add_u64(&cfs_control->map_segment_evictions, 1);
        pg_atomic_fetch_add_u64(&cfs_control->map_pool_churn, 1);
    }
    LWLockRelease(&cfs_map_seg_locks[id].lock);
}
 
void
cfs_shared_map_invalidate_relation(RelFileLocatorBackend rlocator,
                                   ForkNumber forknum)
{
    CfsMapSegmentRelKey relkey;
 
    if (cfs_map_seg_count == 0)
        return;
 
    /*
     * Walk the relation's segment list instead of the whole pool.  Each
     * iteration detaches one node under the index lock (together with a
     * sample of the descriptor key and epoch), then evicts outside it.  The
     * sampled epoch makes eviction a no-op if the id was recycled meanwhile;
     * the node is detached exactly once even with concurrent invalidations.
     */
    cfs_map_segment_rel_key(&relkey, rlocator, forknum);
 
    for (;;)
    {
        CfsMapSegmentRelEnt *ent;
        CfsMapSegmentDesc *desc;
        uint32      hash;
        BlockNumber first_block;
        uint64      epoch;
        int         id;
 
        LWLockAcquire(&cfs_map_rel_index_lock->lock, LW_EXCLUSIVE);
        ent = hash_search(cfs_map_rel_index, &relkey, HASH_FIND, NULL);
        if (ent == NULL || dlist_is_empty(&ent->head))
        {
            LWLockRelease(&cfs_map_rel_index_lock->lock);
            break;
        }
 
        desc = dlist_container(CfsMapSegmentDesc, rel_node,
                               dlist_head_node(&ent->head));
        id = desc - cfs_map_seg_descs;
 
        LWLockAcquire(&cfs_map_seg_locks[id].lock, LW_SHARED);
        hash = desc->hash;
        first_block = desc->first_block;
        epoch = desc->seg_epoch;
        cfs_map_segment_rel_unlink_locked(id);
        LWLockRelease(&cfs_map_seg_locks[id].lock);
        LWLockRelease(&cfs_map_rel_index_lock->lock);
 
        if (hash != 0)
            cfs_map_segment_evict_one(id, hash, first_block, epoch, false);
    }
}
 
void
cfs_shared_map_invalidate_db(Oid dbid)
{
    int         id;
 
    if (cfs_map_seg_count == 0)
        return;
 
    for (id = 0; id < cfs_map_seg_count; id++)
    {
        CfsMapSegmentDesc *desc = &cfs_map_seg_descs[id];
        uint32      hash;
        BlockNumber first_block;
        uint64      epoch;
 
        LWLockAcquire(&cfs_map_seg_locks[id].lock, LW_SHARED);
        hash = desc->hash;
        first_block = desc->first_block;
        epoch = desc->seg_epoch;
        if (hash == 0 || desc->rlocator.locator.dbOid != dbid)
        {
            LWLockRelease(&cfs_map_seg_locks[id].lock);
            continue;
        }
        LWLockRelease(&cfs_map_seg_locks[id].lock);
 
        cfs_map_segment_evict_one(id, hash, first_block, epoch, true);
    }
}
 
void
cfs_shared_map_stats(uint64 *segments_in_use, uint64 *segment_loads,
                     uint64 *segment_evictions, uint64 *pool_segments)
{
    uint64      dummy;
 
    if (segments_in_use == NULL)
        segments_in_use = &dummy;
    if (segment_loads == NULL)
        segment_loads = &dummy;
    if (segment_evictions == NULL)
        segment_evictions = &dummy;
    if (pool_segments == NULL)
        pool_segments = &dummy;
 
    if (cfs_control == NULL)
    {
        *segments_in_use = *segment_loads = 0;
        *segment_evictions = *pool_segments = 0;
        return;
    }
    *segments_in_use = pg_atomic_read_u64(&cfs_control->map_segments_in_use);
    *segment_loads = pg_atomic_read_u64(&cfs_control->map_segment_loads);
    *segment_evictions = pg_atomic_read_u64(&cfs_control->map_segment_evictions);
    *pool_segments = (uint64) cfs_map_seg_count;
}
 
uint64
cfs_shared_map_fallback_reads(void)
{
    if (cfs_control == NULL)
        return 0;
    return pg_atomic_read_u64(&cfs_control->map_fallback_reads);
}
 
uint64
cfs_shared_full_map_opens(void)
{
    if (cfs_control == NULL)
        return 0;
    return pg_atomic_read_u64(&cfs_control->full_map_opens);
}
 
#ifdef USE_ASSERT_CHECKING
 
/*
 * Test-only: publish the segment covering 'blocknum' straight from the
 * .cfsmap snapshot with journal_synced == false, i.e. exactly the state a
 * fresh publication has before the first replay.  A lookup must treat that
 * segment as a miss until cfs_shared_map_sync_segment() catches it up with
 * the journal (C2).
 */
bool
cfs_shared_map_test_publish_unsynced(CfsRelation *cfs, BlockNumber blocknum)
{
    RelFileLocatorBackend rlocator = cfs->rlocator;
    ForkNumber  forknum = cfs->forknum;
    CfsMapSegmentKey key;
    uint32      hash;
    CfsMapEntry *buf;
    Size        seg_bytes = (Size) CFS_MAP_SEGMENT_BLOCKS * sizeof(CfsMapEntry);
    uint16      jrn_incarnation;
    int         id;
    bool        fresh = false;
    bool        ok = false;
 
    if (cfs_map_seg_count == 0)
        return false;
 
    key.rlocator = rlocator;
    key.forknum = forknum;
    key.first_block = blocknum & ~(BlockNumber) (CFS_MAP_SEGMENT_BLOCKS - 1);
    hash = cfs_map_segment_hash(rlocator, forknum, key.first_block);
 
    if (!cfs_map_segment_acquire(&key, hash, cfs->open_generation, &id,
                                 &fresh))
        return false;
 
    buf = cfs_map_segment_scratch();
    MemSet(buf, 0, seg_bytes);
    {
        char       *corrupt_mask = palloc0(CFS_MAP_SEGMENT_BLOCKS);
 
        if (cfs_map_segment_load_buf(cfs, key.first_block, buf, seg_bytes,
                                     corrupt_mask) < 0)
        {
            pfree(corrupt_mask);
            if (fresh)
                cfs_map_segment_release_reservation(&key, hash, id);
            return false;
        }
        pfree(corrupt_mask);
    }
 
    /*
     * Sampled before the locks, like cfs_shared_map_ensure(): no journal
     * header I/O under the index/segment locks.
     */
    jrn_incarnation = cfs_map_segment_journal_incarnation(cfs);
 
    if (fresh)
        cfs_map_segment_clear_reservation(&key, hash);
 
    LWLockAcquire(&cfs_map_rel_index_lock->lock, LW_EXCLUSIVE);
    LWLockAcquire(&cfs_map_seg_locks[id].lock, LW_EXCLUSIVE);
    if (cfs_map_seg_descs[id].hash == 0 ||
        cfs_map_segment_valid(&cfs_map_seg_descs[id], hash, rlocator,
                              forknum, key.first_block))
    {
        bool        newly_used = (cfs_map_seg_descs[id].hash == 0);
 
        cfs_map_segment_publish_locked(id, hash, rlocator, forknum,
                                       key.first_block,
                                       cfs->open_generation, buf, false,
                                       jrn_incarnation);
        if (newly_used)
            pg_atomic_fetch_add_u64(&cfs_control->map_segment_loads, 1);
        ok = true;
    }
    LWLockRelease(&cfs_map_seg_locks[id].lock);
    LWLockRelease(&cfs_map_rel_index_lock->lock);
 
    return ok;
}
 
/*
 * Test-only: leave an in-flight reservation for a free segment id, as a
 * backend that died between claiming the descriptor and publishing it
 * would.  Unlike a real acquirer this one marks the descriptor reserved and
 * records a provably dead owner (pid 0, invalid ProcNumber, epoch 0), so a
 * competitor must reap it and reuse the same id.
 */
int
cfs_shared_map_test_reserve_orphan(RelFileLocatorBackend rlocator,
                                   ForkNumber forknum, BlockNumber blocknum)
{
    CfsMapSegmentKey key;
    CfsMapSegmentReservation *live;
    CfsMapSegmentHashEnt *ent;
    uint32      hash;
    int         part;
    int         id = -1;
    int         i;
    bool        found;
 
    if (cfs_map_seg_count == 0 || cfs_map_seg_live == NULL)
        return -1;
 
    for (i = 0; i < cfs_map_seg_count; i++)
    {
        bool        free;
 
        LWLockAcquire(&cfs_map_seg_locks[i].lock, LW_SHARED);
        free = (cfs_map_seg_descs[i].hash == 0 &&
                !cfs_map_seg_descs[i].reserved);
        LWLockRelease(&cfs_map_seg_locks[i].lock);
        if (free)
        {
            id = i;
            break;
        }
    }
    if (id < 0)
        return -1;
 
    key.rlocator = rlocator;
    key.forknum = forknum;
    key.first_block = blocknum & ~(BlockNumber) (CFS_MAP_SEGMENT_BLOCKS - 1);
    hash = cfs_map_segment_hash(rlocator, forknum, key.first_block);
    part = hash & CFS_PART_MASK;
 
    LWLockAcquire(&cfs_map_seg_locks[id].lock, LW_EXCLUSIVE);
    if (cfs_map_seg_descs[id].hash != 0 || cfs_map_seg_descs[id].reserved)
    {
        LWLockRelease(&cfs_map_seg_locks[id].lock);
        return -1;
    }
    cfs_map_seg_descs[id].rlocator = rlocator;
    cfs_map_seg_descs[id].forknum = forknum;
    cfs_map_seg_descs[id].first_block = key.first_block;
    cfs_map_seg_descs[id].seg_epoch++;
    cfs_map_seg_descs[id].reserved = true;
    LWLockRelease(&cfs_map_seg_locks[id].lock);
 
    LWLockAcquire(&cfs_map_locks[part].lock, LW_EXCLUSIVE);
    ent = (CfsMapSegmentHashEnt *)
        hash_search_with_hash_value(cfs_map_seg_hash, &key, hash,
                                    HASH_ENTER, &found);
    if (found)
    {
        LWLockRelease(&cfs_map_locks[part].lock);
        LWLockAcquire(&cfs_map_seg_locks[id].lock, LW_EXCLUSIVE);
        cfs_map_seg_descs[id].reserved = false;
        LWLockRelease(&cfs_map_seg_locks[id].lock);
        return -1;
    }
    ent->segment_id = id;
 
    live = (CfsMapSegmentReservation *)
        hash_search_with_hash_value(cfs_map_seg_live, &key, hash,
                                    HASH_ENTER, NULL);
    live->segment_id = id;
    live->owner_pid = 0;
    live->owner_procno = INVALID_PROC_NUMBER;
    live->owner_epoch = 0;
    LWLockRelease(&cfs_map_locks[part].lock);
 
    return id;
}
 
/* Test-only: clock-sweep usage counter of a descriptor (0 if out of range). */
uint32
cfs_shared_map_test_desc_usage(int id)
{
    if (id < 0 || id >= cfs_map_seg_count)
        return 0;
    return pg_atomic_read_u32(&cfs_map_seg_descs[id].usage_count);
}
 
/* Test-only: force a usage value, to exercise the decrement edge cases. */
void
cfs_shared_map_test_set_desc_usage(int id, uint32 value)
{
    if (id < 0 || id >= cfs_map_seg_count)
        return;
    pg_atomic_write_u32(&cfs_map_seg_descs[id].usage_count, value);
}
 
/* Test-only: run the production decrement helper on one descriptor. */
void
cfs_shared_map_test_dec_desc_usage(int id)
{
    if (id < 0 || id >= cfs_map_seg_count)
        return;
    (void) cfs_map_segment_dec_usage(&cfs_map_seg_descs[id]);
}
 
/* Test-only: current segment id of a key (or -1 when not mapped). */
int
cfs_shared_map_test_segment_id(RelFileLocatorBackend rlocator,
                               ForkNumber forknum, BlockNumber blocknum)
{
    CfsMapSegmentKey key;
    uint32      hash;
 
    if (cfs_map_seg_count == 0)
        return -1;
 
    key.rlocator = rlocator;
    key.forknum = forknum;
    key.first_block = blocknum & ~(BlockNumber) (CFS_MAP_SEGMENT_BLOCKS - 1);
    hash = cfs_map_segment_hash(rlocator, forknum, key.first_block);
    return cfs_map_segment_find(&key, hash, LW_SHARED);
}
 
/*
 * Test-only switch for the I4 race: cfs_shared_map_ensure() consumes it
 * between the snapshot load and the segment phase and merges the snapshot
 * the way a competing backend already would have.
 */
bool
cfs_shared_map_test_merge_race(CfsRelation *cfs, BlockNumber blocknum)
{
    (void) blocknum;
 
    if (cfs_map_seg_count == 0)
        return false;
    cfs_test_merge_race_pending = true;
    return true;
}
 
#endif                          /* USE_ASSERT_CHECKING */
 
/* ================================================================
 * Append serialization
 * ================================================================
 */
 
/*
 * Locate the metadata slot for a relation without holding any lock; returns
 * a stable pointer because the slot array is a fixed shared-memory
 * allocation.  The caller must have pinned the slot (so it cannot be
 * evicted) before relying on the returned pointer for lock operations.
 */
static CfsRelMetaSlot *
cfs_append_lock_find_slot(RelFileLocatorBackend rlocator, ForkNumber forknum)
{
    uint32      rel_hash = cfs_cache_hash_rel(rlocator, forknum);
    int         part = rel_hash & CFS_PART_MASK;
    CfsRelMetaSlot *m;
 
    LWLockAcquire(&cfs_map_locks[part].lock, LW_SHARED);
    m = cfs_meta_find(rel_hash, rlocator, forknum);
    LWLockRelease(&cfs_map_locks[part].lock);
 
    return m;
}
 
void
cfs_append_lock_acquire(RelFileLocatorBackend rlocator, ForkNumber forknum,
                        LWLockMode mode)
{
    CfsRelMetaSlot *m;
 
    m = cfs_append_lock_find_slot(rlocator, forknum);
    if (m == NULL)
        ereport(ERROR,
                (errcode(ERRCODE_CONFIGURATION_LIMIT_EXCEEDED),
                 errmsg("CFS: could not acquire append lock for relation %u/%u/%u",
                        rlocator.locator.spcOid, rlocator.locator.dbOid,
                        rlocator.locator.relNumber),
                 errdetail("The relation has no metadata slot in shared memory."),
                 errhint("Increase the configuration parameter "
                         "\"cfs_map_cache_rels_per_partition\" and restart "
                         "the server.")));
 
    LWLockAcquire(&m->append_lock, mode);
}
 
/*
 * The non-blocking form for callers that must not wait out a long holder:
 * the checkpoint's handle open races an in-flight compaction (which holds
 * this lock across its whole copy + swap window), so it skips the
 * relation for one round instead of stalling behind it.  Returns false
 * without blocking when the lock is taken; the caller must hold a pin so
 * the slot outlives the call.
 */
bool
cfs_append_lock_try_acquire(RelFileLocatorBackend rlocator, ForkNumber forknum)
{
    CfsRelMetaSlot *m;
 
    m = cfs_append_lock_find_slot(rlocator, forknum);
    if (m == NULL)
        ereport(ERROR,
                (errcode(ERRCODE_CONFIGURATION_LIMIT_EXCEEDED),
                 errmsg("CFS: could not acquire append lock for relation %u/%u/%u",
                        rlocator.locator.spcOid, rlocator.locator.dbOid,
                        rlocator.locator.relNumber),
                 errdetail("The relation has no metadata slot in shared memory."),
                 errhint("Increase the configuration parameter "
                         "\"cfs_map_cache_rels_per_partition\" and restart "
                         "the server.")));
 
    return LWLockConditionalAcquire(&m->append_lock, LW_EXCLUSIVE);
}
 
void
cfs_shared_note_full_map_open(RelFileLocatorBackend rlocator,
                              ForkNumber forknum)
{
    CfsRelMetaSlot *m;
 
    if (cfs_control == NULL)
        return;
    pg_atomic_add_fetch_u64(&cfs_control->full_map_opens, 1);
 
    /*
     * The per-relation half (a slot may legitimately not exist yet for a
     * relation whose full handle is being opened for the very first time -
     * the global counter above already accounts for it).
     */
    m = cfs_append_lock_find_slot(rlocator, forknum);
    if (m != NULL)
        pg_atomic_add_fetch_u64(&m->full_map_opens, 1);
}
 
uint64
cfs_shared_full_map_opens_rel(RelFileLocatorBackend rlocator,
                              ForkNumber forknum)
{
    CfsRelMetaSlot *m;
 
    if (cfs_control == NULL)
        return 0;
    m = cfs_append_lock_find_slot(rlocator, forknum);
    if (m == NULL)
        return 0;
    return pg_atomic_read_u64(&m->full_map_opens);
}
 
void
cfs_append_lock_release(RelFileLocatorBackend rlocator, ForkNumber forknum)
{
    CfsRelMetaSlot *m;
 
    m = cfs_append_lock_find_slot(rlocator, forknum);
 
    /*
     * The slot must exist: the caller holds a pin (acquired when the
     * SMgrRelation handle was opened, or explicitly for compaction), so the
     * slot cannot have been evicted between acquire and release.  A missing
     * slot here is a logic bug, not a capacity issue — fail loudly instead
     * of silently leaving the append lock held.
     */
    Assert(m != NULL);
 
    /* The normal path consumes the holdoff credit from LWLockAcquire. */
    if (LWLockHeldByMe(&m->append_lock))
        LWLockRelease(&m->append_lock);
}
 
 
/*
 * Local ERROR unwinding happens before transaction abort.  errfinish has
 * reset InterruptHoldoffCount, even if this lock is still held.  As in
 * LWLockReleaseAll, preserve the current holdoff count while releasing the
 * owned lock.  Call only on error paths that propagate the exception.
 */
void
cfs_append_lock_release_after_error(RelFileLocatorBackend rlocator,
                                  ForkNumber forknum)
{
    CfsRelMetaSlot *m = cfs_append_lock_find_slot(rlocator, forknum);
 
    Assert(m != NULL);
    if (m != NULL && LWLockHeldByMe(&m->append_lock))
    {
        HOLD_INTERRUPTS();
        LWLockRelease(&m->append_lock);
    }
}
 
/* ================================================================
 * Authoritative .cfp tail (shared append cursor)
 * ================================================================ */
 
/*
 * Fetch the slot's authoritative .cfp tail.  Every non-IDLE state answers
 * false, so a crashed appender (IN_PROGRESS left behind), a failed pwrite
 * and a freshly created slot all send the caller down the
 * cfs_cfp_discover_eof() walk instead of a possibly-wrong offset.
 */
bool
cfs_cfp_tail_fetch(RelFileLocatorBackend rlocator, ForkNumber forknum,
                   uint64 *out_tail)
{
    CfsRelMetaSlot *m = cfs_append_lock_find_slot(rlocator, forknum);
 
    if (m == NULL ||
        m->cfp_append_state != CFS_CFP_APPEND_IDLE)
        return false;
 
    *out_tail = m->cfp_tail;
    return true;
}
 
/*
 * Mark the append in progress under the append lock.  The owner is
 * recorded for diagnostics only: a recycled ProcNumber never validates a
 * stale IN_PROGRESS, the state itself is what the next writer checks.
 */
void
cfs_cfp_tail_begin(RelFileLocatorBackend rlocator, ForkNumber forknum)
{
    CfsRelMetaSlot *m = cfs_append_lock_find_slot(rlocator, forknum);
 
    if (m == NULL)
        return;
 
    m->cfp_append_state = CFS_CFP_APPEND_IN_PROGRESS;
    m->cfp_append_proc = MyProcNumber;
}
 
/*
 * Publish the authoritative tail after a successful pwrite.  Must be
 * called under the append lock; the value is the aligned offset just past
 * the record the caller wrote.
 */
void
cfs_cfp_tail_commit(RelFileLocatorBackend rlocator, ForkNumber forknum,
                    uint64 new_tail)
{
    CfsRelMetaSlot *m = cfs_append_lock_find_slot(rlocator, forknum);
 
    if (m == NULL)
        return;
 
    m->cfp_tail = new_tail;
    m->cfp_append_state = CFS_CFP_APPEND_IDLE;
    m->cfp_append_proc = INVALID_PROC_NUMBER;
}
 
/*
 * Drop trust in the stored tail.  Used after a failed pwrite (the file end
 * is then whatever the failed write left behind) and whenever the sidecar
 * pair was replaced out from under the slot (compaction swap).
 */
void
cfs_cfp_tail_dirty(RelFileLocatorBackend rlocator, ForkNumber forknum)
{
    CfsRelMetaSlot *m = cfs_append_lock_find_slot(rlocator, forknum);
 
    if (m == NULL)
        return;
 
    m->cfp_append_state = CFS_CFP_APPEND_DIRTY;
    m->cfp_append_proc = INVALID_PROC_NUMBER;
}
 
/*
 * Online-compaction ownership mark (QDB-1514).  The pair (ProcNumber, pid)
 * is the liveness identity: a recycled ProcNumber points at some other
 * backend's PGPROC whose pid differs, and a dead backend's slot either is
 * free (pid 0) or belongs to a successor.  Both read as "not active", which
 * is exactly how a compaction whose backend died mid-copy must look to the
 * interrupted-swap recovery below the storage layer.
 */
void
cfs_compact_mark_active(RelFileLocatorBackend rlocator, ForkNumber forknum)
{
    CfsRelMetaSlot *m = cfs_append_lock_find_slot(rlocator, forknum);
 
    if (m == NULL)
        return;
 
    m->compact_proc = MyProcNumber;
    m->compact_pid = MyProcPid;
}
 
/*
 * Clear the mark.  Called on every completion path of the compaction that
 * set it; a leftover mark from a dead backend needs no cleanup (see above),
 * so a missed clear is safe, merely delaying orphan cleanup until the next
 * open after the backend exits.
 */
void
cfs_compact_mark_inactive(RelFileLocatorBackend rlocator, ForkNumber forknum)
{
    CfsRelMetaSlot *m = cfs_append_lock_find_slot(rlocator, forknum);
 
    if (m == NULL)
        return;
 
    m->compact_proc = INVALID_PROC_NUMBER;
    m->compact_pid = 0;
}
 
/*
 * The compaction provider of the ownership-state judge: is an online
 * compaction with a live owner running for this relation fork?  Reads the
 * mark without taking the append lock: the answer only gates the
 * interrupted-swap recovery, where a momentary stale "active" is harmless
 * (the real owner is still holding or about to take the append lock for the
 * swap) and a stale "inactive" is impossible while the owner lives.
 */
bool
cfs_map_cache_compaction_active(RelFileLocatorBackend rlocator,
                                ForkNumber forknum)
{
    CfsRelMetaSlot *m = cfs_append_lock_find_slot(rlocator, forknum);
    PGPROC     *owner;
 
    if (m == NULL || m->compact_proc == INVALID_PROC_NUMBER)
        return false;
 
    owner = GetPGProcByNumber(m->compact_proc);
 
    return owner->pid != 0 && owner->pid == m->compact_pid;
}
 
/*
 * Sidecar-open guard (QDB-1514), the shmem side of the state judge's hook:
 * a shared hold of the relation's append lock around lock-free sidecar
 * opens.  Skipped when this backend already holds the lock (any mode) —
 * checkpoint, fsck and the compactor itself serialize through their own
 * holds, and an LWLock must never be re-acquired by its holder.
 *
 * The slot is PINNED for the duration of the hold: the append lock lives
 * inside the slot, and the pin-before-lock contract of
 * cfs_append_lock_find_slot() is what keeps an evictable (refcount 0) slot
 * from being wiped — and its lock re-initialized — while we hold it.  The
 * caller of cfs_open_paths() pins the slot again after the open; the pair
 * of refcounts here is balanced by cfs_open_guard_release_impl().
 */
static bool
cfs_open_guard_acquire_impl(RelFileLocatorBackend rlocator, ForkNumber forknum)
{
    CfsRelMetaSlot *m;
 
    /*
     * May raise ERROR when the slot pool is exhausted — nothing is held
     * yet, and the smgr-level pin after the open would fail the same way
     * a moment later.
     */
    cfs_map_cache_pin(rlocator, forknum);
 
    m = cfs_append_lock_find_slot(rlocator, forknum);
    if (m == NULL)
    {
        cfs_map_cache_unpin(rlocator, forknum);
        return false;
    }
    if (LWLockHeldByMe(&m->append_lock))
    {
        cfs_map_cache_unpin(rlocator, forknum);
        return false;
    }
 
    LWLockAcquire(&m->append_lock, LW_SHARED);
    return true;
}
 
static void
cfs_open_guard_release_impl(RelFileLocatorBackend rlocator, ForkNumber forknum,
                            bool after_error)
{
    if (after_error)
        cfs_append_lock_release_after_error(rlocator, forknum);
    else
        cfs_append_lock_release(rlocator, forknum);
 
    /* The pin must outlive the lock, including on ERROR. */
    cfs_map_cache_unpin(rlocator, forknum);
}
 
/* ================================================================
 * Background worker control
 * ================================================================ */
 
void
cfs_bg_pause(int64 paused_until)
{
    Assert(cfs_bg_control != NULL && cfs_bg_lock != NULL);
 
    LWLockAcquire(&cfs_bg_lock->lock, LW_EXCLUSIVE);
    cfs_bg_control->paused = true;
    cfs_bg_control->paused_until = paused_until;
    LWLockRelease(&cfs_bg_lock->lock);
 
    ereport(DEBUG1,
            (errmsg("CFS bgworker paused%s",
                    paused_until != 0 ? " until expiry" : " indefinitely")));
}
 
void
cfs_bg_resume(void)
{
    Assert(cfs_bg_control != NULL && cfs_bg_lock != NULL);
 
    LWLockAcquire(&cfs_bg_lock->lock, LW_EXCLUSIVE);
    cfs_bg_control->paused = false;
    cfs_bg_control->paused_until = 0;
    LWLockRelease(&cfs_bg_lock->lock);
 
    ereport(DEBUG1, (errmsg("CFS bgworker resumed")));
}
 
/*
 * cfs_bg_expire_if_due — clear a timed pause whose deadline has passed.
 *
 * Writes the cleared pause state, so the caller must hold the bgworker lock
 * in LW_EXCLUSIVE mode.
 */
static void
cfs_bg_expire_if_due(void)
{
    if (cfs_bg_control->paused &&
        cfs_bg_control->paused_until != 0 &&
        (int64) GetCurrentTimestamp() >= cfs_bg_control->paused_until)
    {
        cfs_bg_control->paused = false;
        cfs_bg_control->paused_until = 0;
    }
}
 
bool
cfs_bg_is_paused(void)
{
    bool        result;
 
    Assert(cfs_bg_control != NULL && cfs_bg_lock != NULL);
 
    LWLockAcquire(&cfs_bg_lock->lock, LW_EXCLUSIVE);
 
    cfs_bg_expire_if_due();
 
    result = cfs_bg_control->paused;
 
    LWLockRelease(&cfs_bg_lock->lock);
    return result;
}
 
void
cfs_bg_set_cycle_started(void)
{
    Assert(cfs_bg_control != NULL && cfs_bg_lock != NULL);
 
    LWLockAcquire(&cfs_bg_lock->lock, LW_EXCLUSIVE);
    cfs_bg_control->last_cycle_started_at = (int64) GetCurrentTimestamp();
    LWLockRelease(&cfs_bg_lock->lock);
}
 
void
cfs_bg_set_cycle_finished(void)
{
    Assert(cfs_bg_control != NULL && cfs_bg_lock != NULL);
 
    LWLockAcquire(&cfs_bg_lock->lock, LW_EXCLUSIVE);
    cfs_bg_control->last_cycle_finished_at = (int64) GetCurrentTimestamp();
    LWLockRelease(&cfs_bg_lock->lock);
}
 
void
cfs_bg_history_set(Oid relid, TimestampTz ts)
{
    CfsBgHistoryKey key;
    CfsBgHistoryEntry *h;
    bool        found;
 
    Assert(cfs_bg_history_hash != NULL && cfs_bg_lock != NULL);
 
    /*
     * The entries are keyed by (database, relation): relids are unique only
     * within a database.  Both callers (the per-database worker and manual
     * pg_cfs_compact) always run with MyDatabaseId set.
     */
    key.dboid = MyDatabaseId;
    key.relid = relid;
 
    LWLockAcquire(&cfs_bg_lock->lock, LW_EXCLUSIVE);
    h = hash_search(cfs_bg_history_hash, &key, HASH_ENTER_NULL, &found);
    if (h == NULL)
    {
        /*
         * ponytail: more relations compacted within cfs_bg_min_interval_s
         * than CFS_BG_HISTORY_MAX.  Skipping the record costs this one
         * relation its throttle until the sweep frees space -- extra
         * background work, not a correctness problem.  Ceiling and upgrade
         * path: a GUC-sized hash.
         */
        if (!cfs_bg_history_overflow_logged)
        {
            cfs_bg_history_overflow_logged = true;
            ereport(LOG,
                    (errmsg("CFS: compaction history is full (%d entries); the minimum interval cannot be enforced for further relations until older entries expire",
                            CFS_BG_HISTORY_MAX)));
        }
    }
    else
        h->last_compact = (int64) ts;
    LWLockRelease(&cfs_bg_lock->lock);
}
 
TimestampTz
cfs_bg_history_get(Oid relid)
{
    CfsBgHistoryKey key;
    CfsBgHistoryEntry *h;
    TimestampTz result = 0;
 
    Assert(cfs_bg_history_hash != NULL && cfs_bg_lock != NULL);
 
    key.dboid = MyDatabaseId;
    key.relid = relid;
 
    LWLockAcquire(&cfs_bg_lock->lock, LW_SHARED);
    h = hash_search(cfs_bg_history_hash, &key, HASH_FIND, NULL);
    if (h != NULL)
        result = (TimestampTz) h->last_compact;
    LWLockRelease(&cfs_bg_lock->lock);
    return result;
}
 
void
cfs_bg_history_sweep(void)
{
    HASH_SEQ_STATUS status;
    CfsBgHistoryEntry *h;
    int64       horizon;
 
    if (cfs_bg_history_hash == NULL)
        return;
 
    /*
     * An entry older than the throttle window cannot matter: the interval it
     * exists to enforce has expired.  Retiring expired entries also retires
     * the entries of dropped relations without any catalog cross-check
     * (pgstat needs one for its persistent statistics; the history is
     * volatile, so ageing out is enough).  Increasing cfs_bg_min_interval_s
     * after a sweep may find earlier entries gone: one relation then risks a
     * single premature compaction, which is safe.
     */
    horizon = (int64) GetCurrentTimestamp() -
        (int64) cfs_bg_min_interval_s * USECS_PER_SEC;
 
    LWLockAcquire(&cfs_bg_lock->lock, LW_EXCLUSIVE);
 
    /*
     * The scan always runs to completion (hash_seq_search returns NULL), so
     * no hash_seq_term() is needed: per dynahash, terminating is only for
     * scans abandoned before completion, and removing entries along the way
     * is explicitly supported.
     */
    hash_seq_init(&status, cfs_bg_history_hash);
    while ((h = hash_seq_search(&status)) != NULL)
    {
        if (h->last_compact < horizon)
            hash_search(cfs_bg_history_hash, &h->key, HASH_REMOVE, NULL);
    }
    LWLockRelease(&cfs_bg_lock->lock);
 
    /* Room may have been freed: re-arm the overflow notice. */
    cfs_bg_history_overflow_logged = false;
}
 
void
cfs_bg_get_status(CfsBgStatus *out)
{
    Assert(cfs_bg_control != NULL && cfs_bg_lock != NULL && out != NULL);
 
    LWLockAcquire(&cfs_bg_lock->lock, LW_EXCLUSIVE);
 
    cfs_bg_expire_if_due();
 
    out->paused = cfs_bg_control->paused;
    out->paused_until = cfs_bg_control->paused_until;
    out->last_cycle_started_at = cfs_bg_control->last_cycle_started_at;
    out->last_cycle_finished_at = cfs_bg_control->last_cycle_finished_at;
 
    LWLockRelease(&cfs_bg_lock->lock);
}
 
/* ================================================================
 * Relation metadata (helpers for the map cache)
 * ================================================================ */
 
/*
 * Per-partition hash chains over the metadata slots (QDB-1516 Д2).  The
 * invariants I1-I3 are stated in cfs_shmem_internal.h; all helpers below
 * mutate chains only under LW_EXCLUSIVE of the partition.
 */
 
/*
 * Bucket of a key inside its partition: the hash bits that do not select
 * the partition, run through a multiplicative mix (Knuth's 2654435761).
 * The partition is selected by the low CFS_PART_BITS bits; the multiply
 * folds those (and every other input bit) back into the bits the modulo
 * keeps, so the choice of partition and the choice of chain do not
 * correlate even though the underlying hash is a simple polynomial.
 */
static inline int
cfs_meta_bucket(uint32 rel_hash)
{
    uint32      b = rel_hash * 2654435761U;
 
    return (int) ((b >> CFS_PART_BITS) %
                  (uint32) cfs_map_cache_rels_per_partition);
}
 
/* The bucket-head cell (part, bucket) of the metadata chains. */
static inline int32 *
cfs_meta_head(int part, int bucket)
{
    return &cfs_map_bucket_heads[part * cfs_map_cache_rels_per_partition +
                                 bucket];
}
 
/* Partition-relative index of a metadata slot. */
static inline int
cfs_meta_slot_index(int part, const CfsRelMetaSlot *slot)
{
    return (int) (slot -
                  &cfs_rel_meta[part * cfs_map_cache_rels_per_partition]);
}
 
/*
 * Link an occupied slot at the head of its bucket chain.  The caller holds
 * the partition lock exclusively; the slot is populated (hash set) and not
 * in any chain yet.
 */
static void
cfs_meta_chain_link(int part, CfsRelMetaSlot *slot)
{
    int         bucket = cfs_meta_bucket(slot->hash);
    int32      *head = cfs_meta_head(part, bucket);
 
    slot->chain_next = *head;
    *head = cfs_meta_slot_index(part, slot);
}
 
/*
 * Unlink an occupied slot from its chain.  The caller holds the partition
 * lock exclusively.  Must run BEFORE the slot is cleared (invariant I3):
 * it walks the slot's own chain to find the predecessor.
 */
static void
cfs_meta_chain_unlink(int part, CfsRelMetaSlot *slot)
{
    int         idx = cfs_meta_slot_index(part, slot);
    int         bucket = cfs_meta_bucket(slot->hash);
    int32      *head = cfs_meta_head(part, bucket);
    int         cur = *head;
    int         prev = -1;
 
    Assert(slot->hash != 0);
    Assert(cur != -1);          /* an occupied slot is always chained (I1) */
    while (cur != idx)
    {
        /* A broken I1 must error out, not read slot(part, -1). */
        if (cur == -1)
            elog(ERROR, "CFS: relation metadata slot %d not found in its "
                 "hash chain", idx);
        prev = cur;
        cur = cfs_rel_meta_slot(part, cur)->chain_next;
    }
    if (prev == -1)
        *head = slot->chain_next;
    else
        cfs_rel_meta_slot(part, prev)->chain_next = slot->chain_next;
}
 
/*
 * Rebuild one partition's bucket heads from its occupied slots.  The
 * caller holds the partition lock exclusively.  Used after bulk clears
 * (DROP DATABASE) that clear slots without unlinking them one by one;
 * surviving occupied slots are re-linked at their buckets' heads, and the
 * cleared slots stay free (I1).
 */
static void
cfs_meta_heads_rebuild(int part)
{
    int         nslots = cfs_map_cache_rels_per_partition;
    int         i;
 
    MemSet(cfs_meta_head(part, 0), 0xFF, mul_size(sizeof(int32), nslots));
    for (i = 0; i < nslots; i++)
    {
        CfsRelMetaSlot *m = cfs_rel_meta_slot(part, i);
 
        if (m->hash != 0)
        {
            int         bucket = cfs_meta_bucket(m->hash);
            int32      *head = cfs_meta_head(part, bucket);
 
            m->chain_next = *head;
            *head = i;
        }
    }
}
 
/*
 * Locate the metadata slot for a relation by walking its hash chain.  The
 * caller must hold the lock of the partition selected by rel_hash (in
 * LW_SHARED or LW_EXCLUSIVE mode); touching the slot without that lock is
 * a data race.  Returns NULL when none exists.
 */
static CfsRelMetaSlot *
cfs_meta_find(uint32 rel_hash, RelFileLocatorBackend rlocator,
              ForkNumber forknum)
{
    int         part = rel_hash & CFS_PART_MASK;
    int         bucket = cfs_meta_bucket(rel_hash);
    int         cur;
 
    Assert(LWLockHeldByMe(&cfs_map_locks[part].lock));
 
    for (cur = *cfs_meta_head(part, bucket); cur != -1;)
    {
        CfsRelMetaSlot *m = cfs_rel_meta_slot(part, cur);
        int         next = m->chain_next;
 
        if (m->hash == rel_hash &&
            cfs_rlbe_eq(m->rlocator, rlocator) &&
            m->forknum == forknum)
            return m;
        cur = next;
    }
    return NULL;
}
 
/*
 * Find or create a metadata slot.  The caller must hold the lock of the
 * partition selected by rel_hash in LW_EXCLUSIVE mode.
 *
 * Creation order (QDB-1516 Д2): the key's own chain is searched first;
 * on a miss the first free slot (hash == 0) of the partition is taken by
 * a plain scan — a per-partition LIFO free list was judged not worth the
 * extra shared state at <= CFS_MAP_CACHE_MAX_RELS_PER_PART slots — and
 * only when no free slot remains is an LRU victim chosen by a full
 * partition scan and unlinked from ITS chain before being cleared (I3).
 * A newly claimed slot is linked at the head of its bucket.
 *
 * Returns NULL when every slot of the partition is pinned or dirty for
 * checkpoint.  The caller MUST check for NULL and raise ERROR (via
 * cfs_meta_overflow_error) AFTER releasing the partition lock — raising
 * ERROR from here would longjmp past the caller's LWLockRelease and leak
 * the partition lock.
 */
static CfsRelMetaSlot *
cfs_meta_get_or_create(uint32 rel_hash, RelFileLocatorBackend rlocator,
                       ForkNumber forknum)
{
    int         part = rel_hash & CFS_PART_MASK;
    int         bucket = cfs_meta_bucket(rel_hash);
    CfsRelMetaSlot *free_slot = NULL;
    CfsRelMetaSlot *victim = NULL;
    uint64      min_clock = PG_UINT64_MAX;
    int         i;
    int         cur;
 
    Assert(LWLockHeldByMeInMode(&cfs_map_locks[part].lock, LW_EXCLUSIVE));
 
    /* Search the key's own chain (the hit path of the partition). */
    for (cur = *cfs_meta_head(part, bucket); cur != -1;)
    {
        CfsRelMetaSlot *m = cfs_rel_meta_slot(part, cur);
        int         next = m->chain_next;
 
        if (m->hash == rel_hash &&
            cfs_rlbe_eq(m->rlocator, rlocator) &&
            m->forknum == forknum)
            return m;
        cur = next;
    }
 
    /* Miss: take the first free slot of the partition. */
    for (i = 0; i < cfs_map_cache_rels_per_partition; i++)
    {
        CfsRelMetaSlot *m = cfs_rel_meta_slot(part, i);
 
        if (m->hash == 0)
        {
            free_slot = m;
            break;
        }
    }
 
    /*
     * No free slot: LRU victim among all occupied slots (a full partition
     * scan, as before the chains).  Never evict a dirty-checkpoint slot -
     * a relation that was written since the last checkpoint must survive
     * until the checkpointer has fsync'd its sidecars - and never a pinned
     * one.  The victim is unlinked from its own chain BEFORE the clear
     * (invariant I3).
     */
    if (free_slot == NULL)
    {
        for (i = 0; i < cfs_map_cache_rels_per_partition; i++)
        {
            CfsRelMetaSlot *m = cfs_rel_meta_slot(part, i);
 
            if (m->hash != 0 &&
                m->refcount == 0 && !m->dirty_checkpoint &&
                m->access_clock < min_clock)
            {
                min_clock = m->access_clock;
                victim = m;
            }
        }
 
        free_slot = victim;
        if (free_slot != NULL)
        {
            pg_atomic_fetch_add_u64(&cfs_control->evictions, 1);
            cfs_meta_chain_unlink(part, free_slot);
            MemSet(free_slot, 0, sizeof(CfsRelMetaSlot));
        }
    }
 
    if (free_slot == NULL)
        return NULL;            /* partition full of pinned/dirty relations */
 
    free_slot->hash = rel_hash;
    free_slot->rlocator = rlocator;
    free_slot->forknum = forknum;
    free_slot->generation = 0;
    free_slot->refcount = 0;
    free_slot->access_clock = cfs_map_clock_tick(part);
 
    /*
     * A freshly claimed slot knows nothing about the .cfp chain end: start
     * untrusted so the first writer re-discovers it (the D1 tail protocol;
     * cfp_tail stays zero and is never read while the state is DIRTY).
     */
    free_slot->cfp_tail = 0;
    free_slot->cfp_append_state = CFS_CFP_APPEND_DIRTY;
    free_slot->cfp_append_proc = INVALID_PROC_NUMBER;
    free_slot->compact_proc = INVALID_PROC_NUMBER;
    free_slot->compact_pid = 0;
    pg_atomic_init_u32(&free_slot->next_generation, 0);
    pg_atomic_init_u64(&free_slot->full_map_opens, 0);
    free_slot->generation_initialized = false;
 
    /*
     * Initialise the embedded per-relation append lock.  The slot was just
     * claimed (fresh or evicted-and-zeroed), so the lock state is undefined;
     * LWLockInitialize() resets it to the unlocked state with the correct
     * tranche id for wait-event display.
     */
    LWLockInitialize(&free_slot->append_lock, cfs_control->append_tranche_id);
 
    /* Insert the claimed slot at the head of its bucket chain (I2). */
    cfs_meta_chain_link(part, free_slot);
    return free_slot;
}
 
/*
 * Raise the slot-exhaustion ERROR.  Must be called AFTER releasing the
 * partition lock so the longjmp does not leak it.
 */
static void
cfs_meta_overflow_error(RelFileLocatorBackend rlocator, int part)
{
    ereport(ERROR,
            (errcode(ERRCODE_CONFIGURATION_LIMIT_EXCEEDED),
             errmsg("CFS: out of relation metadata slots for relation %u/%u/%u",
                    rlocator.locator.spcOid, rlocator.locator.dbOid,
                    rlocator.locator.relNumber),
             errdetail("All %d slots in cache partition %d are pinned or dirty "
                       "for checkpoint.",
                       cfs_map_cache_rels_per_partition, part),
             errhint("Increase the configuration parameter "
                     "\"cfs_map_cache_rels_per_partition\" and restart the server.")));
}
 
/*
 * Warn about slot exhaustion on a post-commit path, where raising ERROR is
 * no longer safe: the commit is already durable and cannot be rolled back
 * (a vanilla post-commit step degrades instead of failing).  The policy
 * stays in the catalog; the next open of the relation republishes it
 * through cfs_open_relation_smgr().
 */
static void
cfs_meta_overflow_warning(RelFileLocatorBackend rlocator, int part)
{
    ereport(WARNING,
            (errcode(ERRCODE_CONFIGURATION_LIMIT_EXCEEDED),
             errmsg("CFS: could not publish the policy for relation %u/%u/%u after commit",
                    rlocator.locator.spcOid, rlocator.locator.dbOid,
                    rlocator.locator.relNumber),
             errdetail("All %d slots in cache partition %d are pinned or dirty "
                       "for checkpoint.",
                       cfs_map_cache_rels_per_partition, part),
             errhint("The policy will be republished the next time the relation is "
                     "opened. To avoid this, increase the configuration parameter "
                     "\"cfs_map_cache_rels_per_partition\" and restart the server.")));
}
 
/* ================================================================
 * Relation metadata cache
 * ================================================================ */
 
void
cfs_map_cache_invalidate(RelFileLocatorBackend rlocator, ForkNumber forknum)
{
    uint32      rel_hash = cfs_cache_hash_rel(rlocator, forknum);
 
    Assert(cfs_control != NULL);
 
    /*
     * Drop the metadata slot under its own partition lock.  Block entries
     * live in the shared segment pool and are dropped by the caller through
     * cfs_shared_map_invalidate_relation().
     */
    {
        int         mpart = rel_hash & CFS_PART_MASK;
        CfsRelMetaSlot *m;
 
        LWLockAcquire(&cfs_map_locks[mpart].lock, LW_EXCLUSIVE);
        m = cfs_meta_find(rel_hash, rlocator, forknum);
        if (m != NULL)
        {
            /* Unlink from the chain before the clear (invariant I3). */
            cfs_meta_chain_unlink(mpart, m);
            MemSet(m, 0, sizeof(CfsRelMetaSlot));
        }
        LWLockRelease(&cfs_map_locks[mpart].lock);
    }
 
    /*
     * Statistics are deliberately NOT reset here: wiping the counters would
     * destroy the pg_stat_cfs signal (including crc_failures) without the
     * user asking for it.  Counters survive until an explicit
     * pg_cfs_reset_stats() (or slot eviction); a stale row for a dropped
     * relation is reclaimed by the statistics LRU.
     */
    ereport(DEBUG1,
            (errmsg("CFS: invalidated cache entries for relation %u/%u/%u",
                    rlocator.locator.spcOid, rlocator.locator.dbOid,
                    rlocator.locator.relNumber)));
}
 
/*
 * cfs_drop_database_caches — drop every shared-memory cache entry that
 * belongs to a database being dropped: cached page-map entries, per-relation
 * metadata and published policies.  Called from DROP DATABASE (and its WAL
 * redo) alongside DropDatabaseBuffers()/ForgetDatabaseSyncRequests(): the
 * database directory is removed wholesale, without per-relation smgr unlink
 * processing, so without this sweep the entries would survive and confuse a
 * relation that later reuses the same (tablespace, database, relfilenumber)
 * key — a stale block mapping would then read a foreign .cfp offset.
 *
 * Statistics slots are deliberately kept (see cfs_map_cache_invalidate).
 */
void
cfs_drop_database_caches(Oid dbid)
{
    int         part;
    int         i;
 
    Assert(cfs_control != NULL);
 
    /*
     * Relation-metadata slots are spread across every partition, so sweep
     * them all under each partition lock.  This is O(NUM_PARTITIONS *
     * RELS_PER_PART) but runs only on DROP DATABASE. Block entries live in
     * the shared segment pool and are dropped through
     * cfs_shared_map_invalidate_relation() per relation.
     */
    for (part = 0; part < CFS_MAP_CACHE_NUM_PARTITIONS; part++)
    {
        LWLockAcquire(&cfs_map_locks[part].lock, LW_EXCLUSIVE);
 
        for (i = 0; i < cfs_map_cache_rels_per_partition; i++)
        {
            CfsRelMetaSlot *m = cfs_rel_meta_slot(part, i);
 
            if (m->hash != 0 && m->rlocator.locator.dbOid == dbid)
                MemSet(m, 0, sizeof(CfsRelMetaSlot));
        }
 
        /*
         * The clears above broke the chains: rebuild the partition's
         * bucket heads wholesale (simpler than unlinking every dropped
         * slot, and DROP DATABASE is rare).  Surviving occupied slots are
         * re-linked; the cleared slots stay free (I1).
         */
        cfs_meta_heads_rebuild(part);
 
        LWLockRelease(&cfs_map_locks[part].lock);
    }
 
    /*
     * Drop only this database's segments.  Segment keys carry dbOid, so a
     * relation of another database can never share them; resetting the whole
     * pool would throw away every other database's warm segments (and, in WAL
     * redo, make the startup process sweep a large pool).
     */
    cfs_shared_map_invalidate_db(dbid);
 
    ereport(DEBUG1,
            (errmsg("CFS: invalidated cache entries for dropped database %u",
                    dbid)));
}
 
void
cfs_map_cache_compact_reset(RelFileLocatorBackend rlocator, ForkNumber forknum)
{
    uint32      rel_hash = cfs_cache_hash_rel(rlocator, forknum);
 
    Assert(cfs_control != NULL);
 
    /*
     * Compaction rewrote the .cfp (every physical offset changed) and the
     * caller drops the relation's pool segments separately.  What remains
     * here is the metadata slot: bump the generation (so any in-flight
     * readers notice the offset change) and, crucially, mark dirty_checkpoint
     * so the next CfsCheckpoint() still finds this relation (the policy
     * fields are preserved) and snapshots the freshly compacted map. Unlike
     * cfs_map_cache_invalidate(), the slot is kept alive.
     */
    {
        int         mpart = rel_hash & CFS_PART_MASK;
        CfsRelMetaSlot *m;
 
        LWLockAcquire(&cfs_map_locks[mpart].lock, LW_EXCLUSIVE);
        m = cfs_meta_find(rel_hash, rlocator, forknum);
        if (m != NULL)
        {
            m->generation++;
            m->access_clock = cfs_map_clock_tick(mpart);
            m->dirty_checkpoint = true;
 
            /*
             * The compaction replaced the whole .cfp chain: the stored tail
             * describes the replaced inode pair and must not be trusted.
             */
            m->cfp_append_state = CFS_CFP_APPEND_DIRTY;
            m->cfp_append_proc = INVALID_PROC_NUMBER;
        }
        LWLockRelease(&cfs_map_locks[mpart].lock);
    }
 
    ereport(DEBUG1,
            (errmsg("CFS: reset cache after compaction for relation %u/%u/%u",
                    rlocator.locator.spcOid, rlocator.locator.dbOid,
                    rlocator.locator.relNumber)));
}
 
uint64
cfs_map_cache_get_generation(RelFileLocatorBackend rlocator, ForkNumber forknum)
{
    uint32      rel_hash = cfs_cache_hash_rel(rlocator, forknum);
    int         part = rel_hash & CFS_PART_MASK;
    CfsRelMetaSlot *m;
    uint64      generation = 0;
 
    Assert(cfs_control != NULL);
 
    LWLockAcquire(&cfs_map_locks[part].lock, LW_SHARED);
    m = cfs_meta_find(rel_hash, rlocator, forknum);
    if (m != NULL)
        generation = m->generation;
    LWLockRelease(&cfs_map_locks[part].lock);
 
    return generation;
}
 
uint32
cfs_map_cache_next_generation(CfsRelation *cfs)
{
    CfsRelMetaSlot *m;
 
    m = cfs_append_lock_find_slot(cfs->rlocator, cfs->forknum);
    Assert(m != NULL);
    Assert(LWLockHeldByMe(&m->append_lock));
 
    if (!m->generation_initialized)
    {
        uint32      max_gen;
 
        /*
         * cfs_generation_summary() seeds from the in-memory map, the journal
         * header watermark (stamped by every journal reset, so it survives
         * map truncation) and every UPDATE the journal still holds beyond its
         * last reset (the header may predate the journal tail). Durability of
         * the referenced .cfp bytes is not checked here: a generation is
         * occupied once its journal record exists, even when replay would
         * later skip the record.
         *
         * The scan reads the whole journal of the relation under the
         * exclusive append lock.  It is a one-time cost per metadata slot:
         * m->generation_initialized stays set until the slot is evicted
         * (which needs the relation to be closed), so steady-state writes
         * only consume the atomic counter.
         */
        if (cfs_generation_summary(cfs, &max_gen) != CFS_STORAGE_OK)
            ereport(ERROR,
                    (errcode_for_file_access(),
                     errmsg("CFS: could not scan journal for relation %u/%u/%u",
                            cfs->rlocator.locator.spcOid,
                            cfs->rlocator.locator.dbOid,
                            cfs->rlocator.locator.relNumber)));
 
        pg_atomic_write_u32(&m->next_generation, max_gen);
        m->generation_initialized = true;
    }
 
    return pg_atomic_add_fetch_u32(&m->next_generation, 1);
}
 
void
cfs_handle_refresh_if_stale(CfsRelation *cfs)
{
    uint64      generation;
 
    Assert(cfs != NULL);
 
    generation = cfs_map_cache_get_generation(cfs->rlocator, cfs->forknum);
    if (generation == cfs->open_generation)
        return;
 
    /*
     * The generation moved: a compaction swapped the sidecar files while we
     * were waiting for the append lock.  The old descriptors point at the
     * replaced inode, so writing through them would be lost silently. Reopen
     * and continue on the new pair.  cfs_reopen() retags the handle with the
     * current generation; the generation cannot move again while we hold the
     * append lock.
     */
    ereport(DEBUG1,
            (errmsg("CFS: refreshing stale handle for relation %u/%u/%u "
                    "(generation %llu -> %llu)",
                    cfs->rlocator.locator.spcOid,
                    cfs->rlocator.locator.dbOid,
                    cfs->rlocator.locator.relNumber,
                    (unsigned long long) cfs->open_generation,
                    (unsigned long long) generation)));
 
    cfs_reopen(cfs);
}
 
void
cfs_map_cache_truncate(RelFileLocatorBackend rlocator, ForkNumber forknum,
                       BlockNumber nblocks)
{
    uint32      rel_hash = cfs_cache_hash_rel(rlocator, forknum);
 
    Assert(cfs_control != NULL);
 
    /*
     * Shrink the cached logical size under the metadata slot's own partition
     * lock (selected by rel_hash; the sweep above only holds the block-entry
     * partition locks).  Done exactly once, not per sweep iteration.
     */
    {
        int         mpart = rel_hash & CFS_PART_MASK;
        CfsRelMetaSlot *m;
 
        LWLockAcquire(&cfs_map_locks[mpart].lock, LW_EXCLUSIVE);
        m = cfs_meta_find(rel_hash, rlocator, forknum);
        if (m != NULL)
        {
            m->generation++;
            m->nblocks = Min(m->nblocks, (uint64) nblocks);
            m->access_clock = cfs_map_clock_tick(mpart);
        }
        LWLockRelease(&cfs_map_locks[mpart].lock);
    }
}
 
/* ================================================================
 * Map cache: pinning
 * ================================================================ */
 
void
cfs_map_cache_pin(RelFileLocatorBackend rlocator, ForkNumber forknum)
{
    uint32      rel_hash = cfs_cache_hash_rel(rlocator, forknum);
    int         part = rel_hash & CFS_PART_MASK;
    CfsRelMetaSlot *m;
    bool        reaped = false;
 
    LWLockAcquire(&cfs_map_locks[part].lock, LW_EXCLUSIVE);
    m = cfs_meta_get_or_create(rel_hash, rlocator, forknum);
    if (m == NULL)
    {
        /*
         * Every slot of the partition is pinned or dirty.  Pins of processes
         * that died hard never unpinned themselves - reap them once before
         * giving up (cfs_map_slot_reap_dead_pins takes ALL partition locks
         * itself, so drop ours first).  The overflow ERROR must be raised
         * with no partition lock held: ereport(ERROR) would longjmp past
         * LWLockRelease and leak the lock.
         */
        LWLockRelease(&cfs_map_locks[part].lock);
        if (!reaped && cfs_map_slot_reap_dead_pins(false))
        {
            reaped = true;
            LWLockAcquire(&cfs_map_locks[part].lock, LW_EXCLUSIVE);
            m = cfs_meta_get_or_create(rel_hash, rlocator, forknum);
            if (m == NULL)
                LWLockRelease(&cfs_map_locks[part].lock);
        }
        if (m == NULL)
            cfs_meta_overflow_error(rlocator, part);
    }
    cfs_map_pin_track(rlocator, forknum, rel_hash);
    m->refcount++;
    m->access_clock = cfs_map_clock_tick(part);
    LWLockRelease(&cfs_map_locks[part].lock);
}
 
/*
 * Record this process's pin of the relation's slot in the pin-owner
 * registry (or bump the count of an existing record).  The caller holds
 * the partition lock selected by part.
 */
static void
cfs_map_pin_track(RelFileLocatorBackend rlocator, ForkNumber forknum,
                  uint32 rel_hash)
{
    CfsMapPinKey key;
    CfsMapPinOwner *owner;
    uint32      pin_hash;
    bool        found;
 
    if (cfs_map_pin_live == NULL)
        return;
 
    pin_hash = cfs_map_pin_key_hash(rlocator, forknum, MyProcNumber,
                                    &key, rel_hash);
    owner = (CfsMapPinOwner *)
        hash_search_with_hash_value(cfs_map_pin_live, &key, pin_hash,
                                    HASH_ENTER_NULL, &found);
    if (owner == NULL)
    {
        /*
         * ponytail: the registry holds cfs_map_pin_registry_size() owners; a
         * backend pinning more relations than that loses the death protection
         * for the excess pins - the pins themselves keep working, only the
         * reaper cannot return them later.  Ceiling and upgrade path: size
         * the hash from a GUC.
         */
        if (!cfs_pin_registry_overflow_logged)
        {
            cfs_pin_registry_overflow_logged = true;
            ereport(LOG,
                    (errmsg("CFS: pin-owner registry is full (%d entries); pins left by processes that die hard cannot be reclaimed",
                            cfs_map_pin_registry_size())));
        }
        return;
    }
    if (!found || owner->owner_pid != MyProcPid ||
        owner->owner_epoch != cfs_map_owner_epoch_get())
    {
        /*
         * A fresh record, one recycled from the dynahash freelist, or one
         * adopted from a dead predecessor on this ProcNumber: dynahash copies
         * only the key into a (re)used element, and a recycled ProcNumber
         * reuses the key as well, so the payload - and with a dead
         * predecessor its slot pins - must be returned here, not inferred
         * from a zero pin_count.
         */
        if (found && owner->pin_count > 0)
        {
            CfsRelMetaSlot *m = cfs_meta_find(rel_hash, rlocator, forknum);
 
            if (m != NULL)
                m->refcount = (m->refcount > (uint32) owner->pin_count) ?
                    m->refcount - owner->pin_count : 0;
        }
        owner->owner_pid = MyProcPid;
        owner->owner_epoch = cfs_map_owner_epoch_get();
        owner->pin_count = 0;
    }
    owner->pin_count++;
}
 
/*
 * Drop one pin of this process from the registry.  The caller holds the
 * partition lock selected by rel_hash.
 */
static void
cfs_map_pin_untrack(RelFileLocatorBackend rlocator, ForkNumber forknum,
                    uint32 rel_hash)
{
    CfsMapPinKey key;
    CfsMapPinOwner *owner;
    uint32      pin_hash;
 
    if (cfs_map_pin_live == NULL)
        return;
 
    pin_hash = cfs_map_pin_key_hash(rlocator, forknum, MyProcNumber,
                                    &key, rel_hash);
    owner = (CfsMapPinOwner *)
        hash_search_with_hash_value(cfs_map_pin_live, &key, pin_hash,
                                    HASH_FIND, NULL);
    if (owner != NULL && owner->pin_count > 0 && --owner->pin_count == 0)
        hash_search_with_hash_value(cfs_map_pin_live, &key, pin_hash,
                                    HASH_REMOVE, NULL);
}
 
/*
 * Reap pins whose owner died hard: walk the pin-owner registry, and for
 * every record whose (procno, pid, epoch) no longer names a live process,
 * return its pins to the slot and drop the record.  Returns true when
 * anything was reaped.
 */
static bool
cfs_map_slot_reap_dead_pins(bool force)
{
    HASH_SEQ_STATUS status;
    CfsMapPinOwner *owner;
    bool        reaped = false;
    int         i;
 
    if (cfs_map_pin_live == NULL)
        return false;
 
    /*
     * Throttle repeated empty sweeps: a partition saturated with live pins
     * would otherwise repeat this stop-the-world scan (all partition locks
     * exclusively) on every failed pin attempt.  The timestamp is set only by
     * a sweep that reaped nothing and cleared by one that reaped, so a rescue
     * is delayed by at most the retry interval, never lost.
     */
    if (!force &&
        pg_atomic_read_u64(&cfs_control->map_pin_reap_empty_at) != 0 &&
        (uint64) GetCurrentTimestamp() -
        pg_atomic_read_u64(&cfs_control->map_pin_reap_empty_at) <
        CFS_PIN_REAP_EMPTY_RETRY_USECS)
        return false;
 
    /*
     * The pg_locks pattern (GetLockStatusData in lock.c): hold every
     * partition lock of the table for the whole scan.  dynahash requires at
     * least a shared lock on all partitions throughout hash_seq_search and
     * tolerates no concurrent insertions or deletions by other backends; our
     * removals make them exclusive.  With all locks held no track or untrack
     * can run, two reapers serialise on partition 0 instead of racing for one
     * record, and deleting the returned element is the one deletion dynahash
     * explicitly allows during a scan.  The scan always runs to completion,
     * so no hash_seq_term() is needed.
     */
    for (i = 0; i < CFS_MAP_CACHE_NUM_PARTITIONS; i++)
        LWLockAcquire(&cfs_map_locks[i].lock, LW_EXCLUSIVE);
 
    hash_seq_init(&status, cfs_map_pin_live);
    while ((owner = (CfsMapPinOwner *) hash_seq_search(&status)) != NULL)
    {
        uint32      rel_hash;
        CfsRelMetaSlot *m;
        bool        removed;
        int         pin_count;
 
        if (cfs_map_owner_alive(owner->key.procno, owner->owner_pid,
                                owner->owner_epoch))
            continue;
 
        rel_hash = cfs_cache_hash_rel(owner->key.rlocator,
                                      owner->key.forknum);
        m = cfs_meta_find(rel_hash, owner->key.rlocator, owner->key.forknum);
        pin_count = owner->pin_count;
        (void) hash_search_with_hash_value(cfs_map_pin_live, &owner->key,
                                           cfs_map_pin_hash(&owner->key,
                                                            rel_hash),
                                           HASH_REMOVE, &removed);
        if (removed)
        {
            if (m != NULL)
                m->refcount = (m->refcount > pin_count) ?
                    m->refcount - pin_count : 0;
            reaped = true;
        }
    }
 
    for (i = 0; i < CFS_MAP_CACHE_NUM_PARTITIONS; i++)
        LWLockRelease(&cfs_map_locks[i].lock);
 
    pg_atomic_write_u64(&cfs_control->map_pin_reap_empty_at,
                        reaped ? 0 : (uint64) GetCurrentTimestamp());
 
    return reaped;
}
 
/*
 * Test hook: raise a slot's refcount on behalf of a process that is
 * already dead (a negative procno can never name a live backend, and
 * never the caller's own), recording the pin in the registry exactly
 * like cfs_map_cache_pin() would have.  Returns the partition the slot
 * lives in, so the caller can fill it.
 */
int
cfs_map_cache_test_pin_orphan(RelFileLocatorBackend rlocator,
                              ForkNumber forknum)
{
    uint32      rel_hash = cfs_cache_hash_rel(rlocator, forknum);
    int         part = rel_hash & CFS_PART_MASK;
    CfsRelMetaSlot *m;
    CfsMapPinKey key;
    CfsMapPinOwner *owner;
 
    LWLockAcquire(&cfs_map_locks[part].lock, LW_EXCLUSIVE);
    m = cfs_meta_get_or_create(rel_hash, rlocator, forknum);
    if (m != NULL)
        m->refcount++;
    if (cfs_map_pin_live != NULL)
    {
        uint32      pin_hash;
 
        pin_hash = cfs_map_pin_key_hash(rlocator, forknum, -1, &key,
                                        rel_hash);
        owner = (CfsMapPinOwner *)
            hash_search_with_hash_value(cfs_map_pin_live, &key, pin_hash,
                                        HASH_ENTER, NULL);
        if (owner != NULL)
        {
            owner->owner_pid = 0;
            owner->owner_epoch = 0;
            owner->pin_count = 1;
        }
    }
    LWLockRelease(&cfs_map_locks[part].lock);
    return part;
}
 
/*
 * Test hook: run the dead-pin reaper directly and report whether it
 * reaped anything.  Used by test_cfs to prove reaper idempotence: a
 * second run must find nothing and must not touch any refcount again.
 * The call bypasses and clears the empty-sweep throttle so the suite
 * stays deterministic no matter when it runs.
 */
bool
cfs_map_cache_test_reap_dead_pins(void)
{
    bool        reaped;
 
    pg_atomic_write_u64(&cfs_control->map_pin_reap_empty_at, 0);
    reaped = cfs_map_slot_reap_dead_pins(true);
    pg_atomic_write_u64(&cfs_control->map_pin_reap_empty_at, 0);
    return reaped;
}
 
/*
 * Test hook: the current refcount of the relation's metadata slot, or -1
 * when no slot exists.  Used by test_cfs to prove the reaper returns
 * exactly the dead owner's pins and never a live owner's.
 */
int
cfs_map_cache_test_slot_refcount(RelFileLocatorBackend rlocator,
                                 ForkNumber forknum)
{
    uint32      rel_hash = cfs_cache_hash_rel(rlocator, forknum);
    int         part = rel_hash & CFS_PART_MASK;
    CfsRelMetaSlot *m;
    int         refcount;
 
    LWLockAcquire(&cfs_map_locks[part].lock, LW_SHARED);
    m = cfs_meta_find(rel_hash, rlocator, forknum);
    refcount = (m != NULL) ? (int) m->refcount : -1;
    LWLockRelease(&cfs_map_locks[part].lock);
 
    return refcount;
}
 
/*
 * Test hook: does the pin-owner registry exist?  It must for every pool
 * size, including cfs_map_memory = 0, where metadata slots are pinned
 * and reaped just the same.
 */
bool
cfs_map_cache_test_pin_registry_live(void)
{
    return cfs_map_pin_live != NULL;
}
 
void
cfs_map_cache_unpin(RelFileLocatorBackend rlocator, ForkNumber forknum)
{
    uint32      rel_hash = cfs_cache_hash_rel(rlocator, forknum);
    int         part = rel_hash & CFS_PART_MASK;
    CfsRelMetaSlot *m;
 
    LWLockAcquire(&cfs_map_locks[part].lock, LW_EXCLUSIVE);
    m = cfs_meta_find(rel_hash, rlocator, forknum);
    if (m != NULL && m->refcount > 0)
    {
        m->refcount--;
        cfs_map_pin_untrack(rlocator, forknum, rel_hash);
 
        /*
         * The relation's segments may have become evictable: wake the
         * exhaustion memo of every backend (see cfs_shared_map_ensure).
         */
        pg_atomic_fetch_add_u64(&cfs_control->map_pool_churn, 1);
    }
    LWLockRelease(&cfs_map_locks[part].lock);
}
 
void
cfs_map_cache_release_relation(RelFileLocatorBackend rlocator,
                               ForkNumber forknum)
{
    uint32      rel_hash = cfs_cache_hash_rel(rlocator, forknum);
    int         part = rel_hash & CFS_PART_MASK;
    CfsRelMetaSlot *m;
 
    LWLockAcquire(&cfs_map_locks[part].lock, LW_EXCLUSIVE);
    m = cfs_meta_find(rel_hash, rlocator, forknum);
    if (m != NULL)
    {
        if (m->refcount > 0)
        {
            m->refcount--;
            cfs_map_pin_untrack(rlocator, forknum, rel_hash);
        }
        if (m->refcount == 0)
        {
            /*
             * Make the metadata slot reclaimable.  Cached block entries are
             * left in place; they will be evicted lazily by LRU pressure or
             * discarded by an explicit invalidate.  Unlink before the clear
             * (invariant I3).
             */
            cfs_meta_chain_unlink(part, m);
            MemSet(m, 0, sizeof(CfsRelMetaSlot));
            pg_atomic_fetch_add_u64(&cfs_control->map_pool_churn, 1);
        }
    }
    LWLockRelease(&cfs_map_locks[part].lock);
}
 
/* ================================================================
 * Map cache: relation metadata accessors
 * ================================================================ */
 
bool
cfs_map_cache_get_nblocks(RelFileLocatorBackend rlocator, ForkNumber forknum,
                          uint64 *out_nblocks)
{
    uint32      rel_hash = cfs_cache_hash_rel(rlocator, forknum);
    int         part = rel_hash & CFS_PART_MASK;
    CfsRelMetaSlot *m;
    bool        found = false;
 
    LWLockAcquire(&cfs_map_locks[part].lock, LW_SHARED);
    m = cfs_meta_find(rel_hash, rlocator, forknum);
    if (m != NULL)
    {
        *out_nblocks = m->nblocks;
        found = true;
    }
    LWLockRelease(&cfs_map_locks[part].lock);
    return found;
}
 
void
cfs_map_cache_set_meta(RelFileLocatorBackend rlocator, ForkNumber forknum,
                       uint64 nblocks)
{
    uint32      rel_hash = cfs_cache_hash_rel(rlocator, forknum);
    int         part = rel_hash & CFS_PART_MASK;
    CfsRelMetaSlot *m;
 
    LWLockAcquire(&cfs_map_locks[part].lock, LW_EXCLUSIVE);
    m = cfs_meta_get_or_create(rel_hash, rlocator, forknum);
    if (m == NULL)
    {
        LWLockRelease(&cfs_map_locks[part].lock);
        cfs_meta_overflow_error(rlocator, part);
    }
 
    /*
     * The logical size is monotonic under publication: a writer (bgwriter
     * flushing a stale page, an extender) may carry a private map whose
     * nblocks lags behind another backend's concurrent extension.  The
     * callers try to publish max(local, cached), but that read-modify-write
     * is not atomic: between the get_nblocks() and this set_meta() another
     * backend can advance the slot, and an unconditional store here would
     * clobber the larger value, regressing the authoritative size.  A later
     * P_NEW (smgrnblocks reads this slot) would then target an existing
     * block, raising "unexpected data beyond EOF".  Grow-only here, under the
     * partition lock, makes the regression impossible.  Truncation shrinks
     * the size through the dedicated cfs_map_cache_truncate() (which applies
     * Min() atomically under this same lock) before calling here, so the
     * grow-only rule never blocks a legitimate shrink.
     */
    if (nblocks > m->nblocks)
        m->nblocks = nblocks;
    m->access_clock = cfs_map_clock_tick(part);
 
    /*
     * Mark dirty so checkpoint fsyncs sidecars
     */
    if (m->is_cfs)
        m->dirty_checkpoint = true;
    LWLockRelease(&cfs_map_locks[part].lock);
 
    /* The statistics high-water mark: only grows, never shrinks here. */
    cfs_stats_note_logical_pages(rel_hash, rlocator, forknum, nblocks);
}
 
void
cfs_map_cache_mark_dirty(RelFileLocatorBackend rlocator, ForkNumber forknum)
{
    uint32      rel_hash = cfs_cache_hash_rel(rlocator, forknum);
    int         part = rel_hash & CFS_PART_MASK;
    CfsRelMetaSlot *m;
 
    LWLockAcquire(&cfs_map_locks[part].lock, LW_EXCLUSIVE);
    m = cfs_meta_find(rel_hash, rlocator, forknum);
 
    /*
     * A writer always holds a pinned slot (smgr open pins it), so a missing
     * slot means the relation is not open for writing; nothing to mark.
     */
    if (m != NULL)
    {
        m->access_clock = cfs_map_clock_tick(part);
        if (m->is_cfs)
            m->dirty_checkpoint = true;
    }
    LWLockRelease(&cfs_map_locks[part].lock);
}
 
void
cfs_map_cache_clear_dirty(RelFileLocatorBackend rlocator, ForkNumber forknum)
{
    uint32      rel_hash = cfs_cache_hash_rel(rlocator, forknum);
    int         part = rel_hash & CFS_PART_MASK;
    CfsRelMetaSlot *m;
 
    LWLockAcquire(&cfs_map_locks[part].lock, LW_EXCLUSIVE);
    m = cfs_meta_find(rel_hash, rlocator, forknum);
    if (m != NULL)
        m->dirty_checkpoint = false;
    LWLockRelease(&cfs_map_locks[part].lock);
}
 
/*
 * Common body of cfs_publish_options / cfs_publish_options_postcommit.
 * soft_overflow selects the slot-exhaustion behaviour: raise ERROR (safe
 * only while the transaction can still roll back) or degrade to a WARNING
 * and skip the entry (mandatory on post-commit paths).
 */
static uint64
cfs_publish_options_internal(RelFileLocatorBackend rlocator,
                             ForkNumber forknum,
                             const CfsEffectiveOptions *opts,
                             bool soft_overflow)
{
    uint32      rel_hash = cfs_cache_hash_rel(rlocator, forknum);
    int         part = rel_hash & CFS_PART_MASK;
    CfsRelMetaSlot *m;
    uint64      gen = 0;
 
    LWLockAcquire(&cfs_map_locks[part].lock, LW_EXCLUSIVE);
    m = cfs_meta_get_or_create(rel_hash, rlocator, forknum);
    if (m == NULL)
    {
        LWLockRelease(&cfs_map_locks[part].lock);
        if (soft_overflow)
        {
            cfs_meta_overflow_warning(rlocator, part);
            return 0;
        }
        cfs_meta_overflow_error(rlocator, part);
    }
    else
    {
        uint8       new_algo = opts->is_cfs ? (uint8) opts->algorithm : 0;
 
        /*
         * Bump the policy generation when the published policy actually
         * changes (a fresh slot counts as a change), so that SMgrRelation
         * holders — auxiliary processes in particular — notice and
         * re-resolve.  The is_cfs flag is compared explicitly: on a
         * codec-less build a valid policy is RAW (new_algo == 0), which a
         * plain cfs_algo comparison would miss.  The set-flags are part of
         * the comparison: a SET-vs-RESET of a field is a policy change even
         * when the resolved value happens to stay the same.  The generation
         * comes from the partition's map-domain access clock, which is
         * strictly increasing within the partition: a relation and every
         * observer of its policy always hash to the same partition, so a
         * generation can never collide with one observed from an
         * evicted-and-recreated slot (the ABA case; the clock is never reset
         * within a server run).
         */
        if (m->is_cfs != opts->is_cfs ||
            m->cfs_algo != new_algo ||
            m->level != opts->level ||
            m->min_gain_bytes != opts->min_gain_bytes ||
            m->level_set != opts->level_set ||
            m->min_gain_bytes_set != opts->min_gain_bytes_set)
            m->policy_gen = cfs_map_clock_tick(part);
 
        m->is_cfs = opts->is_cfs;
        m->cfs_algo = new_algo;
        m->level = opts->level;
        m->min_gain_bytes = opts->min_gain_bytes;
        m->level_set = opts->level_set;
        m->min_gain_bytes_set = opts->min_gain_bytes_set;
        m->access_clock = cfs_map_clock_tick(part);
        gen = m->policy_gen;
    }
    LWLockRelease(&cfs_map_locks[part].lock);
    return gen;
}
 
uint64
cfs_publish_options(RelFileLocatorBackend rlocator, ForkNumber forknum,
                    const CfsEffectiveOptions *opts)
{
    return cfs_publish_options_internal(rlocator, forknum, opts, false);
}
 
uint64
cfs_publish_options_postcommit(RelFileLocatorBackend rlocator,
                               ForkNumber forknum,
                               const CfsEffectiveOptions *opts)
{
    return cfs_publish_options_internal(rlocator, forknum, opts, true);
}
 
bool
cfs_get_options(RelFileLocatorBackend rlocator, ForkNumber forknum,
                CfsEffectiveOptions *out)
{
    uint32      rel_hash = cfs_cache_hash_rel(rlocator, forknum);
    int         part = rel_hash & CFS_PART_MASK;
    CfsRelMetaSlot *m;
    bool        found = false;
 
    LWLockAcquire(&cfs_map_locks[part].lock, LW_SHARED);
    m = cfs_meta_find(rel_hash, rlocator, forknum);
    if (m != NULL && m->is_cfs)
    {
        /*
         * The algorithm may legitimately be RAW (= 0) on a codec-less build;
         * is_cfs, not the algorithm value, decides whether a policy is
         * stored.
         */
        out->is_cfs = true;
        out->algorithm = (CfsAlgorithm) m->cfs_algo;
        out->level = m->level;
        out->min_gain_bytes = m->min_gain_bytes;
        out->level_set = m->level_set;
        out->min_gain_bytes_set = m->min_gain_bytes_set;
        found = true;
    }
    LWLockRelease(&cfs_map_locks[part].lock);
    return found;
}
 
bool
cfs_slot_present(RelFileLocatorBackend rlocator, ForkNumber forknum)
{
    uint32      rel_hash = cfs_cache_hash_rel(rlocator, forknum);
    int         part = rel_hash & CFS_PART_MASK;
    CfsRelMetaSlot *m;
    bool        present;
 
    LWLockAcquire(&cfs_map_locks[part].lock, LW_SHARED);
    m = cfs_meta_find(rel_hash, rlocator, forknum);
    present = (m != NULL);
    LWLockRelease(&cfs_map_locks[part].lock);
    return present;
}
 
void
cfs_forget_options(RelFileLocatorBackend rlocator, ForkNumber forknum)
{
    uint32      rel_hash = cfs_cache_hash_rel(rlocator, forknum);
    int         part = rel_hash & CFS_PART_MASK;
    CfsRelMetaSlot *m;
 
    LWLockAcquire(&cfs_map_locks[part].lock, LW_EXCLUSIVE);
    m = cfs_meta_find(rel_hash, rlocator, forknum);
    if (m != NULL && m->refcount == 0)
    {
        /* Unlink from the chain before the clear (invariant I3). */
        cfs_meta_chain_unlink(part, m);
        MemSet(m, 0, sizeof(CfsRelMetaSlot));
    }
    else if (m != NULL)
    {
        /*
         * Bump the generation so cached copies of the policy are dropped.
         * The map-domain partition clock keeps the value unique within the
         * partition (the ABA-safe source cfs_publish_options_internal
         * documents).
         */
        if (m->is_cfs)
            m->policy_gen = cfs_map_clock_tick(part);
        m->is_cfs = false;
        m->cfs_algo = 0;
    }
    LWLockRelease(&cfs_map_locks[part].lock);
}
 
/* ================================================================
 * Deferred policy publication
 *
 * DDL that changes the CFS tunables (level / min_gain_bytes) of an
 * already-CFS relation publishes the new policy into the shared cache only
 * after the transaction commits durably, matching the vanilla pattern for
 * externally-visible DDL effects (sinval invalidation, smgr pending
 * deletes): private effects are applied immediately, public effects at
 * commit.  An ALTER that aborts — at any subtransaction depth — therefore
 * leaves the shared cache untouched; a committed ALTER still reaches every
 * process through the generation check before the first reopen of the
 * relation.
 *
 * The deferred list is per-process and lives in TopMemoryContext.  It
 * follows the transaction tree exactly like the vanilla PendingRelDelete
 * list (catalog/storage.c): each entry records the nesting level it was
 * queued at, a subtransaction commit hands its entries to the parent, and
 * a subtransaction abort drops the entries queued inside it.  Every entry
 * is self-contained — "publish this policy for this storage node" — and
 * entries never interact, like the entries of the vanilla list: the fate
 * of an entry is decided by the transaction tree alone.  Entries are
 * never merged on requeue: they survive in queue order, so the last
 * queued surviving version of a policy is the one published at commit —
 * which is also the surviving catalog state.
 *
 * An ALTER that turns the relation non-CFS queues nothing: the relation
 * goes through a rewrite, the old storage node is scheduled for deletion
 * like a vanilla RelationDropStorage() would, and the entries queued for
 * it earlier (if any) still publish at commit — harmlessly.  The
 * publication bumps the generation for a node that dies at the same
 * commit: XACT_EVENT_COMMIT callbacks run before smgrDoPendingDeletes()
 * (xact.c), nothing reads the replaced node in that window, and the
 * unlink forgets the slot together with the sidecar files.  This is the
 * vanilla double-entry answer (a pending delete scheduled for a node
 * that is deleted anyway): harmless execution beats a cancel mechanism.
 * The COMMIT PREPARED path is the one exception: there the files are
 * dropped before the postcommit callbacks run, so the entries of the
 * deleted nodes are never transferred to the two-phase state file
 * (cfs_publish_at_prepare).
 * ================================================================ */
 
typedef struct CfsDeferredPublish
{
    RelFileLocatorBackend rlocator;
    ForkNumber  forknum;
    int         nestLevel;      /* xact nesting level of request */
    CfsEffectiveOptions opts;
}           CfsDeferredPublish;
 
static CfsDeferredPublish * cfs_deferred = NULL;
static int  cfs_deferred_count = 0;
static int  cfs_deferred_cap = 0;
static bool cfs_deferred_cb_registered = false;
 
static void cfs_publish_xact_callback(XactEvent event, void *arg);
static void cfs_publish_subxact_callback(SubXactEvent event,
                                         SubTransactionId mySubid,
                                         SubTransactionId parentSubid,
                                         void *arg);
 
/*
 * cfs_deferred_push
 *      Append a policy publication entry to the deferred list.
 */
static void
cfs_deferred_push(RelFileLocatorBackend rlocator, ForkNumber forknum,
                  const CfsEffectiveOptions *opts)
{
    MemoryContext oldctx;
 
    /* Lazily register the transaction callbacks on first use. */
    if (!cfs_deferred_cb_registered)
    {
        RegisterXactCallback(cfs_publish_xact_callback, NULL);
        RegisterSubXactCallback(cfs_publish_subxact_callback, NULL);
        cfs_deferred_cb_registered = true;
    }
 
    /* Grow the array in TopMemoryContext if needed. */
    oldctx = MemoryContextSwitchTo(TopMemoryContext);
    if (cfs_deferred_count == cfs_deferred_cap)
    {
        int         newcap = cfs_deferred_cap == 0 ? 4 : cfs_deferred_cap * 2;
 
        cfs_deferred = cfs_deferred == NULL
            ? palloc(newcap * sizeof(CfsDeferredPublish))
            : repalloc(cfs_deferred, newcap * sizeof(CfsDeferredPublish));
        cfs_deferred_cap = newcap;
    }
 
    cfs_deferred[cfs_deferred_count].rlocator = rlocator;
    cfs_deferred[cfs_deferred_count].forknum = forknum;
    cfs_deferred[cfs_deferred_count].nestLevel = GetCurrentTransactionNestLevel();
    cfs_deferred[cfs_deferred_count].opts = *opts;
    cfs_deferred_count++;
    MemoryContextSwitchTo(oldctx);
}
 
/*
 * cfs_publish_options_deferred
 *      Queue a policy publication for the end of the current transaction
 *      instead of publishing immediately.  See the block comment above.
 */
void
cfs_publish_options_deferred(RelFileLocatorBackend rlocator,
                             ForkNumber forknum,
                             const CfsEffectiveOptions *opts)
{
    cfs_deferred_push(rlocator, forknum, opts);
}
 
/*
 * cfs_publish_is_pending
 *      True when (rlocator, forknum) has a deferred publication queued in the
 *      current transaction.  Used by cfs_open_relation_smgr() to skip the immediate
 *      publication for a relation whose policy comes from an uncommitted
 *      catalog change: the flush after the durable commit (or the first
 *      reopen after abort) publishes the surviving policy.
 */
bool
cfs_publish_is_pending(RelFileLocatorBackend rlocator, ForkNumber forknum)
{
    int         i;
 
    for (i = 0; i < cfs_deferred_count; i++)
    {
        if (RelFileLocatorBackendEquals(cfs_deferred[i].rlocator, rlocator) &&
            cfs_deferred[i].forknum == forknum)
            return true;
    }
    return false;
}
 
/*
 * cfs_publish_xact_callback
 *      Flush deferred policy publications after the durable commit, and
 *      drop them without publishing at abort or prepare.
 */
static void
cfs_publish_xact_callback(XactEvent event, void *arg)
{
    MemoryContext oldctx;
 
    if (event == XACT_EVENT_COMMIT)
    {
        int         i;
 
        /*
         * The post-commit phase, after RecordTransactionCommit(): the
         * transaction can no longer roll back, so publishing here can never
         * leak an uncommitted policy — the same phase the vanilla
         * invalidation messages are sent from (AtEOXact_Inval).  A failure in
         * any of the pre-commit steps above leaves the list intact for
         * XACT_EVENT_ABORT instead.  Publication uses the postcommit variant:
         * an ERROR here is no longer abortable and would escalate to PANIC,
         * so slot exhaustion degrades to a WARNING and the entry is
         * republished on the next open of the relation.
         */
        for (i = 0; i < cfs_deferred_count; i++)
        {
            cfs_publish_options_postcommit(cfs_deferred[i].rlocator,
                                           cfs_deferred[i].forknum,
                                           &cfs_deferred[i].opts);
        }
    }
    else if (event != XACT_EVENT_ABORT && event != XACT_EVENT_PREPARE)
        return;
 
    /*
     * Clear the list.  At abort nothing has been published; at prepare the
     * entries have already been transferred to the two-phase state file by
     * cfs_publish_at_prepare() (which runs between StartPrepare and
     * EndPrepare, where RegisterTwoPhaseRecord is legal), and COMMIT PREPARED
     * publishes them after the durable commit.
     */
    oldctx = MemoryContextSwitchTo(TopMemoryContext);
    if (cfs_deferred != NULL)
        pfree(cfs_deferred);
    cfs_deferred = NULL;
    cfs_deferred_count = 0;
    cfs_deferred_cap = 0;
    MemoryContextSwitchTo(oldctx);
}
 
/*
 * cfs_publish_at_prepare
 *      Transfer the deferred publications of a preparing transaction into
 *      the two-phase state file, following the vanilla pattern of
 *      AtPrepare_MultiXact: called from PrepareTransaction() between
 *      StartPrepare() and EndPrepare(), where RegisterTwoPhaseRecord() is
 *      legal.  A ROLLBACK PREPARED discards the records; a COMMIT PREPARED
 *      replays them through cfs_twophase_postcommit after the durable
 *      commit — mirroring how the shared invalidation messages of a
 *      prepared transaction behave.
 *
 *      Entries for storage nodes the transaction schedules for deletion are
 *      skipped.  FinishPreparedTransaction() drops those files (DropRelationFiles)
 *      before replaying the postcommit callbacks — the reverse of the
 *      CommitTransaction() order, where the unlink that follows the
 *      publication forgets the slot again.  A skipped entry therefore never
 *      reaches the state file, and COMMIT PREPARED cannot republish a stale
 *      policy for an already-deleted node.  The same list is used here that
 *      StartPrepare() itself puts into the state-file header
 *      (smgrGetPendingDeletes(true)); it is safe to call again because the
 *      in-memory list is only dropped later, by PostPrepare_smgr().
 */
void
cfs_publish_at_prepare(void)
{
    RelFileLocator *delrels;
    int         ndelrels;
    int         i;
    int         j;
 
    ndelrels = smgrGetPendingDeletes(true, &delrels);
 
    for (i = 0; i < cfs_deferred_count; i++)
    {
        CfsDeferredPublish *entry = &cfs_deferred[i];
        bool        node_dropped = false;
 
        /*
         * smgrGetPendingDeletes() returns only non-temp relations, so a
         * deferred entry for a temp backend can never match — but keep the
         * comparison honest by checking the backend id anyway.
         */
        if (entry->rlocator.backend == INVALID_PROC_NUMBER)
        {
            for (j = 0; j < ndelrels; j++)
            {
                if (RelFileLocatorEquals(entry->rlocator.locator, delrels[j]))
                {
                    node_dropped = true;
                    break;
                }
            }
        }
 
        if (node_dropped)
            continue;
 
        RegisterTwoPhaseRecord(TWOPHASE_RM_CFS_POLICY_ID, 0,
                               entry,
                               sizeof(CfsDeferredPublish));
    }
 
    if (delrels != NULL)
        pfree(delrels);
 
    /* The entries now live in the state file; nothing to flush locally. */
    cfs_deferred_count = 0;
}
 
/*
 * cfs_twophase_postcommit
 *      Publish the policy entries a committed prepared transaction carried
 *   in its state file.  Runs from FinishPreparedTransaction() after the
 *   commit WAL record is durable, in the session executing COMMIT
 *   PREPARED.
 */
void
cfs_twophase_postcommit(FullTransactionId fxid, uint16 info,
                        void *recdata, uint32 len)
{
    CfsDeferredPublish *entry = (CfsDeferredPublish *) recdata;
    TransactionId xid = XidFromFullTransactionId(fxid);
 
    if (len != sizeof(CfsDeferredPublish))
    {
        elog(WARNING, "CFS: ignoring malformed deferred policy record of length %u in prepared transaction %u",
             len, xid);
        return;
    }
 
    /*
     * Runs after the commit WAL record of COMMIT PREPARED is durable: use the
     * postcommit variant, which degrades to a WARNING instead of an ERROR
     * that could no longer be rolled back here.
     */
    cfs_publish_options_postcommit(entry->rlocator, entry->forknum, &entry->opts);
}
 
/*
 * cfs_publish_subxact_callback
 *      Track the transaction tree exactly like AtSubCommit_smgr /
 *      AtSubAbort_smgr (catalog/storage.c): a subtransaction commit hands
 *      its queued entries to the parent level, a subtransaction abort
 *      drops the entries queued inside it.
 */
static void
cfs_publish_subxact_callback(SubXactEvent event, SubTransactionId mySubid,
                             SubTransactionId parentSubid, void *arg)
{
    int         nestLevel = GetCurrentTransactionNestLevel();
    int         i;
    int         j;
 
    if (event == SUBXACT_EVENT_COMMIT_SUB)
    {
        for (i = 0; i < cfs_deferred_count; i++)
        {
            if (cfs_deferred[i].nestLevel >= nestLevel)
                cfs_deferred[i].nestLevel = nestLevel - 1;
        }
    }
    else if (event == SUBXACT_EVENT_ABORT_SUB)
    {
        j = 0;
        for (i = 0; i < cfs_deferred_count; i++)
        {
            if (cfs_deferred[i].nestLevel >= nestLevel)
                continue;
            cfs_deferred[j++] = cfs_deferred[i];
        }
        cfs_deferred_count = j;
    }
}
 
uint64
cfs_policy_generation(RelFileLocatorBackend rlocator, ForkNumber forknum)
{
    uint32      rel_hash = cfs_cache_hash_rel(rlocator, forknum);
    int         part = rel_hash & CFS_PART_MASK;
    CfsRelMetaSlot *m;
    uint64      gen = 0;
 
    LWLockAcquire(&cfs_map_locks[part].lock, LW_SHARED);
    m = cfs_meta_find(rel_hash, rlocator, forknum);
    if (m != NULL)
        gen = m->policy_gen;
    LWLockRelease(&cfs_map_locks[part].lock);
    return gen;
}
 
void
cfs_for_each_cfs_relation(CfsRelCB cb, void *arg)
{
    /*
     * Maximum number of relation-metadata slots across all partitions.
     * Collecting a snapshot keeps the partition lock held only while copying
     * the (rlocator, forknum) keys, then invokes the callback without any CFS
     * lock held.  This avoids releasing and reacquiring the lock inside the
     * iteration, which previously let another backend evict or replace a slot
     * mid-scan (skip / double-process).
     *
     * Only relations marked dirty_checkpoint (written since the last
     * checkpoint) are enumerated: the sole caller is the checkpoint path,
     * which must not re-snapshot and re-fsync relations that saw no writes.
     */
    int         max_rels = CFS_MAP_CACHE_NUM_PARTITIONS *
        cfs_map_cache_rels_per_partition;
    RelFileLocatorBackend *snapshot_rlocator;
    ForkNumber *snapshot_forknum;
    int         nrels = 0;
    int         part;
    int         i;
    int         j;
 
    Assert(cfs_control != NULL);
 
    snapshot_rlocator = (RelFileLocatorBackend *)
        palloc(max_rels * sizeof(RelFileLocatorBackend));
    snapshot_forknum = (ForkNumber *)
        palloc(max_rels * sizeof(ForkNumber));
 
    /*
     * First pass: collect the keys of the relations written since the last
     * checkpoint (dirty_checkpoint) under each partition's shared lock.  A
     * relation without a single write since then needs no new map snapshot or
     * fsync and is skipped.  A relation dirtied only after its partition was
     * scanned is left for the next checkpoint: its journal is not truncated
     * by this run, and WAL replay from the previous redo pointer still covers
     * those writes after a crash, so nothing is lost.
     */
    for (part = 0; part < CFS_MAP_CACHE_NUM_PARTITIONS; part++)
    {
        LWLockAcquire(&cfs_map_locks[part].lock, LW_SHARED);
        for (i = 0; i < cfs_map_cache_rels_per_partition; i++)
        {
            CfsRelMetaSlot *m = cfs_rel_meta_slot(part, i);
 
            if (m->hash != 0 && m->is_cfs && m->dirty_checkpoint)
            {
                if (nrels < max_rels)
                {
                    snapshot_rlocator[nrels] = m->rlocator;
                    snapshot_forknum[nrels] = m->forknum;
                    nrels++;
                }
            }
        }
        LWLockRelease(&cfs_map_locks[part].lock);
    }
 
    /* Second pass: invoke the callback without holding any CFS lock. */
    for (j = 0; j < nrels; j++)
        cb(snapshot_rlocator[j], snapshot_forknum[j], arg);
 
    pfree(snapshot_rlocator);
    pfree(snapshot_forknum);
}
 
/*
 * The statistics counters, their slots and the statsfile moved to
 * cfs_stats.c (a leaf module the storage layer may call directly).
 */
 
 
/* ================================================================
 * Cache integration with the storage layer
 * ================================================================ */
 
/*
 * cfs_map_segment_invalidate_block — clear one entry of a resident segment
 * (the entry proved unusable: CRC mismatch or unreadable record), so the
 * next lookup misses and the authoritative path re-resolves it.
 */
static void
cfs_map_segment_invalidate_block(RelFileLocatorBackend rlocator,
                                 ForkNumber forknum, BlockNumber blocknum)
{
    CfsMapSegmentKey key;
    uint32      hash;
    int         id;
 
    if (cfs_map_seg_count == 0)
        return;
    key.rlocator = rlocator;
    key.forknum = forknum;
    key.first_block = blocknum & ~(BlockNumber) (CFS_MAP_SEGMENT_BLOCKS - 1);
    hash = cfs_map_segment_hash(rlocator, forknum, key.first_block);
 
    id = cfs_map_segment_find(&key, hash, LW_SHARED);
    if (id < 0)
        return;
 
    LWLockAcquire(&cfs_map_seg_locks[id].lock, LW_EXCLUSIVE);
    if (cfs_map_segment_valid(&cfs_map_seg_descs[id], hash, rlocator,
                              forknum, key.first_block))
    {
        MemSet(&cfs_map_seg_data[id][blocknum - key.first_block], 0,
               sizeof(CfsMapEntry));
 
        /*
         * The cleared slot must be re-resolvable from the snapshot on the
         * next miss (a corrupted record keeps re-reporting its error, a store
         * that could not land gets re-read authoritatively): let the next
         * ensure merge the snapshot part again.
         */
        cfs_map_seg_descs[id].snapshot_loaded = false;
        cfs_map_seg_descs[id].journal_synced = false;
    }
    LWLockRelease(&cfs_map_seg_locks[id].lock);
}
 
/* Context for the segment journal-delta replay callback. */
typedef struct CfsSegSyncCtx
{
    int         id;
    uint32      hash;
    RelFileLocatorBackend rlocator;
    ForkNumber  forknum;
    BlockNumber first_block;
    char       *corrupt_mask;   /* blocks still needing a heal */
} CfsSegSyncCtx;
 
/* One replayed journal record: store/clear the entry in the segment. */
static void
cfs_seg_sync_cb(BlockNumber blocknum, const CfsMapEntry *entry, void *arg)
{
    CfsSegSyncCtx *ctx = (CfsSegSyncCtx *) arg;
    CfsMapSegmentDesc *desc = &cfs_map_seg_descs[ctx->id];
    int         off = blocknum - ctx->first_block;
 
    LWLockAcquire(&cfs_map_seg_locks[ctx->id].lock, LW_EXCLUSIVE);
    if (cfs_map_segment_valid(desc, ctx->hash, ctx->rlocator,
                              ctx->forknum, ctx->first_block))
    {
        if (entry != NULL)
            cfs_map_seg_data[ctx->id][off] = *entry;
        else
            MemSet(&cfs_map_seg_data[ctx->id][off], 0, sizeof(CfsMapEntry));
        if (ctx->corrupt_mask != NULL)
            ctx->corrupt_mask[off] = 0;
 
        /*
         * A journal record (UPDATE or DELETE) resolves this block: it is no
         * longer torn, so the block may serve again.
         */
        cfs_seg_unhealed_clear(desc, off);
    }
    LWLockRelease(&cfs_map_seg_locks[ctx->id].lock);
}
 
/*
 * cfs_shared_map_sync_segment — replay the journal delta into the resident
 * segment covering 'blocknum', advancing its jrn_synced_off.  The caller
 * must hold the relation's append lock (shared suffices: the journal is
 * append-only and replaying the same records twice is idempotent), which
 * also serialises against compaction so the handle's descriptors are
 * stable while the segment reads the journal through them.
 *
 * A journal whose header incarnation differs from the segment's stamp — or
 * that shrank below the segment's sync offset — was reset by a checkpoint
 * (truncate + incarnation bump) whose snapshot already contains everything
 * the journal no longer does.  The incarnation catches the ABA case the
 * size check cannot: the new-incarnation journal may grow back past the
 * stale offset, and replaying from there would silently skip the records
 * below it.  Either way the segment resyncs: the fresh .cfsmap is merged
 * into its INVALID slots and the replay restarts from the journal header.
 *
 * Returns 1 on success, 0 when the segment vanished or could not be read
 * (a concurrent eviction or reopen — transient, the caller may retry or
 * fall back), -1 when the journal replay itself rejected the segment
 * (mid-journal corruption — fatal), and
 * CFS_STORAGE_CORRUPT when the requested block still has a row no
 * journal record healed: that block's bit is left in the segment's
 * unhealed bitmap (lookup refuses only it) and the caller must fail the
 * read through the smgr entry point's corruption report.  Neither
 * failure path throws from here: the caller may run under the append
 * lock / inside an AIO callback.
 */
/*
 * Post-replay validation of a segment's corrupt rows.
 * Every still-set mask byte names a block whose snapshot row failed its
 * entry_crc; a byte the journal healed was cleared by cfs_seg_sync_cb.
 * The still-torn blocks are recorded in the descriptor's per-block bitmap
 * (the segment itself stays publishable for the rest of the range), and
 * the requested block decides whether the caller reports corruption.
 *
 * The caller must hold the segment's lock (either mode): the bitmap is
 * part of the segment's published state.
 */
static inline bool
cfs_seg_unhealed_test(const CfsMapSegmentDesc *desc, uint32 off)
{
    return (desc->unhealed_mask[off >> 3] &
            (1u << (off & 7))) != 0;
}
 
static inline void
cfs_seg_unhealed_set(CfsMapSegmentDesc *desc, uint32 off)
{
    desc->unhealed_mask[off >> 3] |= (1u << (off & 7));
}
 
static inline void
cfs_seg_unhealed_clear(CfsMapSegmentDesc *desc, uint32 off)
{
    desc->unhealed_mask[off >> 3] &= ~(1u << (off & 7));
}
 
/* Can the resident segment serve this block, or is the row still torn? */
static bool
cfs_map_segment_unhealed_at(int id, uint32 hash,
                            RelFileLocatorBackend rlocator,
                            ForkNumber forknum, BlockNumber first_block,
                            BlockNumber blocknum)
{
    CfsMapSegmentDesc *desc = &cfs_map_seg_descs[id];
    uint32      off = blocknum - first_block;
 
    if (!cfs_map_segment_valid(desc, hash, rlocator, forknum, first_block))
        return false;
    if (off >= CFS_MAP_SEGMENT_BLOCKS)
        return false;
    return cfs_seg_unhealed_test(desc, off);
}
 
/*
 * Merge the still-torn rows of one snapshot load into the descriptor's
 * sticky bitmap: a mask bit whose slot the journal healed (the callback
 * cleared the byte) or whose slot holds a valid row is not corruption.
 * Returns the number of blocks left unhealed by this pass.
 */
static void
cfs_map_segment_collect_unhealed(int id, uint32 hash,
                                 RelFileLocatorBackend rlocator,
                                 ForkNumber forknum, BlockNumber first_block,
                                 const char *corrupt_mask)
{
    CfsMapSegmentDesc *desc = &cfs_map_seg_descs[id];
    uint32      off;
 
    if (!cfs_map_segment_valid(desc, hash, rlocator, forknum, first_block))
        return;
 
    for (off = 0; off < CFS_MAP_SEGMENT_BLOCKS; off++)
    {
        if (corrupt_mask[off] &&
            cfs_map_seg_data[id][off].physical_offset ==
            CFS_ENTRY_INVALID_OFFSET)
            cfs_seg_unhealed_set(desc, off);
    }
}
 
static int
cfs_shared_map_sync_segment(CfsRelation *cfs, BlockNumber blocknum,
                            char *corrupt_mask)
{
    char       *owned_mask = NULL;
    RelFileLocatorBackend rlocator = cfs->rlocator;
    ForkNumber  forknum = cfs->forknum;
    CfsMapSegmentKey key;
    uint32      hash;
    CfsSegSyncCtx ctx;
    CfsJournalFileHeader jhdr;
    uint16      stamped_incarnation;
    int         state_fl;
    off_t       cur_size;
    off_t       start;
    off_t       stop;
 
    if (cfs_map_seg_count == 0)
        return 0;
 
    key.rlocator = rlocator;
    key.forknum = forknum;
    key.first_block = blocknum & ~(BlockNumber) (CFS_MAP_SEGMENT_BLOCKS - 1);
    hash = cfs_map_segment_hash(rlocator, forknum, key.first_block);
 
    ctx.id = cfs_map_segment_find(&key, hash, LW_SHARED);
    if (ctx.id < 0)
        return 0;
 
    LWLockAcquire(&cfs_map_seg_locks[ctx.id].lock, LW_SHARED);
    if (!cfs_seg_matches(&cfs_map_seg_descs[ctx.id], hash, rlocator,
                         forknum, key.first_block, cfs))
    {
        LWLockRelease(&cfs_map_seg_locks[ctx.id].lock);
        return 0;
    }
 
    start = (off_t) cfs_map_seg_descs[ctx.id].jrn_synced_off;
    stamped_incarnation = cfs_map_seg_descs[ctx.id].jrn_incarnation;
    LWLockRelease(&cfs_map_seg_locks[ctx.id].lock);
 
    /* Journal records begin after the file header. */
    if (start < (off_t) CFS_JOURNAL_HEADER_SIZE)
        start = CFS_JOURNAL_HEADER_SIZE;
 
    cur_size = cfs_fd_size(cfs->jrn_fd);
    if (cur_size < 0)
        return 0;
 
    /*
     * The judge derives the reset/shrink signals against the segment's
     * stamped baseline (see the caller mask table in cfs_state.c); this site
     * gives up on a stale/unreadable header exactly like it always did.
     */
    state_fl = cfs_state_journal_moved(cfs, stamped_incarnation, start, &jhdr);
    if (state_fl & (CFS_STATE_JRN_STAT_FAILED |
                    CFS_STATE_JRN_HEADER_STALE))
        return 0;
 
    if (state_fl & (CFS_STATE_JRN_RESET | CFS_STATE_JRN_SHRANK))
    {
        if (corrupt_mask == NULL)
        {
            owned_mask = palloc0(CFS_MAP_SEGMENT_BLOCKS);
            corrupt_mask = owned_mask;
        }
 
        /*
         * Journal reset since the segment last synced: re-baseline the
         * segment (fresh snapshot merge + replay from the header).  Under the
         * append lock the reset has completed, so the on-disk header is
         * stable here.
         */
        LWLockAcquire(&cfs_map_seg_locks[ctx.id].lock, LW_EXCLUSIVE);
        if (cfs_seg_matches(&cfs_map_seg_descs[ctx.id], hash, rlocator,
                            forknum, key.first_block, cfs))
        {
            cfs_map_seg_descs[ctx.id].snapshot_loaded = false;
            cfs_map_seg_descs[ctx.id].journal_synced = false;
            cfs_map_seg_descs[ctx.id].jrn_synced_off = 0;
            cfs_map_seg_descs[ctx.id].jrn_incarnation = jhdr.incarnation;
        }
        else
        {
            LWLockRelease(&cfs_map_seg_locks[ctx.id].lock);
            return 0;
        }
        LWLockRelease(&cfs_map_seg_locks[ctx.id].lock);
 
        if (!cfs_map_segment_merge_snapshot(cfs, ctx.id, hash, rlocator,
                                            forknum, key.first_block,
                                            corrupt_mask))
        {
            if (owned_mask != NULL)
                pfree(owned_mask);
            return 0;
        }
        start = (off_t) CFS_JOURNAL_HEADER_SIZE;
    }
 
    if (start >= cur_size)
    {
        /* Already synced (or the journal holds no new records). */
        LWLockAcquire(&cfs_map_seg_locks[ctx.id].lock, LW_EXCLUSIVE);
        if (cfs_seg_matches(&cfs_map_seg_descs[ctx.id], hash, rlocator,
                            forknum, key.first_block, cfs))
        {
            /*
             * The journal cannot heal anything anymore (it holds no new
             * records): still-set mask bits are unhealed corruption, and
             * those blocks must not serve their INVALID slots as zero pages .
             * Only the requested block decides this call's outcome; the other
             * bits stay in the bitmap so their own reads report the damage on
             * the right block.
             */
            if (corrupt_mask != NULL)
                cfs_map_segment_collect_unhealed(ctx.id, hash, rlocator,
                                                 forknum, key.first_block,
                                                 corrupt_mask);
            if (cfs_map_segment_unhealed_at(ctx.id, hash, rlocator, forknum,
                                            key.first_block, blocknum))
            {
                LWLockRelease(&cfs_map_seg_locks[ctx.id].lock);
                if (owned_mask != NULL)
                    pfree(owned_mask);
                return CFS_STORAGE_CORRUPT;
            }
            cfs_map_seg_descs[ctx.id].journal_synced = true;
        }
        LWLockRelease(&cfs_map_seg_locks[ctx.id].lock);
        if (owned_mask != NULL)
            pfree(owned_mask);
        return 1;
    }
 
    ctx.hash = hash;
    ctx.rlocator = rlocator;
    ctx.forknum = forknum;
    ctx.first_block = key.first_block;
    ctx.corrupt_mask = corrupt_mask;
 
    stop = cfs_journal_replay_segment(cfs, start, key.first_block,
                                      cfs_seg_sync_cb, &ctx);
    if (stop < 0)
    {
        if (owned_mask != NULL)
            pfree(owned_mask);
        return -1;
    }
 
    LWLockAcquire(&cfs_map_seg_locks[ctx.id].lock, LW_EXCLUSIVE);
    if (cfs_seg_matches(&cfs_map_seg_descs[ctx.id], hash, rlocator,
                        forknum, key.first_block, cfs))
    {
        /*
         * The replay is done: mask bits it did not heal name rows no journal
         * record covers.  Keep them in the per-block bitmap and publish the
         * segment for everything else; the requested block fails the call if
         * it is one of the still-torn ones.
         */
        if (corrupt_mask != NULL)
            cfs_map_segment_collect_unhealed(ctx.id, hash, rlocator, forknum,
                                             key.first_block, corrupt_mask);
        if (cfs_map_segment_unhealed_at(ctx.id, hash, rlocator, forknum,
                                        key.first_block, blocknum))
        {
            LWLockRelease(&cfs_map_seg_locks[ctx.id].lock);
            if (owned_mask != NULL)
                pfree(owned_mask);
            return CFS_STORAGE_CORRUPT;
        }
        if ((off_t) cfs_map_seg_descs[ctx.id].jrn_synced_off < stop)
            cfs_map_seg_descs[ctx.id].jrn_synced_off = (uint64) stop;
        cfs_map_seg_descs[ctx.id].jrn_incarnation = jhdr.incarnation;
        cfs_map_seg_descs[ctx.id].journal_synced = true;
    }
    LWLockRelease(&cfs_map_seg_locks[ctx.id].lock);
 
    if (owned_mask != NULL)
        pfree(owned_mask);
    return 1;
}
 
/*
 * Validate a segment entry and read the page through it.  On an integrity
 * failure the block's entry is cleared so the next read re-resolves it.
 */
static int
cfs_read_entry_record(CfsRelation *cfs, BlockNumber blocknum,
                      CfsMapEntry *entry, char *dst)
{
    RelFileLocatorBackend rl = cfs->rlocator;
    ForkNumber  forknum = cfs->forknum;
    CfsFormatStatus st;
    int         rc;
 
    st = cfs_map_entry_validate(entry, true);
    if (st != CFS_FORMAT_OK)
    {
        cfs_stats_count_crc_failure(rl, forknum);
        cfs_map_segment_invalidate_block(rl, forknum, blocknum);
 
        /*
         * Escalate through the configured severity (error/panic) exactly like
         * the authoritative map path: the entry-level detail is logged here,
         * the client-facing ERROR/PANIC comes from cfs_report_corruption().
         */
        cfs_report_corruption(rl, forknum, blocknum,
                              psprintf("invalid page map entry for block %u "
                                       "(status %s)",
                                       blocknum,
                                       CfsFormatStatusString(st)),
                              false);
        return CFS_STORAGE_CORRUPT;
    }
 
    rc = cfs_read_record(cfs, (off_t) entry->physical_offset,
                         entry->compressed_size, dst, CFS_BLCKSZ);
    if (rc != CFS_STORAGE_OK)
    {
        cfs_stats_count_crc_failure(rl, forknum);
        cfs_map_segment_invalidate_block(rl, forknum, blocknum);
        return rc;
    }
    cfs_stats_count_read(rl, forknum, entry->compressed_size);
    return CFS_STORAGE_OK;
}
 
/*
 * True when the resident segment covering 'blocknum' can speak for the whole
 * range: it is the current incarnation of the relation's map, its snapshot
 * part has been merged and the journal replay has caught it up.  Only then
 * does an INVALID slot mean "never written" rather than "not resolved yet".
 */
static bool
cfs_shared_map_segment_authoritative(RelFileLocatorBackend rlocator,
                                     ForkNumber forknum,
                                     BlockNumber blocknum,
                                     uint64 generation)
{
    CfsMapSegmentKey key;
    uint32      hash;
    int         id;
    bool        ok;
 
    if (cfs_map_seg_count == 0)
        return false;
 
    key.rlocator = rlocator;
    key.forknum = forknum;
    key.first_block = blocknum & ~(BlockNumber) (CFS_MAP_SEGMENT_BLOCKS - 1);
    hash = cfs_map_segment_hash(rlocator, forknum, key.first_block);
 
    id = cfs_map_segment_find(&key, hash, LW_SHARED);
    if (id < 0)
        return false;
 
    LWLockAcquire(&cfs_map_seg_locks[id].lock, LW_SHARED);
    ok = cfs_map_segment_valid(&cfs_map_seg_descs[id], hash, rlocator,
                               forknum, key.first_block) &&
        cfs_map_seg_descs[id].rel_generation == generation &&
        cfs_map_seg_descs[id].snapshot_loaded &&
        cfs_map_seg_descs[id].journal_synced &&
        !cfs_map_segment_unhealed_at(id, hash, rlocator, forknum,
                                     key.first_block, blocknum);
    LWLockRelease(&cfs_map_seg_locks[id].lock);
 
    return ok;
}
 
/* Context for the non-pool (scratch) journal replay callback. */
typedef struct CfsScratchSyncCtx
{
    CfsMapEntry *buf;
    BlockNumber first_block;
    char       *corrupt_mask;   /* byte per block; a replayed record for a
                                 * masked block heals it (clears the bit) */
} CfsScratchSyncCtx;
 
/* One replayed journal record into the private scratch segment. */
static void
cfs_scratch_sync_cb(BlockNumber blocknum, const CfsMapEntry *entry, void *arg)
{
    CfsScratchSyncCtx *ctx = (CfsScratchSyncCtx *) arg;
    int         off = blocknum - ctx->first_block;
 
    if (entry != NULL)
        ctx->buf[off] = *entry;
    else
        MemSet(&ctx->buf[off], 0, sizeof(CfsMapEntry));
    /* A journal record covers the block: its corruption is healed. */
    if (ctx->corrupt_mask != NULL)
        ctx->corrupt_mask[off] = 0;
}
 
/*
 * Resolve an authoritative INVALID slot: inside the logical size it is an
 * extension gap, so a zero page is returned; beyond it the read is out of
 * range exactly like the full-map path.  The caller must have established
 * that the map it consults is current — this never fabricates zeroes from a
 * stale or unsynced map.
 */
static int
cfs_read_extension_gap(CfsRelation *cfs, BlockNumber blocknum, char *dst)
{
    RelFileLocatorBackend rl = cfs->rlocator;
    ForkNumber  forknum = cfs->forknum;
    uint64      nblocks = 0;
 
    if (!cfs_map_cache_get_nblocks(rl, forknum, &nblocks))
        nblocks = cfs->map_hdr.nblocks;
 
    if ((uint64) blocknum >= nblocks)
        ereport(ERROR,
                (errcode(ERRCODE_INTERNAL_ERROR),
                 errmsg("CFS: read_page: block %u out of range (nblocks=%llu)",
                        blocknum,
                        (unsigned long long) nblocks)));
 
    MemSet(dst, 0, CFS_BLCKSZ);
    cfs_stats_count_read(rl, forknum, 0);
    return CFS_STORAGE_OK;
}
 
/*
 * cfs_read_page_authoritative — resolve one page without a pool segment.
 *
 * Called when the shared pool has no free or evictable segment but the data
 * is still available on disk.  Load the 768 kB .cfsmap range covering the
 * block into the per-backend scratch buffer, replay the journal delta for
 * that range on top of it and resolve the entry from the result.  Nothing
 * is published into the pool, so a pool that stays exhausted (many open
 * relations pin their segments) degrades to one segment load per miss
 * instead of a full map load per page.
 *
 * The append lock is held while the snapshot range and the journal are
 * read: every .cfsmap rewrite (checkpoint, compaction, truncate) and the
 * journal truncate take it exclusively, so under it the pair is stable and
 * a torn record can only be a peer mid-append.  A stale handle is reopened
 * first, exactly like the pool miss path does.
 *
 * The result has the same authority as a fully synced resident segment:
 * the snapshot plus the complete journal delta over it.  An INVALID slot
 * therefore means "never written", which cfs_read_extension_gap() turns
 * into a zero page (or an out-of-range error); a short or corrupt snapshot
 * raises instead of being published as zeroes, and a row that failed its
 * entry_crc and that no journal record healed is returned as
 * CFS_STORAGE_CORRUPT for the smgr entry point to report.  An ERROR raised
 * here inside the synchronous read of cfs_smgr_startreadv() is caught
 * there, converted to the inline AIO failure code and reported later by
 * aio_cfs_readv_report(), so this path never throws out of an AIO
 * operation.
 */
static int
cfs_read_page_authoritative(CfsRelation *cfs, BlockNumber blocknum, char *dst)
{
    RelFileLocatorBackend rl = cfs->rlocator;
    ForkNumber  forknum = cfs->forknum;
    BlockNumber first_block = blocknum &
        ~(BlockNumber) (CFS_MAP_SEGMENT_BLOCKS - 1);
    CfsMapEntry *buf;
    Size        seg_bytes = (Size) CFS_MAP_SEGMENT_BLOCKS * sizeof(CfsMapEntry);
    CfsScratchSyncCtx ctx;
    uint32      save_holdoff;
    uint32      save_crit_section;
    char       *corrupt_mask;
    bool        unhealed = false;
    int         off;
 
    Assert(cfs->map == NULL);
 
    buf = cfs_map_segment_scratch();
    MemSet(buf, 0, seg_bytes);
 
    /*
     * Byte-per-block mask of the rows whose snapshot load failed the
     * entry_crc; cfs_scratch_sync_cb clears the bits journal records cover.
     * Only the still-set bits after the replay name corruption.  Cold
     * fallback path: the palloc is fine here.
     */
    corrupt_mask = palloc0(CFS_MAP_SEGMENT_BLOCKS);
 
    cfs_append_lock_acquire(rl, forknum, LW_SHARED);
    save_holdoff = InterruptHoldoffCount;
    save_crit_section = CritSectionCount;
 
    PG_TRY();
    {
        cfs_handle_refresh_if_stale(cfs);
 
        {
            int         load_rc;
 
            load_rc = cfs_map_segment_load_buf(cfs, first_block, buf,
                                               seg_bytes, corrupt_mask);
            if (load_rc == -2)
                ereport(ERROR,
                        (errcode_for_file_access(),
                         errmsg("CFS: could not read map segment from \"%s\"",
                                cfs->map_path)));
        }
 
        ctx.buf = buf;
        ctx.first_block = first_block;
        ctx.corrupt_mask = corrupt_mask;
        if (cfs_journal_replay_segment(cfs, (off_t) CFS_JOURNAL_HEADER_SIZE,
                                       first_block, cfs_scratch_sync_cb,
                                       &ctx) < 0)
            ereport(ERROR,
                    (errcode(ERRCODE_INTERNAL_ERROR),
                     errmsg("CFS: could not replay the journal into the block map "
                            "segment for block %u of relation %u/%u/%u",
                            blocknum, rl.locator.spcOid, rl.locator.dbOid,
                            rl.locator.relNumber)));
 
        /*
         * Only the requested block decides this read: a masked row no record
         * healed is unhealed corruption for that block, while its healthy
         * neighbours in the same 768 KiB range still read normally.
         */
        off = (int) (blocknum - first_block);
        if (corrupt_mask[off] &&
            buf[off].physical_offset == CFS_ENTRY_INVALID_OFFSET)
            unhealed = true;
    }
    PG_CATCH();
    {
        /*
         * errfinish() zeroes InterruptHoldoffCount and CritSectionCount on
         * ERROR (elog.c), so a plain release would trip the assert inside
         * RESUME_INTERRUPTS().  Restore the values as they were with the lock
         * held, release, then rethrow: cfs_smgr_startreadv() converts the
         * structural error into an AIO failure code.
         */
        InterruptHoldoffCount = save_holdoff;
        CritSectionCount = save_crit_section;
        cfs_append_lock_release(rl, forknum);
        PG_RE_THROW();
    }
    PG_END_TRY();
    cfs_append_lock_release(rl, forknum);
    pfree(corrupt_mask);
 
    /*
     * Row-level corruption is still deferred to the entry point, which raises
     * the checksum-failure report; structural errors above are caught by
     * cfs_smgr_startreadv() and converted to the AIO failure code.
     */
    if (unhealed)
        return CFS_STORAGE_CORRUPT;
 
    if (buf[blocknum - first_block].physical_offset != CFS_ENTRY_INVALID_OFFSET)
        return cfs_read_entry_record(cfs, blocknum,
                                     &buf[blocknum - first_block], dst);
 
    return cfs_read_extension_gap(cfs, blocknum, dst);
}
 
/*
 * cfs_map_contiguous_run — length of the run of physically contiguous
 * records in .cfp starting at 'blocknum', capped at 'maxblocks' (the
 * caller passes io_combine_limit).  Purely advisory and cheap: entries are
 * only read from already-resident state (the private map array or resident
 * pool segments), with no I/O, no segment residency and no journal replay;
 * the first miss, hole, offset gap, segment boundary or capacity limit
 * ends the run.  Returns at least 1.  cfs_smgr_maxcombine() publishes this
 * to the buffer manager, while cfs_read_pages_batch() re-derives the
 * grouping independently at read time — correctness never depends on the
 * value returned here (a compaction between planning and reading merely
 * shrinks the batches).
 */
int
cfs_map_contiguous_run(CfsRelation *cfs, BlockNumber blocknum,
                       BlockNumber maxblocks)
{
    RelFileLocatorBackend rl = cfs->rlocator;
    ForkNumber  forknum = cfs->forknum;
    CfsMapEntry prev;
    CfsMapEntry entry;
    uint64      seg_gen = 0;
    BlockNumber run = 1;
 
    if (maxblocks <= 1)
        return 1;
 
    if (cfs->map != NULL)
    {
        /*
         * Private map (cfs_map_memory=0, compaction, the checkpoint
         * snapshot writer): the array may legitimately lag nblocks, so cap
         * the walk by the allocated capacity as well.  Stale rows are fine:
         * the answer is advisory.
         */
        uint64      limit = cfs->map_hdr.nblocks;
 
        if (limit > cfs->map_capacity)
            limit = cfs->map_capacity;
        if ((uint64) blocknum >= limit || limit == 0)
            return 1;
        limit -= blocknum;
 
        while (run < maxblocks && (uint64) run < limit)
        {
            CfsMapEntry *e = &cfs->map[blocknum + run];
            CfsMapEntry *p = &cfs->map[blocknum + run - 1];
 
            if (!CFS_MAP_ENTRY_VALID(p) || !CFS_MAP_ENTRY_VALID(e))
                break;
            if (e->physical_offset !=
                p->physical_offset + CFS_RECORD_SIZE(p->compressed_size))
                break;
            if (CFS_CFP_SEGNO(e->physical_offset) !=
                CFS_CFP_SEGNO(p->physical_offset))
                break;
            run++;
        }
        return run;
    }
 
    /* Pool-backed handle: resident entries only, tag-checked. */
    if (!cfs_shared_map_lookup(rl, forknum, blocknum, &prev, &seg_gen) ||
        !cfs_seg_tag_matches(seg_gen, cfs))
        return 1;
 
    while (run < maxblocks)
    {
        if (!cfs_shared_map_lookup(rl, forknum, blocknum + run, &entry,
                                   &seg_gen) ||
            !cfs_seg_tag_matches(seg_gen, cfs))
            break;
        if (entry.physical_offset !=
            prev.physical_offset + CFS_RECORD_SIZE(prev.compressed_size))
            break;
        if (CFS_CFP_SEGNO(entry.physical_offset) !=
            CFS_CFP_SEGNO(prev.physical_offset))
            break;
        prev = entry;
        run++;
    }
    return run;
}
 
/*
 * cfs_read_span_corrupt_bookkeeping — pool-side failure bookkeeping for
 * an offloaded span whose executor detected corruption (see cfs_shmem.h).
 * Defined here so the static pool helper is already in scope.
 */
void
cfs_read_span_corrupt_bookkeeping(RelFileLocatorBackend rl,
                                  ForkNumber forknum,
                                  BlockNumber fail_block, bool pooled)
{
    if (pooled)
    {
        cfs_stats_count_crc_failure(rl, forknum);
        cfs_map_segment_invalidate_block(rl, forknum, fail_block);
    }
}
 
/*
 * cfs_gather_contiguous_run — copy the map rows of the longest physically
 * contiguous run of stored records starting at 'blocknum' into 'entries'
 * (capacity 'nmax') and return its length.  Pure map state consultation
 * (private array or already-resident pool segments, tag-checked): no I/O,
 * no residency work.  The first miss, hole, stale tag, offset gap or
 * segment boundary ends the run.  Shared by cfs_read_pages_batch() and
 * cfs_read_span_plan(), so the two paths can never disagree about what a
 * run is.
 */
static BlockNumber
cfs_gather_contiguous_run(CfsRelation *cfs, CfsMapEntry *entries,
                          BlockNumber nmax, BlockNumber blocknum)
{
    RelFileLocatorBackend rl = cfs->rlocator;
    ForkNumber  forknum = cfs->forknum;
    BlockNumber run = 0;
 
    while (run < nmax)
    {
        BlockNumber blk = blocknum + run;
        CfsMapEntry entry;
        uint64      seg_gen = 0;
        bool        have = false;
 
        if (cfs->map != NULL)
        {
            if ((uint64) blk < cfs->map_hdr.nblocks &&
                (uint64) blk < cfs->map_capacity)
            {
                entry = cfs->map[blk];
                have = true;
            }
        }
        else
        {
            have = cfs_shared_map_lookup(rl, forknum, blk,
                                         &entry, &seg_gen) &&
                cfs_seg_tag_matches(seg_gen, cfs);
        }
 
        if (!have || !CFS_MAP_ENTRY_VALID(&entry))
            break;
        if (run > 0)
        {
            CfsMapEntry *prev = &entries[run - 1];
 
            if (entry.physical_offset !=
                prev->physical_offset +
                CFS_RECORD_SIZE(prev->compressed_size))
                break;
            if (CFS_CFP_SEGNO(entry.physical_offset) !=
                CFS_CFP_SEGNO(prev->physical_offset))
                break;
        }
        entries[run++] = entry;
    }
 
    return run;
}
 
/*
 * cfs_read_pages_batch — fill 'nblocks' buffers starting at 'blocknum',
 * batching runs of physically contiguous records into single preads
 * (cfs_read_records_span) and serving everything else through the existing
 * per-block path cfs_read_page_cached() (pool misses, stale tags, holes,
 * offset gaps, segment boundaries, out-of-range reads).  The produced pages
 * are bit-identical to the per-block path: positions come from the map
 * entries, integrity from each record's own header CRC.
 *
 * On failure returns the CfsStorageStatus of the first failure and stores
 * the code and failing block for the caller (the synchronous entry point
 * reports centrally, the AIO one encodes the code — same contract as
 * before batching).  Pool-sourced failures mirror cfs_read_entry_record():
 * the failing block is invalidated in the pool and counted as a CRC
 * failure, so the next read re-resolves it from the journal.
 */
int
cfs_read_pages_batch(CfsRelation *cfs, BlockNumber blocknum,
                     void **buffers, BlockNumber nblocks,
                     int *fail_code, BlockNumber *fail_block)
{
    RelFileLocatorBackend rl = cfs->rlocator;
    ForkNumber  forknum = cfs->forknum;
    CfsMapEntry *entries;
    BlockNumber b;
 
    Assert(cfs != NULL && buffers != NULL);
    Assert(nblocks >= 1);
 
    if (nblocks == 1)
    {
        int         rc = cfs_read_page_cached(cfs, blocknum, buffers[0]);
 
        if (rc != CFS_STORAGE_OK)
        {
            if (fail_code != NULL)
                *fail_code = rc;
            if (fail_block != NULL)
                *fail_block = blocknum;
            return rc;
        }
        /*
         * read_count is only maintained for shared-pool reads: on a
         * private map the per-block path never reaches it, so the fallback
         * counter must skip it too to keep the invariant balanced.
         */
        if (cfs->map == NULL)
            cfs_stats_count_read_fallback(rl, forknum, 1);
        return rc;
    }
 
    /*
     * Private map: one journal refresh covers the whole call — the per-block
     * path pays it per block.  The append-lock protocol (including the
     * errfinish holdoff subtlety) is identical to cfs_read_page_cached().
     */
    if (cfs->map != NULL && cfs_map_needs_refresh(cfs))
    {
        int         refresh_rc = CFS_STORAGE_OK;
 
        cfs_append_lock_acquire(rl, forknum, LW_SHARED);
        PG_TRY();
        {
            refresh_rc = cfs_refresh_map(cfs, true, CFS_LOAD_READ);
        }
        PG_CATCH();
        {
            /*
             * errfinish() resets InterruptHoldoffCount to zero on ERROR
             * (elog.c), so the RESUME_INTERRUPTS() inside LWLockRelease
             * would assert even though the lock is still held.  Put the
             * holdoff back for the release, then rethrow: the caller
             * (cfs_smgr_startreadv) is the one that converts the error
             * into an AIO failure.
             */
            HOLD_INTERRUPTS();
            cfs_append_lock_release(rl, forknum);
            PG_RE_THROW();
        }
        PG_END_TRY();
        cfs_append_lock_release(rl, forknum);
        if (refresh_rc != CFS_STORAGE_OK)
        {
            if (fail_code != NULL)
                *fail_code = refresh_rc;
            if (fail_block != NULL)
                *fail_block = blocknum;
            return refresh_rc;
        }
    }
 
    entries = (CfsMapEntry *) palloc(nblocks * sizeof(CfsMapEntry));
 
    b = 0;
    while (b < nblocks)
    {
        BlockNumber run;
 
        /* Gather the longest contiguous run starting at blocknum + b. */
        run = cfs_gather_contiguous_run(cfs, entries, nblocks - b,
                                        blocknum + b);
 
        if (run >= 2)
        {
            BlockNumber fblock = blocknum + b;
            int         rc;
 
            rc = cfs_read_records_span(cfs, entries, blocknum + b, run,
                                       &buffers[b], &fblock);
            if (rc != CFS_STORAGE_OK)
            {
                /*
                 * Mirror cfs_read_entry_record()'s bookkeeping for
                 * pool-sourced runs: drop the failing block from the pool
                 * and count the failure, so the next read re-resolves it
                 * from the journal.  For private-map runs the per-block
                 * path does neither, and neither do we.
                 */
                if (cfs->map == NULL)
                {
                    cfs_stats_count_crc_failure(rl, forknum);
                    cfs_map_segment_invalidate_block(rl, forknum, fblock);
                }
                if (fail_code != NULL)
                    *fail_code = rc;
                if (fail_block != NULL)
                    *fail_block = fblock;
                pfree(entries);
                return rc;
            }
            b += run;
        }
        else
        {
            int         rc = cfs_read_page_cached(cfs, blocknum + b,
                                                   buffers[b]);
 
            if (rc != CFS_STORAGE_OK)
            {
                if (fail_code != NULL)
                    *fail_code = rc;
                if (fail_block != NULL)
                    *fail_block = blocknum + b;
                pfree(entries);
                return rc;
            }
            /* Same pool-only rule as the nblocks == 1 fast path above. */
            if (cfs->map == NULL)
                cfs_stats_count_read_fallback(rl, forknum, 1);
            b++;
        }
    }
 
    pfree(entries);
    return CFS_STORAGE_OK;
}
 
/*
 * cfs_read_span_plan — build the offload plan for one readv request; see
 * cfs_shmem.h for the contract.  The body mirrors the corresponding
 * halves of cfs_read_pages_batch() (map refresh prologue, run gathering)
 * and cfs_read_records_span() (row validation, boundary check, segment
 * fd), so an offloaded read produces exactly the pages and exactly the
 * failure codes its inline counterpart would.
 */
CfsReadPlanStatus
cfs_read_span_plan(CfsRelation *cfs, BlockNumber blocknum,
                   BlockNumber nblocks, CfsReadScratchSlot **out_slot,
                   int *out_fd, uint64 *out_span_off,
                   int *fail_code, BlockNumber *fail_block)
{
    RelFileLocatorBackend rl = cfs->rlocator;
    ForkNumber  forknum = cfs->forknum;
    CfsMapEntry *entries;
    CfsReadScratchSlot *slot;
    uint64      span_off;
    uint64      span_end;
    uint32      segno;
    size_t      span_len;
    BlockNumber run;
    BlockNumber b;
    int         fd;
 
    Assert(cfs != NULL && out_slot != NULL && out_fd != NULL &&
           out_span_off != NULL);
    Assert(nblocks >= 2);
 
    /*
     * Requests beyond the plan capacity cannot be represented; the combine
     * clamp makes this unreachable, but degrading is cheaper than trusting
     * two GUCs to agree forever.
     */
    if (nblocks > CFS_READ_PLAN_MAX)
    {
        return CFS_READ_PLAN_DEGRADE;
    }
 
    /*
     * Private map: one journal refresh covers the whole plan, exactly the
     * cfs_read_pages_batch() prologue (including the errfinish holdoff
     * subtlety).
     */
    if (cfs->map != NULL && cfs_map_needs_refresh(cfs))
    {
        int         refresh_rc = CFS_STORAGE_OK;
 
        cfs_append_lock_acquire(rl, forknum, LW_SHARED);
        PG_TRY();
        {
            refresh_rc = cfs_refresh_map(cfs, true, CFS_LOAD_READ);
        }
        PG_CATCH();
        {
            HOLD_INTERRUPTS();
            cfs_append_lock_release(rl, forknum);
            PG_RE_THROW();
        }
        PG_END_TRY();
        cfs_append_lock_release(rl, forknum);
        if (refresh_rc != CFS_STORAGE_OK)
        {
            if (fail_code != NULL)
                *fail_code = refresh_rc;
            if (fail_block != NULL)
                *fail_block = blocknum;
            return CFS_READ_PLAN_FAIL;
        }
    }
 
    entries = (CfsMapEntry *) palloc(nblocks * sizeof(CfsMapEntry));
 
    run = cfs_gather_contiguous_run(cfs, entries, nblocks, blocknum);
 
    /*
     * Only a request that is one whole span can be offloaded: a partial
     * run would leave the remaining blocks to the caller, and the buffers
     * of one IO must never be written by both paths.
     */
    if (run < nblocks)
    {
        pfree(entries);
        return CFS_READ_PLAN_DEGRADE;
    }
 
    /*
     * Row validation before anything else, mirroring
     * cfs_read_records_span(): a corrupted last-record size must not
     * drive an overlong span, and the failure stays attributed to the
     * exact block.
     */
    for (b = 0; b < nblocks; b++)
    {
        const CfsMapEntry *e = &entries[b];
        CfsFormatStatus fst = cfs_map_entry_validate(e, true);
 
        if (fst != CFS_FORMAT_OK || e->compressed_size > CFS_BLCKSZ)
        {
            ereport(WARNING,
                    (errcode(ERRCODE_DATA_CORRUPTED),
                     errmsg("CFS: invalid page map entry for block %u "
                            "(offset %llu, status %s)",
                            blocknum + b,
                            (unsigned long long) e->physical_offset,
                            CfsFormatStatusString(fst))));
            if (cfs->map == NULL)
            {
                cfs_stats_count_crc_failure(rl, forknum);
                cfs_map_segment_invalidate_block(rl, forknum, blocknum + b);
            }
            if (fail_code != NULL)
                *fail_code = CFS_STORAGE_CORRUPT;
            if (fail_block != NULL)
                *fail_block = blocknum + b;
            pfree(entries);
            return CFS_READ_PLAN_FAIL;
        }
    }
 
    span_off = entries[0].physical_offset;
    span_end = entries[nblocks - 1].physical_offset +
        CFS_RECORD_SIZE(entries[nblocks - 1].compressed_size);
    span_len = (size_t) (span_end - span_off);
    segno = CFS_CFP_SEGNO(span_off);
 
    /* Same segment-boundary rejection as cfs_read_records_span(). */
    if (CFS_CFP_SEGNO(span_end - 1) != segno)
    {
        ereport(WARNING,
                (errcode(ERRCODE_DATA_CORRUPTED),
                 errmsg("CFS: record span at offset %llu crosses a segment boundary",
                        (unsigned long long) span_off)));
        if (cfs->map == NULL)
        {
            cfs_stats_count_crc_failure(rl, forknum);
            cfs_map_segment_invalidate_block(rl, forknum,
                                             blocknum + nblocks - 1);
        }
        if (fail_code != NULL)
            *fail_code = CFS_STORAGE_CORRUPT;
        if (fail_block != NULL)
            *fail_block = blocknum + nblocks - 1;
        pfree(entries);
        return CFS_READ_PLAN_FAIL;
    }
 
    /* The span cannot outgrow the slot capacity (see cfs_read_span_capacity). */
    if (span_len > cfs_read_span_capacity())
    {
        pfree(entries);
        return CFS_READ_PLAN_DEGRADE;
    }
 
    fd = cfs_cfp_read_segment_fd(cfs, segno);
    if (fd < 0)
    {
        if (fd == -1)
        {
            ereport(WARNING,
                    (errcode(ERRCODE_DATA_CORRUPTED),
                     errmsg("CFS: .cfp segment %u referenced by the map is missing",
                            segno)));
            if (fail_code != NULL)
                *fail_code = CFS_STORAGE_CORRUPT;
        }
        else
        {
            ereport(WARNING,
                    (errcode_for_file_access(),
                     errmsg("CFS: could not open .cfp segment %u for reading",
                            segno)));
            if (fail_code != NULL)
                *fail_code = CFS_STORAGE_ERROR;
        }
        if (fail_block != NULL)
            *fail_block = blocknum;
        if (cfs->map == NULL)
        {
            cfs_stats_count_crc_failure(rl, forknum);
            cfs_map_segment_invalidate_block(rl, forknum, blocknum);
        }
        pfree(entries);
        return CFS_READ_PLAN_FAIL;
    }
 
    /*
     * Debug fault injection, mirroring cfs_read_records_span(): the
     * counter is spent on the span, so the offloaded and the inline read
     * paths fail deterministically under the same GUC.  The failure is
     * reported through the inline code path (the owner backend raises
     * it); exercising a real preadv errno in the executor is the
     * recovery injection's job (aio-worker-after-reopen).
     */
    if (cfs_debug_fail_read > 0)
    {
        cfs_debug_fail_read--;
        errno = EIO;
        ereport(WARNING,
                (errcode_for_file_access(),
                 errmsg("CFS: could not read %zu-byte record span at "
                        "offset %llu from .cfp",
                        span_len, (unsigned long long) span_off)));
        if (fail_code != NULL)
            *fail_code = CFS_STORAGE_ERROR;
        if (fail_block != NULL)
            *fail_block = blocknum;
        if (cfs->map == NULL)
        {
            cfs_stats_count_crc_failure(rl, forknum);
            cfs_map_segment_invalidate_block(rl, forknum, blocknum);
        }
        pfree(entries);
        return CFS_READ_PLAN_FAIL;
    }
 
    slot = cfs_read_scratch_acquire();
    if (slot == NULL)
    {
        pfree(entries);
        return CFS_READ_PLAN_DEGRADE;
    }
 
    slot->pooled = (cfs->map == NULL);
    slot->span_len = (uint32) span_len;
    slot->plan_len = (uint32) nblocks;
    for (b = 0; b < nblocks; b++)
    {
        CfsReadPlanEntry *pe = &slot->entries[b];
 
        pe->rec_off = (uint32) (entries[b].physical_offset - span_off);
        pe->payload = entries[b].compressed_size;
        pe->buf_off = (uint8) b;
        pe->flags = 0;
    }
 
    pfree(entries);
 
    *out_slot = slot;
    *out_fd = fd;
    *out_span_off = span_off;
    return CFS_READ_PLAN_OK;
}
 
int
cfs_read_page_cached(CfsRelation *cfs, BlockNumber blocknum, char *dst)
{
    RelFileLocatorBackend rl;
    ForkNumber  forknum;
    CfsMapEntry entry;
    uint64      seg_gen = 0;
    bool        have_entry;
    bool        ensured;
    int         sync_rc;
    int         ensure_rc;
    int         attempt;
    uint32      save_holdoff;
    uint32      save_crit_section;
 
    Assert(cfs != NULL && dst != NULL);
 
    rl = cfs->rlocator;
    forknum = cfs->forknum;
 
    /*
     * A full handle carries its own private map (cfs_map_memory=0,
     * compaction, the checkpoint snapshot writer, tests) and resolves every
     * read through it, exactly like before the segment pool; the steps below
     * only serve lazy (pool-backed) handles.
     *
     * The private map is a cache: another backend may have appended journal
     * records (including updates of blocks this map already holds) since it
     * was last synced.  Probe the journal cheaply and refresh under the same
     * lock writers use, exactly as the base branch did before the segment
     * pool moved reads to shared memory.
     */
    if (cfs->map != NULL)
    {
        if (cfs_map_needs_refresh(cfs))
        {
            int         refresh_rc = CFS_STORAGE_OK;
 
            /*
             * The READ context defers row-level corruption: the refresh
             * returns CORRUPT instead and the smgr report path re-reports it
             * centrally.  Structural failures (corrupt prologue or journal
             * header) still raise ERROR here.  That is safe inside
             * cfs_smgr_startreadv(): its PG_TRY/PG_CATCH converts the ERROR
             * into the inline AIO failure code, which aio_cfs_readv_report()
             * later raises to the caller.  The append lock is released on
             * both paths; see the catch below for the interrupt-holdoff
             * subtlety.
             */
            cfs_append_lock_acquire(rl, forknum, LW_SHARED);
            PG_TRY();
            {
                refresh_rc = cfs_refresh_map(cfs, true, CFS_LOAD_READ);
            }
            PG_CATCH();
            {
                /*
                 * errfinish() resets InterruptHoldoffCount to zero on ERROR
                 * (elog.c), so the RESUME_INTERRUPTS() inside LWLockRelease
                 * would assert even though the lock is still held.  Put the
                 * holdoff back for the release, then rethrow: the caller
                 * (cfs_smgr_startreadv) is the one that converts the error
                 * into an AIO failure.  A plain PG_FINALLY release cannot be
                 * used here for exactly this reason.
                 */
                HOLD_INTERRUPTS();
                cfs_append_lock_release(rl, forknum);
                PG_RE_THROW();
            }
            PG_END_TRY();
            cfs_append_lock_release(rl, forknum);
            if (refresh_rc != CFS_STORAGE_OK)
                return refresh_rc;
        }
        return cfs_read_page(cfs, blocknum, dst);
    }
 
    /*
     * Step 1: the shared segment pool.  On a hit the entry was published
     * either by a writer (under the append lock, right after journaling) or
     * by a delta replay; its offset is safe to read without any CFS lock
     * because .cfp is append-only — provided the entry belongs to the
     * sidecar pair this handle's descriptors point at.  The segment tag (the
     * relation map generation of its offsets) tells them apart: a compaction
     * or truncate bumps the generation AND drops every segment of the
     * relation, so a tagged disagreement means the handle is stale — reopen
     * it and re-lookup before reading.
     */
    have_entry = cfs_shared_map_lookup(rl, forknum, blocknum, &entry,
                                       &seg_gen);
    if (have_entry && !cfs_seg_tag_matches(seg_gen, cfs))
    {
        cfs_append_lock_acquire(rl, forknum, LW_SHARED);
        save_holdoff = InterruptHoldoffCount;
        save_crit_section = CritSectionCount;
        PG_TRY();
        {
            cfs_handle_refresh_if_stale(cfs);
        }
        PG_CATCH();
        {
            /*
             * A reopen inside the refresh can raise on structural map
             * corruption.  Restore the counters errfinish() zeroed, release
             * the append lock, and let the caller convert the error.
             */
            InterruptHoldoffCount = save_holdoff;
            CritSectionCount = save_crit_section;
            cfs_append_lock_release(rl, forknum);
            PG_RE_THROW();
        }
        PG_END_TRY();
        cfs_append_lock_release(rl, forknum);
 
        have_entry = cfs_shared_map_lookup(rl, forknum, blocknum, &entry,
                                           &seg_gen);
    }
    if (have_entry && cfs_seg_tag_matches(seg_gen, cfs))
        return cfs_read_entry_record(cfs, blocknum, &entry, dst);
 
    /*
     * A lookup that still misses (or whose tag still disagrees after the
     * reopen — a second compaction raced it) falls through to the miss
     * path, which re-resolves everything from disk.
     */
 
    /*
     * Step 2: miss.  Under the append lock (shared): reopen a stale handle
     * (compaction swap), make the segment resident from the .cfsmap snapshot
     * and replay the journal delta into it.  The lock guarantees the journal
     * records we replay are fully written (a peer mid-append holds the
     * exclusive mode); replay stops before its torn record.
     *
     * The 768 kB snapshot read therefore happens while the relation's writers
     * wait for the shared append lock.  That is a deliberate trade-off rather
     * than an oversight: the lock is exactly what makes the snapshot and the
     * journal a consistent pair (both are rewritten only under the exclusive
     * mode), and an optimistic load-then-revalidate would need an identity
     * check of the snapshot file plus a retry loop for a case that only
     * occurs when the pool must load a segment anyway. The one-time journal
     * scan in cfs_map_cache_next_generation() follows the same reasoning.
     */
    for (attempt = 0; attempt < 2; attempt++)
    {
        cfs_append_lock_acquire(rl, forknum, LW_SHARED);
        save_holdoff = InterruptHoldoffCount;
        save_crit_section = CritSectionCount;
        PG_TRY();
        {
            cfs_handle_refresh_if_stale(cfs);
            ensure_rc = cfs_shared_map_ensure(cfs, blocknum);
            sync_rc = (ensure_rc == CFS_STORAGE_OK) ?
                cfs_shared_map_sync_segment(cfs, blocknum, NULL) : 0;
        }
        PG_CATCH();
        {
            /*
             * ensure/sync raise on structural map or journal corruption.
             * Restore the counters errfinish() zeroed, release the append
             * lock, and rethrow so cfs_smgr_startreadv() turns it into an AIO
             * failure instead of leaking the lock into the transaction.
             */
            InterruptHoldoffCount = save_holdoff;
            CritSectionCount = save_crit_section;
            cfs_append_lock_release(rl, forknum);
            PG_RE_THROW();
        }
        PG_END_TRY();
        cfs_append_lock_release(rl, forknum);
 
        /*
         * Unhealed corruption (a map row that failed its entry_crc with no
         * covering journal record) is returned, not raised: the read path may
         * run inside an AIO callback, and the caller reports it centrally
         * through cfs_checksum_failure.  Structural errors do raise, but the
         * catch above has already released the append lock, so a producer is
         * never left waiting on it.
         */
        if (ensure_rc == CFS_STORAGE_CORRUPT || sync_rc == CFS_STORAGE_CORRUPT)
            return CFS_STORAGE_CORRUPT;
        ensured = (ensure_rc == CFS_STORAGE_OK);
 
        /* Step 3: re-lookup; a resident VALID entry now resolves the read. */
        if (cfs_shared_map_lookup(rl, forknum, blocknum, &entry, &seg_gen) &&
            cfs_seg_tag_matches(seg_gen, cfs))
            return cfs_read_entry_record(cfs, blocknum, &entry, dst);
 
        /*
         * Step 4: no entry exists — or the pool could not make the segment
         * resident.  An unavailable segment is a resource shortage, not a
         * reason to fail: the authoritative on-disk state still holds the
         * data, so degrade to a one-segment scratch read and account for it.
         * Only when even that path fails does the pool-exhaustion error
         * stand.
         *
         * A zero page must never be fabricated here: the authoritative
         * conclusion below is only drawn when the segment was actually made
         * resident and the journal replayed into it.
         */
        if (!ensured)
        {
            int         rc;
 
            pg_atomic_fetch_add_u64(&cfs_control->map_fallback_reads, 1);
            rc = cfs_read_page_authoritative(cfs, blocknum, dst);
            if (rc == CFS_STORAGE_OK || rc == CFS_STORAGE_CORRUPT)
                return rc;
 
            ereport(ERROR,
                    (errcode(ERRCODE_CONFIGURATION_LIMIT_EXCEEDED),
                     errmsg("CFS: could not load the block map segment for block "
                            "%u of relation %u/%u/%u",
                            blocknum, rl.locator.spcOid, rl.locator.dbOid,
                            rl.locator.relNumber),
                     errdetail("The shared block-map pool has no free or evictable segment, "
                               "and the authoritative map could not serve the read."),
                     errhint("Increase \"cfs_map_memory\".")));
        }
 
        /*
         * Mid-journal corruption is real and stays fatal (the replay has
         * already reported it): the segment must not be published as
         * journal_synced, and no fallback may paper over a corrupt map.
         */
        if (sync_rc < 0)
            ereport(ERROR,
                    (errcode(ERRCODE_INTERNAL_ERROR),
                     errmsg("CFS: could not replay the journal into the block map "
                            "segment for block %u of relation %u/%u/%u",
                            blocknum, rl.locator.spcOid, rl.locator.dbOid,
                            rl.locator.relNumber)));
 
        /*
         * An INVALID slot is only evidence of "never written" when the
         * segment is the current map incarnation, snapshot-loaded and fully
         * caught up with the journal: then it is an extension gap. Otherwise
         * the segment may be stale or freshly evicted and reloaded by a
         * competitor — retry once, and after the retry degrade to the
         * authoritative fallback instead of failing: with segments now
         * evictable a small pool under a parallel scan can lose that race
         * repeatedly, while the on-disk state still holds the data (and never
         * yields a fabricated zero).
         */
        if (!cfs_shared_map_segment_authoritative(rl, forknum, blocknum,
                                                  cfs->open_generation))
        {
            if (attempt == 0)
                continue;
 
            pg_atomic_fetch_add_u64(&cfs_control->map_fallback_reads, 1);
            return cfs_read_page_authoritative(cfs, blocknum, dst);
        }
 
        /*
         * Inside the logical size an unwritten block is an extension gap:
         * return a zero page.  Beyond it, the read is out of range exactly
         * like the authoritative map path.
         */
        return cfs_read_extension_gap(cfs, blocknum, dst);
    }
 
    return CFS_STORAGE_ERROR;
}
 
int
cfs_write_page_cached(CfsRelation *cfs, BlockNumber blocknum,
                      const char *src,
                      const CfsWriteOptions *opts)
{
    RelFileLocatorBackend rl;
    ForkNumber  forknum;
    CfsCompressResult cres;
    CfsMapEntry new_entry;
    int         rc;
 
    Assert(cfs != NULL && src != NULL && opts != NULL);
 
    rl = cfs->rlocator;
    forknum = cfs->forknum;
 
    /*
     * Step 1: compress the page into the per-handle scratch buffer *before*
     * acquiring the per-relation append lock.
     *
     * Compression is the most expensive part of the write path (tens of ms
     * for high zstd levels) and is fully self-contained: the compressed
     * record depends only on the source page and the compression options, not
     * on the append offset or the map state.  Performing it outside the lock
     * lets concurrent writers of the same relation compress in parallel on
     * different CPU cores, so single-relation write throughput scales with
     * the number of backends instead of being capped at one core.
     *
     * The scratch buffer is per-CfsRelation (per-backend handle) and is not
     * reallocated by cfs_reopen(), so the compressed blob stays valid even
     * when cfs_handle_refresh_if_stale() swaps the sidecar files under us
     * while we wait for the lock.
     */
    if (cfs_compress_page(cfs, src, CFS_BLCKSZ, opts, &cres)
        != CFS_STORAGE_OK)
        return CFS_STORAGE_ERROR;
 
    /*
     * Step 2: under the per-relation append lock, append the pre-compressed
     * record, journal the update and refresh the local in-memory map.  Only
     * the offset computation + pwrite + journal append + map/cache update
     * remain inside the critical section — the operations that actually
     * need serialisation to avoid two backends computing the same append
     * offset.
     */
    cfs_append_lock_acquire(rl, forknum, LW_EXCLUSIVE);
 
    /*
     * A compaction may have swapped the sidecar files while we waited for the
     * append lock; reopen the handle if its generation is stale. cfs_reopen()
     * reloads the map and re-derives the append cursor but does not touch the
     * compression scratch, so the compressed blob prepared above is still
     * valid for the pwrite.
     */
    cfs_handle_refresh_if_stale(cfs);
 
    /*
     * Derive the new generation under the append lock.  The generation is
     * relation-wide, so it no longer needs the old entry — and therefore no
     * longer ensures or replicates the segment (that forced a journal replay
     * of the whole segment on the write path after every eviction). Dead
     * accounting is exact and lives at the checkpoint: the fold sees every
     * superseded row since the last reset, so the write path counts nothing
     * here.
     */
    {
        uint32      generation = cfs_map_cache_next_generation(cfs);
 
        rc = cfs_write_compressed_page(cfs, blocknum, &cres, opts,
                                       generation, &new_entry);
    }
 
    /*
     * Step 3: publish the new entry into the shared segment pool while the
     * append lock is still held: the lock serialises against the compactor,
     * which invalidates the relation's segments right after swapping the
     * sidecars, so a store racing a compaction is either dropped by the
     * segment-key validation or lands in a segment the compaction already
     * dropped — never into the new pair.  Only the cheap store happens
     * here, no I/O.
     */
    if (rc == CFS_STORAGE_OK)
    {
        if (!cfs_shared_map_store(rl, forknum, blocknum, &new_entry,
                                  cfs->open_generation))
        {
            /*
             * The store failed (all segments pinned, or a lost race): drop
             * any older resident entry of the block so no reader is served a
             * superseded version — the authoritative miss path re-resolves
             * the block from the journal on the next lookup.
             */
            cfs_map_segment_invalidate_block(rl, forknum, blocknum);
        }
        cfs_stats_count_write(rl, forknum, new_entry.compressed_size,
                              cres.is_raw);
    }
    cfs_append_lock_release(rl, forknum);
    if (rc != CFS_STORAGE_OK)
        return rc;
 
    /*
     * Register the dirtied sidecar files (.cfp first, then .cfsjrn) with the
     * checkpointer sync queue.  This deliberately happens OUTSIDE the append
     * lock: when the queue is full, RegisterSyncRequest() returns false and
     * cfs_register_dirty_file() falls back to a synchronous local fsync of
     * the whole segment chain — holding the append lock through that would
     * park every writer of the relation behind the fsync.  md.c makes the
     * same choice: register_dirty_segment() performs its fallback fsync
     * without any relation-level lock.
     *
     * A bulk write (skip_fsync, e.g. CREATE INDEX / CLUSTER /
     * RelationCopyStorage) skips this exactly like md.c skips
     * register_dirty_segment() when skipFsync is true; it registers or syncs
     * the files once at the end of the operation instead (smgrregistersync()
     * / smgrimmedsync()).
     *
     * Doing this before the metadata refresh below is safe in both
     * directions: if the refresh errored out, the request is merely a
     * redundant fsync that the transaction abort makes harmless, while
     * registering after a potential failure point could lose it.  And a
     * checkpoint that sneaks in before the request is absorbed still syncs
     * the sidecars through the dirty_checkpoint mark set below, so durability
     * never depends on this queue entry.
     */
    if (!opts->skip_fsync)
    {
        cfs_register_dirty_file(rl, forknum, CFS_FILE_DATA);
        cfs_register_dirty_file(rl, forknum, CFS_FILE_JOURNAL);
    }
 
    /*
     * Step 4: refresh the cached relation metadata.  Only a genuine extension
     * changes the logical size; a plain overwrite (bgwriter or checkpoint
     * flush) says nothing about it, and a lazy handle's local nblocks is a
     * stale snapshot value.  Publishing it here is what used to resurrect the
     * pre-VACUUM size after an in-place truncate.  Both helpers mark the slot
     * dirty_checkpoint so the checkpointer fsyncs and snapshots the sidecars.
     */
    if (opts->is_extend)
        cfs_map_cache_set_meta(rl, forknum, (uint64) blocknum + 1);
    else
        cfs_map_cache_mark_dirty(rl, forknum);
 
    return CFS_STORAGE_OK;
}