Исходный код СУБД 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
/*-------------------------------------------------------------------------
 * cfs_stats.c
 *    Per-relation CFS statistics: the shared slots, their counters, the
 *    snapshot/enumeration API, and the pg_cfs_stats statsfile
 *    (save at shutdown, restore at startup).  A leaf module: it touches
 *    no other CFS layer.  Dead space has a single publisher, the
 *    checkpoint (which is also the one that truncates the dropped rows
 *    off the map file, so it sees their payloads); compaction resets
 *    the counters with its exact recomputation.
 *
 *    Locking model (QDB-1516 Д3): the counters are pg_atomic_uint64.
 *    Accounting events take the partition lock in LW_SHARED mode, find
 *    the slot through its hash chain and bump the counters with
 *    pg_atomic_fetch_add_u64(); only a miss upgrades to LW_EXCLUSIVE
 *    (release, re-acquire, re-find) to create the slot.  Creation,
 *    eviction, reset and the wholesale publications after a fold or
 *    compaction always run under LW_EXCLUSIVE.
 *
 * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
 * Portions Copyright (c) 2026, Diasoft
 *
 * src/backend/storage/cfs/cfs_stats.c
 *
 *-------------------------------------------------------------------------
 */
 
#include "postgres.h"
 
#include <unistd.h>
 
#include "miscadmin.h"
#include "storage/cfs/cfs.h"
#include "storage/cfs/cfs_cfp.h"
#include "storage/cfs/cfs_guc.h"
#include "storage/cfs/cfs_shmem.h"
#include "storage/cfs/cfs_shmem_internal.h"
#include "storage/cfs/cfs_stats.h"
#include "storage/fd.h"
#include "storage/shmem.h"
#include "utils/timestamp.h"
#include "utils/palloc.h"
#include "utils/memutils.h"
#include "utils/guc.h"
 
/*
 * Partition locks, the flat slot array, the per-partition bucket heads and
 * the stats-domain access clock (allocated in cfs_stats_shmem_init).  The
 * slot count is the cfs_stats_slots_per_partition GUC (frozen in
 * cfs_control->stats_slots_per_part), so the array is indexed through
 * cfs_stats_slot(), not with a compile-time second dimension.
 */
static LWLockPadded *cfs_stats_locks = NULL;
static CfsRelationStats *cfs_stats_slots = NULL;
static int32 *cfs_stats_bucket_heads = NULL;
pg_atomic_uint64 *cfs_stats_clocks = NULL;
 
/* Index the flat statistics slot array by (partition, slot). */
static inline CfsRelationStats *
cfs_stats_slot(int part, int i)
{
    return &cfs_stats_slots[part * cfs_stats_slots_per_partition + i];
}
 
/*
 * Initialise every counter of a freshly claimed (zeroed) slot to zero.
 * Called on the first-boot zeroing pass and whenever a slot is claimed
 * (fresh or evicted): pg_atomic_init_u64 is legal here because the caller
 * either just cleared the memory or runs before any concurrent access.
 */
static void
cfs_stats_counters_init(CfsRelationStats *s)
{
    pg_atomic_init_u64(&s->logical_pages, 0);
    pg_atomic_init_u64(&s->compressed_bytes, 0);
    pg_atomic_init_u64(&s->raw_bytes, 0);
    pg_atomic_init_u64(&s->dead_bytes, 0);
    pg_atomic_init_u64(&s->dead_pages, 0);
    pg_atomic_init_u64(&s->checkpoint_map_rows_written, 0);
    pg_atomic_init_u64(&s->compressed_pages, 0);
    pg_atomic_init_u64(&s->uncompressed_pages, 0);
    pg_atomic_init_u64(&s->read_count, 0);
    pg_atomic_init_u64(&s->read_batch_count, 0);
    pg_atomic_init_u64(&s->read_batched_pages, 0);
    pg_atomic_init_u64(&s->read_fallback_pages, 0);
    pg_atomic_init_u64(&s->write_count, 0);
    pg_atomic_init_u64(&s->compress_count, 0);
    pg_atomic_init_u64(&s->decompress_count, 0);
    pg_atomic_init_u64(&s->crc_failures, 0);
}
 
/*
 * cfs_stats_clock_tick — advance and return the stats-domain access clock
 * of a partition (QDB-1516 Д1).  Unlike the map domain, the accounting
 * paths tick the clock while holding the partition lock only in
 * LW_SHARED mode, so two backends may tick the same partition
 * concurrently: the cells are atomic and the tick is an atomic
 * fetch-add — the acceptable per-partition RMW, in exchange for keeping
 * the whole accounting path free of exclusive locks.  The caller must
 * hold the partition lock in some mode.
 */
uint64
cfs_stats_clock_tick(int part)
{
    Assert(cfs_stats_clocks != NULL);
    Assert(LWLockHeldByMe(&cfs_stats_locks[part].lock));
    return pg_atomic_fetch_add_u64(&cfs_stats_clocks[part], 1) + 1;
}
 
/*
 * cfs_stats_shmem_init — allocate the statistics locks, slots, chain
 * heads and access clock.  Called by CfsShmemInit(); the tranche id comes
 * from the control block the caller owns.
 */
void
cfs_stats_shmem_init(void)
{
    Size        slots_size;
    Size        heads_size;
    bool        found;
    int         i;
 
    /*
     * The slot count is frozen in the control block by the postmaster.  A
     * process attaching to already allocated shared memory (EXEC_BACKEND
     * children) re-parses its own configuration: a different value here
     * means the arrays were laid out for another count, and indexing them
     * would corrupt shared memory — refuse to start instead (the
     * cfs_map_cache_rels_per_partition overflow-hint style).
     */
    if (cfs_control->stats_slots_per_part != cfs_stats_slots_per_partition)
        ereport(ERROR,
                (errcode(ERRCODE_CONFIGURATION_LIMIT_EXCEEDED),
                 errmsg("CFS: statistics slots per partition mismatch"),
                 errdetail("Shared memory holds %d statistics slots per "
                           "partition, but this process is configured "
                           "with %d.",
                           cfs_control->stats_slots_per_part,
                           cfs_stats_slots_per_partition),
                 errhint("Check the configuration parameter "
                         "\"cfs_stats_slots_per_partition\" and restart "
                         "the server with the value it was started "
                         "with.")));
 
    cfs_stats_locks = ShmemInitStruct("CFS Stats 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_stats_locks[i].lock,
                             cfs_control->stats_tranche_id);
    }
 
    /*
     * Stats-domain per-partition access clock: its own CACHELINEALIGN-ed
     * allocation keeps the clock off the partition locks' cache lines; the
     * atomic cells are updated under the partition lock in either mode
     * (see cfs_stats_clock_tick).
     */
    cfs_stats_clocks =
        ShmemInitStruct("CFS Stats Clocks",
                        CACHELINEALIGN((Size) CFS_MAP_CACHE_NUM_PARTITIONS *
                                       sizeof(pg_atomic_uint64)),
                        &found);
    if (!found)
    {
        for (i = 0; i < CFS_MAP_CACHE_NUM_PARTITIONS; i++)
            pg_atomic_init_u64(&cfs_stats_clocks[i], 0);
    }
 
    slots_size = mul_size(sizeof(CfsRelationStats),
                          mul_size(CFS_MAP_CACHE_NUM_PARTITIONS,
                                   cfs_stats_slots_per_partition));
    cfs_stats_slots = ShmemInitStruct("CFS Stats", slots_size, &found);
    if (!found)
    {
        MemSet(cfs_stats_slots, 0, slots_size);
        for (i = 0; i < CFS_MAP_CACHE_NUM_PARTITIONS *
             cfs_stats_slots_per_partition; i++)
            cfs_stats_counters_init(&cfs_stats_slots[i]);
    }
 
    /*
     * Bucket heads of the statistics hash chains (QDB-1516 Д2): all heads
     * start empty (-1), matching the zeroed (all-free) slot array.
     */
    heads_size = mul_size(sizeof(int32),
                          mul_size(CFS_MAP_CACHE_NUM_PARTITIONS,
                                   cfs_stats_slots_per_partition));
    cfs_stats_bucket_heads = ShmemInitStruct("CFS Stats Buckets", heads_size,
                                             &found);
    if (!found)
        MemSet(cfs_stats_bucket_heads, 0xFF, heads_size);
}
 
/* ================================================================
 * Per-partition hash chains over the statistics 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 partition is selected by the
 * low CFS_PART_BITS bits of rel_hash; the multiply (Knuth's 2654435761)
 * folds those partition bits — and every other input bit — into the bits
 * above the shift, so the choice of chain is decorrelated from the choice
 * of partition (mirrors cfs_meta_bucket() in cfs_shmem.c).
 */
static inline int
cfs_stats_bucket(uint32 rel_hash)
{
    uint32      b = rel_hash * 2654435761U;
 
    return (int) ((b >> CFS_PART_BITS) %
                  (uint32) cfs_stats_slots_per_partition);
}
 
/* The bucket-head cell (part, bucket) of the statistics chains. */
static inline int32 *
cfs_stats_head(int part, int bucket)
{
    return &cfs_stats_bucket_heads[part * cfs_stats_slots_per_partition +
                                    bucket];
}
 
/* Partition-relative index of a statistics slot. */
static inline int
cfs_stats_slot_index(int part, const CfsRelationStats *slot)
{
    return (int) (slot -
                  &cfs_stats_slots[part * cfs_stats_slots_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_stats_chain_link(int part, CfsRelationStats *slot)
{
    int         bucket = cfs_stats_bucket(slot->hash);
    int32      *head = cfs_stats_head(part, bucket);
 
    slot->chain_next = *head;
    *head = cfs_stats_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_stats_chain_unlink(int part, CfsRelationStats *slot)
{
    int         idx = cfs_stats_slot_index(part, slot);
    int         bucket = cfs_stats_bucket(slot->hash);
    int32      *head = cfs_stats_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: statistics slot %d not found in its "
                 "hash chain", idx);
        prev = cur;
        cur = cfs_stats_slot(part, cur)->chain_next;
    }
    if (prev == -1)
        *head = slot->chain_next;
    else
        cfs_stats_slot(part, prev)->chain_next = slot->chain_next;
}
 
/*
 * Locate the statistics slot of a relation by walking its hash chain.
 * The caller must hold the partition lock selected by rel_hash in either
 * mode.  Returns NULL when none exists.
 */
static CfsRelationStats *
cfs_stats_find(uint32 rel_hash, RelFileLocatorBackend rlocator,
               ForkNumber forknum)
{
    int         part = rel_hash & CFS_PART_MASK;
    int         bucket = cfs_stats_bucket(rel_hash);
    int         cur;
 
    Assert(LWLockHeldByMe(&cfs_stats_locks[part].lock));
 
    for (cur = *cfs_stats_head(part, bucket); cur != -1;)
    {
        CfsRelationStats *s = cfs_stats_slot(part, cur);
        int         next = s->chain_next;
 
        if (s->hash == rel_hash &&
            cfs_rlbe_eq(s->rlocator, rlocator) &&
            s->forknum == forknum)
            return s;
        cur = next;
    }
    return NULL;
}
 
/*
 * Find or create a statistics slot.  The caller must hold the lock of the
 * partition selected by rel_hash in LW_EXCLUSIVE mode.
 *
 * Creation order (QDB-1516 Д2, mirrors cfs_meta_get_or_create): the key's
 * own chain is searched first; on a miss the first free slot (hash == 0)
 * is taken by a plain scan, and only when no free slot remains is the LRU
 * victim (smallest access_clock) chosen by a full partition scan and
 * unlinked from its chain BEFORE the clear (I3).  A claimed slot is
 * linked at the head of its bucket.  Returns NULL only when the partition
 * holds no slot at all (impossible with the GUC minimum of 4).
 */
static CfsRelationStats *
cfs_stats_get_or_create(uint32 rel_hash, RelFileLocatorBackend rlocator,
                        ForkNumber forknum)
{
    int         part = rel_hash & CFS_PART_MASK;
    int         bucket = cfs_stats_bucket(rel_hash);
    CfsRelationStats *free_slot = NULL;
    CfsRelationStats *victim = NULL;
    uint64      min_clock = PG_UINT64_MAX;
    int         i;
    int         cur;
 
    Assert(LWLockHeldByMeInMode(&cfs_stats_locks[part].lock, LW_EXCLUSIVE));
 
    /* Search the key's own chain (the hit path of the partition). */
    for (cur = *cfs_stats_head(part, bucket); cur != -1;)
    {
        CfsRelationStats *s = cfs_stats_slot(part, cur);
        int         next = s->chain_next;
 
        if (s->hash == rel_hash &&
            cfs_rlbe_eq(s->rlocator, rlocator) &&
            s->forknum == forknum)
            return s;
        cur = next;
    }
 
    /* Miss: take the first free slot of the partition. */
    for (i = 0; i < cfs_stats_slots_per_partition; i++)
    {
        CfsRelationStats *s = cfs_stats_slot(part, i);
 
        if (s->hash == 0)
        {
            free_slot = s;
            break;
        }
    }
 
    /* No free slot: LRU victim among the occupied slots, full scan. */
    if (free_slot == NULL)
    {
        for (i = 0; i < cfs_stats_slots_per_partition; i++)
        {
            CfsRelationStats *s = cfs_stats_slot(part, i);
 
            if (s->hash != 0 && s->access_clock < min_clock)
            {
                min_clock = s->access_clock;
                victim = s;
            }
        }
 
        free_slot = victim;
        if (free_slot != NULL)
        {
            pg_atomic_fetch_add_u64(&cfs_control->evictions, 1);
            cfs_stats_chain_unlink(part, free_slot);
            MemSet(free_slot, 0, sizeof(CfsRelationStats));
            cfs_stats_counters_init(free_slot);
        }
    }
 
    if (free_slot == NULL)
        return NULL;
 
    free_slot->hash = rel_hash;
    free_slot->rlocator = rlocator;
    free_slot->forknum = forknum;
    free_slot->access_clock = cfs_stats_clock_tick(part);
 
    /*
     * QDB-1507 U1: a slot claimed while the crash-boot sweep is still
     * pending starts stale - its zeroed counters know nothing about
     * the dead space accumulated before the crash, exactly like a
     * restored value, so the first measurement resyncs it from the
     * map.  The owners that publish right after claiming (set_dead,
     * note_compaction, resync_dead) clear the mark under the same
     * exclusive partition lock they already hold here, so the
     * created -> published -> stale = false order is preserved.
     */
    if (cfs_control->stats_boot_stale)
        free_slot->stale = true;
 
    /* Insert the claimed slot at the head of its bucket chain (I2). */
    cfs_stats_chain_link(part, free_slot);
    return free_slot;
}
 
/*
 * Find or create the statistics slot for an accounting event (QDB-1516
 * Д3).  The fast path holds the partition lock in LW_SHARED mode: the
 * counters are atomics and the slot pointer stays valid for the whole
 * critical section, because evicting or clearing the slot requires
 * LW_EXCLUSIVE of the same partition.  Only a miss upgrades: release the
 * shared lock, take the exclusive one and re-find through
 * cfs_stats_get_or_create, so a slot created by a concurrent backend in
 * between is reused rather than duplicated.  On return the lock is held
 * in *mode and the caller must release it with that mode.
 */
static CfsRelationStats *
cfs_stats_find_or_create_locked(uint32 rel_hash,
                                RelFileLocatorBackend rlocator,
                                ForkNumber forknum, LWLockMode *mode)
{
    int         part = rel_hash & CFS_PART_MASK;
    CfsRelationStats *s;
 
    LWLockAcquire(&cfs_stats_locks[part].lock, LW_SHARED);
    s = cfs_stats_find(rel_hash, rlocator, forknum);
    if (s != NULL)
    {
        *mode = LW_SHARED;
        return s;
    }
    LWLockRelease(&cfs_stats_locks[part].lock);
 
    LWLockAcquire(&cfs_stats_locks[part].lock, LW_EXCLUSIVE);
    *mode = LW_EXCLUSIVE;
    return cfs_stats_get_or_create(rel_hash, rlocator, forknum);
}
 
/*
 * Touch the slot's LRU clock.  A plain field write is enough here: the
 * value only orders eviction, and its only readers (victim scans) run
 * under LW_EXCLUSIVE.  Two backends accounting the same relation under
 * LW_SHARED may race the store - one of their ticks is lost, which can
 * reorder the LRU by a single tick but never loses a relation or mixes
 * counters.
 */
static inline void
cfs_stats_touch(int part, CfsRelationStats *s)
{
    s->access_clock = cfs_stats_clock_tick(part);
}
 
void
cfs_stats_count_read(RelFileLocatorBackend rlocator, ForkNumber forknum,
                     uint64 compressed_bytes)
{
    uint32      rel_hash = cfs_cache_hash_rel(rlocator, forknum);
    int         part = rel_hash & CFS_PART_MASK;
    CfsRelationStats *s;
    LWLockMode  mode;
 
    s = cfs_stats_find_or_create_locked(rel_hash, rlocator, forknum, &mode);
    if (s != NULL)
    {
        pg_atomic_fetch_add_u64(&s->read_count, 1);
        pg_atomic_fetch_add_u64(&s->decompress_count, 1);
        cfs_stats_touch(part, s);
    }
    LWLockRelease(&cfs_stats_locks[part].lock);
}
 
/*
 * Batched-read accounting, see cfs_stats.h.  Both counters share the same
 * partition lock pattern as cfs_stats_count_read(); they run after the
 * read itself succeeded, so no accounting happens for failed reads.
 */
void
cfs_stats_count_read_span(RelFileLocatorBackend rlocator, ForkNumber forknum,
                          uint32 npages)
{
    uint32      rel_hash = cfs_cache_hash_rel(rlocator, forknum);
    int         part = rel_hash & CFS_PART_MASK;
    CfsRelationStats *s;
    LWLockMode  mode;
 
    s = cfs_stats_find_or_create_locked(rel_hash, rlocator, forknum, &mode);
    if (s != NULL)
    {
        pg_atomic_fetch_add_u64(&s->read_batch_count, 1);
        pg_atomic_fetch_add_u64(&s->read_batched_pages, npages);
        cfs_stats_touch(part, s);
    }
    LWLockRelease(&cfs_stats_locks[part].lock);
}
 
void
cfs_stats_count_read_fallback(RelFileLocatorBackend rlocator,
                              ForkNumber forknum, uint32 npages)
{
    uint32      rel_hash = cfs_cache_hash_rel(rlocator, forknum);
    int         part = rel_hash & CFS_PART_MASK;
    CfsRelationStats *s;
    LWLockMode  mode;
 
    s = cfs_stats_find_or_create_locked(rel_hash, rlocator, forknum, &mode);
    if (s != NULL)
    {
        pg_atomic_fetch_add_u64(&s->read_fallback_pages, npages);
        cfs_stats_touch(part, s);
    }
    LWLockRelease(&cfs_stats_locks[part].lock);
}
 
void
cfs_stats_count_write(RelFileLocatorBackend rlocator, ForkNumber forknum,
                      uint64 compressed_bytes, bool is_raw)
{
    uint32      rel_hash = cfs_cache_hash_rel(rlocator, forknum);
    int         part = rel_hash & CFS_PART_MASK;
    CfsRelationStats *s;
    LWLockMode  mode;
 
    s = cfs_stats_find_or_create_locked(rel_hash, rlocator, forknum, &mode);
    if (s != NULL)
    {
        pg_atomic_fetch_add_u64(&s->write_count, 1);
        pg_atomic_fetch_add_u64(&s->compress_count, 1);
        if (is_raw)
        {
            pg_atomic_fetch_add_u64(&s->raw_bytes, compressed_bytes);
            pg_atomic_fetch_add_u64(&s->uncompressed_pages, 1);
        }
        else
        {
            pg_atomic_fetch_add_u64(&s->compressed_bytes, compressed_bytes);
            pg_atomic_fetch_add_u64(&s->compressed_pages, 1);
        }
        cfs_stats_touch(part, s);
    }
    LWLockRelease(&cfs_stats_locks[part].lock);
}
 
/*
 * cfs_stats_note_logical_pages — the logical-size high-water mark: only
 * grows, never shrinks (a truncate is accounted separately by the
 * caller).  Split out of cfs_map_cache_set_meta so the slot array stays
 * private to this module.  The read-modify-write "grow only" comparison
 * is not commutative, so this stays on the exclusive path.
 */
void
cfs_stats_note_logical_pages(uint32 rel_hash, RelFileLocatorBackend rlocator,
                             ForkNumber forknum, uint64 nblocks)
{
    CfsRelationStats *s2;
    int         spart = rel_hash & CFS_PART_MASK;
 
    LWLockAcquire(&cfs_stats_locks[spart].lock, LW_EXCLUSIVE);
    s2 = cfs_stats_get_or_create(rel_hash, rlocator, forknum);
    if (s2 != NULL)
    {
        if (nblocks > pg_atomic_read_u64(&s2->logical_pages))
            pg_atomic_write_u64(&s2->logical_pages, nblocks);
        cfs_stats_touch(spart, s2);
    }
    LWLockRelease(&cfs_stats_locks[spart].lock);
}
 
void
cfs_stats_set_dead(RelFileLocatorBackend rlocator, ForkNumber forknum,
                   uint64 dead_bytes, uint64 dead_pages_add)
{
    uint32      rel_hash = cfs_cache_hash_rel(rlocator, forknum);
    int         part = rel_hash & CFS_PART_MASK;
    CfsRelationStats *s;
 
    LWLockAcquire(&cfs_stats_locks[part].lock, LW_EXCLUSIVE);
    s = cfs_stats_get_or_create(rel_hash, rlocator, forknum);
    if (s != NULL)
    {
        /*
         * dead_bytes is set wholesale by its owner: the checkpoint publishes
         * the previous value plus its fold's delta (superseded payloads and,
         * in the crash-recovery window, truncated ones), and compaction -
         * which walks the live rows - publishes the exact recomputation.
         * dead_pages accumulates the checkpoint deltas: the folds'
         * supersession counts plus the rows the truncating RESIZE dropped (no
         * other source exists, so the counter reads "superseded page versions
         * and dropped truncation rows since the last compaction or reset").
         */
        pg_atomic_write_u64(&s->dead_bytes, dead_bytes);
        pg_atomic_fetch_add_u64(&s->dead_pages, dead_pages_add);
        /*
         * The owner's publication makes the restored value current, so
         * the crash-boot resync must not overwrite it (QDB-1507 U1).
         */
        s->stale = false;
        cfs_stats_touch(part, s);
    }
    LWLockRelease(&cfs_stats_locks[part].lock);
}
 
void
cfs_stats_count_checkpoint_rows(RelFileLocatorBackend rlocator,
                                ForkNumber forknum, uint64 nrows)
{
    uint32      rel_hash = cfs_cache_hash_rel(rlocator, forknum);
    int         part = rel_hash & CFS_PART_MASK;
    CfsRelationStats *s;
    LWLockMode  mode;
 
    s = cfs_stats_find_or_create_locked(rel_hash, rlocator, forknum, &mode);
    if (s != NULL)
    {
        pg_atomic_fetch_add_u64(&s->checkpoint_map_rows_written, nrows);
        cfs_stats_touch(part, s);
    }
    LWLockRelease(&cfs_stats_locks[part].lock);
}
 
void
cfs_stats_note_compaction(RelFileLocatorBackend rlocator, ForkNumber forknum,
                          int64 ts)
{
    uint32      rel_hash = cfs_cache_hash_rel(rlocator, forknum);
    int         part = rel_hash & CFS_PART_MASK;
    CfsRelationStats *s;
 
    LWLockAcquire(&cfs_stats_locks[part].lock, LW_EXCLUSIVE);
    s = cfs_stats_get_or_create(rel_hash, rlocator, forknum);
    if (s != NULL)
    {
        s->last_compaction = ts;
        pg_atomic_write_u64(&s->dead_bytes, 0);
        pg_atomic_write_u64(&s->dead_pages, 0);
        /*
         * Compaction publishes its exact recomputation (QDB-1507 U1).
         */
        s->stale = false;
        cfs_stats_touch(part, s);
    }
    LWLockRelease(&cfs_stats_locks[part].lock);
}
 
/*
 * QDB-1507 U1: the crash-boot resync marker - an empty file whose
 * presence is the signal.  Written at a clean shutdown that overtook
 * the still-pending sweep; unlinked only when the sweep retires
 * (cfs_stats_boot_sweep_done), never at boot, so an interrupted
 * start loses nothing.
 */
#define CFS_STATS_SWEEP_PENDING_FILENAME    "pg_cfs_stats_resync"
 
/*
 * cfs_stats_slot_stale - does the slot's dead_bytes predate the last
 * crash?  The slot is looked up under the partition's shared lock and
 * is never created here; a missing slot reports false (the callers
 * decide separately what a missing entry means: the crash-boot sweep
 * resyncs unconditionally, the checkpoint samples its base from the
 * map).
 */
bool
cfs_stats_slot_stale(RelFileLocatorBackend rlocator, ForkNumber forknum)
{
    uint32      rel_hash = cfs_cache_hash_rel(rlocator, forknum);
    int         part = rel_hash & CFS_PART_MASK;
    CfsRelationStats *s;
    bool        stale = false;
 
    LWLockAcquire(&cfs_stats_locks[part].lock, LW_SHARED);
    s = cfs_stats_find(rel_hash, rlocator, forknum);
    if (s != NULL)
        stale = s->stale;
    LWLockRelease(&cfs_stats_locks[part].lock);
    return stale;
}
 
/*
 * cfs_stats_resync_dead - publish a map-derived dead_bytes into a
 * stale slot.  When the slot is missing and create_slot is set, the
 * slot is created and the value is published unconditionally (a fresh
 * slot has no owner to race with).  An existing stale slot takes the
 * value and loses the stale mark; an existing non-stale slot keeps its
 * value - the conditional publication prevents a stale resync scan
 * from regressing a newer owner's exact value (a checkpoint's or a
 * compaction's).  Returns true when this call published the value.
 */
bool
cfs_stats_resync_dead(RelFileLocatorBackend rlocator, ForkNumber forknum,
                      uint64 dead_bytes, bool create_slot)
{
    uint32      rel_hash = cfs_cache_hash_rel(rlocator, forknum);
    int         part = rel_hash & CFS_PART_MASK;
    CfsRelationStats *s;
    bool        created = false;
    bool        published = false;
 
    LWLockAcquire(&cfs_stats_locks[part].lock, LW_EXCLUSIVE);
    s = cfs_stats_find(rel_hash, rlocator, forknum);
    if (s == NULL && create_slot)
    {
        s = cfs_stats_get_or_create(rel_hash, rlocator, forknum);
        created = (s != NULL);
    }
    if (s != NULL && (created || s->stale))
    {
        pg_atomic_write_u64(&s->dead_bytes, dead_bytes);
        s->stale = false;
        cfs_stats_touch(part, s);
        published = true;
    }
    LWLockRelease(&cfs_stats_locks[part].lock);
    return published;
}
 
/*
 * cfs_stats_forget_stale_flags - clear the stale mark of every
 * occupied slot.  Called at a clean boot: the persisted values were
 * written at the clean shutdown that produced them, so they stay
 * authoritative and no map resync must run on a clean start
 * (QDB-1507 U1).
 */
void
cfs_stats_forget_stale_flags(void)
{
    int         p;
    int         i;
 
    for (p = 0; p < CFS_MAP_CACHE_NUM_PARTITIONS; p++)
    {
        LWLockAcquire(&cfs_stats_locks[p].lock, LW_EXCLUSIVE);
        for (i = 0; i < cfs_stats_slots_per_partition; i++)
        {
            CfsRelationStats *s = cfs_stats_slot(p, i);
 
            if (s->hash != 0)
                s->stale = false;
        }
        LWLockRelease(&cfs_stats_locks[p].lock);
    }
}
 
/*
 * cfs_stats_boot_after_crash - arm the one dead-space resync pass of
 * the first full background worker cycle after a crash boot (the
 * restored counters predate the crash; QDB-1507 U1).  The sweep is
 * also armed at a clean boot that found the persistent resync marker
 * (cfs_stats_boot_restore_marker): a clean shutdown overtook it, and
 * the persisted values are equally unresynced.
 */
void
cfs_stats_boot_after_crash(void)
{
    cfs_control->stats_boot_stale = true;
}
 
/*
 * cfs_stats_boot_sweep_pending - is the crash-boot resync pass still
 * ahead (QDB-1507 U1)?  Read by StartupXLOG to decide whether a
 * clean boot may declare the restored values authoritative, by the
 * statsfile writer to decide whether the resync marker must persist,
 * and by the background worker to gate the sweep.
 */
bool
cfs_stats_boot_sweep_pending(void)
{
    return cfs_control->stats_boot_stale;
}
 
/*
 * cfs_stats_boot_sweep_done - retire the crash-boot resync pass after
 * the first complete launcher cycle (every database serviced, no
 * pause, no early exit); relations the sweep could not heal keep
 * their stale slots and are resynced by their next checkpoint's
 * map-based base instead (QDB-1507 U1).
 *
 * The durable marker is removed HERE, not at the boot that armed the
 * sweep: removing it at boot would leave a start killed before the
 * first full cycle (whose control file may still read as a clean
 * shutdown) with no carrier of the obligation at all.  The unlink
 * runs before the shared flag clears, and a non-ENOENT failure keeps
 * the flag armed, so the next full cycle retries the retirement;
 * ENOENT is the norm - a crash boot never wrote the marker at all.
 */
void
cfs_stats_boot_sweep_done(void)
{
    char       *markerfile;
 
    if (!cfs_control->stats_boot_stale)
        return;
 
    markerfile = psprintf("%s/%s", DataDir,
                          CFS_STATS_SWEEP_PENDING_FILENAME);
    if (unlink(markerfile) != 0 && errno != ENOENT)
    {
        ereport(LOG,
                (errcode_for_file_access(),
                 errmsg("CFS: could not remove statistics resync "
                        "marker \"%s\": %m",
                        markerfile)));
        pfree(markerfile);
        return;
    }
 
    pfree(markerfile);
    cfs_control->stats_boot_stale = false;
}
 
void
cfs_stats_count_crc_failure(RelFileLocatorBackend rlocator, ForkNumber forknum)
{
    uint32      rel_hash = cfs_cache_hash_rel(rlocator, forknum);
    int         part = rel_hash & CFS_PART_MASK;
    CfsRelationStats *s;
    LWLockMode  mode;
 
    s = cfs_stats_find_or_create_locked(rel_hash, rlocator, forknum, &mode);
    if (s != NULL)
    {
        pg_atomic_fetch_add_u64(&s->crc_failures, 1);
        cfs_stats_touch(part, s);
    }
    LWLockRelease(&cfs_stats_locks[part].lock);
}
 
/*
 * Copy the counters of one slot into a snapshot.  Each counter is read
 * atomically, so every single value is consistent; cross-counter
 * consistency of the whole snapshot is not guaranteed (the pgstat
 * approximation).  The caller holds the partition lock (either mode).
 */
static void
cfs_stats_snapshot_copy(CfsRelationStats *s, CfsStatsSnapshot *out)
{
    out->found = true;
    out->logical_pages = pg_atomic_read_u64(&s->logical_pages);
    out->compressed_bytes = pg_atomic_read_u64(&s->compressed_bytes);
    out->raw_bytes = pg_atomic_read_u64(&s->raw_bytes);
    out->dead_bytes = pg_atomic_read_u64(&s->dead_bytes);
    out->dead_pages = pg_atomic_read_u64(&s->dead_pages);
    out->checkpoint_map_rows_written =
        pg_atomic_read_u64(&s->checkpoint_map_rows_written);
    out->compressed_pages = pg_atomic_read_u64(&s->compressed_pages);
    out->uncompressed_pages = pg_atomic_read_u64(&s->uncompressed_pages);
    out->read_count = pg_atomic_read_u64(&s->read_count);
    out->read_batch_count = pg_atomic_read_u64(&s->read_batch_count);
    out->read_batched_pages = pg_atomic_read_u64(&s->read_batched_pages);
    out->read_fallback_pages = pg_atomic_read_u64(&s->read_fallback_pages);
    out->write_count = pg_atomic_read_u64(&s->write_count);
    out->compress_count = pg_atomic_read_u64(&s->compress_count);
    out->decompress_count = pg_atomic_read_u64(&s->decompress_count);
    out->crc_failures = pg_atomic_read_u64(&s->crc_failures);
    out->last_reset = s->last_reset;
    out->last_compaction = s->last_compaction;
}
 
bool
cfs_stats_snapshot(RelFileLocatorBackend rlocator, ForkNumber forknum,
                   CfsStatsSnapshot *out)
{
    uint32      rel_hash = cfs_cache_hash_rel(rlocator, forknum);
    int         part = rel_hash & CFS_PART_MASK;
    CfsRelationStats *s;
 
    MemSet(out, 0, sizeof(CfsStatsSnapshot));
 
    LWLockAcquire(&cfs_stats_locks[part].lock, LW_SHARED);
    s = cfs_stats_find(rel_hash, rlocator, forknum);
    if (s != NULL)
        cfs_stats_snapshot_copy(s, out);
    LWLockRelease(&cfs_stats_locks[part].lock);
    return out->found;
}
 
/*
 * Zero the counters of one occupied slot, keeping its identity.  The
 * caller holds the partition lock exclusively: reset cannot interleave
 * with an atomic add (creation/eviction/reset stay exclusive by design).
 */
static void
cfs_stats_reset_slot(CfsRelationStats *s, bool clear_compaction)
{
    pg_atomic_write_u64(&s->logical_pages, 0);
    pg_atomic_write_u64(&s->compressed_bytes, 0);
    pg_atomic_write_u64(&s->raw_bytes, 0);
    pg_atomic_write_u64(&s->dead_bytes, 0);
    pg_atomic_write_u64(&s->dead_pages, 0);
    pg_atomic_write_u64(&s->checkpoint_map_rows_written, 0);
    pg_atomic_write_u64(&s->compressed_pages, 0);
    pg_atomic_write_u64(&s->uncompressed_pages, 0);
    pg_atomic_write_u64(&s->read_count, 0);
    pg_atomic_write_u64(&s->read_batch_count, 0);
    pg_atomic_write_u64(&s->read_batched_pages, 0);
    pg_atomic_write_u64(&s->read_fallback_pages, 0);
    pg_atomic_write_u64(&s->write_count, 0);
    pg_atomic_write_u64(&s->compress_count, 0);
    pg_atomic_write_u64(&s->decompress_count, 0);
    pg_atomic_write_u64(&s->crc_failures, 0);
    s->last_reset = (int64) GetCurrentTimestamp();
    if (clear_compaction)
        s->last_compaction = 0;
}
 
void
cfs_stats_reset(RelFileLocatorBackend rlocator, ForkNumber forknum)
{
    uint32      rel_hash = cfs_cache_hash_rel(rlocator, forknum);
    int         part = rel_hash & CFS_PART_MASK;
    CfsRelationStats *s;
 
    LWLockAcquire(&cfs_stats_locks[part].lock, LW_EXCLUSIVE);
    s = cfs_stats_find(rel_hash, rlocator, forknum);
    if (s != NULL)
    {
        /* Keep the slot but zero the counters. */
        cfs_stats_reset_slot(s, false);
        cfs_stats_touch(part, s);
    }
    LWLockRelease(&cfs_stats_locks[part].lock);
}
 
/*
 * cfs_stats_reset_all — zero the counters of every statistics slot across
 * all partitions.  Used by pg_cfs_reset_stats(NULL).  The relation identity
 * of each slot is preserved so a subsequent snapshot still 'finds' the
 * relation, but the per-relation last_compaction timestamp is also cleared
 * because the whole point of a reset is a clean slate.
 */
void
cfs_stats_reset_all(void)
{
    int         p;
    int         i;
 
    for (p = 0; p < CFS_MAP_CACHE_NUM_PARTITIONS; p++)
    {
        LWLockAcquire(&cfs_stats_locks[p].lock, LW_EXCLUSIVE);
        for (i = 0; i < cfs_stats_slots_per_partition; i++)
        {
            CfsRelationStats *s = cfs_stats_slot(p, i);
 
            if (s->hash != 0)
            {
                cfs_stats_reset_slot(s, true);
                cfs_stats_touch(p, s);
            }
        }
        LWLockRelease(&cfs_stats_locks[p].lock);
    }
}
 
/*
 * cfs_stats_for_each — enumerate every populated statistics slot and invoke
 * the callback with a consistent snapshot.  Used by the pg_stat_cfs view.
 */
void
cfs_stats_for_each(CfsStatsEnumCB cb, void *arg)
{
    int         p;
    int         i;
 
    for (p = 0; p < CFS_MAP_CACHE_NUM_PARTITIONS; p++)
    {
        LWLockAcquire(&cfs_stats_locks[p].lock, LW_SHARED);
        for (i = 0; i < cfs_stats_slots_per_partition; i++)
        {
            CfsRelationStats *s = cfs_stats_slot(p, i);
            CfsStatsSnapshot snap;
 
            if (s->hash == 0)
                continue;
 
            MemSet(&snap, 0, sizeof(snap));
            cfs_stats_snapshot_copy(s, &snap);
 
            if (!cb(s->rlocator, s->forknum, &snap, arg))
            {
                LWLockRelease(&cfs_stats_locks[p].lock);
                return;
            }
        }
        LWLockRelease(&cfs_stats_locks[p].lock);
    }
}
 
/* ================================================================
 * Persistence of the per-relation statistics
 *
 * The PG15 pgstat pattern (pgstat_before_server_shutdown /
 * pgstat_restore_stats): the checkpointer writes the counters to
 * PGDATA/pg_cfs_stats at a regular shutdown, only on proc_exit(0), and
 * the postmaster restores them at startup.  Without this the background
 * compaction worker loses the accumulated dead-space estimates to every
 * maintenance restart: dead_bytes comes back as 0 and the relations stop
 * being candidates until new writes re-fragment them.  A crash loses
 * everything since the last regular shutdown -- the same degradation
 * vanilla pgstat accepts.
 * ================================================================
 */
 
#define CFS_STATS_FILE_FORMATID     UINT64CONST(0x01C5F51A9D)
#define CFS_STATS_FILENAME          "pg_cfs_stats"
#define CFS_STATS_TMPNAME           "pg_cfs_stats.tmp"
 
typedef struct CfsStatsFileHeader
{
    uint64      formatid;
    uint32      nentries;
    uint32      entry_size;
}           CfsStatsFileHeader;
 
typedef struct CfsStatsFileEntry
{
    RelFileLocatorBackend rlocator;
    ForkNumber  forknum;
    CfsStatsSnapshot stats;
}           CfsStatsFileEntry;
 
typedef struct CfsStatsCollectCtx
{
    CfsStatsFileEntry *entries;
    int         n;
    int         max;
}           CfsStatsCollectCtx;
 
static bool
cfs_stats_collect_cb(RelFileLocatorBackend rlocator, ForkNumber forknum,
                     const CfsStatsSnapshot *stats, void *arg)
{
    CfsStatsCollectCtx *ctx = (CfsStatsCollectCtx *) arg;
 
    if (ctx->n >= ctx->max)
        return false;           /* cannot happen: slots bound entries */
 
    ctx->entries[ctx->n].rlocator = rlocator;
    ctx->entries[ctx->n].forknum = forknum;
    ctx->entries[ctx->n].stats = *stats;
    ctx->n++;
    return true;
}
 
/*
 * Copy the persisted counters into a fresh slot.  The hash and access
 * clock are recomputed: they are runtime bookkeeping, not data.  The slot
 * is linked into its bucket chain exactly like a runtime creation would
 * (invariant I2); the partition lock is taken even though only the
 * postmaster runs here, so the chain invariants hold uniformly.
 *
 * Returns false when the partition holds no free slot (skew): the
 * caller counts the entry as not restored instead of silently
 * dropping it.
 */
static bool
cfs_stats_restore_entry(const CfsStatsFileEntry * e)
{
    uint32      rel_hash = cfs_cache_hash_rel(e->rlocator, e->forknum);
    int         part = rel_hash & CFS_PART_MASK;
    CfsRelationStats *s = NULL;
    int         i;
    bool        ok = false;
 
    LWLockAcquire(&cfs_stats_locks[part].lock, LW_EXCLUSIVE);
 
    for (i = 0; i < cfs_stats_slots_per_partition; i++)
    {
        if (cfs_stats_slot(part, i)->hash == 0)
        {
            s = cfs_stats_slot(part, i);
            break;
        }
    }
    if (s == NULL)
    {
        LWLockRelease(&cfs_stats_locks[part].lock);
        return false;           /* partition skew: skip the extra entry */
    }
 
    s->rlocator = e->rlocator;
    s->forknum = e->forknum;
    s->hash = rel_hash;
    pg_atomic_write_u64(&s->logical_pages, e->stats.logical_pages);
    pg_atomic_write_u64(&s->compressed_bytes, e->stats.compressed_bytes);
    pg_atomic_write_u64(&s->raw_bytes, e->stats.raw_bytes);
    pg_atomic_write_u64(&s->dead_bytes, e->stats.dead_bytes);
    pg_atomic_write_u64(&s->dead_pages, e->stats.dead_pages);
    pg_atomic_write_u64(&s->checkpoint_map_rows_written,
                        e->stats.checkpoint_map_rows_written);
    pg_atomic_write_u64(&s->compressed_pages, e->stats.compressed_pages);
    pg_atomic_write_u64(&s->uncompressed_pages, e->stats.uncompressed_pages);
    pg_atomic_write_u64(&s->read_count, e->stats.read_count);
    pg_atomic_write_u64(&s->read_batch_count, e->stats.read_batch_count);
    pg_atomic_write_u64(&s->read_batched_pages, e->stats.read_batched_pages);
    pg_atomic_write_u64(&s->read_fallback_pages, e->stats.read_fallback_pages);
    pg_atomic_write_u64(&s->write_count, e->stats.write_count);
    pg_atomic_write_u64(&s->compress_count, e->stats.compress_count);
    pg_atomic_write_u64(&s->decompress_count, e->stats.decompress_count);
    pg_atomic_write_u64(&s->crc_failures, e->stats.crc_failures);
    s->last_reset = e->stats.last_reset;
    s->last_compaction = e->stats.last_compaction;
    /*
     * The restored dead_bytes may predate the last crash (the file is
     * written only at a clean shutdown): mark the value stale, so the
     * first measurement after a crash boot resyncs it from the map
     * (QDB-1507 U1).  A clean boot clears the marks again
     * (cfs_stats_forget_stale_flags).
     */
    s->stale = true;
    cfs_stats_touch(part, s);
    cfs_stats_chain_link(part, s);
    ok = true;
 
    LWLockRelease(&cfs_stats_locks[part].lock);
    return ok;
}
 
void
cfs_stats_write_statsfile(int code, Datum arg)
{
    MemoryContext oldctx;
    CfsStatsCollectCtx ctx;
    CfsStatsFileHeader hdr;
    char       *tmpfile;
    char       *statfile;
    FILE       *fp;
 
    /* Only a regular shutdown persists the counters (pgstat pattern). */
    if (code != 0)
        return;
 
    /* Single writer by construction (registered in the checkpointer). */
    if (cfs_control->stats_saved)
        return;
 
    tmpfile = psprintf("%s/%s", DataDir, CFS_STATS_TMPNAME);
    statfile = psprintf("%s/%s", DataDir, CFS_STATS_FILENAME);
 
    oldctx = MemoryContextSwitchTo(TopMemoryContext);
    ctx.max = CFS_MAP_CACHE_NUM_PARTITIONS * cfs_stats_slots_per_partition;
    ctx.entries = palloc(sizeof(CfsStatsFileEntry) * ctx.max);
    ctx.n = 0;
    cfs_stats_for_each(cfs_stats_collect_cb, &ctx);
 
    hdr.formatid = CFS_STATS_FILE_FORMATID;
    hdr.nentries = ctx.n;
    hdr.entry_size = sizeof(CfsStatsFileEntry);
 
    if ((fp = AllocateFile(tmpfile, "wb")) == NULL)
    {
        ereport(LOG,
                (errcode_for_file_access(),
                 errmsg("CFS: could not open \"%s\" for writing: %m",
                        tmpfile)));
    }
    else if (fwrite(&hdr, sizeof(hdr), 1, fp) != 1 ||
             fwrite(ctx.entries, sizeof(CfsStatsFileEntry), ctx.n, fp)
             != (size_t) ctx.n ||
             fflush(fp) != 0 ||
             pg_fsync(fileno(fp)) != 0)
    {
        ereport(LOG,
                (errcode_for_file_access(),
                 errmsg("CFS: could not write statistics file \"%s\": %m",
                        tmpfile)));
        FreeFile(fp);
        unlink(tmpfile);
    }
    else if (FreeFile(fp) != 0)
    {
        ereport(LOG,
                (errcode_for_file_access(),
                 errmsg("CFS: could not write statistics file \"%s\": %m",
                        tmpfile)));
        unlink(tmpfile);
    }
    else if (durable_rename(tmpfile, statfile, LOG) != 0)
    {
        /* durable_rename has already logged the failure. */
    }
    else
    {
        cfs_control->stats_saved = true;
        ereport(DEBUG1,
                (errmsg("CFS: wrote %d per-relation statistics entries to \"%s\"",
                        ctx.n, statfile)));
 
        /*
         * QDB-1507 U1: a clean shutdown that overtook the crash-boot
         * sweep persists values that were never resynced.  Record that
         * durably: the next - clean! - start must keep the sweep armed
         * instead of declaring the just-persisted values
         * authoritative.  The marker is removed only by the sweep
         * itself (cfs_stats_boot_sweep_done): with the sweep already
         * completed the pending flag is clear and this writer creates
         * nothing, and a start interrupted before the sweep keeps the
         * obligation on disk.  A creation failure is only LOG: the
         * degradation is that a clean restart after this one trusts
         * understated values - the exact window the marker closes.
         */
        if (cfs_stats_boot_sweep_pending())
        {
            char       *markerfile =
                psprintf("%s/%s", DataDir,
                         CFS_STATS_SWEEP_PENDING_FILENAME);
            int         mfd = OpenTransientFile(markerfile,
                                                O_CREAT | O_WRONLY |
                                                O_TRUNC | PG_BINARY);
 
            if (mfd < 0)
                ereport(LOG,
                        (errcode_for_file_access(),
                         errmsg("CFS: could not create statistics resync "
                                "marker \"%s\": %m",
                                markerfile)));
            else
            {
                if (pg_fsync(mfd) != 0)
                    ereport(LOG,
                            (errcode_for_file_access(),
                             errmsg("CFS: could not fsync statistics resync "
                                    "marker \"%s\": %m",
                                    markerfile)));
                CloseTransientFile(mfd);
                cfs_fsync_parent_dir(markerfile, LOG);
            }
            pfree(markerfile);
        }
    }
 
    MemoryContextSwitchTo(oldctx);
}
 
void
cfs_stats_restore_statsfile(void)
{
    char       *statfile = psprintf("%s/%s", DataDir, CFS_STATS_FILENAME);
    CfsStatsFileHeader hdr;
    CfsStatsFileEntry *entries = NULL;
    FILE       *fp;
    int         i;
 
    if ((fp = AllocateFile(statfile, "rb")) == NULL)
        return;                 /* first boot: nothing to restore */
 
    if (fread(&hdr, sizeof(hdr), 1, fp) != 1 ||
        hdr.formatid != CFS_STATS_FILE_FORMATID ||
        hdr.entry_size != sizeof(CfsStatsFileEntry) ||
        hdr.nentries > CFS_MAP_CACHE_NUM_PARTITIONS *
        cfs_stats_slots_per_partition)
        goto discard;
 
    entries = palloc(hdr.nentries * sizeof(CfsStatsFileEntry));
    if (fread(entries, sizeof(CfsStatsFileEntry), hdr.nentries, fp)
        != hdr.nentries)
        goto discard;
    FreeFile(fp);
    fp = NULL;
 
    /*
     * All slots are free at this point: postmaster, before any child.  A full
     * partition (skew) still skips its extra entries, so the LOG below
     * reports how many were actually restored, never just how many were read.
     */
    {
        int         restored = 0;
 
        for (i = 0; i < hdr.nentries; i++)
        {
            if (cfs_stats_restore_entry(&entries[i]))
                restored++;
        }
 
        ereport(LOG,
                (errmsg("CFS: restored %d of %d per-relation statistics entries from \"%s\"",
                        restored, hdr.nentries, statfile)));
    }
    return;
 
discard:
    if (fp)
        FreeFile(fp);
    ereport(LOG,
            (errmsg("CFS: discarding invalid statistics file \"%s\"",
                    statfile)));
}
 
/*
 * cfs_stats_boot_restore_marker - arm the sweep from the persistent
 * crash-boot resync marker (QDB-1507 U1).  A clean shutdown that
 * happened before the sweep completed wrote the marker next to the
 * stats file: the values it persisted are just as unresynced as the
 * ones the crash left, so the next boot - a clean one, where
 * StartupXLOG would otherwise declare them authoritative - must keep
 * the sweep armed.
 *
 * Presence detection only: the marker is NOT unlinked here.  It is
 * the durable carrier of the still-unfulfilled obligation, so a boot
 * killed before the first full cycle (whose control file can still
 * read as a clean shutdown) loses nothing - the marker survives and
 * the next boot re-arms; it is removed only when the sweep itself
 * retires (cfs_stats_boot_sweep_done).  Runs in the postmaster
 * (CfsShmemInit), before StartupXLOG's crash/clean decision.
 */
void
cfs_stats_boot_restore_marker(void)
{
    char       *markerfile = psprintf("%s/%s", DataDir,
                                      CFS_STATS_SWEEP_PENDING_FILENAME);
    FILE       *fp;
 
    if ((fp = AllocateFile(markerfile, "rb")) != NULL)
    {
        FreeFile(fp);
        cfs_control->stats_boot_stale = true;
    }
 
    pfree(markerfile);
}