Line data Source code
1 : /*-------------------------------------------------------------------------
2 : *
3 : * bufmgr.c
4 : * buffer manager interface routines
5 : *
6 : * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
7 : * Portions Copyright (c) 1994, Regents of the University of California
8 : *
9 : *
10 : * IDENTIFICATION
11 : * src/backend/storage/buffer/bufmgr.c
12 : *
13 : *-------------------------------------------------------------------------
14 : */
15 : /*
16 : * Principal entry points:
17 : *
18 : * ReadBuffer() -- find or create a buffer holding the requested page,
19 : * and pin it so that no one can destroy it while this process
20 : * is using it.
21 : *
22 : * StartReadBuffer() -- as above, with separate wait step
23 : * StartReadBuffers() -- multiple block version
24 : * WaitReadBuffers() -- second step of above
25 : *
26 : * ReleaseBuffer() -- unpin a buffer
27 : *
28 : * MarkBufferDirty() -- mark a pinned buffer's contents as "dirty".
29 : * The disk write is delayed until buffer replacement or checkpoint.
30 : *
31 : * See also these files:
32 : * freelist.c -- chooses victim for buffer replacement
33 : * buf_table.c -- manages the buffer lookup table
34 : */
35 : #include "postgres.h"
36 :
37 : #include <sys/file.h>
38 : #include <unistd.h>
39 :
40 : #include "access/tableam.h"
41 : #include "access/xloginsert.h"
42 : #include "access/xlogutils.h"
43 : #include "catalog/storage.h"
44 : #include "catalog/storage_xlog.h"
45 : #include "executor/instrument.h"
46 : #include "lib/binaryheap.h"
47 : #include "miscadmin.h"
48 : #include "pg_trace.h"
49 : #include "pgstat.h"
50 : #include "postmaster/bgwriter.h"
51 : #include "storage/buf_internals.h"
52 : #include "storage/bufmgr.h"
53 : #include "storage/fd.h"
54 : #include "storage/ipc.h"
55 : #include "storage/lmgr.h"
56 : #include "storage/proc.h"
57 : #include "storage/read_stream.h"
58 : #include "storage/smgr.h"
59 : #include "storage/standby.h"
60 : #include "utils/memdebug.h"
61 : #include "utils/ps_status.h"
62 : #include "utils/rel.h"
63 : #include "utils/resowner.h"
64 : #include "utils/timestamp.h"
65 :
66 :
67 : /* Note: these two macros only work on shared buffers, not local ones! */
68 : #define BufHdrGetBlock(bufHdr) ((Block) (BufferBlocks + ((Size) (bufHdr)->buf_id) * BLCKSZ))
69 : #define BufferGetLSN(bufHdr) (PageGetLSN(BufHdrGetBlock(bufHdr)))
70 :
71 : /* Note: this macro only works on local buffers, not shared ones! */
72 : #define LocalBufHdrGetBlock(bufHdr) \
73 : LocalBufferBlockPointers[-((bufHdr)->buf_id + 2)]
74 :
75 : /* Bits in SyncOneBuffer's return value */
76 : #define BUF_WRITTEN 0x01
77 : #define BUF_REUSABLE 0x02
78 :
79 : #define RELS_BSEARCH_THRESHOLD 20
80 :
81 : /*
82 : * This is the size (in the number of blocks) above which we scan the
83 : * entire buffer pool to remove the buffers for all the pages of relation
84 : * being dropped. For the relations with size below this threshold, we find
85 : * the buffers by doing lookups in BufMapping table.
86 : */
87 : #define BUF_DROP_FULL_SCAN_THRESHOLD (uint64) (NBuffers / 32)
88 :
89 : typedef struct PrivateRefCountEntry
90 : {
91 : Buffer buffer;
92 : int32 refcount;
93 : } PrivateRefCountEntry;
94 :
95 : /* 64 bytes, about the size of a cache line on common systems */
96 : #define REFCOUNT_ARRAY_ENTRIES 8
97 :
98 : /*
99 : * Status of buffers to checkpoint for a particular tablespace, used
100 : * internally in BufferSync.
101 : */
102 : typedef struct CkptTsStatus
103 : {
104 : /* oid of the tablespace */
105 : Oid tsId;
106 :
107 : /*
108 : * Checkpoint progress for this tablespace. To make progress comparable
109 : * between tablespaces the progress is, for each tablespace, measured as a
110 : * number between 0 and the total number of to-be-checkpointed pages. Each
111 : * page checkpointed in this tablespace increments this space's progress
112 : * by progress_slice.
113 : */
114 : float8 progress;
115 : float8 progress_slice;
116 :
117 : /* number of to-be checkpointed pages in this tablespace */
118 : int num_to_scan;
119 : /* already processed pages in this tablespace */
120 : int num_scanned;
121 :
122 : /* current offset in CkptBufferIds for this tablespace */
123 : int index;
124 : } CkptTsStatus;
125 :
126 : /*
127 : * Type for array used to sort SMgrRelations
128 : *
129 : * FlushRelationsAllBuffers shares the same comparator function with
130 : * DropRelationsAllBuffers. Pointer to this struct and RelFileLocator must be
131 : * compatible.
132 : */
133 : typedef struct SMgrSortArray
134 : {
135 : RelFileLocator rlocator; /* This must be the first member */
136 : SMgrRelation srel;
137 : } SMgrSortArray;
138 :
139 : /* GUC variables */
140 : bool zero_damaged_pages = false;
141 : int bgwriter_lru_maxpages = 100;
142 : double bgwriter_lru_multiplier = 2.0;
143 : bool track_io_timing = false;
144 :
145 : /*
146 : * How many buffers PrefetchBuffer callers should try to stay ahead of their
147 : * ReadBuffer calls by. Zero means "never prefetch". This value is only used
148 : * for buffers not belonging to tablespaces that have their
149 : * effective_io_concurrency parameter set.
150 : */
151 : int effective_io_concurrency = DEFAULT_EFFECTIVE_IO_CONCURRENCY;
152 :
153 : /*
154 : * Like effective_io_concurrency, but used by maintenance code paths that might
155 : * benefit from a higher setting because they work on behalf of many sessions.
156 : * Overridden by the tablespace setting of the same name.
157 : */
158 : int maintenance_io_concurrency = DEFAULT_MAINTENANCE_IO_CONCURRENCY;
159 :
160 : /*
161 : * Limit on how many blocks should be handled in single I/O operations.
162 : * StartReadBuffers() callers should respect it, as should other operations
163 : * that call smgr APIs directly.
164 : */
165 : int io_combine_limit = DEFAULT_IO_COMBINE_LIMIT;
166 :
167 : /*
168 : * GUC variables about triggering kernel writeback for buffers written; OS
169 : * dependent defaults are set via the GUC mechanism.
170 : */
171 : int checkpoint_flush_after = DEFAULT_CHECKPOINT_FLUSH_AFTER;
172 : int bgwriter_flush_after = DEFAULT_BGWRITER_FLUSH_AFTER;
173 : int backend_flush_after = DEFAULT_BACKEND_FLUSH_AFTER;
174 :
175 : /* local state for LockBufferForCleanup */
176 : static BufferDesc *PinCountWaitBuf = NULL;
177 :
178 : /*
179 : * Backend-Private refcount management:
180 : *
181 : * Each buffer also has a private refcount that keeps track of the number of
182 : * times the buffer is pinned in the current process. This is so that the
183 : * shared refcount needs to be modified only once if a buffer is pinned more
184 : * than once by an individual backend. It's also used to check that no buffers
185 : * are still pinned at the end of transactions and when exiting.
186 : *
187 : *
188 : * To avoid - as we used to - requiring an array with NBuffers entries to keep
189 : * track of local buffers, we use a small sequentially searched array
190 : * (PrivateRefCountArray) and an overflow hash table (PrivateRefCountHash) to
191 : * keep track of backend local pins.
192 : *
193 : * Until no more than REFCOUNT_ARRAY_ENTRIES buffers are pinned at once, all
194 : * refcounts are kept track of in the array; after that, new array entries
195 : * displace old ones into the hash table. That way a frequently used entry
196 : * can't get "stuck" in the hashtable while infrequent ones clog the array.
197 : *
198 : * Note that in most scenarios the number of pinned buffers will not exceed
199 : * REFCOUNT_ARRAY_ENTRIES.
200 : *
201 : *
202 : * To enter a buffer into the refcount tracking mechanism first reserve a free
203 : * entry using ReservePrivateRefCountEntry() and then later, if necessary,
204 : * fill it with NewPrivateRefCountEntry(). That split lets us avoid doing
205 : * memory allocations in NewPrivateRefCountEntry() which can be important
206 : * because in some scenarios it's called with a spinlock held...
207 : */
208 : static struct PrivateRefCountEntry PrivateRefCountArray[REFCOUNT_ARRAY_ENTRIES];
209 : static HTAB *PrivateRefCountHash = NULL;
210 : static int32 PrivateRefCountOverflowed = 0;
211 : static uint32 PrivateRefCountClock = 0;
212 : static PrivateRefCountEntry *ReservedRefCountEntry = NULL;
213 :
214 : static void ReservePrivateRefCountEntry(void);
215 : static PrivateRefCountEntry *NewPrivateRefCountEntry(Buffer buffer);
216 : static PrivateRefCountEntry *GetPrivateRefCountEntry(Buffer buffer, bool do_move);
217 : static inline int32 GetPrivateRefCount(Buffer buffer);
218 : static void ForgetPrivateRefCountEntry(PrivateRefCountEntry *ref);
219 :
220 : /* ResourceOwner callbacks to hold in-progress I/Os and buffer pins */
221 : static void ResOwnerReleaseBufferIO(Datum res);
222 : static char *ResOwnerPrintBufferIO(Datum res);
223 : static void ResOwnerReleaseBufferPin(Datum res);
224 : static char *ResOwnerPrintBufferPin(Datum res);
225 :
226 : const ResourceOwnerDesc buffer_io_resowner_desc =
227 : {
228 : .name = "buffer io",
229 : .release_phase = RESOURCE_RELEASE_BEFORE_LOCKS,
230 : .release_priority = RELEASE_PRIO_BUFFER_IOS,
231 : .ReleaseResource = ResOwnerReleaseBufferIO,
232 : .DebugPrint = ResOwnerPrintBufferIO
233 : };
234 :
235 : const ResourceOwnerDesc buffer_pin_resowner_desc =
236 : {
237 : .name = "buffer pin",
238 : .release_phase = RESOURCE_RELEASE_BEFORE_LOCKS,
239 : .release_priority = RELEASE_PRIO_BUFFER_PINS,
240 : .ReleaseResource = ResOwnerReleaseBufferPin,
241 : .DebugPrint = ResOwnerPrintBufferPin
242 : };
243 :
244 : /*
245 : * Ensure that the PrivateRefCountArray has sufficient space to store one more
246 : * entry. This has to be called before using NewPrivateRefCountEntry() to fill
247 : * a new entry - but it's perfectly fine to not use a reserved entry.
248 : */
249 : static void
250 118193550 : ReservePrivateRefCountEntry(void)
251 : {
252 : /* Already reserved (or freed), nothing to do */
253 118193550 : if (ReservedRefCountEntry != NULL)
254 110430286 : return;
255 :
256 : /*
257 : * First search for a free entry the array, that'll be sufficient in the
258 : * majority of cases.
259 : */
260 : {
261 : int i;
262 :
263 19430302 : for (i = 0; i < REFCOUNT_ARRAY_ENTRIES; i++)
264 : {
265 : PrivateRefCountEntry *res;
266 :
267 19177824 : res = &PrivateRefCountArray[i];
268 :
269 19177824 : if (res->buffer == InvalidBuffer)
270 : {
271 7510786 : ReservedRefCountEntry = res;
272 7510786 : return;
273 : }
274 : }
275 : }
276 :
277 : /*
278 : * No luck. All array entries are full. Move one array entry into the hash
279 : * table.
280 : */
281 : {
282 : /*
283 : * Move entry from the current clock position in the array into the
284 : * hashtable. Use that slot.
285 : */
286 : PrivateRefCountEntry *hashent;
287 : bool found;
288 :
289 : /* select victim slot */
290 252478 : ReservedRefCountEntry =
291 252478 : &PrivateRefCountArray[PrivateRefCountClock++ % REFCOUNT_ARRAY_ENTRIES];
292 :
293 : /* Better be used, otherwise we shouldn't get here. */
294 : Assert(ReservedRefCountEntry->buffer != InvalidBuffer);
295 :
296 : /* enter victim array entry into hashtable */
297 252478 : hashent = hash_search(PrivateRefCountHash,
298 252478 : &(ReservedRefCountEntry->buffer),
299 : HASH_ENTER,
300 : &found);
301 : Assert(!found);
302 252478 : hashent->refcount = ReservedRefCountEntry->refcount;
303 :
304 : /* clear the now free array slot */
305 252478 : ReservedRefCountEntry->buffer = InvalidBuffer;
306 252478 : ReservedRefCountEntry->refcount = 0;
307 :
308 252478 : PrivateRefCountOverflowed++;
309 : }
310 : }
311 :
312 : /*
313 : * Fill a previously reserved refcount entry.
314 : */
315 : static PrivateRefCountEntry *
316 107568838 : NewPrivateRefCountEntry(Buffer buffer)
317 : {
318 : PrivateRefCountEntry *res;
319 :
320 : /* only allowed to be called when a reservation has been made */
321 : Assert(ReservedRefCountEntry != NULL);
322 :
323 : /* use up the reserved entry */
324 107568838 : res = ReservedRefCountEntry;
325 107568838 : ReservedRefCountEntry = NULL;
326 :
327 : /* and fill it */
328 107568838 : res->buffer = buffer;
329 107568838 : res->refcount = 0;
330 :
331 107568838 : return res;
332 : }
333 :
334 : /*
335 : * Return the PrivateRefCount entry for the passed buffer.
336 : *
337 : * Returns NULL if a buffer doesn't have a refcount entry. Otherwise, if
338 : * do_move is true, and the entry resides in the hashtable the entry is
339 : * optimized for frequent access by moving it to the array.
340 : */
341 : static PrivateRefCountEntry *
342 264299704 : GetPrivateRefCountEntry(Buffer buffer, bool do_move)
343 : {
344 : PrivateRefCountEntry *res;
345 : int i;
346 :
347 : Assert(BufferIsValid(buffer));
348 : Assert(!BufferIsLocal(buffer));
349 :
350 : /*
351 : * First search for references in the array, that'll be sufficient in the
352 : * majority of cases.
353 : */
354 1252637636 : for (i = 0; i < REFCOUNT_ARRAY_ENTRIES; i++)
355 : {
356 1148864312 : res = &PrivateRefCountArray[i];
357 :
358 1148864312 : if (res->buffer == buffer)
359 160526380 : return res;
360 : }
361 :
362 : /*
363 : * By here we know that the buffer, if already pinned, isn't residing in
364 : * the array.
365 : *
366 : * Only look up the buffer in the hashtable if we've previously overflowed
367 : * into it.
368 : */
369 103773324 : if (PrivateRefCountOverflowed == 0)
370 103061266 : return NULL;
371 :
372 712058 : res = hash_search(PrivateRefCountHash, &buffer, HASH_FIND, NULL);
373 :
374 712058 : if (res == NULL)
375 457306 : return NULL;
376 254752 : else if (!do_move)
377 : {
378 : /* caller doesn't want us to move the hash entry into the array */
379 233154 : return res;
380 : }
381 : else
382 : {
383 : /* move buffer from hashtable into the free array slot */
384 : bool found;
385 : PrivateRefCountEntry *free;
386 :
387 : /* Ensure there's a free array slot */
388 21598 : ReservePrivateRefCountEntry();
389 :
390 : /* Use up the reserved slot */
391 : Assert(ReservedRefCountEntry != NULL);
392 21598 : free = ReservedRefCountEntry;
393 21598 : ReservedRefCountEntry = NULL;
394 : Assert(free->buffer == InvalidBuffer);
395 :
396 : /* and fill it */
397 21598 : free->buffer = buffer;
398 21598 : free->refcount = res->refcount;
399 :
400 : /* delete from hashtable */
401 21598 : hash_search(PrivateRefCountHash, &buffer, HASH_REMOVE, &found);
402 : Assert(found);
403 : Assert(PrivateRefCountOverflowed > 0);
404 21598 : PrivateRefCountOverflowed--;
405 :
406 21598 : return free;
407 : }
408 : }
409 :
410 : /*
411 : * Returns how many times the passed buffer is pinned by this backend.
412 : *
413 : * Only works for shared memory buffers!
414 : */
415 : static inline int32
416 5177482 : GetPrivateRefCount(Buffer buffer)
417 : {
418 : PrivateRefCountEntry *ref;
419 :
420 : Assert(BufferIsValid(buffer));
421 : Assert(!BufferIsLocal(buffer));
422 :
423 : /*
424 : * Not moving the entry - that's ok for the current users, but we might
425 : * want to change this one day.
426 : */
427 5177482 : ref = GetPrivateRefCountEntry(buffer, false);
428 :
429 5177482 : if (ref == NULL)
430 9328 : return 0;
431 5168154 : return ref->refcount;
432 : }
433 :
434 : /*
435 : * Release resources used to track the reference count of a buffer which we no
436 : * longer have pinned and don't want to pin again immediately.
437 : */
438 : static void
439 107568838 : ForgetPrivateRefCountEntry(PrivateRefCountEntry *ref)
440 : {
441 : Assert(ref->refcount == 0);
442 :
443 107568838 : if (ref >= &PrivateRefCountArray[0] &&
444 : ref < &PrivateRefCountArray[REFCOUNT_ARRAY_ENTRIES])
445 : {
446 107337958 : ref->buffer = InvalidBuffer;
447 :
448 : /*
449 : * Mark the just used entry as reserved - in many scenarios that
450 : * allows us to avoid ever having to search the array/hash for free
451 : * entries.
452 : */
453 107337958 : ReservedRefCountEntry = ref;
454 : }
455 : else
456 : {
457 : bool found;
458 230880 : Buffer buffer = ref->buffer;
459 :
460 230880 : hash_search(PrivateRefCountHash, &buffer, HASH_REMOVE, &found);
461 : Assert(found);
462 : Assert(PrivateRefCountOverflowed > 0);
463 230880 : PrivateRefCountOverflowed--;
464 : }
465 107568838 : }
466 :
467 : /*
468 : * BufferIsPinned
469 : * True iff the buffer is pinned (also checks for valid buffer number).
470 : *
471 : * NOTE: what we check here is that *this* backend holds a pin on
472 : * the buffer. We do not care whether some other backend does.
473 : */
474 : #define BufferIsPinned(bufnum) \
475 : ( \
476 : !BufferIsValid(bufnum) ? \
477 : false \
478 : : \
479 : BufferIsLocal(bufnum) ? \
480 : (LocalRefCount[-(bufnum) - 1] > 0) \
481 : : \
482 : (GetPrivateRefCount(bufnum) > 0) \
483 : )
484 :
485 :
486 : static Buffer ReadBuffer_common(Relation rel,
487 : SMgrRelation smgr, char smgr_persistence,
488 : ForkNumber forkNum, BlockNumber blockNum,
489 : ReadBufferMode mode, BufferAccessStrategy strategy);
490 : static BlockNumber ExtendBufferedRelCommon(BufferManagerRelation bmr,
491 : ForkNumber fork,
492 : BufferAccessStrategy strategy,
493 : uint32 flags,
494 : uint32 extend_by,
495 : BlockNumber extend_upto,
496 : Buffer *buffers,
497 : uint32 *extended_by);
498 : static BlockNumber ExtendBufferedRelShared(BufferManagerRelation bmr,
499 : ForkNumber fork,
500 : BufferAccessStrategy strategy,
501 : uint32 flags,
502 : uint32 extend_by,
503 : BlockNumber extend_upto,
504 : Buffer *buffers,
505 : uint32 *extended_by);
506 : static bool PinBuffer(BufferDesc *buf, BufferAccessStrategy strategy);
507 : static void PinBuffer_Locked(BufferDesc *buf);
508 : static void UnpinBuffer(BufferDesc *buf);
509 : static void UnpinBufferNoOwner(BufferDesc *buf);
510 : static void BufferSync(int flags);
511 : static uint32 WaitBufHdrUnlocked(BufferDesc *buf);
512 : static int SyncOneBuffer(int buf_id, bool skip_recently_used,
513 : WritebackContext *wb_context);
514 : static void WaitIO(BufferDesc *buf);
515 : static bool StartBufferIO(BufferDesc *buf, bool forInput, bool nowait);
516 : static void TerminateBufferIO(BufferDesc *buf, bool clear_dirty,
517 : uint32 set_flag_bits, bool forget_owner);
518 : static void AbortBufferIO(Buffer buffer);
519 : static void shared_buffer_write_error_callback(void *arg);
520 : static void local_buffer_write_error_callback(void *arg);
521 : static inline BufferDesc *BufferAlloc(SMgrRelation smgr,
522 : char relpersistence,
523 : ForkNumber forkNum,
524 : BlockNumber blockNum,
525 : BufferAccessStrategy strategy,
526 : bool *foundPtr, IOContext io_context);
527 : static Buffer GetVictimBuffer(BufferAccessStrategy strategy, IOContext io_context);
528 : static void FlushBuffer(BufferDesc *buf, SMgrRelation reln,
529 : IOObject io_object, IOContext io_context);
530 : static void FindAndDropRelationBuffers(RelFileLocator rlocator,
531 : ForkNumber forkNum,
532 : BlockNumber nForkBlock,
533 : BlockNumber firstDelBlock);
534 : static void RelationCopyStorageUsingBuffer(RelFileLocator srclocator,
535 : RelFileLocator dstlocator,
536 : ForkNumber forkNum, bool permanent);
537 : static void AtProcExit_Buffers(int code, Datum arg);
538 : static void CheckForBufferLeaks(void);
539 : static int rlocator_comparator(const void *p1, const void *p2);
540 : static inline int buffertag_comparator(const BufferTag *ba, const BufferTag *bb);
541 : static inline int ckpt_buforder_comparator(const CkptSortItem *a, const CkptSortItem *b);
542 : static int ts_ckpt_progress_comparator(Datum a, Datum b, void *arg);
543 :
544 :
545 : /*
546 : * Implementation of PrefetchBuffer() for shared buffers.
547 : */
548 : PrefetchBufferResult
549 405028 : PrefetchSharedBuffer(SMgrRelation smgr_reln,
550 : ForkNumber forkNum,
551 : BlockNumber blockNum)
552 : {
553 405028 : PrefetchBufferResult result = {InvalidBuffer, false};
554 : BufferTag newTag; /* identity of requested block */
555 : uint32 newHash; /* hash value for newTag */
556 : LWLock *newPartitionLock; /* buffer partition lock for it */
557 : int buf_id;
558 :
559 : Assert(BlockNumberIsValid(blockNum));
560 :
561 : /* create a tag so we can lookup the buffer */
562 405028 : InitBufferTag(&newTag, &smgr_reln->smgr_rlocator.locator,
563 : forkNum, blockNum);
564 :
565 : /* determine its hash code and partition lock ID */
566 405028 : newHash = BufTableHashCode(&newTag);
567 405028 : newPartitionLock = BufMappingPartitionLock(newHash);
568 :
569 : /* see if the block is in the buffer pool already */
570 405028 : LWLockAcquire(newPartitionLock, LW_SHARED);
571 405028 : buf_id = BufTableLookup(&newTag, newHash);
572 405028 : LWLockRelease(newPartitionLock);
573 :
574 : /* If not in buffers, initiate prefetch */
575 405028 : if (buf_id < 0)
576 : {
577 : #ifdef USE_PREFETCH
578 : /*
579 : * Try to initiate an asynchronous read. This returns false in
580 : * recovery if the relation file doesn't exist.
581 : */
582 349492 : if ((io_direct_flags & IO_DIRECT_DATA) == 0 &&
583 174524 : smgrprefetch(smgr_reln, forkNum, blockNum, 1))
584 : {
585 174524 : result.initiated_io = true;
586 : }
587 : #endif /* USE_PREFETCH */
588 : }
589 : else
590 : {
591 : /*
592 : * Report the buffer it was in at that time. The caller may be able
593 : * to avoid a buffer table lookup, but it's not pinned and it must be
594 : * rechecked!
595 : */
596 230060 : result.recent_buffer = buf_id + 1;
597 : }
598 :
599 : /*
600 : * If the block *is* in buffers, we do nothing. This is not really ideal:
601 : * the block might be just about to be evicted, which would be stupid
602 : * since we know we are going to need it soon. But the only easy answer
603 : * is to bump the usage_count, which does not seem like a great solution:
604 : * when the caller does ultimately touch the block, usage_count would get
605 : * bumped again, resulting in too much favoritism for blocks that are
606 : * involved in a prefetch sequence. A real fix would involve some
607 : * additional per-buffer state, and it's not clear that there's enough of
608 : * a problem to justify that.
609 : */
610 :
611 405028 : return result;
612 : }
613 :
614 : /*
615 : * PrefetchBuffer -- initiate asynchronous read of a block of a relation
616 : *
617 : * This is named by analogy to ReadBuffer but doesn't actually allocate a
618 : * buffer. Instead it tries to ensure that a future ReadBuffer for the given
619 : * block will not be delayed by the I/O. Prefetching is optional.
620 : *
621 : * There are three possible outcomes:
622 : *
623 : * 1. If the block is already cached, the result includes a valid buffer that
624 : * could be used by the caller to avoid the need for a later buffer lookup, but
625 : * it's not pinned, so the caller must recheck it.
626 : *
627 : * 2. If the kernel has been asked to initiate I/O, the initiated_io member is
628 : * true. Currently there is no way to know if the data was already cached by
629 : * the kernel and therefore didn't really initiate I/O, and no way to know when
630 : * the I/O completes other than using synchronous ReadBuffer().
631 : *
632 : * 3. Otherwise, the buffer wasn't already cached by PostgreSQL, and
633 : * USE_PREFETCH is not defined (this build doesn't support prefetching due to
634 : * lack of a kernel facility), direct I/O is enabled, or the underlying
635 : * relation file wasn't found and we are in recovery. (If the relation file
636 : * wasn't found and we are not in recovery, an error is raised).
637 : */
638 : PrefetchBufferResult
639 389284 : PrefetchBuffer(Relation reln, ForkNumber forkNum, BlockNumber blockNum)
640 : {
641 : Assert(RelationIsValid(reln));
642 : Assert(BlockNumberIsValid(blockNum));
643 :
644 389284 : if (RelationUsesLocalBuffers(reln))
645 : {
646 : /* see comments in ReadBufferExtended */
647 6224 : if (RELATION_IS_OTHER_TEMP(reln))
648 0 : ereport(ERROR,
649 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
650 : errmsg("cannot access temporary tables of other sessions")));
651 :
652 : /* pass it off to localbuf.c */
653 6224 : return PrefetchLocalBuffer(RelationGetSmgr(reln), forkNum, blockNum);
654 : }
655 : else
656 : {
657 : /* pass it to the shared buffer version */
658 383060 : return PrefetchSharedBuffer(RelationGetSmgr(reln), forkNum, blockNum);
659 : }
660 : }
661 :
662 : /*
663 : * ReadRecentBuffer -- try to pin a block in a recently observed buffer
664 : *
665 : * Compared to ReadBuffer(), this avoids a buffer mapping lookup when it's
666 : * successful. Return true if the buffer is valid and still has the expected
667 : * tag. In that case, the buffer is pinned and the usage count is bumped.
668 : */
669 : bool
670 9328 : ReadRecentBuffer(RelFileLocator rlocator, ForkNumber forkNum, BlockNumber blockNum,
671 : Buffer recent_buffer)
672 : {
673 : BufferDesc *bufHdr;
674 : BufferTag tag;
675 : uint32 buf_state;
676 : bool have_private_ref;
677 :
678 : Assert(BufferIsValid(recent_buffer));
679 :
680 9328 : ResourceOwnerEnlarge(CurrentResourceOwner);
681 9328 : ReservePrivateRefCountEntry();
682 9328 : InitBufferTag(&tag, &rlocator, forkNum, blockNum);
683 :
684 9328 : if (BufferIsLocal(recent_buffer))
685 : {
686 0 : int b = -recent_buffer - 1;
687 :
688 0 : bufHdr = GetLocalBufferDescriptor(b);
689 0 : buf_state = pg_atomic_read_u32(&bufHdr->state);
690 :
691 : /* Is it still valid and holding the right tag? */
692 0 : if ((buf_state & BM_VALID) && BufferTagsEqual(&tag, &bufHdr->tag))
693 : {
694 0 : PinLocalBuffer(bufHdr, true);
695 :
696 0 : pgBufferUsage.local_blks_hit++;
697 :
698 0 : return true;
699 : }
700 : }
701 : else
702 : {
703 9328 : bufHdr = GetBufferDescriptor(recent_buffer - 1);
704 9328 : have_private_ref = GetPrivateRefCount(recent_buffer) > 0;
705 :
706 : /*
707 : * Do we already have this buffer pinned with a private reference? If
708 : * so, it must be valid and it is safe to check the tag without
709 : * locking. If not, we have to lock the header first and then check.
710 : */
711 9328 : if (have_private_ref)
712 0 : buf_state = pg_atomic_read_u32(&bufHdr->state);
713 : else
714 9328 : buf_state = LockBufHdr(bufHdr);
715 :
716 9328 : if ((buf_state & BM_VALID) && BufferTagsEqual(&tag, &bufHdr->tag))
717 : {
718 : /*
719 : * It's now safe to pin the buffer. We can't pin first and ask
720 : * questions later, because it might confuse code paths like
721 : * InvalidateBuffer() if we pinned a random non-matching buffer.
722 : */
723 9272 : if (have_private_ref)
724 0 : PinBuffer(bufHdr, NULL); /* bump pin count */
725 : else
726 9272 : PinBuffer_Locked(bufHdr); /* pin for first time */
727 :
728 9272 : pgBufferUsage.shared_blks_hit++;
729 :
730 9272 : return true;
731 : }
732 :
733 : /* If we locked the header above, now unlock. */
734 56 : if (!have_private_ref)
735 56 : UnlockBufHdr(bufHdr, buf_state);
736 : }
737 :
738 56 : return false;
739 : }
740 :
741 : /*
742 : * ReadBuffer -- a shorthand for ReadBufferExtended, for reading from main
743 : * fork with RBM_NORMAL mode and default strategy.
744 : */
745 : Buffer
746 78808084 : ReadBuffer(Relation reln, BlockNumber blockNum)
747 : {
748 78808084 : return ReadBufferExtended(reln, MAIN_FORKNUM, blockNum, RBM_NORMAL, NULL);
749 : }
750 :
751 : /*
752 : * ReadBufferExtended -- returns a buffer containing the requested
753 : * block of the requested relation. If the blknum
754 : * requested is P_NEW, extend the relation file and
755 : * allocate a new block. (Caller is responsible for
756 : * ensuring that only one backend tries to extend a
757 : * relation at the same time!)
758 : *
759 : * Returns: the buffer number for the buffer containing
760 : * the block read. The returned buffer has been pinned.
761 : * Does not return on error --- elog's instead.
762 : *
763 : * Assume when this function is called, that reln has been opened already.
764 : *
765 : * In RBM_NORMAL mode, the page is read from disk, and the page header is
766 : * validated. An error is thrown if the page header is not valid. (But
767 : * note that an all-zero page is considered "valid"; see
768 : * PageIsVerifiedExtended().)
769 : *
770 : * RBM_ZERO_ON_ERROR is like the normal mode, but if the page header is not
771 : * valid, the page is zeroed instead of throwing an error. This is intended
772 : * for non-critical data, where the caller is prepared to repair errors.
773 : *
774 : * In RBM_ZERO_AND_LOCK mode, if the page isn't in buffer cache already, it's
775 : * filled with zeros instead of reading it from disk. Useful when the caller
776 : * is going to fill the page from scratch, since this saves I/O and avoids
777 : * unnecessary failure if the page-on-disk has corrupt page headers.
778 : * The page is returned locked to ensure that the caller has a chance to
779 : * initialize the page before it's made visible to others.
780 : * Caution: do not use this mode to read a page that is beyond the relation's
781 : * current physical EOF; that is likely to cause problems in md.c when
782 : * the page is modified and written out. P_NEW is OK, though.
783 : *
784 : * RBM_ZERO_AND_CLEANUP_LOCK is the same as RBM_ZERO_AND_LOCK, but acquires
785 : * a cleanup-strength lock on the page.
786 : *
787 : * RBM_NORMAL_NO_LOG mode is treated the same as RBM_NORMAL here.
788 : *
789 : * If strategy is not NULL, a nondefault buffer access strategy is used.
790 : * See buffer/README for details.
791 : */
792 : inline Buffer
793 95129844 : ReadBufferExtended(Relation reln, ForkNumber forkNum, BlockNumber blockNum,
794 : ReadBufferMode mode, BufferAccessStrategy strategy)
795 : {
796 : Buffer buf;
797 :
798 : /*
799 : * Reject attempts to read non-local temporary relations; we would be
800 : * likely to get wrong data since we have no visibility into the owning
801 : * session's local buffers.
802 : */
803 95129844 : if (RELATION_IS_OTHER_TEMP(reln))
804 0 : ereport(ERROR,
805 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
806 : errmsg("cannot access temporary tables of other sessions")));
807 :
808 : /*
809 : * Read the buffer, and update pgstat counters to reflect a cache hit or
810 : * miss.
811 : */
812 95129844 : buf = ReadBuffer_common(reln, RelationGetSmgr(reln), 0,
813 : forkNum, blockNum, mode, strategy);
814 :
815 95129814 : return buf;
816 : }
817 :
818 :
819 : /*
820 : * ReadBufferWithoutRelcache -- like ReadBufferExtended, but doesn't require
821 : * a relcache entry for the relation.
822 : *
823 : * Pass permanent = true for a RELPERSISTENCE_PERMANENT relation, and
824 : * permanent = false for a RELPERSISTENCE_UNLOGGED relation. This function
825 : * cannot be used for temporary relations (and making that work might be
826 : * difficult, unless we only want to read temporary relations for our own
827 : * ProcNumber).
828 : */
829 : Buffer
830 11050732 : ReadBufferWithoutRelcache(RelFileLocator rlocator, ForkNumber forkNum,
831 : BlockNumber blockNum, ReadBufferMode mode,
832 : BufferAccessStrategy strategy, bool permanent)
833 : {
834 11050732 : SMgrRelation smgr = smgropen(rlocator, INVALID_PROC_NUMBER);
835 :
836 11050732 : return ReadBuffer_common(NULL, smgr,
837 : permanent ? RELPERSISTENCE_PERMANENT : RELPERSISTENCE_UNLOGGED,
838 : forkNum, blockNum,
839 : mode, strategy);
840 : }
841 :
842 : /*
843 : * Convenience wrapper around ExtendBufferedRelBy() extending by one block.
844 : */
845 : Buffer
846 89958 : ExtendBufferedRel(BufferManagerRelation bmr,
847 : ForkNumber forkNum,
848 : BufferAccessStrategy strategy,
849 : uint32 flags)
850 : {
851 : Buffer buf;
852 89958 : uint32 extend_by = 1;
853 :
854 89958 : ExtendBufferedRelBy(bmr, forkNum, strategy, flags, extend_by,
855 : &buf, &extend_by);
856 :
857 89958 : return buf;
858 : }
859 :
860 : /*
861 : * Extend relation by multiple blocks.
862 : *
863 : * Tries to extend the relation by extend_by blocks. Depending on the
864 : * availability of resources the relation may end up being extended by a
865 : * smaller number of pages (unless an error is thrown, always by at least one
866 : * page). *extended_by is updated to the number of pages the relation has been
867 : * extended to.
868 : *
869 : * buffers needs to be an array that is at least extend_by long. Upon
870 : * completion, the first extend_by array elements will point to a pinned
871 : * buffer.
872 : *
873 : * If EB_LOCK_FIRST is part of flags, the first returned buffer is
874 : * locked. This is useful for callers that want a buffer that is guaranteed to
875 : * be empty.
876 : */
877 : BlockNumber
878 297876 : ExtendBufferedRelBy(BufferManagerRelation bmr,
879 : ForkNumber fork,
880 : BufferAccessStrategy strategy,
881 : uint32 flags,
882 : uint32 extend_by,
883 : Buffer *buffers,
884 : uint32 *extended_by)
885 : {
886 : Assert((bmr.rel != NULL) != (bmr.smgr != NULL));
887 : Assert(bmr.smgr == NULL || bmr.relpersistence != 0);
888 : Assert(extend_by > 0);
889 :
890 297876 : if (bmr.smgr == NULL)
891 : {
892 297876 : bmr.smgr = RelationGetSmgr(bmr.rel);
893 297876 : bmr.relpersistence = bmr.rel->rd_rel->relpersistence;
894 : }
895 :
896 297876 : return ExtendBufferedRelCommon(bmr, fork, strategy, flags,
897 : extend_by, InvalidBlockNumber,
898 : buffers, extended_by);
899 : }
900 :
901 : /*
902 : * Extend the relation so it is at least extend_to blocks large, return buffer
903 : * (extend_to - 1).
904 : *
905 : * This is useful for callers that want to write a specific page, regardless
906 : * of the current size of the relation (e.g. useful for visibilitymap and for
907 : * crash recovery).
908 : */
909 : Buffer
910 99892 : ExtendBufferedRelTo(BufferManagerRelation bmr,
911 : ForkNumber fork,
912 : BufferAccessStrategy strategy,
913 : uint32 flags,
914 : BlockNumber extend_to,
915 : ReadBufferMode mode)
916 : {
917 : BlockNumber current_size;
918 99892 : uint32 extended_by = 0;
919 99892 : Buffer buffer = InvalidBuffer;
920 : Buffer buffers[64];
921 :
922 : Assert((bmr.rel != NULL) != (bmr.smgr != NULL));
923 : Assert(bmr.smgr == NULL || bmr.relpersistence != 0);
924 : Assert(extend_to != InvalidBlockNumber && extend_to > 0);
925 :
926 99892 : if (bmr.smgr == NULL)
927 : {
928 12880 : bmr.smgr = RelationGetSmgr(bmr.rel);
929 12880 : bmr.relpersistence = bmr.rel->rd_rel->relpersistence;
930 : }
931 :
932 : /*
933 : * If desired, create the file if it doesn't exist. If
934 : * smgr_cached_nblocks[fork] is positive then it must exist, no need for
935 : * an smgrexists call.
936 : */
937 99892 : if ((flags & EB_CREATE_FORK_IF_NEEDED) &&
938 12880 : (bmr.smgr->smgr_cached_nblocks[fork] == 0 ||
939 42 : bmr.smgr->smgr_cached_nblocks[fork] == InvalidBlockNumber) &&
940 12838 : !smgrexists(bmr.smgr, fork))
941 : {
942 12818 : LockRelationForExtension(bmr.rel, ExclusiveLock);
943 :
944 : /* recheck, fork might have been created concurrently */
945 12818 : if (!smgrexists(bmr.smgr, fork))
946 12814 : smgrcreate(bmr.smgr, fork, flags & EB_PERFORMING_RECOVERY);
947 :
948 12818 : UnlockRelationForExtension(bmr.rel, ExclusiveLock);
949 : }
950 :
951 : /*
952 : * If requested, invalidate size cache, so that smgrnblocks asks the
953 : * kernel.
954 : */
955 99892 : if (flags & EB_CLEAR_SIZE_CACHE)
956 12880 : bmr.smgr->smgr_cached_nblocks[fork] = InvalidBlockNumber;
957 :
958 : /*
959 : * Estimate how many pages we'll need to extend by. This avoids acquiring
960 : * unnecessarily many victim buffers.
961 : */
962 99892 : current_size = smgrnblocks(bmr.smgr, fork);
963 :
964 : /*
965 : * Since no-one else can be looking at the page contents yet, there is no
966 : * difference between an exclusive lock and a cleanup-strength lock. Note
967 : * that we pass the original mode to ReadBuffer_common() below, when
968 : * falling back to reading the buffer to a concurrent relation extension.
969 : */
970 99892 : if (mode == RBM_ZERO_AND_LOCK || mode == RBM_ZERO_AND_CLEANUP_LOCK)
971 86312 : flags |= EB_LOCK_TARGET;
972 :
973 203796 : while (current_size < extend_to)
974 : {
975 103904 : uint32 num_pages = lengthof(buffers);
976 : BlockNumber first_block;
977 :
978 103904 : if ((uint64) current_size + num_pages > extend_to)
979 103772 : num_pages = extend_to - current_size;
980 :
981 103904 : first_block = ExtendBufferedRelCommon(bmr, fork, strategy, flags,
982 : num_pages, extend_to,
983 : buffers, &extended_by);
984 :
985 103904 : current_size = first_block + extended_by;
986 : Assert(num_pages != 0 || current_size >= extend_to);
987 :
988 220970 : for (uint32 i = 0; i < extended_by; i++)
989 : {
990 117066 : if (first_block + i != extend_to - 1)
991 17188 : ReleaseBuffer(buffers[i]);
992 : else
993 99878 : buffer = buffers[i];
994 : }
995 : }
996 :
997 : /*
998 : * It's possible that another backend concurrently extended the relation.
999 : * In that case read the buffer.
1000 : *
1001 : * XXX: Should we control this via a flag?
1002 : */
1003 99892 : if (buffer == InvalidBuffer)
1004 : {
1005 : Assert(extended_by == 0);
1006 14 : buffer = ReadBuffer_common(bmr.rel, bmr.smgr, bmr.relpersistence,
1007 : fork, extend_to - 1, mode, strategy);
1008 : }
1009 :
1010 99892 : return buffer;
1011 : }
1012 :
1013 : /*
1014 : * Lock and optionally zero a buffer, as part of the implementation of
1015 : * RBM_ZERO_AND_LOCK or RBM_ZERO_AND_CLEANUP_LOCK. The buffer must be already
1016 : * pinned. If the buffer is not already valid, it is zeroed and made valid.
1017 : */
1018 : static void
1019 561810 : ZeroAndLockBuffer(Buffer buffer, ReadBufferMode mode, bool already_valid)
1020 : {
1021 : BufferDesc *bufHdr;
1022 : bool need_to_zero;
1023 561810 : bool isLocalBuf = BufferIsLocal(buffer);
1024 :
1025 : Assert(mode == RBM_ZERO_AND_LOCK || mode == RBM_ZERO_AND_CLEANUP_LOCK);
1026 :
1027 561810 : if (already_valid)
1028 : {
1029 : /*
1030 : * If the caller already knew the buffer was valid, we can skip some
1031 : * header interaction. The caller just wants to lock the buffer.
1032 : */
1033 73124 : need_to_zero = false;
1034 : }
1035 488686 : else if (isLocalBuf)
1036 : {
1037 : /* Simple case for non-shared buffers. */
1038 0 : bufHdr = GetLocalBufferDescriptor(-buffer - 1);
1039 0 : need_to_zero = (pg_atomic_read_u32(&bufHdr->state) & BM_VALID) == 0;
1040 : }
1041 : else
1042 : {
1043 : /*
1044 : * Take BM_IO_IN_PROGRESS, or discover that BM_VALID has been set
1045 : * concurrently. Even though we aren't doing I/O, that ensures that
1046 : * we don't zero a page that someone else has pinned. An exclusive
1047 : * content lock wouldn't be enough, because readers are allowed to
1048 : * drop the content lock after determining that a tuple is visible
1049 : * (see buffer access rules in README).
1050 : */
1051 488686 : bufHdr = GetBufferDescriptor(buffer - 1);
1052 488686 : need_to_zero = StartBufferIO(bufHdr, true, false);
1053 : }
1054 :
1055 561810 : if (need_to_zero)
1056 : {
1057 488686 : memset(BufferGetPage(buffer), 0, BLCKSZ);
1058 :
1059 : /*
1060 : * Grab the buffer content lock before marking the page as valid, to
1061 : * make sure that no other backend sees the zeroed page before the
1062 : * caller has had a chance to initialize it.
1063 : *
1064 : * Since no-one else can be looking at the page contents yet, there is
1065 : * no difference between an exclusive lock and a cleanup-strength
1066 : * lock. (Note that we cannot use LockBuffer() or
1067 : * LockBufferForCleanup() here, because they assert that the buffer is
1068 : * already valid.)
1069 : */
1070 488686 : if (!isLocalBuf)
1071 488686 : LWLockAcquire(BufferDescriptorGetContentLock(bufHdr), LW_EXCLUSIVE);
1072 :
1073 488686 : if (isLocalBuf)
1074 : {
1075 : /* Only need to adjust flags */
1076 0 : uint32 buf_state = pg_atomic_read_u32(&bufHdr->state);
1077 :
1078 0 : buf_state |= BM_VALID;
1079 0 : pg_atomic_unlocked_write_u32(&bufHdr->state, buf_state);
1080 : }
1081 : else
1082 : {
1083 : /* Set BM_VALID, terminate IO, and wake up any waiters */
1084 488686 : TerminateBufferIO(bufHdr, false, BM_VALID, true);
1085 : }
1086 : }
1087 73124 : else if (!isLocalBuf)
1088 : {
1089 : /*
1090 : * The buffer is valid, so we can't zero it. The caller still expects
1091 : * the page to be locked on return.
1092 : */
1093 73124 : if (mode == RBM_ZERO_AND_LOCK)
1094 73040 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
1095 : else
1096 84 : LockBufferForCleanup(buffer);
1097 : }
1098 561810 : }
1099 :
1100 : /*
1101 : * Pin a buffer for a given block. *foundPtr is set to true if the block was
1102 : * already present, or false if more work is required to either read it in or
1103 : * zero it.
1104 : */
1105 : static pg_attribute_always_inline Buffer
1106 112968824 : PinBufferForBlock(Relation rel,
1107 : SMgrRelation smgr,
1108 : char persistence,
1109 : ForkNumber forkNum,
1110 : BlockNumber blockNum,
1111 : BufferAccessStrategy strategy,
1112 : bool *foundPtr)
1113 : {
1114 : BufferDesc *bufHdr;
1115 : IOContext io_context;
1116 : IOObject io_object;
1117 :
1118 : Assert(blockNum != P_NEW);
1119 :
1120 : /* Persistence should be set before */
1121 : Assert((persistence == RELPERSISTENCE_TEMP ||
1122 : persistence == RELPERSISTENCE_PERMANENT ||
1123 : persistence == RELPERSISTENCE_UNLOGGED));
1124 :
1125 112968824 : if (persistence == RELPERSISTENCE_TEMP)
1126 : {
1127 2124852 : io_context = IOCONTEXT_NORMAL;
1128 2124852 : io_object = IOOBJECT_TEMP_RELATION;
1129 : }
1130 : else
1131 : {
1132 110843972 : io_context = IOContextForStrategy(strategy);
1133 110843972 : io_object = IOOBJECT_RELATION;
1134 : }
1135 :
1136 : TRACE_POSTGRESQL_BUFFER_READ_START(forkNum, blockNum,
1137 : smgr->smgr_rlocator.locator.spcOid,
1138 : smgr->smgr_rlocator.locator.dbOid,
1139 : smgr->smgr_rlocator.locator.relNumber,
1140 : smgr->smgr_rlocator.backend);
1141 :
1142 112968824 : if (persistence == RELPERSISTENCE_TEMP)
1143 : {
1144 2124852 : bufHdr = LocalBufferAlloc(smgr, forkNum, blockNum, foundPtr);
1145 2124852 : if (*foundPtr)
1146 2117154 : pgBufferUsage.local_blks_hit++;
1147 : }
1148 : else
1149 : {
1150 110843972 : bufHdr = BufferAlloc(smgr, persistence, forkNum, blockNum,
1151 : strategy, foundPtr, io_context);
1152 110843972 : if (*foundPtr)
1153 107744074 : pgBufferUsage.shared_blks_hit++;
1154 : }
1155 112968824 : if (rel)
1156 : {
1157 : /*
1158 : * While pgBufferUsage's "read" counter isn't bumped unless we reach
1159 : * WaitReadBuffers() (so, not for hits, and not for buffers that are
1160 : * zeroed instead), the per-relation stats always count them.
1161 : */
1162 101507364 : pgstat_count_buffer_read(rel);
1163 101507364 : if (*foundPtr)
1164 99210820 : pgstat_count_buffer_hit(rel);
1165 : }
1166 112968824 : if (*foundPtr)
1167 : {
1168 109861228 : pgstat_count_io_op(io_object, io_context, IOOP_HIT, 1, 0);
1169 109861228 : if (VacuumCostActive)
1170 3271584 : VacuumCostBalance += VacuumCostPageHit;
1171 :
1172 : TRACE_POSTGRESQL_BUFFER_READ_DONE(forkNum, blockNum,
1173 : smgr->smgr_rlocator.locator.spcOid,
1174 : smgr->smgr_rlocator.locator.dbOid,
1175 : smgr->smgr_rlocator.locator.relNumber,
1176 : smgr->smgr_rlocator.backend,
1177 : true);
1178 : }
1179 :
1180 112968824 : return BufferDescriptorGetBuffer(bufHdr);
1181 : }
1182 :
1183 : /*
1184 : * ReadBuffer_common -- common logic for all ReadBuffer variants
1185 : *
1186 : * smgr is required, rel is optional unless using P_NEW.
1187 : */
1188 : static pg_attribute_always_inline Buffer
1189 106180590 : ReadBuffer_common(Relation rel, SMgrRelation smgr, char smgr_persistence,
1190 : ForkNumber forkNum,
1191 : BlockNumber blockNum, ReadBufferMode mode,
1192 : BufferAccessStrategy strategy)
1193 : {
1194 : ReadBuffersOperation operation;
1195 : Buffer buffer;
1196 : int flags;
1197 : char persistence;
1198 :
1199 : /*
1200 : * Backward compatibility path, most code should use ExtendBufferedRel()
1201 : * instead, as acquiring the extension lock inside ExtendBufferedRel()
1202 : * scales a lot better.
1203 : */
1204 106180590 : if (unlikely(blockNum == P_NEW))
1205 : {
1206 520 : uint32 flags = EB_SKIP_EXTENSION_LOCK;
1207 :
1208 : /*
1209 : * Since no-one else can be looking at the page contents yet, there is
1210 : * no difference between an exclusive lock and a cleanup-strength
1211 : * lock.
1212 : */
1213 520 : if (mode == RBM_ZERO_AND_LOCK || mode == RBM_ZERO_AND_CLEANUP_LOCK)
1214 0 : flags |= EB_LOCK_FIRST;
1215 :
1216 520 : return ExtendBufferedRel(BMR_REL(rel), forkNum, strategy, flags);
1217 : }
1218 :
1219 106180070 : if (rel)
1220 95129338 : persistence = rel->rd_rel->relpersistence;
1221 : else
1222 11050732 : persistence = smgr_persistence;
1223 :
1224 106180070 : if (unlikely(mode == RBM_ZERO_AND_CLEANUP_LOCK ||
1225 : mode == RBM_ZERO_AND_LOCK))
1226 : {
1227 : bool found;
1228 :
1229 561810 : buffer = PinBufferForBlock(rel, smgr, persistence,
1230 : forkNum, blockNum, strategy, &found);
1231 561810 : ZeroAndLockBuffer(buffer, mode, found);
1232 561810 : return buffer;
1233 : }
1234 :
1235 105618260 : if (mode == RBM_ZERO_ON_ERROR)
1236 2374196 : flags = READ_BUFFERS_ZERO_ON_ERROR;
1237 : else
1238 103244064 : flags = 0;
1239 105618260 : operation.smgr = smgr;
1240 105618260 : operation.rel = rel;
1241 105618260 : operation.persistence = persistence;
1242 105618260 : operation.forknum = forkNum;
1243 105618260 : operation.strategy = strategy;
1244 105618260 : if (StartReadBuffer(&operation,
1245 : &buffer,
1246 : blockNum,
1247 : flags))
1248 1383340 : WaitReadBuffers(&operation);
1249 :
1250 105618230 : return buffer;
1251 : }
1252 :
1253 : static pg_attribute_always_inline bool
1254 112141820 : StartReadBuffersImpl(ReadBuffersOperation *operation,
1255 : Buffer *buffers,
1256 : BlockNumber blockNum,
1257 : int *nblocks,
1258 : int flags)
1259 : {
1260 112141820 : int actual_nblocks = *nblocks;
1261 112141820 : int io_buffers_len = 0;
1262 112141820 : int maxcombine = 0;
1263 :
1264 : Assert(*nblocks > 0);
1265 : Assert(*nblocks <= MAX_IO_COMBINE_LIMIT);
1266 :
1267 114760730 : for (int i = 0; i < actual_nblocks; ++i)
1268 : {
1269 : bool found;
1270 :
1271 224814028 : buffers[i] = PinBufferForBlock(operation->rel,
1272 112407014 : operation->smgr,
1273 112407014 : operation->persistence,
1274 : operation->forknum,
1275 : blockNum + i,
1276 : operation->strategy,
1277 : &found);
1278 :
1279 112407014 : if (found)
1280 : {
1281 : /*
1282 : * Terminate the read as soon as we get a hit. It could be a
1283 : * single buffer hit, or it could be a hit that follows a readable
1284 : * range. We don't want to create more than one readable range,
1285 : * so we stop here.
1286 : */
1287 109788104 : actual_nblocks = i + 1;
1288 109788104 : break;
1289 : }
1290 : else
1291 : {
1292 : /* Extend the readable range to cover this block. */
1293 2618910 : io_buffers_len++;
1294 :
1295 : /*
1296 : * Check how many blocks we can cover with the same IO. The smgr
1297 : * implementation might e.g. be limited due to a segment boundary.
1298 : */
1299 2618910 : if (i == 0 && actual_nblocks > 1)
1300 : {
1301 55352 : maxcombine = smgrmaxcombine(operation->smgr,
1302 : operation->forknum,
1303 : blockNum);
1304 55352 : if (unlikely(maxcombine < actual_nblocks))
1305 : {
1306 0 : elog(DEBUG2, "limiting nblocks at %u from %u to %u",
1307 : blockNum, actual_nblocks, maxcombine);
1308 0 : actual_nblocks = maxcombine;
1309 : }
1310 : }
1311 : }
1312 : }
1313 112141820 : *nblocks = actual_nblocks;
1314 :
1315 112141820 : if (likely(io_buffers_len == 0))
1316 109786020 : return false;
1317 :
1318 : /* Populate information needed for I/O. */
1319 2355800 : operation->buffers = buffers;
1320 2355800 : operation->blocknum = blockNum;
1321 2355800 : operation->flags = flags;
1322 2355800 : operation->nblocks = actual_nblocks;
1323 2355800 : operation->io_buffers_len = io_buffers_len;
1324 :
1325 2355800 : if (flags & READ_BUFFERS_ISSUE_ADVICE)
1326 : {
1327 : /*
1328 : * In theory we should only do this if PinBufferForBlock() had to
1329 : * allocate new buffers above. That way, if two calls to
1330 : * StartReadBuffers() were made for the same blocks before
1331 : * WaitReadBuffers(), only the first would issue the advice. That'd be
1332 : * a better simulation of true asynchronous I/O, which would only
1333 : * start the I/O once, but isn't done here for simplicity.
1334 : */
1335 1648 : smgrprefetch(operation->smgr,
1336 : operation->forknum,
1337 : blockNum,
1338 1648 : operation->io_buffers_len);
1339 : }
1340 :
1341 : /* Indicate that WaitReadBuffers() should be called. */
1342 2355800 : return true;
1343 : }
1344 :
1345 : /*
1346 : * Begin reading a range of blocks beginning at blockNum and extending for
1347 : * *nblocks. On return, up to *nblocks pinned buffers holding those blocks
1348 : * are written into the buffers array, and *nblocks is updated to contain the
1349 : * actual number, which may be fewer than requested. Caller sets some of the
1350 : * members of operation; see struct definition.
1351 : *
1352 : * If false is returned, no I/O is necessary. If true is returned, one I/O
1353 : * has been started, and WaitReadBuffers() must be called with the same
1354 : * operation object before the buffers are accessed. Along with the operation
1355 : * object, the caller-supplied array of buffers must remain valid until
1356 : * WaitReadBuffers() is called.
1357 : *
1358 : * Currently the I/O is only started with optional operating system advice if
1359 : * requested by the caller with READ_BUFFERS_ISSUE_ADVICE, and the real I/O
1360 : * happens synchronously in WaitReadBuffers(). In future work, true I/O could
1361 : * be initiated here.
1362 : */
1363 : bool
1364 3045706 : StartReadBuffers(ReadBuffersOperation *operation,
1365 : Buffer *buffers,
1366 : BlockNumber blockNum,
1367 : int *nblocks,
1368 : int flags)
1369 : {
1370 3045706 : return StartReadBuffersImpl(operation, buffers, blockNum, nblocks, flags);
1371 : }
1372 :
1373 : /*
1374 : * Single block version of the StartReadBuffers(). This might save a few
1375 : * instructions when called from another translation unit, because it is
1376 : * specialized for nblocks == 1.
1377 : */
1378 : bool
1379 109096114 : StartReadBuffer(ReadBuffersOperation *operation,
1380 : Buffer *buffer,
1381 : BlockNumber blocknum,
1382 : int flags)
1383 : {
1384 109096114 : int nblocks = 1;
1385 : bool result;
1386 :
1387 109096114 : result = StartReadBuffersImpl(operation, buffer, blocknum, &nblocks, flags);
1388 : Assert(nblocks == 1); /* single block can't be short */
1389 :
1390 109096114 : return result;
1391 : }
1392 :
1393 : static inline bool
1394 2618908 : WaitReadBuffersCanStartIO(Buffer buffer, bool nowait)
1395 : {
1396 2618908 : if (BufferIsLocal(buffer))
1397 : {
1398 7698 : BufferDesc *bufHdr = GetLocalBufferDescriptor(-buffer - 1);
1399 :
1400 7698 : return (pg_atomic_read_u32(&bufHdr->state) & BM_VALID) == 0;
1401 : }
1402 : else
1403 2611210 : return StartBufferIO(GetBufferDescriptor(buffer - 1), true, nowait);
1404 : }
1405 :
1406 : void
1407 2355798 : WaitReadBuffers(ReadBuffersOperation *operation)
1408 : {
1409 : Buffer *buffers;
1410 : int nblocks;
1411 : BlockNumber blocknum;
1412 : ForkNumber forknum;
1413 : IOContext io_context;
1414 : IOObject io_object;
1415 : char persistence;
1416 :
1417 : /*
1418 : * Currently operations are only allowed to include a read of some range,
1419 : * with an optional extra buffer that is already pinned at the end. So
1420 : * nblocks can be at most one more than io_buffers_len.
1421 : */
1422 : Assert((operation->nblocks == operation->io_buffers_len) ||
1423 : (operation->nblocks == operation->io_buffers_len + 1));
1424 :
1425 : /* Find the range of the physical read we need to perform. */
1426 2355798 : nblocks = operation->io_buffers_len;
1427 2355798 : if (nblocks == 0)
1428 0 : return; /* nothing to do */
1429 :
1430 2355798 : buffers = &operation->buffers[0];
1431 2355798 : blocknum = operation->blocknum;
1432 2355798 : forknum = operation->forknum;
1433 2355798 : persistence = operation->persistence;
1434 :
1435 2355798 : if (persistence == RELPERSISTENCE_TEMP)
1436 : {
1437 1674 : io_context = IOCONTEXT_NORMAL;
1438 1674 : io_object = IOOBJECT_TEMP_RELATION;
1439 : }
1440 : else
1441 : {
1442 2354124 : io_context = IOContextForStrategy(operation->strategy);
1443 2354124 : io_object = IOOBJECT_RELATION;
1444 : }
1445 :
1446 : /*
1447 : * We count all these blocks as read by this backend. This is traditional
1448 : * behavior, but might turn out to be not true if we find that someone
1449 : * else has beaten us and completed the read of some of these blocks. In
1450 : * that case the system globally double-counts, but we traditionally don't
1451 : * count this as a "hit", and we don't have a separate counter for "miss,
1452 : * but another backend completed the read".
1453 : */
1454 2355798 : if (persistence == RELPERSISTENCE_TEMP)
1455 1674 : pgBufferUsage.local_blks_read += nblocks;
1456 : else
1457 2354124 : pgBufferUsage.shared_blks_read += nblocks;
1458 :
1459 4711566 : for (int i = 0; i < nblocks; ++i)
1460 : {
1461 : int io_buffers_len;
1462 : Buffer io_buffers[MAX_IO_COMBINE_LIMIT];
1463 : void *io_pages[MAX_IO_COMBINE_LIMIT];
1464 : instr_time io_start;
1465 : BlockNumber io_first_block;
1466 :
1467 : /*
1468 : * Skip this block if someone else has already completed it. If an
1469 : * I/O is already in progress in another backend, this will wait for
1470 : * the outcome: either done, or something went wrong and we will
1471 : * retry.
1472 : */
1473 2355798 : if (!WaitReadBuffersCanStartIO(buffers[i], false))
1474 : {
1475 : /*
1476 : * Report this as a 'hit' for this backend, even though it must
1477 : * have started out as a miss in PinBufferForBlock().
1478 : */
1479 : TRACE_POSTGRESQL_BUFFER_READ_DONE(forknum, blocknum + i,
1480 : operation->smgr->smgr_rlocator.locator.spcOid,
1481 : operation->smgr->smgr_rlocator.locator.dbOid,
1482 : operation->smgr->smgr_rlocator.locator.relNumber,
1483 : operation->smgr->smgr_rlocator.backend,
1484 : true);
1485 3218 : continue;
1486 : }
1487 :
1488 : /* We found a buffer that we need to read in. */
1489 2352580 : io_buffers[0] = buffers[i];
1490 2352580 : io_pages[0] = BufferGetBlock(buffers[i]);
1491 2352580 : io_first_block = blocknum + i;
1492 2352580 : io_buffers_len = 1;
1493 :
1494 : /*
1495 : * How many neighboring-on-disk blocks can we scatter-read into other
1496 : * buffers at the same time? In this case we don't wait if we see an
1497 : * I/O already in progress. We already hold BM_IO_IN_PROGRESS for the
1498 : * head block, so we should get on with that I/O as soon as possible.
1499 : * We'll come back to this block again, above.
1500 : */
1501 2878800 : while ((i + 1) < nblocks &&
1502 263110 : WaitReadBuffersCanStartIO(buffers[i + 1], true))
1503 : {
1504 : /* Must be consecutive block numbers. */
1505 : Assert(BufferGetBlockNumber(buffers[i + 1]) ==
1506 : BufferGetBlockNumber(buffers[i]) + 1);
1507 :
1508 263110 : io_buffers[io_buffers_len] = buffers[++i];
1509 263110 : io_pages[io_buffers_len++] = BufferGetBlock(buffers[i]);
1510 : }
1511 :
1512 2352580 : io_start = pgstat_prepare_io_time(track_io_timing);
1513 2352580 : smgrreadv(operation->smgr, forknum, io_first_block, io_pages, io_buffers_len);
1514 2352550 : pgstat_count_io_op_time(io_object, io_context, IOOP_READ, io_start,
1515 2352550 : 1, io_buffers_len * BLCKSZ);
1516 :
1517 : /* Verify each block we read, and terminate the I/O. */
1518 4968210 : for (int j = 0; j < io_buffers_len; ++j)
1519 : {
1520 : BufferDesc *bufHdr;
1521 : Block bufBlock;
1522 :
1523 2615660 : if (persistence == RELPERSISTENCE_TEMP)
1524 : {
1525 7698 : bufHdr = GetLocalBufferDescriptor(-io_buffers[j] - 1);
1526 7698 : bufBlock = LocalBufHdrGetBlock(bufHdr);
1527 : }
1528 : else
1529 : {
1530 2607962 : bufHdr = GetBufferDescriptor(io_buffers[j] - 1);
1531 2607962 : bufBlock = BufHdrGetBlock(bufHdr);
1532 : }
1533 :
1534 : /* check for garbage data */
1535 2615660 : if (!PageIsVerifiedExtended((Page) bufBlock, io_first_block + j,
1536 : PIV_LOG_WARNING | PIV_REPORT_STAT))
1537 : {
1538 0 : if ((operation->flags & READ_BUFFERS_ZERO_ON_ERROR) || zero_damaged_pages)
1539 : {
1540 0 : ereport(WARNING,
1541 : (errcode(ERRCODE_DATA_CORRUPTED),
1542 : errmsg("invalid page in block %u of relation %s; zeroing out page",
1543 : io_first_block + j,
1544 : relpath(operation->smgr->smgr_rlocator, forknum))));
1545 0 : memset(bufBlock, 0, BLCKSZ);
1546 : }
1547 : else
1548 0 : ereport(ERROR,
1549 : (errcode(ERRCODE_DATA_CORRUPTED),
1550 : errmsg("invalid page in block %u of relation %s",
1551 : io_first_block + j,
1552 : relpath(operation->smgr->smgr_rlocator, forknum))));
1553 : }
1554 :
1555 : /* Terminate I/O and set BM_VALID. */
1556 2615660 : if (persistence == RELPERSISTENCE_TEMP)
1557 : {
1558 7698 : uint32 buf_state = pg_atomic_read_u32(&bufHdr->state);
1559 :
1560 7698 : buf_state |= BM_VALID;
1561 7698 : pg_atomic_unlocked_write_u32(&bufHdr->state, buf_state);
1562 : }
1563 : else
1564 : {
1565 : /* Set BM_VALID, terminate IO, and wake up any waiters */
1566 2607962 : TerminateBufferIO(bufHdr, false, BM_VALID, true);
1567 : }
1568 :
1569 : /* Report I/Os as completing individually. */
1570 : TRACE_POSTGRESQL_BUFFER_READ_DONE(forknum, io_first_block + j,
1571 : operation->smgr->smgr_rlocator.locator.spcOid,
1572 : operation->smgr->smgr_rlocator.locator.dbOid,
1573 : operation->smgr->smgr_rlocator.locator.relNumber,
1574 : operation->smgr->smgr_rlocator.backend,
1575 : false);
1576 : }
1577 :
1578 2352550 : if (VacuumCostActive)
1579 8604 : VacuumCostBalance += VacuumCostPageMiss * io_buffers_len;
1580 : }
1581 : }
1582 :
1583 : /*
1584 : * BufferAlloc -- subroutine for PinBufferForBlock. Handles lookup of a shared
1585 : * buffer. If no buffer exists already, selects a replacement victim and
1586 : * evicts the old page, but does NOT read in new page.
1587 : *
1588 : * "strategy" can be a buffer replacement strategy object, or NULL for
1589 : * the default strategy. The selected buffer's usage_count is advanced when
1590 : * using the default strategy, but otherwise possibly not (see PinBuffer).
1591 : *
1592 : * The returned buffer is pinned and is already marked as holding the
1593 : * desired page. If it already did have the desired page, *foundPtr is
1594 : * set true. Otherwise, *foundPtr is set false.
1595 : *
1596 : * io_context is passed as an output parameter to avoid calling
1597 : * IOContextForStrategy() when there is a shared buffers hit and no IO
1598 : * statistics need be captured.
1599 : *
1600 : * No locks are held either at entry or exit.
1601 : */
1602 : static pg_attribute_always_inline BufferDesc *
1603 110843972 : BufferAlloc(SMgrRelation smgr, char relpersistence, ForkNumber forkNum,
1604 : BlockNumber blockNum,
1605 : BufferAccessStrategy strategy,
1606 : bool *foundPtr, IOContext io_context)
1607 : {
1608 : BufferTag newTag; /* identity of requested block */
1609 : uint32 newHash; /* hash value for newTag */
1610 : LWLock *newPartitionLock; /* buffer partition lock for it */
1611 : int existing_buf_id;
1612 : Buffer victim_buffer;
1613 : BufferDesc *victim_buf_hdr;
1614 : uint32 victim_buf_state;
1615 :
1616 : /* Make sure we will have room to remember the buffer pin */
1617 110843972 : ResourceOwnerEnlarge(CurrentResourceOwner);
1618 110843972 : ReservePrivateRefCountEntry();
1619 :
1620 : /* create a tag so we can lookup the buffer */
1621 110843972 : InitBufferTag(&newTag, &smgr->smgr_rlocator.locator, forkNum, blockNum);
1622 :
1623 : /* determine its hash code and partition lock ID */
1624 110843972 : newHash = BufTableHashCode(&newTag);
1625 110843972 : newPartitionLock = BufMappingPartitionLock(newHash);
1626 :
1627 : /* see if the block is in the buffer pool already */
1628 110843972 : LWLockAcquire(newPartitionLock, LW_SHARED);
1629 110843972 : existing_buf_id = BufTableLookup(&newTag, newHash);
1630 110843972 : if (existing_buf_id >= 0)
1631 : {
1632 : BufferDesc *buf;
1633 : bool valid;
1634 :
1635 : /*
1636 : * Found it. Now, pin the buffer so no one can steal it from the
1637 : * buffer pool, and check to see if the correct data has been loaded
1638 : * into the buffer.
1639 : */
1640 107746814 : buf = GetBufferDescriptor(existing_buf_id);
1641 :
1642 107746814 : valid = PinBuffer(buf, strategy);
1643 :
1644 : /* Can release the mapping lock as soon as we've pinned it */
1645 107746814 : LWLockRelease(newPartitionLock);
1646 :
1647 107746814 : *foundPtr = true;
1648 :
1649 107746814 : if (!valid)
1650 : {
1651 : /*
1652 : * We can only get here if (a) someone else is still reading in
1653 : * the page, (b) a previous read attempt failed, or (c) someone
1654 : * called StartReadBuffers() but not yet WaitReadBuffers().
1655 : */
1656 2986 : *foundPtr = false;
1657 : }
1658 :
1659 107746814 : return buf;
1660 : }
1661 :
1662 : /*
1663 : * Didn't find it in the buffer pool. We'll have to initialize a new
1664 : * buffer. Remember to unlock the mapping lock while doing the work.
1665 : */
1666 3097158 : LWLockRelease(newPartitionLock);
1667 :
1668 : /*
1669 : * Acquire a victim buffer. Somebody else might try to do the same, we
1670 : * don't hold any conflicting locks. If so we'll have to undo our work
1671 : * later.
1672 : */
1673 3097158 : victim_buffer = GetVictimBuffer(strategy, io_context);
1674 3097158 : victim_buf_hdr = GetBufferDescriptor(victim_buffer - 1);
1675 :
1676 : /*
1677 : * Try to make a hashtable entry for the buffer under its new tag. If
1678 : * somebody else inserted another buffer for the tag, we'll release the
1679 : * victim buffer we acquired and use the already inserted one.
1680 : */
1681 3097158 : LWLockAcquire(newPartitionLock, LW_EXCLUSIVE);
1682 3097158 : existing_buf_id = BufTableInsert(&newTag, newHash, victim_buf_hdr->buf_id);
1683 3097158 : if (existing_buf_id >= 0)
1684 : {
1685 : BufferDesc *existing_buf_hdr;
1686 : bool valid;
1687 :
1688 : /*
1689 : * Got a collision. Someone has already done what we were about to do.
1690 : * We'll just handle this as if it were found in the buffer pool in
1691 : * the first place. First, give up the buffer we were planning to
1692 : * use.
1693 : *
1694 : * We could do this after releasing the partition lock, but then we'd
1695 : * have to call ResourceOwnerEnlarge() & ReservePrivateRefCountEntry()
1696 : * before acquiring the lock, for the rare case of such a collision.
1697 : */
1698 502 : UnpinBuffer(victim_buf_hdr);
1699 :
1700 : /*
1701 : * The victim buffer we acquired previously is clean and unused, let
1702 : * it be found again quickly
1703 : */
1704 502 : StrategyFreeBuffer(victim_buf_hdr);
1705 :
1706 : /* remaining code should match code at top of routine */
1707 :
1708 502 : existing_buf_hdr = GetBufferDescriptor(existing_buf_id);
1709 :
1710 502 : valid = PinBuffer(existing_buf_hdr, strategy);
1711 :
1712 : /* Can release the mapping lock as soon as we've pinned it */
1713 502 : LWLockRelease(newPartitionLock);
1714 :
1715 502 : *foundPtr = true;
1716 :
1717 502 : if (!valid)
1718 : {
1719 : /*
1720 : * We can only get here if (a) someone else is still reading in
1721 : * the page, (b) a previous read attempt failed, or (c) someone
1722 : * called StartReadBuffers() but not yet WaitReadBuffers().
1723 : */
1724 256 : *foundPtr = false;
1725 : }
1726 :
1727 502 : return existing_buf_hdr;
1728 : }
1729 :
1730 : /*
1731 : * Need to lock the buffer header too in order to change its tag.
1732 : */
1733 3096656 : victim_buf_state = LockBufHdr(victim_buf_hdr);
1734 :
1735 : /* some sanity checks while we hold the buffer header lock */
1736 : Assert(BUF_STATE_GET_REFCOUNT(victim_buf_state) == 1);
1737 : Assert(!(victim_buf_state & (BM_TAG_VALID | BM_VALID | BM_DIRTY | BM_IO_IN_PROGRESS)));
1738 :
1739 3096656 : victim_buf_hdr->tag = newTag;
1740 :
1741 : /*
1742 : * Make sure BM_PERMANENT is set for buffers that must be written at every
1743 : * checkpoint. Unlogged buffers only need to be written at shutdown
1744 : * checkpoints, except for their "init" forks, which need to be treated
1745 : * just like permanent relations.
1746 : */
1747 3096656 : victim_buf_state |= BM_TAG_VALID | BUF_USAGECOUNT_ONE;
1748 3096656 : if (relpersistence == RELPERSISTENCE_PERMANENT || forkNum == INIT_FORKNUM)
1749 3095976 : victim_buf_state |= BM_PERMANENT;
1750 :
1751 3096656 : UnlockBufHdr(victim_buf_hdr, victim_buf_state);
1752 :
1753 3096656 : LWLockRelease(newPartitionLock);
1754 :
1755 : /*
1756 : * Buffer contents are currently invalid.
1757 : */
1758 3096656 : *foundPtr = false;
1759 :
1760 3096656 : return victim_buf_hdr;
1761 : }
1762 :
1763 : /*
1764 : * InvalidateBuffer -- mark a shared buffer invalid and return it to the
1765 : * freelist.
1766 : *
1767 : * The buffer header spinlock must be held at entry. We drop it before
1768 : * returning. (This is sane because the caller must have locked the
1769 : * buffer in order to be sure it should be dropped.)
1770 : *
1771 : * This is used only in contexts such as dropping a relation. We assume
1772 : * that no other backend could possibly be interested in using the page,
1773 : * so the only reason the buffer might be pinned is if someone else is
1774 : * trying to write it out. We have to let them finish before we can
1775 : * reclaim the buffer.
1776 : *
1777 : * The buffer could get reclaimed by someone else while we are waiting
1778 : * to acquire the necessary locks; if so, don't mess it up.
1779 : */
1780 : static void
1781 200238 : InvalidateBuffer(BufferDesc *buf)
1782 : {
1783 : BufferTag oldTag;
1784 : uint32 oldHash; /* hash value for oldTag */
1785 : LWLock *oldPartitionLock; /* buffer partition lock for it */
1786 : uint32 oldFlags;
1787 : uint32 buf_state;
1788 :
1789 : /* Save the original buffer tag before dropping the spinlock */
1790 200238 : oldTag = buf->tag;
1791 :
1792 200238 : buf_state = pg_atomic_read_u32(&buf->state);
1793 : Assert(buf_state & BM_LOCKED);
1794 200238 : UnlockBufHdr(buf, buf_state);
1795 :
1796 : /*
1797 : * Need to compute the old tag's hashcode and partition lock ID. XXX is it
1798 : * worth storing the hashcode in BufferDesc so we need not recompute it
1799 : * here? Probably not.
1800 : */
1801 200238 : oldHash = BufTableHashCode(&oldTag);
1802 200238 : oldPartitionLock = BufMappingPartitionLock(oldHash);
1803 :
1804 200238 : retry:
1805 :
1806 : /*
1807 : * Acquire exclusive mapping lock in preparation for changing the buffer's
1808 : * association.
1809 : */
1810 200238 : LWLockAcquire(oldPartitionLock, LW_EXCLUSIVE);
1811 :
1812 : /* Re-lock the buffer header */
1813 200238 : buf_state = LockBufHdr(buf);
1814 :
1815 : /* If it's changed while we were waiting for lock, do nothing */
1816 200238 : if (!BufferTagsEqual(&buf->tag, &oldTag))
1817 : {
1818 0 : UnlockBufHdr(buf, buf_state);
1819 0 : LWLockRelease(oldPartitionLock);
1820 0 : return;
1821 : }
1822 :
1823 : /*
1824 : * We assume the only reason for it to be pinned is that someone else is
1825 : * flushing the page out. Wait for them to finish. (This could be an
1826 : * infinite loop if the refcount is messed up... it would be nice to time
1827 : * out after awhile, but there seems no way to be sure how many loops may
1828 : * be needed. Note that if the other guy has pinned the buffer but not
1829 : * yet done StartBufferIO, WaitIO will fall through and we'll effectively
1830 : * be busy-looping here.)
1831 : */
1832 200238 : if (BUF_STATE_GET_REFCOUNT(buf_state) != 0)
1833 : {
1834 0 : UnlockBufHdr(buf, buf_state);
1835 0 : LWLockRelease(oldPartitionLock);
1836 : /* safety check: should definitely not be our *own* pin */
1837 0 : if (GetPrivateRefCount(BufferDescriptorGetBuffer(buf)) > 0)
1838 0 : elog(ERROR, "buffer is pinned in InvalidateBuffer");
1839 0 : WaitIO(buf);
1840 0 : goto retry;
1841 : }
1842 :
1843 : /*
1844 : * Clear out the buffer's tag and flags. We must do this to ensure that
1845 : * linear scans of the buffer array don't think the buffer is valid.
1846 : */
1847 200238 : oldFlags = buf_state & BUF_FLAG_MASK;
1848 200238 : ClearBufferTag(&buf->tag);
1849 200238 : buf_state &= ~(BUF_FLAG_MASK | BUF_USAGECOUNT_MASK);
1850 200238 : UnlockBufHdr(buf, buf_state);
1851 :
1852 : /*
1853 : * Remove the buffer from the lookup hashtable, if it was in there.
1854 : */
1855 200238 : if (oldFlags & BM_TAG_VALID)
1856 200238 : BufTableDelete(&oldTag, oldHash);
1857 :
1858 : /*
1859 : * Done with mapping lock.
1860 : */
1861 200238 : LWLockRelease(oldPartitionLock);
1862 :
1863 : /*
1864 : * Insert the buffer at the head of the list of free buffers.
1865 : */
1866 200238 : StrategyFreeBuffer(buf);
1867 : }
1868 :
1869 : /*
1870 : * Helper routine for GetVictimBuffer()
1871 : *
1872 : * Needs to be called on a buffer with a valid tag, pinned, but without the
1873 : * buffer header spinlock held.
1874 : *
1875 : * Returns true if the buffer can be reused, in which case the buffer is only
1876 : * pinned by this backend and marked as invalid, false otherwise.
1877 : */
1878 : static bool
1879 2292452 : InvalidateVictimBuffer(BufferDesc *buf_hdr)
1880 : {
1881 : uint32 buf_state;
1882 : uint32 hash;
1883 : LWLock *partition_lock;
1884 : BufferTag tag;
1885 :
1886 : Assert(GetPrivateRefCount(BufferDescriptorGetBuffer(buf_hdr)) == 1);
1887 :
1888 : /* have buffer pinned, so it's safe to read tag without lock */
1889 2292452 : tag = buf_hdr->tag;
1890 :
1891 2292452 : hash = BufTableHashCode(&tag);
1892 2292452 : partition_lock = BufMappingPartitionLock(hash);
1893 :
1894 2292452 : LWLockAcquire(partition_lock, LW_EXCLUSIVE);
1895 :
1896 : /* lock the buffer header */
1897 2292452 : buf_state = LockBufHdr(buf_hdr);
1898 :
1899 : /*
1900 : * We have the buffer pinned nobody else should have been able to unset
1901 : * this concurrently.
1902 : */
1903 : Assert(buf_state & BM_TAG_VALID);
1904 : Assert(BUF_STATE_GET_REFCOUNT(buf_state) > 0);
1905 : Assert(BufferTagsEqual(&buf_hdr->tag, &tag));
1906 :
1907 : /*
1908 : * If somebody else pinned the buffer since, or even worse, dirtied it,
1909 : * give up on this buffer: It's clearly in use.
1910 : */
1911 2292452 : if (BUF_STATE_GET_REFCOUNT(buf_state) != 1 || (buf_state & BM_DIRTY))
1912 : {
1913 : Assert(BUF_STATE_GET_REFCOUNT(buf_state) > 0);
1914 :
1915 624 : UnlockBufHdr(buf_hdr, buf_state);
1916 624 : LWLockRelease(partition_lock);
1917 :
1918 624 : return false;
1919 : }
1920 :
1921 : /*
1922 : * Clear out the buffer's tag and flags and usagecount. This is not
1923 : * strictly required, as BM_TAG_VALID/BM_VALID needs to be checked before
1924 : * doing anything with the buffer. But currently it's beneficial, as the
1925 : * cheaper pre-check for several linear scans of shared buffers use the
1926 : * tag (see e.g. FlushDatabaseBuffers()).
1927 : */
1928 2291828 : ClearBufferTag(&buf_hdr->tag);
1929 2291828 : buf_state &= ~(BUF_FLAG_MASK | BUF_USAGECOUNT_MASK);
1930 2291828 : UnlockBufHdr(buf_hdr, buf_state);
1931 :
1932 : Assert(BUF_STATE_GET_REFCOUNT(buf_state) > 0);
1933 :
1934 : /* finally delete buffer from the buffer mapping table */
1935 2291828 : BufTableDelete(&tag, hash);
1936 :
1937 2291828 : LWLockRelease(partition_lock);
1938 :
1939 : Assert(!(buf_state & (BM_DIRTY | BM_VALID | BM_TAG_VALID)));
1940 : Assert(BUF_STATE_GET_REFCOUNT(buf_state) > 0);
1941 : Assert(BUF_STATE_GET_REFCOUNT(pg_atomic_read_u32(&buf_hdr->state)) > 0);
1942 :
1943 2291828 : return true;
1944 : }
1945 :
1946 : static Buffer
1947 3521814 : GetVictimBuffer(BufferAccessStrategy strategy, IOContext io_context)
1948 : {
1949 : BufferDesc *buf_hdr;
1950 : Buffer buf;
1951 : uint32 buf_state;
1952 : bool from_ring;
1953 :
1954 : /*
1955 : * Ensure, while the spinlock's not yet held, that there's a free refcount
1956 : * entry, and a resource owner slot for the pin.
1957 : */
1958 3521814 : ReservePrivateRefCountEntry();
1959 3521814 : ResourceOwnerEnlarge(CurrentResourceOwner);
1960 :
1961 : /* we return here if a prospective victim buffer gets used concurrently */
1962 3534030 : again:
1963 :
1964 : /*
1965 : * Select a victim buffer. The buffer is returned with its header
1966 : * spinlock still held!
1967 : */
1968 3534030 : buf_hdr = StrategyGetBuffer(strategy, &buf_state, &from_ring);
1969 3534030 : buf = BufferDescriptorGetBuffer(buf_hdr);
1970 :
1971 : Assert(BUF_STATE_GET_REFCOUNT(buf_state) == 0);
1972 :
1973 : /* Pin the buffer and then release the buffer spinlock */
1974 3534030 : PinBuffer_Locked(buf_hdr);
1975 :
1976 : /*
1977 : * We shouldn't have any other pins for this buffer.
1978 : */
1979 3534030 : CheckBufferIsPinnedOnce(buf);
1980 :
1981 : /*
1982 : * If the buffer was dirty, try to write it out. There is a race
1983 : * condition here, in that someone might dirty it after we released the
1984 : * buffer header lock above, or even while we are writing it out (since
1985 : * our share-lock won't prevent hint-bit updates). We will recheck the
1986 : * dirty bit after re-locking the buffer header.
1987 : */
1988 3534030 : if (buf_state & BM_DIRTY)
1989 : {
1990 : LWLock *content_lock;
1991 :
1992 : Assert(buf_state & BM_TAG_VALID);
1993 : Assert(buf_state & BM_VALID);
1994 :
1995 : /*
1996 : * We need a share-lock on the buffer contents to write it out (else
1997 : * we might write invalid data, eg because someone else is compacting
1998 : * the page contents while we write). We must use a conditional lock
1999 : * acquisition here to avoid deadlock. Even though the buffer was not
2000 : * pinned (and therefore surely not locked) when StrategyGetBuffer
2001 : * returned it, someone else could have pinned and exclusive-locked it
2002 : * by the time we get here. If we try to get the lock unconditionally,
2003 : * we'd block waiting for them; if they later block waiting for us,
2004 : * deadlock ensues. (This has been observed to happen when two
2005 : * backends are both trying to split btree index pages, and the second
2006 : * one just happens to be trying to split the page the first one got
2007 : * from StrategyGetBuffer.)
2008 : */
2009 470444 : content_lock = BufferDescriptorGetContentLock(buf_hdr);
2010 470444 : if (!LWLockConditionalAcquire(content_lock, LW_SHARED))
2011 : {
2012 : /*
2013 : * Someone else has locked the buffer, so give it up and loop back
2014 : * to get another one.
2015 : */
2016 0 : UnpinBuffer(buf_hdr);
2017 0 : goto again;
2018 : }
2019 :
2020 : /*
2021 : * If using a nondefault strategy, and writing the buffer would
2022 : * require a WAL flush, let the strategy decide whether to go ahead
2023 : * and write/reuse the buffer or to choose another victim. We need a
2024 : * lock to inspect the page LSN, so this can't be done inside
2025 : * StrategyGetBuffer.
2026 : */
2027 470444 : if (strategy != NULL)
2028 : {
2029 : XLogRecPtr lsn;
2030 :
2031 : /* Read the LSN while holding buffer header lock */
2032 132342 : buf_state = LockBufHdr(buf_hdr);
2033 132342 : lsn = BufferGetLSN(buf_hdr);
2034 132342 : UnlockBufHdr(buf_hdr, buf_state);
2035 :
2036 132342 : if (XLogNeedsFlush(lsn)
2037 15992 : && StrategyRejectBuffer(strategy, buf_hdr, from_ring))
2038 : {
2039 11592 : LWLockRelease(content_lock);
2040 11592 : UnpinBuffer(buf_hdr);
2041 11592 : goto again;
2042 : }
2043 : }
2044 :
2045 : /* OK, do the I/O */
2046 458852 : FlushBuffer(buf_hdr, NULL, IOOBJECT_RELATION, io_context);
2047 458852 : LWLockRelease(content_lock);
2048 :
2049 458852 : ScheduleBufferTagForWriteback(&BackendWritebackContext, io_context,
2050 : &buf_hdr->tag);
2051 : }
2052 :
2053 :
2054 3522438 : if (buf_state & BM_VALID)
2055 : {
2056 : /*
2057 : * When a BufferAccessStrategy is in use, blocks evicted from shared
2058 : * buffers are counted as IOOP_EVICT in the corresponding context
2059 : * (e.g. IOCONTEXT_BULKWRITE). Shared buffers are evicted by a
2060 : * strategy in two cases: 1) while initially claiming buffers for the
2061 : * strategy ring 2) to replace an existing strategy ring buffer
2062 : * because it is pinned or in use and cannot be reused.
2063 : *
2064 : * Blocks evicted from buffers already in the strategy ring are
2065 : * counted as IOOP_REUSE in the corresponding strategy context.
2066 : *
2067 : * At this point, we can accurately count evictions and reuses,
2068 : * because we have successfully claimed the valid buffer. Previously,
2069 : * we may have been forced to release the buffer due to concurrent
2070 : * pinners or erroring out.
2071 : */
2072 2292450 : pgstat_count_io_op(IOOBJECT_RELATION, io_context,
2073 2292450 : from_ring ? IOOP_REUSE : IOOP_EVICT, 1, 0);
2074 : }
2075 :
2076 : /*
2077 : * If the buffer has an entry in the buffer mapping table, delete it. This
2078 : * can fail because another backend could have pinned or dirtied the
2079 : * buffer.
2080 : */
2081 3522438 : if ((buf_state & BM_TAG_VALID) && !InvalidateVictimBuffer(buf_hdr))
2082 : {
2083 624 : UnpinBuffer(buf_hdr);
2084 624 : goto again;
2085 : }
2086 :
2087 : /* a final set of sanity checks */
2088 : #ifdef USE_ASSERT_CHECKING
2089 : buf_state = pg_atomic_read_u32(&buf_hdr->state);
2090 :
2091 : Assert(BUF_STATE_GET_REFCOUNT(buf_state) == 1);
2092 : Assert(!(buf_state & (BM_TAG_VALID | BM_VALID | BM_DIRTY)));
2093 :
2094 : CheckBufferIsPinnedOnce(buf);
2095 : #endif
2096 :
2097 3521814 : return buf;
2098 : }
2099 :
2100 : /*
2101 : * Limit the number of pins a batch operation may additionally acquire, to
2102 : * avoid running out of pinnable buffers.
2103 : *
2104 : * One additional pin is always allowed, as otherwise the operation likely
2105 : * cannot be performed at all.
2106 : *
2107 : * The number of allowed pins for a backend is computed based on
2108 : * shared_buffers and the maximum number of connections possible. That's very
2109 : * pessimistic, but outside of toy-sized shared_buffers it should allow
2110 : * sufficient pins.
2111 : */
2112 : void
2113 1288916 : LimitAdditionalPins(uint32 *additional_pins)
2114 : {
2115 : uint32 max_backends;
2116 : int max_proportional_pins;
2117 :
2118 1288916 : if (*additional_pins <= 1)
2119 365308 : return;
2120 :
2121 923608 : max_backends = MaxBackends + NUM_AUXILIARY_PROCS;
2122 923608 : max_proportional_pins = NBuffers / max_backends;
2123 :
2124 : /*
2125 : * Subtract the approximate number of buffers already pinned by this
2126 : * backend. We get the number of "overflowed" pins for free, but don't
2127 : * know the number of pins in PrivateRefCountArray. The cost of
2128 : * calculating that exactly doesn't seem worth it, so just assume the max.
2129 : */
2130 923608 : max_proportional_pins -= PrivateRefCountOverflowed + REFCOUNT_ARRAY_ENTRIES;
2131 :
2132 923608 : if (max_proportional_pins <= 0)
2133 173328 : max_proportional_pins = 1;
2134 :
2135 923608 : if (*additional_pins > max_proportional_pins)
2136 173992 : *additional_pins = max_proportional_pins;
2137 : }
2138 :
2139 : /*
2140 : * Logic shared between ExtendBufferedRelBy(), ExtendBufferedRelTo(). Just to
2141 : * avoid duplicating the tracing and relpersistence related logic.
2142 : */
2143 : static BlockNumber
2144 401780 : ExtendBufferedRelCommon(BufferManagerRelation bmr,
2145 : ForkNumber fork,
2146 : BufferAccessStrategy strategy,
2147 : uint32 flags,
2148 : uint32 extend_by,
2149 : BlockNumber extend_upto,
2150 : Buffer *buffers,
2151 : uint32 *extended_by)
2152 : {
2153 : BlockNumber first_block;
2154 :
2155 : TRACE_POSTGRESQL_BUFFER_EXTEND_START(fork,
2156 : bmr.smgr->smgr_rlocator.locator.spcOid,
2157 : bmr.smgr->smgr_rlocator.locator.dbOid,
2158 : bmr.smgr->smgr_rlocator.locator.relNumber,
2159 : bmr.smgr->smgr_rlocator.backend,
2160 : extend_by);
2161 :
2162 401780 : if (bmr.relpersistence == RELPERSISTENCE_TEMP)
2163 17680 : first_block = ExtendBufferedRelLocal(bmr, fork, flags,
2164 : extend_by, extend_upto,
2165 : buffers, &extend_by);
2166 : else
2167 384100 : first_block = ExtendBufferedRelShared(bmr, fork, strategy, flags,
2168 : extend_by, extend_upto,
2169 : buffers, &extend_by);
2170 401780 : *extended_by = extend_by;
2171 :
2172 : TRACE_POSTGRESQL_BUFFER_EXTEND_DONE(fork,
2173 : bmr.smgr->smgr_rlocator.locator.spcOid,
2174 : bmr.smgr->smgr_rlocator.locator.dbOid,
2175 : bmr.smgr->smgr_rlocator.locator.relNumber,
2176 : bmr.smgr->smgr_rlocator.backend,
2177 : *extended_by,
2178 : first_block);
2179 :
2180 401780 : return first_block;
2181 : }
2182 :
2183 : /*
2184 : * Implementation of ExtendBufferedRelBy() and ExtendBufferedRelTo() for
2185 : * shared buffers.
2186 : */
2187 : static BlockNumber
2188 384100 : ExtendBufferedRelShared(BufferManagerRelation bmr,
2189 : ForkNumber fork,
2190 : BufferAccessStrategy strategy,
2191 : uint32 flags,
2192 : uint32 extend_by,
2193 : BlockNumber extend_upto,
2194 : Buffer *buffers,
2195 : uint32 *extended_by)
2196 : {
2197 : BlockNumber first_block;
2198 384100 : IOContext io_context = IOContextForStrategy(strategy);
2199 : instr_time io_start;
2200 :
2201 384100 : LimitAdditionalPins(&extend_by);
2202 :
2203 : /*
2204 : * Acquire victim buffers for extension without holding extension lock.
2205 : * Writing out victim buffers is the most expensive part of extending the
2206 : * relation, particularly when doing so requires WAL flushes. Zeroing out
2207 : * the buffers is also quite expensive, so do that before holding the
2208 : * extension lock as well.
2209 : *
2210 : * These pages are pinned by us and not valid. While we hold the pin they
2211 : * can't be acquired as victim buffers by another backend.
2212 : */
2213 808756 : for (uint32 i = 0; i < extend_by; i++)
2214 : {
2215 : Block buf_block;
2216 :
2217 424656 : buffers[i] = GetVictimBuffer(strategy, io_context);
2218 424656 : buf_block = BufHdrGetBlock(GetBufferDescriptor(buffers[i] - 1));
2219 :
2220 : /* new buffers are zero-filled */
2221 424656 : MemSet(buf_block, 0, BLCKSZ);
2222 : }
2223 :
2224 : /*
2225 : * Lock relation against concurrent extensions, unless requested not to.
2226 : *
2227 : * We use the same extension lock for all forks. That's unnecessarily
2228 : * restrictive, but currently extensions for forks don't happen often
2229 : * enough to make it worth locking more granularly.
2230 : *
2231 : * Note that another backend might have extended the relation by the time
2232 : * we get the lock.
2233 : */
2234 384100 : if (!(flags & EB_SKIP_EXTENSION_LOCK))
2235 282884 : LockRelationForExtension(bmr.rel, ExclusiveLock);
2236 :
2237 : /*
2238 : * If requested, invalidate size cache, so that smgrnblocks asks the
2239 : * kernel.
2240 : */
2241 384100 : if (flags & EB_CLEAR_SIZE_CACHE)
2242 14162 : bmr.smgr->smgr_cached_nblocks[fork] = InvalidBlockNumber;
2243 :
2244 384100 : first_block = smgrnblocks(bmr.smgr, fork);
2245 :
2246 : /*
2247 : * Now that we have the accurate relation size, check if the caller wants
2248 : * us to extend to only up to a specific size. If there were concurrent
2249 : * extensions, we might have acquired too many buffers and need to release
2250 : * them.
2251 : */
2252 384100 : if (extend_upto != InvalidBlockNumber)
2253 : {
2254 103622 : uint32 orig_extend_by = extend_by;
2255 :
2256 103622 : if (first_block > extend_upto)
2257 0 : extend_by = 0;
2258 103622 : else if ((uint64) first_block + extend_by > extend_upto)
2259 14 : extend_by = extend_upto - first_block;
2260 :
2261 103648 : for (uint32 i = extend_by; i < orig_extend_by; i++)
2262 : {
2263 26 : BufferDesc *buf_hdr = GetBufferDescriptor(buffers[i] - 1);
2264 :
2265 : /*
2266 : * The victim buffer we acquired previously is clean and unused,
2267 : * let it be found again quickly
2268 : */
2269 26 : StrategyFreeBuffer(buf_hdr);
2270 26 : UnpinBuffer(buf_hdr);
2271 : }
2272 :
2273 103622 : if (extend_by == 0)
2274 : {
2275 14 : if (!(flags & EB_SKIP_EXTENSION_LOCK))
2276 14 : UnlockRelationForExtension(bmr.rel, ExclusiveLock);
2277 14 : *extended_by = extend_by;
2278 14 : return first_block;
2279 : }
2280 : }
2281 :
2282 : /* Fail if relation is already at maximum possible length */
2283 384086 : if ((uint64) first_block + extend_by >= MaxBlockNumber)
2284 0 : ereport(ERROR,
2285 : (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
2286 : errmsg("cannot extend relation %s beyond %u blocks",
2287 : relpath(bmr.smgr->smgr_rlocator, fork),
2288 : MaxBlockNumber)));
2289 :
2290 : /*
2291 : * Insert buffers into buffer table, mark as IO_IN_PROGRESS.
2292 : *
2293 : * This needs to happen before we extend the relation, because as soon as
2294 : * we do, other backends can start to read in those pages.
2295 : */
2296 808716 : for (uint32 i = 0; i < extend_by; i++)
2297 : {
2298 424630 : Buffer victim_buf = buffers[i];
2299 424630 : BufferDesc *victim_buf_hdr = GetBufferDescriptor(victim_buf - 1);
2300 : BufferTag tag;
2301 : uint32 hash;
2302 : LWLock *partition_lock;
2303 : int existing_id;
2304 :
2305 : /* in case we need to pin an existing buffer below */
2306 424630 : ResourceOwnerEnlarge(CurrentResourceOwner);
2307 424630 : ReservePrivateRefCountEntry();
2308 :
2309 424630 : InitBufferTag(&tag, &bmr.smgr->smgr_rlocator.locator, fork, first_block + i);
2310 424630 : hash = BufTableHashCode(&tag);
2311 424630 : partition_lock = BufMappingPartitionLock(hash);
2312 :
2313 424630 : LWLockAcquire(partition_lock, LW_EXCLUSIVE);
2314 :
2315 424630 : existing_id = BufTableInsert(&tag, hash, victim_buf_hdr->buf_id);
2316 :
2317 : /*
2318 : * We get here only in the corner case where we are trying to extend
2319 : * the relation but we found a pre-existing buffer. This can happen
2320 : * because a prior attempt at extending the relation failed, and
2321 : * because mdread doesn't complain about reads beyond EOF (when
2322 : * zero_damaged_pages is ON) and so a previous attempt to read a block
2323 : * beyond EOF could have left a "valid" zero-filled buffer.
2324 : * Unfortunately, we have also seen this case occurring because of
2325 : * buggy Linux kernels that sometimes return an lseek(SEEK_END) result
2326 : * that doesn't account for a recent write. In that situation, the
2327 : * pre-existing buffer would contain valid data that we don't want to
2328 : * overwrite. Since the legitimate cases should always have left a
2329 : * zero-filled buffer, complain if not PageIsNew.
2330 : */
2331 424630 : if (existing_id >= 0)
2332 : {
2333 0 : BufferDesc *existing_hdr = GetBufferDescriptor(existing_id);
2334 : Block buf_block;
2335 : bool valid;
2336 :
2337 : /*
2338 : * Pin the existing buffer before releasing the partition lock,
2339 : * preventing it from being evicted.
2340 : */
2341 0 : valid = PinBuffer(existing_hdr, strategy);
2342 :
2343 0 : LWLockRelease(partition_lock);
2344 :
2345 : /*
2346 : * The victim buffer we acquired previously is clean and unused,
2347 : * let it be found again quickly
2348 : */
2349 0 : StrategyFreeBuffer(victim_buf_hdr);
2350 0 : UnpinBuffer(victim_buf_hdr);
2351 :
2352 0 : buffers[i] = BufferDescriptorGetBuffer(existing_hdr);
2353 0 : buf_block = BufHdrGetBlock(existing_hdr);
2354 :
2355 0 : if (valid && !PageIsNew((Page) buf_block))
2356 0 : ereport(ERROR,
2357 : (errmsg("unexpected data beyond EOF in block %u of relation %s",
2358 : existing_hdr->tag.blockNum, relpath(bmr.smgr->smgr_rlocator, fork)),
2359 : errhint("This has been seen to occur with buggy kernels; consider updating your system.")));
2360 :
2361 : /*
2362 : * We *must* do smgr[zero]extend before succeeding, else the page
2363 : * will not be reserved by the kernel, and the next P_NEW call
2364 : * will decide to return the same page. Clear the BM_VALID bit,
2365 : * do StartBufferIO() and proceed.
2366 : *
2367 : * Loop to handle the very small possibility that someone re-sets
2368 : * BM_VALID between our clearing it and StartBufferIO inspecting
2369 : * it.
2370 : */
2371 : do
2372 : {
2373 0 : uint32 buf_state = LockBufHdr(existing_hdr);
2374 :
2375 0 : buf_state &= ~BM_VALID;
2376 0 : UnlockBufHdr(existing_hdr, buf_state);
2377 0 : } while (!StartBufferIO(existing_hdr, true, false));
2378 : }
2379 : else
2380 : {
2381 : uint32 buf_state;
2382 :
2383 424630 : buf_state = LockBufHdr(victim_buf_hdr);
2384 :
2385 : /* some sanity checks while we hold the buffer header lock */
2386 : Assert(!(buf_state & (BM_VALID | BM_TAG_VALID | BM_DIRTY | BM_JUST_DIRTIED)));
2387 : Assert(BUF_STATE_GET_REFCOUNT(buf_state) == 1);
2388 :
2389 424630 : victim_buf_hdr->tag = tag;
2390 :
2391 424630 : buf_state |= BM_TAG_VALID | BUF_USAGECOUNT_ONE;
2392 424630 : if (bmr.relpersistence == RELPERSISTENCE_PERMANENT || fork == INIT_FORKNUM)
2393 416460 : buf_state |= BM_PERMANENT;
2394 :
2395 424630 : UnlockBufHdr(victim_buf_hdr, buf_state);
2396 :
2397 424630 : LWLockRelease(partition_lock);
2398 :
2399 : /* XXX: could combine the locked operations in it with the above */
2400 424630 : StartBufferIO(victim_buf_hdr, true, false);
2401 : }
2402 : }
2403 :
2404 384086 : io_start = pgstat_prepare_io_time(track_io_timing);
2405 :
2406 : /*
2407 : * Note: if smgrzeroextend fails, we will end up with buffers that are
2408 : * allocated but not marked BM_VALID. The next relation extension will
2409 : * still select the same block number (because the relation didn't get any
2410 : * longer on disk) and so future attempts to extend the relation will find
2411 : * the same buffers (if they have not been recycled) but come right back
2412 : * here to try smgrzeroextend again.
2413 : *
2414 : * We don't need to set checksum for all-zero pages.
2415 : */
2416 384086 : smgrzeroextend(bmr.smgr, fork, first_block, extend_by, false);
2417 :
2418 : /*
2419 : * Release the file-extension lock; it's now OK for someone else to extend
2420 : * the relation some more.
2421 : *
2422 : * We remove IO_IN_PROGRESS after this, as waking up waiting backends can
2423 : * take noticeable time.
2424 : */
2425 384086 : if (!(flags & EB_SKIP_EXTENSION_LOCK))
2426 282870 : UnlockRelationForExtension(bmr.rel, ExclusiveLock);
2427 :
2428 384086 : pgstat_count_io_op_time(IOOBJECT_RELATION, io_context, IOOP_EXTEND,
2429 384086 : io_start, 1, extend_by * BLCKSZ);
2430 :
2431 : /* Set BM_VALID, terminate IO, and wake up any waiters */
2432 808716 : for (uint32 i = 0; i < extend_by; i++)
2433 : {
2434 424630 : Buffer buf = buffers[i];
2435 424630 : BufferDesc *buf_hdr = GetBufferDescriptor(buf - 1);
2436 424630 : bool lock = false;
2437 :
2438 424630 : if (flags & EB_LOCK_FIRST && i == 0)
2439 279958 : lock = true;
2440 144672 : else if (flags & EB_LOCK_TARGET)
2441 : {
2442 : Assert(extend_upto != InvalidBlockNumber);
2443 87428 : if (first_block + i + 1 == extend_upto)
2444 86312 : lock = true;
2445 : }
2446 :
2447 424630 : if (lock)
2448 366270 : LWLockAcquire(BufferDescriptorGetContentLock(buf_hdr), LW_EXCLUSIVE);
2449 :
2450 424630 : TerminateBufferIO(buf_hdr, false, BM_VALID, true);
2451 : }
2452 :
2453 384086 : pgBufferUsage.shared_blks_written += extend_by;
2454 :
2455 384086 : *extended_by = extend_by;
2456 :
2457 384086 : return first_block;
2458 : }
2459 :
2460 : /*
2461 : * BufferIsExclusiveLocked
2462 : *
2463 : * Checks if buffer is exclusive-locked.
2464 : *
2465 : * Buffer must be pinned.
2466 : */
2467 : bool
2468 0 : BufferIsExclusiveLocked(Buffer buffer)
2469 : {
2470 : BufferDesc *bufHdr;
2471 :
2472 : Assert(BufferIsPinned(buffer));
2473 :
2474 0 : if (BufferIsLocal(buffer))
2475 : {
2476 : /* Content locks are not maintained for local buffers. */
2477 0 : return true;
2478 : }
2479 : else
2480 : {
2481 0 : bufHdr = GetBufferDescriptor(buffer - 1);
2482 0 : return LWLockHeldByMeInMode(BufferDescriptorGetContentLock(bufHdr),
2483 : LW_EXCLUSIVE);
2484 : }
2485 : }
2486 :
2487 : /*
2488 : * BufferIsDirty
2489 : *
2490 : * Checks if buffer is already dirty.
2491 : *
2492 : * Buffer must be pinned and exclusive-locked. (Without an exclusive lock,
2493 : * the result may be stale before it's returned.)
2494 : */
2495 : bool
2496 0 : BufferIsDirty(Buffer buffer)
2497 : {
2498 : BufferDesc *bufHdr;
2499 :
2500 : Assert(BufferIsPinned(buffer));
2501 :
2502 0 : if (BufferIsLocal(buffer))
2503 : {
2504 0 : int bufid = -buffer - 1;
2505 :
2506 0 : bufHdr = GetLocalBufferDescriptor(bufid);
2507 : /* Content locks are not maintained for local buffers. */
2508 : }
2509 : else
2510 : {
2511 0 : bufHdr = GetBufferDescriptor(buffer - 1);
2512 : Assert(LWLockHeldByMeInMode(BufferDescriptorGetContentLock(bufHdr),
2513 : LW_EXCLUSIVE));
2514 : }
2515 :
2516 0 : return pg_atomic_read_u32(&bufHdr->state) & BM_DIRTY;
2517 : }
2518 :
2519 : /*
2520 : * MarkBufferDirty
2521 : *
2522 : * Marks buffer contents as dirty (actual write happens later).
2523 : *
2524 : * Buffer must be pinned and exclusive-locked. (If caller does not hold
2525 : * exclusive lock, then somebody could be in process of writing the buffer,
2526 : * leading to risk of bad data written to disk.)
2527 : */
2528 : void
2529 41005844 : MarkBufferDirty(Buffer buffer)
2530 : {
2531 : BufferDesc *bufHdr;
2532 : uint32 buf_state;
2533 : uint32 old_buf_state;
2534 :
2535 41005844 : if (!BufferIsValid(buffer))
2536 0 : elog(ERROR, "bad buffer ID: %d", buffer);
2537 :
2538 41005844 : if (BufferIsLocal(buffer))
2539 : {
2540 2091110 : MarkLocalBufferDirty(buffer);
2541 2091110 : return;
2542 : }
2543 :
2544 38914734 : bufHdr = GetBufferDescriptor(buffer - 1);
2545 :
2546 : Assert(BufferIsPinned(buffer));
2547 : Assert(LWLockHeldByMeInMode(BufferDescriptorGetContentLock(bufHdr),
2548 : LW_EXCLUSIVE));
2549 :
2550 38914734 : old_buf_state = pg_atomic_read_u32(&bufHdr->state);
2551 : for (;;)
2552 : {
2553 38915130 : if (old_buf_state & BM_LOCKED)
2554 58 : old_buf_state = WaitBufHdrUnlocked(bufHdr);
2555 :
2556 38915130 : buf_state = old_buf_state;
2557 :
2558 : Assert(BUF_STATE_GET_REFCOUNT(buf_state) > 0);
2559 38915130 : buf_state |= BM_DIRTY | BM_JUST_DIRTIED;
2560 :
2561 38915130 : if (pg_atomic_compare_exchange_u32(&bufHdr->state, &old_buf_state,
2562 : buf_state))
2563 38914734 : break;
2564 : }
2565 :
2566 : /*
2567 : * If the buffer was not dirty already, do vacuum accounting.
2568 : */
2569 38914734 : if (!(old_buf_state & BM_DIRTY))
2570 : {
2571 1155300 : pgBufferUsage.shared_blks_dirtied++;
2572 1155300 : if (VacuumCostActive)
2573 4302 : VacuumCostBalance += VacuumCostPageDirty;
2574 : }
2575 : }
2576 :
2577 : /*
2578 : * ReleaseAndReadBuffer -- combine ReleaseBuffer() and ReadBuffer()
2579 : *
2580 : * Formerly, this saved one cycle of acquiring/releasing the BufMgrLock
2581 : * compared to calling the two routines separately. Now it's mainly just
2582 : * a convenience function. However, if the passed buffer is valid and
2583 : * already contains the desired block, we just return it as-is; and that
2584 : * does save considerable work compared to a full release and reacquire.
2585 : *
2586 : * Note: it is OK to pass buffer == InvalidBuffer, indicating that no old
2587 : * buffer actually needs to be released. This case is the same as ReadBuffer,
2588 : * but can save some tests in the caller.
2589 : */
2590 : Buffer
2591 52382788 : ReleaseAndReadBuffer(Buffer buffer,
2592 : Relation relation,
2593 : BlockNumber blockNum)
2594 : {
2595 52382788 : ForkNumber forkNum = MAIN_FORKNUM;
2596 : BufferDesc *bufHdr;
2597 :
2598 52382788 : if (BufferIsValid(buffer))
2599 : {
2600 : Assert(BufferIsPinned(buffer));
2601 31269798 : if (BufferIsLocal(buffer))
2602 : {
2603 20862 : bufHdr = GetLocalBufferDescriptor(-buffer - 1);
2604 27906 : if (bufHdr->tag.blockNum == blockNum &&
2605 14088 : BufTagMatchesRelFileLocator(&bufHdr->tag, &relation->rd_locator) &&
2606 7044 : BufTagGetForkNum(&bufHdr->tag) == forkNum)
2607 7044 : return buffer;
2608 13818 : UnpinLocalBuffer(buffer);
2609 : }
2610 : else
2611 : {
2612 31248936 : bufHdr = GetBufferDescriptor(buffer - 1);
2613 : /* we have pin, so it's ok to examine tag without spinlock */
2614 41940290 : if (bufHdr->tag.blockNum == blockNum &&
2615 21382708 : BufTagMatchesRelFileLocator(&bufHdr->tag, &relation->rd_locator) &&
2616 10691354 : BufTagGetForkNum(&bufHdr->tag) == forkNum)
2617 10691354 : return buffer;
2618 20557582 : UnpinBuffer(bufHdr);
2619 : }
2620 : }
2621 :
2622 41684390 : return ReadBuffer(relation, blockNum);
2623 : }
2624 :
2625 : /*
2626 : * PinBuffer -- make buffer unavailable for replacement.
2627 : *
2628 : * For the default access strategy, the buffer's usage_count is incremented
2629 : * when we first pin it; for other strategies we just make sure the usage_count
2630 : * isn't zero. (The idea of the latter is that we don't want synchronized
2631 : * heap scans to inflate the count, but we need it to not be zero to discourage
2632 : * other backends from stealing buffers from our ring. As long as we cycle
2633 : * through the ring faster than the global clock-sweep cycles, buffers in
2634 : * our ring won't be chosen as victims for replacement by other backends.)
2635 : *
2636 : * This should be applied only to shared buffers, never local ones.
2637 : *
2638 : * Since buffers are pinned/unpinned very frequently, pin buffers without
2639 : * taking the buffer header lock; instead update the state variable in loop of
2640 : * CAS operations. Hopefully it's just a single CAS.
2641 : *
2642 : * Note that ResourceOwnerEnlarge() and ReservePrivateRefCountEntry()
2643 : * must have been done already.
2644 : *
2645 : * Returns true if buffer is BM_VALID, else false. This provision allows
2646 : * some callers to avoid an extra spinlock cycle.
2647 : */
2648 : static bool
2649 107747316 : PinBuffer(BufferDesc *buf, BufferAccessStrategy strategy)
2650 : {
2651 107747316 : Buffer b = BufferDescriptorGetBuffer(buf);
2652 : bool result;
2653 : PrivateRefCountEntry *ref;
2654 :
2655 : Assert(!BufferIsLocal(b));
2656 : Assert(ReservedRefCountEntry != NULL);
2657 :
2658 107747316 : ref = GetPrivateRefCountEntry(b, true);
2659 :
2660 107747316 : if (ref == NULL)
2661 : {
2662 : uint32 buf_state;
2663 : uint32 old_buf_state;
2664 :
2665 103509244 : ref = NewPrivateRefCountEntry(b);
2666 :
2667 103509244 : old_buf_state = pg_atomic_read_u32(&buf->state);
2668 : for (;;)
2669 : {
2670 103532188 : if (old_buf_state & BM_LOCKED)
2671 3758 : old_buf_state = WaitBufHdrUnlocked(buf);
2672 :
2673 103532188 : buf_state = old_buf_state;
2674 :
2675 : /* increase refcount */
2676 103532188 : buf_state += BUF_REFCOUNT_ONE;
2677 :
2678 103532188 : if (strategy == NULL)
2679 : {
2680 : /* Default case: increase usagecount unless already max. */
2681 102273690 : if (BUF_STATE_GET_USAGECOUNT(buf_state) < BM_MAX_USAGE_COUNT)
2682 5747796 : buf_state += BUF_USAGECOUNT_ONE;
2683 : }
2684 : else
2685 : {
2686 : /*
2687 : * Ring buffers shouldn't evict others from pool. Thus we
2688 : * don't make usagecount more than 1.
2689 : */
2690 1258498 : if (BUF_STATE_GET_USAGECOUNT(buf_state) == 0)
2691 74292 : buf_state += BUF_USAGECOUNT_ONE;
2692 : }
2693 :
2694 103532188 : if (pg_atomic_compare_exchange_u32(&buf->state, &old_buf_state,
2695 : buf_state))
2696 : {
2697 103509244 : result = (buf_state & BM_VALID) != 0;
2698 :
2699 : /*
2700 : * Assume that we acquired a buffer pin for the purposes of
2701 : * Valgrind buffer client checks (even in !result case) to
2702 : * keep things simple. Buffers that are unsafe to access are
2703 : * not generally guaranteed to be marked undefined or
2704 : * non-accessible in any case.
2705 : */
2706 : VALGRIND_MAKE_MEM_DEFINED(BufHdrGetBlock(buf), BLCKSZ);
2707 103509244 : break;
2708 : }
2709 : }
2710 : }
2711 : else
2712 : {
2713 : /*
2714 : * If we previously pinned the buffer, it is likely to be valid, but
2715 : * it may not be if StartReadBuffers() was called and
2716 : * WaitReadBuffers() hasn't been called yet. We'll check by loading
2717 : * the flags without locking. This is racy, but it's OK to return
2718 : * false spuriously: when WaitReadBuffers() calls StartBufferIO(),
2719 : * it'll see that it's now valid.
2720 : *
2721 : * Note: We deliberately avoid a Valgrind client request here.
2722 : * Individual access methods can optionally superimpose buffer page
2723 : * client requests on top of our client requests to enforce that
2724 : * buffers are only accessed while locked (and pinned). It's possible
2725 : * that the buffer page is legitimately non-accessible here. We
2726 : * cannot meddle with that.
2727 : */
2728 4238072 : result = (pg_atomic_read_u32(&buf->state) & BM_VALID) != 0;
2729 : }
2730 :
2731 107747316 : ref->refcount++;
2732 : Assert(ref->refcount > 0);
2733 107747316 : ResourceOwnerRememberBuffer(CurrentResourceOwner, b);
2734 107747316 : return result;
2735 : }
2736 :
2737 : /*
2738 : * PinBuffer_Locked -- as above, but caller already locked the buffer header.
2739 : * The spinlock is released before return.
2740 : *
2741 : * As this function is called with the spinlock held, the caller has to
2742 : * previously call ReservePrivateRefCountEntry() and
2743 : * ResourceOwnerEnlarge(CurrentResourceOwner);
2744 : *
2745 : * Currently, no callers of this function want to modify the buffer's
2746 : * usage_count at all, so there's no need for a strategy parameter.
2747 : * Also we don't bother with a BM_VALID test (the caller could check that for
2748 : * itself).
2749 : *
2750 : * Also all callers only ever use this function when it's known that the
2751 : * buffer can't have a preexisting pin by this backend. That allows us to skip
2752 : * searching the private refcount array & hash, which is a boon, because the
2753 : * spinlock is still held.
2754 : *
2755 : * Note: use of this routine is frequently mandatory, not just an optimization
2756 : * to save a spin lock/unlock cycle, because we need to pin a buffer before
2757 : * its state can change under us.
2758 : */
2759 : static void
2760 4059594 : PinBuffer_Locked(BufferDesc *buf)
2761 : {
2762 : Buffer b;
2763 : PrivateRefCountEntry *ref;
2764 : uint32 buf_state;
2765 :
2766 : /*
2767 : * As explained, We don't expect any preexisting pins. That allows us to
2768 : * manipulate the PrivateRefCount after releasing the spinlock
2769 : */
2770 : Assert(GetPrivateRefCountEntry(BufferDescriptorGetBuffer(buf), false) == NULL);
2771 :
2772 : /*
2773 : * Buffer can't have a preexisting pin, so mark its page as defined to
2774 : * Valgrind (this is similar to the PinBuffer() case where the backend
2775 : * doesn't already have a buffer pin)
2776 : */
2777 : VALGRIND_MAKE_MEM_DEFINED(BufHdrGetBlock(buf), BLCKSZ);
2778 :
2779 : /*
2780 : * Since we hold the buffer spinlock, we can update the buffer state and
2781 : * release the lock in one operation.
2782 : */
2783 4059594 : buf_state = pg_atomic_read_u32(&buf->state);
2784 : Assert(buf_state & BM_LOCKED);
2785 4059594 : buf_state += BUF_REFCOUNT_ONE;
2786 4059594 : UnlockBufHdr(buf, buf_state);
2787 :
2788 4059594 : b = BufferDescriptorGetBuffer(buf);
2789 :
2790 4059594 : ref = NewPrivateRefCountEntry(b);
2791 4059594 : ref->refcount++;
2792 :
2793 4059594 : ResourceOwnerRememberBuffer(CurrentResourceOwner, b);
2794 4059594 : }
2795 :
2796 : /*
2797 : * UnpinBuffer -- make buffer available for replacement.
2798 : *
2799 : * This should be applied only to shared buffers, never local ones. This
2800 : * always adjusts CurrentResourceOwner.
2801 : */
2802 : static void
2803 131582422 : UnpinBuffer(BufferDesc *buf)
2804 : {
2805 131582422 : Buffer b = BufferDescriptorGetBuffer(buf);
2806 :
2807 131582422 : ResourceOwnerForgetBuffer(CurrentResourceOwner, b);
2808 131582422 : UnpinBufferNoOwner(buf);
2809 131582422 : }
2810 :
2811 : static void
2812 131590908 : UnpinBufferNoOwner(BufferDesc *buf)
2813 : {
2814 : PrivateRefCountEntry *ref;
2815 131590908 : Buffer b = BufferDescriptorGetBuffer(buf);
2816 :
2817 : Assert(!BufferIsLocal(b));
2818 :
2819 : /* not moving as we're likely deleting it soon anyway */
2820 131590908 : ref = GetPrivateRefCountEntry(b, false);
2821 : Assert(ref != NULL);
2822 : Assert(ref->refcount > 0);
2823 131590908 : ref->refcount--;
2824 131590908 : if (ref->refcount == 0)
2825 : {
2826 : uint32 buf_state;
2827 : uint32 old_buf_state;
2828 :
2829 : /*
2830 : * Mark buffer non-accessible to Valgrind.
2831 : *
2832 : * Note that the buffer may have already been marked non-accessible
2833 : * within access method code that enforces that buffers are only
2834 : * accessed while a buffer lock is held.
2835 : */
2836 : VALGRIND_MAKE_MEM_NOACCESS(BufHdrGetBlock(buf), BLCKSZ);
2837 :
2838 : /* I'd better not still hold the buffer content lock */
2839 : Assert(!LWLockHeldByMe(BufferDescriptorGetContentLock(buf)));
2840 :
2841 : /*
2842 : * Decrement the shared reference count.
2843 : *
2844 : * Since buffer spinlock holder can update status using just write,
2845 : * it's not safe to use atomic decrement here; thus use a CAS loop.
2846 : */
2847 107568838 : old_buf_state = pg_atomic_read_u32(&buf->state);
2848 : for (;;)
2849 : {
2850 107586682 : if (old_buf_state & BM_LOCKED)
2851 2666 : old_buf_state = WaitBufHdrUnlocked(buf);
2852 :
2853 107586682 : buf_state = old_buf_state;
2854 :
2855 107586682 : buf_state -= BUF_REFCOUNT_ONE;
2856 :
2857 107586682 : if (pg_atomic_compare_exchange_u32(&buf->state, &old_buf_state,
2858 : buf_state))
2859 107568838 : break;
2860 : }
2861 :
2862 : /* Support LockBufferForCleanup() */
2863 107568838 : if (buf_state & BM_PIN_COUNT_WAITER)
2864 : {
2865 : /*
2866 : * Acquire the buffer header lock, re-check that there's a waiter.
2867 : * Another backend could have unpinned this buffer, and already
2868 : * woken up the waiter. There's no danger of the buffer being
2869 : * replaced after we unpinned it above, as it's pinned by the
2870 : * waiter.
2871 : */
2872 4 : buf_state = LockBufHdr(buf);
2873 :
2874 4 : if ((buf_state & BM_PIN_COUNT_WAITER) &&
2875 4 : BUF_STATE_GET_REFCOUNT(buf_state) == 1)
2876 4 : {
2877 : /* we just released the last pin other than the waiter's */
2878 4 : int wait_backend_pgprocno = buf->wait_backend_pgprocno;
2879 :
2880 4 : buf_state &= ~BM_PIN_COUNT_WAITER;
2881 4 : UnlockBufHdr(buf, buf_state);
2882 4 : ProcSendSignal(wait_backend_pgprocno);
2883 : }
2884 : else
2885 0 : UnlockBufHdr(buf, buf_state);
2886 : }
2887 107568838 : ForgetPrivateRefCountEntry(ref);
2888 : }
2889 131590908 : }
2890 :
2891 : #define ST_SORT sort_checkpoint_bufferids
2892 : #define ST_ELEMENT_TYPE CkptSortItem
2893 : #define ST_COMPARE(a, b) ckpt_buforder_comparator(a, b)
2894 : #define ST_SCOPE static
2895 : #define ST_DEFINE
2896 : #include <lib/sort_template.h>
2897 :
2898 : /*
2899 : * BufferSync -- Write out all dirty buffers in the pool.
2900 : *
2901 : * This is called at checkpoint time to write out all dirty shared buffers.
2902 : * The checkpoint request flags should be passed in. If CHECKPOINT_IMMEDIATE
2903 : * is set, we disable delays between writes; if CHECKPOINT_IS_SHUTDOWN,
2904 : * CHECKPOINT_END_OF_RECOVERY or CHECKPOINT_FLUSH_ALL is set, we write even
2905 : * unlogged buffers, which are otherwise skipped. The remaining flags
2906 : * currently have no effect here.
2907 : */
2908 : static void
2909 2506 : BufferSync(int flags)
2910 : {
2911 : uint32 buf_state;
2912 : int buf_id;
2913 : int num_to_scan;
2914 : int num_spaces;
2915 : int num_processed;
2916 : int num_written;
2917 2506 : CkptTsStatus *per_ts_stat = NULL;
2918 : Oid last_tsid;
2919 : binaryheap *ts_heap;
2920 : int i;
2921 2506 : int mask = BM_DIRTY;
2922 : WritebackContext wb_context;
2923 :
2924 : /*
2925 : * Unless this is a shutdown checkpoint or we have been explicitly told,
2926 : * we write only permanent, dirty buffers. But at shutdown or end of
2927 : * recovery, we write all dirty buffers.
2928 : */
2929 2506 : if (!((flags & (CHECKPOINT_IS_SHUTDOWN | CHECKPOINT_END_OF_RECOVERY |
2930 : CHECKPOINT_FLUSH_ALL))))
2931 1226 : mask |= BM_PERMANENT;
2932 :
2933 : /*
2934 : * Loop over all buffers, and mark the ones that need to be written with
2935 : * BM_CHECKPOINT_NEEDED. Count them as we go (num_to_scan), so that we
2936 : * can estimate how much work needs to be done.
2937 : *
2938 : * This allows us to write only those pages that were dirty when the
2939 : * checkpoint began, and not those that get dirtied while it proceeds.
2940 : * Whenever a page with BM_CHECKPOINT_NEEDED is written out, either by us
2941 : * later in this function, or by normal backends or the bgwriter cleaning
2942 : * scan, the flag is cleared. Any buffer dirtied after this point won't
2943 : * have the flag set.
2944 : *
2945 : * Note that if we fail to write some buffer, we may leave buffers with
2946 : * BM_CHECKPOINT_NEEDED still set. This is OK since any such buffer would
2947 : * certainly need to be written for the next checkpoint attempt, too.
2948 : */
2949 2506 : num_to_scan = 0;
2950 20740202 : for (buf_id = 0; buf_id < NBuffers; buf_id++)
2951 : {
2952 20737696 : BufferDesc *bufHdr = GetBufferDescriptor(buf_id);
2953 :
2954 : /*
2955 : * Header spinlock is enough to examine BM_DIRTY, see comment in
2956 : * SyncOneBuffer.
2957 : */
2958 20737696 : buf_state = LockBufHdr(bufHdr);
2959 :
2960 20737696 : if ((buf_state & mask) == mask)
2961 : {
2962 : CkptSortItem *item;
2963 :
2964 518382 : buf_state |= BM_CHECKPOINT_NEEDED;
2965 :
2966 518382 : item = &CkptBufferIds[num_to_scan++];
2967 518382 : item->buf_id = buf_id;
2968 518382 : item->tsId = bufHdr->tag.spcOid;
2969 518382 : item->relNumber = BufTagGetRelNumber(&bufHdr->tag);
2970 518382 : item->forkNum = BufTagGetForkNum(&bufHdr->tag);
2971 518382 : item->blockNum = bufHdr->tag.blockNum;
2972 : }
2973 :
2974 20737696 : UnlockBufHdr(bufHdr, buf_state);
2975 :
2976 : /* Check for barrier events in case NBuffers is large. */
2977 20737696 : if (ProcSignalBarrierPending)
2978 0 : ProcessProcSignalBarrier();
2979 : }
2980 :
2981 2506 : if (num_to_scan == 0)
2982 604 : return; /* nothing to do */
2983 :
2984 1902 : WritebackContextInit(&wb_context, &checkpoint_flush_after);
2985 :
2986 : TRACE_POSTGRESQL_BUFFER_SYNC_START(NBuffers, num_to_scan);
2987 :
2988 : /*
2989 : * Sort buffers that need to be written to reduce the likelihood of random
2990 : * IO. The sorting is also important for the implementation of balancing
2991 : * writes between tablespaces. Without balancing writes we'd potentially
2992 : * end up writing to the tablespaces one-by-one; possibly overloading the
2993 : * underlying system.
2994 : */
2995 1902 : sort_checkpoint_bufferids(CkptBufferIds, num_to_scan);
2996 :
2997 1902 : num_spaces = 0;
2998 :
2999 : /*
3000 : * Allocate progress status for each tablespace with buffers that need to
3001 : * be flushed. This requires the to-be-flushed array to be sorted.
3002 : */
3003 1902 : last_tsid = InvalidOid;
3004 520284 : for (i = 0; i < num_to_scan; i++)
3005 : {
3006 : CkptTsStatus *s;
3007 : Oid cur_tsid;
3008 :
3009 518382 : cur_tsid = CkptBufferIds[i].tsId;
3010 :
3011 : /*
3012 : * Grow array of per-tablespace status structs, every time a new
3013 : * tablespace is found.
3014 : */
3015 518382 : if (last_tsid == InvalidOid || last_tsid != cur_tsid)
3016 2808 : {
3017 : Size sz;
3018 :
3019 2808 : num_spaces++;
3020 :
3021 : /*
3022 : * Not worth adding grow-by-power-of-2 logic here - even with a
3023 : * few hundred tablespaces this should be fine.
3024 : */
3025 2808 : sz = sizeof(CkptTsStatus) * num_spaces;
3026 :
3027 2808 : if (per_ts_stat == NULL)
3028 1902 : per_ts_stat = (CkptTsStatus *) palloc(sz);
3029 : else
3030 906 : per_ts_stat = (CkptTsStatus *) repalloc(per_ts_stat, sz);
3031 :
3032 2808 : s = &per_ts_stat[num_spaces - 1];
3033 2808 : memset(s, 0, sizeof(*s));
3034 2808 : s->tsId = cur_tsid;
3035 :
3036 : /*
3037 : * The first buffer in this tablespace. As CkptBufferIds is sorted
3038 : * by tablespace all (s->num_to_scan) buffers in this tablespace
3039 : * will follow afterwards.
3040 : */
3041 2808 : s->index = i;
3042 :
3043 : /*
3044 : * progress_slice will be determined once we know how many buffers
3045 : * are in each tablespace, i.e. after this loop.
3046 : */
3047 :
3048 2808 : last_tsid = cur_tsid;
3049 : }
3050 : else
3051 : {
3052 515574 : s = &per_ts_stat[num_spaces - 1];
3053 : }
3054 :
3055 518382 : s->num_to_scan++;
3056 :
3057 : /* Check for barrier events. */
3058 518382 : if (ProcSignalBarrierPending)
3059 0 : ProcessProcSignalBarrier();
3060 : }
3061 :
3062 : Assert(num_spaces > 0);
3063 :
3064 : /*
3065 : * Build a min-heap over the write-progress in the individual tablespaces,
3066 : * and compute how large a portion of the total progress a single
3067 : * processed buffer is.
3068 : */
3069 1902 : ts_heap = binaryheap_allocate(num_spaces,
3070 : ts_ckpt_progress_comparator,
3071 : NULL);
3072 :
3073 4710 : for (i = 0; i < num_spaces; i++)
3074 : {
3075 2808 : CkptTsStatus *ts_stat = &per_ts_stat[i];
3076 :
3077 2808 : ts_stat->progress_slice = (float8) num_to_scan / ts_stat->num_to_scan;
3078 :
3079 2808 : binaryheap_add_unordered(ts_heap, PointerGetDatum(ts_stat));
3080 : }
3081 :
3082 1902 : binaryheap_build(ts_heap);
3083 :
3084 : /*
3085 : * Iterate through to-be-checkpointed buffers and write the ones (still)
3086 : * marked with BM_CHECKPOINT_NEEDED. The writes are balanced between
3087 : * tablespaces; otherwise the sorting would lead to only one tablespace
3088 : * receiving writes at a time, making inefficient use of the hardware.
3089 : */
3090 1902 : num_processed = 0;
3091 1902 : num_written = 0;
3092 520284 : while (!binaryheap_empty(ts_heap))
3093 : {
3094 518382 : BufferDesc *bufHdr = NULL;
3095 : CkptTsStatus *ts_stat = (CkptTsStatus *)
3096 518382 : DatumGetPointer(binaryheap_first(ts_heap));
3097 :
3098 518382 : buf_id = CkptBufferIds[ts_stat->index].buf_id;
3099 : Assert(buf_id != -1);
3100 :
3101 518382 : bufHdr = GetBufferDescriptor(buf_id);
3102 :
3103 518382 : num_processed++;
3104 :
3105 : /*
3106 : * We don't need to acquire the lock here, because we're only looking
3107 : * at a single bit. It's possible that someone else writes the buffer
3108 : * and clears the flag right after we check, but that doesn't matter
3109 : * since SyncOneBuffer will then do nothing. However, there is a
3110 : * further race condition: it's conceivable that between the time we
3111 : * examine the bit here and the time SyncOneBuffer acquires the lock,
3112 : * someone else not only wrote the buffer but replaced it with another
3113 : * page and dirtied it. In that improbable case, SyncOneBuffer will
3114 : * write the buffer though we didn't need to. It doesn't seem worth
3115 : * guarding against this, though.
3116 : */
3117 518382 : if (pg_atomic_read_u32(&bufHdr->state) & BM_CHECKPOINT_NEEDED)
3118 : {
3119 480044 : if (SyncOneBuffer(buf_id, false, &wb_context) & BUF_WRITTEN)
3120 : {
3121 : TRACE_POSTGRESQL_BUFFER_SYNC_WRITTEN(buf_id);
3122 480044 : PendingCheckpointerStats.buffers_written++;
3123 480044 : num_written++;
3124 : }
3125 : }
3126 :
3127 : /*
3128 : * Measure progress independent of actually having to flush the buffer
3129 : * - otherwise writing become unbalanced.
3130 : */
3131 518382 : ts_stat->progress += ts_stat->progress_slice;
3132 518382 : ts_stat->num_scanned++;
3133 518382 : ts_stat->index++;
3134 :
3135 : /* Have all the buffers from the tablespace been processed? */
3136 518382 : if (ts_stat->num_scanned == ts_stat->num_to_scan)
3137 : {
3138 2808 : binaryheap_remove_first(ts_heap);
3139 : }
3140 : else
3141 : {
3142 : /* update heap with the new progress */
3143 515574 : binaryheap_replace_first(ts_heap, PointerGetDatum(ts_stat));
3144 : }
3145 :
3146 : /*
3147 : * Sleep to throttle our I/O rate.
3148 : *
3149 : * (This will check for barrier events even if it doesn't sleep.)
3150 : */
3151 518382 : CheckpointWriteDelay(flags, (double) num_processed / num_to_scan);
3152 : }
3153 :
3154 : /*
3155 : * Issue all pending flushes. Only checkpointer calls BufferSync(), so
3156 : * IOContext will always be IOCONTEXT_NORMAL.
3157 : */
3158 1902 : IssuePendingWritebacks(&wb_context, IOCONTEXT_NORMAL);
3159 :
3160 1902 : pfree(per_ts_stat);
3161 1902 : per_ts_stat = NULL;
3162 1902 : binaryheap_free(ts_heap);
3163 :
3164 : /*
3165 : * Update checkpoint statistics. As noted above, this doesn't include
3166 : * buffers written by other backends or bgwriter scan.
3167 : */
3168 1902 : CheckpointStats.ckpt_bufs_written += num_written;
3169 :
3170 : TRACE_POSTGRESQL_BUFFER_SYNC_DONE(NBuffers, num_written, num_to_scan);
3171 : }
3172 :
3173 : /*
3174 : * BgBufferSync -- Write out some dirty buffers in the pool.
3175 : *
3176 : * This is called periodically by the background writer process.
3177 : *
3178 : * Returns true if it's appropriate for the bgwriter process to go into
3179 : * low-power hibernation mode. (This happens if the strategy clock sweep
3180 : * has been "lapped" and no buffer allocations have occurred recently,
3181 : * or if the bgwriter has been effectively disabled by setting
3182 : * bgwriter_lru_maxpages to 0.)
3183 : */
3184 : bool
3185 18370 : BgBufferSync(WritebackContext *wb_context)
3186 : {
3187 : /* info obtained from freelist.c */
3188 : int strategy_buf_id;
3189 : uint32 strategy_passes;
3190 : uint32 recent_alloc;
3191 :
3192 : /*
3193 : * Information saved between calls so we can determine the strategy
3194 : * point's advance rate and avoid scanning already-cleaned buffers.
3195 : */
3196 : static bool saved_info_valid = false;
3197 : static int prev_strategy_buf_id;
3198 : static uint32 prev_strategy_passes;
3199 : static int next_to_clean;
3200 : static uint32 next_passes;
3201 :
3202 : /* Moving averages of allocation rate and clean-buffer density */
3203 : static float smoothed_alloc = 0;
3204 : static float smoothed_density = 10.0;
3205 :
3206 : /* Potentially these could be tunables, but for now, not */
3207 18370 : float smoothing_samples = 16;
3208 18370 : float scan_whole_pool_milliseconds = 120000.0;
3209 :
3210 : /* Used to compute how far we scan ahead */
3211 : long strategy_delta;
3212 : int bufs_to_lap;
3213 : int bufs_ahead;
3214 : float scans_per_alloc;
3215 : int reusable_buffers_est;
3216 : int upcoming_alloc_est;
3217 : int min_scan_buffers;
3218 :
3219 : /* Variables for the scanning loop proper */
3220 : int num_to_scan;
3221 : int num_written;
3222 : int reusable_buffers;
3223 :
3224 : /* Variables for final smoothed_density update */
3225 : long new_strategy_delta;
3226 : uint32 new_recent_alloc;
3227 :
3228 : /*
3229 : * Find out where the freelist clock sweep currently is, and how many
3230 : * buffer allocations have happened since our last call.
3231 : */
3232 18370 : strategy_buf_id = StrategySyncStart(&strategy_passes, &recent_alloc);
3233 :
3234 : /* Report buffer alloc counts to pgstat */
3235 18370 : PendingBgWriterStats.buf_alloc += recent_alloc;
3236 :
3237 : /*
3238 : * If we're not running the LRU scan, just stop after doing the stats
3239 : * stuff. We mark the saved state invalid so that we can recover sanely
3240 : * if LRU scan is turned back on later.
3241 : */
3242 18370 : if (bgwriter_lru_maxpages <= 0)
3243 : {
3244 38 : saved_info_valid = false;
3245 38 : return true;
3246 : }
3247 :
3248 : /*
3249 : * Compute strategy_delta = how many buffers have been scanned by the
3250 : * clock sweep since last time. If first time through, assume none. Then
3251 : * see if we are still ahead of the clock sweep, and if so, how many
3252 : * buffers we could scan before we'd catch up with it and "lap" it. Note:
3253 : * weird-looking coding of xxx_passes comparisons are to avoid bogus
3254 : * behavior when the passes counts wrap around.
3255 : */
3256 18332 : if (saved_info_valid)
3257 : {
3258 17434 : int32 passes_delta = strategy_passes - prev_strategy_passes;
3259 :
3260 17434 : strategy_delta = strategy_buf_id - prev_strategy_buf_id;
3261 17434 : strategy_delta += (long) passes_delta * NBuffers;
3262 :
3263 : Assert(strategy_delta >= 0);
3264 :
3265 17434 : if ((int32) (next_passes - strategy_passes) > 0)
3266 : {
3267 : /* we're one pass ahead of the strategy point */
3268 3738 : bufs_to_lap = strategy_buf_id - next_to_clean;
3269 : #ifdef BGW_DEBUG
3270 : elog(DEBUG2, "bgwriter ahead: bgw %u-%u strategy %u-%u delta=%ld lap=%d",
3271 : next_passes, next_to_clean,
3272 : strategy_passes, strategy_buf_id,
3273 : strategy_delta, bufs_to_lap);
3274 : #endif
3275 : }
3276 13696 : else if (next_passes == strategy_passes &&
3277 10768 : next_to_clean >= strategy_buf_id)
3278 : {
3279 : /* on same pass, but ahead or at least not behind */
3280 10554 : bufs_to_lap = NBuffers - (next_to_clean - strategy_buf_id);
3281 : #ifdef BGW_DEBUG
3282 : elog(DEBUG2, "bgwriter ahead: bgw %u-%u strategy %u-%u delta=%ld lap=%d",
3283 : next_passes, next_to_clean,
3284 : strategy_passes, strategy_buf_id,
3285 : strategy_delta, bufs_to_lap);
3286 : #endif
3287 : }
3288 : else
3289 : {
3290 : /*
3291 : * We're behind, so skip forward to the strategy point and start
3292 : * cleaning from there.
3293 : */
3294 : #ifdef BGW_DEBUG
3295 : elog(DEBUG2, "bgwriter behind: bgw %u-%u strategy %u-%u delta=%ld",
3296 : next_passes, next_to_clean,
3297 : strategy_passes, strategy_buf_id,
3298 : strategy_delta);
3299 : #endif
3300 3142 : next_to_clean = strategy_buf_id;
3301 3142 : next_passes = strategy_passes;
3302 3142 : bufs_to_lap = NBuffers;
3303 : }
3304 : }
3305 : else
3306 : {
3307 : /*
3308 : * Initializing at startup or after LRU scanning had been off. Always
3309 : * start at the strategy point.
3310 : */
3311 : #ifdef BGW_DEBUG
3312 : elog(DEBUG2, "bgwriter initializing: strategy %u-%u",
3313 : strategy_passes, strategy_buf_id);
3314 : #endif
3315 898 : strategy_delta = 0;
3316 898 : next_to_clean = strategy_buf_id;
3317 898 : next_passes = strategy_passes;
3318 898 : bufs_to_lap = NBuffers;
3319 : }
3320 :
3321 : /* Update saved info for next time */
3322 18332 : prev_strategy_buf_id = strategy_buf_id;
3323 18332 : prev_strategy_passes = strategy_passes;
3324 18332 : saved_info_valid = true;
3325 :
3326 : /*
3327 : * Compute how many buffers had to be scanned for each new allocation, ie,
3328 : * 1/density of reusable buffers, and track a moving average of that.
3329 : *
3330 : * If the strategy point didn't move, we don't update the density estimate
3331 : */
3332 18332 : if (strategy_delta > 0 && recent_alloc > 0)
3333 : {
3334 3928 : scans_per_alloc = (float) strategy_delta / (float) recent_alloc;
3335 3928 : smoothed_density += (scans_per_alloc - smoothed_density) /
3336 : smoothing_samples;
3337 : }
3338 :
3339 : /*
3340 : * Estimate how many reusable buffers there are between the current
3341 : * strategy point and where we've scanned ahead to, based on the smoothed
3342 : * density estimate.
3343 : */
3344 18332 : bufs_ahead = NBuffers - bufs_to_lap;
3345 18332 : reusable_buffers_est = (float) bufs_ahead / smoothed_density;
3346 :
3347 : /*
3348 : * Track a moving average of recent buffer allocations. Here, rather than
3349 : * a true average we want a fast-attack, slow-decline behavior: we
3350 : * immediately follow any increase.
3351 : */
3352 18332 : if (smoothed_alloc <= (float) recent_alloc)
3353 5204 : smoothed_alloc = recent_alloc;
3354 : else
3355 13128 : smoothed_alloc += ((float) recent_alloc - smoothed_alloc) /
3356 : smoothing_samples;
3357 :
3358 : /* Scale the estimate by a GUC to allow more aggressive tuning. */
3359 18332 : upcoming_alloc_est = (int) (smoothed_alloc * bgwriter_lru_multiplier);
3360 :
3361 : /*
3362 : * If recent_alloc remains at zero for many cycles, smoothed_alloc will
3363 : * eventually underflow to zero, and the underflows produce annoying
3364 : * kernel warnings on some platforms. Once upcoming_alloc_est has gone to
3365 : * zero, there's no point in tracking smaller and smaller values of
3366 : * smoothed_alloc, so just reset it to exactly zero to avoid this
3367 : * syndrome. It will pop back up as soon as recent_alloc increases.
3368 : */
3369 18332 : if (upcoming_alloc_est == 0)
3370 3124 : smoothed_alloc = 0;
3371 :
3372 : /*
3373 : * Even in cases where there's been little or no buffer allocation
3374 : * activity, we want to make a small amount of progress through the buffer
3375 : * cache so that as many reusable buffers as possible are clean after an
3376 : * idle period.
3377 : *
3378 : * (scan_whole_pool_milliseconds / BgWriterDelay) computes how many times
3379 : * the BGW will be called during the scan_whole_pool time; slice the
3380 : * buffer pool into that many sections.
3381 : */
3382 18332 : min_scan_buffers = (int) (NBuffers / (scan_whole_pool_milliseconds / BgWriterDelay));
3383 :
3384 18332 : if (upcoming_alloc_est < (min_scan_buffers + reusable_buffers_est))
3385 : {
3386 : #ifdef BGW_DEBUG
3387 : elog(DEBUG2, "bgwriter: alloc_est=%d too small, using min=%d + reusable_est=%d",
3388 : upcoming_alloc_est, min_scan_buffers, reusable_buffers_est);
3389 : #endif
3390 10270 : upcoming_alloc_est = min_scan_buffers + reusable_buffers_est;
3391 : }
3392 :
3393 : /*
3394 : * Now write out dirty reusable buffers, working forward from the
3395 : * next_to_clean point, until we have lapped the strategy scan, or cleaned
3396 : * enough buffers to match our estimate of the next cycle's allocation
3397 : * requirements, or hit the bgwriter_lru_maxpages limit.
3398 : */
3399 :
3400 18332 : num_to_scan = bufs_to_lap;
3401 18332 : num_written = 0;
3402 18332 : reusable_buffers = reusable_buffers_est;
3403 :
3404 : /* Execute the LRU scan */
3405 2902090 : while (num_to_scan > 0 && reusable_buffers < upcoming_alloc_est)
3406 : {
3407 2883760 : int sync_state = SyncOneBuffer(next_to_clean, true,
3408 : wb_context);
3409 :
3410 2883760 : if (++next_to_clean >= NBuffers)
3411 : {
3412 3536 : next_to_clean = 0;
3413 3536 : next_passes++;
3414 : }
3415 2883760 : num_to_scan--;
3416 :
3417 2883760 : if (sync_state & BUF_WRITTEN)
3418 : {
3419 29102 : reusable_buffers++;
3420 29102 : if (++num_written >= bgwriter_lru_maxpages)
3421 : {
3422 2 : PendingBgWriterStats.maxwritten_clean++;
3423 2 : break;
3424 : }
3425 : }
3426 2854658 : else if (sync_state & BUF_REUSABLE)
3427 2159790 : reusable_buffers++;
3428 : }
3429 :
3430 18332 : PendingBgWriterStats.buf_written_clean += num_written;
3431 :
3432 : #ifdef BGW_DEBUG
3433 : elog(DEBUG1, "bgwriter: recent_alloc=%u smoothed=%.2f delta=%ld ahead=%d density=%.2f reusable_est=%d upcoming_est=%d scanned=%d wrote=%d reusable=%d",
3434 : recent_alloc, smoothed_alloc, strategy_delta, bufs_ahead,
3435 : smoothed_density, reusable_buffers_est, upcoming_alloc_est,
3436 : bufs_to_lap - num_to_scan,
3437 : num_written,
3438 : reusable_buffers - reusable_buffers_est);
3439 : #endif
3440 :
3441 : /*
3442 : * Consider the above scan as being like a new allocation scan.
3443 : * Characterize its density and update the smoothed one based on it. This
3444 : * effectively halves the moving average period in cases where both the
3445 : * strategy and the background writer are doing some useful scanning,
3446 : * which is helpful because a long memory isn't as desirable on the
3447 : * density estimates.
3448 : */
3449 18332 : new_strategy_delta = bufs_to_lap - num_to_scan;
3450 18332 : new_recent_alloc = reusable_buffers - reusable_buffers_est;
3451 18332 : if (new_strategy_delta > 0 && new_recent_alloc > 0)
3452 : {
3453 14308 : scans_per_alloc = (float) new_strategy_delta / (float) new_recent_alloc;
3454 14308 : smoothed_density += (scans_per_alloc - smoothed_density) /
3455 : smoothing_samples;
3456 :
3457 : #ifdef BGW_DEBUG
3458 : elog(DEBUG2, "bgwriter: cleaner density alloc=%u scan=%ld density=%.2f new smoothed=%.2f",
3459 : new_recent_alloc, new_strategy_delta,
3460 : scans_per_alloc, smoothed_density);
3461 : #endif
3462 : }
3463 :
3464 : /* Return true if OK to hibernate */
3465 18332 : return (bufs_to_lap == 0 && recent_alloc == 0);
3466 : }
3467 :
3468 : /*
3469 : * SyncOneBuffer -- process a single buffer during syncing.
3470 : *
3471 : * If skip_recently_used is true, we don't write currently-pinned buffers, nor
3472 : * buffers marked recently used, as these are not replacement candidates.
3473 : *
3474 : * Returns a bitmask containing the following flag bits:
3475 : * BUF_WRITTEN: we wrote the buffer.
3476 : * BUF_REUSABLE: buffer is available for replacement, ie, it has
3477 : * pin count 0 and usage count 0.
3478 : *
3479 : * (BUF_WRITTEN could be set in error if FlushBuffer finds the buffer clean
3480 : * after locking it, but we don't care all that much.)
3481 : */
3482 : static int
3483 3363804 : SyncOneBuffer(int buf_id, bool skip_recently_used, WritebackContext *wb_context)
3484 : {
3485 3363804 : BufferDesc *bufHdr = GetBufferDescriptor(buf_id);
3486 3363804 : int result = 0;
3487 : uint32 buf_state;
3488 : BufferTag tag;
3489 :
3490 : /* Make sure we can handle the pin */
3491 3363804 : ReservePrivateRefCountEntry();
3492 3363804 : ResourceOwnerEnlarge(CurrentResourceOwner);
3493 :
3494 : /*
3495 : * Check whether buffer needs writing.
3496 : *
3497 : * We can make this check without taking the buffer content lock so long
3498 : * as we mark pages dirty in access methods *before* logging changes with
3499 : * XLogInsert(): if someone marks the buffer dirty just after our check we
3500 : * don't worry because our checkpoint.redo points before log record for
3501 : * upcoming changes and so we are not required to write such dirty buffer.
3502 : */
3503 3363804 : buf_state = LockBufHdr(bufHdr);
3504 :
3505 3363804 : if (BUF_STATE_GET_REFCOUNT(buf_state) == 0 &&
3506 3359638 : BUF_STATE_GET_USAGECOUNT(buf_state) == 0)
3507 : {
3508 2192908 : result |= BUF_REUSABLE;
3509 : }
3510 1170896 : else if (skip_recently_used)
3511 : {
3512 : /* Caller told us not to write recently-used buffers */
3513 694868 : UnlockBufHdr(bufHdr, buf_state);
3514 694868 : return result;
3515 : }
3516 :
3517 2668936 : if (!(buf_state & BM_VALID) || !(buf_state & BM_DIRTY))
3518 : {
3519 : /* It's clean, so nothing to do */
3520 2159790 : UnlockBufHdr(bufHdr, buf_state);
3521 2159790 : return result;
3522 : }
3523 :
3524 : /*
3525 : * Pin it, share-lock it, write it. (FlushBuffer will do nothing if the
3526 : * buffer is clean by the time we've locked it.)
3527 : */
3528 509146 : PinBuffer_Locked(bufHdr);
3529 509146 : LWLockAcquire(BufferDescriptorGetContentLock(bufHdr), LW_SHARED);
3530 :
3531 509146 : FlushBuffer(bufHdr, NULL, IOOBJECT_RELATION, IOCONTEXT_NORMAL);
3532 :
3533 509146 : LWLockRelease(BufferDescriptorGetContentLock(bufHdr));
3534 :
3535 509146 : tag = bufHdr->tag;
3536 :
3537 509146 : UnpinBuffer(bufHdr);
3538 :
3539 : /*
3540 : * SyncOneBuffer() is only called by checkpointer and bgwriter, so
3541 : * IOContext will always be IOCONTEXT_NORMAL.
3542 : */
3543 509146 : ScheduleBufferTagForWriteback(wb_context, IOCONTEXT_NORMAL, &tag);
3544 :
3545 509146 : return result | BUF_WRITTEN;
3546 : }
3547 :
3548 : /*
3549 : * AtEOXact_Buffers - clean up at end of transaction.
3550 : *
3551 : * As of PostgreSQL 8.0, buffer pins should get released by the
3552 : * ResourceOwner mechanism. This routine is just a debugging
3553 : * cross-check that no pins remain.
3554 : */
3555 : void
3556 802076 : AtEOXact_Buffers(bool isCommit)
3557 : {
3558 802076 : CheckForBufferLeaks();
3559 :
3560 802076 : AtEOXact_LocalBuffers(isCommit);
3561 :
3562 : Assert(PrivateRefCountOverflowed == 0);
3563 802076 : }
3564 :
3565 : /*
3566 : * Initialize access to shared buffer pool
3567 : *
3568 : * This is called during backend startup (whether standalone or under the
3569 : * postmaster). It sets up for this backend's access to the already-existing
3570 : * buffer pool.
3571 : */
3572 : void
3573 35014 : InitBufferManagerAccess(void)
3574 : {
3575 : HASHCTL hash_ctl;
3576 :
3577 35014 : memset(&PrivateRefCountArray, 0, sizeof(PrivateRefCountArray));
3578 :
3579 35014 : hash_ctl.keysize = sizeof(int32);
3580 35014 : hash_ctl.entrysize = sizeof(PrivateRefCountEntry);
3581 :
3582 35014 : PrivateRefCountHash = hash_create("PrivateRefCount", 100, &hash_ctl,
3583 : HASH_ELEM | HASH_BLOBS);
3584 :
3585 : /*
3586 : * AtProcExit_Buffers needs LWLock access, and thereby has to be called at
3587 : * the corresponding phase of backend shutdown.
3588 : */
3589 : Assert(MyProc != NULL);
3590 35014 : on_shmem_exit(AtProcExit_Buffers, 0);
3591 35014 : }
3592 :
3593 : /*
3594 : * During backend exit, ensure that we released all shared-buffer locks and
3595 : * assert that we have no remaining pins.
3596 : */
3597 : static void
3598 35014 : AtProcExit_Buffers(int code, Datum arg)
3599 : {
3600 35014 : UnlockBuffers();
3601 :
3602 35014 : CheckForBufferLeaks();
3603 :
3604 : /* localbuf.c needs a chance too */
3605 35014 : AtProcExit_LocalBuffers();
3606 35014 : }
3607 :
3608 : /*
3609 : * CheckForBufferLeaks - ensure this backend holds no buffer pins
3610 : *
3611 : * As of PostgreSQL 8.0, buffer pins should get released by the
3612 : * ResourceOwner mechanism. This routine is just a debugging
3613 : * cross-check that no pins remain.
3614 : */
3615 : static void
3616 837090 : CheckForBufferLeaks(void)
3617 : {
3618 : #ifdef USE_ASSERT_CHECKING
3619 : int RefCountErrors = 0;
3620 : PrivateRefCountEntry *res;
3621 : int i;
3622 : char *s;
3623 :
3624 : /* check the array */
3625 : for (i = 0; i < REFCOUNT_ARRAY_ENTRIES; i++)
3626 : {
3627 : res = &PrivateRefCountArray[i];
3628 :
3629 : if (res->buffer != InvalidBuffer)
3630 : {
3631 : s = DebugPrintBufferRefcount(res->buffer);
3632 : elog(WARNING, "buffer refcount leak: %s", s);
3633 : pfree(s);
3634 :
3635 : RefCountErrors++;
3636 : }
3637 : }
3638 :
3639 : /* if necessary search the hash */
3640 : if (PrivateRefCountOverflowed)
3641 : {
3642 : HASH_SEQ_STATUS hstat;
3643 :
3644 : hash_seq_init(&hstat, PrivateRefCountHash);
3645 : while ((res = (PrivateRefCountEntry *) hash_seq_search(&hstat)) != NULL)
3646 : {
3647 : s = DebugPrintBufferRefcount(res->buffer);
3648 : elog(WARNING, "buffer refcount leak: %s", s);
3649 : pfree(s);
3650 : RefCountErrors++;
3651 : }
3652 : }
3653 :
3654 : Assert(RefCountErrors == 0);
3655 : #endif
3656 837090 : }
3657 :
3658 : /*
3659 : * Helper routine to issue warnings when a buffer is unexpectedly pinned
3660 : */
3661 : char *
3662 0 : DebugPrintBufferRefcount(Buffer buffer)
3663 : {
3664 : BufferDesc *buf;
3665 : int32 loccount;
3666 : char *path;
3667 : char *result;
3668 : ProcNumber backend;
3669 : uint32 buf_state;
3670 :
3671 : Assert(BufferIsValid(buffer));
3672 0 : if (BufferIsLocal(buffer))
3673 : {
3674 0 : buf = GetLocalBufferDescriptor(-buffer - 1);
3675 0 : loccount = LocalRefCount[-buffer - 1];
3676 0 : backend = MyProcNumber;
3677 : }
3678 : else
3679 : {
3680 0 : buf = GetBufferDescriptor(buffer - 1);
3681 0 : loccount = GetPrivateRefCount(buffer);
3682 0 : backend = INVALID_PROC_NUMBER;
3683 : }
3684 :
3685 : /* theoretically we should lock the bufhdr here */
3686 0 : path = relpathbackend(BufTagGetRelFileLocator(&buf->tag), backend,
3687 : BufTagGetForkNum(&buf->tag));
3688 0 : buf_state = pg_atomic_read_u32(&buf->state);
3689 :
3690 0 : result = psprintf("[%03d] (rel=%s, blockNum=%u, flags=0x%x, refcount=%u %d)",
3691 : buffer, path,
3692 : buf->tag.blockNum, buf_state & BUF_FLAG_MASK,
3693 : BUF_STATE_GET_REFCOUNT(buf_state), loccount);
3694 0 : pfree(path);
3695 0 : return result;
3696 : }
3697 :
3698 : /*
3699 : * CheckPointBuffers
3700 : *
3701 : * Flush all dirty blocks in buffer pool to disk at checkpoint time.
3702 : *
3703 : * Note: temporary relations do not participate in checkpoints, so they don't
3704 : * need to be flushed.
3705 : */
3706 : void
3707 2506 : CheckPointBuffers(int flags)
3708 : {
3709 2506 : BufferSync(flags);
3710 2506 : }
3711 :
3712 : /*
3713 : * BufferGetBlockNumber
3714 : * Returns the block number associated with a buffer.
3715 : *
3716 : * Note:
3717 : * Assumes that the buffer is valid and pinned, else the
3718 : * value may be obsolete immediately...
3719 : */
3720 : BlockNumber
3721 91962536 : BufferGetBlockNumber(Buffer buffer)
3722 : {
3723 : BufferDesc *bufHdr;
3724 :
3725 : Assert(BufferIsPinned(buffer));
3726 :
3727 91962536 : if (BufferIsLocal(buffer))
3728 3333830 : bufHdr = GetLocalBufferDescriptor(-buffer - 1);
3729 : else
3730 88628706 : bufHdr = GetBufferDescriptor(buffer - 1);
3731 :
3732 : /* pinned, so OK to read tag without spinlock */
3733 91962536 : return bufHdr->tag.blockNum;
3734 : }
3735 :
3736 : /*
3737 : * BufferGetTag
3738 : * Returns the relfilelocator, fork number and block number associated with
3739 : * a buffer.
3740 : */
3741 : void
3742 28742444 : BufferGetTag(Buffer buffer, RelFileLocator *rlocator, ForkNumber *forknum,
3743 : BlockNumber *blknum)
3744 : {
3745 : BufferDesc *bufHdr;
3746 :
3747 : /* Do the same checks as BufferGetBlockNumber. */
3748 : Assert(BufferIsPinned(buffer));
3749 :
3750 28742444 : if (BufferIsLocal(buffer))
3751 0 : bufHdr = GetLocalBufferDescriptor(-buffer - 1);
3752 : else
3753 28742444 : bufHdr = GetBufferDescriptor(buffer - 1);
3754 :
3755 : /* pinned, so OK to read tag without spinlock */
3756 28742444 : *rlocator = BufTagGetRelFileLocator(&bufHdr->tag);
3757 28742444 : *forknum = BufTagGetForkNum(&bufHdr->tag);
3758 28742444 : *blknum = bufHdr->tag.blockNum;
3759 28742444 : }
3760 :
3761 : /*
3762 : * FlushBuffer
3763 : * Physically write out a shared buffer.
3764 : *
3765 : * NOTE: this actually just passes the buffer contents to the kernel; the
3766 : * real write to disk won't happen until the kernel feels like it. This
3767 : * is okay from our point of view since we can redo the changes from WAL.
3768 : * However, we will need to force the changes to disk via fsync before
3769 : * we can checkpoint WAL.
3770 : *
3771 : * The caller must hold a pin on the buffer and have share-locked the
3772 : * buffer contents. (Note: a share-lock does not prevent updates of
3773 : * hint bits in the buffer, so the page could change while the write
3774 : * is in progress, but we assume that that will not invalidate the data
3775 : * written.)
3776 : *
3777 : * If the caller has an smgr reference for the buffer's relation, pass it
3778 : * as the second parameter. If not, pass NULL.
3779 : */
3780 : static void
3781 975202 : FlushBuffer(BufferDesc *buf, SMgrRelation reln, IOObject io_object,
3782 : IOContext io_context)
3783 : {
3784 : XLogRecPtr recptr;
3785 : ErrorContextCallback errcallback;
3786 : instr_time io_start;
3787 : Block bufBlock;
3788 : char *bufToWrite;
3789 : uint32 buf_state;
3790 :
3791 : /*
3792 : * Try to start an I/O operation. If StartBufferIO returns false, then
3793 : * someone else flushed the buffer before we could, so we need not do
3794 : * anything.
3795 : */
3796 975202 : if (!StartBufferIO(buf, false, false))
3797 52 : return;
3798 :
3799 : /* Setup error traceback support for ereport() */
3800 975150 : errcallback.callback = shared_buffer_write_error_callback;
3801 975150 : errcallback.arg = buf;
3802 975150 : errcallback.previous = error_context_stack;
3803 975150 : error_context_stack = &errcallback;
3804 :
3805 : /* Find smgr relation for buffer */
3806 975150 : if (reln == NULL)
3807 968058 : reln = smgropen(BufTagGetRelFileLocator(&buf->tag), INVALID_PROC_NUMBER);
3808 :
3809 : TRACE_POSTGRESQL_BUFFER_FLUSH_START(BufTagGetForkNum(&buf->tag),
3810 : buf->tag.blockNum,
3811 : reln->smgr_rlocator.locator.spcOid,
3812 : reln->smgr_rlocator.locator.dbOid,
3813 : reln->smgr_rlocator.locator.relNumber);
3814 :
3815 975150 : buf_state = LockBufHdr(buf);
3816 :
3817 : /*
3818 : * Run PageGetLSN while holding header lock, since we don't have the
3819 : * buffer locked exclusively in all cases.
3820 : */
3821 975150 : recptr = BufferGetLSN(buf);
3822 :
3823 : /* To check if block content changes while flushing. - vadim 01/17/97 */
3824 975150 : buf_state &= ~BM_JUST_DIRTIED;
3825 975150 : UnlockBufHdr(buf, buf_state);
3826 :
3827 : /*
3828 : * Force XLOG flush up to buffer's LSN. This implements the basic WAL
3829 : * rule that log updates must hit disk before any of the data-file changes
3830 : * they describe do.
3831 : *
3832 : * However, this rule does not apply to unlogged relations, which will be
3833 : * lost after a crash anyway. Most unlogged relation pages do not bear
3834 : * LSNs since we never emit WAL records for them, and therefore flushing
3835 : * up through the buffer LSN would be useless, but harmless. However,
3836 : * GiST indexes use LSNs internally to track page-splits, and therefore
3837 : * unlogged GiST pages bear "fake" LSNs generated by
3838 : * GetFakeLSNForUnloggedRel. It is unlikely but possible that the fake
3839 : * LSN counter could advance past the WAL insertion point; and if it did
3840 : * happen, attempting to flush WAL through that location would fail, with
3841 : * disastrous system-wide consequences. To make sure that can't happen,
3842 : * skip the flush if the buffer isn't permanent.
3843 : */
3844 975150 : if (buf_state & BM_PERMANENT)
3845 971596 : XLogFlush(recptr);
3846 :
3847 : /*
3848 : * Now it's safe to write buffer to disk. Note that no one else should
3849 : * have been able to write it while we were busy with log flushing because
3850 : * only one process at a time can set the BM_IO_IN_PROGRESS bit.
3851 : */
3852 975150 : bufBlock = BufHdrGetBlock(buf);
3853 :
3854 : /*
3855 : * Update page checksum if desired. Since we have only shared lock on the
3856 : * buffer, other processes might be updating hint bits in it, so we must
3857 : * copy the page to private storage if we do checksumming.
3858 : */
3859 975150 : bufToWrite = PageSetChecksumCopy((Page) bufBlock, buf->tag.blockNum);
3860 :
3861 975150 : io_start = pgstat_prepare_io_time(track_io_timing);
3862 :
3863 : /*
3864 : * bufToWrite is either the shared buffer or a copy, as appropriate.
3865 : */
3866 975150 : smgrwrite(reln,
3867 975150 : BufTagGetForkNum(&buf->tag),
3868 : buf->tag.blockNum,
3869 : bufToWrite,
3870 : false);
3871 :
3872 : /*
3873 : * When a strategy is in use, only flushes of dirty buffers already in the
3874 : * strategy ring are counted as strategy writes (IOCONTEXT
3875 : * [BULKREAD|BULKWRITE|VACUUM] IOOP_WRITE) for the purpose of IO
3876 : * statistics tracking.
3877 : *
3878 : * If a shared buffer initially added to the ring must be flushed before
3879 : * being used, this is counted as an IOCONTEXT_NORMAL IOOP_WRITE.
3880 : *
3881 : * If a shared buffer which was added to the ring later because the
3882 : * current strategy buffer is pinned or in use or because all strategy
3883 : * buffers were dirty and rejected (for BAS_BULKREAD operations only)
3884 : * requires flushing, this is counted as an IOCONTEXT_NORMAL IOOP_WRITE
3885 : * (from_ring will be false).
3886 : *
3887 : * When a strategy is not in use, the write can only be a "regular" write
3888 : * of a dirty shared buffer (IOCONTEXT_NORMAL IOOP_WRITE).
3889 : */
3890 975150 : pgstat_count_io_op_time(IOOBJECT_RELATION, io_context,
3891 : IOOP_WRITE, io_start, 1, BLCKSZ);
3892 :
3893 975150 : pgBufferUsage.shared_blks_written++;
3894 :
3895 : /*
3896 : * Mark the buffer as clean (unless BM_JUST_DIRTIED has become set) and
3897 : * end the BM_IO_IN_PROGRESS state.
3898 : */
3899 975150 : TerminateBufferIO(buf, true, 0, true);
3900 :
3901 : TRACE_POSTGRESQL_BUFFER_FLUSH_DONE(BufTagGetForkNum(&buf->tag),
3902 : buf->tag.blockNum,
3903 : reln->smgr_rlocator.locator.spcOid,
3904 : reln->smgr_rlocator.locator.dbOid,
3905 : reln->smgr_rlocator.locator.relNumber);
3906 :
3907 : /* Pop the error context stack */
3908 975150 : error_context_stack = errcallback.previous;
3909 : }
3910 :
3911 : /*
3912 : * RelationGetNumberOfBlocksInFork
3913 : * Determines the current number of pages in the specified relation fork.
3914 : *
3915 : * Note that the accuracy of the result will depend on the details of the
3916 : * relation's storage. For builtin AMs it'll be accurate, but for external AMs
3917 : * it might not be.
3918 : */
3919 : BlockNumber
3920 3554226 : RelationGetNumberOfBlocksInFork(Relation relation, ForkNumber forkNum)
3921 : {
3922 3554226 : if (RELKIND_HAS_TABLE_AM(relation->rd_rel->relkind))
3923 : {
3924 : /*
3925 : * Not every table AM uses BLCKSZ wide fixed size blocks. Therefore
3926 : * tableam returns the size in bytes - but for the purpose of this
3927 : * routine, we want the number of blocks. Therefore divide, rounding
3928 : * up.
3929 : */
3930 : uint64 szbytes;
3931 :
3932 2533354 : szbytes = table_relation_size(relation, forkNum);
3933 :
3934 2533316 : return (szbytes + (BLCKSZ - 1)) / BLCKSZ;
3935 : }
3936 1020872 : else if (RELKIND_HAS_STORAGE(relation->rd_rel->relkind))
3937 : {
3938 1020872 : return smgrnblocks(RelationGetSmgr(relation), forkNum);
3939 : }
3940 : else
3941 : Assert(false);
3942 :
3943 0 : return 0; /* keep compiler quiet */
3944 : }
3945 :
3946 : /*
3947 : * BufferIsPermanent
3948 : * Determines whether a buffer will potentially still be around after
3949 : * a crash. Caller must hold a buffer pin.
3950 : */
3951 : bool
3952 18593484 : BufferIsPermanent(Buffer buffer)
3953 : {
3954 : BufferDesc *bufHdr;
3955 :
3956 : /* Local buffers are used only for temp relations. */
3957 18593484 : if (BufferIsLocal(buffer))
3958 1151540 : return false;
3959 :
3960 : /* Make sure we've got a real buffer, and that we hold a pin on it. */
3961 : Assert(BufferIsValid(buffer));
3962 : Assert(BufferIsPinned(buffer));
3963 :
3964 : /*
3965 : * BM_PERMANENT can't be changed while we hold a pin on the buffer, so we
3966 : * need not bother with the buffer header spinlock. Even if someone else
3967 : * changes the buffer header state while we're doing this, the state is
3968 : * changed atomically, so we'll read the old value or the new value, but
3969 : * not random garbage.
3970 : */
3971 17441944 : bufHdr = GetBufferDescriptor(buffer - 1);
3972 17441944 : return (pg_atomic_read_u32(&bufHdr->state) & BM_PERMANENT) != 0;
3973 : }
3974 :
3975 : /*
3976 : * BufferGetLSNAtomic
3977 : * Retrieves the LSN of the buffer atomically using a buffer header lock.
3978 : * This is necessary for some callers who may not have an exclusive lock
3979 : * on the buffer.
3980 : */
3981 : XLogRecPtr
3982 16468010 : BufferGetLSNAtomic(Buffer buffer)
3983 : {
3984 16468010 : char *page = BufferGetPage(buffer);
3985 : BufferDesc *bufHdr;
3986 : XLogRecPtr lsn;
3987 : uint32 buf_state;
3988 :
3989 : /*
3990 : * If we don't need locking for correctness, fastpath out.
3991 : */
3992 16468010 : if (!XLogHintBitIsNeeded() || BufferIsLocal(buffer))
3993 570904 : return PageGetLSN(page);
3994 :
3995 : /* Make sure we've got a real buffer, and that we hold a pin on it. */
3996 : Assert(BufferIsValid(buffer));
3997 : Assert(BufferIsPinned(buffer));
3998 :
3999 15897106 : bufHdr = GetBufferDescriptor(buffer - 1);
4000 15897106 : buf_state = LockBufHdr(bufHdr);
4001 15897106 : lsn = PageGetLSN(page);
4002 15897106 : UnlockBufHdr(bufHdr, buf_state);
4003 :
4004 15897106 : return lsn;
4005 : }
4006 :
4007 : /* ---------------------------------------------------------------------
4008 : * DropRelationBuffers
4009 : *
4010 : * This function removes from the buffer pool all the pages of the
4011 : * specified relation forks that have block numbers >= firstDelBlock.
4012 : * (In particular, with firstDelBlock = 0, all pages are removed.)
4013 : * Dirty pages are simply dropped, without bothering to write them
4014 : * out first. Therefore, this is NOT rollback-able, and so should be
4015 : * used only with extreme caution!
4016 : *
4017 : * Currently, this is called only from smgr.c when the underlying file
4018 : * is about to be deleted or truncated (firstDelBlock is needed for
4019 : * the truncation case). The data in the affected pages would therefore
4020 : * be deleted momentarily anyway, and there is no point in writing it.
4021 : * It is the responsibility of higher-level code to ensure that the
4022 : * deletion or truncation does not lose any data that could be needed
4023 : * later. It is also the responsibility of higher-level code to ensure
4024 : * that no other process could be trying to load more pages of the
4025 : * relation into buffers.
4026 : * --------------------------------------------------------------------
4027 : */
4028 : void
4029 1152 : DropRelationBuffers(SMgrRelation smgr_reln, ForkNumber *forkNum,
4030 : int nforks, BlockNumber *firstDelBlock)
4031 : {
4032 : int i;
4033 : int j;
4034 : RelFileLocatorBackend rlocator;
4035 : BlockNumber nForkBlock[MAX_FORKNUM];
4036 1152 : uint64 nBlocksToInvalidate = 0;
4037 :
4038 1152 : rlocator = smgr_reln->smgr_rlocator;
4039 :
4040 : /* If it's a local relation, it's localbuf.c's problem. */
4041 1152 : if (RelFileLocatorBackendIsTemp(rlocator))
4042 : {
4043 658 : if (rlocator.backend == MyProcNumber)
4044 : {
4045 1350 : for (j = 0; j < nforks; j++)
4046 692 : DropRelationLocalBuffers(rlocator.locator, forkNum[j],
4047 692 : firstDelBlock[j]);
4048 : }
4049 734 : return;
4050 : }
4051 :
4052 : /*
4053 : * To remove all the pages of the specified relation forks from the buffer
4054 : * pool, we need to scan the entire buffer pool but we can optimize it by
4055 : * finding the buffers from BufMapping table provided we know the exact
4056 : * size of each fork of the relation. The exact size is required to ensure
4057 : * that we don't leave any buffer for the relation being dropped as
4058 : * otherwise the background writer or checkpointer can lead to a PANIC
4059 : * error while flushing buffers corresponding to files that don't exist.
4060 : *
4061 : * To know the exact size, we rely on the size cached for each fork by us
4062 : * during recovery which limits the optimization to recovery and on
4063 : * standbys but we can easily extend it once we have shared cache for
4064 : * relation size.
4065 : *
4066 : * In recovery, we cache the value returned by the first lseek(SEEK_END)
4067 : * and the future writes keeps the cached value up-to-date. See
4068 : * smgrextend. It is possible that the value of the first lseek is smaller
4069 : * than the actual number of existing blocks in the file due to buggy
4070 : * Linux kernels that might not have accounted for the recent write. But
4071 : * that should be fine because there must not be any buffers after that
4072 : * file size.
4073 : */
4074 676 : for (i = 0; i < nforks; i++)
4075 : {
4076 : /* Get the number of blocks for a relation's fork */
4077 578 : nForkBlock[i] = smgrnblocks_cached(smgr_reln, forkNum[i]);
4078 :
4079 578 : if (nForkBlock[i] == InvalidBlockNumber)
4080 : {
4081 396 : nBlocksToInvalidate = InvalidBlockNumber;
4082 396 : break;
4083 : }
4084 :
4085 : /* calculate the number of blocks to be invalidated */
4086 182 : nBlocksToInvalidate += (nForkBlock[i] - firstDelBlock[i]);
4087 : }
4088 :
4089 : /*
4090 : * We apply the optimization iff the total number of blocks to invalidate
4091 : * is below the BUF_DROP_FULL_SCAN_THRESHOLD.
4092 : */
4093 494 : if (BlockNumberIsValid(nBlocksToInvalidate) &&
4094 98 : nBlocksToInvalidate < BUF_DROP_FULL_SCAN_THRESHOLD)
4095 : {
4096 208 : for (j = 0; j < nforks; j++)
4097 132 : FindAndDropRelationBuffers(rlocator.locator, forkNum[j],
4098 132 : nForkBlock[j], firstDelBlock[j]);
4099 76 : return;
4100 : }
4101 :
4102 5515938 : for (i = 0; i < NBuffers; i++)
4103 : {
4104 5515520 : BufferDesc *bufHdr = GetBufferDescriptor(i);
4105 : uint32 buf_state;
4106 :
4107 : /*
4108 : * We can make this a tad faster by prechecking the buffer tag before
4109 : * we attempt to lock the buffer; this saves a lot of lock
4110 : * acquisitions in typical cases. It should be safe because the
4111 : * caller must have AccessExclusiveLock on the relation, or some other
4112 : * reason to be certain that no one is loading new pages of the rel
4113 : * into the buffer pool. (Otherwise we might well miss such pages
4114 : * entirely.) Therefore, while the tag might be changing while we
4115 : * look at it, it can't be changing *to* a value we care about, only
4116 : * *away* from such a value. So false negatives are impossible, and
4117 : * false positives are safe because we'll recheck after getting the
4118 : * buffer lock.
4119 : *
4120 : * We could check forkNum and blockNum as well as the rlocator, but
4121 : * the incremental win from doing so seems small.
4122 : */
4123 5515520 : if (!BufTagMatchesRelFileLocator(&bufHdr->tag, &rlocator.locator))
4124 5502356 : continue;
4125 :
4126 13164 : buf_state = LockBufHdr(bufHdr);
4127 :
4128 34440 : for (j = 0; j < nforks; j++)
4129 : {
4130 24066 : if (BufTagMatchesRelFileLocator(&bufHdr->tag, &rlocator.locator) &&
4131 24066 : BufTagGetForkNum(&bufHdr->tag) == forkNum[j] &&
4132 12990 : bufHdr->tag.blockNum >= firstDelBlock[j])
4133 : {
4134 2790 : InvalidateBuffer(bufHdr); /* releases spinlock */
4135 2790 : break;
4136 : }
4137 : }
4138 13164 : if (j >= nforks)
4139 10374 : UnlockBufHdr(bufHdr, buf_state);
4140 : }
4141 : }
4142 :
4143 : /* ---------------------------------------------------------------------
4144 : * DropRelationsAllBuffers
4145 : *
4146 : * This function removes from the buffer pool all the pages of all
4147 : * forks of the specified relations. It's equivalent to calling
4148 : * DropRelationBuffers once per fork per relation with firstDelBlock = 0.
4149 : * --------------------------------------------------------------------
4150 : */
4151 : void
4152 26072 : DropRelationsAllBuffers(SMgrRelation *smgr_reln, int nlocators)
4153 : {
4154 : int i;
4155 26072 : int n = 0;
4156 : SMgrRelation *rels;
4157 : BlockNumber (*block)[MAX_FORKNUM + 1];
4158 26072 : uint64 nBlocksToInvalidate = 0;
4159 : RelFileLocator *locators;
4160 26072 : bool cached = true;
4161 : bool use_bsearch;
4162 :
4163 26072 : if (nlocators == 0)
4164 0 : return;
4165 :
4166 26072 : rels = palloc(sizeof(SMgrRelation) * nlocators); /* non-local relations */
4167 :
4168 : /* If it's a local relation, it's localbuf.c's problem. */
4169 115196 : for (i = 0; i < nlocators; i++)
4170 : {
4171 89124 : if (RelFileLocatorBackendIsTemp(smgr_reln[i]->smgr_rlocator))
4172 : {
4173 6064 : if (smgr_reln[i]->smgr_rlocator.backend == MyProcNumber)
4174 6064 : DropRelationAllLocalBuffers(smgr_reln[i]->smgr_rlocator.locator);
4175 : }
4176 : else
4177 83060 : rels[n++] = smgr_reln[i];
4178 : }
4179 :
4180 : /*
4181 : * If there are no non-local relations, then we're done. Release the
4182 : * memory and return.
4183 : */
4184 26072 : if (n == 0)
4185 : {
4186 1516 : pfree(rels);
4187 1516 : return;
4188 : }
4189 :
4190 : /*
4191 : * This is used to remember the number of blocks for all the relations
4192 : * forks.
4193 : */
4194 : block = (BlockNumber (*)[MAX_FORKNUM + 1])
4195 24556 : palloc(sizeof(BlockNumber) * n * (MAX_FORKNUM + 1));
4196 :
4197 : /*
4198 : * We can avoid scanning the entire buffer pool if we know the exact size
4199 : * of each of the given relation forks. See DropRelationBuffers.
4200 : */
4201 51746 : for (i = 0; i < n && cached; i++)
4202 : {
4203 44312 : for (int j = 0; j <= MAX_FORKNUM; j++)
4204 : {
4205 : /* Get the number of blocks for a relation's fork. */
4206 40054 : block[i][j] = smgrnblocks_cached(rels[i], j);
4207 :
4208 : /* We need to only consider the relation forks that exists. */
4209 40054 : if (block[i][j] == InvalidBlockNumber)
4210 : {
4211 35424 : if (!smgrexists(rels[i], j))
4212 12492 : continue;
4213 22932 : cached = false;
4214 22932 : break;
4215 : }
4216 :
4217 : /* calculate the total number of blocks to be invalidated */
4218 4630 : nBlocksToInvalidate += block[i][j];
4219 : }
4220 : }
4221 :
4222 : /*
4223 : * We apply the optimization iff the total number of blocks to invalidate
4224 : * is below the BUF_DROP_FULL_SCAN_THRESHOLD.
4225 : */
4226 24556 : if (cached && nBlocksToInvalidate < BUF_DROP_FULL_SCAN_THRESHOLD)
4227 : {
4228 2658 : for (i = 0; i < n; i++)
4229 : {
4230 7300 : for (int j = 0; j <= MAX_FORKNUM; j++)
4231 : {
4232 : /* ignore relation forks that doesn't exist */
4233 5840 : if (!BlockNumberIsValid(block[i][j]))
4234 4362 : continue;
4235 :
4236 : /* drop all the buffers for a particular relation fork */
4237 1478 : FindAndDropRelationBuffers(rels[i]->smgr_rlocator.locator,
4238 1478 : j, block[i][j], 0);
4239 : }
4240 : }
4241 :
4242 1198 : pfree(block);
4243 1198 : pfree(rels);
4244 1198 : return;
4245 : }
4246 :
4247 23358 : pfree(block);
4248 23358 : locators = palloc(sizeof(RelFileLocator) * n); /* non-local relations */
4249 104958 : for (i = 0; i < n; i++)
4250 81600 : locators[i] = rels[i]->smgr_rlocator.locator;
4251 :
4252 : /*
4253 : * For low number of relations to drop just use a simple walk through, to
4254 : * save the bsearch overhead. The threshold to use is rather a guess than
4255 : * an exactly determined value, as it depends on many factors (CPU and RAM
4256 : * speeds, amount of shared buffers etc.).
4257 : */
4258 23358 : use_bsearch = n > RELS_BSEARCH_THRESHOLD;
4259 :
4260 : /* sort the list of rlocators if necessary */
4261 23358 : if (use_bsearch)
4262 334 : qsort(locators, n, sizeof(RelFileLocator), rlocator_comparator);
4263 :
4264 253355582 : for (i = 0; i < NBuffers; i++)
4265 : {
4266 253332224 : RelFileLocator *rlocator = NULL;
4267 253332224 : BufferDesc *bufHdr = GetBufferDescriptor(i);
4268 : uint32 buf_state;
4269 :
4270 : /*
4271 : * As in DropRelationBuffers, an unlocked precheck should be safe and
4272 : * saves some cycles.
4273 : */
4274 :
4275 253332224 : if (!use_bsearch)
4276 : {
4277 : int j;
4278 :
4279 1017298594 : for (j = 0; j < n; j++)
4280 : {
4281 767655230 : if (BufTagMatchesRelFileLocator(&bufHdr->tag, &locators[j]))
4282 : {
4283 167324 : rlocator = &locators[j];
4284 167324 : break;
4285 : }
4286 : }
4287 : }
4288 : else
4289 : {
4290 : RelFileLocator locator;
4291 :
4292 3521536 : locator = BufTagGetRelFileLocator(&bufHdr->tag);
4293 3521536 : rlocator = bsearch(&locator,
4294 : locators, n, sizeof(RelFileLocator),
4295 : rlocator_comparator);
4296 : }
4297 :
4298 : /* buffer doesn't belong to any of the given relfilelocators; skip it */
4299 253332224 : if (rlocator == NULL)
4300 253161354 : continue;
4301 :
4302 170870 : buf_state = LockBufHdr(bufHdr);
4303 170870 : if (BufTagMatchesRelFileLocator(&bufHdr->tag, rlocator))
4304 170870 : InvalidateBuffer(bufHdr); /* releases spinlock */
4305 : else
4306 0 : UnlockBufHdr(bufHdr, buf_state);
4307 : }
4308 :
4309 23358 : pfree(locators);
4310 23358 : pfree(rels);
4311 : }
4312 :
4313 : /* ---------------------------------------------------------------------
4314 : * FindAndDropRelationBuffers
4315 : *
4316 : * This function performs look up in BufMapping table and removes from the
4317 : * buffer pool all the pages of the specified relation fork that has block
4318 : * number >= firstDelBlock. (In particular, with firstDelBlock = 0, all
4319 : * pages are removed.)
4320 : * --------------------------------------------------------------------
4321 : */
4322 : static void
4323 1610 : FindAndDropRelationBuffers(RelFileLocator rlocator, ForkNumber forkNum,
4324 : BlockNumber nForkBlock,
4325 : BlockNumber firstDelBlock)
4326 : {
4327 : BlockNumber curBlock;
4328 :
4329 3892 : for (curBlock = firstDelBlock; curBlock < nForkBlock; curBlock++)
4330 : {
4331 : uint32 bufHash; /* hash value for tag */
4332 : BufferTag bufTag; /* identity of requested block */
4333 : LWLock *bufPartitionLock; /* buffer partition lock for it */
4334 : int buf_id;
4335 : BufferDesc *bufHdr;
4336 : uint32 buf_state;
4337 :
4338 : /* create a tag so we can lookup the buffer */
4339 2282 : InitBufferTag(&bufTag, &rlocator, forkNum, curBlock);
4340 :
4341 : /* determine its hash code and partition lock ID */
4342 2282 : bufHash = BufTableHashCode(&bufTag);
4343 2282 : bufPartitionLock = BufMappingPartitionLock(bufHash);
4344 :
4345 : /* Check that it is in the buffer pool. If not, do nothing. */
4346 2282 : LWLockAcquire(bufPartitionLock, LW_SHARED);
4347 2282 : buf_id = BufTableLookup(&bufTag, bufHash);
4348 2282 : LWLockRelease(bufPartitionLock);
4349 :
4350 2282 : if (buf_id < 0)
4351 264 : continue;
4352 :
4353 2018 : bufHdr = GetBufferDescriptor(buf_id);
4354 :
4355 : /*
4356 : * We need to lock the buffer header and recheck if the buffer is
4357 : * still associated with the same block because the buffer could be
4358 : * evicted by some other backend loading blocks for a different
4359 : * relation after we release lock on the BufMapping table.
4360 : */
4361 2018 : buf_state = LockBufHdr(bufHdr);
4362 :
4363 4036 : if (BufTagMatchesRelFileLocator(&bufHdr->tag, &rlocator) &&
4364 2018 : BufTagGetForkNum(&bufHdr->tag) == forkNum &&
4365 2018 : bufHdr->tag.blockNum >= firstDelBlock)
4366 2018 : InvalidateBuffer(bufHdr); /* releases spinlock */
4367 : else
4368 0 : UnlockBufHdr(bufHdr, buf_state);
4369 : }
4370 1610 : }
4371 :
4372 : /* ---------------------------------------------------------------------
4373 : * DropDatabaseBuffers
4374 : *
4375 : * This function removes all the buffers in the buffer cache for a
4376 : * particular database. Dirty pages are simply dropped, without
4377 : * bothering to write them out first. This is used when we destroy a
4378 : * database, to avoid trying to flush data to disk when the directory
4379 : * tree no longer exists. Implementation is pretty similar to
4380 : * DropRelationBuffers() which is for destroying just one relation.
4381 : * --------------------------------------------------------------------
4382 : */
4383 : void
4384 116 : DropDatabaseBuffers(Oid dbid)
4385 : {
4386 : int i;
4387 :
4388 : /*
4389 : * We needn't consider local buffers, since by assumption the target
4390 : * database isn't our own.
4391 : */
4392 :
4393 665204 : for (i = 0; i < NBuffers; i++)
4394 : {
4395 665088 : BufferDesc *bufHdr = GetBufferDescriptor(i);
4396 : uint32 buf_state;
4397 :
4398 : /*
4399 : * As in DropRelationBuffers, an unlocked precheck should be safe and
4400 : * saves some cycles.
4401 : */
4402 665088 : if (bufHdr->tag.dbOid != dbid)
4403 640528 : continue;
4404 :
4405 24560 : buf_state = LockBufHdr(bufHdr);
4406 24560 : if (bufHdr->tag.dbOid == dbid)
4407 24560 : InvalidateBuffer(bufHdr); /* releases spinlock */
4408 : else
4409 0 : UnlockBufHdr(bufHdr, buf_state);
4410 : }
4411 116 : }
4412 :
4413 : /* ---------------------------------------------------------------------
4414 : * FlushRelationBuffers
4415 : *
4416 : * This function writes all dirty pages of a relation out to disk
4417 : * (or more accurately, out to kernel disk buffers), ensuring that the
4418 : * kernel has an up-to-date view of the relation.
4419 : *
4420 : * Generally, the caller should be holding AccessExclusiveLock on the
4421 : * target relation to ensure that no other backend is busy dirtying
4422 : * more blocks of the relation; the effects can't be expected to last
4423 : * after the lock is released.
4424 : *
4425 : * XXX currently it sequentially searches the buffer pool, should be
4426 : * changed to more clever ways of searching. This routine is not
4427 : * used in any performance-critical code paths, so it's not worth
4428 : * adding additional overhead to normal paths to make it go faster.
4429 : * --------------------------------------------------------------------
4430 : */
4431 : void
4432 276 : FlushRelationBuffers(Relation rel)
4433 : {
4434 : int i;
4435 : BufferDesc *bufHdr;
4436 276 : SMgrRelation srel = RelationGetSmgr(rel);
4437 :
4438 276 : if (RelationUsesLocalBuffers(rel))
4439 : {
4440 1818 : for (i = 0; i < NLocBuffer; i++)
4441 : {
4442 : uint32 buf_state;
4443 : instr_time io_start;
4444 :
4445 1800 : bufHdr = GetLocalBufferDescriptor(i);
4446 1800 : if (BufTagMatchesRelFileLocator(&bufHdr->tag, &rel->rd_locator) &&
4447 600 : ((buf_state = pg_atomic_read_u32(&bufHdr->state)) &
4448 : (BM_VALID | BM_DIRTY)) == (BM_VALID | BM_DIRTY))
4449 : {
4450 : ErrorContextCallback errcallback;
4451 : Page localpage;
4452 :
4453 594 : localpage = (char *) LocalBufHdrGetBlock(bufHdr);
4454 :
4455 : /* Setup error traceback support for ereport() */
4456 594 : errcallback.callback = local_buffer_write_error_callback;
4457 594 : errcallback.arg = bufHdr;
4458 594 : errcallback.previous = error_context_stack;
4459 594 : error_context_stack = &errcallback;
4460 :
4461 594 : PageSetChecksumInplace(localpage, bufHdr->tag.blockNum);
4462 :
4463 594 : io_start = pgstat_prepare_io_time(track_io_timing);
4464 :
4465 594 : smgrwrite(srel,
4466 594 : BufTagGetForkNum(&bufHdr->tag),
4467 : bufHdr->tag.blockNum,
4468 : localpage,
4469 : false);
4470 :
4471 594 : pgstat_count_io_op_time(IOOBJECT_TEMP_RELATION,
4472 : IOCONTEXT_NORMAL, IOOP_WRITE,
4473 : io_start, 1, BLCKSZ);
4474 :
4475 594 : buf_state &= ~(BM_DIRTY | BM_JUST_DIRTIED);
4476 594 : pg_atomic_unlocked_write_u32(&bufHdr->state, buf_state);
4477 :
4478 594 : pgBufferUsage.local_blks_written++;
4479 :
4480 : /* Pop the error context stack */
4481 594 : error_context_stack = errcallback.previous;
4482 : }
4483 : }
4484 :
4485 18 : return;
4486 : }
4487 :
4488 3024386 : for (i = 0; i < NBuffers; i++)
4489 : {
4490 : uint32 buf_state;
4491 :
4492 3024128 : bufHdr = GetBufferDescriptor(i);
4493 :
4494 : /*
4495 : * As in DropRelationBuffers, an unlocked precheck should be safe and
4496 : * saves some cycles.
4497 : */
4498 3024128 : if (!BufTagMatchesRelFileLocator(&bufHdr->tag, &rel->rd_locator))
4499 3023684 : continue;
4500 :
4501 : /* Make sure we can handle the pin */
4502 444 : ReservePrivateRefCountEntry();
4503 444 : ResourceOwnerEnlarge(CurrentResourceOwner);
4504 :
4505 444 : buf_state = LockBufHdr(bufHdr);
4506 444 : if (BufTagMatchesRelFileLocator(&bufHdr->tag, &rel->rd_locator) &&
4507 444 : (buf_state & (BM_VALID | BM_DIRTY)) == (BM_VALID | BM_DIRTY))
4508 : {
4509 358 : PinBuffer_Locked(bufHdr);
4510 358 : LWLockAcquire(BufferDescriptorGetContentLock(bufHdr), LW_SHARED);
4511 358 : FlushBuffer(bufHdr, srel, IOOBJECT_RELATION, IOCONTEXT_NORMAL);
4512 358 : LWLockRelease(BufferDescriptorGetContentLock(bufHdr));
4513 358 : UnpinBuffer(bufHdr);
4514 : }
4515 : else
4516 86 : UnlockBufHdr(bufHdr, buf_state);
4517 : }
4518 : }
4519 :
4520 : /* ---------------------------------------------------------------------
4521 : * FlushRelationsAllBuffers
4522 : *
4523 : * This function flushes out of the buffer pool all the pages of all
4524 : * forks of the specified smgr relations. It's equivalent to calling
4525 : * FlushRelationBuffers once per relation. The relations are assumed not
4526 : * to use local buffers.
4527 : * --------------------------------------------------------------------
4528 : */
4529 : void
4530 20 : FlushRelationsAllBuffers(SMgrRelation *smgrs, int nrels)
4531 : {
4532 : int i;
4533 : SMgrSortArray *srels;
4534 : bool use_bsearch;
4535 :
4536 20 : if (nrels == 0)
4537 0 : return;
4538 :
4539 : /* fill-in array for qsort */
4540 20 : srels = palloc(sizeof(SMgrSortArray) * nrels);
4541 :
4542 40 : for (i = 0; i < nrels; i++)
4543 : {
4544 : Assert(!RelFileLocatorBackendIsTemp(smgrs[i]->smgr_rlocator));
4545 :
4546 20 : srels[i].rlocator = smgrs[i]->smgr_rlocator.locator;
4547 20 : srels[i].srel = smgrs[i];
4548 : }
4549 :
4550 : /*
4551 : * Save the bsearch overhead for low number of relations to sync. See
4552 : * DropRelationsAllBuffers for details.
4553 : */
4554 20 : use_bsearch = nrels > RELS_BSEARCH_THRESHOLD;
4555 :
4556 : /* sort the list of SMgrRelations if necessary */
4557 20 : if (use_bsearch)
4558 0 : qsort(srels, nrels, sizeof(SMgrSortArray), rlocator_comparator);
4559 :
4560 327700 : for (i = 0; i < NBuffers; i++)
4561 : {
4562 327680 : SMgrSortArray *srelent = NULL;
4563 327680 : BufferDesc *bufHdr = GetBufferDescriptor(i);
4564 : uint32 buf_state;
4565 :
4566 : /*
4567 : * As in DropRelationBuffers, an unlocked precheck should be safe and
4568 : * saves some cycles.
4569 : */
4570 :
4571 327680 : if (!use_bsearch)
4572 : {
4573 : int j;
4574 :
4575 647724 : for (j = 0; j < nrels; j++)
4576 : {
4577 327680 : if (BufTagMatchesRelFileLocator(&bufHdr->tag, &srels[j].rlocator))
4578 : {
4579 7636 : srelent = &srels[j];
4580 7636 : break;
4581 : }
4582 : }
4583 : }
4584 : else
4585 : {
4586 : RelFileLocator rlocator;
4587 :
4588 0 : rlocator = BufTagGetRelFileLocator(&bufHdr->tag);
4589 0 : srelent = bsearch(&rlocator,
4590 : srels, nrels, sizeof(SMgrSortArray),
4591 : rlocator_comparator);
4592 : }
4593 :
4594 : /* buffer doesn't belong to any of the given relfilelocators; skip it */
4595 327680 : if (srelent == NULL)
4596 320044 : continue;
4597 :
4598 : /* Make sure we can handle the pin */
4599 7636 : ReservePrivateRefCountEntry();
4600 7636 : ResourceOwnerEnlarge(CurrentResourceOwner);
4601 :
4602 7636 : buf_state = LockBufHdr(bufHdr);
4603 7636 : if (BufTagMatchesRelFileLocator(&bufHdr->tag, &srelent->rlocator) &&
4604 7636 : (buf_state & (BM_VALID | BM_DIRTY)) == (BM_VALID | BM_DIRTY))
4605 : {
4606 6734 : PinBuffer_Locked(bufHdr);
4607 6734 : LWLockAcquire(BufferDescriptorGetContentLock(bufHdr), LW_SHARED);
4608 6734 : FlushBuffer(bufHdr, srelent->srel, IOOBJECT_RELATION, IOCONTEXT_NORMAL);
4609 6734 : LWLockRelease(BufferDescriptorGetContentLock(bufHdr));
4610 6734 : UnpinBuffer(bufHdr);
4611 : }
4612 : else
4613 902 : UnlockBufHdr(bufHdr, buf_state);
4614 : }
4615 :
4616 20 : pfree(srels);
4617 : }
4618 :
4619 : /* ---------------------------------------------------------------------
4620 : * RelationCopyStorageUsingBuffer
4621 : *
4622 : * Copy fork's data using bufmgr. Same as RelationCopyStorage but instead
4623 : * of using smgrread and smgrextend this will copy using bufmgr APIs.
4624 : *
4625 : * Refer comments atop CreateAndCopyRelationData() for details about
4626 : * 'permanent' parameter.
4627 : * --------------------------------------------------------------------
4628 : */
4629 : static void
4630 131156 : RelationCopyStorageUsingBuffer(RelFileLocator srclocator,
4631 : RelFileLocator dstlocator,
4632 : ForkNumber forkNum, bool permanent)
4633 : {
4634 : Buffer srcBuf;
4635 : Buffer dstBuf;
4636 : Page srcPage;
4637 : Page dstPage;
4638 : bool use_wal;
4639 : BlockNumber nblocks;
4640 : BlockNumber blkno;
4641 : PGIOAlignedBlock buf;
4642 : BufferAccessStrategy bstrategy_src;
4643 : BufferAccessStrategy bstrategy_dst;
4644 : BlockRangeReadStreamPrivate p;
4645 : ReadStream *src_stream;
4646 : SMgrRelation src_smgr;
4647 :
4648 : /*
4649 : * In general, we want to write WAL whenever wal_level > 'minimal', but we
4650 : * can skip it when copying any fork of an unlogged relation other than
4651 : * the init fork.
4652 : */
4653 131156 : use_wal = XLogIsNeeded() && (permanent || forkNum == INIT_FORKNUM);
4654 :
4655 : /* Get number of blocks in the source relation. */
4656 131156 : nblocks = smgrnblocks(smgropen(srclocator, INVALID_PROC_NUMBER),
4657 : forkNum);
4658 :
4659 : /* Nothing to copy; just return. */
4660 131156 : if (nblocks == 0)
4661 22878 : return;
4662 :
4663 : /*
4664 : * Bulk extend the destination relation of the same size as the source
4665 : * relation before starting to copy block by block.
4666 : */
4667 108278 : memset(buf.data, 0, BLCKSZ);
4668 108278 : smgrextend(smgropen(dstlocator, INVALID_PROC_NUMBER), forkNum, nblocks - 1,
4669 : buf.data, true);
4670 :
4671 : /* This is a bulk operation, so use buffer access strategies. */
4672 108278 : bstrategy_src = GetAccessStrategy(BAS_BULKREAD);
4673 108278 : bstrategy_dst = GetAccessStrategy(BAS_BULKWRITE);
4674 :
4675 : /* Initialize streaming read */
4676 108278 : p.current_blocknum = 0;
4677 108278 : p.last_exclusive = nblocks;
4678 108278 : src_smgr = smgropen(srclocator, INVALID_PROC_NUMBER);
4679 108278 : src_stream = read_stream_begin_smgr_relation(READ_STREAM_FULL,
4680 : bstrategy_src,
4681 : src_smgr,
4682 : permanent ? RELPERSISTENCE_PERMANENT : RELPERSISTENCE_UNLOGGED,
4683 : forkNum,
4684 : block_range_read_stream_cb,
4685 : &p,
4686 : 0);
4687 :
4688 : /* Iterate over each block of the source relation file. */
4689 519006 : for (blkno = 0; blkno < nblocks; blkno++)
4690 : {
4691 410728 : CHECK_FOR_INTERRUPTS();
4692 :
4693 : /* Read block from source relation. */
4694 410728 : srcBuf = read_stream_next_buffer(src_stream, NULL);
4695 410728 : LockBuffer(srcBuf, BUFFER_LOCK_SHARE);
4696 410728 : srcPage = BufferGetPage(srcBuf);
4697 :
4698 410728 : dstBuf = ReadBufferWithoutRelcache(dstlocator, forkNum,
4699 : BufferGetBlockNumber(srcBuf),
4700 : RBM_ZERO_AND_LOCK, bstrategy_dst,
4701 : permanent);
4702 410728 : dstPage = BufferGetPage(dstBuf);
4703 :
4704 410728 : START_CRIT_SECTION();
4705 :
4706 : /* Copy page data from the source to the destination. */
4707 410728 : memcpy(dstPage, srcPage, BLCKSZ);
4708 410728 : MarkBufferDirty(dstBuf);
4709 :
4710 : /* WAL-log the copied page. */
4711 410728 : if (use_wal)
4712 237170 : log_newpage_buffer(dstBuf, true);
4713 :
4714 410728 : END_CRIT_SECTION();
4715 :
4716 410728 : UnlockReleaseBuffer(dstBuf);
4717 410728 : UnlockReleaseBuffer(srcBuf);
4718 : }
4719 : Assert(read_stream_next_buffer(src_stream, NULL) == InvalidBuffer);
4720 108278 : read_stream_end(src_stream);
4721 :
4722 108278 : FreeAccessStrategy(bstrategy_src);
4723 108278 : FreeAccessStrategy(bstrategy_dst);
4724 : }
4725 :
4726 : /* ---------------------------------------------------------------------
4727 : * CreateAndCopyRelationData
4728 : *
4729 : * Create destination relation storage and copy all forks from the
4730 : * source relation to the destination.
4731 : *
4732 : * Pass permanent as true for permanent relations and false for
4733 : * unlogged relations. Currently this API is not supported for
4734 : * temporary relations.
4735 : * --------------------------------------------------------------------
4736 : */
4737 : void
4738 98592 : CreateAndCopyRelationData(RelFileLocator src_rlocator,
4739 : RelFileLocator dst_rlocator, bool permanent)
4740 : {
4741 : char relpersistence;
4742 : SMgrRelation src_rel;
4743 : SMgrRelation dst_rel;
4744 :
4745 : /* Set the relpersistence. */
4746 98592 : relpersistence = permanent ?
4747 : RELPERSISTENCE_PERMANENT : RELPERSISTENCE_UNLOGGED;
4748 :
4749 98592 : src_rel = smgropen(src_rlocator, INVALID_PROC_NUMBER);
4750 98592 : dst_rel = smgropen(dst_rlocator, INVALID_PROC_NUMBER);
4751 :
4752 : /*
4753 : * Create and copy all forks of the relation. During create database we
4754 : * have a separate cleanup mechanism which deletes complete database
4755 : * directory. Therefore, each individual relation doesn't need to be
4756 : * registered for cleanup.
4757 : */
4758 98592 : RelationCreateStorage(dst_rlocator, relpersistence, false);
4759 :
4760 : /* copy main fork. */
4761 98592 : RelationCopyStorageUsingBuffer(src_rlocator, dst_rlocator, MAIN_FORKNUM,
4762 : permanent);
4763 :
4764 : /* copy those extra forks that exist */
4765 394368 : for (ForkNumber forkNum = MAIN_FORKNUM + 1;
4766 295776 : forkNum <= MAX_FORKNUM; forkNum++)
4767 : {
4768 295776 : if (smgrexists(src_rel, forkNum))
4769 : {
4770 32564 : smgrcreate(dst_rel, forkNum, false);
4771 :
4772 : /*
4773 : * WAL log creation if the relation is persistent, or this is the
4774 : * init fork of an unlogged relation.
4775 : */
4776 32564 : if (permanent || forkNum == INIT_FORKNUM)
4777 32564 : log_smgrcreate(&dst_rlocator, forkNum);
4778 :
4779 : /* Copy a fork's data, block by block. */
4780 32564 : RelationCopyStorageUsingBuffer(src_rlocator, dst_rlocator, forkNum,
4781 : permanent);
4782 : }
4783 : }
4784 98592 : }
4785 :
4786 : /* ---------------------------------------------------------------------
4787 : * FlushDatabaseBuffers
4788 : *
4789 : * This function writes all dirty pages of a database out to disk
4790 : * (or more accurately, out to kernel disk buffers), ensuring that the
4791 : * kernel has an up-to-date view of the database.
4792 : *
4793 : * Generally, the caller should be holding an appropriate lock to ensure
4794 : * no other backend is active in the target database; otherwise more
4795 : * pages could get dirtied.
4796 : *
4797 : * Note we don't worry about flushing any pages of temporary relations.
4798 : * It's assumed these wouldn't be interesting.
4799 : * --------------------------------------------------------------------
4800 : */
4801 : void
4802 8 : FlushDatabaseBuffers(Oid dbid)
4803 : {
4804 : int i;
4805 : BufferDesc *bufHdr;
4806 :
4807 1032 : for (i = 0; i < NBuffers; i++)
4808 : {
4809 : uint32 buf_state;
4810 :
4811 1024 : bufHdr = GetBufferDescriptor(i);
4812 :
4813 : /*
4814 : * As in DropRelationBuffers, an unlocked precheck should be safe and
4815 : * saves some cycles.
4816 : */
4817 1024 : if (bufHdr->tag.dbOid != dbid)
4818 700 : continue;
4819 :
4820 : /* Make sure we can handle the pin */
4821 324 : ReservePrivateRefCountEntry();
4822 324 : ResourceOwnerEnlarge(CurrentResourceOwner);
4823 :
4824 324 : buf_state = LockBufHdr(bufHdr);
4825 324 : if (bufHdr->tag.dbOid == dbid &&
4826 324 : (buf_state & (BM_VALID | BM_DIRTY)) == (BM_VALID | BM_DIRTY))
4827 : {
4828 54 : PinBuffer_Locked(bufHdr);
4829 54 : LWLockAcquire(BufferDescriptorGetContentLock(bufHdr), LW_SHARED);
4830 54 : FlushBuffer(bufHdr, NULL, IOOBJECT_RELATION, IOCONTEXT_NORMAL);
4831 54 : LWLockRelease(BufferDescriptorGetContentLock(bufHdr));
4832 54 : UnpinBuffer(bufHdr);
4833 : }
4834 : else
4835 270 : UnlockBufHdr(bufHdr, buf_state);
4836 : }
4837 8 : }
4838 :
4839 : /*
4840 : * Flush a previously, shared or exclusively, locked and pinned buffer to the
4841 : * OS.
4842 : */
4843 : void
4844 58 : FlushOneBuffer(Buffer buffer)
4845 : {
4846 : BufferDesc *bufHdr;
4847 :
4848 : /* currently not needed, but no fundamental reason not to support */
4849 : Assert(!BufferIsLocal(buffer));
4850 :
4851 : Assert(BufferIsPinned(buffer));
4852 :
4853 58 : bufHdr = GetBufferDescriptor(buffer - 1);
4854 :
4855 : Assert(LWLockHeldByMe(BufferDescriptorGetContentLock(bufHdr)));
4856 :
4857 58 : FlushBuffer(bufHdr, NULL, IOOBJECT_RELATION, IOCONTEXT_NORMAL);
4858 58 : }
4859 :
4860 : /*
4861 : * ReleaseBuffer -- release the pin on a buffer
4862 : */
4863 : void
4864 113328198 : ReleaseBuffer(Buffer buffer)
4865 : {
4866 113328198 : if (!BufferIsValid(buffer))
4867 0 : elog(ERROR, "bad buffer ID: %d", buffer);
4868 :
4869 113328198 : if (BufferIsLocal(buffer))
4870 2832394 : UnpinLocalBuffer(buffer);
4871 : else
4872 110495804 : UnpinBuffer(GetBufferDescriptor(buffer - 1));
4873 113328198 : }
4874 :
4875 : /*
4876 : * UnlockReleaseBuffer -- release the content lock and pin on a buffer
4877 : *
4878 : * This is just a shorthand for a common combination.
4879 : */
4880 : void
4881 35617164 : UnlockReleaseBuffer(Buffer buffer)
4882 : {
4883 35617164 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
4884 35617164 : ReleaseBuffer(buffer);
4885 35617164 : }
4886 :
4887 : /*
4888 : * IncrBufferRefCount
4889 : * Increment the pin count on a buffer that we have *already* pinned
4890 : * at least once.
4891 : *
4892 : * This function cannot be used on a buffer we do not have pinned,
4893 : * because it doesn't change the shared buffer state.
4894 : */
4895 : void
4896 20481952 : IncrBufferRefCount(Buffer buffer)
4897 : {
4898 : Assert(BufferIsPinned(buffer));
4899 20481952 : ResourceOwnerEnlarge(CurrentResourceOwner);
4900 20481952 : if (BufferIsLocal(buffer))
4901 697954 : LocalRefCount[-buffer - 1]++;
4902 : else
4903 : {
4904 : PrivateRefCountEntry *ref;
4905 :
4906 19783998 : ref = GetPrivateRefCountEntry(buffer, true);
4907 : Assert(ref != NULL);
4908 19783998 : ref->refcount++;
4909 : }
4910 20481952 : ResourceOwnerRememberBuffer(CurrentResourceOwner, buffer);
4911 20481952 : }
4912 :
4913 : /*
4914 : * MarkBufferDirtyHint
4915 : *
4916 : * Mark a buffer dirty for non-critical changes.
4917 : *
4918 : * This is essentially the same as MarkBufferDirty, except:
4919 : *
4920 : * 1. The caller does not write WAL; so if checksums are enabled, we may need
4921 : * to write an XLOG_FPI_FOR_HINT WAL record to protect against torn pages.
4922 : * 2. The caller might have only share-lock instead of exclusive-lock on the
4923 : * buffer's content lock.
4924 : * 3. This function does not guarantee that the buffer is always marked dirty
4925 : * (due to a race condition), so it cannot be used for important changes.
4926 : */
4927 : void
4928 19451728 : MarkBufferDirtyHint(Buffer buffer, bool buffer_std)
4929 : {
4930 : BufferDesc *bufHdr;
4931 19451728 : Page page = BufferGetPage(buffer);
4932 :
4933 19451728 : if (!BufferIsValid(buffer))
4934 0 : elog(ERROR, "bad buffer ID: %d", buffer);
4935 :
4936 19451728 : if (BufferIsLocal(buffer))
4937 : {
4938 1163642 : MarkLocalBufferDirty(buffer);
4939 1163642 : return;
4940 : }
4941 :
4942 18288086 : bufHdr = GetBufferDescriptor(buffer - 1);
4943 :
4944 : Assert(GetPrivateRefCount(buffer) > 0);
4945 : /* here, either share or exclusive lock is OK */
4946 : Assert(LWLockHeldByMe(BufferDescriptorGetContentLock(bufHdr)));
4947 :
4948 : /*
4949 : * This routine might get called many times on the same page, if we are
4950 : * making the first scan after commit of an xact that added/deleted many
4951 : * tuples. So, be as quick as we can if the buffer is already dirty. We
4952 : * do this by not acquiring spinlock if it looks like the status bits are
4953 : * already set. Since we make this test unlocked, there's a chance we
4954 : * might fail to notice that the flags have just been cleared, and failed
4955 : * to reset them, due to memory-ordering issues. But since this function
4956 : * is only intended to be used in cases where failing to write out the
4957 : * data would be harmless anyway, it doesn't really matter.
4958 : */
4959 18288086 : if ((pg_atomic_read_u32(&bufHdr->state) & (BM_DIRTY | BM_JUST_DIRTIED)) !=
4960 : (BM_DIRTY | BM_JUST_DIRTIED))
4961 : {
4962 2159770 : XLogRecPtr lsn = InvalidXLogRecPtr;
4963 2159770 : bool dirtied = false;
4964 2159770 : bool delayChkptFlags = false;
4965 : uint32 buf_state;
4966 :
4967 : /*
4968 : * If we need to protect hint bit updates from torn writes, WAL-log a
4969 : * full page image of the page. This full page image is only necessary
4970 : * if the hint bit update is the first change to the page since the
4971 : * last checkpoint.
4972 : *
4973 : * We don't check full_page_writes here because that logic is included
4974 : * when we call XLogInsert() since the value changes dynamically.
4975 : */
4976 4317754 : if (XLogHintBitIsNeeded() &&
4977 2157984 : (pg_atomic_read_u32(&bufHdr->state) & BM_PERMANENT))
4978 : {
4979 : /*
4980 : * If we must not write WAL, due to a relfilelocator-specific
4981 : * condition or being in recovery, don't dirty the page. We can
4982 : * set the hint, just not dirty the page as a result so the hint
4983 : * is lost when we evict the page or shutdown.
4984 : *
4985 : * See src/backend/storage/page/README for longer discussion.
4986 : */
4987 2267720 : if (RecoveryInProgress() ||
4988 109792 : RelFileLocatorSkippingWAL(BufTagGetRelFileLocator(&bufHdr->tag)))
4989 2051476 : return;
4990 :
4991 : /*
4992 : * If the block is already dirty because we either made a change
4993 : * or set a hint already, then we don't need to write a full page
4994 : * image. Note that aggressive cleaning of blocks dirtied by hint
4995 : * bit setting would increase the call rate. Bulk setting of hint
4996 : * bits would reduce the call rate...
4997 : *
4998 : * We must issue the WAL record before we mark the buffer dirty.
4999 : * Otherwise we might write the page before we write the WAL. That
5000 : * causes a race condition, since a checkpoint might occur between
5001 : * writing the WAL record and marking the buffer dirty. We solve
5002 : * that with a kluge, but one that is already in use during
5003 : * transaction commit to prevent race conditions. Basically, we
5004 : * simply prevent the checkpoint WAL record from being written
5005 : * until we have marked the buffer dirty. We don't start the
5006 : * checkpoint flush until we have marked dirty, so our checkpoint
5007 : * must flush the change to disk successfully or the checkpoint
5008 : * never gets written, so crash recovery will fix.
5009 : *
5010 : * It's possible we may enter here without an xid, so it is
5011 : * essential that CreateCheckPoint waits for virtual transactions
5012 : * rather than full transactionids.
5013 : */
5014 : Assert((MyProc->delayChkptFlags & DELAY_CHKPT_START) == 0);
5015 106452 : MyProc->delayChkptFlags |= DELAY_CHKPT_START;
5016 106452 : delayChkptFlags = true;
5017 106452 : lsn = XLogSaveBufferForHint(buffer, buffer_std);
5018 : }
5019 :
5020 108294 : buf_state = LockBufHdr(bufHdr);
5021 :
5022 : Assert(BUF_STATE_GET_REFCOUNT(buf_state) > 0);
5023 :
5024 108294 : if (!(buf_state & BM_DIRTY))
5025 : {
5026 108236 : dirtied = true; /* Means "will be dirtied by this action" */
5027 :
5028 : /*
5029 : * Set the page LSN if we wrote a backup block. We aren't supposed
5030 : * to set this when only holding a share lock but as long as we
5031 : * serialise it somehow we're OK. We choose to set LSN while
5032 : * holding the buffer header lock, which causes any reader of an
5033 : * LSN who holds only a share lock to also obtain a buffer header
5034 : * lock before using PageGetLSN(), which is enforced in
5035 : * BufferGetLSNAtomic().
5036 : *
5037 : * If checksums are enabled, you might think we should reset the
5038 : * checksum here. That will happen when the page is written
5039 : * sometime later in this checkpoint cycle.
5040 : */
5041 108236 : if (!XLogRecPtrIsInvalid(lsn))
5042 55230 : PageSetLSN(page, lsn);
5043 : }
5044 :
5045 108294 : buf_state |= BM_DIRTY | BM_JUST_DIRTIED;
5046 108294 : UnlockBufHdr(bufHdr, buf_state);
5047 :
5048 108294 : if (delayChkptFlags)
5049 106452 : MyProc->delayChkptFlags &= ~DELAY_CHKPT_START;
5050 :
5051 108294 : if (dirtied)
5052 : {
5053 108236 : pgBufferUsage.shared_blks_dirtied++;
5054 108236 : if (VacuumCostActive)
5055 826 : VacuumCostBalance += VacuumCostPageDirty;
5056 : }
5057 : }
5058 : }
5059 :
5060 : /*
5061 : * Release buffer content locks for shared buffers.
5062 : *
5063 : * Used to clean up after errors.
5064 : *
5065 : * Currently, we can expect that lwlock.c's LWLockReleaseAll() took care
5066 : * of releasing buffer content locks per se; the only thing we need to deal
5067 : * with here is clearing any PIN_COUNT request that was in progress.
5068 : */
5069 : void
5070 92392 : UnlockBuffers(void)
5071 : {
5072 92392 : BufferDesc *buf = PinCountWaitBuf;
5073 :
5074 92392 : if (buf)
5075 : {
5076 : uint32 buf_state;
5077 :
5078 0 : buf_state = LockBufHdr(buf);
5079 :
5080 : /*
5081 : * Don't complain if flag bit not set; it could have been reset but we
5082 : * got a cancel/die interrupt before getting the signal.
5083 : */
5084 0 : if ((buf_state & BM_PIN_COUNT_WAITER) != 0 &&
5085 0 : buf->wait_backend_pgprocno == MyProcNumber)
5086 0 : buf_state &= ~BM_PIN_COUNT_WAITER;
5087 :
5088 0 : UnlockBufHdr(buf, buf_state);
5089 :
5090 0 : PinCountWaitBuf = NULL;
5091 : }
5092 92392 : }
5093 :
5094 : /*
5095 : * Acquire or release the content_lock for the buffer.
5096 : */
5097 : void
5098 320204338 : LockBuffer(Buffer buffer, int mode)
5099 : {
5100 : BufferDesc *buf;
5101 :
5102 : Assert(BufferIsPinned(buffer));
5103 320204338 : if (BufferIsLocal(buffer))
5104 18922956 : return; /* local buffers need no lock */
5105 :
5106 301281382 : buf = GetBufferDescriptor(buffer - 1);
5107 :
5108 301281382 : if (mode == BUFFER_LOCK_UNLOCK)
5109 152362626 : LWLockRelease(BufferDescriptorGetContentLock(buf));
5110 148918756 : else if (mode == BUFFER_LOCK_SHARE)
5111 104735400 : LWLockAcquire(BufferDescriptorGetContentLock(buf), LW_SHARED);
5112 44183356 : else if (mode == BUFFER_LOCK_EXCLUSIVE)
5113 44183356 : LWLockAcquire(BufferDescriptorGetContentLock(buf), LW_EXCLUSIVE);
5114 : else
5115 0 : elog(ERROR, "unrecognized buffer lock mode: %d", mode);
5116 : }
5117 :
5118 : /*
5119 : * Acquire the content_lock for the buffer, but only if we don't have to wait.
5120 : *
5121 : * This assumes the caller wants BUFFER_LOCK_EXCLUSIVE mode.
5122 : */
5123 : bool
5124 2719344 : ConditionalLockBuffer(Buffer buffer)
5125 : {
5126 : BufferDesc *buf;
5127 :
5128 : Assert(BufferIsPinned(buffer));
5129 2719344 : if (BufferIsLocal(buffer))
5130 129246 : return true; /* act as though we got it */
5131 :
5132 2590098 : buf = GetBufferDescriptor(buffer - 1);
5133 :
5134 2590098 : return LWLockConditionalAcquire(BufferDescriptorGetContentLock(buf),
5135 : LW_EXCLUSIVE);
5136 : }
5137 :
5138 : /*
5139 : * Verify that this backend is pinning the buffer exactly once.
5140 : *
5141 : * NOTE: Like in BufferIsPinned(), what we check here is that *this* backend
5142 : * holds a pin on the buffer. We do not care whether some other backend does.
5143 : */
5144 : void
5145 4328860 : CheckBufferIsPinnedOnce(Buffer buffer)
5146 : {
5147 4328860 : if (BufferIsLocal(buffer))
5148 : {
5149 1560 : if (LocalRefCount[-buffer - 1] != 1)
5150 0 : elog(ERROR, "incorrect local pin count: %d",
5151 : LocalRefCount[-buffer - 1]);
5152 : }
5153 : else
5154 : {
5155 4327300 : if (GetPrivateRefCount(buffer) != 1)
5156 0 : elog(ERROR, "incorrect local pin count: %d",
5157 : GetPrivateRefCount(buffer));
5158 : }
5159 4328860 : }
5160 :
5161 : /*
5162 : * LockBufferForCleanup - lock a buffer in preparation for deleting items
5163 : *
5164 : * Items may be deleted from a disk page only when the caller (a) holds an
5165 : * exclusive lock on the buffer and (b) has observed that no other backend
5166 : * holds a pin on the buffer. If there is a pin, then the other backend
5167 : * might have a pointer into the buffer (for example, a heapscan reference
5168 : * to an item --- see README for more details). It's OK if a pin is added
5169 : * after the cleanup starts, however; the newly-arrived backend will be
5170 : * unable to look at the page until we release the exclusive lock.
5171 : *
5172 : * To implement this protocol, a would-be deleter must pin the buffer and
5173 : * then call LockBufferForCleanup(). LockBufferForCleanup() is similar to
5174 : * LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE), except that it loops until
5175 : * it has successfully observed pin count = 1.
5176 : */
5177 : void
5178 35620 : LockBufferForCleanup(Buffer buffer)
5179 : {
5180 : BufferDesc *bufHdr;
5181 35620 : TimestampTz waitStart = 0;
5182 35620 : bool waiting = false;
5183 35620 : bool logged_recovery_conflict = false;
5184 :
5185 : Assert(BufferIsPinned(buffer));
5186 : Assert(PinCountWaitBuf == NULL);
5187 :
5188 35620 : CheckBufferIsPinnedOnce(buffer);
5189 :
5190 : /* Nobody else to wait for */
5191 35620 : if (BufferIsLocal(buffer))
5192 32 : return;
5193 :
5194 35588 : bufHdr = GetBufferDescriptor(buffer - 1);
5195 :
5196 : for (;;)
5197 20 : {
5198 : uint32 buf_state;
5199 :
5200 : /* Try to acquire lock */
5201 35608 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
5202 35608 : buf_state = LockBufHdr(bufHdr);
5203 :
5204 : Assert(BUF_STATE_GET_REFCOUNT(buf_state) > 0);
5205 35608 : if (BUF_STATE_GET_REFCOUNT(buf_state) == 1)
5206 : {
5207 : /* Successfully acquired exclusive lock with pincount 1 */
5208 35588 : UnlockBufHdr(bufHdr, buf_state);
5209 :
5210 : /*
5211 : * Emit the log message if recovery conflict on buffer pin was
5212 : * resolved but the startup process waited longer than
5213 : * deadlock_timeout for it.
5214 : */
5215 35588 : if (logged_recovery_conflict)
5216 4 : LogRecoveryConflict(PROCSIG_RECOVERY_CONFLICT_BUFFERPIN,
5217 : waitStart, GetCurrentTimestamp(),
5218 : NULL, false);
5219 :
5220 35588 : if (waiting)
5221 : {
5222 : /* reset ps display to remove the suffix if we added one */
5223 4 : set_ps_display_remove_suffix();
5224 4 : waiting = false;
5225 : }
5226 35588 : return;
5227 : }
5228 : /* Failed, so mark myself as waiting for pincount 1 */
5229 20 : if (buf_state & BM_PIN_COUNT_WAITER)
5230 : {
5231 0 : UnlockBufHdr(bufHdr, buf_state);
5232 0 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
5233 0 : elog(ERROR, "multiple backends attempting to wait for pincount 1");
5234 : }
5235 20 : bufHdr->wait_backend_pgprocno = MyProcNumber;
5236 20 : PinCountWaitBuf = bufHdr;
5237 20 : buf_state |= BM_PIN_COUNT_WAITER;
5238 20 : UnlockBufHdr(bufHdr, buf_state);
5239 20 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
5240 :
5241 : /* Wait to be signaled by UnpinBuffer() */
5242 20 : if (InHotStandby)
5243 : {
5244 20 : if (!waiting)
5245 : {
5246 : /* adjust the process title to indicate that it's waiting */
5247 4 : set_ps_display_suffix("waiting");
5248 4 : waiting = true;
5249 : }
5250 :
5251 : /*
5252 : * Emit the log message if the startup process is waiting longer
5253 : * than deadlock_timeout for recovery conflict on buffer pin.
5254 : *
5255 : * Skip this if first time through because the startup process has
5256 : * not started waiting yet in this case. So, the wait start
5257 : * timestamp is set after this logic.
5258 : */
5259 20 : if (waitStart != 0 && !logged_recovery_conflict)
5260 : {
5261 6 : TimestampTz now = GetCurrentTimestamp();
5262 :
5263 6 : if (TimestampDifferenceExceeds(waitStart, now,
5264 : DeadlockTimeout))
5265 : {
5266 4 : LogRecoveryConflict(PROCSIG_RECOVERY_CONFLICT_BUFFERPIN,
5267 : waitStart, now, NULL, true);
5268 4 : logged_recovery_conflict = true;
5269 : }
5270 : }
5271 :
5272 : /*
5273 : * Set the wait start timestamp if logging is enabled and first
5274 : * time through.
5275 : */
5276 20 : if (log_recovery_conflict_waits && waitStart == 0)
5277 4 : waitStart = GetCurrentTimestamp();
5278 :
5279 : /* Publish the bufid that Startup process waits on */
5280 20 : SetStartupBufferPinWaitBufId(buffer - 1);
5281 : /* Set alarm and then wait to be signaled by UnpinBuffer() */
5282 20 : ResolveRecoveryConflictWithBufferPin();
5283 : /* Reset the published bufid */
5284 20 : SetStartupBufferPinWaitBufId(-1);
5285 : }
5286 : else
5287 0 : ProcWaitForSignal(WAIT_EVENT_BUFFER_PIN);
5288 :
5289 : /*
5290 : * Remove flag marking us as waiter. Normally this will not be set
5291 : * anymore, but ProcWaitForSignal() can return for other signals as
5292 : * well. We take care to only reset the flag if we're the waiter, as
5293 : * theoretically another backend could have started waiting. That's
5294 : * impossible with the current usages due to table level locking, but
5295 : * better be safe.
5296 : */
5297 20 : buf_state = LockBufHdr(bufHdr);
5298 20 : if ((buf_state & BM_PIN_COUNT_WAITER) != 0 &&
5299 16 : bufHdr->wait_backend_pgprocno == MyProcNumber)
5300 16 : buf_state &= ~BM_PIN_COUNT_WAITER;
5301 20 : UnlockBufHdr(bufHdr, buf_state);
5302 :
5303 20 : PinCountWaitBuf = NULL;
5304 : /* Loop back and try again */
5305 : }
5306 : }
5307 :
5308 : /*
5309 : * Check called from ProcessRecoveryConflictInterrupts() when Startup process
5310 : * requests cancellation of all pin holders that are blocking it.
5311 : */
5312 : bool
5313 8 : HoldingBufferPinThatDelaysRecovery(void)
5314 : {
5315 8 : int bufid = GetStartupBufferPinWaitBufId();
5316 :
5317 : /*
5318 : * If we get woken slowly then it's possible that the Startup process was
5319 : * already woken by other backends before we got here. Also possible that
5320 : * we get here by multiple interrupts or interrupts at inappropriate
5321 : * times, so make sure we do nothing if the bufid is not set.
5322 : */
5323 8 : if (bufid < 0)
5324 4 : return false;
5325 :
5326 4 : if (GetPrivateRefCount(bufid + 1) > 0)
5327 4 : return true;
5328 :
5329 0 : return false;
5330 : }
5331 :
5332 : /*
5333 : * ConditionalLockBufferForCleanup - as above, but don't wait to get the lock
5334 : *
5335 : * We won't loop, but just check once to see if the pin count is OK. If
5336 : * not, return false with no lock held.
5337 : */
5338 : bool
5339 839146 : ConditionalLockBufferForCleanup(Buffer buffer)
5340 : {
5341 : BufferDesc *bufHdr;
5342 : uint32 buf_state,
5343 : refcount;
5344 :
5345 : Assert(BufferIsValid(buffer));
5346 :
5347 839146 : if (BufferIsLocal(buffer))
5348 : {
5349 1582 : refcount = LocalRefCount[-buffer - 1];
5350 : /* There should be exactly one pin */
5351 : Assert(refcount > 0);
5352 1582 : if (refcount != 1)
5353 42 : return false;
5354 : /* Nobody else to wait for */
5355 1540 : return true;
5356 : }
5357 :
5358 : /* There should be exactly one local pin */
5359 837564 : refcount = GetPrivateRefCount(buffer);
5360 : Assert(refcount);
5361 837564 : if (refcount != 1)
5362 534 : return false;
5363 :
5364 : /* Try to acquire lock */
5365 837030 : if (!ConditionalLockBuffer(buffer))
5366 50 : return false;
5367 :
5368 836980 : bufHdr = GetBufferDescriptor(buffer - 1);
5369 836980 : buf_state = LockBufHdr(bufHdr);
5370 836980 : refcount = BUF_STATE_GET_REFCOUNT(buf_state);
5371 :
5372 : Assert(refcount > 0);
5373 836980 : if (refcount == 1)
5374 : {
5375 : /* Successfully acquired exclusive lock with pincount 1 */
5376 836776 : UnlockBufHdr(bufHdr, buf_state);
5377 836776 : return true;
5378 : }
5379 :
5380 : /* Failed, so release the lock */
5381 204 : UnlockBufHdr(bufHdr, buf_state);
5382 204 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
5383 204 : return false;
5384 : }
5385 :
5386 : /*
5387 : * IsBufferCleanupOK - as above, but we already have the lock
5388 : *
5389 : * Check whether it's OK to perform cleanup on a buffer we've already
5390 : * locked. If we observe that the pin count is 1, our exclusive lock
5391 : * happens to be a cleanup lock, and we can proceed with anything that
5392 : * would have been allowable had we sought a cleanup lock originally.
5393 : */
5394 : bool
5395 3286 : IsBufferCleanupOK(Buffer buffer)
5396 : {
5397 : BufferDesc *bufHdr;
5398 : uint32 buf_state;
5399 :
5400 : Assert(BufferIsValid(buffer));
5401 :
5402 3286 : if (BufferIsLocal(buffer))
5403 : {
5404 : /* There should be exactly one pin */
5405 0 : if (LocalRefCount[-buffer - 1] != 1)
5406 0 : return false;
5407 : /* Nobody else to wait for */
5408 0 : return true;
5409 : }
5410 :
5411 : /* There should be exactly one local pin */
5412 3286 : if (GetPrivateRefCount(buffer) != 1)
5413 0 : return false;
5414 :
5415 3286 : bufHdr = GetBufferDescriptor(buffer - 1);
5416 :
5417 : /* caller must hold exclusive lock on buffer */
5418 : Assert(LWLockHeldByMeInMode(BufferDescriptorGetContentLock(bufHdr),
5419 : LW_EXCLUSIVE));
5420 :
5421 3286 : buf_state = LockBufHdr(bufHdr);
5422 :
5423 : Assert(BUF_STATE_GET_REFCOUNT(buf_state) > 0);
5424 3286 : if (BUF_STATE_GET_REFCOUNT(buf_state) == 1)
5425 : {
5426 : /* pincount is OK. */
5427 3286 : UnlockBufHdr(bufHdr, buf_state);
5428 3286 : return true;
5429 : }
5430 :
5431 0 : UnlockBufHdr(bufHdr, buf_state);
5432 0 : return false;
5433 : }
5434 :
5435 :
5436 : /*
5437 : * Functions for buffer I/O handling
5438 : *
5439 : * Note: We assume that nested buffer I/O never occurs.
5440 : * i.e at most one BM_IO_IN_PROGRESS bit is set per proc.
5441 : *
5442 : * Also note that these are used only for shared buffers, not local ones.
5443 : */
5444 :
5445 : /*
5446 : * WaitIO -- Block until the IO_IN_PROGRESS flag on 'buf' is cleared.
5447 : */
5448 : static void
5449 2604 : WaitIO(BufferDesc *buf)
5450 : {
5451 2604 : ConditionVariable *cv = BufferDescriptorGetIOCV(buf);
5452 :
5453 2604 : ConditionVariablePrepareToSleep(cv);
5454 : for (;;)
5455 2580 : {
5456 : uint32 buf_state;
5457 :
5458 : /*
5459 : * It may not be necessary to acquire the spinlock to check the flag
5460 : * here, but since this test is essential for correctness, we'd better
5461 : * play it safe.
5462 : */
5463 5184 : buf_state = LockBufHdr(buf);
5464 5184 : UnlockBufHdr(buf, buf_state);
5465 :
5466 5184 : if (!(buf_state & BM_IO_IN_PROGRESS))
5467 2604 : break;
5468 2580 : ConditionVariableSleep(cv, WAIT_EVENT_BUFFER_IO);
5469 : }
5470 2604 : ConditionVariableCancelSleep();
5471 2604 : }
5472 :
5473 : /*
5474 : * StartBufferIO: begin I/O on this buffer
5475 : * (Assumptions)
5476 : * My process is executing no IO
5477 : * The buffer is Pinned
5478 : *
5479 : * In some scenarios there are race conditions in which multiple backends
5480 : * could attempt the same I/O operation concurrently. If someone else
5481 : * has already started I/O on this buffer then we will block on the
5482 : * I/O condition variable until he's done.
5483 : *
5484 : * Input operations are only attempted on buffers that are not BM_VALID,
5485 : * and output operations only on buffers that are BM_VALID and BM_DIRTY,
5486 : * so we can always tell if the work is already done.
5487 : *
5488 : * Returns true if we successfully marked the buffer as I/O busy,
5489 : * false if someone else already did the work.
5490 : *
5491 : * If nowait is true, then we don't wait for an I/O to be finished by another
5492 : * backend. In that case, false indicates either that the I/O was already
5493 : * finished, or is still in progress. This is useful for callers that want to
5494 : * find out if they can perform the I/O as part of a larger operation, without
5495 : * waiting for the answer or distinguishing the reasons why not.
5496 : */
5497 : static bool
5498 4499728 : StartBufferIO(BufferDesc *buf, bool forInput, bool nowait)
5499 : {
5500 : uint32 buf_state;
5501 :
5502 4499728 : ResourceOwnerEnlarge(CurrentResourceOwner);
5503 :
5504 : for (;;)
5505 : {
5506 4502332 : buf_state = LockBufHdr(buf);
5507 :
5508 4502332 : if (!(buf_state & BM_IO_IN_PROGRESS))
5509 4499728 : break;
5510 2604 : UnlockBufHdr(buf, buf_state);
5511 2604 : if (nowait)
5512 0 : return false;
5513 2604 : WaitIO(buf);
5514 : }
5515 :
5516 : /* Once we get here, there is definitely no I/O active on this buffer */
5517 :
5518 4499728 : if (forInput ? (buf_state & BM_VALID) : !(buf_state & BM_DIRTY))
5519 : {
5520 : /* someone else already did the I/O */
5521 3270 : UnlockBufHdr(buf, buf_state);
5522 3270 : return false;
5523 : }
5524 :
5525 4496458 : buf_state |= BM_IO_IN_PROGRESS;
5526 4496458 : UnlockBufHdr(buf, buf_state);
5527 :
5528 4496458 : ResourceOwnerRememberBufferIO(CurrentResourceOwner,
5529 : BufferDescriptorGetBuffer(buf));
5530 :
5531 4496458 : return true;
5532 : }
5533 :
5534 : /*
5535 : * TerminateBufferIO: release a buffer we were doing I/O on
5536 : * (Assumptions)
5537 : * My process is executing IO for the buffer
5538 : * BM_IO_IN_PROGRESS bit is set for the buffer
5539 : * The buffer is Pinned
5540 : *
5541 : * If clear_dirty is true and BM_JUST_DIRTIED is not set, we clear the
5542 : * buffer's BM_DIRTY flag. This is appropriate when terminating a
5543 : * successful write. The check on BM_JUST_DIRTIED is necessary to avoid
5544 : * marking the buffer clean if it was re-dirtied while we were writing.
5545 : *
5546 : * set_flag_bits gets ORed into the buffer's flags. It must include
5547 : * BM_IO_ERROR in a failure case. For successful completion it could
5548 : * be 0, or BM_VALID if we just finished reading in the page.
5549 : *
5550 : * If forget_owner is true, we release the buffer I/O from the current
5551 : * resource owner. (forget_owner=false is used when the resource owner itself
5552 : * is being released)
5553 : */
5554 : static void
5555 4496458 : TerminateBufferIO(BufferDesc *buf, bool clear_dirty, uint32 set_flag_bits,
5556 : bool forget_owner)
5557 : {
5558 : uint32 buf_state;
5559 :
5560 4496458 : buf_state = LockBufHdr(buf);
5561 :
5562 : Assert(buf_state & BM_IO_IN_PROGRESS);
5563 :
5564 4496458 : buf_state &= ~(BM_IO_IN_PROGRESS | BM_IO_ERROR);
5565 4496458 : if (clear_dirty && !(buf_state & BM_JUST_DIRTIED))
5566 975096 : buf_state &= ~(BM_DIRTY | BM_CHECKPOINT_NEEDED);
5567 :
5568 4496458 : buf_state |= set_flag_bits;
5569 4496458 : UnlockBufHdr(buf, buf_state);
5570 :
5571 4496458 : if (forget_owner)
5572 4496428 : ResourceOwnerForgetBufferIO(CurrentResourceOwner,
5573 : BufferDescriptorGetBuffer(buf));
5574 :
5575 4496458 : ConditionVariableBroadcast(BufferDescriptorGetIOCV(buf));
5576 4496458 : }
5577 :
5578 : /*
5579 : * AbortBufferIO: Clean up active buffer I/O after an error.
5580 : *
5581 : * All LWLocks we might have held have been released,
5582 : * but we haven't yet released buffer pins, so the buffer is still pinned.
5583 : *
5584 : * If I/O was in progress, we always set BM_IO_ERROR, even though it's
5585 : * possible the error condition wasn't related to the I/O.
5586 : *
5587 : * Note: this does not remove the buffer I/O from the resource owner.
5588 : * That's correct when we're releasing the whole resource owner, but
5589 : * beware if you use this in other contexts.
5590 : */
5591 : static void
5592 30 : AbortBufferIO(Buffer buffer)
5593 : {
5594 30 : BufferDesc *buf_hdr = GetBufferDescriptor(buffer - 1);
5595 : uint32 buf_state;
5596 :
5597 30 : buf_state = LockBufHdr(buf_hdr);
5598 : Assert(buf_state & (BM_IO_IN_PROGRESS | BM_TAG_VALID));
5599 :
5600 30 : if (!(buf_state & BM_VALID))
5601 : {
5602 : Assert(!(buf_state & BM_DIRTY));
5603 30 : UnlockBufHdr(buf_hdr, buf_state);
5604 : }
5605 : else
5606 : {
5607 : Assert(buf_state & BM_DIRTY);
5608 0 : UnlockBufHdr(buf_hdr, buf_state);
5609 :
5610 : /* Issue notice if this is not the first failure... */
5611 0 : if (buf_state & BM_IO_ERROR)
5612 : {
5613 : /* Buffer is pinned, so we can read tag without spinlock */
5614 : char *path;
5615 :
5616 0 : path = relpathperm(BufTagGetRelFileLocator(&buf_hdr->tag),
5617 : BufTagGetForkNum(&buf_hdr->tag));
5618 0 : ereport(WARNING,
5619 : (errcode(ERRCODE_IO_ERROR),
5620 : errmsg("could not write block %u of %s",
5621 : buf_hdr->tag.blockNum, path),
5622 : errdetail("Multiple failures --- write error might be permanent.")));
5623 0 : pfree(path);
5624 : }
5625 : }
5626 :
5627 30 : TerminateBufferIO(buf_hdr, false, BM_IO_ERROR, false);
5628 30 : }
5629 :
5630 : /*
5631 : * Error context callback for errors occurring during shared buffer writes.
5632 : */
5633 : static void
5634 78 : shared_buffer_write_error_callback(void *arg)
5635 : {
5636 78 : BufferDesc *bufHdr = (BufferDesc *) arg;
5637 :
5638 : /* Buffer is pinned, so we can read the tag without locking the spinlock */
5639 78 : if (bufHdr != NULL)
5640 : {
5641 78 : char *path = relpathperm(BufTagGetRelFileLocator(&bufHdr->tag),
5642 : BufTagGetForkNum(&bufHdr->tag));
5643 :
5644 78 : errcontext("writing block %u of relation %s",
5645 : bufHdr->tag.blockNum, path);
5646 78 : pfree(path);
5647 : }
5648 78 : }
5649 :
5650 : /*
5651 : * Error context callback for errors occurring during local buffer writes.
5652 : */
5653 : static void
5654 0 : local_buffer_write_error_callback(void *arg)
5655 : {
5656 0 : BufferDesc *bufHdr = (BufferDesc *) arg;
5657 :
5658 0 : if (bufHdr != NULL)
5659 : {
5660 0 : char *path = relpathbackend(BufTagGetRelFileLocator(&bufHdr->tag),
5661 : MyProcNumber,
5662 : BufTagGetForkNum(&bufHdr->tag));
5663 :
5664 0 : errcontext("writing block %u of relation %s",
5665 : bufHdr->tag.blockNum, path);
5666 0 : pfree(path);
5667 : }
5668 0 : }
5669 :
5670 : /*
5671 : * RelFileLocator qsort/bsearch comparator; see RelFileLocatorEquals.
5672 : */
5673 : static int
5674 18429164 : rlocator_comparator(const void *p1, const void *p2)
5675 : {
5676 18429164 : RelFileLocator n1 = *(const RelFileLocator *) p1;
5677 18429164 : RelFileLocator n2 = *(const RelFileLocator *) p2;
5678 :
5679 18429164 : if (n1.relNumber < n2.relNumber)
5680 18338392 : return -1;
5681 90772 : else if (n1.relNumber > n2.relNumber)
5682 87226 : return 1;
5683 :
5684 3546 : if (n1.dbOid < n2.dbOid)
5685 0 : return -1;
5686 3546 : else if (n1.dbOid > n2.dbOid)
5687 0 : return 1;
5688 :
5689 3546 : if (n1.spcOid < n2.spcOid)
5690 0 : return -1;
5691 3546 : else if (n1.spcOid > n2.spcOid)
5692 0 : return 1;
5693 : else
5694 3546 : return 0;
5695 : }
5696 :
5697 : /*
5698 : * Lock buffer header - set BM_LOCKED in buffer state.
5699 : */
5700 : uint32
5701 66489088 : LockBufHdr(BufferDesc *desc)
5702 : {
5703 : SpinDelayStatus delayStatus;
5704 : uint32 old_buf_state;
5705 :
5706 : Assert(!BufferIsLocal(BufferDescriptorGetBuffer(desc)));
5707 :
5708 66489088 : init_local_spin_delay(&delayStatus);
5709 :
5710 : while (true)
5711 : {
5712 : /* set BM_LOCKED flag */
5713 66508104 : old_buf_state = pg_atomic_fetch_or_u32(&desc->state, BM_LOCKED);
5714 : /* if it wasn't set before we're OK */
5715 66508104 : if (!(old_buf_state & BM_LOCKED))
5716 66489088 : break;
5717 19016 : perform_spin_delay(&delayStatus);
5718 : }
5719 66489088 : finish_spin_delay(&delayStatus);
5720 66489088 : return old_buf_state | BM_LOCKED;
5721 : }
5722 :
5723 : /*
5724 : * Wait until the BM_LOCKED flag isn't set anymore and return the buffer's
5725 : * state at that point.
5726 : *
5727 : * Obviously the buffer could be locked by the time the value is returned, so
5728 : * this is primarily useful in CAS style loops.
5729 : */
5730 : static uint32
5731 6482 : WaitBufHdrUnlocked(BufferDesc *buf)
5732 : {
5733 : SpinDelayStatus delayStatus;
5734 : uint32 buf_state;
5735 :
5736 6482 : init_local_spin_delay(&delayStatus);
5737 :
5738 6482 : buf_state = pg_atomic_read_u32(&buf->state);
5739 :
5740 19726 : while (buf_state & BM_LOCKED)
5741 : {
5742 13244 : perform_spin_delay(&delayStatus);
5743 13244 : buf_state = pg_atomic_read_u32(&buf->state);
5744 : }
5745 :
5746 6482 : finish_spin_delay(&delayStatus);
5747 :
5748 6482 : return buf_state;
5749 : }
5750 :
5751 : /*
5752 : * BufferTag comparator.
5753 : */
5754 : static inline int
5755 0 : buffertag_comparator(const BufferTag *ba, const BufferTag *bb)
5756 : {
5757 : int ret;
5758 : RelFileLocator rlocatora;
5759 : RelFileLocator rlocatorb;
5760 :
5761 0 : rlocatora = BufTagGetRelFileLocator(ba);
5762 0 : rlocatorb = BufTagGetRelFileLocator(bb);
5763 :
5764 0 : ret = rlocator_comparator(&rlocatora, &rlocatorb);
5765 :
5766 0 : if (ret != 0)
5767 0 : return ret;
5768 :
5769 0 : if (BufTagGetForkNum(ba) < BufTagGetForkNum(bb))
5770 0 : return -1;
5771 0 : if (BufTagGetForkNum(ba) > BufTagGetForkNum(bb))
5772 0 : return 1;
5773 :
5774 0 : if (ba->blockNum < bb->blockNum)
5775 0 : return -1;
5776 0 : if (ba->blockNum > bb->blockNum)
5777 0 : return 1;
5778 :
5779 0 : return 0;
5780 : }
5781 :
5782 : /*
5783 : * Comparator determining the writeout order in a checkpoint.
5784 : *
5785 : * It is important that tablespaces are compared first, the logic balancing
5786 : * writes between tablespaces relies on it.
5787 : */
5788 : static inline int
5789 5276972 : ckpt_buforder_comparator(const CkptSortItem *a, const CkptSortItem *b)
5790 : {
5791 : /* compare tablespace */
5792 5276972 : if (a->tsId < b->tsId)
5793 11890 : return -1;
5794 5265082 : else if (a->tsId > b->tsId)
5795 36498 : return 1;
5796 : /* compare relation */
5797 5228584 : if (a->relNumber < b->relNumber)
5798 1479236 : return -1;
5799 3749348 : else if (a->relNumber > b->relNumber)
5800 1374646 : return 1;
5801 : /* compare fork */
5802 2374702 : else if (a->forkNum < b->forkNum)
5803 105924 : return -1;
5804 2268778 : else if (a->forkNum > b->forkNum)
5805 99350 : return 1;
5806 : /* compare block number */
5807 2169428 : else if (a->blockNum < b->blockNum)
5808 1060206 : return -1;
5809 1109222 : else if (a->blockNum > b->blockNum)
5810 1044846 : return 1;
5811 : /* equal page IDs are unlikely, but not impossible */
5812 64376 : return 0;
5813 : }
5814 :
5815 : /*
5816 : * Comparator for a Min-Heap over the per-tablespace checkpoint completion
5817 : * progress.
5818 : */
5819 : static int
5820 411814 : ts_ckpt_progress_comparator(Datum a, Datum b, void *arg)
5821 : {
5822 411814 : CkptTsStatus *sa = (CkptTsStatus *) a;
5823 411814 : CkptTsStatus *sb = (CkptTsStatus *) b;
5824 :
5825 : /* we want a min-heap, so return 1 for the a < b */
5826 411814 : if (sa->progress < sb->progress)
5827 391984 : return 1;
5828 19830 : else if (sa->progress == sb->progress)
5829 1438 : return 0;
5830 : else
5831 18392 : return -1;
5832 : }
5833 :
5834 : /*
5835 : * Initialize a writeback context, discarding potential previous state.
5836 : *
5837 : * *max_pending is a pointer instead of an immediate value, so the coalesce
5838 : * limits can easily changed by the GUC mechanism, and so calling code does
5839 : * not have to check the current configuration. A value of 0 means that no
5840 : * writeback control will be performed.
5841 : */
5842 : void
5843 4750 : WritebackContextInit(WritebackContext *context, int *max_pending)
5844 : {
5845 : Assert(*max_pending <= WRITEBACK_MAX_PENDING_FLUSHES);
5846 :
5847 4750 : context->max_pending = max_pending;
5848 4750 : context->nr_pending = 0;
5849 4750 : }
5850 :
5851 : /*
5852 : * Add buffer to list of pending writeback requests.
5853 : */
5854 : void
5855 967998 : ScheduleBufferTagForWriteback(WritebackContext *wb_context, IOContext io_context,
5856 : BufferTag *tag)
5857 : {
5858 : PendingWriteback *pending;
5859 :
5860 : /*
5861 : * As pg_flush_data() doesn't do anything with fsync disabled, there's no
5862 : * point in tracking in that case.
5863 : */
5864 967998 : if (io_direct_flags & IO_DIRECT_DATA ||
5865 966974 : !enableFsync)
5866 967998 : return;
5867 :
5868 : /*
5869 : * Add buffer to the pending writeback array, unless writeback control is
5870 : * disabled.
5871 : */
5872 0 : if (*wb_context->max_pending > 0)
5873 : {
5874 : Assert(*wb_context->max_pending <= WRITEBACK_MAX_PENDING_FLUSHES);
5875 :
5876 0 : pending = &wb_context->pending_writebacks[wb_context->nr_pending++];
5877 :
5878 0 : pending->tag = *tag;
5879 : }
5880 :
5881 : /*
5882 : * Perform pending flushes if the writeback limit is exceeded. This
5883 : * includes the case where previously an item has been added, but control
5884 : * is now disabled.
5885 : */
5886 0 : if (wb_context->nr_pending >= *wb_context->max_pending)
5887 0 : IssuePendingWritebacks(wb_context, io_context);
5888 : }
5889 :
5890 : #define ST_SORT sort_pending_writebacks
5891 : #define ST_ELEMENT_TYPE PendingWriteback
5892 : #define ST_COMPARE(a, b) buffertag_comparator(&a->tag, &b->tag)
5893 : #define ST_SCOPE static
5894 : #define ST_DEFINE
5895 : #include <lib/sort_template.h>
5896 :
5897 : /*
5898 : * Issue all pending writeback requests, previously scheduled with
5899 : * ScheduleBufferTagForWriteback, to the OS.
5900 : *
5901 : * Because this is only used to improve the OSs IO scheduling we try to never
5902 : * error out - it's just a hint.
5903 : */
5904 : void
5905 1902 : IssuePendingWritebacks(WritebackContext *wb_context, IOContext io_context)
5906 : {
5907 : instr_time io_start;
5908 : int i;
5909 :
5910 1902 : if (wb_context->nr_pending == 0)
5911 1902 : return;
5912 :
5913 : /*
5914 : * Executing the writes in-order can make them a lot faster, and allows to
5915 : * merge writeback requests to consecutive blocks into larger writebacks.
5916 : */
5917 0 : sort_pending_writebacks(wb_context->pending_writebacks,
5918 0 : wb_context->nr_pending);
5919 :
5920 0 : io_start = pgstat_prepare_io_time(track_io_timing);
5921 :
5922 : /*
5923 : * Coalesce neighbouring writes, but nothing else. For that we iterate
5924 : * through the, now sorted, array of pending flushes, and look forward to
5925 : * find all neighbouring (or identical) writes.
5926 : */
5927 0 : for (i = 0; i < wb_context->nr_pending; i++)
5928 : {
5929 : PendingWriteback *cur;
5930 : PendingWriteback *next;
5931 : SMgrRelation reln;
5932 : int ahead;
5933 : BufferTag tag;
5934 : RelFileLocator currlocator;
5935 0 : Size nblocks = 1;
5936 :
5937 0 : cur = &wb_context->pending_writebacks[i];
5938 0 : tag = cur->tag;
5939 0 : currlocator = BufTagGetRelFileLocator(&tag);
5940 :
5941 : /*
5942 : * Peek ahead, into following writeback requests, to see if they can
5943 : * be combined with the current one.
5944 : */
5945 0 : for (ahead = 0; i + ahead + 1 < wb_context->nr_pending; ahead++)
5946 : {
5947 :
5948 0 : next = &wb_context->pending_writebacks[i + ahead + 1];
5949 :
5950 : /* different file, stop */
5951 0 : if (!RelFileLocatorEquals(currlocator,
5952 0 : BufTagGetRelFileLocator(&next->tag)) ||
5953 0 : BufTagGetForkNum(&cur->tag) != BufTagGetForkNum(&next->tag))
5954 : break;
5955 :
5956 : /* ok, block queued twice, skip */
5957 0 : if (cur->tag.blockNum == next->tag.blockNum)
5958 0 : continue;
5959 :
5960 : /* only merge consecutive writes */
5961 0 : if (cur->tag.blockNum + 1 != next->tag.blockNum)
5962 0 : break;
5963 :
5964 0 : nblocks++;
5965 0 : cur = next;
5966 : }
5967 :
5968 0 : i += ahead;
5969 :
5970 : /* and finally tell the kernel to write the data to storage */
5971 0 : reln = smgropen(currlocator, INVALID_PROC_NUMBER);
5972 0 : smgrwriteback(reln, BufTagGetForkNum(&tag), tag.blockNum, nblocks);
5973 : }
5974 :
5975 : /*
5976 : * Assume that writeback requests are only issued for buffers containing
5977 : * blocks of permanent relations.
5978 : */
5979 0 : pgstat_count_io_op_time(IOOBJECT_RELATION, io_context,
5980 0 : IOOP_WRITEBACK, io_start, wb_context->nr_pending, 0);
5981 :
5982 0 : wb_context->nr_pending = 0;
5983 : }
5984 :
5985 : /* ResourceOwner callbacks */
5986 :
5987 : static void
5988 30 : ResOwnerReleaseBufferIO(Datum res)
5989 : {
5990 30 : Buffer buffer = DatumGetInt32(res);
5991 :
5992 30 : AbortBufferIO(buffer);
5993 30 : }
5994 :
5995 : static char *
5996 0 : ResOwnerPrintBufferIO(Datum res)
5997 : {
5998 0 : Buffer buffer = DatumGetInt32(res);
5999 :
6000 0 : return psprintf("lost track of buffer IO on buffer %d", buffer);
6001 : }
6002 :
6003 : static void
6004 9252 : ResOwnerReleaseBufferPin(Datum res)
6005 : {
6006 9252 : Buffer buffer = DatumGetInt32(res);
6007 :
6008 : /* Like ReleaseBuffer, but don't call ResourceOwnerForgetBuffer */
6009 9252 : if (!BufferIsValid(buffer))
6010 0 : elog(ERROR, "bad buffer ID: %d", buffer);
6011 :
6012 9252 : if (BufferIsLocal(buffer))
6013 766 : UnpinLocalBufferNoOwner(buffer);
6014 : else
6015 8486 : UnpinBufferNoOwner(GetBufferDescriptor(buffer - 1));
6016 9252 : }
6017 :
6018 : static char *
6019 0 : ResOwnerPrintBufferPin(Datum res)
6020 : {
6021 0 : return DebugPrintBufferRefcount(DatumGetInt32(res));
6022 : }
6023 :
6024 : /*
6025 : * Try to evict the current block in a shared buffer.
6026 : *
6027 : * This function is intended for testing/development use only!
6028 : *
6029 : * To succeed, the buffer must not be pinned on entry, so if the caller had a
6030 : * particular block in mind, it might already have been replaced by some other
6031 : * block by the time this function runs. It's also unpinned on return, so the
6032 : * buffer might be occupied again by the time control is returned, potentially
6033 : * even by the same block. This inherent raciness without other interlocking
6034 : * makes the function unsuitable for non-testing usage.
6035 : *
6036 : * Returns true if the buffer was valid and it has now been made invalid.
6037 : * Returns false if it wasn't valid, if it couldn't be evicted due to a pin,
6038 : * or if the buffer becomes dirty again while we're trying to write it out.
6039 : */
6040 : bool
6041 0 : EvictUnpinnedBuffer(Buffer buf)
6042 : {
6043 : BufferDesc *desc;
6044 : uint32 buf_state;
6045 : bool result;
6046 :
6047 : /* Make sure we can pin the buffer. */
6048 0 : ResourceOwnerEnlarge(CurrentResourceOwner);
6049 0 : ReservePrivateRefCountEntry();
6050 :
6051 : Assert(!BufferIsLocal(buf));
6052 0 : desc = GetBufferDescriptor(buf - 1);
6053 :
6054 : /* Lock the header and check if it's valid. */
6055 0 : buf_state = LockBufHdr(desc);
6056 0 : if ((buf_state & BM_VALID) == 0)
6057 : {
6058 0 : UnlockBufHdr(desc, buf_state);
6059 0 : return false;
6060 : }
6061 :
6062 : /* Check that it's not pinned already. */
6063 0 : if (BUF_STATE_GET_REFCOUNT(buf_state) > 0)
6064 : {
6065 0 : UnlockBufHdr(desc, buf_state);
6066 0 : return false;
6067 : }
6068 :
6069 0 : PinBuffer_Locked(desc); /* releases spinlock */
6070 :
6071 : /* If it was dirty, try to clean it once. */
6072 0 : if (buf_state & BM_DIRTY)
6073 : {
6074 0 : LWLockAcquire(BufferDescriptorGetContentLock(desc), LW_SHARED);
6075 0 : FlushBuffer(desc, NULL, IOOBJECT_RELATION, IOCONTEXT_NORMAL);
6076 0 : LWLockRelease(BufferDescriptorGetContentLock(desc));
6077 : }
6078 :
6079 : /* This will return false if it becomes dirty or someone else pins it. */
6080 0 : result = InvalidateVictimBuffer(desc);
6081 :
6082 0 : UnpinBuffer(desc);
6083 :
6084 0 : return result;
6085 : }
|