PostgreSQL Source Code git master
Loading...
Searching...
No Matches
localbuf.c File Reference
#include "postgres.h"
#include "access/parallel.h"
#include "executor/instrument.h"
#include "pgstat.h"
#include "storage/aio.h"
#include "storage/buf_internals.h"
#include "storage/bufmgr.h"
#include "storage/fd.h"
#include "utils/guc_hooks.h"
#include "utils/memdebug.h"
#include "utils/memutils.h"
#include "utils/rel.h"
#include "utils/resowner.h"
Include dependency graph for localbuf.c:

Go to the source code of this file.

Data Structures

struct  LocalBufferLookupEnt
 

Macros

#define LocalBufHdrGetBlock(bufHdr)    LocalBufferBlockPointers[-((bufHdr)->buf_id + 2)]
 

Functions

static void InitLocalBuffers (void)
 
static Block GetLocalBufferStorage (void)
 
static Buffer GetLocalVictimBuffer (void)
 
PrefetchBufferResult PrefetchLocalBuffer (SMgrRelation smgr, ForkNumber forkNum, BlockNumber blockNum)
 
BufferDescLocalBufferAlloc (SMgrRelation smgr, ForkNumber forkNum, BlockNumber blockNum, bool *foundPtr)
 
void FlushLocalBuffer (BufferDesc *bufHdr, SMgrRelation reln)
 
uint32 GetLocalPinLimit (void)
 
uint32 GetAdditionalLocalPinLimit (void)
 
void LimitAdditionalLocalPins (uint32 *additional_pins)
 
BlockNumber ExtendBufferedRelLocal (BufferManagerRelation bmr, ForkNumber fork, uint32 flags, uint32 extend_by, BlockNumber extend_upto, Buffer *buffers, uint32 *extended_by)
 
void MarkLocalBufferDirty (Buffer buffer)
 
bool StartLocalBufferIO (BufferDesc *bufHdr, bool forInput, bool nowait)
 
void TerminateLocalBufferIO (BufferDesc *bufHdr, bool clear_dirty, uint64 set_flag_bits, bool release_aio)
 
void InvalidateLocalBuffer (BufferDesc *bufHdr, bool check_unreferenced)
 
void DropRelationLocalBuffers (RelFileLocator rlocator, ForkNumber *forkNum, int nforks, BlockNumber *firstDelBlock)
 
void DropRelationAllLocalBuffers (RelFileLocator rlocator)
 
bool PinLocalBuffer (BufferDesc *buf_hdr, bool adjust_usagecount)
 
void UnpinLocalBuffer (Buffer buffer)
 
void UnpinLocalBufferNoOwner (Buffer buffer)
 
bool check_temp_buffers (int *newval, void **extra, GucSource source)
 
static void CheckForLocalBufferLeaks (void)
 
void AtEOXact_LocalBuffers (bool isCommit)
 
void AtProcExit_LocalBuffers (void)
 

Variables

int NLocBuffer = 0
 
BufferDescLocalBufferDescriptors = NULL
 
BlockLocalBufferBlockPointers = NULL
 
int32LocalRefCount = NULL
 
static int nextFreeLocalBufId = 0
 
static HTABLocalBufHash = NULL
 
static int NLocalPinnedBuffers = 0
 

Macro Definition Documentation

◆ LocalBufHdrGetBlock

#define LocalBufHdrGetBlock (   bufHdr)     LocalBufferBlockPointers[-((bufHdr)->buf_id + 2)]

Definition at line 42 of file localbuf.c.

73{
74 PrefetchBufferResult result = {InvalidBuffer, false};
75 BufferTag newTag; /* identity of requested block */
77
78 InitBufferTag(&newTag, &smgr->smgr_rlocator.locator, forkNum, blockNum);
79
80 /* Initialize local buffers if first request in this session */
81 if (LocalBufHash == NULL)
83
84 /* See if the desired buffer already exists */
87
88 if (hresult)
89 {
90 /* Yes, so nothing to do */
91 result.recent_buffer = -hresult->id - 1;
92 }
93 else
94 {
95#ifdef USE_PREFETCH
96 /* Not in buffers, so initiate prefetch */
97 if ((io_direct_flags & IO_DIRECT_DATA) == 0 &&
98 smgrprefetch(smgr, forkNum, blockNum, 1))
99 {
100 result.initiated_io = true;
101 }
102#endif /* USE_PREFETCH */
103 }
104
105 return result;
106}
107
108
109/*
110 * LocalBufferAlloc -
111 * Find or create a local buffer for the given page of the given relation.
112 *
113 * API is similar to bufmgr.c's BufferAlloc, except that we do not need to do
114 * any locking since this is all local. We support only default access
115 * strategy (hence, usage_count is always advanced).
116 */
119 bool *foundPtr)
120{
121 BufferTag newTag; /* identity of requested block */
125 int bufid;
126 bool found;
127
128 InitBufferTag(&newTag, &smgr->smgr_rlocator.locator, forkNum, blockNum);
129
130 /* Initialize local buffers if first request in this session */
131 if (LocalBufHash == NULL)
133
135
136 /* See if the desired buffer already exists */
139
140 if (hresult)
141 {
142 bufid = hresult->id;
145
147 }
148 else
149 {
151
153 bufid = -victim_buffer - 1;
155
158 if (found) /* shouldn't happen */
159 elog(ERROR, "local buffer hash table corrupted");
160 hresult->id = bufid;
161
162 /*
163 * it's all ours now.
164 */
165 bufHdr->tag = newTag;
166
171
172 *foundPtr = false;
173 }
174
175 return bufHdr;
176}
177
178/*
179 * Like FlushBuffer(), just for local buffers.
180 */
181void
183{
186
188
189 /*
190 * Try to start an I/O operation. There currently are no reasons for
191 * StartLocalBufferIO to return false, so we raise an error in that case.
192 */
193 if (!StartLocalBufferIO(bufHdr, false, false))
194 elog(ERROR, "failed to start write IO on local buffer");
195
196 /* Find smgr relation for buffer */
197 if (reln == NULL)
200
202
204
205 /* And write... */
208 bufHdr->tag.blockNum,
209 localpage,
210 false);
211
212 /* Temporary table I/O does not use Buffer Access Strategies */
215
216 /* Mark not-dirty */
217 TerminateLocalBufferIO(bufHdr, true, 0, false);
218
220}
221
222static Buffer
224{
225 int victim_bufid;
226 int trycounter;
228
230
231 /*
232 * Need to get a new buffer. We use a clock-sweep algorithm (essentially
233 * the same as what freelist.c does now...)
234 */
236 for (;;)
237 {
239
242
244
245 if (LocalRefCount[victim_bufid] == 0)
246 {
248
250 {
254 }
255 else if (BUF_STATE_GET_REFCOUNT(buf_state) > 0)
256 {
257 /*
258 * This can be reached if the backend initiated AIO for this
259 * buffer and then errored out.
260 */
261 }
262 else
263 {
264 /* Found a usable buffer */
265 PinLocalBuffer(bufHdr, false);
266 break;
267 }
268 }
269 else if (--trycounter == 0)
272 errmsg("no empty local buffer available")));
273 }
274
275 /*
276 * lazy memory allocation: allocate space on first use of a buffer.
277 */
279 {
280 /* Set pointer for use by BufferGetBlock() macro */
282 }
283
284 /*
285 * this buffer is not referenced but it might still be dirty. if that's
286 * the case, write it out before reusing it!
287 */
288 if (pg_atomic_read_u64(&bufHdr->state) & BM_DIRTY)
290
291 /*
292 * Remove the victim buffer from the hashtable and mark as invalid.
293 */
295 {
297
299 }
300
302}
303
304/* see GetPinLimit() */
305uint32
307{
308 /* Every backend has its own temporary buffers, and can pin them all. */
309 return num_temp_buffers;
310}
311
312/* see GetAdditionalPinLimit() */
313uint32
315{
318}
319
320/* see LimitAdditionalPins() */
321void
323{
325
326 if (*additional_pins <= 1)
327 return;
328
329 /*
330 * In contrast to LimitAdditionalPins() other backends don't play a role
331 * here. We can allow up to NLocBuffer pins in total, but it might not be
332 * initialized yet so read num_temp_buffers.
333 */
335
338}
339
340/*
341 * Implementation of ExtendBufferedRelBy() and ExtendBufferedRelTo() for
342 * temporary buffers.
343 */
347 uint32 flags,
350 Buffer *buffers,
352{
355
356 /* Initialize local buffers if first request in this session */
357 if (LocalBufHash == NULL)
359
361
362 for (uint32 i = 0; i < extend_by; i++)
363 {
366
367 buffers[i] = GetLocalVictimBuffer();
368 buf_hdr = GetLocalBufferDescriptor(-buffers[i] - 1);
370
371 /* new buffers are zero-filled */
373 }
374
376
378 {
379 /*
380 * In contrast to shared relations, nothing could change the relation
381 * size concurrently. Thus we shouldn't end up finding that we don't
382 * need to do anything.
383 */
385
387 }
388
389 /* Fail if relation is already at maximum possible length */
393 errmsg("cannot extend relation %s beyond %u blocks",
394 relpath(BMR_GET_SMGR(bmr)->smgr_rlocator, fork).str,
396
397 for (uint32 i = 0; i < extend_by; i++)
398 {
399 int victim_buf_id;
401 BufferTag tag;
403 bool found;
404
405 victim_buf_id = -buffers[i] - 1;
407
408 /* in case we need to pin an existing buffer below */
410
411 InitBufferTag(&tag, &BMR_GET_SMGR(bmr)->smgr_rlocator.locator, fork,
412 first_block + i);
413
415 hash_search(LocalBufHash, &tag, HASH_ENTER, &found);
416 if (found)
417 {
420
422
426
427 /*
428 * Clear the BM_VALID bit, do StartLocalBufferIO() and proceed.
429 */
435
436 /* no need to loop for local buffers */
437 StartLocalBufferIO(existing_hdr, true, false);
438 }
439 else
440 {
442
444
445 victim_buf_hdr->tag = tag;
446
448
450
452
454 }
455 }
456
458
459 /* actually extend relation */
461
464
465 for (uint32 i = 0; i < extend_by; i++)
466 {
467 Buffer buf = buffers[i];
470
472
476 }
477
479
481
482 return first_block;
483}
484
485/*
486 * MarkLocalBufferDirty -
487 * mark a local buffer dirty
488 */
489void
491{
492 int bufid;
495
496 Assert(BufferIsLocal(buffer));
497
498#ifdef LBDEBUG
499 fprintf(stderr, "LB DIRTY %d\n", buffer);
500#endif
501
502 bufid = -buffer - 1;
503
505
507
509
510 if (!(buf_state & BM_DIRTY))
512
514
516}
517
518/*
519 * Like StartBufferIO, but for local buffers
520 */
521bool
522StartLocalBufferIO(BufferDesc *bufHdr, bool forInput, bool nowait)
523{
525
526 /*
527 * With AIO the buffer could have IO in progress, e.g. when there are two
528 * scans of the same relation. Either wait for the other IO or return
529 * false.
530 */
531 if (pgaio_wref_valid(&bufHdr->io_wref))
532 {
533 PgAioWaitRef iow = bufHdr->io_wref;
534
535 if (nowait)
536 return false;
537
539 }
540
541 /* Once we get here, there is definitely no I/O active on this buffer */
542
543 /* Check if someone else already did the I/O */
546 {
547 return false;
548 }
549
550 /* BM_IO_IN_PROGRESS isn't currently used for local buffers */
551
552 /* local buffers don't track IO using resowners */
553
554 return true;
555}
556
557/*
558 * Like TerminateBufferIO, but for local buffers
559 */
560void
562 bool release_aio)
563{
564 /* Only need to adjust flags */
566
567 /* BM_IO_IN_PROGRESS isn't currently used for local buffers */
568
569 /* Clear earlier errors, if this IO failed, it'll be marked again */
571
572 if (clear_dirty)
574
575 if (release_aio)
576 {
577 /* release pin held by IO subsystem, see also buffer_stage_common() */
580 pgaio_wref_clear(&bufHdr->io_wref);
581 }
582
585
586 /* local buffers don't track IO using resowners */
587
588 /* local buffers don't use the IO CV, as no other process can see buffer */
589
590 /* local buffers don't use BM_PIN_COUNT_WAITER, so no need to wake */
591}
592
593/*
594 * InvalidateLocalBuffer -- mark a local buffer invalid.
595 *
596 * If check_unreferenced is true, error out if the buffer is still
597 * pinned. Passing false is appropriate when calling InvalidateLocalBuffer()
598 * as part of changing the identity of a buffer, instead of just dropping the
599 * buffer.
600 *
601 * See also InvalidateBuffer().
602 */
603void
605{
607 int bufid = -buffer - 1;
610
611 /*
612 * It's possible that we started IO on this buffer before e.g. aborting
613 * the transaction that created a table. We need to wait for that IO to
614 * complete before removing / reusing the buffer.
615 */
616 if (pgaio_wref_valid(&bufHdr->io_wref))
617 {
618 PgAioWaitRef iow = bufHdr->io_wref;
619
621 Assert(!pgaio_wref_valid(&bufHdr->io_wref));
622 }
623
625
626 /*
627 * We need to test not just LocalRefCount[bufid] but also the BufferDesc
628 * itself, as the latter is used to represent a pin by the AIO subsystem.
629 * This can happen if AIO is initiated and then the query errors out.
630 */
631 if (check_unreferenced &&
633 elog(ERROR, "block %u of %s is still referenced (local %d)",
634 bufHdr->tag.blockNum,
637 BufTagGetForkNum(&bufHdr->tag)).str,
639
640 /* Remove entry from hashtable */
643 if (!hresult) /* shouldn't happen */
644 elog(ERROR, "local buffer hash table corrupted");
645 /* Mark buffer invalid */
646 ClearBufferTag(&bufHdr->tag);
650}
651
652/*
653 * DropRelationLocalBuffers
654 * This function removes from the buffer pool all the pages of the
655 * specified relation that have block numbers >= firstDelBlock.
656 * (In particular, with firstDelBlock = 0, all pages are removed.)
657 * Dirty pages are simply dropped, without bothering to write them
658 * out first. Therefore, this is NOT rollback-able, and so should be
659 * used only with extreme caution!
660 *
661 * See DropRelationBuffers in bufmgr.c for more notes.
662 */
663void
666{
667 int i;
668 int j;
669
670 for (i = 0; i < NLocBuffer; i++)
671 {
674
676
677 if (!(buf_state & BM_TAG_VALID) ||
678 !BufTagMatchesRelFileLocator(&bufHdr->tag, &rlocator))
679 continue;
680
681 for (j = 0; j < nforks; j++)
682 {
683 if (BufTagGetForkNum(&bufHdr->tag) == forkNum[j] &&
684 bufHdr->tag.blockNum >= firstDelBlock[j])
685 {
687 break;
688 }
689 }
690 }
691}
692
693/*
694 * DropRelationAllLocalBuffers
695 * This function removes from the buffer pool all pages of all forks
696 * of the specified relation.
697 *
698 * See DropRelationsAllBuffers in bufmgr.c for more notes.
699 */
700void
702{
703 int i;
704
705 for (i = 0; i < NLocBuffer; i++)
706 {
709
711
712 if ((buf_state & BM_TAG_VALID) &&
713 BufTagMatchesRelFileLocator(&bufHdr->tag, &rlocator))
714 {
716 }
717 }
718}
719
720/*
721 * InitLocalBuffers -
722 * init the local buffer cache. Since most queries (esp. multi-user ones)
723 * don't involve local buffers, we delay allocating actual memory for the
724 * buffers until we need them; just make the buffer headers here.
725 */
726static void
728{
730 HASHCTL info;
731 int i;
732
733 /*
734 * Parallel workers can't access data in temporary tables, because they
735 * have no visibility into the local buffers of their leader. This is a
736 * convenient, low-cost place to provide a backstop check for that. Note
737 * that we don't wish to prevent a parallel worker from accessing catalog
738 * metadata about a temp table, so checks at higher levels would be
739 * inappropriate.
740 */
741 if (IsParallelWorker())
744 errmsg("cannot access temporary tables during a parallel operation")));
745
746 /* Allocate and zero buffer headers and auxiliary arrays */
749 LocalRefCount = (int32 *) calloc(nbufs, sizeof(int32));
753 errmsg("out of memory")));
754
756
757 /* initialize fields that need to start off nonzero */
758 for (i = 0; i < nbufs; i++)
759 {
761
762 /*
763 * negative to indicate local buffer. This is tricky: shared buffers
764 * start with 0. We have to start with -2. (Note that the routine
765 * BufferDescriptorGetBuffer adds 1 to buf_id so our first buffer id
766 * is -1.)
767 */
768 buf->buf_id = -i - 2;
769
770 pgaio_wref_clear(&buf->io_wref);
771
772 /*
773 * Intentionally do not initialize the buffer's atomic variable
774 * (besides zeroing the underlying memory above). That way we get
775 * errors on platforms without atomics, if somebody (re-)introduces
776 * atomic operations for local buffers.
777 */
778 }
779
780 /* Create the lookup hash table */
781 info.keysize = sizeof(BufferTag);
782 info.entrysize = sizeof(LocalBufferLookupEnt);
783
784 LocalBufHash = hash_create("Local Buffer Lookup Table",
785 nbufs,
786 &info,
788
789 if (!LocalBufHash)
790 elog(ERROR, "could not initialize local buffer hash table");
791
792 /* Initialization done, mark buffers allocated */
794}
795
796/*
797 * XXX: We could have a slightly more efficient version of PinLocalBuffer()
798 * that does not support adjusting the usagecount - but so far it does not
799 * seem worth the trouble.
800 *
801 * Note that ResourceOwnerEnlarge() must have been done already.
802 */
803bool
805{
808 int bufid = -buffer - 1;
809
811
812 if (LocalRefCount[bufid] == 0)
813 {
816 if (adjust_usagecount &&
818 {
820 }
822
823 /*
824 * See comment in PinBuffer().
825 *
826 * If the buffer isn't allocated yet, it'll be marked as defined in
827 * GetLocalBufferStorage().
828 */
831 }
835
836 return buf_state & BM_VALID;
837}
838
839void
841{
844}
845
846void
848{
849 int buffid = -buffer - 1;
850
851 Assert(BufferIsLocal(buffer));
854
855 if (--LocalRefCount[buffid] == 0)
856 {
859
861
866
867 /* see comment in UnpinBufferNoOwner */
869 }
870}
871
872/*
873 * GUC check_hook for temp_buffers
874 */
875bool
876check_temp_buffers(int *newval, void **extra, GucSource source)
877{
878 /*
879 * Once local buffers have been initialized, it's too late to change this.
880 * However, if this is only a test call, allow it.
881 */
883 {
884 GUC_check_errdetail("\"temp_buffers\" cannot be changed after any temporary tables have been accessed in the session.");
885 return false;
886 }
887 return true;
888}
889
890/*
891 * GetLocalBufferStorage - allocate memory for a local buffer
892 *
893 * The idea of this function is to aggregate our requests for storage
894 * so that the memory manager doesn't see a whole lot of relatively small
895 * requests. Since we'll never give back a local buffer once it's created
896 * within a particular process, no point in burdening memmgr with separately
897 * managed chunks.
898 */
899static Block
901{
902 static char *cur_block = NULL;
903 static int next_buf_in_block = 0;
904 static int num_bufs_in_block = 0;
905 static int total_bufs_allocated = 0;
907
908 char *this_buf;
909
911
913 {
914 /* Need to make a new request to memmgr */
915 int num_bufs;
916
917 /*
918 * We allocate local buffers in a context of their own, so that the
919 * space eaten for them is easily recognizable in MemoryContextStats
920 * output. Create the context on first use.
921 */
925 "LocalBufferContext",
927
928 /* Start with a 16-buffer request; subsequent ones double each time */
929 num_bufs = Max(num_bufs_in_block * 2, 16);
930 /* But not more than what we need for all remaining local bufs */
932 /* And don't overflow MaxAllocSize, either */
934
935 /* Buffers should be I/O aligned. */
939 0);
940
943 }
944
945 /* Allocate next buffer in current memory block */
949
950 /*
951 * Caller's PinLocalBuffer() was too early for Valgrind updates, so do it
952 * here. The block is actually undefined, but we want consistency with
953 * the regular case of not needing to allocate memory. This is
954 * specifically needed when method_io_uring.c fills the block, because
955 * Valgrind doesn't recognize io_uring reads causing undefined memory to
956 * become defined.
957 */
959
960 return (Block) this_buf;
961}
962
963/*
964 * CheckForLocalBufferLeaks - ensure this backend holds no local buffer pins
965 *
966 * This is just like CheckForBufferLeaks(), but for local buffers.
967 */
968static void
970{
971#ifdef USE_ASSERT_CHECKING
972 if (LocalRefCount)
973 {
974 int RefCountErrors = 0;
975 int i;
976
977 for (i = 0; i < NLocBuffer; i++)
978 {
979 if (LocalRefCount[i] != 0)
980 {
981 Buffer b = -i - 1;
982 char *s;
983
985 elog(WARNING, "local buffer refcount leak: %s", s);
986 pfree(s);
987
989 }
990 }
992 }
993#endif
994}
995
996/*
997 * AtEOXact_LocalBuffers - clean up at end of transaction.
998 *
999 * This is just like AtEOXact_Buffers, but for local buffers.
1000 */
1001void
1003{
1005}
1006
1007/*
1008 * AtProcExit_LocalBuffers - ensure we have dropped pins during backend exit.
1009 *
1010 * This is just like AtProcExit_Buffers, but for local buffers.
1011 */
1012void
1014{
1015 /*
1016 * We shouldn't be holding any remaining pins; if we are, and assertions
1017 * aren't enabled, we'll fail later in DropRelationBuffers while trying to
1018 * drop the temp rels.
1019 */
1021}
bool pgaio_wref_valid(PgAioWaitRef *iow)
Definition aio.c:971
void pgaio_wref_clear(PgAioWaitRef *iow)
Definition aio.c:964
void pgaio_wref_wait(PgAioWaitRef *iow)
Definition aio.c:991
static void pg_atomic_unlocked_write_u64(volatile pg_atomic_uint64 *ptr, uint64 val)
Definition atomics.h:494
static uint64 pg_atomic_read_u64(volatile pg_atomic_uint64 *ptr)
Definition atomics.h:467
uint32 BlockNumber
Definition block.h:31
#define InvalidBlockNumber
Definition block.h:33
#define MaxBlockNumber
Definition block.h:35
int Buffer
Definition buf.h:23
#define InvalidBuffer
Definition buf.h:25
#define BufferIsLocal(buffer)
Definition buf.h:37
#define BM_MAX_USAGE_COUNT
static void InitBufferTag(BufferTag *tag, const RelFileLocator *rlocator, ForkNumber forkNum, BlockNumber blockNum)
#define BM_TAG_VALID
#define BUF_USAGECOUNT_MASK
static ForkNumber BufTagGetForkNum(const BufferTag *tag)
#define BUF_REFCOUNT_ONE
static bool BufferTagsEqual(const BufferTag *tag1, const BufferTag *tag2)
static bool BufTagMatchesRelFileLocator(const BufferTag *tag, const RelFileLocator *rlocator)
#define BUF_FLAG_MASK
#define BM_DIRTY
#define BM_JUST_DIRTIED
#define BUF_STATE_GET_USAGECOUNT(state)
static void ClearBufferTag(BufferTag *tag)
static void ResourceOwnerRememberBuffer(ResourceOwner owner, Buffer buffer)
struct buftag BufferTag
static void ResourceOwnerForgetBuffer(ResourceOwner owner, Buffer buffer)
#define BUF_USAGECOUNT_ONE
#define BUF_STATE_GET_REFCOUNT(state)
static RelFileLocator BufTagGetRelFileLocator(const BufferTag *tag)
#define BM_VALID
static BufferDesc * GetLocalBufferDescriptor(uint32 id)
static Buffer BufferDescriptorGetBuffer(const BufferDesc *bdesc)
bool track_io_timing
Definition bufmgr.c:176
char * DebugPrintBufferRefcount(Buffer buffer)
Definition bufmgr.c:4299
void * Block
Definition bufmgr.h:26
#define BMR_GET_SMGR(bmr)
Definition bufmgr.h:118
void PageSetChecksumInplace(Page page, BlockNumber blkno)
Definition bufpage.c:1541
PageData * Page
Definition bufpage.h:81
#define Min(x, y)
Definition c.h:997
#define Max(x, y)
Definition c.h:991
#define Assert(condition)
Definition c.h:873
int32_t int32
Definition c.h:542
uint64_t uint64
Definition c.h:547
uint32_t uint32
Definition c.h:546
#define MemSet(start, val, len)
Definition c.h:1013
#define fprintf(file, fmt, msg)
Definition cubescan.l:21
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition dynahash.c:952
HTAB * hash_create(const char *tabname, int64 nelem, const HASHCTL *info, int flags)
Definition dynahash.c:358
int errcode(int sqlerrcode)
Definition elog.c:863
int errmsg(const char *fmt,...)
Definition elog.c:1080
#define FATAL
Definition elog.h:41
#define WARNING
Definition elog.h:36
#define ERROR
Definition elog.h:39
#define elog(elevel,...)
Definition elog.h:226
#define ereport(elevel,...)
Definition elog.h:150
int io_direct_flags
Definition fd.c:168
#define IO_DIRECT_DATA
Definition fd.h:54
#define MaxAllocSize
Definition fe_memutils.h:22
ProcNumber MyProcNumber
Definition globals.c:90
#define newval
#define GUC_check_errdetail
Definition guc.h:505
GucSource
Definition guc.h:112
@ PGC_S_TEST
Definition guc.h:125
int num_temp_buffers
Definition guc_tables.c:553
const char * str
@ HASH_FIND
Definition hsearch.h:113
@ HASH_REMOVE
Definition hsearch.h:115
@ HASH_ENTER
Definition hsearch.h:114
#define HASH_ELEM
Definition hsearch.h:95
#define HASH_BLOBS
Definition hsearch.h:97
#define IsParallelWorker()
Definition parallel.h:60
BufferUsage pgBufferUsage
Definition instrument.c:20
int b
Definition isn.c:74
int j
Definition isn.c:78
int i
Definition isn.c:77
int32 * LocalRefCount
Definition localbuf.c:49
void FlushLocalBuffer(BufferDesc *bufHdr, SMgrRelation reln)
Definition localbuf.c:183
void UnpinLocalBuffer(Buffer buffer)
Definition localbuf.c:841
bool StartLocalBufferIO(BufferDesc *bufHdr, bool forInput, bool nowait)
Definition localbuf.c:523
static HTAB * LocalBufHash
Definition localbuf.c:53
static int NLocalPinnedBuffers
Definition localbuf.c:56
void AtEOXact_LocalBuffers(bool isCommit)
Definition localbuf.c:1003
#define LocalBufHdrGetBlock(bufHdr)
Definition localbuf.c:42
static void CheckForLocalBufferLeaks(void)
Definition localbuf.c:970
uint32 GetAdditionalLocalPinLimit(void)
Definition localbuf.c:315
static Block GetLocalBufferStorage(void)
Definition localbuf.c:901
static int nextFreeLocalBufId
Definition localbuf.c:51
bool check_temp_buffers(int *newval, void **extra, GucSource source)
Definition localbuf.c:877
void AtProcExit_LocalBuffers(void)
Definition localbuf.c:1014
bool PinLocalBuffer(BufferDesc *buf_hdr, bool adjust_usagecount)
Definition localbuf.c:805
static void InitLocalBuffers(void)
Definition localbuf.c:728
void LimitAdditionalLocalPins(uint32 *additional_pins)
Definition localbuf.c:323
uint32 GetLocalPinLimit(void)
Definition localbuf.c:307
static Buffer GetLocalVictimBuffer(void)
Definition localbuf.c:224
void MarkLocalBufferDirty(Buffer buffer)
Definition localbuf.c:491
void DropRelationAllLocalBuffers(RelFileLocator rlocator)
Definition localbuf.c:702
void InvalidateLocalBuffer(BufferDesc *bufHdr, bool check_unreferenced)
Definition localbuf.c:605
void TerminateLocalBufferIO(BufferDesc *bufHdr, bool clear_dirty, uint64 set_flag_bits, bool release_aio)
Definition localbuf.c:562
int NLocBuffer
Definition localbuf.c:45
BlockNumber ExtendBufferedRelLocal(BufferManagerRelation bmr, ForkNumber fork, uint32 flags, uint32 extend_by, BlockNumber extend_upto, Buffer *buffers, uint32 *extended_by)
Definition localbuf.c:346
Block * LocalBufferBlockPointers
Definition localbuf.c:48
void UnpinLocalBufferNoOwner(Buffer buffer)
Definition localbuf.c:848
void DropRelationLocalBuffers(RelFileLocator rlocator, ForkNumber *forkNum, int nforks, BlockNumber *firstDelBlock)
Definition localbuf.c:665
BufferDesc * LocalBufferDescriptors
Definition localbuf.c:47
BufferDesc * LocalBufferAlloc(SMgrRelation smgr, ForkNumber forkNum, BlockNumber blockNum, bool *foundPtr)
Definition localbuf.c:119
void pfree(void *pointer)
Definition mcxt.c:1616
void * MemoryContextAllocAligned(MemoryContext context, Size size, Size alignto, int flags)
Definition mcxt.c:1482
MemoryContext TopMemoryContext
Definition mcxt.c:166
#define VALGRIND_MAKE_MEM_DEFINED(addr, size)
Definition memdebug.h:26
#define VALGRIND_MAKE_MEM_NOACCESS(addr, size)
Definition memdebug.h:27
#define AllocSetContextCreate
Definition memutils.h:129
#define ALLOCSET_DEFAULT_SIZES
Definition memutils.h:160
#define PG_IO_ALIGN_SIZE
static rewind_source * source
Definition pg_rewind.c:89
static char buf[DEFAULT_XLOG_SEG_SIZE]
@ IOOBJECT_TEMP_RELATION
Definition pgstat.h:278
@ IOCONTEXT_NORMAL
Definition pgstat.h:289
@ IOOP_EXTEND
Definition pgstat.h:314
@ IOOP_EVICT
Definition pgstat.h:307
@ IOOP_WRITE
Definition pgstat.h:316
instr_time pgstat_prepare_io_time(bool track_io_guc)
Definition pgstat_io.c:91
void pgstat_count_io_op(IOObject io_object, IOContext io_context, IOOp io_op, uint32 cnt, uint64 bytes)
Definition pgstat_io.c:68
void pgstat_count_io_op_time(IOObject io_object, IOContext io_context, IOOp io_op, instr_time start_time, uint32 cnt, uint64 bytes)
Definition pgstat_io.c:122
static int fb(int x)
ForkNumber
Definition relpath.h:56
#define relpath(rlocator, forknum)
Definition relpath.h:150
#define relpathbackend(rlocator, backend, forknum)
Definition relpath.h:141
ResourceOwner CurrentResourceOwner
Definition resowner.c:173
void ResourceOwnerEnlarge(ResourceOwner owner)
Definition resowner.c:449
BlockNumber smgrnblocks(SMgrRelation reln, ForkNumber forknum)
Definition smgr.c:819
SMgrRelation smgropen(RelFileLocator rlocator, ProcNumber backend)
Definition smgr.c:240
void smgrzeroextend(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum, int nblocks, bool skipFsync)
Definition smgr.c:649
bool smgrprefetch(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum, int nblocks)
Definition smgr.c:678
static void smgrwrite(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum, const void *buffer, bool skipFsync)
Definition smgr.h:131
#define calloc(a, b)
int64 local_blks_written
Definition instrument.h:33
int64 local_blks_dirtied
Definition instrument.h:32
Size keysize
Definition hsearch.h:75
Size entrysize
Definition hsearch.h:76
Buffer recent_buffer
Definition bufmgr.h:61
RelFileLocator locator
RelFileLocatorBackend smgr_rlocator
Definition smgr.h:38

Function Documentation

◆ AtEOXact_LocalBuffers()

void AtEOXact_LocalBuffers ( bool  isCommit)

Definition at line 1003 of file localbuf.c.

1004{
1006}

References CheckForLocalBufferLeaks().

Referenced by AtEOXact_Buffers().

◆ AtProcExit_LocalBuffers()

void AtProcExit_LocalBuffers ( void  )

Definition at line 1014 of file localbuf.c.

1015{
1016 /*
1017 * We shouldn't be holding any remaining pins; if we are, and assertions
1018 * aren't enabled, we'll fail later in DropRelationBuffers while trying to
1019 * drop the temp rels.
1020 */
1022}

References CheckForLocalBufferLeaks().

Referenced by AtProcExit_Buffers().

◆ check_temp_buffers()

bool check_temp_buffers ( int newval,
void **  extra,
GucSource  source 
)

Definition at line 877 of file localbuf.c.

878{
879 /*
880 * Once local buffers have been initialized, it's too late to change this.
881 * However, if this is only a test call, allow it.
882 */
884 {
885 GUC_check_errdetail("\"temp_buffers\" cannot be changed after any temporary tables have been accessed in the session.");
886 return false;
887 }
888 return true;
889}

References GUC_check_errdetail, newval, NLocBuffer, PGC_S_TEST, and source.

◆ CheckForLocalBufferLeaks()

static void CheckForLocalBufferLeaks ( void  )
static

Definition at line 970 of file localbuf.c.

971{
972#ifdef USE_ASSERT_CHECKING
973 if (LocalRefCount)
974 {
975 int RefCountErrors = 0;
976 int i;
977
978 for (i = 0; i < NLocBuffer; i++)
979 {
980 if (LocalRefCount[i] != 0)
981 {
982 Buffer b = -i - 1;
983 char *s;
984
986 elog(WARNING, "local buffer refcount leak: %s", s);
987 pfree(s);
988
990 }
991 }
993 }
994#endif
995}

References Assert, b, DebugPrintBufferRefcount(), elog, fb(), i, LocalRefCount, NLocBuffer, pfree(), and WARNING.

Referenced by AtEOXact_LocalBuffers(), and AtProcExit_LocalBuffers().

◆ DropRelationAllLocalBuffers()

void DropRelationAllLocalBuffers ( RelFileLocator  rlocator)

Definition at line 702 of file localbuf.c.

703{
704 int i;
705
706 for (i = 0; i < NLocBuffer; i++)
707 {
710
712
713 if ((buf_state & BM_TAG_VALID) &&
714 BufTagMatchesRelFileLocator(&bufHdr->tag, &rlocator))
715 {
717 }
718 }
719}

References BM_TAG_VALID, BufTagMatchesRelFileLocator(), fb(), GetLocalBufferDescriptor(), i, InvalidateLocalBuffer(), NLocBuffer, and pg_atomic_read_u64().

Referenced by DropRelationsAllBuffers().

◆ DropRelationLocalBuffers()

void DropRelationLocalBuffers ( RelFileLocator  rlocator,
ForkNumber forkNum,
int  nforks,
BlockNumber firstDelBlock 
)

Definition at line 665 of file localbuf.c.

667{
668 int i;
669 int j;
670
671 for (i = 0; i < NLocBuffer; i++)
672 {
675
677
678 if (!(buf_state & BM_TAG_VALID) ||
679 !BufTagMatchesRelFileLocator(&bufHdr->tag, &rlocator))
680 continue;
681
682 for (j = 0; j < nforks; j++)
683 {
684 if (BufTagGetForkNum(&bufHdr->tag) == forkNum[j] &&
685 bufHdr->tag.blockNum >= firstDelBlock[j])
686 {
688 break;
689 }
690 }
691 }
692}

References BM_TAG_VALID, BufTagGetForkNum(), BufTagMatchesRelFileLocator(), fb(), GetLocalBufferDescriptor(), i, InvalidateLocalBuffer(), j, NLocBuffer, and pg_atomic_read_u64().

Referenced by DropRelationBuffers().

◆ ExtendBufferedRelLocal()

BlockNumber ExtendBufferedRelLocal ( BufferManagerRelation  bmr,
ForkNumber  fork,
uint32  flags,
uint32  extend_by,
BlockNumber  extend_upto,
Buffer buffers,
uint32 extended_by 
)

Definition at line 346 of file localbuf.c.

353{
356
357 /* Initialize local buffers if first request in this session */
358 if (LocalBufHash == NULL)
360
362
363 for (uint32 i = 0; i < extend_by; i++)
364 {
367
368 buffers[i] = GetLocalVictimBuffer();
369 buf_hdr = GetLocalBufferDescriptor(-buffers[i] - 1);
371
372 /* new buffers are zero-filled */
374 }
375
377
379 {
380 /*
381 * In contrast to shared relations, nothing could change the relation
382 * size concurrently. Thus we shouldn't end up finding that we don't
383 * need to do anything.
384 */
386
388 }
389
390 /* Fail if relation is already at maximum possible length */
394 errmsg("cannot extend relation %s beyond %u blocks",
395 relpath(BMR_GET_SMGR(bmr)->smgr_rlocator, fork).str,
397
398 for (uint32 i = 0; i < extend_by; i++)
399 {
400 int victim_buf_id;
402 BufferTag tag;
404 bool found;
405
406 victim_buf_id = -buffers[i] - 1;
408
409 /* in case we need to pin an existing buffer below */
411
412 InitBufferTag(&tag, &BMR_GET_SMGR(bmr)->smgr_rlocator.locator, fork,
413 first_block + i);
414
416 hash_search(LocalBufHash, &tag, HASH_ENTER, &found);
417 if (found)
418 {
421
423
427
428 /*
429 * Clear the BM_VALID bit, do StartLocalBufferIO() and proceed.
430 */
436
437 /* no need to loop for local buffers */
438 StartLocalBufferIO(existing_hdr, true, false);
439 }
440 else
441 {
443
445
446 victim_buf_hdr->tag = tag;
447
449
451
453
455 }
456 }
457
459
460 /* actually extend relation */
462
465
466 for (uint32 i = 0; i < extend_by; i++)
467 {
468 Buffer buf = buffers[i];
471
473
477 }
478
480
482
483 return first_block;
484}

References Assert, BM_DIRTY, BM_JUST_DIRTIED, BM_TAG_VALID, BM_VALID, BMR_GET_SMGR, buf, BUF_USAGECOUNT_ONE, BufferDescriptorGetBuffer(), CurrentResourceOwner, ereport, errcode(), errmsg(), ERROR, fb(), GetLocalBufferDescriptor(), GetLocalVictimBuffer(), HASH_ENTER, hash_search(), i, InitBufferTag(), InitLocalBuffers(), InvalidBlockNumber, IOCONTEXT_NORMAL, IOOBJECT_TEMP_RELATION, IOOP_EXTEND, LimitAdditionalLocalPins(), BufferUsage::local_blks_written, LocalBufHash, LocalBufHdrGetBlock, MaxBlockNumber, MemSet, pg_atomic_read_u64(), pg_atomic_unlocked_write_u64(), pgBufferUsage, pgstat_count_io_op_time(), pgstat_prepare_io_time(), PinLocalBuffer(), relpath, ResourceOwnerEnlarge(), smgrnblocks(), smgrzeroextend(), StartLocalBufferIO(), str, track_io_timing, and UnpinLocalBuffer().

Referenced by ExtendBufferedRelCommon().

◆ FlushLocalBuffer()

void FlushLocalBuffer ( BufferDesc bufHdr,
SMgrRelation  reln 
)

Definition at line 183 of file localbuf.c.

184{
187
189
190 /*
191 * Try to start an I/O operation. There currently are no reasons for
192 * StartLocalBufferIO to return false, so we raise an error in that case.
193 */
194 if (!StartLocalBufferIO(bufHdr, false, false))
195 elog(ERROR, "failed to start write IO on local buffer");
196
197 /* Find smgr relation for buffer */
198 if (reln == NULL)
201
203
205
206 /* And write... */
209 bufHdr->tag.blockNum,
210 localpage,
211 false);
212
213 /* Temporary table I/O does not use Buffer Access Strategies */
216
217 /* Mark not-dirty */
218 TerminateLocalBufferIO(bufHdr, true, 0, false);
219
221}

References Assert, BufferDescriptorGetBuffer(), BufTagGetForkNum(), BufTagGetRelFileLocator(), elog, ERROR, fb(), IOCONTEXT_NORMAL, IOOBJECT_TEMP_RELATION, IOOP_WRITE, BufferUsage::local_blks_written, LocalBufHdrGetBlock, LocalRefCount, MyProcNumber, PageSetChecksumInplace(), pgBufferUsage, pgstat_count_io_op_time(), pgstat_prepare_io_time(), smgropen(), smgrwrite(), StartLocalBufferIO(), TerminateLocalBufferIO(), and track_io_timing.

Referenced by FlushRelationBuffers(), GetLocalVictimBuffer(), and invalidate_rel_block().

◆ GetAdditionalLocalPinLimit()

uint32 GetAdditionalLocalPinLimit ( void  )

◆ GetLocalBufferStorage()

static Block GetLocalBufferStorage ( void  )
static

Definition at line 901 of file localbuf.c.

902{
903 static char *cur_block = NULL;
904 static int next_buf_in_block = 0;
905 static int num_bufs_in_block = 0;
906 static int total_bufs_allocated = 0;
908
909 char *this_buf;
910
912
914 {
915 /* Need to make a new request to memmgr */
916 int num_bufs;
917
918 /*
919 * We allocate local buffers in a context of their own, so that the
920 * space eaten for them is easily recognizable in MemoryContextStats
921 * output. Create the context on first use.
922 */
926 "LocalBufferContext",
928
929 /* Start with a 16-buffer request; subsequent ones double each time */
930 num_bufs = Max(num_bufs_in_block * 2, 16);
931 /* But not more than what we need for all remaining local bufs */
933 /* And don't overflow MaxAllocSize, either */
935
936 /* Buffers should be I/O aligned. */
940 0);
941
944 }
945
946 /* Allocate next buffer in current memory block */
950
951 /*
952 * Caller's PinLocalBuffer() was too early for Valgrind updates, so do it
953 * here. The block is actually undefined, but we want consistency with
954 * the regular case of not needing to allocate memory. This is
955 * specifically needed when method_io_uring.c fills the block, because
956 * Valgrind doesn't recognize io_uring reads causing undefined memory to
957 * become defined.
958 */
960
961 return (Block) this_buf;
962}

References ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, Assert, fb(), Max, MaxAllocSize, MemoryContextAllocAligned(), Min, NLocBuffer, PG_IO_ALIGN_SIZE, TopMemoryContext, and VALGRIND_MAKE_MEM_DEFINED.

Referenced by GetLocalVictimBuffer().

◆ GetLocalPinLimit()

uint32 GetLocalPinLimit ( void  )

Definition at line 307 of file localbuf.c.

308{
309 /* Every backend has its own temporary buffers, and can pin them all. */
310 return num_temp_buffers;
311}

References num_temp_buffers.

Referenced by read_stream_begin_impl().

◆ GetLocalVictimBuffer()

static Buffer GetLocalVictimBuffer ( void  )
static

Definition at line 224 of file localbuf.c.

225{
226 int victim_bufid;
227 int trycounter;
229
231
232 /*
233 * Need to get a new buffer. We use a clock-sweep algorithm (essentially
234 * the same as what freelist.c does now...)
235 */
237 for (;;)
238 {
240
243
245
246 if (LocalRefCount[victim_bufid] == 0)
247 {
249
251 {
255 }
256 else if (BUF_STATE_GET_REFCOUNT(buf_state) > 0)
257 {
258 /*
259 * This can be reached if the backend initiated AIO for this
260 * buffer and then errored out.
261 */
262 }
263 else
264 {
265 /* Found a usable buffer */
266 PinLocalBuffer(bufHdr, false);
267 break;
268 }
269 }
270 else if (--trycounter == 0)
273 errmsg("no empty local buffer available")));
274 }
275
276 /*
277 * lazy memory allocation: allocate space on first use of a buffer.
278 */
280 {
281 /* Set pointer for use by BufferGetBlock() macro */
283 }
284
285 /*
286 * this buffer is not referenced but it might still be dirty. if that's
287 * the case, write it out before reusing it!
288 */
289 if (pg_atomic_read_u64(&bufHdr->state) & BM_DIRTY)
291
292 /*
293 * Remove the victim buffer from the hashtable and mark as invalid.
294 */
296 {
298
300 }
301
303}

References BM_DIRTY, BM_TAG_VALID, BUF_STATE_GET_REFCOUNT, BUF_STATE_GET_USAGECOUNT, BUF_USAGECOUNT_ONE, BufferDescriptorGetBuffer(), CurrentResourceOwner, ereport, errcode(), errmsg(), ERROR, fb(), FlushLocalBuffer(), GetLocalBufferDescriptor(), GetLocalBufferStorage(), InvalidateLocalBuffer(), IOCONTEXT_NORMAL, IOOBJECT_TEMP_RELATION, IOOP_EVICT, LocalBufHdrGetBlock, LocalRefCount, nextFreeLocalBufId, NLocBuffer, pg_atomic_read_u64(), pg_atomic_unlocked_write_u64(), pgstat_count_io_op(), PinLocalBuffer(), and ResourceOwnerEnlarge().

Referenced by ExtendBufferedRelLocal(), and LocalBufferAlloc().

◆ InitLocalBuffers()

static void InitLocalBuffers ( void  )
static

Definition at line 728 of file localbuf.c.

729{
731 HASHCTL info;
732 int i;
733
734 /*
735 * Parallel workers can't access data in temporary tables, because they
736 * have no visibility into the local buffers of their leader. This is a
737 * convenient, low-cost place to provide a backstop check for that. Note
738 * that we don't wish to prevent a parallel worker from accessing catalog
739 * metadata about a temp table, so checks at higher levels would be
740 * inappropriate.
741 */
742 if (IsParallelWorker())
745 errmsg("cannot access temporary tables during a parallel operation")));
746
747 /* Allocate and zero buffer headers and auxiliary arrays */
750 LocalRefCount = (int32 *) calloc(nbufs, sizeof(int32));
754 errmsg("out of memory")));
755
757
758 /* initialize fields that need to start off nonzero */
759 for (i = 0; i < nbufs; i++)
760 {
762
763 /*
764 * negative to indicate local buffer. This is tricky: shared buffers
765 * start with 0. We have to start with -2. (Note that the routine
766 * BufferDescriptorGetBuffer adds 1 to buf_id so our first buffer id
767 * is -1.)
768 */
769 buf->buf_id = -i - 2;
770
771 pgaio_wref_clear(&buf->io_wref);
772
773 /*
774 * Intentionally do not initialize the buffer's atomic variable
775 * (besides zeroing the underlying memory above). That way we get
776 * errors on platforms without atomics, if somebody (re-)introduces
777 * atomic operations for local buffers.
778 */
779 }
780
781 /* Create the lookup hash table */
782 info.keysize = sizeof(BufferTag);
783 info.entrysize = sizeof(LocalBufferLookupEnt);
784
785 LocalBufHash = hash_create("Local Buffer Lookup Table",
786 nbufs,
787 &info,
789
790 if (!LocalBufHash)
791 elog(ERROR, "could not initialize local buffer hash table");
792
793 /* Initialization done, mark buffers allocated */
795}

References buf, calloc, elog, HASHCTL::entrysize, ereport, errcode(), errmsg(), ERROR, FATAL, fb(), GetLocalBufferDescriptor(), HASH_BLOBS, hash_create(), HASH_ELEM, i, IsParallelWorker, HASHCTL::keysize, LocalBufferBlockPointers, LocalBufferDescriptors, LocalBufHash, LocalRefCount, nextFreeLocalBufId, NLocBuffer, num_temp_buffers, and pgaio_wref_clear().

Referenced by ExtendBufferedRelLocal(), LocalBufferAlloc(), and PrefetchLocalBuffer().

◆ InvalidateLocalBuffer()

void InvalidateLocalBuffer ( BufferDesc bufHdr,
bool  check_unreferenced 
)

Definition at line 605 of file localbuf.c.

606{
608 int bufid = -buffer - 1;
611
612 /*
613 * It's possible that we started IO on this buffer before e.g. aborting
614 * the transaction that created a table. We need to wait for that IO to
615 * complete before removing / reusing the buffer.
616 */
617 if (pgaio_wref_valid(&bufHdr->io_wref))
618 {
619 PgAioWaitRef iow = bufHdr->io_wref;
620
622 Assert(!pgaio_wref_valid(&bufHdr->io_wref));
623 }
624
626
627 /*
628 * We need to test not just LocalRefCount[bufid] but also the BufferDesc
629 * itself, as the latter is used to represent a pin by the AIO subsystem.
630 * This can happen if AIO is initiated and then the query errors out.
631 */
632 if (check_unreferenced &&
634 elog(ERROR, "block %u of %s is still referenced (local %d)",
635 bufHdr->tag.blockNum,
638 BufTagGetForkNum(&bufHdr->tag)).str,
640
641 /* Remove entry from hashtable */
644 if (!hresult) /* shouldn't happen */
645 elog(ERROR, "local buffer hash table corrupted");
646 /* Mark buffer invalid */
647 ClearBufferTag(&bufHdr->tag);
651}

References Assert, BUF_STATE_GET_REFCOUNT, BufferDescriptorGetBuffer(), BufTagGetForkNum(), BufTagGetRelFileLocator(), ClearBufferTag(), elog, ERROR, fb(), HASH_REMOVE, hash_search(), LocalBufHash, LocalRefCount, MyProcNumber, pg_atomic_read_u64(), pg_atomic_unlocked_write_u64(), pgaio_wref_valid(), pgaio_wref_wait(), and relpathbackend.

Referenced by DropRelationAllLocalBuffers(), DropRelationLocalBuffers(), GetLocalVictimBuffer(), invalidate_rel_block(), and modify_rel_block().

◆ LimitAdditionalLocalPins()

void LimitAdditionalLocalPins ( uint32 additional_pins)

Definition at line 323 of file localbuf.c.

324{
326
327 if (*additional_pins <= 1)
328 return;
329
330 /*
331 * In contrast to LimitAdditionalPins() other backends don't play a role
332 * here. We can allow up to NLocBuffer pins in total, but it might not be
333 * initialized yet so read num_temp_buffers.
334 */
336
339}

References fb(), NLocalPinnedBuffers, and num_temp_buffers.

Referenced by ExtendBufferedRelLocal().

◆ LocalBufferAlloc()

BufferDesc * LocalBufferAlloc ( SMgrRelation  smgr,
ForkNumber  forkNum,
BlockNumber  blockNum,
bool foundPtr 
)

Definition at line 119 of file localbuf.c.

121{
122 BufferTag newTag; /* identity of requested block */
126 int bufid;
127 bool found;
128
129 InitBufferTag(&newTag, &smgr->smgr_rlocator.locator, forkNum, blockNum);
130
131 /* Initialize local buffers if first request in this session */
132 if (LocalBufHash == NULL)
134
136
137 /* See if the desired buffer already exists */
140
141 if (hresult)
142 {
143 bufid = hresult->id;
146
148 }
149 else
150 {
152
154 bufid = -victim_buffer - 1;
156
159 if (found) /* shouldn't happen */
160 elog(ERROR, "local buffer hash table corrupted");
161 hresult->id = bufid;
162
163 /*
164 * it's all ours now.
165 */
166 bufHdr->tag = newTag;
167
172
173 *foundPtr = false;
174 }
175
176 return bufHdr;
177}

References Assert, BM_TAG_VALID, BUF_FLAG_MASK, BUF_USAGECOUNT_MASK, BUF_USAGECOUNT_ONE, BufferTagsEqual(), CurrentResourceOwner, elog, ERROR, fb(), GetLocalBufferDescriptor(), GetLocalVictimBuffer(), HASH_ENTER, HASH_FIND, hash_search(), InitBufferTag(), InitLocalBuffers(), LocalBufHash, RelFileLocatorBackend::locator, pg_atomic_read_u64(), pg_atomic_unlocked_write_u64(), PinLocalBuffer(), ResourceOwnerEnlarge(), and SMgrRelationData::smgr_rlocator.

Referenced by PinBufferForBlock().

◆ MarkLocalBufferDirty()

void MarkLocalBufferDirty ( Buffer  buffer)

Definition at line 491 of file localbuf.c.

492{
493 int bufid;
496
497 Assert(BufferIsLocal(buffer));
498
499#ifdef LBDEBUG
500 fprintf(stderr, "LB DIRTY %d\n", buffer);
501#endif
502
503 bufid = -buffer - 1;
504
506
508
510
511 if (!(buf_state & BM_DIRTY))
513
515
517}

References Assert, BM_DIRTY, BufferIsLocal, fb(), fprintf, GetLocalBufferDescriptor(), BufferUsage::local_blks_dirtied, LocalRefCount, pg_atomic_read_u64(), pg_atomic_unlocked_write_u64(), and pgBufferUsage.

Referenced by MarkBufferDirty(), and MarkBufferDirtyHint().

◆ PinLocalBuffer()

bool PinLocalBuffer ( BufferDesc buf_hdr,
bool  adjust_usagecount 
)

◆ PrefetchLocalBuffer()

PrefetchBufferResult PrefetchLocalBuffer ( SMgrRelation  smgr,
ForkNumber  forkNum,
BlockNumber  blockNum 
)

Definition at line 72 of file localbuf.c.

74{
75 PrefetchBufferResult result = {InvalidBuffer, false};
76 BufferTag newTag; /* identity of requested block */
78
79 InitBufferTag(&newTag, &smgr->smgr_rlocator.locator, forkNum, blockNum);
80
81 /* Initialize local buffers if first request in this session */
82 if (LocalBufHash == NULL)
84
85 /* See if the desired buffer already exists */
88
89 if (hresult)
90 {
91 /* Yes, so nothing to do */
92 result.recent_buffer = -hresult->id - 1;
93 }
94 else
95 {
96#ifdef USE_PREFETCH
97 /* Not in buffers, so initiate prefetch */
98 if ((io_direct_flags & IO_DIRECT_DATA) == 0 &&
99 smgrprefetch(smgr, forkNum, blockNum, 1))
100 {
101 result.initiated_io = true;
102 }
103#endif /* USE_PREFETCH */
104 }
105
106 return result;
107}

References fb(), HASH_FIND, hash_search(), InitBufferTag(), PrefetchBufferResult::initiated_io, InitLocalBuffers(), InvalidBuffer, IO_DIRECT_DATA, io_direct_flags, LocalBufHash, RelFileLocatorBackend::locator, PrefetchBufferResult::recent_buffer, SMgrRelationData::smgr_rlocator, and smgrprefetch().

Referenced by PrefetchBuffer().

◆ StartLocalBufferIO()

bool StartLocalBufferIO ( BufferDesc bufHdr,
bool  forInput,
bool  nowait 
)

Definition at line 523 of file localbuf.c.

524{
526
527 /*
528 * With AIO the buffer could have IO in progress, e.g. when there are two
529 * scans of the same relation. Either wait for the other IO or return
530 * false.
531 */
532 if (pgaio_wref_valid(&bufHdr->io_wref))
533 {
534 PgAioWaitRef iow = bufHdr->io_wref;
535
536 if (nowait)
537 return false;
538
540 }
541
542 /* Once we get here, there is definitely no I/O active on this buffer */
543
544 /* Check if someone else already did the I/O */
547 {
548 return false;
549 }
550
551 /* BM_IO_IN_PROGRESS isn't currently used for local buffers */
552
553 /* local buffers don't track IO using resowners */
554
555 return true;
556}

References BM_DIRTY, BM_VALID, fb(), pg_atomic_read_u64(), pgaio_wref_valid(), and pgaio_wref_wait().

Referenced by buffer_call_start_io(), ExtendBufferedRelLocal(), FlushLocalBuffer(), read_rel_block_ll(), ReadBuffersCanStartIOOnce(), and ZeroAndLockBuffer().

◆ TerminateLocalBufferIO()

void TerminateLocalBufferIO ( BufferDesc bufHdr,
bool  clear_dirty,
uint64  set_flag_bits,
bool  release_aio 
)

Definition at line 562 of file localbuf.c.

564{
565 /* Only need to adjust flags */
567
568 /* BM_IO_IN_PROGRESS isn't currently used for local buffers */
569
570 /* Clear earlier errors, if this IO failed, it'll be marked again */
572
573 if (clear_dirty)
575
576 if (release_aio)
577 {
578 /* release pin held by IO subsystem, see also buffer_stage_common() */
581 pgaio_wref_clear(&bufHdr->io_wref);
582 }
583
586
587 /* local buffers don't track IO using resowners */
588
589 /* local buffers don't use the IO CV, as no other process can see buffer */
590
591 /* local buffers don't use BM_PIN_COUNT_WAITER, so no need to wake */
592}

References Assert, BUF_REFCOUNT_ONE, BUF_STATE_GET_REFCOUNT, fb(), pg_atomic_read_u64(), pg_atomic_unlocked_write_u64(), and pgaio_wref_clear().

Referenced by buffer_call_terminate_io(), buffer_readv_complete_one(), FlushLocalBuffer(), and ZeroAndLockBuffer().

◆ UnpinLocalBuffer()

◆ UnpinLocalBufferNoOwner()

Variable Documentation

◆ LocalBufferBlockPointers

Block* LocalBufferBlockPointers = NULL

Definition at line 48 of file localbuf.c.

Referenced by BufferGetBlock(), and InitLocalBuffers().

◆ LocalBufferDescriptors

BufferDesc* LocalBufferDescriptors = NULL

Definition at line 47 of file localbuf.c.

Referenced by GetLocalBufferDescriptor(), and InitLocalBuffers().

◆ LocalBufHash

HTAB* LocalBufHash = NULL
static

◆ LocalRefCount

◆ nextFreeLocalBufId

int nextFreeLocalBufId = 0
static

Definition at line 51 of file localbuf.c.

Referenced by GetLocalVictimBuffer(), and InitLocalBuffers().

◆ NLocalPinnedBuffers

int NLocalPinnedBuffers = 0
static

◆ NLocBuffer