Line data Source code
1 : /*-------------------------------------------------------------------------
2 : *
3 : * pg_buffercache_pages.c
4 : * display some contents of the buffer cache
5 : *
6 : * contrib/pg_buffercache/pg_buffercache_pages.c
7 : *-------------------------------------------------------------------------
8 : */
9 : #include "postgres.h"
10 :
11 : #include "access/htup_details.h"
12 : #include "access/relation.h"
13 : #include "catalog/pg_type.h"
14 : #include "funcapi.h"
15 : #include "port/pg_numa.h"
16 : #include "storage/buf_internals.h"
17 : #include "storage/bufmgr.h"
18 : #include "utils/rel.h"
19 :
20 :
21 : #define NUM_BUFFERCACHE_PAGES_MIN_ELEM 8
22 : #define NUM_BUFFERCACHE_PAGES_ELEM 9
23 : #define NUM_BUFFERCACHE_SUMMARY_ELEM 5
24 : #define NUM_BUFFERCACHE_USAGE_COUNTS_ELEM 4
25 : #define NUM_BUFFERCACHE_EVICT_ELEM 2
26 : #define NUM_BUFFERCACHE_EVICT_RELATION_ELEM 3
27 : #define NUM_BUFFERCACHE_EVICT_ALL_ELEM 3
28 :
29 : #define NUM_BUFFERCACHE_NUMA_ELEM 3
30 :
31 2 : PG_MODULE_MAGIC_EXT(
32 : .name = "pg_buffercache",
33 : .version = PG_VERSION
34 : );
35 :
36 : /*
37 : * Record structure holding the to be exposed cache data.
38 : */
39 : typedef struct
40 : {
41 : uint32 bufferid;
42 : RelFileNumber relfilenumber;
43 : Oid reltablespace;
44 : Oid reldatabase;
45 : ForkNumber forknum;
46 : BlockNumber blocknum;
47 : bool isvalid;
48 : bool isdirty;
49 : uint16 usagecount;
50 :
51 : /*
52 : * An int32 is sufficiently large, as MAX_BACKENDS prevents a buffer from
53 : * being pinned by too many backends and each backend will only pin once
54 : * because of bufmgr.c's PrivateRefCount infrastructure.
55 : */
56 : int32 pinning_backends;
57 : } BufferCachePagesRec;
58 :
59 :
60 : /*
61 : * Function context for data persisting over repeated calls.
62 : */
63 : typedef struct
64 : {
65 : TupleDesc tupdesc;
66 : BufferCachePagesRec *record;
67 : } BufferCachePagesContext;
68 :
69 : /*
70 : * Record structure holding the to be exposed cache data.
71 : */
72 : typedef struct
73 : {
74 : uint32 bufferid;
75 : int64 page_num;
76 : int32 numa_node;
77 : } BufferCacheNumaRec;
78 :
79 : /*
80 : * Function context for data persisting over repeated calls.
81 : */
82 : typedef struct
83 : {
84 : TupleDesc tupdesc;
85 : int buffers_per_page;
86 : int pages_per_buffer;
87 : int os_page_size;
88 : BufferCacheNumaRec *record;
89 : } BufferCacheNumaContext;
90 :
91 :
92 : /*
93 : * Function returning data from the shared buffer cache - buffer number,
94 : * relation node/tablespace/database/blocknum and dirty indicator.
95 : */
96 4 : PG_FUNCTION_INFO_V1(pg_buffercache_pages);
97 2 : PG_FUNCTION_INFO_V1(pg_buffercache_numa_pages);
98 4 : PG_FUNCTION_INFO_V1(pg_buffercache_summary);
99 4 : PG_FUNCTION_INFO_V1(pg_buffercache_usage_counts);
100 6 : PG_FUNCTION_INFO_V1(pg_buffercache_evict);
101 4 : PG_FUNCTION_INFO_V1(pg_buffercache_evict_relation);
102 4 : PG_FUNCTION_INFO_V1(pg_buffercache_evict_all);
103 :
104 :
105 : /* Only need to touch memory once per backend process lifetime */
106 : static bool firstNumaTouch = true;
107 :
108 :
109 : Datum
110 65540 : pg_buffercache_pages(PG_FUNCTION_ARGS)
111 : {
112 : FuncCallContext *funcctx;
113 : Datum result;
114 : MemoryContext oldcontext;
115 : BufferCachePagesContext *fctx; /* User function context. */
116 : TupleDesc tupledesc;
117 : TupleDesc expected_tupledesc;
118 : HeapTuple tuple;
119 :
120 65540 : if (SRF_IS_FIRSTCALL())
121 : {
122 : int i;
123 :
124 4 : funcctx = SRF_FIRSTCALL_INIT();
125 :
126 : /* Switch context when allocating stuff to be used in later calls */
127 4 : oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
128 :
129 : /* Create a user function context for cross-call persistence */
130 4 : fctx = (BufferCachePagesContext *) palloc(sizeof(BufferCachePagesContext));
131 :
132 : /*
133 : * To smoothly support upgrades from version 1.0 of this extension
134 : * transparently handle the (non-)existence of the pinning_backends
135 : * column. We unfortunately have to get the result type for that... -
136 : * we can't use the result type determined by the function definition
137 : * without potentially crashing when somebody uses the old (or even
138 : * wrong) function definition though.
139 : */
140 4 : if (get_call_result_type(fcinfo, NULL, &expected_tupledesc) != TYPEFUNC_COMPOSITE)
141 0 : elog(ERROR, "return type must be a row type");
142 :
143 4 : if (expected_tupledesc->natts < NUM_BUFFERCACHE_PAGES_MIN_ELEM ||
144 4 : expected_tupledesc->natts > NUM_BUFFERCACHE_PAGES_ELEM)
145 0 : elog(ERROR, "incorrect number of output arguments");
146 :
147 : /* Construct a tuple descriptor for the result rows. */
148 4 : tupledesc = CreateTemplateTupleDesc(expected_tupledesc->natts);
149 4 : TupleDescInitEntry(tupledesc, (AttrNumber) 1, "bufferid",
150 : INT4OID, -1, 0);
151 4 : TupleDescInitEntry(tupledesc, (AttrNumber) 2, "relfilenode",
152 : OIDOID, -1, 0);
153 4 : TupleDescInitEntry(tupledesc, (AttrNumber) 3, "reltablespace",
154 : OIDOID, -1, 0);
155 4 : TupleDescInitEntry(tupledesc, (AttrNumber) 4, "reldatabase",
156 : OIDOID, -1, 0);
157 4 : TupleDescInitEntry(tupledesc, (AttrNumber) 5, "relforknumber",
158 : INT2OID, -1, 0);
159 4 : TupleDescInitEntry(tupledesc, (AttrNumber) 6, "relblocknumber",
160 : INT8OID, -1, 0);
161 4 : TupleDescInitEntry(tupledesc, (AttrNumber) 7, "isdirty",
162 : BOOLOID, -1, 0);
163 4 : TupleDescInitEntry(tupledesc, (AttrNumber) 8, "usage_count",
164 : INT2OID, -1, 0);
165 :
166 4 : if (expected_tupledesc->natts == NUM_BUFFERCACHE_PAGES_ELEM)
167 4 : TupleDescInitEntry(tupledesc, (AttrNumber) 9, "pinning_backends",
168 : INT4OID, -1, 0);
169 :
170 4 : fctx->tupdesc = BlessTupleDesc(tupledesc);
171 :
172 : /* Allocate NBuffers worth of BufferCachePagesRec records. */
173 4 : fctx->record = (BufferCachePagesRec *)
174 4 : MemoryContextAllocHuge(CurrentMemoryContext,
175 : sizeof(BufferCachePagesRec) * NBuffers);
176 :
177 : /* Set max calls and remember the user function context. */
178 4 : funcctx->max_calls = NBuffers;
179 4 : funcctx->user_fctx = fctx;
180 :
181 : /* Return to original context when allocating transient memory */
182 4 : MemoryContextSwitchTo(oldcontext);
183 :
184 : /*
185 : * Scan through all the buffers, saving the relevant fields in the
186 : * fctx->record structure.
187 : *
188 : * We don't hold the partition locks, so we don't get a consistent
189 : * snapshot across all buffers, but we do grab the buffer header
190 : * locks, so the information of each buffer is self-consistent.
191 : */
192 65540 : for (i = 0; i < NBuffers; i++)
193 : {
194 : BufferDesc *bufHdr;
195 : uint32 buf_state;
196 :
197 65536 : bufHdr = GetBufferDescriptor(i);
198 : /* Lock each buffer header before inspecting. */
199 65536 : buf_state = LockBufHdr(bufHdr);
200 :
201 65536 : fctx->record[i].bufferid = BufferDescriptorGetBuffer(bufHdr);
202 65536 : fctx->record[i].relfilenumber = BufTagGetRelNumber(&bufHdr->tag);
203 65536 : fctx->record[i].reltablespace = bufHdr->tag.spcOid;
204 65536 : fctx->record[i].reldatabase = bufHdr->tag.dbOid;
205 65536 : fctx->record[i].forknum = BufTagGetForkNum(&bufHdr->tag);
206 65536 : fctx->record[i].blocknum = bufHdr->tag.blockNum;
207 65536 : fctx->record[i].usagecount = BUF_STATE_GET_USAGECOUNT(buf_state);
208 65536 : fctx->record[i].pinning_backends = BUF_STATE_GET_REFCOUNT(buf_state);
209 :
210 65536 : if (buf_state & BM_DIRTY)
211 3780 : fctx->record[i].isdirty = true;
212 : else
213 61756 : fctx->record[i].isdirty = false;
214 :
215 : /* Note if the buffer is valid, and has storage created */
216 65536 : if ((buf_state & BM_VALID) && (buf_state & BM_TAG_VALID))
217 7956 : fctx->record[i].isvalid = true;
218 : else
219 57580 : fctx->record[i].isvalid = false;
220 :
221 65536 : UnlockBufHdr(bufHdr, buf_state);
222 : }
223 : }
224 :
225 65540 : funcctx = SRF_PERCALL_SETUP();
226 :
227 : /* Get the saved state */
228 65540 : fctx = funcctx->user_fctx;
229 :
230 65540 : if (funcctx->call_cntr < funcctx->max_calls)
231 : {
232 65536 : uint32 i = funcctx->call_cntr;
233 : Datum values[NUM_BUFFERCACHE_PAGES_ELEM];
234 : bool nulls[NUM_BUFFERCACHE_PAGES_ELEM];
235 :
236 65536 : values[0] = Int32GetDatum(fctx->record[i].bufferid);
237 65536 : nulls[0] = false;
238 :
239 : /*
240 : * Set all fields except the bufferid to null if the buffer is unused
241 : * or not valid.
242 : */
243 65536 : if (fctx->record[i].blocknum == InvalidBlockNumber ||
244 7956 : fctx->record[i].isvalid == false)
245 : {
246 57580 : nulls[1] = true;
247 57580 : nulls[2] = true;
248 57580 : nulls[3] = true;
249 57580 : nulls[4] = true;
250 57580 : nulls[5] = true;
251 57580 : nulls[6] = true;
252 57580 : nulls[7] = true;
253 : /* unused for v1.0 callers, but the array is always long enough */
254 57580 : nulls[8] = true;
255 : }
256 : else
257 : {
258 7956 : values[1] = ObjectIdGetDatum(fctx->record[i].relfilenumber);
259 7956 : nulls[1] = false;
260 7956 : values[2] = ObjectIdGetDatum(fctx->record[i].reltablespace);
261 7956 : nulls[2] = false;
262 7956 : values[3] = ObjectIdGetDatum(fctx->record[i].reldatabase);
263 7956 : nulls[3] = false;
264 7956 : values[4] = ObjectIdGetDatum(fctx->record[i].forknum);
265 7956 : nulls[4] = false;
266 7956 : values[5] = Int64GetDatum((int64) fctx->record[i].blocknum);
267 7956 : nulls[5] = false;
268 7956 : values[6] = BoolGetDatum(fctx->record[i].isdirty);
269 7956 : nulls[6] = false;
270 7956 : values[7] = Int16GetDatum(fctx->record[i].usagecount);
271 7956 : nulls[7] = false;
272 : /* unused for v1.0 callers, but the array is always long enough */
273 7956 : values[8] = Int32GetDatum(fctx->record[i].pinning_backends);
274 7956 : nulls[8] = false;
275 : }
276 :
277 : /* Build and return the tuple. */
278 65536 : tuple = heap_form_tuple(fctx->tupdesc, values, nulls);
279 65536 : result = HeapTupleGetDatum(tuple);
280 :
281 65536 : SRF_RETURN_NEXT(funcctx, result);
282 : }
283 : else
284 4 : SRF_RETURN_DONE(funcctx);
285 : }
286 :
287 : /*
288 : * Inquire about NUMA memory mappings for shared buffers.
289 : *
290 : * Returns NUMA node ID for each memory page used by the buffer. Buffers may
291 : * be smaller or larger than OS memory pages. For each buffer we return one
292 : * entry for each memory page used by the buffer (if the buffer is smaller,
293 : * it only uses a part of one memory page).
294 : *
295 : * We expect both sizes (for buffers and memory pages) to be a power-of-2, so
296 : * one is always a multiple of the other.
297 : *
298 : * In order to get reliable results we also need to touch memory pages, so
299 : * that the inquiry about NUMA memory node doesn't return -2 (which indicates
300 : * unmapped/unallocated pages).
301 : */
302 : Datum
303 0 : pg_buffercache_numa_pages(PG_FUNCTION_ARGS)
304 : {
305 : FuncCallContext *funcctx;
306 : MemoryContext oldcontext;
307 : BufferCacheNumaContext *fctx; /* User function context. */
308 : TupleDesc tupledesc;
309 : TupleDesc expected_tupledesc;
310 : HeapTuple tuple;
311 : Datum result;
312 :
313 0 : if (SRF_IS_FIRSTCALL())
314 : {
315 : int i,
316 : idx;
317 : Size os_page_size;
318 : void **os_page_ptrs;
319 : int *os_page_status;
320 : uint64 os_page_count;
321 : int pages_per_buffer;
322 : int max_entries;
323 : char *startptr,
324 : *endptr;
325 :
326 0 : if (pg_numa_init() == -1)
327 0 : elog(ERROR, "libnuma initialization failed or NUMA is not supported on this platform");
328 :
329 : /*
330 : * The database block size and OS memory page size are unlikely to be
331 : * the same. The block size is 1-32KB, the memory page size depends on
332 : * platform. On x86 it's usually 4KB, on ARM it's 4KB or 64KB, but
333 : * there are also features like THP etc. Moreover, we don't quite know
334 : * how the pages and buffers "align" in memory - the buffers may be
335 : * shifted in some way, using more memory pages than necessary.
336 : *
337 : * So we need to be careful about mapping buffers to memory pages. We
338 : * calculate the maximum number of pages a buffer might use, so that
339 : * we allocate enough space for the entries. And then we count the
340 : * actual number of entries as we scan the buffers.
341 : *
342 : * This information is needed before calling move_pages() for NUMA
343 : * node id inquiry.
344 : */
345 0 : os_page_size = pg_get_shmem_pagesize();
346 :
347 : /*
348 : * The pages and block size is expected to be 2^k, so one divides the
349 : * other (we don't know in which direction). This does not say
350 : * anything about relative alignment of pages/buffers.
351 : */
352 : Assert((os_page_size % BLCKSZ == 0) || (BLCKSZ % os_page_size == 0));
353 :
354 : /*
355 : * How many addresses we are going to query? Simply get the page for
356 : * the first buffer, and first page after the last buffer, and count
357 : * the pages from that.
358 : */
359 0 : startptr = (char *) TYPEALIGN_DOWN(os_page_size,
360 : BufferGetBlock(1));
361 0 : endptr = (char *) TYPEALIGN(os_page_size,
362 : (char *) BufferGetBlock(NBuffers) + BLCKSZ);
363 0 : os_page_count = (endptr - startptr) / os_page_size;
364 :
365 : /* Used to determine the NUMA node for all OS pages at once */
366 0 : os_page_ptrs = palloc0(sizeof(void *) * os_page_count);
367 0 : os_page_status = palloc(sizeof(uint64) * os_page_count);
368 :
369 : /* Fill pointers for all the memory pages. */
370 0 : idx = 0;
371 0 : for (char *ptr = startptr; ptr < endptr; ptr += os_page_size)
372 : {
373 0 : os_page_ptrs[idx++] = ptr;
374 :
375 : /* Only need to touch memory once per backend process lifetime */
376 0 : if (firstNumaTouch)
377 : pg_numa_touch_mem_if_required(ptr);
378 : }
379 :
380 : Assert(idx == os_page_count);
381 :
382 0 : elog(DEBUG1, "NUMA: NBuffers=%d os_page_count=" UINT64_FORMAT " "
383 : "os_page_size=%zu", NBuffers, os_page_count, os_page_size);
384 :
385 : /*
386 : * If we ever get 0xff back from kernel inquiry, then we probably have
387 : * bug in our buffers to OS page mapping code here.
388 : */
389 0 : memset(os_page_status, 0xff, sizeof(int) * os_page_count);
390 :
391 : /* Query NUMA status for all the pointers */
392 0 : if (pg_numa_query_pages(0, os_page_count, os_page_ptrs, os_page_status) == -1)
393 0 : elog(ERROR, "failed NUMA pages inquiry: %m");
394 :
395 : /* Initialize the multi-call context, load entries about buffers */
396 :
397 0 : funcctx = SRF_FIRSTCALL_INIT();
398 :
399 : /* Switch context when allocating stuff to be used in later calls */
400 0 : oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
401 :
402 : /* Create a user function context for cross-call persistence */
403 0 : fctx = (BufferCacheNumaContext *) palloc(sizeof(BufferCacheNumaContext));
404 :
405 0 : if (get_call_result_type(fcinfo, NULL, &expected_tupledesc) != TYPEFUNC_COMPOSITE)
406 0 : elog(ERROR, "return type must be a row type");
407 :
408 0 : if (expected_tupledesc->natts != NUM_BUFFERCACHE_NUMA_ELEM)
409 0 : elog(ERROR, "incorrect number of output arguments");
410 :
411 : /* Construct a tuple descriptor for the result rows. */
412 0 : tupledesc = CreateTemplateTupleDesc(expected_tupledesc->natts);
413 0 : TupleDescInitEntry(tupledesc, (AttrNumber) 1, "bufferid",
414 : INT4OID, -1, 0);
415 0 : TupleDescInitEntry(tupledesc, (AttrNumber) 2, "os_page_num",
416 : INT8OID, -1, 0);
417 0 : TupleDescInitEntry(tupledesc, (AttrNumber) 3, "numa_node",
418 : INT4OID, -1, 0);
419 :
420 0 : fctx->tupdesc = BlessTupleDesc(tupledesc);
421 :
422 : /*
423 : * Each buffer needs at least one entry, but it might be offset in
424 : * some way, and use one extra entry. So we allocate space for the
425 : * maximum number of entries we might need, and then count the exact
426 : * number as we're walking buffers. That way we can do it in one pass,
427 : * without reallocating memory.
428 : */
429 0 : pages_per_buffer = Max(1, BLCKSZ / os_page_size) + 1;
430 0 : max_entries = NBuffers * pages_per_buffer;
431 :
432 : /* Allocate entries for BufferCachePagesRec records. */
433 0 : fctx->record = (BufferCacheNumaRec *)
434 0 : MemoryContextAllocHuge(CurrentMemoryContext,
435 : sizeof(BufferCacheNumaRec) * max_entries);
436 :
437 : /* Return to original context when allocating transient memory */
438 0 : MemoryContextSwitchTo(oldcontext);
439 :
440 0 : if (firstNumaTouch)
441 0 : elog(DEBUG1, "NUMA: page-faulting the buffercache for proper NUMA readouts");
442 :
443 : /*
444 : * Scan through all the buffers, saving the relevant fields in the
445 : * fctx->record structure.
446 : *
447 : * We don't hold the partition locks, so we don't get a consistent
448 : * snapshot across all buffers, but we do grab the buffer header
449 : * locks, so the information of each buffer is self-consistent.
450 : *
451 : * This loop touches and stores addresses into os_page_ptrs[] as input
452 : * to one big move_pages(2) inquiry system call. Basically we ask for
453 : * all memory pages for NBuffers.
454 : */
455 0 : startptr = (char *) TYPEALIGN_DOWN(os_page_size, (char *) BufferGetBlock(1));
456 0 : idx = 0;
457 0 : for (i = 0; i < NBuffers; i++)
458 : {
459 0 : char *buffptr = (char *) BufferGetBlock(i + 1);
460 : BufferDesc *bufHdr;
461 : uint32 buf_state;
462 : uint32 bufferid;
463 : int32 page_num;
464 : char *startptr_buff,
465 : *endptr_buff;
466 :
467 0 : CHECK_FOR_INTERRUPTS();
468 :
469 0 : bufHdr = GetBufferDescriptor(i);
470 :
471 : /* Lock each buffer header before inspecting. */
472 0 : buf_state = LockBufHdr(bufHdr);
473 0 : bufferid = BufferDescriptorGetBuffer(bufHdr);
474 0 : UnlockBufHdr(bufHdr, buf_state);
475 :
476 : /* start of the first page of this buffer */
477 0 : startptr_buff = (char *) TYPEALIGN_DOWN(os_page_size, buffptr);
478 :
479 : /* end of the buffer (no need to align to memory page) */
480 0 : endptr_buff = buffptr + BLCKSZ;
481 :
482 : Assert(startptr_buff < endptr_buff);
483 :
484 : /* calculate ID of the first page for this buffer */
485 0 : page_num = (startptr_buff - startptr) / os_page_size;
486 :
487 : /* Add an entry for each OS page overlapping with this buffer. */
488 0 : for (char *ptr = startptr_buff; ptr < endptr_buff; ptr += os_page_size)
489 : {
490 0 : fctx->record[idx].bufferid = bufferid;
491 0 : fctx->record[idx].page_num = page_num;
492 0 : fctx->record[idx].numa_node = os_page_status[page_num];
493 :
494 : /* advance to the next entry/page */
495 0 : ++idx;
496 0 : ++page_num;
497 : }
498 : }
499 :
500 : Assert((idx >= os_page_count) && (idx <= max_entries));
501 :
502 : /* Set max calls and remember the user function context. */
503 0 : funcctx->max_calls = idx;
504 0 : funcctx->user_fctx = fctx;
505 :
506 : /* Remember this backend touched the pages */
507 0 : firstNumaTouch = false;
508 : }
509 :
510 0 : funcctx = SRF_PERCALL_SETUP();
511 :
512 : /* Get the saved state */
513 0 : fctx = funcctx->user_fctx;
514 :
515 0 : if (funcctx->call_cntr < funcctx->max_calls)
516 : {
517 0 : uint32 i = funcctx->call_cntr;
518 : Datum values[NUM_BUFFERCACHE_NUMA_ELEM];
519 : bool nulls[NUM_BUFFERCACHE_NUMA_ELEM];
520 :
521 0 : values[0] = Int32GetDatum(fctx->record[i].bufferid);
522 0 : nulls[0] = false;
523 :
524 0 : values[1] = Int64GetDatum(fctx->record[i].page_num);
525 0 : nulls[1] = false;
526 :
527 0 : values[2] = Int32GetDatum(fctx->record[i].numa_node);
528 0 : nulls[2] = false;
529 :
530 : /* Build and return the tuple. */
531 0 : tuple = heap_form_tuple(fctx->tupdesc, values, nulls);
532 0 : result = HeapTupleGetDatum(tuple);
533 :
534 0 : SRF_RETURN_NEXT(funcctx, result);
535 : }
536 : else
537 0 : SRF_RETURN_DONE(funcctx);
538 : }
539 :
540 : Datum
541 4 : pg_buffercache_summary(PG_FUNCTION_ARGS)
542 : {
543 : Datum result;
544 : TupleDesc tupledesc;
545 : HeapTuple tuple;
546 : Datum values[NUM_BUFFERCACHE_SUMMARY_ELEM];
547 : bool nulls[NUM_BUFFERCACHE_SUMMARY_ELEM];
548 :
549 4 : int32 buffers_used = 0;
550 4 : int32 buffers_unused = 0;
551 4 : int32 buffers_dirty = 0;
552 4 : int32 buffers_pinned = 0;
553 4 : int64 usagecount_total = 0;
554 :
555 4 : if (get_call_result_type(fcinfo, NULL, &tupledesc) != TYPEFUNC_COMPOSITE)
556 0 : elog(ERROR, "return type must be a row type");
557 :
558 65540 : for (int i = 0; i < NBuffers; i++)
559 : {
560 : BufferDesc *bufHdr;
561 : uint32 buf_state;
562 :
563 : /*
564 : * This function summarizes the state of all headers. Locking the
565 : * buffer headers wouldn't provide an improved result as the state of
566 : * the buffer can still change after we release the lock and it'd
567 : * noticeably increase the cost of the function.
568 : */
569 65536 : bufHdr = GetBufferDescriptor(i);
570 65536 : buf_state = pg_atomic_read_u32(&bufHdr->state);
571 :
572 65536 : if (buf_state & BM_VALID)
573 : {
574 7956 : buffers_used++;
575 7956 : usagecount_total += BUF_STATE_GET_USAGECOUNT(buf_state);
576 :
577 7956 : if (buf_state & BM_DIRTY)
578 3780 : buffers_dirty++;
579 : }
580 : else
581 57580 : buffers_unused++;
582 :
583 65536 : if (BUF_STATE_GET_REFCOUNT(buf_state) > 0)
584 0 : buffers_pinned++;
585 : }
586 :
587 4 : memset(nulls, 0, sizeof(nulls));
588 4 : values[0] = Int32GetDatum(buffers_used);
589 4 : values[1] = Int32GetDatum(buffers_unused);
590 4 : values[2] = Int32GetDatum(buffers_dirty);
591 4 : values[3] = Int32GetDatum(buffers_pinned);
592 :
593 4 : if (buffers_used != 0)
594 4 : values[4] = Float8GetDatum((double) usagecount_total / buffers_used);
595 : else
596 0 : nulls[4] = true;
597 :
598 : /* Build and return the tuple. */
599 4 : tuple = heap_form_tuple(tupledesc, values, nulls);
600 4 : result = HeapTupleGetDatum(tuple);
601 :
602 4 : PG_RETURN_DATUM(result);
603 : }
604 :
605 : Datum
606 4 : pg_buffercache_usage_counts(PG_FUNCTION_ARGS)
607 : {
608 4 : ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
609 4 : int usage_counts[BM_MAX_USAGE_COUNT + 1] = {0};
610 4 : int dirty[BM_MAX_USAGE_COUNT + 1] = {0};
611 4 : int pinned[BM_MAX_USAGE_COUNT + 1] = {0};
612 : Datum values[NUM_BUFFERCACHE_USAGE_COUNTS_ELEM];
613 4 : bool nulls[NUM_BUFFERCACHE_USAGE_COUNTS_ELEM] = {0};
614 :
615 4 : InitMaterializedSRF(fcinfo, 0);
616 :
617 65540 : for (int i = 0; i < NBuffers; i++)
618 : {
619 65536 : BufferDesc *bufHdr = GetBufferDescriptor(i);
620 65536 : uint32 buf_state = pg_atomic_read_u32(&bufHdr->state);
621 : int usage_count;
622 :
623 65536 : usage_count = BUF_STATE_GET_USAGECOUNT(buf_state);
624 65536 : usage_counts[usage_count]++;
625 :
626 65536 : if (buf_state & BM_DIRTY)
627 3780 : dirty[usage_count]++;
628 :
629 65536 : if (BUF_STATE_GET_REFCOUNT(buf_state) > 0)
630 0 : pinned[usage_count]++;
631 : }
632 :
633 28 : for (int i = 0; i < BM_MAX_USAGE_COUNT + 1; i++)
634 : {
635 24 : values[0] = Int32GetDatum(i);
636 24 : values[1] = Int32GetDatum(usage_counts[i]);
637 24 : values[2] = Int32GetDatum(dirty[i]);
638 24 : values[3] = Int32GetDatum(pinned[i]);
639 :
640 24 : tuplestore_putvalues(rsinfo->setResult, rsinfo->setDesc, values, nulls);
641 : }
642 :
643 4 : return (Datum) 0;
644 : }
645 :
646 : /*
647 : * Helper function to check if the user has superuser privileges.
648 : */
649 : static void
650 20 : pg_buffercache_superuser_check(char *func_name)
651 : {
652 20 : if (!superuser())
653 6 : ereport(ERROR,
654 : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
655 : errmsg("must be superuser to use %s()",
656 : func_name)));
657 14 : }
658 :
659 : /*
660 : * Try to evict a shared buffer.
661 : */
662 : Datum
663 10 : pg_buffercache_evict(PG_FUNCTION_ARGS)
664 : {
665 : Datum result;
666 : TupleDesc tupledesc;
667 : HeapTuple tuple;
668 : Datum values[NUM_BUFFERCACHE_EVICT_ELEM];
669 10 : bool nulls[NUM_BUFFERCACHE_EVICT_ELEM] = {0};
670 :
671 10 : Buffer buf = PG_GETARG_INT32(0);
672 : bool buffer_flushed;
673 :
674 10 : if (get_call_result_type(fcinfo, NULL, &tupledesc) != TYPEFUNC_COMPOSITE)
675 0 : elog(ERROR, "return type must be a row type");
676 :
677 10 : pg_buffercache_superuser_check("pg_buffercache_evict");
678 :
679 8 : if (buf < 1 || buf > NBuffers)
680 6 : elog(ERROR, "bad buffer ID: %d", buf);
681 :
682 2 : values[0] = BoolGetDatum(EvictUnpinnedBuffer(buf, &buffer_flushed));
683 2 : values[1] = BoolGetDatum(buffer_flushed);
684 :
685 2 : tuple = heap_form_tuple(tupledesc, values, nulls);
686 2 : result = HeapTupleGetDatum(tuple);
687 :
688 2 : PG_RETURN_DATUM(result);
689 : }
690 :
691 : /*
692 : * Try to evict specified relation.
693 : */
694 : Datum
695 6 : pg_buffercache_evict_relation(PG_FUNCTION_ARGS)
696 : {
697 : Datum result;
698 : TupleDesc tupledesc;
699 : HeapTuple tuple;
700 : Datum values[NUM_BUFFERCACHE_EVICT_RELATION_ELEM];
701 6 : bool nulls[NUM_BUFFERCACHE_EVICT_RELATION_ELEM] = {0};
702 :
703 : Oid relOid;
704 : Relation rel;
705 :
706 6 : int32 buffers_evicted = 0;
707 6 : int32 buffers_flushed = 0;
708 6 : int32 buffers_skipped = 0;
709 :
710 6 : if (get_call_result_type(fcinfo, NULL, &tupledesc) != TYPEFUNC_COMPOSITE)
711 0 : elog(ERROR, "return type must be a row type");
712 :
713 6 : pg_buffercache_superuser_check("pg_buffercache_evict_relation");
714 :
715 4 : relOid = PG_GETARG_OID(0);
716 :
717 4 : rel = relation_open(relOid, AccessShareLock);
718 :
719 4 : if (RelationUsesLocalBuffers(rel))
720 2 : ereport(ERROR,
721 : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
722 : errmsg("relation uses local buffers, %s() is intended to be used for shared buffers only",
723 : "pg_buffercache_evict_relation")));
724 :
725 2 : EvictRelUnpinnedBuffers(rel, &buffers_evicted, &buffers_flushed,
726 : &buffers_skipped);
727 :
728 2 : relation_close(rel, AccessShareLock);
729 :
730 2 : values[0] = Int32GetDatum(buffers_evicted);
731 2 : values[1] = Int32GetDatum(buffers_flushed);
732 2 : values[2] = Int32GetDatum(buffers_skipped);
733 :
734 2 : tuple = heap_form_tuple(tupledesc, values, nulls);
735 2 : result = HeapTupleGetDatum(tuple);
736 :
737 2 : PG_RETURN_DATUM(result);
738 : }
739 :
740 :
741 : /*
742 : * Try to evict all shared buffers.
743 : */
744 : Datum
745 4 : pg_buffercache_evict_all(PG_FUNCTION_ARGS)
746 : {
747 : Datum result;
748 : TupleDesc tupledesc;
749 : HeapTuple tuple;
750 : Datum values[NUM_BUFFERCACHE_EVICT_ALL_ELEM];
751 4 : bool nulls[NUM_BUFFERCACHE_EVICT_ALL_ELEM] = {0};
752 :
753 4 : int32 buffers_evicted = 0;
754 4 : int32 buffers_flushed = 0;
755 4 : int32 buffers_skipped = 0;
756 :
757 4 : if (get_call_result_type(fcinfo, NULL, &tupledesc) != TYPEFUNC_COMPOSITE)
758 0 : elog(ERROR, "return type must be a row type");
759 :
760 4 : pg_buffercache_superuser_check("pg_buffercache_evict_all");
761 :
762 2 : EvictAllUnpinnedBuffers(&buffers_evicted, &buffers_flushed,
763 : &buffers_skipped);
764 :
765 2 : values[0] = Int32GetDatum(buffers_evicted);
766 2 : values[1] = Int32GetDatum(buffers_flushed);
767 2 : values[2] = Int32GetDatum(buffers_skipped);
768 :
769 2 : tuple = heap_form_tuple(tupledesc, values, nulls);
770 2 : result = HeapTupleGetDatum(tuple);
771 :
772 2 : PG_RETURN_DATUM(result);
773 : }
|