-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathpg_stat_kcache.c
1335 lines (1137 loc) · 33.2 KB
/
pg_stat_kcache.c
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
/*---------------
* pg_stat_kcache
*
* Provides basic statistics about real I/O done by the filesystem layer.
* This way, calculating a real hit-ratio is doable. Also provides basis
* statistics about CPU usage.
*
* Large portions of code freely inspired by pg_stat_plans. Thanks to Peter
* Geoghegan for this great extension.
*
* This program is open source, licensed under the PostgreSQL license.
* For license terms, see the LICENSE file.
*
*/
#include "postgres.h"
#include <unistd.h>
/*
* pg16 removed the configure probe for getrusage. Simply define it for all
* platforms except Windows to keep existing code backward compatible.
*/
#if PG_VERSION_NUM >= 160000
#ifndef WIN32
#define HAVE_GETRUSAGE
#endif /* HAVE_GETRUSAGE */
#endif /* pg16+ */
#if PG_VERSION_NUM < 160000
#ifdef HAVE_SYS_RESOURCE_H
#include <sys/time.h>
#include <sys/resource.h>
#endif /* HAVE_SYS_RESOURCE_H */
#ifndef HAVE_GETRUSAGE
#include "rusagestub.h"
#endif /* !HAVE_GETRUSAGE */
#endif /* pg16- */
#include "access/hash.h"
#if PG_VERSION_NUM >= 90600
#include "access/parallel.h"
#endif
#include "executor/executor.h"
#include "funcapi.h"
#include "miscadmin.h"
#if PG_VERSION_NUM >= 130000
#include "optimizer/planner.h"
#endif
#include "pgstat.h"
#if PG_VERSION_NUM >= 90600
#include "postmaster/autovacuum.h"
#endif
#if PG_VERSION_NUM >= 120000
#include "replication/walsender.h"
#endif
#include "storage/fd.h"
#include "storage/ipc.h"
#include "storage/spin.h"
#include "utils/builtins.h"
#include "utils/guc.h"
#if PG_VERSION_NUM >= 160000
#include "utils/pg_rusage.h"
#endif
#include "utils/timestamp.h"
#include "pg_stat_kcache.h"
PG_MODULE_MAGIC;
#if PG_VERSION_NUM >= 90300
#define PGSK_DUMP_FILE "pg_stat/pg_stat_kcache.stat"
#else
#define PGSK_DUMP_FILE "global/pg_stat_kcache.stat"
#endif
/* In PostgreSQL 11, queryid becomes a uint64 internally.
*/
#if PG_VERSION_NUM >= 110000
typedef uint64 pgsk_queryid;
#else
typedef uint32 pgsk_queryid;
#endif
#define USAGE_INCREASE (1.0)
#define USAGE_DECREASE_FACTOR (0.99) /* decreased every pgsk_entry_dealloc */
#define USAGE_DEALLOC_PERCENT 5 /* free this % of entries at once */
#define USAGE_INIT (1.0) /* including initial planning */
#define TIMEVAL_DIFF(start, end) ((double) end.tv_sec + (double) end.tv_usec / 1000000.0) \
- ((double) start.tv_sec + (double) start.tv_usec / 1000000.0)
#if PG_VERSION_NUM < 170000
#define MyProcNumber MyBackendId
#define ParallelLeaderProcNumber ParallelLeaderBackendId
#endif
#if PG_VERSION_NUM < 140000
#define ParallelLeaderBackendId ParallelMasterBackendId
#endif
#define PGSK_MAX_NESTED_LEVEL 64
/*
* Extension version number, for supporting older extension versions' objects
*/
typedef enum pgskVersion
{
PGSK_V2_0 = 0,
PGSK_V2_1,
PGSK_V2_2,
PGSK_V2_3
} pgskVersion;
/* Magic number identifying the stats file format */
static const uint32 PGSK_FILE_HEADER = 0x20240914;
static struct rusage exec_rusage_start[PGSK_MAX_NESTED_LEVEL];
#if PG_VERSION_NUM >= 130000
static struct rusage plan_rusage_start[PGSK_MAX_NESTED_LEVEL];
#endif
static int pgsk_max = 0; /* max #queries to store. pg_stat_statements.max is used */
/*
* Hashtable key that defines the identity of a hashtable entry. We use the
* same hash as pg_stat_statements
*/
typedef struct pgskHashKey
{
Oid userid; /* user OID */
Oid dbid; /* database OID */
pgsk_queryid queryid; /* query identifier */
bool top; /* whether statement is top level */
} pgskHashKey;
/*
* Statistics per database
*/
typedef struct pgskEntry
{
pgskHashKey key; /* hash key of entry - MUST BE FIRST */
pgskCounters counters[PGSK_NUMKIND]; /* statistics for this query */
slock_t mutex; /* protects the counters only */
TimestampTz stats_since; /* timestamp of entry allocation */
} pgskEntry;
/*
* Global shared state
*/
typedef struct pgskSharedState
{
LWLock *lock; /* protects hashtable search/modification */
#if PG_VERSION_NUM >= 90600
pgsk_queryid queryids[FLEXIBLE_ARRAY_MEMBER]; /* queryid info for
parallel leaders */
#endif
} pgskSharedState;
/*---- Local variables ----*/
/* Current nesting depth of planner/ExecutorRun/ProcessUtility calls */
static int nesting_level = 0;
/* saved hook address in case of unload */
#if PG_VERSION_NUM >= 150000
static shmem_request_hook_type prev_shmem_request_hook = NULL;
#endif
static shmem_startup_hook_type prev_shmem_startup_hook = NULL;
#if PG_VERSION_NUM >= 130000
static planner_hook_type prev_planner_hook = NULL;
#endif
static ExecutorStart_hook_type prev_ExecutorStart = NULL;
static ExecutorRun_hook_type prev_ExecutorRun = NULL;
static ExecutorFinish_hook_type prev_ExecutorFinish = NULL;
static ExecutorEnd_hook_type prev_ExecutorEnd = NULL;
/* Links to shared memory state */
static pgskSharedState *pgsk = NULL;
static HTAB *pgsk_hash = NULL;
/*---- HOOK variables ----*/
pgsk_counters_hook_type pgsk_counters_hook = NULL;
/*---- GUC variables ----*/
typedef enum
{
PGSK_TRACK_NONE, /* track no statements */
PGSK_TRACK_TOP, /* only top level statements */
PGSK_TRACK_ALL /* all statements, including nested ones */
} PGSKTrackLevel;
static const struct config_enum_entry pgs_track_options[] =
{
{"none", PGSK_TRACK_NONE, false},
{"top", PGSK_TRACK_TOP, false},
{"all", PGSK_TRACK_ALL, false},
{NULL, 0, false}
};
static int pgsk_track = PGSK_TRACK_TOP; /* tracking level */
#if PG_VERSION_NUM >= 130000
static bool pgsk_track_planning = false; /* whether to track planning duration */
#endif
#define pgsk_enabled(level) \
((pgsk_track == PGSK_TRACK_ALL && (level) < PGSK_MAX_NESTED_LEVEL) || \
(pgsk_track == PGSK_TRACK_TOP && (level) == 0))
/*--- Functions --- */
void _PG_init(void);
extern PGDLLEXPORT Datum pg_stat_kcache_reset(PG_FUNCTION_ARGS);
extern PGDLLEXPORT Datum pg_stat_kcache(PG_FUNCTION_ARGS);
extern PGDLLEXPORT Datum pg_stat_kcache_2_1(PG_FUNCTION_ARGS);
extern PGDLLEXPORT Datum pg_stat_kcache_2_2(PG_FUNCTION_ARGS);
extern PGDLLEXPORT Datum pg_stat_kcache_2_3(PG_FUNCTION_ARGS);
PG_FUNCTION_INFO_V1(pg_stat_kcache_reset);
PG_FUNCTION_INFO_V1(pg_stat_kcache);
PG_FUNCTION_INFO_V1(pg_stat_kcache_2_1);
PG_FUNCTION_INFO_V1(pg_stat_kcache_2_2);
PG_FUNCTION_INFO_V1(pg_stat_kcache_2_3);
static void pg_stat_kcache_internal(FunctionCallInfo fcinfo, pgskVersion
api_version);
static void pgsk_setmax(void);
static Size pgsk_memsize(void);
#if PG_VERSION_NUM >= 150000
static void pgsk_shmem_request(void);
#endif
static void pgsk_shmem_startup(void);
static void pgsk_shmem_shutdown(int code, Datum arg);
#if PG_VERSION_NUM >= 130000
static PlannedStmt *pgsk_planner(Query *parse,
const char *query_string,
int cursorOptions,
ParamListInfo boundParams);
#endif
static void pgsk_ExecutorStart(QueryDesc *queryDesc, int eflags);
static void pgsk_ExecutorRun(QueryDesc *queryDesc,
ScanDirection direction,
#if PG_VERSION_NUM >= 90600
uint64 count
#else
long count
#endif
#if PG_VERSION_NUM >= 100000 && PG_VERSION_NUM < 180000
, bool execute_once
#endif
);
static void pgsk_ExecutorFinish(QueryDesc *queryDesc);
static void pgsk_ExecutorEnd(QueryDesc *queryDesc);
static pgskEntry *pgsk_entry_alloc(pgskHashKey *key);
static void pgsk_entry_dealloc(void);
static void pgsk_entry_reset(void);
static void pgsk_entry_store(pgsk_queryid queryId, pgskStoreKind kind,
pgskCounters counters);
static uint32 pgsk_hash_fn(const void *key, Size keysize);
static int pgsk_match_fn(const void *key1, const void *key2, Size keysize);
static bool pgsk_assign_linux_hz_check_hook(int *newval, void **extra, GucSource source);
static void pgsk_compute_counters(pgskCounters *counters,
struct rusage *rusage_start,
struct rusage *rusage_end,
QueryDesc *queryDesc);
#if PG_VERSION_NUM >= 90600
static Size pgsk_queryids_array_size(void);
static void pgsk_set_queryid(pgsk_queryid queryid);
#endif
static int pgsk_linux_hz = 0;
void
_PG_init(void)
{
if (!process_shared_preload_libraries_in_progress)
{
elog(ERROR, "This module can only be loaded via shared_preload_libraries");
return;
}
DefineCustomIntVariable("pg_stat_kcache.linux_hz",
"Inform pg_stat_kcache of the linux CONFIG_HZ config option",
"This is used by pg_stat_kcache to compensate for sampling errors "
"in getrusage due to the kernel adhering to its ticks. The default value, -1, "
"tries to guess it at startup. ",
&pgsk_linux_hz,
-1,
-1,
INT_MAX,
PGC_USERSET,
0,
pgsk_assign_linux_hz_check_hook,
NULL,
NULL);
DefineCustomEnumVariable("pg_stat_kcache.track",
"Selects which statements are tracked by pg_stat_kcache.",
NULL,
&pgsk_track,
PGSK_TRACK_TOP,
pgs_track_options,
PGC_SUSET,
0,
NULL,
NULL,
NULL);
#if PG_VERSION_NUM >= 130000
DefineCustomBoolVariable("pg_stat_kcache.track_planning",
"Selects whether planning duration is tracked by pg_stat_cache.",
NULL,
&pgsk_track_planning,
false,
PGC_SUSET,
0,
NULL,
NULL,
NULL);
#endif
EmitWarningsOnPlaceholders("pg_stat_kcache");
/* set pgsk_max if needed */
pgsk_setmax();
/*
* If you change code here, don't forget to also report the modifications
* in pgsk_shmem_request() for pg15 and later.
*/
#if PG_VERSION_NUM < 150000
RequestAddinShmemSpace(pgsk_memsize());
#if PG_VERSION_NUM >= 90600
RequestNamedLWLockTranche("pg_stat_kcache", 1);
#else
RequestAddinLWLocks(1);
#endif /* pg 9.6+ */
#endif /* pg 15- */
/* Install hook */
#if PG_VERSION_NUM >= 150000
prev_shmem_request_hook = shmem_request_hook;
shmem_request_hook = pgsk_shmem_request;
#endif
prev_shmem_startup_hook = shmem_startup_hook;
shmem_startup_hook = pgsk_shmem_startup;
#if PG_VERSION_NUM >= 130000
prev_planner_hook = planner_hook;
planner_hook = pgsk_planner;
#endif
prev_ExecutorStart = ExecutorStart_hook;
ExecutorStart_hook = pgsk_ExecutorStart;
prev_ExecutorRun = ExecutorRun_hook;
ExecutorRun_hook = pgsk_ExecutorRun;
prev_ExecutorFinish = ExecutorFinish_hook;
ExecutorFinish_hook = pgsk_ExecutorFinish;
prev_ExecutorEnd = ExecutorEnd_hook;
ExecutorEnd_hook = pgsk_ExecutorEnd;
}
static bool
pgsk_assign_linux_hz_check_hook(int *newval, void **extra, GucSource source)
{
int val = *newval;
struct rusage myrusage;
struct timeval previous_value;
/* In that case we try to guess it */
if (val == -1)
{
elog(LOG, "Auto detecting pg_stat_kcache.linux_hz parameter...");
getrusage(RUSAGE_SELF, &myrusage);
previous_value = myrusage.ru_utime;
while (myrusage.ru_utime.tv_usec == previous_value.tv_usec &&
myrusage.ru_utime.tv_sec == previous_value.tv_sec)
{
getrusage(RUSAGE_SELF, &myrusage);
}
*newval = (int) (1 / ((myrusage.ru_utime.tv_sec - previous_value.tv_sec) +
(myrusage.ru_utime.tv_usec - previous_value.tv_usec) / 1000000.));
elog(LOG, "pg_stat_kcache.linux_hz is set to %d", *newval);
}
return true;
}
static void
pgsk_compute_counters(pgskCounters *counters,
struct rusage *rusage_start,
struct rusage *rusage_end,
QueryDesc *queryDesc)
{
/* Compute CPU time delta */
counters->utime = TIMEVAL_DIFF(rusage_start->ru_utime, rusage_end->ru_utime);
counters->stime = TIMEVAL_DIFF(rusage_start->ru_stime, rusage_end->ru_stime);
if (queryDesc && queryDesc->totaltime)
{
/* Make sure stats accumulation is done */
InstrEndLoop(queryDesc->totaltime);
/*
* We only consider values greater than 3 * linux tick, otherwise the
* bias is too big
*/
if (queryDesc->totaltime->total < (3. / pgsk_linux_hz))
{
counters->stime = 0;
counters->utime = queryDesc->totaltime->total;
}
}
#ifdef HAVE_GETRUSAGE
/* Compute the rest of the counters */
counters->minflts = rusage_end->ru_minflt - rusage_start->ru_minflt;
counters->majflts = rusage_end->ru_majflt - rusage_start->ru_majflt;
counters->nswaps = rusage_end->ru_nswap - rusage_start->ru_nswap;
counters->reads = rusage_end->ru_inblock - rusage_start->ru_inblock;
counters->writes = rusage_end->ru_oublock - rusage_start->ru_oublock;
counters->msgsnds = rusage_end->ru_msgsnd - rusage_start->ru_msgsnd;
counters->msgrcvs = rusage_end->ru_msgrcv - rusage_start->ru_msgrcv;
counters->nsignals = rusage_end->ru_nsignals - rusage_start->ru_nsignals;
counters->nvcsws = rusage_end->ru_nvcsw - rusage_start->ru_nvcsw;
counters->nivcsws = rusage_end->ru_nivcsw - rusage_start->ru_nivcsw;
#endif
}
#if PG_VERSION_NUM >= 90600
static void
pgsk_set_queryid(pgsk_queryid queryid)
{
/* Only the leader knows the queryid. */
Assert(!IsParallelWorker());
pgsk->queryids[MyProcNumber] = queryid;
}
#endif
#if PG_VERSION_NUM >= 150000
/*
* Request additional shared memory resources.
*
* If you change code here, don't forget to also report the modifications in
* _PG_init() for pg14 and below.
*/
static void
pgsk_shmem_request(void)
{
if (prev_shmem_request_hook)
prev_shmem_request_hook();
RequestAddinShmemSpace(pgsk_memsize());
RequestNamedLWLockTranche("pg_stat_kcache", 1);
}
#endif
static void
pgsk_shmem_startup(void)
{
bool found;
HASHCTL info;
FILE *file;
int i;
uint32 header;
int32 num;
pgskEntry *buffer = NULL;
if (prev_shmem_startup_hook)
prev_shmem_startup_hook();
/* reset in case this is a restart within the postmaster */
pgsk = NULL;
/* Create or attach to the shared memory state */
LWLockAcquire(AddinShmemInitLock, LW_EXCLUSIVE);
/* global access lock */
pgsk = ShmemInitStruct("pg_stat_kcache",
(sizeof(pgskSharedState)
#if PG_VERSION_NUM >= 90600
+ pgsk_queryids_array_size()
#endif
),
&found);
if (!found)
{
/* First time through ... */
#if PG_VERSION_NUM >= 90600
pgsk->lock = &(GetNamedLWLockTranche("pg_stat_kcache"))->lock;
#else
pgsk->lock = LWLockAssign();
#endif
}
/* set pgsk_max if needed */
pgsk_setmax();
memset(&info, 0, sizeof(info));
info.keysize = sizeof(pgskHashKey);
info.entrysize = sizeof(pgskEntry);
info.hash = pgsk_hash_fn;
info.match = pgsk_match_fn;
/* allocate stats shared memory hash */
pgsk_hash = ShmemInitHash("pg_stat_kcache hash",
pgsk_max, pgsk_max,
&info,
HASH_ELEM | HASH_FUNCTION | HASH_COMPARE);
LWLockRelease(AddinShmemInitLock);
if (!IsUnderPostmaster)
on_shmem_exit(pgsk_shmem_shutdown, (Datum) 0);
/*
* Done if some other process already completed our initialization.
*/
if (found)
return;
/* Load stat file, don't care about locking */
file = AllocateFile(PGSK_DUMP_FILE, PG_BINARY_R);
if (file == NULL)
{
if (errno == ENOENT)
return; /* ignore not-found error */
goto error;
}
/* check is header is valid */
if (fread(&header, sizeof(uint32), 1, file) != 1 ||
header != PGSK_FILE_HEADER)
goto error;
/* get number of entries */
if (fread(&num, sizeof(int32), 1, file) != 1)
goto error;
for (i = 0; i < num ; i++)
{
pgskEntry temp;
pgskEntry *entry;
if (fread(&temp, sizeof(pgskEntry), 1, file) != 1)
goto error;
/* make the hashtable entry (discards old entries if too many) */
entry = pgsk_entry_alloc(&temp.key);
/* copy in the actual stats */
entry->counters[0] = temp.counters[0];
entry->counters[1] = temp.counters[1];
entry->stats_since = temp.stats_since;
/* don't initialize spinlock, already done */
}
FreeFile(file);
/*
* Remove the file so it's not included in backups/replication slaves,
* etc. A new file will be written on next shutdown.
*/
unlink(PGSK_DUMP_FILE);
return;
error:
ereport(LOG,
(errcode_for_file_access(),
errmsg("could not read pg_stat_kcache file \"%s\": %m",
PGSK_DUMP_FILE)));
if (buffer)
pfree(buffer);
if (file)
FreeFile(file);
/* delete bogus file, don't care of errors in this case */
unlink(PGSK_DUMP_FILE);
}
/*
* shmem_shutdown hook: dump statistics into file.
*
*/
static void
pgsk_shmem_shutdown(int code, Datum arg)
{
FILE *file;
HASH_SEQ_STATUS hash_seq;
int32 num_entries;
pgskEntry *entry;
/* Don't try to dump during a crash. */
if (code)
return;
if (!pgsk)
return;
file = AllocateFile(PGSK_DUMP_FILE ".tmp", PG_BINARY_W);
if (file == NULL)
goto error;
if (fwrite(&PGSK_FILE_HEADER, sizeof(uint32), 1, file) != 1)
goto error;
num_entries = hash_get_num_entries(pgsk_hash);
if (fwrite(&num_entries, sizeof(int32), 1, file) != 1)
goto error;
hash_seq_init(&hash_seq, pgsk_hash);
while ((entry = hash_seq_search(&hash_seq)) != NULL)
{
if (fwrite(entry, sizeof(pgskEntry), 1, file) != 1)
{
/* note: we assume hash_seq_term won't change errno */
hash_seq_term(&hash_seq);
goto error;
}
}
if (FreeFile(file))
{
file = NULL;
goto error;
}
/*
* Rename file inplace
*/
if (rename(PGSK_DUMP_FILE ".tmp", PGSK_DUMP_FILE) != 0)
ereport(LOG,
(errcode_for_file_access(),
errmsg("could not rename pg_stat_kcache file \"%s\": %m",
PGSK_DUMP_FILE ".tmp")));
return;
error:
ereport(LOG,
(errcode_for_file_access(),
errmsg("could not read pg_stat_kcache file \"%s\": %m",
PGSK_DUMP_FILE)));
if (file)
FreeFile(file);
unlink(PGSK_DUMP_FILE);
}
/*
* Retrieve pg_stat_statement.max GUC value and store it into pgsk_max, since
* we want to store the same number of entries as pg_stat_statements. Don't do
* anything if pgsk_max is already set.
*/
static void pgsk_setmax(void)
{
const char *pgss_max;
const char *name = "pg_stat_statements.max";
if (pgsk_max != 0)
return;
pgss_max = GetConfigOption(name, true, false);
/*
* Retrieving pg_stat_statements.max can fail if pgss is loaded after pgsk
* in shared_preload_libraries. Hint user in case this happens.
*/
if (!pgss_max)
ereport(ERROR,
(errcode(ERRCODE_UNDEFINED_OBJECT),
errmsg("unrecognized configuration parameter \"%s\"",
name),
errhint("make sure pg_stat_statements is loaded,\n"
"and make sure pg_stat_kcache is present after pg_stat_statements"
" in the shared_preload_libraries setting")));
pgsk_max = atoi(pgss_max);
}
static Size pgsk_memsize(void)
{
Size size;
Assert(pgsk_max != 0);
size = MAXALIGN(sizeof(pgskSharedState));
size = add_size(size, hash_estimate_size(pgsk_max, sizeof(pgskEntry)));
#if PG_VERSION_NUM >= 90600
size = add_size(size, MAXALIGN(pgsk_queryids_array_size()));
#endif
return size;
}
#if PG_VERSION_NUM >= 90600
static Size
pgsk_queryids_array_size(void)
{
/*
* queryid isn't pushed to parallel workers. We store them in shared mem
* for each query, identified by their BackendId. It therefore needs room
* for all possible backends, plus autovacuum launcher and workers, plus bg
* workers and an extra one since BackendId numerotation starts at 1.
* Starting with pg12, wal senders aren't part of MaxConnections anymore,
* so they need to be accounted for.
*/
#if PG_VERSION_NUM >= 150000
Assert (MaxBackends > 0);
return (sizeof(pgsk_queryid) * (MaxBackends + 1));
#else
return (sizeof(pgsk_queryid) * (MaxConnections + autovacuum_max_workers + 1
+ max_worker_processes
#if PG_VERSION_NUM >= 120000
+ max_wal_senders
#endif /* pg12+ */
+ 1));
#endif /* pg15- */
}
#endif
/*
* support functions
*/
static void
pgsk_entry_store(pgsk_queryid queryId, pgskStoreKind kind,
pgskCounters counters)
{
volatile pgskEntry *e;
pgskHashKey key;
pgskEntry *entry;
/* Safety check... */
if (!pgsk || !pgsk_hash)
return;
/* Set up key for hashtable search */
key.userid = GetUserId();
key.dbid = MyDatabaseId;
key.queryid = queryId;
key.top = (nesting_level == 0);
/* Lookup the hash table entry with shared lock. */
LWLockAcquire(pgsk->lock, LW_SHARED);
entry = (pgskEntry *) hash_search(pgsk_hash, &key, HASH_FIND, NULL);
/* Create new entry, if not present */
if (!entry)
{
/* Need exclusive lock to make a new hashtable entry - promote */
LWLockRelease(pgsk->lock);
LWLockAcquire(pgsk->lock, LW_EXCLUSIVE);
/* OK to create a new hashtable entry */
entry = pgsk_entry_alloc(&key);
}
/*
* Grab the spinlock while updating the counters (see comment about
* locking rules at the head of the file)
*/
e = (volatile pgskEntry *) entry;
SpinLockAcquire(&e->mutex);
e->counters[0].usage += USAGE_INCREASE;
e->counters[kind].utime += counters.utime;
e->counters[kind].stime += counters.stime;
#ifdef HAVE_GETRUSAGE
e->counters[kind].minflts += counters.minflts;
e->counters[kind].majflts += counters.majflts;
e->counters[kind].nswaps += counters.nswaps;
e->counters[kind].reads += counters.reads;
e->counters[kind].writes += counters.writes;
e->counters[kind].msgsnds += counters.msgsnds;
e->counters[kind].msgrcvs += counters.msgrcvs;
e->counters[kind].nsignals += counters.nsignals;
e->counters[kind].nvcsws += counters.nvcsws;
e->counters[kind].nivcsws += counters.nivcsws;
#endif
SpinLockRelease(&e->mutex);
LWLockRelease(pgsk->lock);
}
/*
* Allocate a new hashtable entry.
* caller must hold an exclusive lock on pgsk->lock
*/
static pgskEntry *pgsk_entry_alloc(pgskHashKey *key)
{
pgskEntry *entry;
bool found;
/* Make space if needed */
while (hash_get_num_entries(pgsk_hash) >= pgsk_max)
pgsk_entry_dealloc();
/* Find or create an entry with desired hash code */
entry = (pgskEntry *) hash_search(pgsk_hash, key, HASH_ENTER, &found);
if (!found)
{
/* New entry, initialize it */
/* reset the statistics */
memset(&entry->counters, 0, sizeof(pgskCounters) * PGSK_NUMKIND);
/* set the appropriate initial usage count */
entry->counters[0].usage = USAGE_INIT;
/* re-initialize the mutex each time ... we assume no one using it */
SpinLockInit(&entry->mutex);
entry->stats_since = GetCurrentTimestamp();
}
return entry;
}
/*
* qsort comparator for sorting into increasing usage order
*/
static int
entry_cmp(const void *lhs, const void *rhs)
{
double l_usage = (*(pgskEntry *const *) lhs)->counters[0].usage;
double r_usage = (*(pgskEntry *const *) rhs)->counters[0].usage;
if (l_usage < r_usage)
return -1;
else if (l_usage > r_usage)
return +1;
else
return 0;
}
/*
* Deallocate least used entries.
* Caller must hold an exclusive lock on pgsk->lock.
*/
static void
pgsk_entry_dealloc(void)
{
HASH_SEQ_STATUS hash_seq;
pgskEntry **entries;
pgskEntry *entry;
int nvictims;
int i;
/*
* Sort entries by usage and deallocate USAGE_DEALLOC_PERCENT of them.
* While we're scanning the table, apply the decay factor to the usage
* values.
*/
entries = palloc(hash_get_num_entries(pgsk_hash) * sizeof(pgskEntry *));
i = 0;
hash_seq_init(&hash_seq, pgsk_hash);
while ((entry = hash_seq_search(&hash_seq)) != NULL)
{
entries[i++] = entry;
entry->counters[0].usage *= USAGE_DECREASE_FACTOR;
}
qsort(entries, i, sizeof(pgskEntry *), entry_cmp);
nvictims = Max(10, i * USAGE_DEALLOC_PERCENT / 100);
nvictims = Min(nvictims, i);
for (i = 0; i < nvictims; i++)
{
hash_search(pgsk_hash, &entries[i]->key, HASH_REMOVE, NULL);
}
pfree(entries);
}
static void pgsk_entry_reset(void)
{
HASH_SEQ_STATUS hash_seq;
pgskEntry *entry;
LWLockAcquire(pgsk->lock, LW_EXCLUSIVE);
hash_seq_init(&hash_seq, pgsk_hash);
while ((entry = hash_seq_search(&hash_seq)) != NULL)
{
hash_search(pgsk_hash, &entry->key, HASH_REMOVE, NULL);
}
LWLockRelease(pgsk->lock);
}
/*
* Hooks
*/
#if PG_VERSION_NUM >= 130000
/*
* Planner hook: forward to regular planner, but measure planning time
* if needed.
*/
static PlannedStmt *
pgsk_planner(Query *parse,
const char *query_string,
int cursorOptions,
ParamListInfo boundParams)
{
PlannedStmt *result;
/* We can't process the query if no queryid has been computed. */
if (pgsk_enabled(nesting_level)
&& pgsk_track_planning
&& parse->queryId != UINT64CONST(0))
{
struct rusage *rusage_start = &plan_rusage_start[nesting_level];
struct rusage rusage_end;
pgskCounters counters;
/* capture kernel usage stats in rusage_start */
getrusage(RUSAGE_SELF, rusage_start);
nesting_level++;
PG_TRY();
{
if (prev_planner_hook)
result = prev_planner_hook(parse, query_string, cursorOptions,
boundParams);
else
result = standard_planner(parse, query_string, cursorOptions,
boundParams);
nesting_level--;
}
PG_CATCH();
{
nesting_level--;
PG_RE_THROW();
}
PG_END_TRY();
/* capture kernel usage stats in rusage_end */
getrusage(RUSAGE_SELF, &rusage_end);
pgsk_compute_counters(&counters, rusage_start, &rusage_end, NULL);
/* store current number of block reads and writes */
pgsk_entry_store(parse->queryId, PGSK_PLAN, counters);
if (pgsk_counters_hook)
pgsk_counters_hook(&counters,
query_string,
nesting_level,
PGSK_PLAN);
}
else
{
/*
* Even though we're not tracking planning for this statement, we
* must still increment the nesting level, to ensure that functions
* evaluated during planning are not seen as top-level calls.
*/
nesting_level++;
PG_TRY();
{
if (prev_planner_hook)
result = prev_planner_hook(parse, query_string, cursorOptions,
boundParams);
else
result = standard_planner(parse, query_string, cursorOptions,
boundParams);
nesting_level--;
}
PG_CATCH();
{
nesting_level--;
PG_RE_THROW();
}
PG_END_TRY();
}
return result;
}
#endif
static void
pgsk_ExecutorStart (QueryDesc *queryDesc, int eflags)
{
if (pgsk_enabled(nesting_level))