File: plprofiler.c

package info (click to toggle)
plprofiler 4.2.5-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 944 kB
  • sloc: python: 2,125; ansic: 1,440; perl: 670; sql: 357; sh: 55; makefile: 28
file content (2089 lines) | stat: -rwxr-xr-x 60,332 bytes parent folder | download | duplicates (2)
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
/*-------------------------------------------------------------------------
 *
 * plprofiler.c
 *
 *	  Profiling plugin for PL/pgSQL instrumentation
 *
 * Copyright (c) 2022-2024, pgEdge
 * Copyright (c) 2014-2022, OSCG-Partners
 * Copyright (c) 2008-2014, PostgreSQL Global Development Group
 * Copyright 2006,2007 - EnterpriseDB, Inc.
 *
 * Major Change History:
 * 2012 - Removed from PostgreSQL plDebugger Extension
 * 2015 - Resurrected as standalone plProfiler by OpenSCG
 * 2016 - Rewritten as v2 to use shared hash tables, have lower overhead
 *			- v3 Major performance improvements, flame graph UI
 *
 *-------------------------------------------------------------------------
 */

#include "postgres.h"

#include "plprofiler.h"

/**********************************************************************
 * PL executor callback function prototypes
 **********************************************************************/

static void profiler_func_init(PLpgSQL_execstate *estate,
						  PLpgSQL_function * func);
static void profiler_func_beg(PLpgSQL_execstate *estate,
							  PLpgSQL_function *func);
static void profiler_func_end(PLpgSQL_execstate *estate,
							  PLpgSQL_function *func);
static void profiler_stmt_beg(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt);
static void profiler_stmt_end(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt);

/**********************************************************************
 * Local function prototypes
 **********************************************************************/
static Size profiler_shmem_size(void);
static void profiler_shmem_startup(void);
#if PG_VERSION_NUM >= 150000
static void profiler_shmem_request(void);
#endif
static void init_hash_tables(void);
static char *find_source(Oid oid, HeapTuple *tup, char **funcName);
static int count_source_lines(const char *src);
static uint32 line_hash_fn(const void *key, Size keysize);
static int line_match_fn(const void *key1, const void *key2, Size keysize);
static uint32 callgraph_hash_fn(const void *key, Size keysize);
static int callgraph_match_fn(const void *key1, const void *key2, Size keysize);
static void callgraph_push(Oid func_oid);
static void callgraph_pop_one(void);
static void callgraph_pop(Oid func_oid);
static void callgraph_check(Oid func_oid);
static void callgraph_collect(uint64 us_elapsed, uint64 us_self,
							  uint64 us_children);
static int32 profiler_collect_data(void);
static void profiler_xact_callback(XactEvent event, void *arg);

/**********************************************************************
 * Local variables
 **********************************************************************/

static MemoryContext	profiler_mcxt = NULL;
static HTAB			   *functions_hash = NULL;
static HTAB			   *callgraph_hash = NULL;
static profilerSharedState *profiler_shared_state = NULL;
static HTAB			   *functions_shared = NULL;
static HTAB			   *callgraph_shared = NULL;

static bool				profiler_first_call_in_xact = true;
static bool				profiler_active = false;
static bool				profiler_enabled_local = false;
static int				profiler_max_functions = PL_MIN_FUNCTIONS;
static int				profiler_max_lines = PL_MIN_LINES;
static int				profiler_max_callgraph = PL_MIN_CALLGRAPH;

static callGraphKey		graph_stack;
static instr_time		graph_stack_entry[PL_MAX_STACK_DEPTH];
static uint64			graph_stack_child_time[PL_MAX_STACK_DEPTH];
static int				graph_stack_pt = 0;
static time_t			last_collect_time = 0;
static bool				have_new_local_data = false;

static PLpgSQL_plugin  *prev_plpgsql_plugin = NULL;
static PLpgSQL_plugin  *prev_pltsql_plugin = NULL;
static shmem_startup_hook_type	prev_shmem_startup_hook = NULL;
#if PG_VERSION_NUM >= 150000
static shmem_request_hook_type	prev_shmem_request_hook = NULL;
#endif

static PLpgSQL_plugin	plugin_funcs = {
		profiler_func_init,
		profiler_func_beg,
		profiler_func_end,
		profiler_stmt_beg,
		profiler_stmt_end,
		NULL,
		NULL
	};

/**********************************************************************
 * Extension (de)initialization functions.
 **********************************************************************/

void
_PG_init(void)
{
	PLpgSQL_plugin **plugin_ptr;

	/* Link us into the PL/pgSQL executor. */
	plugin_ptr = (PLpgSQL_plugin **)find_rendezvous_variable("PLpgSQL_plugin");
	prev_plpgsql_plugin = *plugin_ptr;
	*plugin_ptr = &plugin_funcs;

	/* Link us into the PL/TSQL executor. */
	plugin_ptr = (PLpgSQL_plugin **)find_rendezvous_variable("PLTSQL_plugin");
	prev_pltsql_plugin = *plugin_ptr;
	*plugin_ptr = &plugin_funcs;

	/* Initialize local hash tables. */
	init_hash_tables();

	if (process_shared_preload_libraries_in_progress)
	{
		/*
		 * When loaded via shared_preload_libraries, we have to
		 * also hook into the shmem_startup call chain and register
		 * a callback at transaction end.
		 */
		prev_shmem_startup_hook = shmem_startup_hook;
		shmem_startup_hook = profiler_shmem_startup;
		#if PG_VERSION_NUM >= 150000
		prev_shmem_request_hook = shmem_request_hook;
		shmem_request_hook = profiler_shmem_request;
		#endif

		RegisterXactCallback(profiler_xact_callback, NULL);

		/*
		 * Additional config options only available if running via
		 * shared_preload_libraries. These all affect the amount of
		 * shared memory used by the extension, so they only make
		 * sense as PGC_POSTMASTER.
		 */
		DefineCustomIntVariable("plprofiler.max_functions",
								"Maximum number of functions that can be "
								"tracked in shared memory when using "
								"plprofiler.collect_in_shmem",
								NULL,
								&profiler_max_functions,
								PL_MIN_FUNCTIONS,
								PL_MIN_FUNCTIONS,
								INT_MAX,
								PGC_POSTMASTER,
								0,
								NULL,
								NULL,
								NULL);

		DefineCustomIntVariable("plprofiler.max_lines",
								"Maximum number of source lines that can be "
								"tracked in shared memory when using "
								"plprofiler.collect_in_shmem",
								NULL,
								&profiler_max_lines,
								PL_MIN_LINES,
								PL_MIN_LINES,
								INT_MAX,
								PGC_POSTMASTER,
								0,
								NULL,
								NULL,
								NULL);

		DefineCustomIntVariable("plprofiler.max_callgraphs",
								"Maximum number of call graphs that can be "
								"tracked in shared memory when using "
								"plprofiler.collect_in_shmem",
								NULL,
								&profiler_max_callgraph,
								PL_MIN_CALLGRAPH,
								PL_MIN_CALLGRAPH,
								INT_MAX,
								PGC_POSTMASTER,
								0,
								NULL,
								NULL,
								NULL);

		/* Request the additionl shared memory and LWLock needed. */
		#if PG_VERSION_NUM < 150000
		RequestAddinShmemSpace(profiler_shmem_size());
		RequestNamedLWLockTranche("plprofiler", 1);
		#endif
	}
}

void
_PG_fini(void)
{
	PLpgSQL_plugin **plugin_ptr;

	plugin_ptr = (PLpgSQL_plugin **)find_rendezvous_variable("PLpgSQL_plugin");
	*plugin_ptr = prev_plpgsql_plugin;
	prev_plpgsql_plugin = NULL;

	plugin_ptr = (PLpgSQL_plugin **)find_rendezvous_variable("PLTSQL_plugin");
	*plugin_ptr = prev_pltsql_plugin;
	prev_pltsql_plugin = NULL;

	MemoryContextDelete(profiler_mcxt);
	profiler_mcxt = NULL;
	functions_hash = NULL;
	callgraph_hash = NULL;

	if (prev_shmem_startup_hook != NULL)
	{
		shmem_startup_hook = prev_shmem_startup_hook;
		prev_shmem_startup_hook = NULL;

		UnregisterXactCallback(profiler_xact_callback, NULL);
	}
}

/* -------------------------------------------------------------------
 * profiler_shmem_size()
 *
 * 	Calculate the amount of shared memory the profiler needs to
 * 	keep functions, callgraphs and line statistics globally.
 * -------------------------------------------------------------------
 */
static Size
profiler_shmem_size(void)
{
	Size	num_bytes;

	num_bytes = offsetof(profilerSharedState, line_info);
	num_bytes = add_size(num_bytes,
						 sizeof(linestatsLineInfo) * profiler_max_lines);
	num_bytes = add_size(num_bytes,
						 hash_estimate_size(profiler_max_functions,
						 					sizeof(linestatsEntry)));
	num_bytes = add_size(num_bytes,
						 hash_estimate_size(profiler_max_callgraph,
						 					sizeof(callGraphEntry)));

	return num_bytes;
}

/**********************************************************************
 * Hook functions
 **********************************************************************/

/* -------------------------------------------------------------------
 * profiler_func_init()
 *
 *	This hook function is called by the PL/pgSQL interpreter when a
 *	new function is about to start.	 Specifically, this instrumentation
 *	hook is called after the stack frame has been created, but before
 *	values are assigned to the local variables.
 *
 *	'estate' points to the stack frame for this function, 'func'
 *	points to the definition of the function
 *
 *	We use this hook to load the source code for the function that's
 *	being invoked and to set up our context structures
 * -------------------------------------------------------------------
 */
static void
profiler_func_init(PLpgSQL_execstate *estate, PLpgSQL_function *func )
{
	profilerInfo	   *profiler_info;
	linestatsHashKey	linestats_key;
	linestatsEntry	   *linestats_entry;
	bool				linestats_found;

	/*
	 * On first call within a transaction we determine if the profiler
	 * is active or not. This means that starting/stopping to collect
	 * data will only happen on a transaction boundary.
	 */
	if (profiler_first_call_in_xact)
	{
		profiler_first_call_in_xact = false;

		if (profiler_shared_state != NULL)
		{
			profiler_active = (
				profiler_shared_state->profiler_enabled_global ||
				profiler_shared_state->profiler_enabled_pid == MyProcPid ||
				profiler_enabled_local);
		}
		else
		{
			profiler_active = profiler_enabled_local;
		}
	}

	if (!profiler_active)
	{
		/*
		 * The profiler can be enabled/disabled via changing postgresql.conf
		 * and reload (SIGHUP). The change becomes visible in backends the
		 * next time, the TCOP loop is ready for a new client query. This
		 * allows to enable the profiler for some time, have it save the
		 * stats in the permanent tables, then turn it off again. At that
		 * moment, we want to release all profiler resources.
		 */
		if (functions_hash != NULL)
			init_hash_tables();
		return;
	}

	/*
	 * Anonymous code blocks do not have function source code
	 * that we can lookup in pg_proc. For now we ignore them.
	 */
	if (func->fn_oid == InvalidOid)
		return;

	/* Tell collect_data() that new information has arrived locally. */
	have_new_local_data = true;

	/*
	 * Search for this function in our line stats hash table. Create the
	 * entry if it does not exist yet.
	 */
	linestats_key.db_oid = MyDatabaseId;
	linestats_key.fn_oid = func->fn_oid;

	linestats_entry = (linestatsEntry *)hash_search(functions_hash,
													&linestats_key,
													HASH_ENTER,
													&linestats_found);
	if (linestats_entry == NULL)
		elog(ERROR, "plprofiler out of memory");
	if (!linestats_found)
	{
		/* New function, initialize entry. */
		MemoryContext	old_context;
		HeapTuple		proc_tuple;
		char		   *proc_src;
		char		   *func_name;

		proc_src = find_source( func->fn_oid, &proc_tuple, &func_name );
		linestats_entry->line_count = count_source_lines(proc_src) + 1;
		old_context = MemoryContextSwitchTo(profiler_mcxt);
		linestats_entry->line_info = palloc0(linestats_entry->line_count *
											 sizeof(linestatsLineInfo));
		MemoryContextSwitchTo(old_context);

		ReleaseSysCache(proc_tuple);
	}


	/*
	 * The PL/pgSQL interpreter provides a void pointer (in each stack frame)
	 * that's reserved for plugins.	 We allocate a profilerInfo structure and
	 * record it's address in that pointer so we can keep some per-invocation
	 * information.
	 */
	profiler_info = (profilerInfo *)palloc(sizeof(profilerInfo ));

	profiler_info->fn_oid = func->fn_oid;
	profiler_info->line_count = linestats_entry->line_count;
	profiler_info->line_info = palloc0(profiler_info->line_count *
									  sizeof(profilerLineInfo));

	estate->plugin_info = profiler_info;
}

/* -------------------------------------------------------------------
 * profiler_func_beg()
 *
 *	This hook function is called by the PL/pgSQL interpreter when a
 *	new function is starting.  Specifically, this instrumentation
 *	hook is called after values have been assigned to all local
 *	variables (and all function parameters).
 *
 *	'estate' points to the stack frame for this function, 'func'
 *	points to the definition of the function
 * -------------------------------------------------------------------
 */
static void
profiler_func_beg(PLpgSQL_execstate *estate, PLpgSQL_function *func)
{
	if (!profiler_active)
		return;

	/* Ignore anonymous code block. */
	if (estate->plugin_info == NULL)
		return;

	/*
	 * Push this function Oid onto the stack, remember the entry time and
	 * set the time spent in children to zero.
	 */
	callgraph_push(func->fn_oid);
}

/* -------------------------------------------------------------------
 * profiler_func_end()
 *
 *	This hook function is called by the PL/pgSQL interpreter when a
 *	function runs to completion.
 * -------------------------------------------------------------------
 */
static void
profiler_func_end(PLpgSQL_execstate *estate, PLpgSQL_function *func)
{
	profilerInfo	   *profiler_info;
	linestatsHashKey	key;
	linestatsEntry	   *entry;
	int					i;

	if (!profiler_active)
		return;

	/* Ignore anonymous code block. */
	if (estate->plugin_info == NULL)
		return;

	/* Tell collect_data() that new information has arrived locally. */
	have_new_local_data = true;

	/* Find the linestats hash table entry for this function. */
	profiler_info = (profilerInfo *) estate->plugin_info;
	key.db_oid = MyDatabaseId;
	key.fn_oid = func->fn_oid;
	entry = (linestatsEntry *)hash_search(functions_hash, &key,
										  HASH_FIND, NULL);
	if (!entry)
	{
		elog(DEBUG1, "plprofiler: local linestats entry for fn_oid %u "
					"not found", func->fn_oid);
		return;
	}

	/* Loop through each line of source code and update the stats */
	for(i = 1; i < profiler_info->line_count; i++)
	{
		entry->line_info[i].exec_count +=
				profiler_info->line_info[i].exec_count;
		entry->line_info[i].us_total +=
				profiler_info->line_info[i].us_total;

		if (profiler_info->line_info[i].us_max > entry->line_info[i].us_max)
			entry->line_info[i].us_max =
					profiler_info->line_info[i].us_max;
	}

	/*
	 * Pop the call stack. This also does the time accounting
	 * for call graphs.
	 */
	callgraph_pop(func->fn_oid);

	/*
	 * Finally if a plprofiler.collect_interval is configured, save and reset
	 * the stats if the interval has elapsed.
	 */
	if (profiler_shared_state != NULL &&
		(profiler_shared_state->profiler_enabled_global ||
		 MyProcPid == profiler_shared_state->profiler_enabled_pid) &&
		profiler_shared_state->profiler_collect_interval > 0)
	{
		time_t	now = time(NULL);

		if (now >= last_collect_time +
				   profiler_shared_state->profiler_collect_interval)
		{
		    profiler_collect_data();
			last_collect_time = now;
		}
	}
}

/* -------------------------------------------------------------------
 * profiler_stmt_beg()
 *
 *	This hook function is called by the PL/pgSQL interpreter just before
 *	executing a statement (stmt).
 *
 *	Prior to executing each statement, we record the current time and
 *	the current values of all of the performance counters.
 * -------------------------------------------------------------------
 */
static void
profiler_stmt_beg(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
{
	profilerLineInfo   *line_info;
	profilerInfo	   *profiler_info;

	if (!profiler_active)
		return;

	/* Ignore anonymous code block. */
	if (estate->plugin_info == NULL)
		return;

	/* Set the start time of the statement */
	profiler_info = (profilerInfo *)estate->plugin_info;
	if (stmt->lineno < profiler_info->line_count)
	{
		line_info = profiler_info->line_info + stmt->lineno;
		INSTR_TIME_SET_CURRENT(line_info->start_time);
	}

	/* Check the call graph stack. */
	callgraph_check(profiler_info->fn_oid);
}

/* -------------------------------------------------------------------
 * profiler_stmt_end()
 *
 *	This hook function is called by the PL/pgSQL interpreter just after
 *	it executes a statement (stmt).
 *
 *	We use this hook to 'delta' the before and after performance counters
 *	and record the differences in the profilerStmtInfo structure associated
 *	with this statement.
 * -------------------------------------------------------------------
 */
static void
profiler_stmt_end(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
{
	profilerLineInfo   *line_info;
	profilerInfo	   *profiler_info;
	instr_time			end_time;
	uint64				elapsed;

	if (!profiler_active)
		return;

	/* Ignore anonymous code block. */
	if (estate->plugin_info == NULL)
		return;

	profiler_info = (profilerInfo *)estate->plugin_info;

	/*
	 * Ignore out of bounds line numbers. Someone is apparently
	 * profiling while executing DDL ... not much use in that.
	 */
	if (stmt->lineno >= profiler_info->line_count)
		return;

	/* Tell collect_data() that new information has arrived locally. */
	have_new_local_data = true;

	line_info = profiler_info->line_info + stmt->lineno;

	INSTR_TIME_SET_CURRENT(end_time);
	INSTR_TIME_SUBTRACT(end_time, line_info->start_time);

	elapsed = INSTR_TIME_GET_MICROSEC(end_time);

	if (elapsed > line_info->us_max)
		line_info->us_max = elapsed;

	line_info->us_total += elapsed;
	line_info->exec_count++;
}

/**********************************************************************
 * Helper functions
 **********************************************************************/

/* -------------------------------------------------------------------
 * init_hash_tables()
 *
 * Initialize hash table
 * -------------------------------------------------------------------
 */
static void
init_hash_tables(void)
{
	HASHCTL		hash_ctl;

	/* Create the memory context for our data */
	if (profiler_mcxt != NULL)
	{
		if (profiler_mcxt->isReset)
			return;
		MemoryContextReset(profiler_mcxt);
	}
	else
	{
		profiler_mcxt = AllocSetContextCreate(TopMemoryContext,
											  "PL/pgSQL profiler",
											  ALLOCSET_DEFAULT_MINSIZE,
											  ALLOCSET_DEFAULT_INITSIZE,
											  ALLOCSET_DEFAULT_MAXSIZE);
	}

	/* Create the hash table for line stats */
	MemSet(&hash_ctl, 0, sizeof(hash_ctl));

	hash_ctl.keysize = sizeof(linestatsHashKey);
	hash_ctl.entrysize = sizeof(linestatsEntry);
	hash_ctl.hash = line_hash_fn;
	hash_ctl.match = line_match_fn;
	hash_ctl.hcxt = profiler_mcxt;

	functions_hash = hash_create("Function Lines",
				 10000,
				 &hash_ctl,
				 HASH_ELEM | HASH_FUNCTION | HASH_COMPARE);

	/* Create the hash table for call stats */
	MemSet(&hash_ctl, 0, sizeof(hash_ctl));

	hash_ctl.keysize = sizeof(callGraphKey);
	hash_ctl.entrysize = sizeof(callGraphEntry);
	hash_ctl.hash = callgraph_hash_fn;
	hash_ctl.match = callgraph_match_fn;
	hash_ctl.hcxt = profiler_mcxt;

	callgraph_hash = hash_create("Function Call Graphs",
				 1000,
				 &hash_ctl,
				 HASH_ELEM | HASH_FUNCTION | HASH_COMPARE);
}

#if PG_VERSION_NUM >= 150000
static void
profiler_shmem_request(void)
{
	if (prev_shmem_request_hook)
		prev_shmem_request_hook();

	RequestAddinShmemSpace(profiler_shmem_size());
	RequestNamedLWLockTranche("plprofiler", 1);
}
#endif

static void
profiler_shmem_startup(void)
{
	bool					found;
	profilerSharedState	   *plpss;
	Size					plpss_size = 0;
	HASHCTL					hash_ctl;

	if (prev_shmem_startup_hook)
	        prev_shmem_startup_hook();

	/* Reset in case of restart inside of the postmaster. */
	profiler_shared_state = NULL;
	functions_shared = NULL;
	callgraph_shared = NULL;

	LWLockAcquire(AddinShmemInitLock, LW_EXCLUSIVE);

	/* Create or attach to the shared state */
	plpss_size = add_size(plpss_size,
						  offsetof(profilerSharedState, line_info));
	plpss_size = add_size(plpss_size,
						  sizeof(linestatsLineInfo) * profiler_max_lines);
	profiler_shared_state = ShmemInitStruct("plprofiler state", plpss_size,
											&found);
	plpss = profiler_shared_state;
	if (!found)
	{
		memset(plpss, 0, offsetof(profilerSharedState, line_info) +
						 sizeof(linestatsLineInfo) * profiler_max_lines);

		plpss->lock = &(GetNamedLWLockTranche("plprofiler"))->lock;
	}

	/* (Re)Initialize local hash tables. */
	init_hash_tables();

	/* Create or attache to the shared functions hash table */
	memset(&hash_ctl, 0, sizeof(hash_ctl));
	hash_ctl.keysize = sizeof(linestatsHashKey);
	hash_ctl.entrysize = sizeof(linestatsEntry);
	hash_ctl.hash = line_hash_fn;
	hash_ctl.match = line_match_fn;
	functions_shared = ShmemInitHash("plprofiler functions",
									 profiler_max_functions,
									 profiler_max_functions,
									 &hash_ctl,
									 HASH_ELEM | HASH_FUNCTION | HASH_COMPARE);

	/* Create or attache to the shared callgraph hash table */
	memset(&hash_ctl, 0, sizeof(hash_ctl));
	hash_ctl.keysize = sizeof(callGraphKey);
	hash_ctl.entrysize = sizeof(callGraphEntry);
	hash_ctl.hash = callgraph_hash_fn;
	hash_ctl.match = callgraph_match_fn;
	callgraph_shared = ShmemInitHash("plprofiler callgraph",
									  profiler_max_callgraph,
									  profiler_max_callgraph,
									  &hash_ctl,
									  HASH_ELEM | HASH_FUNCTION | HASH_COMPARE);

	LWLockRelease(AddinShmemInitLock);
}

/* -------------------------------------------------------------------
 * find_source()
 *
 *	This function locates and returns a pointer to a null-terminated string
 *	that contains the source code for the given function.
 *
 *	In addition to returning a pointer to the requested source code, this
 *	function sets *tup to point to a HeapTuple (that you must release when
 *	you are finished with it) and sets *funcName to point to the name of
 *	the given function.
 * -------------------------------------------------------------------
 */
static char *
find_source(Oid oid, HeapTuple *tup, char **funcName)
{
	bool	isNull;

	*tup = SearchSysCache(PROCOID, ObjectIdGetDatum(oid), 0, 0, 0);

	if(!HeapTupleIsValid(*tup))
		elog(ERROR, "plprofiler: cache lookup for function %u failed", oid);

	if (funcName != NULL)
		*funcName = NameStr(((Form_pg_proc)GETSTRUCT(*tup))->proname);

	return DatumGetCString(DirectFunctionCall1(textout,
											   SysCacheGetAttr(PROCOID,
															   *tup,
															   Anum_pg_proc_prosrc,
															   &isNull)));
}

/* -------------------------------------------------------------------
 * count_source_lines()
 *
 *	This function scans through the source code for a given function
 *	and counts the number of lines of code present in the string.
 * -------------------------------------------------------------------
 */
static int
count_source_lines(const char *src)
{
	int			line_count = 1;
	const char *cp = src;

	while(cp != NULL)
	{
		line_count++;
		cp = strchr(cp, '\n');
		if (cp)
			cp++;
	}

	return line_count;
}

static uint32
line_hash_fn(const void *key, Size keysize)
{
	const linestatsHashKey *k = (const linestatsHashKey *) key;

	return hash_uint32((uint32) k->fn_oid) ^
		hash_uint32((uint32) k->db_oid);
}

static int
line_match_fn(const void *key1, const void *key2, Size keysize)
{
	const linestatsHashKey  *k1 = (const linestatsHashKey *)key1;
	const linestatsHashKey  *k2 = (const linestatsHashKey *)key2;

	if (k1->fn_oid == k2->fn_oid &&
		k1->db_oid == k2->db_oid)
		return 0;
	else
		return 1;
}

static uint32
callgraph_hash_fn(const void *key, Size keysize)
{
	return hash_any(key, keysize);
}

static int
callgraph_match_fn(const void *key1, const void *key2, Size keysize)
{
	callGraphKey   *stack1 = (callGraphKey *)key1;
	callGraphKey   *stack2 = (callGraphKey *)key2;
	int				i;

	if (stack1->db_oid != stack2->db_oid)
		return 1;
	for (i = 0; i < PL_MAX_STACK_DEPTH && stack1->stack[i] != InvalidOid; i++)
		if (stack1->stack[i] != stack2->stack[i])
			return 1;
	return 0;
}

static void
callgraph_push(Oid func_oid)
{
	/*
	 * We only track function Oids in the call stack up to PL_MAX_STACK_DEPTH.
	 * Beyond that we just count the current stack depth.
	 */
	if (graph_stack_pt < PL_MAX_STACK_DEPTH)
	{
		/*
		 * Push this function Oid onto the stack, remember the entry time and
		 * set the time spent in children to zero.
		 */
		graph_stack.stack[graph_stack_pt] = func_oid;
		INSTR_TIME_SET_CURRENT(graph_stack_entry[graph_stack_pt]);
		graph_stack_child_time[graph_stack_pt] = 0;
	}
	graph_stack_pt++;
}

static void
callgraph_pop_one(void)
{
	instr_time			now;
	uint64				us_elapsed;
	uint64				us_self;
	linestatsHashKey	key;
	linestatsEntry	   *entry;

	/* Check for call stack underrun. */
    if (graph_stack_pt <= 0)
	{
		elog(DEBUG1, "plprofiler: call graph stack underrun");
		return;
	}

	/* Remove one level from the call stack. */
	graph_stack_pt--;

	/* Calculate the time spent in this function and record it. */
	INSTR_TIME_SET_CURRENT(now);
	INSTR_TIME_SUBTRACT(now, graph_stack_entry[graph_stack_pt]);
	us_elapsed = INSTR_TIME_GET_MICROSEC(now);
	us_self = us_elapsed - graph_stack_child_time[graph_stack_pt];
	callgraph_collect(us_elapsed, us_self,
					  graph_stack_child_time[graph_stack_pt]);

	/* If we have a caller, add our own time to the time of its children. */
	if (graph_stack_pt > 0)
		graph_stack_child_time[graph_stack_pt - 1] += us_elapsed;

	/*
	 * We also collect per function global counts in the pseudo line number
	 * zero. The line stats are cumulative (for example a FOR ... LOOP
	 * statement has the entire execution time of all statements in its
	 * block), so this can't be derived from the actual per line data.
	 */
	key.fn_oid = graph_stack.stack[graph_stack_pt];
	key.db_oid = MyDatabaseId;

	entry = (linestatsEntry *)hash_search(functions_hash, &key, HASH_FIND, NULL);

	if (entry)
	{
		entry->line_info[0].exec_count += 1;
		entry->line_info[0].us_total += us_elapsed;

		if (us_elapsed > entry->line_info[0].us_max)
			entry->line_info[0].us_max = us_elapsed;
	}
	else
	{
		elog(DEBUG1, "plprofiler: local linestats entry for fn_oid %u "
					"not found", graph_stack.stack[graph_stack_pt]);
	}

	/* Zap the oid from the call stack. */
	graph_stack.stack[graph_stack_pt] = InvalidOid;
}

static void
callgraph_pop(Oid func_oid)
{
	callgraph_check(func_oid);
	callgraph_pop_one();
}

static void
callgraph_check(Oid func_oid)
{
	/*
	 * Unwind the call stack until our own func_oid appears on the top.
	 *
	 * In case of an exception, the pl executor does not call the
	 * func_end callback, so we record now as the end of the function
	 * calls, that were left on the stack.
	 */
	while (graph_stack_pt > 0
		   && graph_stack.stack[graph_stack_pt - 1] != func_oid)
	{
		elog(DEBUG1, "plprofiler: unwinding excess call graph stack entry for %u in %u",
			 graph_stack.stack[graph_stack_pt - 1], func_oid);
		callgraph_pop_one();
	}
}

static void
callgraph_collect(uint64 us_elapsed, uint64 us_self, uint64 us_children)
{
	callGraphEntry *entry;
	bool			found;

	graph_stack.db_oid = MyDatabaseId;
	entry = (callGraphEntry *)hash_search(callgraph_hash, &graph_stack,
										  HASH_ENTER, &found);

	if (!found)
	{
		entry->callCount = 1;
		entry->totalTime = us_elapsed;
		entry->childTime = us_children;
		entry->selfTime = us_self;
	}
	else
	{
		entry->callCount++;
		entry->totalTime = entry->totalTime + us_elapsed;
		entry->childTime = entry->childTime + us_children;
		entry->selfTime  = entry->selfTime + us_self;
	}
}

static int32
profiler_collect_data(void)
{
	HASH_SEQ_STATUS			hash_seq;
	callGraphEntry		   *cge1;
	callGraphEntry		   *cge2;
	linestatsEntry		   *lse1;
	linestatsEntry		   *lse2;
	profilerSharedState	   *plpss = profiler_shared_state;
	bool					have_exclusive_lock = false;
	bool					found;
	int						i;

	/*
	 * Return without doing anything if the plprofiler extension
	 * was not loaded via shared_preload_libraries. We don't have
	 * any shared memory state in that case.
	 */
	if (plpss == NULL)
		return -1;

	/*
	 * Don't waste any time here if there was no new data recorded
	 * since the last collect_data() call.
	 */
	if (!have_new_local_data)
		return 0;
	have_new_local_data = false;

	/*
	 * Acquire a shared lock on the shared hash tables. We escalate
	 * to an exclusive lock later in case we need to add a new entry.
	 */
	LWLockAcquire(plpss->lock, LW_SHARED);

	/* Collect the callgraph data into shared memory. */
	hash_seq_init(&hash_seq, callgraph_hash);
	while ((cge1 = hash_seq_search(&hash_seq)) != NULL)
	{
		cge2 = hash_search(callgraph_shared, &(cge1->key),
						   HASH_FIND, NULL);
		if (cge2 == NULL)
		{
			/*
			 * This callgraph is not yet known in shared memory.
			 * Need to escalate the lock to exclusive.
			 */
			if (!have_exclusive_lock)
			{
				LWLockRelease(plpss->lock);
				LWLockAcquire(plpss->lock, LW_EXCLUSIVE);
				have_exclusive_lock = true;
			}

			cge2 = hash_search(callgraph_shared, &(cge1->key),
							   HASH_ENTER, &found);
			if (cge2 == NULL)
			{
				/*
				 * This means that we are out of shared memory for the
				 * callgraph_shared hash table. Nothing we can do
				 * here but complain.
				 */
				if (!plpss->callgraph_overflow)
				{
					elog(LOG,
						 "plprofiler: entry limit reached for "
						 "shared memory call graph data");
					plpss->callgraph_overflow = true;
				}
				break;
			}

			/*
			 * Since we released the lock above for lock escalation to
			 * exclusive, it is possible that someone else in the meantime
			 * created the entry for this call graph.
			 */
			if (!found)
			{
				/*
				 * We created a new entry for this call graph in the
				 * shared hash table. Initialize it.
				 */
				/* memcpy(&(cge2->key), &(cge1->key), sizeof(callGraphKey)); */
				SpinLockInit(&(cge2->mutex));
				cge2->callCount = 0;
				cge2->totalTime = 0;
				cge2->childTime = 0;
				cge2->selfTime = 0;
			}
		}

		/*
		 * At this point we have the local entry in cge1 and the shared
		 * entry in cge2. Since we may still only hold a shared lock on
		 * the shared state, use a spinlock on the shared entry while
		 * adding the counters. Then reset our local counters to zero.
		 */
		SpinLockAcquire(&(cge2->mutex));
		cge2->callCount += cge1->callCount;
		cge2->totalTime += cge1->totalTime;
		cge2->childTime += cge1->childTime;
		cge2->selfTime  += cge1->selfTime ;
		SpinLockRelease(&(cge2->mutex));

		cge1->callCount = 0;
		cge1->totalTime = 0;
		cge1->childTime = 0;
		cge1->selfTime = 0;
	}

	/* Collect the linestats data into shared memory. */
	hash_seq_init(&hash_seq, functions_hash);
	while ((lse1 = hash_seq_search(&hash_seq)) != NULL)
	{
		lse2 = hash_search(functions_shared, &(lse1->key),
						   HASH_FIND, NULL);
		if (lse2 == NULL)
		{
			/*
			 * This function is not yet known in shared memory.
			 * Need to escalate the lock to exclusive.
			 */
			if (!have_exclusive_lock)
			{
				LWLockRelease(plpss->lock);
				LWLockAcquire(plpss->lock, LW_EXCLUSIVE);
				have_exclusive_lock = true;
			}

			lse2 = hash_search(functions_shared, &(lse1->key),
							   HASH_ENTER, &found);
			if (lse2 == NULL)
			{
				/*
				 * This means that we are out of shared memory for the
				 * functions_shared hash table. Nothing we can do
				 * here but complain.
				 */
				if (!plpss->functions_overflow)
				{
					elog(LOG,
						 "plprofiler: entry limit reached for "
						 "shared memory functions data");
					plpss->functions_overflow = true;
				}
				break;
			}
			if (memcmp(&(lse2->key), &(lse1->key), sizeof(linestatsHashKey)) != 0)
			{
				elog(FATAL, "key of new hash entry doesn't match");
			}

			/*
			 * Since we released the lock above for lock escalation to
			 * exclusive, it is possible that someone else in the meantime
			 * created the entry for this function.
			 */
			if (!found)
			{
				/*
				 * We created a new entry for this function in the
				 * shared hash table. Initialize it. We also need to
				 * allocate the per line counters here. If we run out
				 * of per line counters in the shared state, we don't
				 * keep count for any lines of this function at all.
				 */
				SpinLockInit(&(lse2->mutex));
				if (lse1->line_count <= profiler_max_lines - plpss->lines_used)
				{
					lse2->line_count = lse1->line_count;
					lse2->line_info = &(plpss->line_info[plpss->lines_used]);
					plpss->lines_used += lse1->line_count;
					memset(lse2->line_info, 0,
						   sizeof(linestatsLineInfo) * lse1->line_count);
				}
				else
				{
					if (!plpss->lines_overflow)
					{
						elog(LOG,
							 "plprofiler: entry limit reached for "
							 "shared memory per source line data");
						plpss->lines_overflow = true;
					}
					lse2->line_count = 0;
					lse2->line_info = NULL;
				}
			}
		}

		/*
		 * At this point we have the local entry in lse1 and the shared
		 * entry in lse2. Since we may still only hold a shared lock on
		 * the shared state, use a spinlock on the shared entry while
		 * adding the counters.
		 */
		SpinLockAcquire(&(lse2->mutex));
		for (i = 0; i < lse1->line_count && i < lse2->line_count; i++)
		{
			if (lse1->line_info[i].us_max > lse2->line_info[i].us_max)
				lse2->line_info[i].us_max = lse1->line_info[i].us_max;
			lse2->line_info[i].us_total += lse1->line_info[i].us_total;
			lse2->line_info[i].exec_count += lse1->line_info[i].exec_count;
		}
		SpinLockRelease(&(lse2->mutex));

		memset(lse1->line_info, 0,
			   sizeof(linestatsLineInfo) * lse1->line_count);
	}

	/* All done, release the lock. */
	LWLockRelease(plpss->lock);

	return 0;
}

static void
profiler_xact_callback(XactEvent event, void *arg)
{
	Assert(profiler_shared_state != NULL);

	/* Collect the statistics if needed. */
	if (profiler_active &&
		profiler_shared_state->profiler_collect_interval > 0)
	{
		switch (event)
		{
			case XACT_EVENT_COMMIT:
			case XACT_EVENT_ABORT:
			case XACT_EVENT_PARALLEL_COMMIT:
			case XACT_EVENT_PARALLEL_ABORT:
				profiler_collect_data();
				break;

			default:
				break;
		}
	}

	/* Tell func_init that we need to evaluate the new active state. */
	profiler_first_call_in_xact = true;

	/* We can also unwind the callstack here in case of abort. */
	callgraph_check(InvalidOid);
}

/**********************************************************************
 * SQL callable functions
 **********************************************************************/

/* -------------------------------------------------------------------
 * pl_profiler_get_stack(stack oid[])
 *
 *	Converts a stack in Oid[] format into a text[].
 * -------------------------------------------------------------------
 */
Datum
pl_profiler_get_stack(PG_FUNCTION_ARGS)
{
	ArrayType	   *stack_in = PG_GETARG_ARRAYTYPE_P(0);
	Datum		   *stack_oid;
	bool		   *nulls;
	int				nelems;
	int				i;
	Datum		   *funcdefs;
	char			funcdef_buf[100 + NAMEDATALEN * 2];

	/* Take the array apart */
	deconstruct_array(stack_in, OIDOID,
					  sizeof(Oid), true, 'i',
					  &stack_oid, &nulls, &nelems);

	/* Allocate the Datum array for the individual function signatures. */
	funcdefs = palloc(sizeof(Datum) * nelems);

	/*
	 * Turn each of the function Oids, that are in the array, into
	 * a text that is "schema.funcname(funcargs) oid=funcoid".
	 */
	for (i = 0; i < nelems; i++)
	{
		char	   *funcname;
		char	   *nspname;

		funcname = get_func_name(DatumGetObjectId(stack_oid[i]));
		if (funcname != NULL)
		{
			nspname = get_namespace_name(get_func_namespace(DatumGetObjectId(stack_oid[i])));
			if (nspname == NULL)
				nspname = pstrdup("<unknown>");
		}
		else
		{
			nspname = pstrdup("<unknown>");
			funcname = pstrdup("<unknown>");
		}

		snprintf(funcdef_buf, sizeof(funcdef_buf),
				 "%s.%s() oid=%u", nspname, funcname,
				 DatumGetObjectId(stack_oid[i]));

		pfree(nspname);
		pfree(funcname);

		funcdefs[i] = PointerGetDatum(cstring_to_text(funcdef_buf));
	}

	/* Return the texts as a text[]. */
	PG_RETURN_ARRAYTYPE_P(construct_array(funcdefs, nelems,
										  TEXTOID, -1,
										  false, 'i'));
}

/* -------------------------------------------------------------------
 * pl_profiler_linestats_local()
 *
 *	Returns the content of the local line stats hash table
 *	as a set of rows.
 * -------------------------------------------------------------------
 */
Datum
pl_profiler_linestats_local(PG_FUNCTION_ARGS)
{
	ReturnSetInfo	   *rsinfo = (ReturnSetInfo *)fcinfo->resultinfo;
	TupleDesc			tupdesc;
	Tuplestorestate	   *tupstore;
	MemoryContext		per_query_ctx;
	MemoryContext		oldcontext;
	HASH_SEQ_STATUS		hash_seq;
	linestatsEntry	   *entry;

	/* check to see if caller supports us returning a tuplestore */
	if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
		ereport(ERROR,
				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
				 errmsg("set-valued function called in context "
						"that cannot accept a set")));
	if (!(rsinfo->allowedModes & SFRM_Materialize))
		ereport(ERROR,
				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
				 errmsg("materialize mode required, but it is not "
						"allowed in this context")));

	/* Build a tuple descriptor for our result type */
	if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
		elog(ERROR, "return type must be a row type");

	per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
	oldcontext = MemoryContextSwitchTo(per_query_ctx);

	tupstore = tuplestore_begin_heap(true, false, work_mem);
	rsinfo->returnMode = SFRM_Materialize;
	rsinfo->setResult = tupstore;
	rsinfo->setDesc = tupdesc;

	MemoryContextSwitchTo(oldcontext);

	if (functions_hash != NULL)
	{
		hash_seq_init(&hash_seq, functions_hash);
		while ((entry = hash_seq_search(&hash_seq)) != NULL)
		{
			int64	lno;

			for (lno = 0; lno < entry->line_count; lno++)
			{
				Datum		values[PL_PROFILE_COLS];
				bool		nulls[PL_PROFILE_COLS];
				int			i = 0;

				/* Include this entry in the result. */
				MemSet(values, 0, sizeof(values));
				MemSet(nulls, 0, sizeof(nulls));

				values[i++] = ObjectIdGetDatum(entry->key.fn_oid);
				values[i++] = Int64GetDatumFast(lno);
				values[i++] = Int64GetDatumFast(entry->line_info[lno].exec_count);
				values[i++] = Int64GetDatumFast(entry->line_info[lno].us_total);
				values[i++] = Int64GetDatumFast(entry->line_info[lno].us_max);

				Assert(i == PL_PROFILE_COLS);

				tuplestore_putvalues(tupstore, tupdesc, values, nulls);
			}
		}
	}

	PG_RETURN_VOID();
}

/* -------------------------------------------------------------------
 * pl_profiler_linestats_shared()
 *
 *	Returns the content of the shared line stats hash table
 *	as a set of rows.
 * -------------------------------------------------------------------
 */
Datum
pl_profiler_linestats_shared(PG_FUNCTION_ARGS)
{
	ReturnSetInfo		   *rsinfo = (ReturnSetInfo *)fcinfo->resultinfo;
	TupleDesc				tupdesc;
	Tuplestorestate		   *tupstore;
	MemoryContext			per_query_ctx;
	MemoryContext			oldcontext;
	HASH_SEQ_STATUS			hash_seq;
	linestatsEntry		   *entry;
	profilerSharedState	   *plpss = profiler_shared_state;

	/* check to see if caller supports us returning a tuplestore */
	if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
		ereport(ERROR,
				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
				 errmsg("set-valued function called in context "
						"that cannot accept a set")));
	if (!(rsinfo->allowedModes & SFRM_Materialize))
		ereport(ERROR,
				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
				 errmsg("materialize mode required, but it is not "
						"allowed in this context")));

	/* Check that plprofiler was loaded via shared_preload_libraries */
	if (plpss == NULL)
		elog(ERROR, "plprofiler was not loaded via shared_preload_libraries");

	/* Build a tuple descriptor for our result type */
	if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
		elog(ERROR, "return type must be a row type");

	per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
	oldcontext = MemoryContextSwitchTo(per_query_ctx);

	tupstore = tuplestore_begin_heap(true, false, work_mem);
	rsinfo->returnMode = SFRM_Materialize;
	rsinfo->setResult = tupstore;
	rsinfo->setDesc = tupdesc;

	MemoryContextSwitchTo(oldcontext);

	/* Place a shared lock on the shared memory data. */
	LWLockAcquire(plpss->lock, LW_SHARED);

	hash_seq_init(&hash_seq, functions_shared);
	while ((entry = hash_seq_search(&hash_seq)) != NULL)
	{
		int64	lno;

		if (entry->key.db_oid != MyDatabaseId)
			continue;

		/* Guard agains concurrent updates of the counters. */
		SpinLockAcquire(&(entry->mutex));

		for (lno = 0; lno <= entry->line_count; lno++)
		{
			Datum		values[PL_PROFILE_COLS];
			bool		nulls[PL_PROFILE_COLS];
			int			i = 0;

			/* Include this entry in the result. */
			MemSet(values, 0, sizeof(values));
			MemSet(nulls, 0, sizeof(nulls));

			values[i++] = ObjectIdGetDatum(entry->key.fn_oid);
			values[i++] = Int64GetDatumFast(lno);
			values[i++] = Int64GetDatumFast(entry->line_info[lno].exec_count);
			values[i++] = Int64GetDatumFast(entry->line_info[lno].us_total);
			values[i++] = Int64GetDatumFast(entry->line_info[lno].us_max);

			Assert(i == PL_PROFILE_COLS);

			tuplestore_putvalues(tupstore, tupdesc, values, nulls);
		}

		/* Done with the counter access. */
		SpinLockRelease(&(entry->mutex));
	}

	/* Release the shared lock on the shared memory data. */
	LWLockRelease(plpss->lock);

	PG_RETURN_VOID();
}

/* -------------------------------------------------------------------
 * pl_profiler_callgraph_local()
 *
 *	Returns the content of the local call graph hash table
 *	as a set of rows.
 * -------------------------------------------------------------------
 */
Datum
pl_profiler_callgraph_local(PG_FUNCTION_ARGS)
{
	ReturnSetInfo	   *rsinfo = (ReturnSetInfo *)fcinfo->resultinfo;
	TupleDesc			tupdesc;
	Tuplestorestate	   *tupstore;
	MemoryContext		per_query_ctx;
	MemoryContext		oldcontext;
	HASH_SEQ_STATUS		hash_seq;
	callGraphEntry	   *entry;

	/* Check to see if caller supports us returning a tuplestore */
	if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
		ereport(ERROR,
				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
				 errmsg("set-valued function called in context "
						"that cannot accept a set")));
	if (!(rsinfo->allowedModes & SFRM_Materialize))
		ereport(ERROR,
				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
				 errmsg("materialize mode required, but it is not "
						"allowed in this context")));

	/* Build a tuple descriptor for our result type */
	if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
		elog(ERROR, "return type must be a row type");

	per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
	oldcontext = MemoryContextSwitchTo(per_query_ctx);

	tupstore = tuplestore_begin_heap(true, false, work_mem);
	rsinfo->returnMode = SFRM_Materialize;
	rsinfo->setResult = tupstore;
	rsinfo->setDesc = tupdesc;

	MemoryContextSwitchTo(oldcontext);

	if (callgraph_hash != NULL)
	{
		hash_seq_init(&hash_seq, callgraph_hash);
		while ((entry = hash_seq_search(&hash_seq)) != NULL)
		{
			Datum		values[PL_CALLGRAPH_COLS];
			bool		nulls[PL_CALLGRAPH_COLS];
			Datum		funcdefs[PL_MAX_STACK_DEPTH];

			int			i = 0;
			int			j = 0;

			MemSet(values, 0, sizeof(values));
			MemSet(nulls, 0, sizeof(nulls));

			for (i = 0; i < PL_MAX_STACK_DEPTH && entry->key.stack[i] != InvalidOid; i++)
				funcdefs[i] = ObjectIdGetDatum(entry->key.stack[i]);

			values[j++] = PointerGetDatum(construct_array(funcdefs, i,
														  OIDOID, sizeof(Oid),
														  true, 'i'));
			values[j++] = Int64GetDatumFast(entry->callCount);
			values[j++] = UInt64GetDatum(entry->totalTime);
			values[j++] = UInt64GetDatum(entry->childTime);
			values[j++] = UInt64GetDatum(entry->selfTime);

			Assert(j == PL_CALLGRAPH_COLS);

			tuplestore_putvalues(tupstore, tupdesc, values, nulls);
		}
	}

	PG_RETURN_VOID();
}

/* -------------------------------------------------------------------
 * pl_profiler_callgraph_shared()
 *
 *	Returns the content of the shared call graph hash table
 *	as a set of rows.
 * -------------------------------------------------------------------
 */
Datum
pl_profiler_callgraph_shared(PG_FUNCTION_ARGS)
{
	ReturnSetInfo		   *rsinfo = (ReturnSetInfo *)fcinfo->resultinfo;
	TupleDesc				tupdesc;
	Tuplestorestate		   *tupstore;
	MemoryContext			per_query_ctx;
	MemoryContext			oldcontext;
	HASH_SEQ_STATUS			hash_seq;
	callGraphEntry		   *entry;
	profilerSharedState	   *plpss = profiler_shared_state;

	/* Check to see if caller supports us returning a tuplestore */
	if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
		ereport(ERROR,
				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
				 errmsg("set-valued function called in context "
						"that cannot accept a set")));
	if (!(rsinfo->allowedModes & SFRM_Materialize))
		ereport(ERROR,
				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
				 errmsg("materialize mode required, but it is not "
						"allowed in this context")));

	/* Check that plprofiler was loaded via shared_preload_libraries */
	if (plpss == NULL)
		elog(ERROR, "plprofiler was not loaded via shared_preload_libraries");

	/* Build a tuple descriptor for our result type */
	if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
		elog(ERROR, "return type must be a row type");

	per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
	oldcontext = MemoryContextSwitchTo(per_query_ctx);

	tupstore = tuplestore_begin_heap(true, false, work_mem);
	rsinfo->returnMode = SFRM_Materialize;
	rsinfo->setResult = tupstore;
	rsinfo->setDesc = tupdesc;

	MemoryContextSwitchTo(oldcontext);

	/* Place a shared lock on the shared memory data. */
	LWLockAcquire(plpss->lock, LW_SHARED);

	hash_seq_init(&hash_seq, callgraph_shared);
	while ((entry = hash_seq_search(&hash_seq)) != NULL)
	{
		Datum		values[PL_CALLGRAPH_COLS];
		bool		nulls[PL_CALLGRAPH_COLS];
		Datum		funcdefs[PL_MAX_STACK_DEPTH];

		int			i = 0;
		int			j = 0;

		/* Only entries of the local database are visible. */
		if (entry->key.db_oid != MyDatabaseId)
			continue;

		MemSet(values, 0, sizeof(values));
		MemSet(nulls, 0, sizeof(nulls));

		for (i = 0; i < PL_MAX_STACK_DEPTH && entry->key.stack[i] != InvalidOid; i++)
			funcdefs[i] = ObjectIdGetDatum(entry->key.stack[i]);

		values[j++] = PointerGetDatum(construct_array(funcdefs, i,
													  OIDOID, sizeof(Oid),
													  true, 'i'));

		/* Guard agains concurrent updates of the counters. */
		SpinLockAcquire(&(entry->mutex));

		values[j++] = Int64GetDatumFast(entry->callCount);
		values[j++] = UInt64GetDatum(entry->totalTime);
		values[j++] = UInt64GetDatum(entry->childTime);
		values[j++] = UInt64GetDatum(entry->selfTime);

		/* Done with the counter access. */
		SpinLockRelease(&(entry->mutex));

		Assert(j == PL_CALLGRAPH_COLS);

		tuplestore_putvalues(tupstore, tupdesc, values, nulls);
	}

	/* Release the shared lock on the shared memory data. */
	LWLockRelease(plpss->lock);

	PG_RETURN_VOID();
}

/* -------------------------------------------------------------------
 * pl_profiler_func_oids_local()
 *
 *	Returns an array of all function Oids that we have
 *	linestat information for in the local hash table.
 * -------------------------------------------------------------------
 */
Datum
pl_profiler_func_oids_local(PG_FUNCTION_ARGS)
{
	int					i = 0;
	Datum			   *result;
	HASH_SEQ_STATUS		hash_seq;
	linestatsEntry	   *entry;

	/* First pass to count the number of Oids, we will return. */

	if (functions_hash != NULL)
	{
		hash_seq_init(&hash_seq, functions_hash);
		while ((entry = hash_seq_search(&hash_seq)) != NULL)
			i++;
	}

	/* Allocate Oid array for result. */
	if (i == 0)
	{
		result = palloc(sizeof(Datum));
	}
	else
	{
		result = palloc(sizeof(Datum) * i);
	}
	if (result == NULL)
		elog(ERROR, "out of memory in pl_profiler_func_oids_local()");

	/* Second pass to collect the Oids. */
	if (functions_hash != NULL)
	{
		i = 0;
		hash_seq_init(&hash_seq, functions_hash);
		while ((entry = hash_seq_search(&hash_seq)) != NULL)
			result[i++] = ObjectIdGetDatum(entry->key.fn_oid);
	}

	/* Build and return the actual array. */
	PG_RETURN_ARRAYTYPE_P(construct_array(result, i,
										  OIDOID, sizeof(Oid),
										  true, 'i'));
}

/* -------------------------------------------------------------------
 * pl_profiler_func_oids_shared()
 *
 *	Returns an array of all function Oids that we have
 *	linestat information for in the shared hash table.
 * -------------------------------------------------------------------
 */
Datum
pl_profiler_func_oids_shared(PG_FUNCTION_ARGS)
{
	int						i = 0;
	Datum				   *result;
	HASH_SEQ_STATUS			hash_seq;
	linestatsEntry		   *entry;
	profilerSharedState	   *plpss = profiler_shared_state;

	/* Check that plprofiler was loaded via shared_preload_libraries */
	if (plpss == NULL)
		elog(ERROR, "plprofiler was not loaded via shared_preload_libraries");

	/* Place a shared lock on the shared memory data. */
	LWLockAcquire(plpss->lock, LW_SHARED);

	/* First pass to count the number of Oids, we will return. */

	hash_seq_init(&hash_seq, functions_shared);
	while ((entry = hash_seq_search(&hash_seq)) != NULL)
	{
		if (entry->key.db_oid == MyDatabaseId)
			i++;
	}

	/* Allocate Oid array for result. */
	if (i == 0)
	{
		result = palloc(sizeof(Datum));
	}
	else
	{
		result = palloc(sizeof(Datum) * i);
	}
	if (result == NULL)
		elog(ERROR, "out of memory in pl_profiler_func_oids_shared()");

	/* Second pass to collect the Oids. */
	i = 0;
	hash_seq_init(&hash_seq, functions_shared);
	while ((entry = hash_seq_search(&hash_seq)) != NULL)
	{
		if (entry->key.db_oid == MyDatabaseId)
			result[i++] = ObjectIdGetDatum(entry->key.fn_oid);
	}

	/* Release the shared lock on the shared memory data. */
	LWLockRelease(plpss->lock);

	/* Build and return the actual array. */
	PG_RETURN_ARRAYTYPE_P(construct_array(result, i,
										  OIDOID, sizeof(Oid),
										  true, 'i'));
}

/* -------------------------------------------------------------------
 * pl_profiler_funcs_source(func_oids oid[])
 *
 *	Return the source code of a number of functions specified by
 *	an input array of Oids.
 * -------------------------------------------------------------------
 */
Datum
pl_profiler_funcs_source(PG_FUNCTION_ARGS)
{
	ArrayType		   *func_oids_in = PG_GETARG_ARRAYTYPE_P(0);
	Datum			   *func_oids;
	bool			   *nulls;
	int					nelems;
	ReturnSetInfo	   *rsinfo = (ReturnSetInfo *)fcinfo->resultinfo;
	TupleDesc			tupdesc;
	Tuplestorestate	   *tupstore;
	MemoryContext		per_query_ctx;
	MemoryContext		oldcontext;
	int					fidx;

	/* check to see if caller supports us returning a tuplestore */
	if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
		ereport(ERROR,
				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
				 errmsg("set-valued function called in context "
						"that cannot accept a set")));
	if (!(rsinfo->allowedModes & SFRM_Materialize))
		ereport(ERROR,
				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
				 errmsg("materialize mode required, but it is not "
						"allowed in this context")));

	/* Build a tuple descriptor for our result type */
	if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
		elog(ERROR, "return type must be a row type");

	per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
	oldcontext = MemoryContextSwitchTo(per_query_ctx);

	tupstore = tuplestore_begin_heap(true, false, work_mem);
	rsinfo->returnMode = SFRM_Materialize;
	rsinfo->setResult = tupstore;
	rsinfo->setDesc = tupdesc;

	MemoryContextSwitchTo(oldcontext);

	/* Take the input array apart */
	deconstruct_array(func_oids_in, OIDOID,
					  sizeof(Oid), true, 'i',
					  &func_oids, &nulls, &nelems);

	/*
	 * Turn each of the function Oids, that are in the array, into
	 * a text that is "schema.funcname(funcargs) oid=funcoid".
	 */
	for (fidx = 0; fidx < nelems; fidx++)
	{
		HeapTuple	procTuple;
		char	   *procSrc;
		char	   *funcName;
		Datum		values[PL_FUNCS_SRC_COLS];
		bool		nulls[PL_FUNCS_SRC_COLS];
		int			i = 0;
		char	   *cp;
		char	   *linestart;
		int64		line_number = 0;

		/* Create the line-0 entry. */
		MemSet(values, 0, sizeof(values));
		MemSet(nulls, 0, sizeof(nulls));

		values[i++] = func_oids[fidx];
		values[i++] = Int64GetDatumFast(line_number);
		values[i++] = PointerGetDatum(cstring_to_text("-- Line 0"));

		Assert(i == PL_FUNCS_SRC_COLS);
		tuplestore_putvalues(tupstore, tupdesc, values, nulls);

		line_number++;

		/* Find the source code and split it. */
		procSrc = find_source(func_oids[fidx], &procTuple, &funcName);
		if (procSrc == NULL)
		{
			ReleaseSysCache(procTuple);
			continue;
		}

		/*
		 * The returned procStr is palloc'd, so it is safe to scribble
		 * around in it.
		 */
		cp = procSrc;
		linestart = procSrc;
		while (cp != NULL)
		{
			cp = strchr(cp, '\n');
			if (cp != NULL)
				*cp++ = '\0';
			i = 0;
			values[i++] = func_oids[fidx];
			values[i++] = Int64GetDatumFast(line_number);
			values[i++] = PointerGetDatum(cstring_to_text(linestart));

			Assert(i == PL_FUNCS_SRC_COLS);
			tuplestore_putvalues(tupstore, tupdesc, values, nulls);

			linestart = cp;
			line_number++;
		}

		ReleaseSysCache(procTuple);
		pfree(procSrc);
	}

	PG_RETURN_VOID();
}

/* -------------------------------------------------------------------
 * pl_profiler_reset_local()
 *
 *	Drop all data collected in the local hash tables.
 * -------------------------------------------------------------------
 */
Datum
pl_profiler_reset_local(PG_FUNCTION_ARGS)
{
	init_hash_tables();

	PG_RETURN_VOID();
}

/* -------------------------------------------------------------------
 * pl_profiler_reset_shared()
 *
 *	Drop all data collected in the shared hash tables and the
 *	shared state.
 * -------------------------------------------------------------------
 */
Datum
pl_profiler_reset_shared(PG_FUNCTION_ARGS)
{
	HASH_SEQ_STATUS			hash_seq;
	callGraphEntry		   *lsent;
	linestatsEntry		   *cgent;
	profilerSharedState	   *plpss = profiler_shared_state;

	/* Check that plprofiler was loaded via shared_preload_libraries */
	if (plpss == NULL)
		elog(ERROR, "plprofiler was not loaded via shared_preload_libraries");

	LWLockAcquire(plpss->lock, LW_EXCLUSIVE);

	/* Reset the shared state. */
	plpss->callgraph_overflow = false;
	plpss->functions_overflow = false;
	plpss->lines_overflow = false;
	plpss->lines_used = 0;

	/* Delete all entries from the callgraph hash table. */
	hash_seq_init(&hash_seq, callgraph_shared);
	while ((cgent = hash_seq_search(&hash_seq)) != NULL)
	{
		hash_search(callgraph_shared, &(cgent->key), HASH_REMOVE, NULL);
	}

	/* Delete all entries from the functions hash table. */
	hash_seq_init(&hash_seq, functions_shared);
	while ((lsent = hash_seq_search(&hash_seq)) != NULL)
	{
		hash_search(functions_shared, &(lsent->key), HASH_REMOVE, NULL);
	}

	LWLockRelease(plpss->lock);

	PG_RETURN_VOID();
}

/* -------------------------------------------------------------------
 * pl_profiler_set_enabled_global()
 *
 *	Turn global profiling on or off.
 * -------------------------------------------------------------------
 */
Datum
pl_profiler_set_enabled_global(PG_FUNCTION_ARGS)
{
	if (PG_ARGISNULL(0))
		PG_RETURN_NULL();

	if (profiler_shared_state == NULL)
		elog(ERROR, "plprofiler not loaded via shared_preload_libraries");
	else
		profiler_shared_state->profiler_enabled_global = PG_GETARG_BOOL(0);

	PG_RETURN_BOOL(profiler_shared_state->profiler_enabled_global);
}

/* -------------------------------------------------------------------
 * pl_profiler_get_enabled_global()
 *
 *	Report global profiling state.
 * -------------------------------------------------------------------
 */
Datum
pl_profiler_get_enabled_global(PG_FUNCTION_ARGS)
{
	if (profiler_shared_state == NULL)
		elog(ERROR, "plprofiler not loaded via shared_preload_libraries");

	PG_RETURN_BOOL(profiler_shared_state->profiler_enabled_global);
}

/* -------------------------------------------------------------------
 * pl_profiler_set_enabled_local()
 *
 *	Turn local profiling on or off.
 * -------------------------------------------------------------------
 */
Datum
pl_profiler_set_enabled_local(PG_FUNCTION_ARGS)
{
	if (PG_ARGISNULL(0))
		PG_RETURN_NULL();

	profiler_enabled_local = PG_GETARG_BOOL(0);

	PG_RETURN_BOOL(profiler_enabled_local);
}

/* -------------------------------------------------------------------
 * pl_profiler_get_enabled_local()
 *
 *	Report local profiling state.
 * -------------------------------------------------------------------
 */
Datum
pl_profiler_get_enabled_local(PG_FUNCTION_ARGS)
{
	PG_RETURN_BOOL(profiler_enabled_local);
}

/* -------------------------------------------------------------------
 * pl_profiler_set_enabled_pid()
 *
 *	Turn pid profiling on or off.
 * -------------------------------------------------------------------
 */
Datum
pl_profiler_set_enabled_pid(PG_FUNCTION_ARGS)
{
	if (PG_ARGISNULL(0))
		PG_RETURN_NULL();

	if (profiler_shared_state == NULL)
		elog(ERROR, "plprofiler not loaded via shared_preload_libraries");
	else
		profiler_shared_state->profiler_enabled_pid = PG_GETARG_INT32(0);

	PG_RETURN_INT32(profiler_shared_state->profiler_enabled_pid);
}

/* -------------------------------------------------------------------
 * pl_profiler_get_enabled_pid()
 *
 *	Report pid profiling state.
 * -------------------------------------------------------------------
 */
Datum
pl_profiler_get_enabled_pid(PG_FUNCTION_ARGS)
{
	if (profiler_shared_state == NULL)
		elog(ERROR, "plprofiler not loaded via shared_preload_libraries");

	PG_RETURN_INT32(profiler_shared_state->profiler_enabled_pid);
}

/* -------------------------------------------------------------------
 * pl_profiler_set_collect_interval()
 *
 *	Turn pid profiling on or off.
 * -------------------------------------------------------------------
 */
Datum
pl_profiler_set_collect_interval(PG_FUNCTION_ARGS)
{
	if (PG_ARGISNULL(0))
		PG_RETURN_NULL();

	if (profiler_shared_state == NULL)
		PG_RETURN_INT32(-1);
	else
		profiler_shared_state->profiler_collect_interval = PG_GETARG_INT32(0);

	PG_RETURN_INT32(profiler_shared_state->profiler_collect_interval);
}

/* -------------------------------------------------------------------
 * pl_profiler_get_collect_interval()
 *
 *	Report pid profiling state.
 * -------------------------------------------------------------------
 */
Datum
pl_profiler_get_collect_interval(PG_FUNCTION_ARGS)
{
	if (profiler_shared_state == NULL)
		elog(ERROR, "plprofiler not loaded via shared_preload_libraries");

	PG_RETURN_INT32(profiler_shared_state->profiler_collect_interval);
}

/* -------------------------------------------------------------------
 * pl_profiler_collect_data()
 *
 *	SQL level callable function to collect profiling data from the
 *	local tables into the shared hash tables.
 * -------------------------------------------------------------------
 */
Datum
pl_profiler_collect_data(PG_FUNCTION_ARGS)
{
	PG_RETURN_INT32(profiler_collect_data());
}

/* -------------------------------------------------------------------
 * pl_profiler_callgraph_overflow()
 *
 *	Return the flag callgraph_overflow from the shared state.
 * -------------------------------------------------------------------
 */
Datum
pl_profiler_callgraph_overflow(PG_FUNCTION_ARGS)
{
	profilerSharedState	   *plpss = profiler_shared_state;

	/* Check that plprofiler was loaded via shared_preload_libraries */
	if (plpss == NULL)
		elog(ERROR, "plprofiler was not loaded via shared_preload_libraries");

	PG_RETURN_BOOL(plpss->callgraph_overflow);
}

/* -------------------------------------------------------------------
 * pl_profiler_functions_overflow()
 *
 *	Return the flag functions_overflow from the shared state.
 * -------------------------------------------------------------------
 */
Datum
pl_profiler_functions_overflow(PG_FUNCTION_ARGS)
{
	profilerSharedState	   *plpss = profiler_shared_state;

	/* Check that plprofiler was loaded via shared_preload_libraries */
	if (plpss == NULL)
		elog(ERROR, "plprofiler was not loaded via shared_preload_libraries");

	PG_RETURN_BOOL(plpss->functions_overflow);
}

/* -------------------------------------------------------------------
 * pl_profiler_lines_overflow()
 *
 *	Return the flag lines_overflow from the shared state.
 * -------------------------------------------------------------------
 */
Datum
pl_profiler_lines_overflow(PG_FUNCTION_ARGS)
{
	profilerSharedState	   *plpss = profiler_shared_state;

	/* Check that plprofiler was loaded via shared_preload_libraries */
	if (plpss == NULL)
		elog(ERROR, "plprofiler was not loaded via shared_preload_libraries");

	PG_RETURN_BOOL(plpss->lines_overflow);
}