PostgreSQL Source Code  git master
bufmgr.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * bufmgr.c
4  * buffer manager interface routines
5  *
6  * Portions Copyright (c) 1996-2021, 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  * ReleaseBuffer() -- unpin a buffer
23  *
24  * MarkBufferDirty() -- mark a pinned buffer's contents as "dirty".
25  * The disk write is delayed until buffer replacement or checkpoint.
26  *
27  * See also these files:
28  * freelist.c -- chooses victim for buffer replacement
29  * buf_table.c -- manages the buffer lookup table
30  */
31 #include "postgres.h"
32 
33 #include <sys/file.h>
34 #include <unistd.h>
35 
36 #include "access/tableam.h"
37 #include "access/xlogutils.h"
38 #include "catalog/catalog.h"
39 #include "catalog/storage.h"
40 #include "executor/instrument.h"
41 #include "lib/binaryheap.h"
42 #include "miscadmin.h"
43 #include "pg_trace.h"
44 #include "pgstat.h"
45 #include "postmaster/bgwriter.h"
46 #include "storage/buf_internals.h"
47 #include "storage/bufmgr.h"
48 #include "storage/ipc.h"
49 #include "storage/proc.h"
50 #include "storage/smgr.h"
51 #include "storage/standby.h"
52 #include "utils/memdebug.h"
53 #include "utils/ps_status.h"
54 #include "utils/rel.h"
55 #include "utils/resowner_private.h"
56 #include "utils/timestamp.h"
57 
58 
59 /* Note: these two macros only work on shared buffers, not local ones! */
60 #define BufHdrGetBlock(bufHdr) ((Block) (BufferBlocks + ((Size) (bufHdr)->buf_id) * BLCKSZ))
61 #define BufferGetLSN(bufHdr) (PageGetLSN(BufHdrGetBlock(bufHdr)))
62 
63 /* Note: this macro only works on local buffers, not shared ones! */
64 #define LocalBufHdrGetBlock(bufHdr) \
65  LocalBufferBlockPointers[-((bufHdr)->buf_id + 2)]
66 
67 /* Bits in SyncOneBuffer's return value */
68 #define BUF_WRITTEN 0x01
69 #define BUF_REUSABLE 0x02
70 
71 #define RELS_BSEARCH_THRESHOLD 20
72 
73 /*
74  * This is the size (in the number of blocks) above which we scan the
75  * entire buffer pool to remove the buffers for all the pages of relation
76  * being dropped. For the relations with size below this threshold, we find
77  * the buffers by doing lookups in BufMapping table.
78  */
79 #define BUF_DROP_FULL_SCAN_THRESHOLD (uint64) (NBuffers / 32)
80 
81 typedef struct PrivateRefCountEntry
82 {
86 
87 /* 64 bytes, about the size of a cache line on common systems */
88 #define REFCOUNT_ARRAY_ENTRIES 8
89 
90 /*
91  * Status of buffers to checkpoint for a particular tablespace, used
92  * internally in BufferSync.
93  */
94 typedef struct CkptTsStatus
95 {
96  /* oid of the tablespace */
98 
99  /*
100  * Checkpoint progress for this tablespace. To make progress comparable
101  * between tablespaces the progress is, for each tablespace, measured as a
102  * number between 0 and the total number of to-be-checkpointed pages. Each
103  * page checkpointed in this tablespace increments this space's progress
104  * by progress_slice.
105  */
108 
109  /* number of to-be checkpointed pages in this tablespace */
111  /* already processed pages in this tablespace */
113 
114  /* current offset in CkptBufferIds for this tablespace */
115  int index;
116 } CkptTsStatus;
117 
118 /*
119  * Type for array used to sort SMgrRelations
120  *
121  * FlushRelationsAllBuffers shares the same comparator function with
122  * DropRelFileNodesAllBuffers. Pointer to this struct and RelFileNode must be
123  * compatible.
124  */
125 typedef struct SMgrSortArray
126 {
127  RelFileNode rnode; /* This must be the first member */
129 } SMgrSortArray;
130 
131 /* GUC variables */
132 bool zero_damaged_pages = false;
135 bool track_io_timing = false;
136 
137 /*
138  * How many buffers PrefetchBuffer callers should try to stay ahead of their
139  * ReadBuffer calls by. Zero means "never prefetch". This value is only used
140  * for buffers not belonging to tablespaces that have their
141  * effective_io_concurrency parameter set.
142  */
144 
145 /*
146  * Like effective_io_concurrency, but used by maintenance code paths that might
147  * benefit from a higher setting because they work on behalf of many sessions.
148  * Overridden by the tablespace setting of the same name.
149  */
151 
152 /*
153  * GUC variables about triggering kernel writeback for buffers written; OS
154  * dependent defaults are set via the GUC mechanism.
155  */
159 
160 /* local state for StartBufferIO and related functions */
161 static BufferDesc *InProgressBuf = NULL;
162 static bool IsForInput;
163 
164 /* local state for LockBufferForCleanup */
166 
167 /*
168  * Backend-Private refcount management:
169  *
170  * Each buffer also has a private refcount that keeps track of the number of
171  * times the buffer is pinned in the current process. This is so that the
172  * shared refcount needs to be modified only once if a buffer is pinned more
173  * than once by an individual backend. It's also used to check that no buffers
174  * are still pinned at the end of transactions and when exiting.
175  *
176  *
177  * To avoid - as we used to - requiring an array with NBuffers entries to keep
178  * track of local buffers, we use a small sequentially searched array
179  * (PrivateRefCountArray) and an overflow hash table (PrivateRefCountHash) to
180  * keep track of backend local pins.
181  *
182  * Until no more than REFCOUNT_ARRAY_ENTRIES buffers are pinned at once, all
183  * refcounts are kept track of in the array; after that, new array entries
184  * displace old ones into the hash table. That way a frequently used entry
185  * can't get "stuck" in the hashtable while infrequent ones clog the array.
186  *
187  * Note that in most scenarios the number of pinned buffers will not exceed
188  * REFCOUNT_ARRAY_ENTRIES.
189  *
190  *
191  * To enter a buffer into the refcount tracking mechanism first reserve a free
192  * entry using ReservePrivateRefCountEntry() and then later, if necessary,
193  * fill it with NewPrivateRefCountEntry(). That split lets us avoid doing
194  * memory allocations in NewPrivateRefCountEntry() which can be important
195  * because in some scenarios it's called with a spinlock held...
196  */
198 static HTAB *PrivateRefCountHash = NULL;
202 
203 static void ReservePrivateRefCountEntry(void);
206 static inline int32 GetPrivateRefCount(Buffer buffer);
208 
209 /*
210  * Ensure that the PrivateRefCountArray has sufficient space to store one more
211  * entry. This has to be called before using NewPrivateRefCountEntry() to fill
212  * a new entry - but it's perfectly fine to not use a reserved entry.
213  */
214 static void
216 {
217  /* Already reserved (or freed), nothing to do */
218  if (ReservedRefCountEntry != NULL)
219  return;
220 
221  /*
222  * First search for a free entry the array, that'll be sufficient in the
223  * majority of cases.
224  */
225  {
226  int i;
227 
228  for (i = 0; i < REFCOUNT_ARRAY_ENTRIES; i++)
229  {
231 
232  res = &PrivateRefCountArray[i];
233 
234  if (res->buffer == InvalidBuffer)
235  {
236  ReservedRefCountEntry = res;
237  return;
238  }
239  }
240  }
241 
242  /*
243  * No luck. All array entries are full. Move one array entry into the hash
244  * table.
245  */
246  {
247  /*
248  * Move entry from the current clock position in the array into the
249  * hashtable. Use that slot.
250  */
251  PrivateRefCountEntry *hashent;
252  bool found;
253 
254  /* select victim slot */
255  ReservedRefCountEntry =
257 
258  /* Better be used, otherwise we shouldn't get here. */
259  Assert(ReservedRefCountEntry->buffer != InvalidBuffer);
260 
261  /* enter victim array entry into hashtable */
262  hashent = hash_search(PrivateRefCountHash,
263  (void *) &(ReservedRefCountEntry->buffer),
264  HASH_ENTER,
265  &found);
266  Assert(!found);
267  hashent->refcount = ReservedRefCountEntry->refcount;
268 
269  /* clear the now free array slot */
270  ReservedRefCountEntry->buffer = InvalidBuffer;
271  ReservedRefCountEntry->refcount = 0;
272 
274  }
275 }
276 
277 /*
278  * Fill a previously reserved refcount entry.
279  */
280 static PrivateRefCountEntry *
282 {
284 
285  /* only allowed to be called when a reservation has been made */
286  Assert(ReservedRefCountEntry != NULL);
287 
288  /* use up the reserved entry */
289  res = ReservedRefCountEntry;
290  ReservedRefCountEntry = NULL;
291 
292  /* and fill it */
293  res->buffer = buffer;
294  res->refcount = 0;
295 
296  return res;
297 }
298 
299 /*
300  * Return the PrivateRefCount entry for the passed buffer.
301  *
302  * Returns NULL if a buffer doesn't have a refcount entry. Otherwise, if
303  * do_move is true, and the entry resides in the hashtable the entry is
304  * optimized for frequent access by moving it to the array.
305  */
306 static PrivateRefCountEntry *
308 {
310  int i;
311 
312  Assert(BufferIsValid(buffer));
313  Assert(!BufferIsLocal(buffer));
314 
315  /*
316  * First search for references in the array, that'll be sufficient in the
317  * majority of cases.
318  */
319  for (i = 0; i < REFCOUNT_ARRAY_ENTRIES; i++)
320  {
321  res = &PrivateRefCountArray[i];
322 
323  if (res->buffer == buffer)
324  return res;
325  }
326 
327  /*
328  * By here we know that the buffer, if already pinned, isn't residing in
329  * the array.
330  *
331  * Only look up the buffer in the hashtable if we've previously overflowed
332  * into it.
333  */
334  if (PrivateRefCountOverflowed == 0)
335  return NULL;
336 
337  res = hash_search(PrivateRefCountHash,
338  (void *) &buffer,
339  HASH_FIND,
340  NULL);
341 
342  if (res == NULL)
343  return NULL;
344  else if (!do_move)
345  {
346  /* caller doesn't want us to move the hash entry into the array */
347  return res;
348  }
349  else
350  {
351  /* move buffer from hashtable into the free array slot */
352  bool found;
354 
355  /* Ensure there's a free array slot */
357 
358  /* Use up the reserved slot */
359  Assert(ReservedRefCountEntry != NULL);
360  free = ReservedRefCountEntry;
361  ReservedRefCountEntry = NULL;
362  Assert(free->buffer == InvalidBuffer);
363 
364  /* and fill it */
365  free->buffer = buffer;
366  free->refcount = res->refcount;
367 
368  /* delete from hashtable */
369  hash_search(PrivateRefCountHash,
370  (void *) &buffer,
371  HASH_REMOVE,
372  &found);
373  Assert(found);
376 
377  return free;
378  }
379 }
380 
381 /*
382  * Returns how many times the passed buffer is pinned by this backend.
383  *
384  * Only works for shared memory buffers!
385  */
386 static inline int32
388 {
390 
391  Assert(BufferIsValid(buffer));
392  Assert(!BufferIsLocal(buffer));
393 
394  /*
395  * Not moving the entry - that's ok for the current users, but we might
396  * want to change this one day.
397  */
398  ref = GetPrivateRefCountEntry(buffer, false);
399 
400  if (ref == NULL)
401  return 0;
402  return ref->refcount;
403 }
404 
405 /*
406  * Release resources used to track the reference count of a buffer which we no
407  * longer have pinned and don't want to pin again immediately.
408  */
409 static void
411 {
412  Assert(ref->refcount == 0);
413 
414  if (ref >= &PrivateRefCountArray[0] &&
416  {
417  ref->buffer = InvalidBuffer;
418 
419  /*
420  * Mark the just used entry as reserved - in many scenarios that
421  * allows us to avoid ever having to search the array/hash for free
422  * entries.
423  */
424  ReservedRefCountEntry = ref;
425  }
426  else
427  {
428  bool found;
429  Buffer buffer = ref->buffer;
430 
431  hash_search(PrivateRefCountHash,
432  (void *) &buffer,
433  HASH_REMOVE,
434  &found);
435  Assert(found);
438  }
439 }
440 
441 /*
442  * BufferIsPinned
443  * True iff the buffer is pinned (also checks for valid buffer number).
444  *
445  * NOTE: what we check here is that *this* backend holds a pin on
446  * the buffer. We do not care whether some other backend does.
447  */
448 #define BufferIsPinned(bufnum) \
449 ( \
450  !BufferIsValid(bufnum) ? \
451  false \
452  : \
453  BufferIsLocal(bufnum) ? \
454  (LocalRefCount[-(bufnum) - 1] > 0) \
455  : \
456  (GetPrivateRefCount(bufnum) > 0) \
457 )
458 
459 
460 static Buffer ReadBuffer_common(SMgrRelation reln, char relpersistence,
461  ForkNumber forkNum, BlockNumber blockNum,
463  bool *hit);
464 static bool PinBuffer(BufferDesc *buf, BufferAccessStrategy strategy);
465 static void PinBuffer_Locked(BufferDesc *buf);
466 static void UnpinBuffer(BufferDesc *buf, bool fixOwner);
467 static void BufferSync(int flags);
469 static int SyncOneBuffer(int buf_id, bool skip_recently_used,
470  WritebackContext *wb_context);
471 static void WaitIO(BufferDesc *buf);
472 static bool StartBufferIO(BufferDesc *buf, bool forInput);
473 static void TerminateBufferIO(BufferDesc *buf, bool clear_dirty,
474  uint32 set_flag_bits);
475 static void shared_buffer_write_error_callback(void *arg);
476 static void local_buffer_write_error_callback(void *arg);
477 static BufferDesc *BufferAlloc(SMgrRelation smgr,
478  char relpersistence,
479  ForkNumber forkNum,
480  BlockNumber blockNum,
481  BufferAccessStrategy strategy,
482  bool *foundPtr);
483 static void FlushBuffer(BufferDesc *buf, SMgrRelation reln);
485  ForkNumber forkNum,
486  BlockNumber nForkBlock,
487  BlockNumber firstDelBlock);
488 static void AtProcExit_Buffers(int code, Datum arg);
489 static void CheckForBufferLeaks(void);
490 static int rnode_comparator(const void *p1, const void *p2);
491 static inline int buffertag_comparator(const BufferTag *a, const BufferTag *b);
492 static inline int ckpt_buforder_comparator(const CkptSortItem *a, const CkptSortItem *b);
493 static int ts_ckpt_progress_comparator(Datum a, Datum b, void *arg);
494 
495 
496 /*
497  * Implementation of PrefetchBuffer() for shared buffers.
498  */
501  ForkNumber forkNum,
502  BlockNumber blockNum)
503 {
504  PrefetchBufferResult result = {InvalidBuffer, false};
505  BufferTag newTag; /* identity of requested block */
506  uint32 newHash; /* hash value for newTag */
507  LWLock *newPartitionLock; /* buffer partition lock for it */
508  int buf_id;
509 
510  Assert(BlockNumberIsValid(blockNum));
511 
512  /* create a tag so we can lookup the buffer */
513  INIT_BUFFERTAG(newTag, smgr_reln->smgr_rnode.node,
514  forkNum, blockNum);
515 
516  /* determine its hash code and partition lock ID */
517  newHash = BufTableHashCode(&newTag);
518  newPartitionLock = BufMappingPartitionLock(newHash);
519 
520  /* see if the block is in the buffer pool already */
521  LWLockAcquire(newPartitionLock, LW_SHARED);
522  buf_id = BufTableLookup(&newTag, newHash);
523  LWLockRelease(newPartitionLock);
524 
525  /* If not in buffers, initiate prefetch */
526  if (buf_id < 0)
527  {
528 #ifdef USE_PREFETCH
529  /*
530  * Try to initiate an asynchronous read. This returns false in
531  * recovery if the relation file doesn't exist.
532  */
533  if (smgrprefetch(smgr_reln, forkNum, blockNum))
534  result.initiated_io = true;
535 #endif /* USE_PREFETCH */
536  }
537  else
538  {
539  /*
540  * Report the buffer it was in at that time. The caller may be able
541  * to avoid a buffer table lookup, but it's not pinned and it must be
542  * rechecked!
543  */
544  result.recent_buffer = buf_id + 1;
545  }
546 
547  /*
548  * If the block *is* in buffers, we do nothing. This is not really ideal:
549  * the block might be just about to be evicted, which would be stupid
550  * since we know we are going to need it soon. But the only easy answer
551  * is to bump the usage_count, which does not seem like a great solution:
552  * when the caller does ultimately touch the block, usage_count would get
553  * bumped again, resulting in too much favoritism for blocks that are
554  * involved in a prefetch sequence. A real fix would involve some
555  * additional per-buffer state, and it's not clear that there's enough of
556  * a problem to justify that.
557  */
558 
559  return result;
560 }
561 
562 /*
563  * PrefetchBuffer -- initiate asynchronous read of a block of a relation
564  *
565  * This is named by analogy to ReadBuffer but doesn't actually allocate a
566  * buffer. Instead it tries to ensure that a future ReadBuffer for the given
567  * block will not be delayed by the I/O. Prefetching is optional.
568  *
569  * There are three possible outcomes:
570  *
571  * 1. If the block is already cached, the result includes a valid buffer that
572  * could be used by the caller to avoid the need for a later buffer lookup, but
573  * it's not pinned, so the caller must recheck it.
574  *
575  * 2. If the kernel has been asked to initiate I/O, the initiated_io member is
576  * true. Currently there is no way to know if the data was already cached by
577  * the kernel and therefore didn't really initiate I/O, and no way to know when
578  * the I/O completes other than using synchronous ReadBuffer().
579  *
580  * 3. Otherwise, the buffer wasn't already cached by PostgreSQL, and either
581  * USE_PREFETCH is not defined (this build doesn't support prefetching due to
582  * lack of a kernel facility), or the underlying relation file wasn't found and
583  * we are in recovery. (If the relation file wasn't found and we are not in
584  * recovery, an error is raised).
585  */
588 {
589  Assert(RelationIsValid(reln));
590  Assert(BlockNumberIsValid(blockNum));
591 
592  if (RelationUsesLocalBuffers(reln))
593  {
594  /* see comments in ReadBufferExtended */
595  if (RELATION_IS_OTHER_TEMP(reln))
596  ereport(ERROR,
597  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
598  errmsg("cannot access temporary tables of other sessions")));
599 
600  /* pass it off to localbuf.c */
601  return PrefetchLocalBuffer(RelationGetSmgr(reln), forkNum, blockNum);
602  }
603  else
604  {
605  /* pass it to the shared buffer version */
606  return PrefetchSharedBuffer(RelationGetSmgr(reln), forkNum, blockNum);
607  }
608 }
609 
610 /*
611  * ReadRecentBuffer -- try to pin a block in a recently observed buffer
612  *
613  * Compared to ReadBuffer(), this avoids a buffer mapping lookup when it's
614  * successful. Return true if the buffer is valid and still has the expected
615  * tag. In that case, the buffer is pinned and the usage count is bumped.
616  */
617 bool
619  Buffer recent_buffer)
620 {
621  BufferDesc *bufHdr;
622  BufferTag tag;
623  uint32 buf_state;
624  bool have_private_ref;
625 
626  Assert(BufferIsValid(recent_buffer));
627 
630  INIT_BUFFERTAG(tag, rnode, forkNum, blockNum);
631 
632  if (BufferIsLocal(recent_buffer))
633  {
634  bufHdr = GetBufferDescriptor(-recent_buffer - 1);
635  buf_state = pg_atomic_read_u32(&bufHdr->state);
636 
637  /* Is it still valid and holding the right tag? */
638  if ((buf_state & BM_VALID) && BUFFERTAGS_EQUAL(tag, bufHdr->tag))
639  {
640  /* Bump local buffer's ref and usage counts. */
642  LocalRefCount[-recent_buffer - 1]++;
644  pg_atomic_write_u32(&bufHdr->state,
645  buf_state + BUF_USAGECOUNT_ONE);
646 
647  return true;
648  }
649  }
650  else
651  {
652  bufHdr = GetBufferDescriptor(recent_buffer - 1);
653  have_private_ref = GetPrivateRefCount(recent_buffer) > 0;
654 
655  /*
656  * Do we already have this buffer pinned with a private reference? If
657  * so, it must be valid and it is safe to check the tag without
658  * locking. If not, we have to lock the header first and then check.
659  */
660  if (have_private_ref)
661  buf_state = pg_atomic_read_u32(&bufHdr->state);
662  else
663  buf_state = LockBufHdr(bufHdr);
664 
665  if ((buf_state & BM_VALID) && BUFFERTAGS_EQUAL(tag, bufHdr->tag))
666  {
667  /*
668  * It's now safe to pin the buffer. We can't pin first and ask
669  * questions later, because it might confuse code paths
670  * like InvalidateBuffer() if we pinned a random non-matching
671  * buffer.
672  */
673  if (have_private_ref)
674  PinBuffer(bufHdr, NULL); /* bump pin count */
675  else
676  PinBuffer_Locked(bufHdr); /* pin for first time */
677 
678  return true;
679  }
680 
681  /* If we locked the header above, now unlock. */
682  if (!have_private_ref)
683  UnlockBufHdr(bufHdr, buf_state);
684  }
685 
686  return false;
687 }
688 
689 /*
690  * ReadBuffer -- a shorthand for ReadBufferExtended, for reading from main
691  * fork with RBM_NORMAL mode and default strategy.
692  */
693 Buffer
695 {
696  return ReadBufferExtended(reln, MAIN_FORKNUM, blockNum, RBM_NORMAL, NULL);
697 }
698 
699 /*
700  * ReadBufferExtended -- returns a buffer containing the requested
701  * block of the requested relation. If the blknum
702  * requested is P_NEW, extend the relation file and
703  * allocate a new block. (Caller is responsible for
704  * ensuring that only one backend tries to extend a
705  * relation at the same time!)
706  *
707  * Returns: the buffer number for the buffer containing
708  * the block read. The returned buffer has been pinned.
709  * Does not return on error --- elog's instead.
710  *
711  * Assume when this function is called, that reln has been opened already.
712  *
713  * In RBM_NORMAL mode, the page is read from disk, and the page header is
714  * validated. An error is thrown if the page header is not valid. (But
715  * note that an all-zero page is considered "valid"; see
716  * PageIsVerifiedExtended().)
717  *
718  * RBM_ZERO_ON_ERROR is like the normal mode, but if the page header is not
719  * valid, the page is zeroed instead of throwing an error. This is intended
720  * for non-critical data, where the caller is prepared to repair errors.
721  *
722  * In RBM_ZERO_AND_LOCK mode, if the page isn't in buffer cache already, it's
723  * filled with zeros instead of reading it from disk. Useful when the caller
724  * is going to fill the page from scratch, since this saves I/O and avoids
725  * unnecessary failure if the page-on-disk has corrupt page headers.
726  * The page is returned locked to ensure that the caller has a chance to
727  * initialize the page before it's made visible to others.
728  * Caution: do not use this mode to read a page that is beyond the relation's
729  * current physical EOF; that is likely to cause problems in md.c when
730  * the page is modified and written out. P_NEW is OK, though.
731  *
732  * RBM_ZERO_AND_CLEANUP_LOCK is the same as RBM_ZERO_AND_LOCK, but acquires
733  * a cleanup-strength lock on the page.
734  *
735  * RBM_NORMAL_NO_LOG mode is treated the same as RBM_NORMAL here.
736  *
737  * If strategy is not NULL, a nondefault buffer access strategy is used.
738  * See buffer/README for details.
739  */
740 Buffer
743 {
744  bool hit;
745  Buffer buf;
746 
747  /*
748  * Reject attempts to read non-local temporary relations; we would be
749  * likely to get wrong data since we have no visibility into the owning
750  * session's local buffers.
751  */
752  if (RELATION_IS_OTHER_TEMP(reln))
753  ereport(ERROR,
754  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
755  errmsg("cannot access temporary tables of other sessions")));
756 
757  /*
758  * Read the buffer, and update pgstat counters to reflect a cache hit or
759  * miss.
760  */
762  buf = ReadBuffer_common(RelationGetSmgr(reln), reln->rd_rel->relpersistence,
763  forkNum, blockNum, mode, strategy, &hit);
764  if (hit)
766  return buf;
767 }
768 
769 
770 /*
771  * ReadBufferWithoutRelcache -- like ReadBufferExtended, but doesn't require
772  * a relcache entry for the relation.
773  *
774  * NB: At present, this function may only be used on permanent relations, which
775  * is OK, because we only use it during XLOG replay. If in the future we
776  * want to use it on temporary or unlogged relations, we could pass additional
777  * parameters.
778  */
779 Buffer
781  BlockNumber blockNum, ReadBufferMode mode,
782  BufferAccessStrategy strategy)
783 {
784  bool hit;
785 
786  SMgrRelation smgr = smgropen(rnode, InvalidBackendId);
787 
789 
790  return ReadBuffer_common(smgr, RELPERSISTENCE_PERMANENT, forkNum, blockNum,
791  mode, strategy, &hit);
792 }
793 
794 
795 /*
796  * ReadBuffer_common -- common logic for all ReadBuffer variants
797  *
798  * *hit is set to true if the request was satisfied from shared buffer cache.
799  */
800 static Buffer
801 ReadBuffer_common(SMgrRelation smgr, char relpersistence, ForkNumber forkNum,
802  BlockNumber blockNum, ReadBufferMode mode,
803  BufferAccessStrategy strategy, bool *hit)
804 {
805  BufferDesc *bufHdr;
806  Block bufBlock;
807  bool found;
808  bool isExtend;
809  bool isLocalBuf = SmgrIsTemp(smgr);
810 
811  *hit = false;
812 
813  /* Make sure we will have room to remember the buffer pin */
815 
816  isExtend = (blockNum == P_NEW);
817 
818  TRACE_POSTGRESQL_BUFFER_READ_START(forkNum, blockNum,
819  smgr->smgr_rnode.node.spcNode,
820  smgr->smgr_rnode.node.dbNode,
821  smgr->smgr_rnode.node.relNode,
822  smgr->smgr_rnode.backend,
823  isExtend);
824 
825  /* Substitute proper block number if caller asked for P_NEW */
826  if (isExtend)
827  {
828  blockNum = smgrnblocks(smgr, forkNum);
829  /* Fail if relation is already at maximum possible length */
830  if (blockNum == P_NEW)
831  ereport(ERROR,
832  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
833  errmsg("cannot extend relation %s beyond %u blocks",
834  relpath(smgr->smgr_rnode, forkNum),
835  P_NEW)));
836  }
837 
838  if (isLocalBuf)
839  {
840  bufHdr = LocalBufferAlloc(smgr, forkNum, blockNum, &found);
841  if (found)
843  else if (isExtend)
845  else if (mode == RBM_NORMAL || mode == RBM_NORMAL_NO_LOG ||
846  mode == RBM_ZERO_ON_ERROR)
848  }
849  else
850  {
851  /*
852  * lookup the buffer. IO_IN_PROGRESS is set if the requested block is
853  * not currently in memory.
854  */
855  bufHdr = BufferAlloc(smgr, relpersistence, forkNum, blockNum,
856  strategy, &found);
857  if (found)
859  else if (isExtend)
861  else if (mode == RBM_NORMAL || mode == RBM_NORMAL_NO_LOG ||
862  mode == RBM_ZERO_ON_ERROR)
864  }
865 
866  /* At this point we do NOT hold any locks. */
867 
868  /* if it was already in the buffer pool, we're done */
869  if (found)
870  {
871  if (!isExtend)
872  {
873  /* Just need to update stats before we exit */
874  *hit = true;
875  VacuumPageHit++;
876 
877  if (VacuumCostActive)
879 
880  TRACE_POSTGRESQL_BUFFER_READ_DONE(forkNum, blockNum,
881  smgr->smgr_rnode.node.spcNode,
882  smgr->smgr_rnode.node.dbNode,
883  smgr->smgr_rnode.node.relNode,
884  smgr->smgr_rnode.backend,
885  isExtend,
886  found);
887 
888  /*
889  * In RBM_ZERO_AND_LOCK mode the caller expects the page to be
890  * locked on return.
891  */
892  if (!isLocalBuf)
893  {
894  if (mode == RBM_ZERO_AND_LOCK)
896  LW_EXCLUSIVE);
897  else if (mode == RBM_ZERO_AND_CLEANUP_LOCK)
899  }
900 
901  return BufferDescriptorGetBuffer(bufHdr);
902  }
903 
904  /*
905  * We get here only in the corner case where we are trying to extend
906  * the relation but we found a pre-existing buffer marked BM_VALID.
907  * This can happen because mdread doesn't complain about reads beyond
908  * EOF (when zero_damaged_pages is ON) and so a previous attempt to
909  * read a block beyond EOF could have left a "valid" zero-filled
910  * buffer. Unfortunately, we have also seen this case occurring
911  * because of buggy Linux kernels that sometimes return an
912  * lseek(SEEK_END) result that doesn't account for a recent write. In
913  * that situation, the pre-existing buffer would contain valid data
914  * that we don't want to overwrite. Since the legitimate case should
915  * always have left a zero-filled buffer, complain if not PageIsNew.
916  */
917  bufBlock = isLocalBuf ? LocalBufHdrGetBlock(bufHdr) : BufHdrGetBlock(bufHdr);
918  if (!PageIsNew((Page) bufBlock))
919  ereport(ERROR,
920  (errmsg("unexpected data beyond EOF in block %u of relation %s",
921  blockNum, relpath(smgr->smgr_rnode, forkNum)),
922  errhint("This has been seen to occur with buggy kernels; consider updating your system.")));
923 
924  /*
925  * We *must* do smgrextend before succeeding, else the page will not
926  * be reserved by the kernel, and the next P_NEW call will decide to
927  * return the same page. Clear the BM_VALID bit, do the StartBufferIO
928  * call that BufferAlloc didn't, and proceed.
929  */
930  if (isLocalBuf)
931  {
932  /* Only need to adjust flags */
933  uint32 buf_state = pg_atomic_read_u32(&bufHdr->state);
934 
935  Assert(buf_state & BM_VALID);
936  buf_state &= ~BM_VALID;
937  pg_atomic_unlocked_write_u32(&bufHdr->state, buf_state);
938  }
939  else
940  {
941  /*
942  * Loop to handle the very small possibility that someone re-sets
943  * BM_VALID between our clearing it and StartBufferIO inspecting
944  * it.
945  */
946  do
947  {
948  uint32 buf_state = LockBufHdr(bufHdr);
949 
950  Assert(buf_state & BM_VALID);
951  buf_state &= ~BM_VALID;
952  UnlockBufHdr(bufHdr, buf_state);
953  } while (!StartBufferIO(bufHdr, true));
954  }
955  }
956 
957  /*
958  * if we have gotten to this point, we have allocated a buffer for the
959  * page but its contents are not yet valid. IO_IN_PROGRESS is set for it,
960  * if it's a shared buffer.
961  *
962  * Note: if smgrextend fails, we will end up with a buffer that is
963  * allocated but not marked BM_VALID. P_NEW will still select the same
964  * block number (because the relation didn't get any longer on disk) and
965  * so future attempts to extend the relation will find the same buffer (if
966  * it's not been recycled) but come right back here to try smgrextend
967  * again.
968  */
969  Assert(!(pg_atomic_read_u32(&bufHdr->state) & BM_VALID)); /* spinlock not needed */
970 
971  bufBlock = isLocalBuf ? LocalBufHdrGetBlock(bufHdr) : BufHdrGetBlock(bufHdr);
972 
973  if (isExtend)
974  {
975  /* new buffers are zero-filled */
976  MemSet((char *) bufBlock, 0, BLCKSZ);
977  /* don't set checksum for all-zero page */
978  smgrextend(smgr, forkNum, blockNum, (char *) bufBlock, false);
979 
980  /*
981  * NB: we're *not* doing a ScheduleBufferTagForWriteback here;
982  * although we're essentially performing a write. At least on linux
983  * doing so defeats the 'delayed allocation' mechanism, leading to
984  * increased file fragmentation.
985  */
986  }
987  else
988  {
989  /*
990  * Read in the page, unless the caller intends to overwrite it and
991  * just wants us to allocate a buffer.
992  */
993  if (mode == RBM_ZERO_AND_LOCK || mode == RBM_ZERO_AND_CLEANUP_LOCK)
994  MemSet((char *) bufBlock, 0, BLCKSZ);
995  else
996  {
997  instr_time io_start,
998  io_time;
999 
1000  if (track_io_timing)
1001  INSTR_TIME_SET_CURRENT(io_start);
1002 
1003  smgrread(smgr, forkNum, blockNum, (char *) bufBlock);
1004 
1005  if (track_io_timing)
1006  {
1007  INSTR_TIME_SET_CURRENT(io_time);
1008  INSTR_TIME_SUBTRACT(io_time, io_start);
1011  }
1012 
1013  /* check for garbage data */
1014  if (!PageIsVerifiedExtended((Page) bufBlock, blockNum,
1016  {
1017  if (mode == RBM_ZERO_ON_ERROR || zero_damaged_pages)
1018  {
1019  ereport(WARNING,
1021  errmsg("invalid page in block %u of relation %s; zeroing out page",
1022  blockNum,
1023  relpath(smgr->smgr_rnode, forkNum))));
1024  MemSet((char *) bufBlock, 0, BLCKSZ);
1025  }
1026  else
1027  ereport(ERROR,
1029  errmsg("invalid page in block %u of relation %s",
1030  blockNum,
1031  relpath(smgr->smgr_rnode, forkNum))));
1032  }
1033  }
1034  }
1035 
1036  /*
1037  * In RBM_ZERO_AND_LOCK mode, grab the buffer content lock before marking
1038  * the page as valid, to make sure that no other backend sees the zeroed
1039  * page before the caller has had a chance to initialize it.
1040  *
1041  * Since no-one else can be looking at the page contents yet, there is no
1042  * difference between an exclusive lock and a cleanup-strength lock. (Note
1043  * that we cannot use LockBuffer() or LockBufferForCleanup() here, because
1044  * they assert that the buffer is already valid.)
1045  */
1046  if ((mode == RBM_ZERO_AND_LOCK || mode == RBM_ZERO_AND_CLEANUP_LOCK) &&
1047  !isLocalBuf)
1048  {
1050  }
1051 
1052  if (isLocalBuf)
1053  {
1054  /* Only need to adjust flags */
1055  uint32 buf_state = pg_atomic_read_u32(&bufHdr->state);
1056 
1057  buf_state |= BM_VALID;
1058  pg_atomic_unlocked_write_u32(&bufHdr->state, buf_state);
1059  }
1060  else
1061  {
1062  /* Set BM_VALID, terminate IO, and wake up any waiters */
1063  TerminateBufferIO(bufHdr, false, BM_VALID);
1064  }
1065 
1066  VacuumPageMiss++;
1067  if (VacuumCostActive)
1069 
1070  TRACE_POSTGRESQL_BUFFER_READ_DONE(forkNum, blockNum,
1071  smgr->smgr_rnode.node.spcNode,
1072  smgr->smgr_rnode.node.dbNode,
1073  smgr->smgr_rnode.node.relNode,
1074  smgr->smgr_rnode.backend,
1075  isExtend,
1076  found);
1077 
1078  return BufferDescriptorGetBuffer(bufHdr);
1079 }
1080 
1081 /*
1082  * BufferAlloc -- subroutine for ReadBuffer. Handles lookup of a shared
1083  * buffer. If no buffer exists already, selects a replacement
1084  * victim and evicts the old page, but does NOT read in new page.
1085  *
1086  * "strategy" can be a buffer replacement strategy object, or NULL for
1087  * the default strategy. The selected buffer's usage_count is advanced when
1088  * using the default strategy, but otherwise possibly not (see PinBuffer).
1089  *
1090  * The returned buffer is pinned and is already marked as holding the
1091  * desired page. If it already did have the desired page, *foundPtr is
1092  * set true. Otherwise, *foundPtr is set false and the buffer is marked
1093  * as IO_IN_PROGRESS; ReadBuffer will now need to do I/O to fill it.
1094  *
1095  * *foundPtr is actually redundant with the buffer's BM_VALID flag, but
1096  * we keep it for simplicity in ReadBuffer.
1097  *
1098  * No locks are held either at entry or exit.
1099  */
1100 static BufferDesc *
1101 BufferAlloc(SMgrRelation smgr, char relpersistence, ForkNumber forkNum,
1102  BlockNumber blockNum,
1103  BufferAccessStrategy strategy,
1104  bool *foundPtr)
1105 {
1106  BufferTag newTag; /* identity of requested block */
1107  uint32 newHash; /* hash value for newTag */
1108  LWLock *newPartitionLock; /* buffer partition lock for it */
1109  BufferTag oldTag; /* previous identity of selected buffer */
1110  uint32 oldHash; /* hash value for oldTag */
1111  LWLock *oldPartitionLock; /* buffer partition lock for it */
1112  uint32 oldFlags;
1113  int buf_id;
1114  BufferDesc *buf;
1115  bool valid;
1116  uint32 buf_state;
1117 
1118  /* create a tag so we can lookup the buffer */
1119  INIT_BUFFERTAG(newTag, smgr->smgr_rnode.node, forkNum, blockNum);
1120 
1121  /* determine its hash code and partition lock ID */
1122  newHash = BufTableHashCode(&newTag);
1123  newPartitionLock = BufMappingPartitionLock(newHash);
1124 
1125  /* see if the block is in the buffer pool already */
1126  LWLockAcquire(newPartitionLock, LW_SHARED);
1127  buf_id = BufTableLookup(&newTag, newHash);
1128  if (buf_id >= 0)
1129  {
1130  /*
1131  * Found it. Now, pin the buffer so no one can steal it from the
1132  * buffer pool, and check to see if the correct data has been loaded
1133  * into the buffer.
1134  */
1135  buf = GetBufferDescriptor(buf_id);
1136 
1137  valid = PinBuffer(buf, strategy);
1138 
1139  /* Can release the mapping lock as soon as we've pinned it */
1140  LWLockRelease(newPartitionLock);
1141 
1142  *foundPtr = true;
1143 
1144  if (!valid)
1145  {
1146  /*
1147  * We can only get here if (a) someone else is still reading in
1148  * the page, or (b) a previous read attempt failed. We have to
1149  * wait for any active read attempt to finish, and then set up our
1150  * own read attempt if the page is still not BM_VALID.
1151  * StartBufferIO does it all.
1152  */
1153  if (StartBufferIO(buf, true))
1154  {
1155  /*
1156  * If we get here, previous attempts to read the buffer must
1157  * have failed ... but we shall bravely try again.
1158  */
1159  *foundPtr = false;
1160  }
1161  }
1162 
1163  return buf;
1164  }
1165 
1166  /*
1167  * Didn't find it in the buffer pool. We'll have to initialize a new
1168  * buffer. Remember to unlock the mapping lock while doing the work.
1169  */
1170  LWLockRelease(newPartitionLock);
1171 
1172  /* Loop here in case we have to try another victim buffer */
1173  for (;;)
1174  {
1175  /*
1176  * Ensure, while the spinlock's not yet held, that there's a free
1177  * refcount entry.
1178  */
1180 
1181  /*
1182  * Select a victim buffer. The buffer is returned with its header
1183  * spinlock still held!
1184  */
1185  buf = StrategyGetBuffer(strategy, &buf_state);
1186 
1187  Assert(BUF_STATE_GET_REFCOUNT(buf_state) == 0);
1188 
1189  /* Must copy buffer flags while we still hold the spinlock */
1190  oldFlags = buf_state & BUF_FLAG_MASK;
1191 
1192  /* Pin the buffer and then release the buffer spinlock */
1193  PinBuffer_Locked(buf);
1194 
1195  /*
1196  * If the buffer was dirty, try to write it out. There is a race
1197  * condition here, in that someone might dirty it after we released it
1198  * above, or even while we are writing it out (since our share-lock
1199  * won't prevent hint-bit updates). We will recheck the dirty bit
1200  * after re-locking the buffer header.
1201  */
1202  if (oldFlags & BM_DIRTY)
1203  {
1204  /*
1205  * We need a share-lock on the buffer contents to write it out
1206  * (else we might write invalid data, eg because someone else is
1207  * compacting the page contents while we write). We must use a
1208  * conditional lock acquisition here to avoid deadlock. Even
1209  * though the buffer was not pinned (and therefore surely not
1210  * locked) when StrategyGetBuffer returned it, someone else could
1211  * have pinned and exclusive-locked it by the time we get here. If
1212  * we try to get the lock unconditionally, we'd block waiting for
1213  * them; if they later block waiting for us, deadlock ensues.
1214  * (This has been observed to happen when two backends are both
1215  * trying to split btree index pages, and the second one just
1216  * happens to be trying to split the page the first one got from
1217  * StrategyGetBuffer.)
1218  */
1220  LW_SHARED))
1221  {
1222  /*
1223  * If using a nondefault strategy, and writing the buffer
1224  * would require a WAL flush, let the strategy decide whether
1225  * to go ahead and write/reuse the buffer or to choose another
1226  * victim. We need lock to inspect the page LSN, so this
1227  * can't be done inside StrategyGetBuffer.
1228  */
1229  if (strategy != NULL)
1230  {
1231  XLogRecPtr lsn;
1232 
1233  /* Read the LSN while holding buffer header lock */
1234  buf_state = LockBufHdr(buf);
1235  lsn = BufferGetLSN(buf);
1236  UnlockBufHdr(buf, buf_state);
1237 
1238  if (XLogNeedsFlush(lsn) &&
1239  StrategyRejectBuffer(strategy, buf))
1240  {
1241  /* Drop lock/pin and loop around for another buffer */
1243  UnpinBuffer(buf, true);
1244  continue;
1245  }
1246  }
1247 
1248  /* OK, do the I/O */
1249  TRACE_POSTGRESQL_BUFFER_WRITE_DIRTY_START(forkNum, blockNum,
1250  smgr->smgr_rnode.node.spcNode,
1251  smgr->smgr_rnode.node.dbNode,
1252  smgr->smgr_rnode.node.relNode);
1253 
1254  FlushBuffer(buf, NULL);
1256 
1258  &buf->tag);
1259 
1260  TRACE_POSTGRESQL_BUFFER_WRITE_DIRTY_DONE(forkNum, blockNum,
1261  smgr->smgr_rnode.node.spcNode,
1262  smgr->smgr_rnode.node.dbNode,
1263  smgr->smgr_rnode.node.relNode);
1264  }
1265  else
1266  {
1267  /*
1268  * Someone else has locked the buffer, so give it up and loop
1269  * back to get another one.
1270  */
1271  UnpinBuffer(buf, true);
1272  continue;
1273  }
1274  }
1275 
1276  /*
1277  * To change the association of a valid buffer, we'll need to have
1278  * exclusive lock on both the old and new mapping partitions.
1279  */
1280  if (oldFlags & BM_TAG_VALID)
1281  {
1282  /*
1283  * Need to compute the old tag's hashcode and partition lock ID.
1284  * XXX is it worth storing the hashcode in BufferDesc so we need
1285  * not recompute it here? Probably not.
1286  */
1287  oldTag = buf->tag;
1288  oldHash = BufTableHashCode(&oldTag);
1289  oldPartitionLock = BufMappingPartitionLock(oldHash);
1290 
1291  /*
1292  * Must lock the lower-numbered partition first to avoid
1293  * deadlocks.
1294  */
1295  if (oldPartitionLock < newPartitionLock)
1296  {
1297  LWLockAcquire(oldPartitionLock, LW_EXCLUSIVE);
1298  LWLockAcquire(newPartitionLock, LW_EXCLUSIVE);
1299  }
1300  else if (oldPartitionLock > newPartitionLock)
1301  {
1302  LWLockAcquire(newPartitionLock, LW_EXCLUSIVE);
1303  LWLockAcquire(oldPartitionLock, LW_EXCLUSIVE);
1304  }
1305  else
1306  {
1307  /* only one partition, only one lock */
1308  LWLockAcquire(newPartitionLock, LW_EXCLUSIVE);
1309  }
1310  }
1311  else
1312  {
1313  /* if it wasn't valid, we need only the new partition */
1314  LWLockAcquire(newPartitionLock, LW_EXCLUSIVE);
1315  /* remember we have no old-partition lock or tag */
1316  oldPartitionLock = NULL;
1317  /* keep the compiler quiet about uninitialized variables */
1318  oldHash = 0;
1319  }
1320 
1321  /*
1322  * Try to make a hashtable entry for the buffer under its new tag.
1323  * This could fail because while we were writing someone else
1324  * allocated another buffer for the same block we want to read in.
1325  * Note that we have not yet removed the hashtable entry for the old
1326  * tag.
1327  */
1328  buf_id = BufTableInsert(&newTag, newHash, buf->buf_id);
1329 
1330  if (buf_id >= 0)
1331  {
1332  /*
1333  * Got a collision. Someone has already done what we were about to
1334  * do. We'll just handle this as if it were found in the buffer
1335  * pool in the first place. First, give up the buffer we were
1336  * planning to use.
1337  */
1338  UnpinBuffer(buf, true);
1339 
1340  /* Can give up that buffer's mapping partition lock now */
1341  if (oldPartitionLock != NULL &&
1342  oldPartitionLock != newPartitionLock)
1343  LWLockRelease(oldPartitionLock);
1344 
1345  /* remaining code should match code at top of routine */
1346 
1347  buf = GetBufferDescriptor(buf_id);
1348 
1349  valid = PinBuffer(buf, strategy);
1350 
1351  /* Can release the mapping lock as soon as we've pinned it */
1352  LWLockRelease(newPartitionLock);
1353 
1354  *foundPtr = true;
1355 
1356  if (!valid)
1357  {
1358  /*
1359  * We can only get here if (a) someone else is still reading
1360  * in the page, or (b) a previous read attempt failed. We
1361  * have to wait for any active read attempt to finish, and
1362  * then set up our own read attempt if the page is still not
1363  * BM_VALID. StartBufferIO does it all.
1364  */
1365  if (StartBufferIO(buf, true))
1366  {
1367  /*
1368  * If we get here, previous attempts to read the buffer
1369  * must have failed ... but we shall bravely try again.
1370  */
1371  *foundPtr = false;
1372  }
1373  }
1374 
1375  return buf;
1376  }
1377 
1378  /*
1379  * Need to lock the buffer header too in order to change its tag.
1380  */
1381  buf_state = LockBufHdr(buf);
1382 
1383  /*
1384  * Somebody could have pinned or re-dirtied the buffer while we were
1385  * doing the I/O and making the new hashtable entry. If so, we can't
1386  * recycle this buffer; we must undo everything we've done and start
1387  * over with a new victim buffer.
1388  */
1389  oldFlags = buf_state & BUF_FLAG_MASK;
1390  if (BUF_STATE_GET_REFCOUNT(buf_state) == 1 && !(oldFlags & BM_DIRTY))
1391  break;
1392 
1393  UnlockBufHdr(buf, buf_state);
1394  BufTableDelete(&newTag, newHash);
1395  if (oldPartitionLock != NULL &&
1396  oldPartitionLock != newPartitionLock)
1397  LWLockRelease(oldPartitionLock);
1398  LWLockRelease(newPartitionLock);
1399  UnpinBuffer(buf, true);
1400  }
1401 
1402  /*
1403  * Okay, it's finally safe to rename the buffer.
1404  *
1405  * Clearing BM_VALID here is necessary, clearing the dirtybits is just
1406  * paranoia. We also reset the usage_count since any recency of use of
1407  * the old content is no longer relevant. (The usage_count starts out at
1408  * 1 so that the buffer can survive one clock-sweep pass.)
1409  *
1410  * Make sure BM_PERMANENT is set for buffers that must be written at every
1411  * checkpoint. Unlogged buffers only need to be written at shutdown
1412  * checkpoints, except for their "init" forks, which need to be treated
1413  * just like permanent relations.
1414  */
1415  buf->tag = newTag;
1416  buf_state &= ~(BM_VALID | BM_DIRTY | BM_JUST_DIRTIED |
1419  if (relpersistence == RELPERSISTENCE_PERMANENT || forkNum == INIT_FORKNUM)
1420  buf_state |= BM_TAG_VALID | BM_PERMANENT | BUF_USAGECOUNT_ONE;
1421  else
1422  buf_state |= BM_TAG_VALID | BUF_USAGECOUNT_ONE;
1423 
1424  UnlockBufHdr(buf, buf_state);
1425 
1426  if (oldPartitionLock != NULL)
1427  {
1428  BufTableDelete(&oldTag, oldHash);
1429  if (oldPartitionLock != newPartitionLock)
1430  LWLockRelease(oldPartitionLock);
1431  }
1432 
1433  LWLockRelease(newPartitionLock);
1434 
1435  /*
1436  * Buffer contents are currently invalid. Try to obtain the right to
1437  * start I/O. If StartBufferIO returns false, then someone else managed
1438  * to read it before we did, so there's nothing left for BufferAlloc() to
1439  * do.
1440  */
1441  if (StartBufferIO(buf, true))
1442  *foundPtr = false;
1443  else
1444  *foundPtr = true;
1445 
1446  return buf;
1447 }
1448 
1449 /*
1450  * InvalidateBuffer -- mark a shared buffer invalid and return it to the
1451  * freelist.
1452  *
1453  * The buffer header spinlock must be held at entry. We drop it before
1454  * returning. (This is sane because the caller must have locked the
1455  * buffer in order to be sure it should be dropped.)
1456  *
1457  * This is used only in contexts such as dropping a relation. We assume
1458  * that no other backend could possibly be interested in using the page,
1459  * so the only reason the buffer might be pinned is if someone else is
1460  * trying to write it out. We have to let them finish before we can
1461  * reclaim the buffer.
1462  *
1463  * The buffer could get reclaimed by someone else while we are waiting
1464  * to acquire the necessary locks; if so, don't mess it up.
1465  */
1466 static void
1468 {
1469  BufferTag oldTag;
1470  uint32 oldHash; /* hash value for oldTag */
1471  LWLock *oldPartitionLock; /* buffer partition lock for it */
1472  uint32 oldFlags;
1473  uint32 buf_state;
1474 
1475  /* Save the original buffer tag before dropping the spinlock */
1476  oldTag = buf->tag;
1477 
1478  buf_state = pg_atomic_read_u32(&buf->state);
1479  Assert(buf_state & BM_LOCKED);
1480  UnlockBufHdr(buf, buf_state);
1481 
1482  /*
1483  * Need to compute the old tag's hashcode and partition lock ID. XXX is it
1484  * worth storing the hashcode in BufferDesc so we need not recompute it
1485  * here? Probably not.
1486  */
1487  oldHash = BufTableHashCode(&oldTag);
1488  oldPartitionLock = BufMappingPartitionLock(oldHash);
1489 
1490 retry:
1491 
1492  /*
1493  * Acquire exclusive mapping lock in preparation for changing the buffer's
1494  * association.
1495  */
1496  LWLockAcquire(oldPartitionLock, LW_EXCLUSIVE);
1497 
1498  /* Re-lock the buffer header */
1499  buf_state = LockBufHdr(buf);
1500 
1501  /* If it's changed while we were waiting for lock, do nothing */
1502  if (!BUFFERTAGS_EQUAL(buf->tag, oldTag))
1503  {
1504  UnlockBufHdr(buf, buf_state);
1505  LWLockRelease(oldPartitionLock);
1506  return;
1507  }
1508 
1509  /*
1510  * We assume the only reason for it to be pinned is that someone else is
1511  * flushing the page out. Wait for them to finish. (This could be an
1512  * infinite loop if the refcount is messed up... it would be nice to time
1513  * out after awhile, but there seems no way to be sure how many loops may
1514  * be needed. Note that if the other guy has pinned the buffer but not
1515  * yet done StartBufferIO, WaitIO will fall through and we'll effectively
1516  * be busy-looping here.)
1517  */
1518  if (BUF_STATE_GET_REFCOUNT(buf_state) != 0)
1519  {
1520  UnlockBufHdr(buf, buf_state);
1521  LWLockRelease(oldPartitionLock);
1522  /* safety check: should definitely not be our *own* pin */
1524  elog(ERROR, "buffer is pinned in InvalidateBuffer");
1525  WaitIO(buf);
1526  goto retry;
1527  }
1528 
1529  /*
1530  * Clear out the buffer's tag and flags. We must do this to ensure that
1531  * linear scans of the buffer array don't think the buffer is valid.
1532  */
1533  oldFlags = buf_state & BUF_FLAG_MASK;
1534  CLEAR_BUFFERTAG(buf->tag);
1535  buf_state &= ~(BUF_FLAG_MASK | BUF_USAGECOUNT_MASK);
1536  UnlockBufHdr(buf, buf_state);
1537 
1538  /*
1539  * Remove the buffer from the lookup hashtable, if it was in there.
1540  */
1541  if (oldFlags & BM_TAG_VALID)
1542  BufTableDelete(&oldTag, oldHash);
1543 
1544  /*
1545  * Done with mapping lock.
1546  */
1547  LWLockRelease(oldPartitionLock);
1548 
1549  /*
1550  * Insert the buffer at the head of the list of free buffers.
1551  */
1552  StrategyFreeBuffer(buf);
1553 }
1554 
1555 /*
1556  * MarkBufferDirty
1557  *
1558  * Marks buffer contents as dirty (actual write happens later).
1559  *
1560  * Buffer must be pinned and exclusive-locked. (If caller does not hold
1561  * exclusive lock, then somebody could be in process of writing the buffer,
1562  * leading to risk of bad data written to disk.)
1563  */
1564 void
1566 {
1567  BufferDesc *bufHdr;
1568  uint32 buf_state;
1569  uint32 old_buf_state;
1570 
1571  if (!BufferIsValid(buffer))
1572  elog(ERROR, "bad buffer ID: %d", buffer);
1573 
1574  if (BufferIsLocal(buffer))
1575  {
1576  MarkLocalBufferDirty(buffer);
1577  return;
1578  }
1579 
1580  bufHdr = GetBufferDescriptor(buffer - 1);
1581 
1582  Assert(BufferIsPinned(buffer));
1584  LW_EXCLUSIVE));
1585 
1586  old_buf_state = pg_atomic_read_u32(&bufHdr->state);
1587  for (;;)
1588  {
1589  if (old_buf_state & BM_LOCKED)
1590  old_buf_state = WaitBufHdrUnlocked(bufHdr);
1591 
1592  buf_state = old_buf_state;
1593 
1594  Assert(BUF_STATE_GET_REFCOUNT(buf_state) > 0);
1595  buf_state |= BM_DIRTY | BM_JUST_DIRTIED;
1596 
1597  if (pg_atomic_compare_exchange_u32(&bufHdr->state, &old_buf_state,
1598  buf_state))
1599  break;
1600  }
1601 
1602  /*
1603  * If the buffer was not dirty already, do vacuum accounting.
1604  */
1605  if (!(old_buf_state & BM_DIRTY))
1606  {
1607  VacuumPageDirty++;
1609  if (VacuumCostActive)
1611  }
1612 }
1613 
1614 /*
1615  * ReleaseAndReadBuffer -- combine ReleaseBuffer() and ReadBuffer()
1616  *
1617  * Formerly, this saved one cycle of acquiring/releasing the BufMgrLock
1618  * compared to calling the two routines separately. Now it's mainly just
1619  * a convenience function. However, if the passed buffer is valid and
1620  * already contains the desired block, we just return it as-is; and that
1621  * does save considerable work compared to a full release and reacquire.
1622  *
1623  * Note: it is OK to pass buffer == InvalidBuffer, indicating that no old
1624  * buffer actually needs to be released. This case is the same as ReadBuffer,
1625  * but can save some tests in the caller.
1626  */
1627 Buffer
1629  Relation relation,
1630  BlockNumber blockNum)
1631 {
1632  ForkNumber forkNum = MAIN_FORKNUM;
1633  BufferDesc *bufHdr;
1634 
1635  if (BufferIsValid(buffer))
1636  {
1637  Assert(BufferIsPinned(buffer));
1638  if (BufferIsLocal(buffer))
1639  {
1640  bufHdr = GetLocalBufferDescriptor(-buffer - 1);
1641  if (bufHdr->tag.blockNum == blockNum &&
1642  RelFileNodeEquals(bufHdr->tag.rnode, relation->rd_node) &&
1643  bufHdr->tag.forkNum == forkNum)
1644  return buffer;
1646  LocalRefCount[-buffer - 1]--;
1647  }
1648  else
1649  {
1650  bufHdr = GetBufferDescriptor(buffer - 1);
1651  /* we have pin, so it's ok to examine tag without spinlock */
1652  if (bufHdr->tag.blockNum == blockNum &&
1653  RelFileNodeEquals(bufHdr->tag.rnode, relation->rd_node) &&
1654  bufHdr->tag.forkNum == forkNum)
1655  return buffer;
1656  UnpinBuffer(bufHdr, true);
1657  }
1658  }
1659 
1660  return ReadBuffer(relation, blockNum);
1661 }
1662 
1663 /*
1664  * PinBuffer -- make buffer unavailable for replacement.
1665  *
1666  * For the default access strategy, the buffer's usage_count is incremented
1667  * when we first pin it; for other strategies we just make sure the usage_count
1668  * isn't zero. (The idea of the latter is that we don't want synchronized
1669  * heap scans to inflate the count, but we need it to not be zero to discourage
1670  * other backends from stealing buffers from our ring. As long as we cycle
1671  * through the ring faster than the global clock-sweep cycles, buffers in
1672  * our ring won't be chosen as victims for replacement by other backends.)
1673  *
1674  * This should be applied only to shared buffers, never local ones.
1675  *
1676  * Since buffers are pinned/unpinned very frequently, pin buffers without
1677  * taking the buffer header lock; instead update the state variable in loop of
1678  * CAS operations. Hopefully it's just a single CAS.
1679  *
1680  * Note that ResourceOwnerEnlargeBuffers must have been done already.
1681  *
1682  * Returns true if buffer is BM_VALID, else false. This provision allows
1683  * some callers to avoid an extra spinlock cycle.
1684  */
1685 static bool
1687 {
1689  bool result;
1690  PrivateRefCountEntry *ref;
1691 
1692  ref = GetPrivateRefCountEntry(b, true);
1693 
1694  if (ref == NULL)
1695  {
1696  uint32 buf_state;
1697  uint32 old_buf_state;
1698 
1700  ref = NewPrivateRefCountEntry(b);
1701 
1702  old_buf_state = pg_atomic_read_u32(&buf->state);
1703  for (;;)
1704  {
1705  if (old_buf_state & BM_LOCKED)
1706  old_buf_state = WaitBufHdrUnlocked(buf);
1707 
1708  buf_state = old_buf_state;
1709 
1710  /* increase refcount */
1711  buf_state += BUF_REFCOUNT_ONE;
1712 
1713  if (strategy == NULL)
1714  {
1715  /* Default case: increase usagecount unless already max. */
1717  buf_state += BUF_USAGECOUNT_ONE;
1718  }
1719  else
1720  {
1721  /*
1722  * Ring buffers shouldn't evict others from pool. Thus we
1723  * don't make usagecount more than 1.
1724  */
1725  if (BUF_STATE_GET_USAGECOUNT(buf_state) == 0)
1726  buf_state += BUF_USAGECOUNT_ONE;
1727  }
1728 
1729  if (pg_atomic_compare_exchange_u32(&buf->state, &old_buf_state,
1730  buf_state))
1731  {
1732  result = (buf_state & BM_VALID) != 0;
1733 
1734  /*
1735  * Assume that we acquired a buffer pin for the purposes of
1736  * Valgrind buffer client checks (even in !result case) to
1737  * keep things simple. Buffers that are unsafe to access are
1738  * not generally guaranteed to be marked undefined or
1739  * non-accessible in any case.
1740  */
1742  break;
1743  }
1744  }
1745  }
1746  else
1747  {
1748  /*
1749  * If we previously pinned the buffer, it must surely be valid.
1750  *
1751  * Note: We deliberately avoid a Valgrind client request here.
1752  * Individual access methods can optionally superimpose buffer page
1753  * client requests on top of our client requests to enforce that
1754  * buffers are only accessed while locked (and pinned). It's possible
1755  * that the buffer page is legitimately non-accessible here. We
1756  * cannot meddle with that.
1757  */
1758  result = true;
1759  }
1760 
1761  ref->refcount++;
1762  Assert(ref->refcount > 0);
1764  return result;
1765 }
1766 
1767 /*
1768  * PinBuffer_Locked -- as above, but caller already locked the buffer header.
1769  * The spinlock is released before return.
1770  *
1771  * As this function is called with the spinlock held, the caller has to
1772  * previously call ReservePrivateRefCountEntry().
1773  *
1774  * Currently, no callers of this function want to modify the buffer's
1775  * usage_count at all, so there's no need for a strategy parameter.
1776  * Also we don't bother with a BM_VALID test (the caller could check that for
1777  * itself).
1778  *
1779  * Also all callers only ever use this function when it's known that the
1780  * buffer can't have a preexisting pin by this backend. That allows us to skip
1781  * searching the private refcount array & hash, which is a boon, because the
1782  * spinlock is still held.
1783  *
1784  * Note: use of this routine is frequently mandatory, not just an optimization
1785  * to save a spin lock/unlock cycle, because we need to pin a buffer before
1786  * its state can change under us.
1787  */
1788 static void
1790 {
1791  Buffer b;
1792  PrivateRefCountEntry *ref;
1793  uint32 buf_state;
1794 
1795  /*
1796  * As explained, We don't expect any preexisting pins. That allows us to
1797  * manipulate the PrivateRefCount after releasing the spinlock
1798  */
1800 
1801  /*
1802  * Buffer can't have a preexisting pin, so mark its page as defined to
1803  * Valgrind (this is similar to the PinBuffer() case where the backend
1804  * doesn't already have a buffer pin)
1805  */
1807 
1808  /*
1809  * Since we hold the buffer spinlock, we can update the buffer state and
1810  * release the lock in one operation.
1811  */
1812  buf_state = pg_atomic_read_u32(&buf->state);
1813  Assert(buf_state & BM_LOCKED);
1814  buf_state += BUF_REFCOUNT_ONE;
1815  UnlockBufHdr(buf, buf_state);
1816 
1817  b = BufferDescriptorGetBuffer(buf);
1818 
1819  ref = NewPrivateRefCountEntry(b);
1820  ref->refcount++;
1821 
1823 }
1824 
1825 /*
1826  * UnpinBuffer -- make buffer available for replacement.
1827  *
1828  * This should be applied only to shared buffers, never local ones.
1829  *
1830  * Most but not all callers want CurrentResourceOwner to be adjusted.
1831  * Those that don't should pass fixOwner = false.
1832  */
1833 static void
1834 UnpinBuffer(BufferDesc *buf, bool fixOwner)
1835 {
1836  PrivateRefCountEntry *ref;
1838 
1839  /* not moving as we're likely deleting it soon anyway */
1840  ref = GetPrivateRefCountEntry(b, false);
1841  Assert(ref != NULL);
1842 
1843  if (fixOwner)
1845 
1846  Assert(ref->refcount > 0);
1847  ref->refcount--;
1848  if (ref->refcount == 0)
1849  {
1850  uint32 buf_state;
1851  uint32 old_buf_state;
1852 
1853  /*
1854  * Mark buffer non-accessible to Valgrind.
1855  *
1856  * Note that the buffer may have already been marked non-accessible
1857  * within access method code that enforces that buffers are only
1858  * accessed while a buffer lock is held.
1859  */
1861 
1862  /* I'd better not still hold the buffer content lock */
1864 
1865  /*
1866  * Decrement the shared reference count.
1867  *
1868  * Since buffer spinlock holder can update status using just write,
1869  * it's not safe to use atomic decrement here; thus use a CAS loop.
1870  */
1871  old_buf_state = pg_atomic_read_u32(&buf->state);
1872  for (;;)
1873  {
1874  if (old_buf_state & BM_LOCKED)
1875  old_buf_state = WaitBufHdrUnlocked(buf);
1876 
1877  buf_state = old_buf_state;
1878 
1879  buf_state -= BUF_REFCOUNT_ONE;
1880 
1881  if (pg_atomic_compare_exchange_u32(&buf->state, &old_buf_state,
1882  buf_state))
1883  break;
1884  }
1885 
1886  /* Support LockBufferForCleanup() */
1887  if (buf_state & BM_PIN_COUNT_WAITER)
1888  {
1889  /*
1890  * Acquire the buffer header lock, re-check that there's a waiter.
1891  * Another backend could have unpinned this buffer, and already
1892  * woken up the waiter. There's no danger of the buffer being
1893  * replaced after we unpinned it above, as it's pinned by the
1894  * waiter.
1895  */
1896  buf_state = LockBufHdr(buf);
1897 
1898  if ((buf_state & BM_PIN_COUNT_WAITER) &&
1899  BUF_STATE_GET_REFCOUNT(buf_state) == 1)
1900  {
1901  /* we just released the last pin other than the waiter's */
1902  int wait_backend_pid = buf->wait_backend_pid;
1903 
1904  buf_state &= ~BM_PIN_COUNT_WAITER;
1905  UnlockBufHdr(buf, buf_state);
1906  ProcSendSignal(wait_backend_pid);
1907  }
1908  else
1909  UnlockBufHdr(buf, buf_state);
1910  }
1912  }
1913 }
1914 
1915 #define ST_SORT sort_checkpoint_bufferids
1916 #define ST_ELEMENT_TYPE CkptSortItem
1917 #define ST_COMPARE(a, b) ckpt_buforder_comparator(a, b)
1918 #define ST_SCOPE static
1919 #define ST_DEFINE
1920 #include <lib/sort_template.h>
1921 
1922 /*
1923  * BufferSync -- Write out all dirty buffers in the pool.
1924  *
1925  * This is called at checkpoint time to write out all dirty shared buffers.
1926  * The checkpoint request flags should be passed in. If CHECKPOINT_IMMEDIATE
1927  * is set, we disable delays between writes; if CHECKPOINT_IS_SHUTDOWN,
1928  * CHECKPOINT_END_OF_RECOVERY or CHECKPOINT_FLUSH_ALL is set, we write even
1929  * unlogged buffers, which are otherwise skipped. The remaining flags
1930  * currently have no effect here.
1931  */
1932 static void
1933 BufferSync(int flags)
1934 {
1935  uint32 buf_state;
1936  int buf_id;
1937  int num_to_scan;
1938  int num_spaces;
1939  int num_processed;
1940  int num_written;
1941  CkptTsStatus *per_ts_stat = NULL;
1942  Oid last_tsid;
1943  binaryheap *ts_heap;
1944  int i;
1945  int mask = BM_DIRTY;
1946  WritebackContext wb_context;
1947 
1948  /* Make sure we can handle the pin inside SyncOneBuffer */
1950 
1951  /*
1952  * Unless this is a shutdown checkpoint or we have been explicitly told,
1953  * we write only permanent, dirty buffers. But at shutdown or end of
1954  * recovery, we write all dirty buffers.
1955  */
1958  mask |= BM_PERMANENT;
1959 
1960  /*
1961  * Loop over all buffers, and mark the ones that need to be written with
1962  * BM_CHECKPOINT_NEEDED. Count them as we go (num_to_scan), so that we
1963  * can estimate how much work needs to be done.
1964  *
1965  * This allows us to write only those pages that were dirty when the
1966  * checkpoint began, and not those that get dirtied while it proceeds.
1967  * Whenever a page with BM_CHECKPOINT_NEEDED is written out, either by us
1968  * later in this function, or by normal backends or the bgwriter cleaning
1969  * scan, the flag is cleared. Any buffer dirtied after this point won't
1970  * have the flag set.
1971  *
1972  * Note that if we fail to write some buffer, we may leave buffers with
1973  * BM_CHECKPOINT_NEEDED still set. This is OK since any such buffer would
1974  * certainly need to be written for the next checkpoint attempt, too.
1975  */
1976  num_to_scan = 0;
1977  for (buf_id = 0; buf_id < NBuffers; buf_id++)
1978  {
1979  BufferDesc *bufHdr = GetBufferDescriptor(buf_id);
1980 
1981  /*
1982  * Header spinlock is enough to examine BM_DIRTY, see comment in
1983  * SyncOneBuffer.
1984  */
1985  buf_state = LockBufHdr(bufHdr);
1986 
1987  if ((buf_state & mask) == mask)
1988  {
1989  CkptSortItem *item;
1990 
1991  buf_state |= BM_CHECKPOINT_NEEDED;
1992 
1993  item = &CkptBufferIds[num_to_scan++];
1994  item->buf_id = buf_id;
1995  item->tsId = bufHdr->tag.rnode.spcNode;
1996  item->relNode = bufHdr->tag.rnode.relNode;
1997  item->forkNum = bufHdr->tag.forkNum;
1998  item->blockNum = bufHdr->tag.blockNum;
1999  }
2000 
2001  UnlockBufHdr(bufHdr, buf_state);
2002 
2003  /* Check for barrier events in case NBuffers is large. */
2006  }
2007 
2008  if (num_to_scan == 0)
2009  return; /* nothing to do */
2010 
2012 
2013  TRACE_POSTGRESQL_BUFFER_SYNC_START(NBuffers, num_to_scan);
2014 
2015  /*
2016  * Sort buffers that need to be written to reduce the likelihood of random
2017  * IO. The sorting is also important for the implementation of balancing
2018  * writes between tablespaces. Without balancing writes we'd potentially
2019  * end up writing to the tablespaces one-by-one; possibly overloading the
2020  * underlying system.
2021  */
2022  sort_checkpoint_bufferids(CkptBufferIds, num_to_scan);
2023 
2024  num_spaces = 0;
2025 
2026  /*
2027  * Allocate progress status for each tablespace with buffers that need to
2028  * be flushed. This requires the to-be-flushed array to be sorted.
2029  */
2030  last_tsid = InvalidOid;
2031  for (i = 0; i < num_to_scan; i++)
2032  {
2033  CkptTsStatus *s;
2034  Oid cur_tsid;
2035 
2036  cur_tsid = CkptBufferIds[i].tsId;
2037 
2038  /*
2039  * Grow array of per-tablespace status structs, every time a new
2040  * tablespace is found.
2041  */
2042  if (last_tsid == InvalidOid || last_tsid != cur_tsid)
2043  {
2044  Size sz;
2045 
2046  num_spaces++;
2047 
2048  /*
2049  * Not worth adding grow-by-power-of-2 logic here - even with a
2050  * few hundred tablespaces this should be fine.
2051  */
2052  sz = sizeof(CkptTsStatus) * num_spaces;
2053 
2054  if (per_ts_stat == NULL)
2055  per_ts_stat = (CkptTsStatus *) palloc(sz);
2056  else
2057  per_ts_stat = (CkptTsStatus *) repalloc(per_ts_stat, sz);
2058 
2059  s = &per_ts_stat[num_spaces - 1];
2060  memset(s, 0, sizeof(*s));
2061  s->tsId = cur_tsid;
2062 
2063  /*
2064  * The first buffer in this tablespace. As CkptBufferIds is sorted
2065  * by tablespace all (s->num_to_scan) buffers in this tablespace
2066  * will follow afterwards.
2067  */
2068  s->index = i;
2069 
2070  /*
2071  * progress_slice will be determined once we know how many buffers
2072  * are in each tablespace, i.e. after this loop.
2073  */
2074 
2075  last_tsid = cur_tsid;
2076  }
2077  else
2078  {
2079  s = &per_ts_stat[num_spaces - 1];
2080  }
2081 
2082  s->num_to_scan++;
2083 
2084  /* Check for barrier events. */
2087  }
2088 
2089  Assert(num_spaces > 0);
2090 
2091  /*
2092  * Build a min-heap over the write-progress in the individual tablespaces,
2093  * and compute how large a portion of the total progress a single
2094  * processed buffer is.
2095  */
2096  ts_heap = binaryheap_allocate(num_spaces,
2098  NULL);
2099 
2100  for (i = 0; i < num_spaces; i++)
2101  {
2102  CkptTsStatus *ts_stat = &per_ts_stat[i];
2103 
2104  ts_stat->progress_slice = (float8) num_to_scan / ts_stat->num_to_scan;
2105 
2106  binaryheap_add_unordered(ts_heap, PointerGetDatum(ts_stat));
2107  }
2108 
2109  binaryheap_build(ts_heap);
2110 
2111  /*
2112  * Iterate through to-be-checkpointed buffers and write the ones (still)
2113  * marked with BM_CHECKPOINT_NEEDED. The writes are balanced between
2114  * tablespaces; otherwise the sorting would lead to only one tablespace
2115  * receiving writes at a time, making inefficient use of the hardware.
2116  */
2117  num_processed = 0;
2118  num_written = 0;
2119  while (!binaryheap_empty(ts_heap))
2120  {
2121  BufferDesc *bufHdr = NULL;
2122  CkptTsStatus *ts_stat = (CkptTsStatus *)
2124 
2125  buf_id = CkptBufferIds[ts_stat->index].buf_id;
2126  Assert(buf_id != -1);
2127 
2128  bufHdr = GetBufferDescriptor(buf_id);
2129 
2130  num_processed++;
2131 
2132  /*
2133  * We don't need to acquire the lock here, because we're only looking
2134  * at a single bit. It's possible that someone else writes the buffer
2135  * and clears the flag right after we check, but that doesn't matter
2136  * since SyncOneBuffer will then do nothing. However, there is a
2137  * further race condition: it's conceivable that between the time we
2138  * examine the bit here and the time SyncOneBuffer acquires the lock,
2139  * someone else not only wrote the buffer but replaced it with another
2140  * page and dirtied it. In that improbable case, SyncOneBuffer will
2141  * write the buffer though we didn't need to. It doesn't seem worth
2142  * guarding against this, though.
2143  */
2145  {
2146  if (SyncOneBuffer(buf_id, false, &wb_context) & BUF_WRITTEN)
2147  {
2148  TRACE_POSTGRESQL_BUFFER_SYNC_WRITTEN(buf_id);
2150  num_written++;
2151  }
2152  }
2153 
2154  /*
2155  * Measure progress independent of actually having to flush the buffer
2156  * - otherwise writing become unbalanced.
2157  */
2158  ts_stat->progress += ts_stat->progress_slice;
2159  ts_stat->num_scanned++;
2160  ts_stat->index++;
2161 
2162  /* Have all the buffers from the tablespace been processed? */
2163  if (ts_stat->num_scanned == ts_stat->num_to_scan)
2164  {
2165  binaryheap_remove_first(ts_heap);
2166  }
2167  else
2168  {
2169  /* update heap with the new progress */
2170  binaryheap_replace_first(ts_heap, PointerGetDatum(ts_stat));
2171  }
2172 
2173  /*
2174  * Sleep to throttle our I/O rate.
2175  *
2176  * (This will check for barrier events even if it doesn't sleep.)
2177  */
2178  CheckpointWriteDelay(flags, (double) num_processed / num_to_scan);
2179  }
2180 
2181  /* issue all pending flushes */
2182  IssuePendingWritebacks(&wb_context);
2183 
2184  pfree(per_ts_stat);
2185  per_ts_stat = NULL;
2186  binaryheap_free(ts_heap);
2187 
2188  /*
2189  * Update checkpoint statistics. As noted above, this doesn't include
2190  * buffers written by other backends or bgwriter scan.
2191  */
2192  CheckpointStats.ckpt_bufs_written += num_written;
2193 
2194  TRACE_POSTGRESQL_BUFFER_SYNC_DONE(NBuffers, num_written, num_to_scan);
2195 }
2196 
2197 /*
2198  * BgBufferSync -- Write out some dirty buffers in the pool.
2199  *
2200  * This is called periodically by the background writer process.
2201  *
2202  * Returns true if it's appropriate for the bgwriter process to go into
2203  * low-power hibernation mode. (This happens if the strategy clock sweep
2204  * has been "lapped" and no buffer allocations have occurred recently,
2205  * or if the bgwriter has been effectively disabled by setting
2206  * bgwriter_lru_maxpages to 0.)
2207  */
2208 bool
2210 {
2211  /* info obtained from freelist.c */
2212  int strategy_buf_id;
2213  uint32 strategy_passes;
2214  uint32 recent_alloc;
2215 
2216  /*
2217  * Information saved between calls so we can determine the strategy
2218  * point's advance rate and avoid scanning already-cleaned buffers.
2219  */
2220  static bool saved_info_valid = false;
2221  static int prev_strategy_buf_id;
2222  static uint32 prev_strategy_passes;
2223  static int next_to_clean;
2224  static uint32 next_passes;
2225 
2226  /* Moving averages of allocation rate and clean-buffer density */
2227  static float smoothed_alloc = 0;
2228  static float smoothed_density = 10.0;
2229 
2230  /* Potentially these could be tunables, but for now, not */
2231  float smoothing_samples = 16;
2232  float scan_whole_pool_milliseconds = 120000.0;
2233 
2234  /* Used to compute how far we scan ahead */
2235  long strategy_delta;
2236  int bufs_to_lap;
2237  int bufs_ahead;
2238  float scans_per_alloc;
2239  int reusable_buffers_est;
2240  int upcoming_alloc_est;
2241  int min_scan_buffers;
2242 
2243  /* Variables for the scanning loop proper */
2244  int num_to_scan;
2245  int num_written;
2246  int reusable_buffers;
2247 
2248  /* Variables for final smoothed_density update */
2249  long new_strategy_delta;
2250  uint32 new_recent_alloc;
2251 
2252  /*
2253  * Find out where the freelist clock sweep currently is, and how many
2254  * buffer allocations have happened since our last call.
2255  */
2256  strategy_buf_id = StrategySyncStart(&strategy_passes, &recent_alloc);
2257 
2258  /* Report buffer alloc counts to pgstat */
2259  PendingBgWriterStats.m_buf_alloc += recent_alloc;
2260 
2261  /*
2262  * If we're not running the LRU scan, just stop after doing the stats
2263  * stuff. We mark the saved state invalid so that we can recover sanely
2264  * if LRU scan is turned back on later.
2265  */
2266  if (bgwriter_lru_maxpages <= 0)
2267  {
2268  saved_info_valid = false;
2269  return true;
2270  }
2271 
2272  /*
2273  * Compute strategy_delta = how many buffers have been scanned by the
2274  * clock sweep since last time. If first time through, assume none. Then
2275  * see if we are still ahead of the clock sweep, and if so, how many
2276  * buffers we could scan before we'd catch up with it and "lap" it. Note:
2277  * weird-looking coding of xxx_passes comparisons are to avoid bogus
2278  * behavior when the passes counts wrap around.
2279  */
2280  if (saved_info_valid)
2281  {
2282  int32 passes_delta = strategy_passes - prev_strategy_passes;
2283 
2284  strategy_delta = strategy_buf_id - prev_strategy_buf_id;
2285  strategy_delta += (long) passes_delta * NBuffers;
2286 
2287  Assert(strategy_delta >= 0);
2288 
2289  if ((int32) (next_passes - strategy_passes) > 0)
2290  {
2291  /* we're one pass ahead of the strategy point */
2292  bufs_to_lap = strategy_buf_id - next_to_clean;
2293 #ifdef BGW_DEBUG
2294  elog(DEBUG2, "bgwriter ahead: bgw %u-%u strategy %u-%u delta=%ld lap=%d",
2295  next_passes, next_to_clean,
2296  strategy_passes, strategy_buf_id,
2297  strategy_delta, bufs_to_lap);
2298 #endif
2299  }
2300  else if (next_passes == strategy_passes &&
2301  next_to_clean >= strategy_buf_id)
2302  {
2303  /* on same pass, but ahead or at least not behind */
2304  bufs_to_lap = NBuffers - (next_to_clean - strategy_buf_id);
2305 #ifdef BGW_DEBUG
2306  elog(DEBUG2, "bgwriter ahead: bgw %u-%u strategy %u-%u delta=%ld lap=%d",
2307  next_passes, next_to_clean,
2308  strategy_passes, strategy_buf_id,
2309  strategy_delta, bufs_to_lap);
2310 #endif
2311  }
2312  else
2313  {
2314  /*
2315  * We're behind, so skip forward to the strategy point and start
2316  * cleaning from there.
2317  */
2318 #ifdef BGW_DEBUG
2319  elog(DEBUG2, "bgwriter behind: bgw %u-%u strategy %u-%u delta=%ld",
2320  next_passes, next_to_clean,
2321  strategy_passes, strategy_buf_id,
2322  strategy_delta);
2323 #endif
2324  next_to_clean = strategy_buf_id;
2325  next_passes = strategy_passes;
2326  bufs_to_lap = NBuffers;
2327  }
2328  }
2329  else
2330  {
2331  /*
2332  * Initializing at startup or after LRU scanning had been off. Always
2333  * start at the strategy point.
2334  */
2335 #ifdef BGW_DEBUG
2336  elog(DEBUG2, "bgwriter initializing: strategy %u-%u",
2337  strategy_passes, strategy_buf_id);
2338 #endif
2339  strategy_delta = 0;
2340  next_to_clean = strategy_buf_id;
2341  next_passes = strategy_passes;
2342  bufs_to_lap = NBuffers;
2343  }
2344 
2345  /* Update saved info for next time */
2346  prev_strategy_buf_id = strategy_buf_id;
2347  prev_strategy_passes = strategy_passes;
2348  saved_info_valid = true;
2349 
2350  /*
2351  * Compute how many buffers had to be scanned for each new allocation, ie,
2352  * 1/density of reusable buffers, and track a moving average of that.
2353  *
2354  * If the strategy point didn't move, we don't update the density estimate
2355  */
2356  if (strategy_delta > 0 && recent_alloc > 0)
2357  {
2358  scans_per_alloc = (float) strategy_delta / (float) recent_alloc;
2359  smoothed_density += (scans_per_alloc - smoothed_density) /
2360  smoothing_samples;
2361  }
2362 
2363  /*
2364  * Estimate how many reusable buffers there are between the current
2365  * strategy point and where we've scanned ahead to, based on the smoothed
2366  * density estimate.
2367  */
2368  bufs_ahead = NBuffers - bufs_to_lap;
2369  reusable_buffers_est = (float) bufs_ahead / smoothed_density;
2370 
2371  /*
2372  * Track a moving average of recent buffer allocations. Here, rather than
2373  * a true average we want a fast-attack, slow-decline behavior: we
2374  * immediately follow any increase.
2375  */
2376  if (smoothed_alloc <= (float) recent_alloc)
2377  smoothed_alloc = recent_alloc;
2378  else
2379  smoothed_alloc += ((float) recent_alloc - smoothed_alloc) /
2380  smoothing_samples;
2381 
2382  /* Scale the estimate by a GUC to allow more aggressive tuning. */
2383  upcoming_alloc_est = (int) (smoothed_alloc * bgwriter_lru_multiplier);
2384 
2385  /*
2386  * If recent_alloc remains at zero for many cycles, smoothed_alloc will
2387  * eventually underflow to zero, and the underflows produce annoying
2388  * kernel warnings on some platforms. Once upcoming_alloc_est has gone to
2389  * zero, there's no point in tracking smaller and smaller values of
2390  * smoothed_alloc, so just reset it to exactly zero to avoid this
2391  * syndrome. It will pop back up as soon as recent_alloc increases.
2392  */
2393  if (upcoming_alloc_est == 0)
2394  smoothed_alloc = 0;
2395 
2396  /*
2397  * Even in cases where there's been little or no buffer allocation
2398  * activity, we want to make a small amount of progress through the buffer
2399  * cache so that as many reusable buffers as possible are clean after an
2400  * idle period.
2401  *
2402  * (scan_whole_pool_milliseconds / BgWriterDelay) computes how many times
2403  * the BGW will be called during the scan_whole_pool time; slice the
2404  * buffer pool into that many sections.
2405  */
2406  min_scan_buffers = (int) (NBuffers / (scan_whole_pool_milliseconds / BgWriterDelay));
2407 
2408  if (upcoming_alloc_est < (min_scan_buffers + reusable_buffers_est))
2409  {
2410 #ifdef BGW_DEBUG
2411  elog(DEBUG2, "bgwriter: alloc_est=%d too small, using min=%d + reusable_est=%d",
2412  upcoming_alloc_est, min_scan_buffers, reusable_buffers_est);
2413 #endif
2414  upcoming_alloc_est = min_scan_buffers + reusable_buffers_est;
2415  }
2416 
2417  /*
2418  * Now write out dirty reusable buffers, working forward from the
2419  * next_to_clean point, until we have lapped the strategy scan, or cleaned
2420  * enough buffers to match our estimate of the next cycle's allocation
2421  * requirements, or hit the bgwriter_lru_maxpages limit.
2422  */
2423 
2424  /* Make sure we can handle the pin inside SyncOneBuffer */
2426 
2427  num_to_scan = bufs_to_lap;
2428  num_written = 0;
2429  reusable_buffers = reusable_buffers_est;
2430 
2431  /* Execute the LRU scan */
2432  while (num_to_scan > 0 && reusable_buffers < upcoming_alloc_est)
2433  {
2434  int sync_state = SyncOneBuffer(next_to_clean, true,
2435  wb_context);
2436 
2437  if (++next_to_clean >= NBuffers)
2438  {
2439  next_to_clean = 0;
2440  next_passes++;
2441  }
2442  num_to_scan--;
2443 
2444  if (sync_state & BUF_WRITTEN)
2445  {
2446  reusable_buffers++;
2447  if (++num_written >= bgwriter_lru_maxpages)
2448  {
2450  break;
2451  }
2452  }
2453  else if (sync_state & BUF_REUSABLE)
2454  reusable_buffers++;
2455  }
2456 
2458 
2459 #ifdef BGW_DEBUG
2460  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",
2461  recent_alloc, smoothed_alloc, strategy_delta, bufs_ahead,
2462  smoothed_density, reusable_buffers_est, upcoming_alloc_est,
2463  bufs_to_lap - num_to_scan,
2464  num_written,
2465  reusable_buffers - reusable_buffers_est);
2466 #endif
2467 
2468  /*
2469  * Consider the above scan as being like a new allocation scan.
2470  * Characterize its density and update the smoothed one based on it. This
2471  * effectively halves the moving average period in cases where both the
2472  * strategy and the background writer are doing some useful scanning,
2473  * which is helpful because a long memory isn't as desirable on the
2474  * density estimates.
2475  */
2476  new_strategy_delta = bufs_to_lap - num_to_scan;
2477  new_recent_alloc = reusable_buffers - reusable_buffers_est;
2478  if (new_strategy_delta > 0 && new_recent_alloc > 0)
2479  {
2480  scans_per_alloc = (float) new_strategy_delta / (float) new_recent_alloc;
2481  smoothed_density += (scans_per_alloc - smoothed_density) /
2482  smoothing_samples;
2483 
2484 #ifdef BGW_DEBUG
2485  elog(DEBUG2, "bgwriter: cleaner density alloc=%u scan=%ld density=%.2f new smoothed=%.2f",
2486  new_recent_alloc, new_strategy_delta,
2487  scans_per_alloc, smoothed_density);
2488 #endif
2489  }
2490 
2491  /* Return true if OK to hibernate */
2492  return (bufs_to_lap == 0 && recent_alloc == 0);
2493 }
2494 
2495 /*
2496  * SyncOneBuffer -- process a single buffer during syncing.
2497  *
2498  * If skip_recently_used is true, we don't write currently-pinned buffers, nor
2499  * buffers marked recently used, as these are not replacement candidates.
2500  *
2501  * Returns a bitmask containing the following flag bits:
2502  * BUF_WRITTEN: we wrote the buffer.
2503  * BUF_REUSABLE: buffer is available for replacement, ie, it has
2504  * pin count 0 and usage count 0.
2505  *
2506  * (BUF_WRITTEN could be set in error if FlushBuffer finds the buffer clean
2507  * after locking it, but we don't care all that much.)
2508  *
2509  * Note: caller must have done ResourceOwnerEnlargeBuffers.
2510  */
2511 static int
2512 SyncOneBuffer(int buf_id, bool skip_recently_used, WritebackContext *wb_context)
2513 {
2514  BufferDesc *bufHdr = GetBufferDescriptor(buf_id);
2515  int result = 0;
2516  uint32 buf_state;
2517  BufferTag tag;
2518 
2520 
2521  /*
2522  * Check whether buffer needs writing.
2523  *
2524  * We can make this check without taking the buffer content lock so long
2525  * as we mark pages dirty in access methods *before* logging changes with
2526  * XLogInsert(): if someone marks the buffer dirty just after our check we
2527  * don't worry because our checkpoint.redo points before log record for
2528  * upcoming changes and so we are not required to write such dirty buffer.
2529  */
2530  buf_state = LockBufHdr(bufHdr);
2531 
2532  if (BUF_STATE_GET_REFCOUNT(buf_state) == 0 &&
2533  BUF_STATE_GET_USAGECOUNT(buf_state) == 0)
2534  {
2535  result |= BUF_REUSABLE;
2536  }
2537  else if (skip_recently_used)
2538  {
2539  /* Caller told us not to write recently-used buffers */
2540  UnlockBufHdr(bufHdr, buf_state);
2541  return result;
2542  }
2543 
2544  if (!(buf_state & BM_VALID) || !(buf_state & BM_DIRTY))
2545  {
2546  /* It's clean, so nothing to do */
2547  UnlockBufHdr(bufHdr, buf_state);
2548  return result;
2549  }
2550 
2551  /*
2552  * Pin it, share-lock it, write it. (FlushBuffer will do nothing if the
2553  * buffer is clean by the time we've locked it.)
2554  */
2555  PinBuffer_Locked(bufHdr);
2557 
2558  FlushBuffer(bufHdr, NULL);
2559 
2561 
2562  tag = bufHdr->tag;
2563 
2564  UnpinBuffer(bufHdr, true);
2565 
2566  ScheduleBufferTagForWriteback(wb_context, &tag);
2567 
2568  return result | BUF_WRITTEN;
2569 }
2570 
2571 /*
2572  * AtEOXact_Buffers - clean up at end of transaction.
2573  *
2574  * As of PostgreSQL 8.0, buffer pins should get released by the
2575  * ResourceOwner mechanism. This routine is just a debugging
2576  * cross-check that no pins remain.
2577  */
2578 void
2579 AtEOXact_Buffers(bool isCommit)
2580 {
2582 
2583  AtEOXact_LocalBuffers(isCommit);
2584 
2586 }
2587 
2588 /*
2589  * Initialize access to shared buffer pool
2590  *
2591  * This is called during backend startup (whether standalone or under the
2592  * postmaster). It sets up for this backend's access to the already-existing
2593  * buffer pool.
2594  */
2595 void
2597 {
2598  HASHCTL hash_ctl;
2599 
2600  memset(&PrivateRefCountArray, 0, sizeof(PrivateRefCountArray));
2601 
2602  hash_ctl.keysize = sizeof(int32);
2603  hash_ctl.entrysize = sizeof(PrivateRefCountEntry);
2604 
2605  PrivateRefCountHash = hash_create("PrivateRefCount", 100, &hash_ctl,
2606  HASH_ELEM | HASH_BLOBS);
2607 
2608  /*
2609  * AtProcExit_Buffers needs LWLock access, and thereby has to be called at
2610  * the corresponding phase of backend shutdown.
2611  */
2612  Assert(MyProc != NULL);
2614 }
2615 
2616 /*
2617  * During backend exit, ensure that we released all shared-buffer locks and
2618  * assert that we have no remaining pins.
2619  */
2620 static void
2622 {
2623  AbortBufferIO();
2624  UnlockBuffers();
2625 
2627 
2628  /* localbuf.c needs a chance too */
2630 }
2631 
2632 /*
2633  * CheckForBufferLeaks - ensure this backend holds no buffer pins
2634  *
2635  * As of PostgreSQL 8.0, buffer pins should get released by the
2636  * ResourceOwner mechanism. This routine is just a debugging
2637  * cross-check that no pins remain.
2638  */
2639 static void
2641 {
2642 #ifdef USE_ASSERT_CHECKING
2643  int RefCountErrors = 0;
2644  PrivateRefCountEntry *res;
2645  int i;
2646 
2647  /* check the array */
2648  for (i = 0; i < REFCOUNT_ARRAY_ENTRIES; i++)
2649  {
2650  res = &PrivateRefCountArray[i];
2651 
2652  if (res->buffer != InvalidBuffer)
2653  {
2655  RefCountErrors++;
2656  }
2657  }
2658 
2659  /* if necessary search the hash */
2661  {
2662  HASH_SEQ_STATUS hstat;
2663 
2664  hash_seq_init(&hstat, PrivateRefCountHash);
2665  while ((res = (PrivateRefCountEntry *) hash_seq_search(&hstat)) != NULL)
2666  {
2668  RefCountErrors++;
2669  }
2670 
2671  }
2672 
2673  Assert(RefCountErrors == 0);
2674 #endif
2675 }
2676 
2677 /*
2678  * Helper routine to issue warnings when a buffer is unexpectedly pinned
2679  */
2680 void
2682 {
2683  BufferDesc *buf;
2684  int32 loccount;
2685  char *path;
2686  BackendId backend;
2687  uint32 buf_state;
2688 
2689  Assert(BufferIsValid(buffer));
2690  if (BufferIsLocal(buffer))
2691  {
2692  buf = GetLocalBufferDescriptor(-buffer - 1);
2693  loccount = LocalRefCount[-buffer - 1];
2694  backend = MyBackendId;
2695  }
2696  else
2697  {
2698  buf = GetBufferDescriptor(buffer - 1);
2699  loccount = GetPrivateRefCount(buffer);
2700  backend = InvalidBackendId;
2701  }
2702 
2703  /* theoretically we should lock the bufhdr here */
2704  path = relpathbackend(buf->tag.rnode, backend, buf->tag.forkNum);
2705  buf_state = pg_atomic_read_u32(&buf->state);
2706  elog(WARNING,
2707  "buffer refcount leak: [%03d] "
2708  "(rel=%s, blockNum=%u, flags=0x%x, refcount=%u %d)",
2709  buffer, path,
2710  buf->tag.blockNum, buf_state & BUF_FLAG_MASK,
2711  BUF_STATE_GET_REFCOUNT(buf_state), loccount);
2712  pfree(path);
2713 }
2714 
2715 /*
2716  * CheckPointBuffers
2717  *
2718  * Flush all dirty blocks in buffer pool to disk at checkpoint time.
2719  *
2720  * Note: temporary relations do not participate in checkpoints, so they don't
2721  * need to be flushed.
2722  */
2723 void
2725 {
2726  BufferSync(flags);
2727 }
2728 
2729 
2730 /*
2731  * Do whatever is needed to prepare for commit at the bufmgr and smgr levels
2732  */
2733 void
2735 {
2736  /* Nothing to do in bufmgr anymore... */
2737 }
2738 
2739 /*
2740  * BufferGetBlockNumber
2741  * Returns the block number associated with a buffer.
2742  *
2743  * Note:
2744  * Assumes that the buffer is valid and pinned, else the
2745  * value may be obsolete immediately...
2746  */
2749 {
2750  BufferDesc *bufHdr;
2751 
2752  Assert(BufferIsPinned(buffer));
2753 
2754  if (BufferIsLocal(buffer))
2755  bufHdr = GetLocalBufferDescriptor(-buffer - 1);
2756  else
2757  bufHdr = GetBufferDescriptor(buffer - 1);
2758 
2759  /* pinned, so OK to read tag without spinlock */
2760  return bufHdr->tag.blockNum;
2761 }
2762 
2763 /*
2764  * BufferGetTag
2765  * Returns the relfilenode, fork number and block number associated with
2766  * a buffer.
2767  */
2768 void
2770  BlockNumber *blknum)
2771 {
2772  BufferDesc *bufHdr;
2773 
2774  /* Do the same checks as BufferGetBlockNumber. */
2775  Assert(BufferIsPinned(buffer));
2776 
2777  if (BufferIsLocal(buffer))
2778  bufHdr = GetLocalBufferDescriptor(-buffer - 1);
2779  else
2780  bufHdr = GetBufferDescriptor(buffer - 1);
2781 
2782  /* pinned, so OK to read tag without spinlock */
2783  *rnode = bufHdr->tag.rnode;
2784  *forknum = bufHdr->tag.forkNum;
2785  *blknum = bufHdr->tag.blockNum;
2786 }
2787 
2788 /*
2789  * FlushBuffer
2790  * Physically write out a shared buffer.
2791  *
2792  * NOTE: this actually just passes the buffer contents to the kernel; the
2793  * real write to disk won't happen until the kernel feels like it. This
2794  * is okay from our point of view since we can redo the changes from WAL.
2795  * However, we will need to force the changes to disk via fsync before
2796  * we can checkpoint WAL.
2797  *
2798  * The caller must hold a pin on the buffer and have share-locked the
2799  * buffer contents. (Note: a share-lock does not prevent updates of
2800  * hint bits in the buffer, so the page could change while the write
2801  * is in progress, but we assume that that will not invalidate the data
2802  * written.)
2803  *
2804  * If the caller has an smgr reference for the buffer's relation, pass it
2805  * as the second parameter. If not, pass NULL.
2806  */
2807 static void
2809 {
2810  XLogRecPtr recptr;
2811  ErrorContextCallback errcallback;
2812  instr_time io_start,
2813  io_time;
2814  Block bufBlock;
2815  char *bufToWrite;
2816  uint32 buf_state;
2817 
2818  /*
2819  * Try to start an I/O operation. If StartBufferIO returns false, then
2820  * someone else flushed the buffer before we could, so we need not do
2821  * anything.
2822  */
2823  if (!StartBufferIO(buf, false))
2824  return;
2825 
2826  /* Setup error traceback support for ereport() */
2828  errcallback.arg = (void *) buf;
2829  errcallback.previous = error_context_stack;
2830  error_context_stack = &errcallback;
2831 
2832  /* Find smgr relation for buffer */
2833  if (reln == NULL)
2834  reln = smgropen(buf->tag.rnode, InvalidBackendId);
2835 
2836  TRACE_POSTGRESQL_BUFFER_FLUSH_START(buf->tag.forkNum,
2837  buf->tag.blockNum,
2838  reln->smgr_rnode.node.spcNode,
2839  reln->smgr_rnode.node.dbNode,
2840  reln->smgr_rnode.node.relNode);
2841 
2842  buf_state = LockBufHdr(buf);
2843 
2844  /*
2845  * Run PageGetLSN while holding header lock, since we don't have the
2846  * buffer locked exclusively in all cases.
2847  */
2848  recptr = BufferGetLSN(buf);
2849 
2850  /* To check if block content changes while flushing. - vadim 01/17/97 */
2851  buf_state &= ~BM_JUST_DIRTIED;
2852  UnlockBufHdr(buf, buf_state);
2853 
2854  /*
2855  * Force XLOG flush up to buffer's LSN. This implements the basic WAL
2856  * rule that log updates must hit disk before any of the data-file changes
2857  * they describe do.
2858  *
2859  * However, this rule does not apply to unlogged relations, which will be
2860  * lost after a crash anyway. Most unlogged relation pages do not bear
2861  * LSNs since we never emit WAL records for them, and therefore flushing
2862  * up through the buffer LSN would be useless, but harmless. However,
2863  * GiST indexes use LSNs internally to track page-splits, and therefore
2864  * unlogged GiST pages bear "fake" LSNs generated by
2865  * GetFakeLSNForUnloggedRel. It is unlikely but possible that the fake
2866  * LSN counter could advance past the WAL insertion point; and if it did
2867  * happen, attempting to flush WAL through that location would fail, with
2868  * disastrous system-wide consequences. To make sure that can't happen,
2869  * skip the flush if the buffer isn't permanent.
2870  */
2871  if (buf_state & BM_PERMANENT)
2872  XLogFlush(recptr);
2873 
2874  /*
2875  * Now it's safe to write buffer to disk. Note that no one else should
2876  * have been able to write it while we were busy with log flushing because
2877  * only one process at a time can set the BM_IO_IN_PROGRESS bit.
2878  */
2879  bufBlock = BufHdrGetBlock(buf);
2880 
2881  /*
2882  * Update page checksum if desired. Since we have only shared lock on the
2883  * buffer, other processes might be updating hint bits in it, so we must
2884  * copy the page to private storage if we do checksumming.
2885  */
2886  bufToWrite = PageSetChecksumCopy((Page) bufBlock, buf->tag.blockNum);
2887 
2888  if (track_io_timing)
2889  INSTR_TIME_SET_CURRENT(io_start);
2890 
2891  /*
2892  * bufToWrite is either the shared buffer or a copy, as appropriate.
2893  */
2894  smgrwrite(reln,
2895  buf->tag.forkNum,
2896  buf->tag.blockNum,
2897  bufToWrite,
2898  false);
2899 
2900  if (track_io_timing)
2901  {
2902  INSTR_TIME_SET_CURRENT(io_time);
2903  INSTR_TIME_SUBTRACT(io_time, io_start);
2906  }
2907 
2909 
2910  /*
2911  * Mark the buffer as clean (unless BM_JUST_DIRTIED has become set) and
2912  * end the BM_IO_IN_PROGRESS state.
2913  */
2914  TerminateBufferIO(buf, true, 0);
2915 
2916  TRACE_POSTGRESQL_BUFFER_FLUSH_DONE(buf->tag.forkNum,
2917  buf->tag.blockNum,
2918  reln->smgr_rnode.node.spcNode,
2919  reln->smgr_rnode.node.dbNode,
2920  reln->smgr_rnode.node.relNode);
2921 
2922  /* Pop the error context stack */
2923  error_context_stack = errcallback.previous;
2924 }
2925 
2926 /*
2927  * RelationGetNumberOfBlocksInFork
2928  * Determines the current number of pages in the specified relation fork.
2929  *
2930  * Note that the accuracy of the result will depend on the details of the
2931  * relation's storage. For builtin AMs it'll be accurate, but for external AMs
2932  * it might not be.
2933  */
2936 {
2937  switch (relation->rd_rel->relkind)
2938  {
2939  case RELKIND_SEQUENCE:
2940  case RELKIND_INDEX:
2941  return smgrnblocks(RelationGetSmgr(relation), forkNum);
2942 
2943  case RELKIND_RELATION:
2944  case RELKIND_TOASTVALUE:
2945  case RELKIND_MATVIEW:
2946  {
2947  /*
2948  * Not every table AM uses BLCKSZ wide fixed size blocks.
2949  * Therefore tableam returns the size in bytes - but for the
2950  * purpose of this routine, we want the number of blocks.
2951  * Therefore divide, rounding up.
2952  */
2953  uint64 szbytes;
2954 
2955  szbytes = table_relation_size(relation, forkNum);
2956 
2957  return (szbytes + (BLCKSZ - 1)) / BLCKSZ;
2958  }
2959  case RELKIND_VIEW:
2960  case RELKIND_COMPOSITE_TYPE:
2961  case RELKIND_FOREIGN_TABLE:
2962  case RELKIND_PARTITIONED_INDEX:
2963  case RELKIND_PARTITIONED_TABLE:
2964  default:
2965  Assert(false);
2966  break;
2967  }
2968 
2969  return 0; /* keep compiler quiet */
2970 }
2971 
2972 /*
2973  * BufferIsPermanent
2974  * Determines whether a buffer will potentially still be around after
2975  * a crash. Caller must hold a buffer pin.
2976  */
2977 bool
2979 {
2980  BufferDesc *bufHdr;
2981 
2982  /* Local buffers are used only for temp relations. */
2983  if (BufferIsLocal(buffer))
2984  return false;
2985 
2986  /* Make sure we've got a real buffer, and that we hold a pin on it. */
2987  Assert(BufferIsValid(buffer));
2988  Assert(BufferIsPinned(buffer));
2989 
2990  /*
2991  * BM_PERMANENT can't be changed while we hold a pin on the buffer, so we
2992  * need not bother with the buffer header spinlock. Even if someone else
2993  * changes the buffer header state while we're doing this, the state is
2994  * changed atomically, so we'll read the old value or the new value, but
2995  * not random garbage.
2996  */
2997  bufHdr = GetBufferDescriptor(buffer - 1);
2998  return (pg_atomic_read_u32(&bufHdr->state) & BM_PERMANENT) != 0;
2999 }
3000 
3001 /*
3002  * BufferGetLSNAtomic
3003  * Retrieves the LSN of the buffer atomically using a buffer header lock.
3004  * This is necessary for some callers who may not have an exclusive lock
3005  * on the buffer.
3006  */
3007 XLogRecPtr
3009 {
3010  BufferDesc *bufHdr = GetBufferDescriptor(buffer - 1);
3011  char *page = BufferGetPage(buffer);
3012  XLogRecPtr lsn;
3013  uint32 buf_state;
3014 
3015  /*
3016  * If we don't need locking for correctness, fastpath out.
3017  */
3018  if (!XLogHintBitIsNeeded() || BufferIsLocal(buffer))
3019  return PageGetLSN(page);
3020 
3021  /* Make sure we've got a real buffer, and that we hold a pin on it. */
3022  Assert(BufferIsValid(buffer));
3023  Assert(BufferIsPinned(buffer));
3024 
3025  buf_state = LockBufHdr(bufHdr);
3026  lsn = PageGetLSN(page);
3027  UnlockBufHdr(bufHdr, buf_state);
3028 
3029  return lsn;
3030 }
3031 
3032 /* ---------------------------------------------------------------------
3033  * DropRelFileNodeBuffers
3034  *
3035  * This function removes from the buffer pool all the pages of the
3036  * specified relation forks that have block numbers >= firstDelBlock.
3037  * (In particular, with firstDelBlock = 0, all pages are removed.)
3038  * Dirty pages are simply dropped, without bothering to write them
3039  * out first. Therefore, this is NOT rollback-able, and so should be
3040  * used only with extreme caution!
3041  *
3042  * Currently, this is called only from smgr.c when the underlying file
3043  * is about to be deleted or truncated (firstDelBlock is needed for
3044  * the truncation case). The data in the affected pages would therefore
3045  * be deleted momentarily anyway, and there is no point in writing it.
3046  * It is the responsibility of higher-level code to ensure that the
3047  * deletion or truncation does not lose any data that could be needed
3048  * later. It is also the responsibility of higher-level code to ensure
3049  * that no other process could be trying to load more pages of the
3050  * relation into buffers.
3051  * --------------------------------------------------------------------
3052  */
3053 void
3055  int nforks, BlockNumber *firstDelBlock)
3056 {
3057  int i;
3058  int j;
3059  RelFileNodeBackend rnode;
3060  BlockNumber nForkBlock[MAX_FORKNUM];
3061  uint64 nBlocksToInvalidate = 0;
3062 
3063  rnode = smgr_reln->smgr_rnode;
3064 
3065  /* If it's a local relation, it's localbuf.c's problem. */
3066  if (RelFileNodeBackendIsTemp(rnode))
3067  {
3068  if (rnode.backend == MyBackendId)
3069  {
3070  for (j = 0; j < nforks; j++)
3071  DropRelFileNodeLocalBuffers(rnode.node, forkNum[j],
3072  firstDelBlock[j]);
3073  }
3074  return;
3075  }
3076 
3077  /*
3078  * To remove all the pages of the specified relation forks from the buffer
3079  * pool, we need to scan the entire buffer pool but we can optimize it by
3080  * finding the buffers from BufMapping table provided we know the exact
3081  * size of each fork of the relation. The exact size is required to ensure
3082  * that we don't leave any buffer for the relation being dropped as
3083  * otherwise the background writer or checkpointer can lead to a PANIC
3084  * error while flushing buffers corresponding to files that don't exist.
3085  *
3086  * To know the exact size, we rely on the size cached for each fork by us
3087  * during recovery which limits the optimization to recovery and on
3088  * standbys but we can easily extend it once we have shared cache for
3089  * relation size.
3090  *
3091  * In recovery, we cache the value returned by the first lseek(SEEK_END)
3092  * and the future writes keeps the cached value up-to-date. See
3093  * smgrextend. It is possible that the value of the first lseek is smaller
3094  * than the actual number of existing blocks in the file due to buggy
3095  * Linux kernels that might not have accounted for the recent write. But
3096  * that should be fine because there must not be any buffers after that
3097  * file size.
3098  */
3099  for (i = 0; i < nforks; i++)
3100  {
3101  /* Get the number of blocks for a relation's fork */
3102  nForkBlock[i] = smgrnblocks_cached(smgr_reln, forkNum[i]);
3103 
3104  if (nForkBlock[i] == InvalidBlockNumber)
3105  {
3106  nBlocksToInvalidate = InvalidBlockNumber;
3107  break;
3108  }
3109 
3110  /* calculate the number of blocks to be invalidated */
3111  nBlocksToInvalidate += (nForkBlock[i] - firstDelBlock[i]);
3112  }
3113 
3114  /*
3115  * We apply the optimization iff the total number of blocks to invalidate
3116  * is below the BUF_DROP_FULL_SCAN_THRESHOLD.
3117  */
3118  if (BlockNumberIsValid(nBlocksToInvalidate) &&
3119  nBlocksToInvalidate < BUF_DROP_FULL_SCAN_THRESHOLD)
3120  {
3121  for (j = 0; j < nforks; j++)
3122  FindAndDropRelFileNodeBuffers(rnode.node, forkNum[j],
3123  nForkBlock[j], firstDelBlock[j]);
3124  return;
3125  }
3126 
3127  for (i = 0; i < NBuffers; i++)
3128  {
3129  BufferDesc *bufHdr = GetBufferDescriptor(i);
3130  uint32 buf_state;
3131 
3132  /*
3133  * We can make this a tad faster by prechecking the buffer tag before
3134  * we attempt to lock the buffer; this saves a lot of lock
3135  * acquisitions in typical cases. It should be safe because the
3136  * caller must have AccessExclusiveLock on the relation, or some other
3137  * reason to be certain that no one is loading new pages of the rel
3138  * into the buffer pool. (Otherwise we might well miss such pages
3139  * entirely.) Therefore, while the tag might be changing while we
3140  * look at it, it can't be changing *to* a value we care about, only
3141  * *away* from such a value. So false negatives are impossible, and
3142  * false positives are safe because we'll recheck after getting the
3143  * buffer lock.
3144  *
3145  * We could check forkNum and blockNum as well as the rnode, but the
3146  * incremental win from doing so seems small.
3147  */
3148  if (!RelFileNodeEquals(bufHdr->tag.rnode, rnode.node))
3149  continue;
3150 
3151  buf_state = LockBufHdr(bufHdr);
3152 
3153  for (j = 0; j < nforks; j++)
3154  {
3155  if (RelFileNodeEquals(bufHdr->tag.rnode, rnode.node) &&
3156  bufHdr->tag.forkNum == forkNum[j] &&
3157  bufHdr->tag.blockNum >= firstDelBlock[j])
3158  {
3159  InvalidateBuffer(bufHdr); /* releases spinlock */
3160  break;
3161  }
3162  }
3163  if (j >= nforks)
3164  UnlockBufHdr(bufHdr, buf_state);
3165  }
3166 }
3167 
3168 /* ---------------------------------------------------------------------
3169  * DropRelFileNodesAllBuffers
3170  *
3171  * This function removes from the buffer pool all the pages of all
3172  * forks of the specified relations. It's equivalent to calling
3173  * DropRelFileNodeBuffers once per fork per relation with
3174  * firstDelBlock = 0.
3175  * --------------------------------------------------------------------
3176  */
3177 void
3179 {
3180  int i;
3181  int j;
3182  int n = 0;
3183  SMgrRelation *rels;
3184  BlockNumber (*block)[MAX_FORKNUM + 1];
3185  uint64 nBlocksToInvalidate = 0;
3186  RelFileNode *nodes;
3187  bool cached = true;
3188  bool use_bsearch;
3189 
3190  if (nnodes == 0)
3191  return;
3192 
3193  rels = palloc(sizeof(SMgrRelation) * nnodes); /* non-local relations */
3194 
3195  /* If it's a local relation, it's localbuf.c's problem. */
3196  for (i = 0; i < nnodes; i++)
3197  {
3198  if (RelFileNodeBackendIsTemp(smgr_reln[i]->smgr_rnode))
3199  {
3200  if (smgr_reln[i]->smgr_rnode.backend == MyBackendId)
3201  DropRelFileNodeAllLocalBuffers(smgr_reln[i]->smgr_rnode.node);
3202  }
3203  else
3204  rels[n++] = smgr_reln[i];
3205  }
3206 
3207  /*
3208  * If there are no non-local relations, then we're done. Release the
3209  * memory and return.
3210  */
3211  if (n == 0)
3212  {
3213  pfree(rels);
3214  return;
3215  }
3216 
3217  /*
3218  * This is used to remember the number of blocks for all the relations
3219  * forks.
3220  */
3221  block = (BlockNumber (*)[MAX_FORKNUM + 1])
3222  palloc(sizeof(BlockNumber) * n * (MAX_FORKNUM + 1));
3223 
3224  /*
3225  * We can avoid scanning the entire buffer pool if we know the exact size
3226  * of each of the given relation forks. See DropRelFileNodeBuffers.
3227  */
3228  for (i = 0; i < n && cached; i++)
3229  {
3230  for (j = 0; j <= MAX_FORKNUM; j++)
3231  {
3232  /* Get the number of blocks for a relation's fork. */
3233  block[i][j] = smgrnblocks_cached(rels[i], j);
3234 
3235  /* We need to only consider the relation forks that exists. */
3236  if (block[i][j] == InvalidBlockNumber)
3237  {
3238  if (!smgrexists(rels[i], j))
3239  continue;
3240  cached = false;
3241  break;
3242  }
3243 
3244  /* calculate the total number of blocks to be invalidated */
3245  nBlocksToInvalidate += block[i][j];
3246  }
3247  }
3248 
3249  /*
3250  * We apply the optimization iff the total number of blocks to invalidate
3251  * is below the BUF_DROP_FULL_SCAN_THRESHOLD.
3252  */
3253  if (cached && nBlocksToInvalidate < BUF_DROP_FULL_SCAN_THRESHOLD)
3254  {
3255  for (i = 0; i < n; i++)
3256  {
3257  for (j = 0; j <= MAX_FORKNUM; j++)
3258  {
3259  /* ignore relation forks that doesn't exist */
3260  if (!BlockNumberIsValid(block[i][j]))
3261  continue;
3262 
3263  /* drop all the buffers for a particular relation fork */
3264  FindAndDropRelFileNodeBuffers(rels[i]->smgr_rnode.node,
3265  j, block[i][j], 0);
3266  }
3267  }
3268 
3269  pfree(block);
3270  pfree(rels);
3271  return;
3272  }
3273 
3274  pfree(block);
3275  nodes = palloc(sizeof(RelFileNode) * n); /* non-local relations */
3276  for (i = 0; i < n; i++)
3277  nodes[i] = rels[i]->smgr_rnode.node;
3278 
3279  /*
3280  * For low number of relations to drop just use a simple walk through, to
3281  * save the bsearch overhead. The threshold to use is rather a guess than
3282  * an exactly determined value, as it depends on many factors (CPU and RAM
3283  * speeds, amount of shared buffers etc.).
3284  */
3285  use_bsearch = n > RELS_BSEARCH_THRESHOLD;
3286 
3287  /* sort the list of rnodes if necessary */
3288  if (use_bsearch)
3289  pg_qsort(nodes, n, sizeof(RelFileNode), rnode_comparator);
3290 
3291  for (i = 0; i < NBuffers; i++)
3292  {
3293  RelFileNode *rnode = NULL;
3294  BufferDesc *bufHdr = GetBufferDescriptor(i);
3295  uint32 buf_state;
3296 
3297  /*
3298  * As in DropRelFileNodeBuffers, an unlocked precheck should be safe
3299  * and saves some cycles.
3300  */
3301 
3302  if (!use_bsearch)
3303  {
3304  int j;
3305 
3306  for (j = 0; j < n; j++)
3307  {
3308  if (RelFileNodeEquals(bufHdr->tag.rnode, nodes[j]))
3309  {
3310  rnode = &nodes[j];
3311  break;
3312  }
3313  }
3314  }
3315  else
3316  {
3317  rnode = bsearch((const void *) &(bufHdr->tag.rnode),
3318  nodes, n, sizeof(RelFileNode),
3320  }
3321 
3322  /* buffer doesn't belong to any of the given relfilenodes; skip it */
3323  if (rnode == NULL)
3324  continue;
3325 
3326  buf_state = LockBufHdr(bufHdr);
3327  if (RelFileNodeEquals(bufHdr->tag.rnode, (*rnode)))
3328  InvalidateBuffer(bufHdr); /* releases spinlock */
3329  else
3330  UnlockBufHdr(bufHdr, buf_state);
3331  }
3332 
3333  pfree(nodes);
3334  pfree(rels);
3335 }
3336 
3337 /* ---------------------------------------------------------------------
3338  * FindAndDropRelFileNodeBuffers
3339  *
3340  * This function performs look up in BufMapping table and removes from the
3341  * buffer pool all the pages of the specified relation fork that has block
3342  * number >= firstDelBlock. (In particular, with firstDelBlock = 0, all
3343  * pages are removed.)
3344  * --------------------------------------------------------------------
3345  */
3346 static void
3348  BlockNumber nForkBlock,
3349  BlockNumber firstDelBlock)
3350 {
3351  BlockNumber curBlock;
3352 
3353  for (curBlock = firstDelBlock; curBlock < nForkBlock; curBlock++)
3354  {
3355  uint32 bufHash; /* hash value for tag */
3356  BufferTag bufTag; /* identity of requested block */
3357  LWLock *bufPartitionLock; /* buffer partition lock for it */
3358  int buf_id;
3359  BufferDesc *bufHdr;
3360  uint32 buf_state;
3361 
3362  /* create a tag so we can lookup the buffer */
3363  INIT_BUFFERTAG(bufTag, rnode, forkNum, curBlock);
3364 
3365  /* determine its hash code and partition lock ID */
3366  bufHash = BufTableHashCode(&bufTag);
3367  bufPartitionLock = BufMappingPartitionLock(bufHash);
3368 
3369  /* Check that it is in the buffer pool. If not, do nothing. */
3370  LWLockAcquire(bufPartitionLock, LW_SHARED);
3371  buf_id = BufTableLookup(&bufTag, bufHash);
3372  LWLockRelease(bufPartitionLock);
3373 
3374  if (buf_id < 0)
3375  continue;
3376 
3377  bufHdr = GetBufferDescriptor(buf_id);
3378 
3379  /*
3380  * We need to lock the buffer header and recheck if the buffer is
3381  * still associated with the same block because the buffer could be
3382  * evicted by some other backend loading blocks for a different
3383  * relation after we release lock on the BufMapping table.
3384  */
3385  buf_state = LockBufHdr(bufHdr);
3386 
3387  if (RelFileNodeEquals(bufHdr->tag.rnode, rnode) &&
3388  bufHdr->tag.forkNum == forkNum &&
3389  bufHdr->tag.blockNum >= firstDelBlock)
3390  InvalidateBuffer(bufHdr); /* releases spinlock */
3391  else
3392  UnlockBufHdr(bufHdr, buf_state);
3393  }
3394 }
3395 
3396 /* ---------------------------------------------------------------------
3397  * DropDatabaseBuffers
3398  *
3399  * This function removes all the buffers in the buffer cache for a
3400  * particular database. Dirty pages are simply dropped, without
3401  * bothering to write them out first. This is used when we destroy a
3402  * database, to avoid trying to flush data to disk when the directory
3403  * tree no longer exists. Implementation is pretty similar to
3404  * DropRelFileNodeBuffers() which is for destroying just one relation.
3405  * --------------------------------------------------------------------
3406  */
3407 void
3409 {
3410  int i;
3411 
3412  /*
3413  * We needn't consider local buffers, since by assumption the target
3414  * database isn't our own.
3415  */
3416 
3417  for (i = 0; i < NBuffers; i++)
3418  {
3419  BufferDesc *bufHdr = GetBufferDescriptor(i);
3420  uint32 buf_state;
3421 
3422  /*
3423  * As in DropRelFileNodeBuffers, an unlocked precheck should be safe
3424  * and saves some cycles.
3425  */
3426  if (bufHdr->tag.rnode.dbNode != dbid)
3427  continue;
3428 
3429  buf_state = LockBufHdr(bufHdr);
3430  if (bufHdr->tag.rnode.dbNode == dbid)
3431  InvalidateBuffer(bufHdr); /* releases spinlock */
3432  else
3433  UnlockBufHdr(bufHdr, buf_state);
3434  }
3435 }
3436 
3437 /* -----------------------------------------------------------------
3438  * PrintBufferDescs
3439  *
3440  * this function prints all the buffer descriptors, for debugging
3441  * use only.
3442  * -----------------------------------------------------------------
3443  */
3444 #ifdef NOT_USED
3445 void
3446 PrintBufferDescs(void)
3447 {
3448  int i;
3449 
3450  for (i = 0; i < NBuffers; ++i)
3451  {
3454 
3455  /* theoretically we should lock the bufhdr here */
3456  elog(LOG,
3457  "[%02d] (freeNext=%d, rel=%s, "
3458  "blockNum=%u, flags=0x%x, refcount=%u %d)",
3459  i, buf->freeNext,
3461  buf->tag.blockNum, buf->flags,
3462  buf->refcount, GetPrivateRefCount(b));
3463  }
3464 }
3465 #endif
3466 
3467 #ifdef NOT_USED
3468 void
3469 PrintPinnedBufs(void)
3470 {
3471  int i;
3472 
3473  for (i = 0; i < NBuffers; ++i)
3474  {
3477 
3478  if (GetPrivateRefCount(b) > 0)
3479  {
3480  /* theoretically we should lock the bufhdr here */
3481  elog(LOG,
3482  "[%02d] (freeNext=%d, rel=%s, "
3483  "blockNum=%u, flags=0x%x, refcount=%u %d)",
3484  i, buf->freeNext,
3485  relpathperm(buf->tag.rnode, buf->tag.forkNum),
3486  buf->tag.blockNum, buf->flags,
3487  buf->refcount, GetPrivateRefCount(b));
3488  }
3489  }
3490 }
3491 #endif
3492 
3493 /* ---------------------------------------------------------------------
3494  * FlushRelationBuffers
3495  *
3496  * This function writes all dirty pages of a relation out to disk
3497  * (or more accurately, out to kernel disk buffers), ensuring that the
3498  * kernel has an up-to-date view of the relation.
3499  *
3500  * Generally, the caller should be holding AccessExclusiveLock on the
3501  * target relation to ensure that no other backend is busy dirtying
3502  * more blocks of the relation; the effects can't be expected to last
3503  * after the lock is released.
3504  *
3505  * XXX currently it sequentially searches the buffer pool, should be
3506  * changed to more clever ways of searching. This routine is not
3507  * used in any performance-critical code paths, so it's not worth
3508  * adding additional overhead to normal paths to make it go faster.
3509  * --------------------------------------------------------------------
3510  */
3511 void
3513 {
3514  int i;
3515  BufferDesc *bufHdr;
3516 
3517  if (RelationUsesLocalBuffers(rel))
3518  {
3519  for (i = 0; i < NLocBuffer; i++)
3520  {
3521  uint32 buf_state;
3522 
3523  bufHdr = GetLocalBufferDescriptor(i);
3524  if (RelFileNodeEquals(bufHdr->tag.rnode, rel->rd_node) &&
3525  ((buf_state = pg_atomic_read_u32(&bufHdr->state)) &
3526  (BM_VALID | BM_DIRTY)) == (BM_VALID | BM_DIRTY))
3527  {
3528  ErrorContextCallback errcallback;
3529  Page localpage;
3530 
3531  localpage = (char *) LocalBufHdrGetBlock(bufHdr);
3532 
3533  /* Setup error traceback support for ereport() */
3535  errcallback.arg = (void *) bufHdr;
3536  errcallback.previous = error_context_stack;
3537  error_context_stack = &errcallback;
3538 
3539  PageSetChecksumInplace(localpage, bufHdr->tag.blockNum);
3540 
3542  bufHdr->tag.forkNum,
3543  bufHdr->tag.blockNum,
3544  localpage,
3545  false);
3546 
3547  buf_state &= ~(BM_DIRTY | BM_JUST_DIRTIED);
3548  pg_atomic_unlocked_write_u32(&bufHdr->state, buf_state);
3549 
3550  /* Pop the error context stack */
3551  error_context_stack = errcallback.previous;
3552  }
3553  }
3554 
3555  return;
3556  }
3557 
3558  /* Make sure we can handle the pin inside the loop */
3560 
3561  for (i = 0; i < NBuffers; i++)
3562  {
3563  uint32 buf_state;
3564 
3565  bufHdr = GetBufferDescriptor(i);
3566 
3567  /*
3568  * As in DropRelFileNodeBuffers, an unlocked precheck should be safe
3569  * and saves some cycles.
3570  */
3571  if (!RelFileNodeEquals(bufHdr->tag.rnode, rel->rd_node))
3572  continue;
3573 
3575 
3576  buf_state = LockBufHdr(bufHdr);
3577  if (RelFileNodeEquals(bufHdr->tag.rnode, rel->rd_node) &&
3578  (buf_state & (BM_VALID | BM_DIRTY)) == (BM_VALID | BM_DIRTY))
3579  {
3580  PinBuffer_Locked(bufHdr);
3582  FlushBuffer(bufHdr, RelationGetSmgr(rel));
3584  UnpinBuffer(bufHdr, true);
3585  }
3586  else
3587  UnlockBufHdr(bufHdr, buf_state);
3588  }
3589 }
3590 
3591 /* ---------------------------------------------------------------------
3592  * FlushRelationsAllBuffers
3593  *
3594  * This function flushes out of the buffer pool all the pages of all
3595  * forks of the specified smgr relations. It's equivalent to calling
3596  * FlushRelationBuffers once per fork per relation. The relations are
3597  * assumed not to use local buffers.
3598  * --------------------------------------------------------------------
3599  */
3600 void
3602 {
3603  int i;
3604  SMgrSortArray *srels;
3605  bool use_bsearch;
3606 
3607  if (nrels == 0)
3608  return;
3609 
3610  /* fill-in array for qsort */
3611  srels = palloc(sizeof(SMgrSortArray) * nrels);
3612 
3613  for (i = 0; i < nrels; i++)
3614  {
3615  Assert(!RelFileNodeBackendIsTemp(smgrs[i]->smgr_rnode));
3616 
3617  srels[i].rnode = smgrs[i]->smgr_rnode.node;
3618  srels[i].srel = smgrs[i];
3619  }
3620 
3621  /*
3622  * Save the bsearch overhead for low number of relations to sync. See
3623  * DropRelFileNodesAllBuffers for details.
3624  */
3625  use_bsearch = nrels > RELS_BSEARCH_THRESHOLD;
3626 
3627  /* sort the list of SMgrRelations if necessary */
3628  if (use_bsearch)
3629  pg_qsort(srels, nrels, sizeof(SMgrSortArray), rnode_comparator);
3630 
3631  /* Make sure we can handle the pin inside the loop */
3633 
3634  for (i = 0; i < NBuffers; i++)
3635  {
3636  SMgrSortArray *srelent = NULL;
3637  BufferDesc *bufHdr = GetBufferDescriptor(i);
3638  uint32 buf_state;
3639 
3640  /*
3641  * As in DropRelFileNodeBuffers, an unlocked precheck should be safe
3642  * and saves some cycles.
3643  */
3644 
3645  if (!use_bsearch)
3646  {
3647  int j;
3648 
3649  for (j = 0; j < nrels; j++)
3650  {
3651  if (RelFileNodeEquals(bufHdr->tag.rnode, srels[j].rnode))
3652  {
3653  srelent = &srels[j];
3654  break;
3655  }
3656  }
3657 
3658  }
3659  else
3660  {
3661  srelent = bsearch((const void *) &(bufHdr->tag.rnode),
3662  srels, nrels, sizeof(SMgrSortArray),
3664  }
3665 
3666  /* buffer doesn't belong to any of the given relfilenodes; skip it */
3667  if (srelent == NULL)
3668  continue;
3669 
3671 
3672  buf_state = LockBufHdr(bufHdr);
3673  if (RelFileNodeEquals(bufHdr->tag.rnode, srelent->rnode) &&
3674  (buf_state & (BM_VALID | BM_DIRTY)) == (BM_VALID | BM_DIRTY))
3675  {
3676  PinBuffer_Locked(bufHdr);
3678  FlushBuffer(bufHdr, srelent->srel);
3680  UnpinBuffer(bufHdr, true);
3681  }
3682  else
3683  UnlockBufHdr(bufHdr, buf_state);
3684  }
3685 
3686  pfree(srels);
3687 }
3688 
3689 /* ---------------------------------------------------------------------
3690  * FlushDatabaseBuffers
3691  *
3692  * This function writes all dirty pages of a database out to disk
3693  * (or more accurately, out to kernel disk buffers), ensuring that the
3694  * kernel has an up-to-date view of the database.
3695  *
3696  * Generally, the caller should be holding an appropriate lock to ensure
3697  * no other backend is active in the target database; otherwise more
3698  * pages could get dirtied.
3699  *
3700  * Note we don't worry about flushing any pages of temporary relations.
3701  * It's assumed these wouldn't be interesting.
3702  * --------------------------------------------------------------------
3703  */
3704 void
3706 {
3707  int i;
3708  BufferDesc *bufHdr;
3709 
3710  /* Make sure we can handle the pin inside the loop */
3712 
3713  for (i = 0; i < NBuffers; i++)
3714  {
3715  uint32 buf_state;
3716 
3717  bufHdr = GetBufferDescriptor(i);
3718 
3719  /*
3720  * As in DropRelFileNodeBuffers, an unlocked precheck should be safe
3721  * and saves some cycles.
3722  */
3723  if (bufHdr->tag.rnode.dbNode != dbid)
3724  continue;
3725 
3727 
3728  buf_state = LockBufHdr(bufHdr);
3729  if (bufHdr->tag.rnode.dbNode == dbid &&
3730  (buf_state & (BM_VALID | BM_DIRTY)) == (BM_VALID | BM_DIRTY))
3731  {
3732  PinBuffer_Locked(bufHdr);
3734  FlushBuffer(bufHdr, NULL);
3736  UnpinBuffer(bufHdr, true);
3737  }
3738  else
3739  UnlockBufHdr(bufHdr, buf_state);
3740  }
3741 }
3742 
3743 /*
3744  * Flush a previously, shared or exclusively, locked and pinned buffer to the
3745  * OS.
3746  */
3747 void
3749 {
3750  BufferDesc *bufHdr;
3751 
3752  /* currently not needed, but no fundamental reason not to support */
3753  Assert(!BufferIsLocal(buffer));
3754 
3755  Assert(BufferIsPinned(buffer));
3756 
3757  bufHdr = GetBufferDescriptor(buffer - 1);
3758 
3760 
3761  FlushBuffer(bufHdr, NULL);
3762 }
3763 
3764 /*
3765  * ReleaseBuffer -- release the pin on a buffer
3766  */
3767 void
3769 {
3770  if (!BufferIsValid(buffer))
3771  elog(ERROR, "bad buffer ID: %d", buffer);
3772 
3773  if (BufferIsLocal(buffer))
3774  {
3776 
3777  Assert(LocalRefCount[-buffer - 1] > 0);
3778  LocalRefCount[-buffer - 1]--;
3779  return;
3780  }
3781 
3782  UnpinBuffer(GetBufferDescriptor(buffer - 1), true);
3783 }
3784 
3785 /*
3786  * UnlockReleaseBuffer -- release the content lock and pin on a buffer
3787  *
3788  * This is just a shorthand for a common combination.
3789  */
3790 void
3792 {
3793  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
3794  ReleaseBuffer(buffer);
3795 }
3796 
3797 /*
3798  * IncrBufferRefCount
3799  * Increment the pin count on a buffer that we have *already* pinned
3800  * at least once.
3801  *
3802  * This function cannot be used on a buffer we do not have pinned,
3803  * because it doesn't change the shared buffer state.
3804  */
3805 void
3807 {
3808  Assert(BufferIsPinned(buffer));
3810  if (BufferIsLocal(buffer))
3811  LocalRefCount[-buffer - 1]++;
3812  else
3813  {
3814  PrivateRefCountEntry *ref;
3815 
3816  ref = GetPrivateRefCountEntry(buffer, true);
3817  Assert(ref != NULL);
3818  ref->refcount++;
3819  }
3821 }
3822 
3823 /*
3824  * MarkBufferDirtyHint
3825  *
3826  * Mark a buffer dirty for non-critical changes.
3827  *
3828  * This is essentially the same as MarkBufferDirty, except:
3829  *
3830  * 1. The caller does not write WAL; so if checksums are enabled, we may need
3831  * to write an XLOG_FPI_FOR_HINT WAL record to protect against torn pages.
3832  * 2. The caller might have only share-lock instead of exclusive-lock on the
3833  * buffer's content lock.
3834  * 3. This function does not guarantee that the buffer is always marked dirty
3835  * (due to a race condition), so it cannot be used for important changes.
3836  */
3837 void
3839 {
3840  BufferDesc *bufHdr;
3841  Page page = BufferGetPage(buffer);
3842 
3843  if (!BufferIsValid(buffer))
3844  elog(ERROR, "bad buffer ID: %d", buffer);
3845 
3846  if (BufferIsLocal(buffer))
3847  {
3848  MarkLocalBufferDirty(buffer);
3849  return;
3850  }
3851 
3852  bufHdr = GetBufferDescriptor(buffer - 1);
3853 
3854  Assert(GetPrivateRefCount(buffer) > 0);
3855  /* here, either share or exclusive lock is OK */
3857 
3858  /*
3859  * This routine might get called many times on the same page, if we are
3860  * making the first scan after commit of an xact that added/deleted many
3861  * tuples. So, be as quick as we can if the buffer is already dirty. We
3862  * do this by not acquiring spinlock if it looks like the status bits are
3863  * already set. Since we make this test unlocked, there's a chance we
3864  * might fail to notice that the flags have just been cleared, and failed
3865  * to reset them, due to memory-ordering issues. But since this function
3866  * is only intended to be used in cases where failing to write out the
3867  * data would be harmless anyway, it doesn't really matter.
3868  */
3869  if ((pg_atomic_read_u32(&bufHdr->state) & (BM_DIRTY | BM_JUST_DIRTIED)) !=
3871  {
3873  bool dirtied = false;
3874  bool delayChkpt = false;
3875  uint32 buf_state;
3876 
3877  /*
3878  * If we need to protect hint bit updates from torn writes, WAL-log a
3879  * full page image of the page. This full page image is only necessary
3880  * if the hint bit update is the first change to the page since the
3881  * last checkpoint.
3882  *
3883  * We don't check full_page_writes here because that logic is included
3884  * when we call XLogInsert() since the value changes dynamically.
3885  */
3886  if (XLogHintBitIsNeeded() &&
3887  (pg_atomic_read_u32(&bufHdr->state) & BM_PERMANENT))
3888  {
3889  /*
3890  * If we must not write WAL, due to a relfilenode-specific
3891  * condition or being in recovery, don't dirty the page. We can
3892  * set the hint, just not dirty the page as a result so the hint
3893  * is lost when we evict the page or shutdown.
3894  *
3895  * See src/backend/storage/page/README for longer discussion.
3896  */
3897  if (RecoveryInProgress() ||
3898  RelFileNodeSkippingWAL(bufHdr->tag.rnode))
3899  return;
3900 
3901  /*
3902  * If the block is already dirty because we either made a change
3903  * or set a hint already, then we don't need to write a full page
3904  * image. Note that aggressive cleaning of blocks dirtied by hint
3905  * bit setting would increase the call rate. Bulk setting of hint
3906  * bits would reduce the call rate...
3907  *
3908  * We must issue the WAL record before we mark the buffer dirty.
3909  * Otherwise we might write the page before we write the WAL. That
3910  * causes a race condition, since a checkpoint might occur between
3911  * writing the WAL record and marking the buffer dirty. We solve
3912  * that with a kluge, but one that is already in use during
3913  * transaction commit to prevent race conditions. Basically, we
3914  * simply prevent the checkpoint WAL record from being written
3915  * until we have marked the buffer dirty. We don't start the
3916  * checkpoint flush until we have marked dirty, so our checkpoint
3917  * must flush the change to disk successfully or the checkpoint
3918  * never gets written, so crash recovery will fix.
3919  *
3920  * It's possible we may enter here without an xid, so it is
3921  * essential that CreateCheckpoint waits for virtual transactions
3922  * rather than full transactionids.
3923  */
3924  MyProc->delayChkpt = delayChkpt = true;
3925  lsn = XLogSaveBufferForHint(buffer, buffer_std);
3926  }
3927 
3928  buf_state = LockBufHdr(bufHdr);
3929 
3930  Assert(BUF_STATE_GET_REFCOUNT(buf_state) > 0);
3931 
3932  if (!(buf_state & BM_DIRTY))
3933  {
3934  dirtied = true; /* Means "will be dirtied by this action" */
3935 
3936  /*
3937  * Set the page LSN if we wrote a backup block. We aren't supposed
3938  * to set this when only holding a share lock but as long as we
3939  * serialise it somehow we're OK. We choose to set LSN while
3940  * holding the buffer header lock, which causes any reader of an
3941  * LSN who holds only a share lock to also obtain a buffer header
3942  * lock before using PageGetLSN(), which is enforced in
3943  * BufferGetLSNAtomic().
3944  *
3945  * If checksums are enabled, you might think we should reset the
3946  * checksum here. That will happen when the page is written
3947  * sometime later in this checkpoint cycle.
3948  */
3949  if (!XLogRecPtrIsInvalid(lsn))
3950  PageSetLSN(page, lsn);
3951  }
3952 
3953  buf_state |= BM_DIRTY | BM_JUST_DIRTIED;
3954  UnlockBufHdr(bufHdr, buf_state);
3955 
3956  if (delayChkpt)
3957  MyProc->delayChkpt = false;
3958 
3959  if (dirtied)
3960  {
3961  VacuumPageDirty++;
3963  if (VacuumCostActive)
3965  }
3966  }
3967 }
3968 
3969 /*
3970  * Release buffer content locks for shared buffers.
3971  *
3972  * Used to clean up after errors.
3973  *
3974  * Currently, we can expect that lwlock.c's LWLockReleaseAll() took care
3975  * of releasing buffer content locks per se; the only thing we need to deal
3976  * with here is clearing any PIN_COUNT request that was in progress.
3977  */
3978 void
3980 {
3982 
3983  if (buf)
3984  {
3985  uint32 buf_state;
3986 
3987  buf_state = LockBufHdr(buf);
3988 
3989  /*
3990  * Don't complain if flag bit not set; it could have been reset but we
3991  * got a cancel/die interrupt before getting the signal.
3992  */
3993  if ((buf_state & BM_PIN_COUNT_WAITER) != 0 &&
3994  buf->wait_backend_pid == MyProcPid)
3995  buf_state &= ~BM_PIN_COUNT_WAITER;
3996 
3997  UnlockBufHdr(buf, buf_state);
3998 
3999  PinCountWaitBuf = NULL;
4000  }
4001 }
4002 
4003 /*
4004  * Acquire or release the content_lock for the buffer.
4005  */
4006 void
4008 {
4009  BufferDesc *buf;
4010 
4011  Assert(BufferIsPinned(buffer));
4012  if (BufferIsLocal(buffer))
4013  return; /* local buffers need no lock */
4014 
4015  buf = GetBufferDescriptor(buffer - 1);
4016 
4017  if (mode == BUFFER_LOCK_UNLOCK)
4019  else if (mode == BUFFER_LOCK_SHARE)
4021  else if (mode == BUFFER_LOCK_EXCLUSIVE)
4023  else
4024  elog(ERROR, "unrecognized buffer lock mode: %d", mode);
4025 }
4026 
4027 /*
4028  * Acquire the content_lock for the buffer, but only if we don't have to wait.
4029  *
4030  * This assumes the caller wants BUFFER_LOCK_EXCLUSIVE mode.
4031  */
4032 bool
4034 {
4035  BufferDesc *buf;
4036 
4037  Assert(BufferIsPinned(buffer));
4038  if (BufferIsLocal(buffer))
4039  return true; /* act as though we got it */
4040 
4041  buf = GetBufferDescriptor(buffer - 1);
4042 
4044  LW_EXCLUSIVE);
4045 }
4046 
4047 /*
4048  * LockBufferForCleanup - lock a buffer in preparation for deleting items
4049  *
4050  * Items may be deleted from a disk page only when the caller (a) holds an
4051  * exclusive lock on the buffer and (b) has observed that no other backend
4052  * holds a pin on the buffer. If there is a pin, then the other backend
4053  * might have a pointer into the buffer (for example, a heapscan reference
4054  * to an item --- see README for more details). It's OK if a pin is added
4055  * after the cleanup starts, however; the newly-arrived backend will be
4056  * unable to look at the page until we release the exclusive lock.
4057  *
4058  * To implement this protocol, a would-be deleter must pin the buffer and
4059  * then call LockBufferForCleanup(). LockBufferForCleanup() is similar to
4060  * LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE), except that it loops until
4061  * it has successfully observed pin count = 1.
4062  */
4063 void
4065 {
4066  BufferDesc *bufHdr;
4067  char *new_status = NULL;
4068  TimestampTz waitStart = 0;
4069  bool logged_recovery_conflict = false;
4070 
4071  Assert(BufferIsPinned(buffer));
4072  Assert(PinCountWaitBuf == NULL);
4073 
4074  if (BufferIsLocal(buffer))
4075  {
4076  /* There should be exactly one pin */
4077  if (LocalRefCount[-buffer - 1] != 1)
4078  elog(ERROR, "incorrect local pin count: %d",
4079  LocalRefCount[-buffer - 1]);
4080  /* Nobody else to wait for */
4081  return;
4082  }
4083 
4084  /* There should be exactly one local pin */
4085  if (GetPrivateRefCount(buffer) != 1)
4086  elog(ERROR, "incorrect local pin count: %d",
4087  GetPrivateRefCount(buffer));
4088 
4089  bufHdr = GetBufferDescriptor(buffer - 1);
4090 
4091  for (;;)
4092  {
4093  uint32 buf_state;
4094 
4095  /* Try to acquire lock */
4097  buf_state = LockBufHdr(bufHdr);
4098 
4099  Assert(BUF_STATE_GET_REFCOUNT(buf_state) > 0);
4100  if (BUF_STATE_GET_REFCOUNT(buf_state) == 1)
4101  {
4102  /* Successfully acquired exclusive lock with pincount 1 */
4103  UnlockBufHdr(bufHdr, buf_state);
4104 
4105  /*
4106  * Emit the log message if recovery conflict on buffer pin was
4107  * resolved but the startup process waited longer than
4108  * deadlock_timeout for it.
4109  */
4110  if (logged_recovery_conflict)
4112  waitStart, GetCurrentTimestamp(),
4113  NULL, false);
4114 
4115  /* Report change to non-waiting status */
4116  if (new_status)
4117  {
4118  set_ps_display(new_status);
4119  pfree(new_status);
4120  }
4121  return;
4122  }
4123  /* Failed, so mark myself as waiting for pincount 1 */
4124  if (buf_state & BM_PIN_COUNT_WAITER)
4125  {
4126  UnlockBufHdr(bufHdr, buf_state);
4127  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
4128  elog(ERROR, "multiple backends attempting to wait for pincount 1");
4129  }
4130  bufHdr->wait_backend_pid = MyProcPid;
4131  PinCountWaitBuf = bufHdr;
4132  buf_state |= BM_PIN_COUNT_WAITER;
4133  UnlockBufHdr(bufHdr, buf_state);
4134  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
4135 
4136  /* Wait to be signaled by UnpinBuffer() */
4137  if (InHotStandby)
4138  {
4139  /* Report change to waiting status */
4140  if (update_process_title && new_status == NULL)
4141  {
4142  const char *old_status;
4143  int len;
4144 
4145  old_status = get_ps_display(&len);
4146  new_status = (char *) palloc(len + 8 + 1);
4147  memcpy(new_status, old_status, len);
4148  strcpy(new_status + len, " waiting");
4149  set_ps_display(new_status);
4150  new_status[len] = '\0'; /* truncate off " waiting" */
4151  }
4152 
4153  /*
4154  * Emit the log message if the startup process is waiting longer
4155  * than deadlock_timeout for recovery conflict on buffer pin.
4156  *
4157  * Skip this if first time through because the startup process has
4158  * not started waiting yet in this case. So, the wait start
4159  * timestamp is set after this logic.
4160  */
4161  if (waitStart != 0 && !logged_recovery_conflict)
4162  {
4164 
4165  if (TimestampDifferenceExceeds(waitStart, now,
4166  DeadlockTimeout))
4167  {
4169  waitStart, now, NULL, true);
4170  logged_recovery_conflict = true;
4171  }
4172  }
4173 
4174  /*
4175  * Set the wait start timestamp if logging is enabled and first
4176  * time through.
4177  */
4178  if (log_recovery_conflict_waits && waitStart == 0)
4179  waitStart = GetCurrentTimestamp();
4180 
4181  /* Publish the bufid that Startup process waits on */
4182  SetStartupBufferPinWaitBufId(buffer - 1);
4183  /* Set alarm and then wait to be signaled by UnpinBuffer() */
4185  /* Reset the published bufid */
4187  }
4188  else
4190 
4191  /*
4192  * Remove flag marking us as waiter. Normally this will not be set
4193  * anymore, but ProcWaitForSignal() can return for other signals as
4194  * well. We take care to only reset the flag if we're the waiter, as
4195  * theoretically another backend could have started waiting. That's
4196  * impossible with the current usages due to table level locking, but
4197  * better be safe.
4198  */
4199  buf_state = LockBufHdr(bufHdr);
4200  if ((buf_state & BM_PIN_COUNT_WAITER) != 0 &&
4201  bufHdr->wait_backend_pid == MyProcPid)
4202  buf_state &= ~BM_PIN_COUNT_WAITER;
4203  UnlockBufHdr(bufHdr, buf_state);
4204 
4205  PinCountWaitBuf = NULL;
4206  /* Loop back and try again */
4207  }
4208 }
4209 
4210 /*
4211  * Check called from RecoveryConflictInterrupt handler when Startup
4212  * process requests cancellation of all pin holders that are blocking it.
4213  */
4214 bool
4216 {
4217  int bufid = GetStartupBufferPinWaitBufId();
4218 
4219  /*
4220  * If we get woken slowly then it's possible that the Startup process was
4221  * already woken by other backends before we got here. Also possible that
4222  * we get here by multiple interrupts or interrupts at inappropriate
4223  * times, so make sure we do nothing if the bufid is not set.
4224  */
4225  if (bufid < 0)
4226  return false;
4227 
4228  if (GetPrivateRefCount(bufid + 1) > 0)
4229  return true;
4230 
4231  return false;
4232 }
4233 
4234 /*
4235  * ConditionalLockBufferForCleanup - as above, but don't wait to get the lock
4236  *
4237  * We won't loop, but just check once to see if the pin count is OK. If
4238  * not, return false with no lock held.
4239  */
4240 bool
4242 {
4243  BufferDesc *bufHdr;
4244  uint32 buf_state,
4245  refcount;
4246 
4247  Assert(BufferIsValid(buffer));
4248 
4249  if (BufferIsLocal(buffer))
4250  {
4251  refcount = LocalRefCount[-buffer - 1];
4252  /* There should be exactly one pin */
4253  Assert(refcount > 0);
4254  if (refcount != 1)
4255  return false;
4256  /* Nobody else to wait for */
4257  return true;
4258  }
4259 
4260  /* There should be exactly one local pin */
4261  refcount = GetPrivateRefCount(buffer);
4262  Assert(refcount);
4263  if (refcount != 1)
4264  return false;
4265 
4266  /* Try to acquire lock */
4267  if (!ConditionalLockBuffer(buffer))
4268  return false;
4269 
4270  bufHdr = GetBufferDescriptor(buffer - 1);
4271  buf_state = LockBufHdr(bufHdr);
4272  refcount = BUF_STATE_GET_REFCOUNT(buf_state);
4273 
4274  Assert(refcount > 0);
4275  if (refcount == 1)
4276  {
4277  /* Successfully acquired exclusive lock with pincount 1 */
4278  UnlockBufHdr(bufHdr, buf_state);
4279  return true;
4280  }
4281 
4282  /* Failed, so release the lock */
4283  UnlockBufHdr(bufHdr, buf_state);
4284  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
4285  return false;
4286 }
4287 
4288 /*
4289  * IsBufferCleanupOK - as above, but we already have the lock
4290  *
4291  * Check whether it's OK to perform cleanup on a buffer we've already
4292  * locked. If we observe that the pin count is 1, our exclusive lock
4293  * happens to be a cleanup lock, and we can proceed with anything that
4294  * would have been allowable had we sought a cleanup lock originally.
4295  */
4296 bool
4298 {
4299  BufferDesc *bufHdr;
4300  uint32 buf_state;
4301 
4302  Assert(BufferIsValid(buffer));
4303 
4304  if (BufferIsLocal(buffer))
4305  {
4306  /* There should be exactly one pin */
4307  if (LocalRefCount[-buffer - 1] != 1)
4308  return false;
4309  /* Nobody else to wait for */
4310  return true;
4311  }
4312 
4313  /* There should be exactly one local pin */
4314  if (GetPrivateRefCount(buffer) != 1)
4315  return false;
4316 
4317  bufHdr = GetBufferDescriptor(buffer - 1);
4318 
4319  /* caller must hold exclusive lock on buffer */
4321  LW_EXCLUSIVE));
4322 
4323  buf_state = LockBufHdr(bufHdr);
4324 
4325  Assert(BUF_STATE_GET_REFCOUNT(buf_state) > 0);
4326  if (BUF_STATE_GET_REFCOUNT(buf_state) == 1)
4327  {
4328  /* pincount is OK. */
4329  UnlockBufHdr(bufHdr, buf_state);
4330  return true;
4331  }
4332 
4333  UnlockBufHdr(bufHdr, buf_state);
4334  return false;
4335 }
4336 
4337 
4338 /*
4339  * Functions for buffer I/O handling
4340  *
4341  * Note: We assume that nested buffer I/O never occurs.
4342  * i.e at most one BM_IO_IN_PROGRESS bit is set per proc.
4343  *
4344  * Also note that these are used only for shared buffers, not local ones.
4345  */
4346 
4347 /*
4348  * WaitIO -- Block until the IO_IN_PROGRESS flag on 'buf' is cleared.
4349  */
4350 static void
4352 {
4354 
4356  for (;;)
4357  {
4358  uint32 buf_state;
4359 
4360  /*
4361  * It may not be necessary to acquire the spinlock to check the flag
4362  * here, but since this test is essential for correctness, we'd better
4363  * play it safe.
4364  */
4365  buf_state = LockBufHdr(buf);
4366  UnlockBufHdr(buf, buf_state);
4367 
4368  if (!(buf_state & BM_IO_IN_PROGRESS))
4369  break;
4371  }
4373 }
4374 
4375 /*
4376  * StartBufferIO: begin I/O on this buffer
4377  * (Assumptions)
4378  * My process is executing no IO
4379  * The buffer is Pinned
4380  *
4381  * In some scenarios there are race conditions in which multiple backends
4382  * could attempt the same I/O operation concurrently. If someone else
4383  * has already started I/O on this buffer then we will block on the
4384  * I/O condition variable until he's done.
4385  *
4386  * Input operations are only attempted on buffers that are not BM_VALID,
4387  * and output operations only on buffers that are BM_VALID and BM_DIRTY,
4388  * so we can always tell if the work is already done.
4389  *
4390  * Returns true if we successfully marked the buffer as I/O busy,
4391  * false if someone else already did the work.
4392  */
4393 static bool
4394 StartBufferIO(BufferDesc *buf, bool forInput)
4395 {
4396  uint32 buf_state;
4397 
4398  Assert(!InProgressBuf);
4399 
4400  for (;;)
4401  {
4402  buf_state = LockBufHdr(buf);
4403 
4404  if (!(buf_state & BM_IO_IN_PROGRESS))
4405  break;
4406  UnlockBufHdr(buf, buf_state);
4407  WaitIO(buf);
4408  }
4409 
4410  /* Once we get here, there is definitely no I/O active on this buffer */
4411 
4412  if (forInput ? (buf_state & BM_VALID) : !(buf_state & BM_DIRTY))
4413  {
4414  /* someone else already did the I/O */
4415  UnlockBufHdr(buf, buf_state);
4416  return false;
4417  }
4418 
4419  buf_state |= BM_IO_IN_PROGRESS;
4420  UnlockBufHdr(buf, buf_state);
4421 
4422  InProgressBuf = buf;
4423  IsForInput = forInput;
4424 
4425  return true;
4426 }
4427 
4428 /*
4429  * TerminateBufferIO: release a buffer we were doing I/O on
4430  * (Assumptions)
4431  * My process is executing IO for the buffer
4432  * BM_IO_IN_PROGRESS bit is set for the buffer
4433  * The buffer is Pinned
4434  *
4435  * If clear_dirty is true and BM_JUST_DIRTIED is not set, we clear the
4436  * buffer's BM_DIRTY flag. This is appropriate when terminating a
4437  * successful write. The check on BM_JUST_DIRTIED is necessary to avoid
4438  * marking the buffer clean if it was re-dirtied while we were writing.
4439  *
4440  * set_flag_bits gets ORed into the buffer's flags. It must include
4441  * BM_IO_ERROR in a failure case. For successful completion it could
4442  * be 0, or BM_VALID if we just finished reading in the page.
4443  */
4444 static void
4445 TerminateBufferIO(BufferDesc *buf, bool clear_dirty, uint32 set_flag_bits)
4446 {
4447  uint32 buf_state;
4448 
4449  Assert(buf == InProgressBuf);
4450 
4451  buf_state = LockBufHdr(buf);
4452 
4453  Assert(buf_state & BM_IO_IN_PROGRESS);
4454 
4455  buf_state &= ~(BM_IO_IN_PROGRESS | BM_IO_ERROR);
4456  if (clear_dirty && !(buf_state & BM_JUST_DIRTIED))
4457  buf_state &= ~(BM_DIRTY | BM_CHECKPOINT_NEEDED);
4458 
4459  buf_state |= set_flag_bits;
4460  UnlockBufHdr(buf, buf_state);
4461 
4462  InProgressBuf = NULL;
4463 
4465 }
4466 
4467 /*
4468  * AbortBufferIO: Clean up any active buffer I/O after an error.
4469  *
4470  * All LWLocks we might have held have been released,
4471  * but we haven't yet released buffer pins, so the buffer is still pinned.
4472  *
4473  * If I/O was in progress, we always set BM_IO_ERROR, even though it's
4474  * possible the error condition wasn't related to the I/O.
4475  */
4476 void
4478 {
4480 
4481  if (buf)
4482  {
4483  uint32 buf_state;
4484 
4485  buf_state = LockBufHdr(buf);
4486  Assert(buf_state & BM_IO_IN_PROGRESS);
4487  if (IsForInput)
4488  {
4489  Assert(!(buf_state & BM_DIRTY));
4490 
4491  /* We'd better not think buffer is valid yet */
4492  Assert(!(buf_state & BM_VALID));
4493  UnlockBufHdr(buf, buf_state);
4494  }
4495  else
4496  {
4497  Assert(buf_state & BM_DIRTY);
4498  UnlockBufHdr(buf, buf_state);
4499  /* Issue notice if this is not the first failure... */
4500  if (buf_state & BM_IO_ERROR)
4501  {
4502  /* Buffer is pinned, so we can read tag without spinlock */
4503  char *path;
4504 
4505  path = relpathperm(buf->tag.rnode, buf->tag.forkNum);
4506  ereport(WARNING,
4507  (errcode(ERRCODE_IO_ERROR),
4508  errmsg("could not write block %u of %s",
4509  buf->tag.blockNum, path),
4510  errdetail("Multiple failures --- write error might be permanent.")));
4511  pfree(path);
4512  }
4513  }
4514  TerminateBufferIO(buf, false, BM_IO_ERROR);
4515  }
4516 }
4517 
4518 /*
4519  * Error context callback for errors occurring during shared buffer writes.
4520  */
4521 static void
4523 {
4524  BufferDesc *bufHdr = (BufferDesc *) arg;
4525 
4526  /* Buffer is pinned, so we can read the tag without locking the spinlock */
4527  if (bufHdr != NULL)
4528  {
4529  char *path = relpathperm(bufHdr->tag.rnode, bufHdr->tag.forkNum);
4530 
4531  errcontext("writing block %u of relation %s",
4532  bufHdr->tag.blockNum, path);
4533  pfree(path);
4534  }
4535 }
4536 
4537 /*
4538  * Error context callback for errors occurring during local buffer writes.
4539  */
4540 static void
4542 {
4543  BufferDesc *bufHdr = (BufferDesc *) arg;
4544 
4545  if (bufHdr != NULL)
4546  {
4547  char *path = relpathbackend(bufHdr->tag.rnode, MyBackendId,
4548  bufHdr->tag.forkNum);
4549 
4550  errcontext("writing block %u of relation %s",
4551  bufHdr->tag.blockNum, path);
4552  pfree(path);
4553  }
4554 }
4555 
4556 /*
4557  * RelFileNode qsort/bsearch comparator; see RelFileNodeEquals.
4558  */
4559 static int
4560 rnode_comparator(const void *p1, const void *p2)
4561 {
4562  RelFileNode n1 = *(const RelFileNode *) p1;
4563  RelFileNode n2 = *(const RelFileNode *) p2;
4564 
4565  if (n1.relNode < n2.relNode)
4566  return -1;
4567  else if (n1.relNode > n2.relNode)
4568  return 1;
4569 
4570  if (n1.dbNode < n2.dbNode)
4571  return -1;
4572  else if (n1.dbNode > n2.dbNode)
4573  return 1;
4574 
4575  if (n1.spcNode < n2.spcNode)
4576  return -1;
4577  else if (n1.spcNode > n2.spcNode)
4578  return 1;
4579  else
4580  return 0;
4581 }
4582 
4583 /*
4584  * Lock buffer header - set BM_LOCKED in buffer state.
4585  */
4586 uint32
4588 {
4589  SpinDelayStatus delayStatus;
4590  uint32 old_buf_state;
4591 
4592  init_local_spin_delay(&delayStatus);
4593 
4594  while (true)
4595  {
4596  /* set BM_LOCKED flag */
4597  old_buf_state = pg_atomic_fetch_or_u32(&desc->state, BM_LOCKED);
4598  /* if it wasn't set before we're OK */
4599  if (!(old_buf_state & BM_LOCKED))
4600  break;
4601  perform_spin_delay(&delayStatus);
4602  }
4603  finish_spin_delay(&delayStatus);
4604  return old_buf_state | BM_LOCKED;
4605 }
4606 
4607 /*
4608  * Wait until the BM_LOCKED flag isn't set anymore and return the buffer's
4609  * state at that point.
4610  *
4611  * Obviously the buffer could be locked by the time the value is returned, so
4612  * this is primarily useful in CAS style loops.
4613  */
4614 static uint32
4616 {
4617  SpinDelayStatus delayStatus;
4618  uint32 buf_state;
4619 
4620  init_local_spin_delay(&delayStatus);
4621 
4622  buf_state = pg_atomic_read_u32(&buf->state);
4623 
4624  while (buf_state & BM_LOCKED)
4625  {
4626  perform_spin_delay(&delayStatus);
4627  buf_state = pg_atomic_read_u32(&buf->state);
4628  }
4629 
4630  finish_spin_delay(&delayStatus);
4631 
4632  return buf_state;
4633 }
4634 
4635 /*
4636  * BufferTag comparator.
4637  */
4638 static inline int
4640 {
4641  int ret;
4642 
4643  ret = rnode_comparator(&ba->rnode, &bb->rnode);
4644 
4645  if (ret != 0)
4646  return ret;
4647 
4648  if (ba->forkNum < bb->forkNum)
4649  return -1;
4650  if (ba->forkNum > bb->forkNum)
4651  return 1;
4652 
4653  if (ba->blockNum < bb->blockNum)
4654  return -1;
4655  if (ba->blockNum > bb->blockNum)
4656  return 1;
4657 
4658  return 0;
4659 }
4660 
4661 /*
4662  * Comparator determining the writeout order in a checkpoint.
4663  *
4664  * It is important that tablespaces are compared first, the logic balancing
4665  * writes between tablespaces relies on it.
4666  */
4667 static inline int
4669 {
4670  /* compare tablespace */
4671  if (a->tsId < b->tsId)
4672  return -1;
4673  else if (a->tsId > b->tsId)
4674  return 1;
4675  /* compare relation */
4676  if (a->relNode < b->relNode)
4677  return -1;
4678  else if (a->relNode > b->relNode)
4679  return 1;
4680  /* compare fork */
4681  else if (a->forkNum < b->forkNum)
4682  return -1;
4683  else if (a->forkNum > b->forkNum)
4684  return 1;
4685  /* compare block number */
4686  else if (a->blockNum < b->blockNum)
4687  return -1;
4688  else if (a->blockNum > b->blockNum)
4689  return 1;
4690  /* equal page IDs are unlikely, but not impossible */
4691  return 0;
4692 }
4693 
4694 /*
4695  * Comparator for a Min-Heap over the per-tablespace checkpoint completion
4696  * progress.
4697  */
4698 static int
4700 {
4701  CkptTsStatus *sa = (CkptTsStatus *) a;
4702  CkptTsStatus *sb = (CkptTsStatus *) b;
4703 
4704  /* we want a min-heap, so return 1 for the a < b */
4705  if (sa->progress < sb->progress)
4706  return 1;
4707  else if (sa->progress == sb->progress)
4708  return 0;
4709  else
4710  return -1;
4711 }
4712 
4713 /*
4714  * Initialize a writeback context, discarding potential previous state.
4715  *
4716  * *max_pending is a pointer instead of an immediate value, so the coalesce
4717  * limits can easily changed by the GUC mechanism, and so calling code does
4718  * not have to check the current configuration. A value of 0 means that no
4719  * writeback control will be performed.
4720  */
4721 void
4722 WritebackContextInit(WritebackContext *context, int *max_pending)
4723 {
4724  Assert(*max_pending <= WRITEBACK_MAX_PENDING_FLUSHES);
4725 
4726  context->max_pending = max_pending;
4727  context->nr_pending = 0;
4728 }
4729 
4730 /*
4731  * Add buffer to list of pending writeback requests.
4732  */
4733 void
4735 {
4736  PendingWriteback *pending;
4737 
4738  /*
4739  * Add buffer to the pending writeback array, unless writeback control is
4740  * disabled.
4741  */
4742  if (*context->max_pending > 0)
4743  {
4745 
4746  pending = &context->pending_writebacks[context->nr_pending++];
4747 
4748  pending->tag = *tag;
4749  }
4750 
4751  /*
4752  * Perform pending flushes if the writeback limit is exceeded. This
4753  * includes the case where previously an item has been added, but control
4754  * is now disabled.
4755  */
4756  if (context->nr_pending >= *context->max_pending)
4757  IssuePendingWritebacks(context);
4758 }
4759 
4760 #define ST_SORT sort_pending_writebacks
4761 #define ST_ELEMENT_TYPE PendingWriteback
4762 #define ST_COMPARE(a, b) buffertag_comparator(&a->tag, &b->tag)
4763 #define ST_SCOPE static
4764 #define ST_DEFINE
4765 #include <lib/sort_template.h>
4766 
4767 /*
4768  * Issue all pending writeback requests, previously scheduled with
4769  * ScheduleBufferTagForWriteback, to the OS.
4770  *
4771  * Because this is only used to improve the OSs IO scheduling we try to never
4772  * error out - it's just a hint.
4773  */
4774 void
4776 {
4777  int i;
4778 
4779  if (context->nr_pending == 0)
4780  return;
4781 
4782  /*
4783  * Executing the writes in-order can make them a lot faster, and allows to
4784  * merge writeback requests to consecutive blocks into larger writebacks.
4785  */
4786  sort_pending_writebacks(context->pending_writebacks, context->nr_pending);
4787 
4788  /*
4789  * Coalesce neighbouring writes, but nothing else. For that we iterate
4790  * through the, now sorted, array of pending flushes, and look forward to
4791  * find all neighbouring (or identical) writes.
4792  */
4793  for (i = 0; i < context->nr_pending; i++)
4794  {
4797  SMgrRelation reln;
4798  int ahead;
4799  BufferTag tag;
4800  Size nblocks = 1;
4801 
4802  cur = &context->pending_writebacks[i];
4803  tag = cur->tag;
4804 
4805  /*
4806  * Peek ahead, into following writeback requests, to see if they can
4807  * be combined with the current one.
4808  */
4809  for (ahead = 0; i + ahead + 1 < context->nr_pending; ahead++)
4810  {
4811  next = &context->pending_writebacks[i + ahead + 1];
4812 
4813  /* different file, stop */
4814  if (!RelFileNodeEquals(cur->tag.rnode, next->tag.rnode) ||
4815  cur->tag.forkNum != next->tag.forkNum)
4816  break;
4817 
4818  /* ok, block queued twice, skip */
4819  if (cur->tag.blockNum == next->tag.blockNum)
4820  continue;
4821 
4822  /* only merge consecutive writes */
4823  if (cur->tag.blockNum + 1 != next->tag.blockNum)
4824  break;
4825 
4826  nblocks++;
4827  cur = next;
4828  }
4829 
4830  i += ahead;
4831 
4832  /* and finally tell the kernel to write the data to storage */
4833  reln = smgropen(tag.rnode, InvalidBackendId);
4834  smgrwriteback(reln, tag.forkNum, tag.blockNum, nblocks);
4835  }
4836 
4837  context->nr_pending = 0;
4838 }
4839 
4840 
4841 /*
4842  * Implement slower/larger portions of TestForOldSnapshot
4843  *
4844  * Smaller/faster portions are put inline, but the entire set of logic is too
4845  * big for that.
4846  */
4847 void
4849 {
4850  if (RelationAllowsEarlyPruning(relation)
4851  && (snapshot)->whenTaken < GetOldSnapshotThresholdTimestamp())
4852  ereport(ERROR,
4853  (errcode(ERRCODE_SNAPSHOT_TOO_OLD),
4854  errmsg("snapshot too old")));
4855 }
PgStat_MsgCheckpointer PendingCheckpointerStats
Definition: pgstat.c:132
#define LocalBufHdrGetBlock(bufHdr)
Definition: bufmgr.c:64
BufferDesc * LocalBufferAlloc(SMgrRelation smgr, ForkNumber forkNum, BlockNumber blockNum, bool *foundPtr)
Definition: localbuf.c:109
static bool PinBuffer(BufferDesc *buf, BufferAccessStrategy strategy)
Definition: bufmgr.c:1686
static PrivateRefCountEntry * GetPrivateRefCountEntry(Buffer buffer, bool do_move)
Definition: bufmgr.c:307
#define init_local_spin_delay(status)
Definition: s_lock.h:1067
struct PrivateRefCountEntry PrivateRefCountEntry
#define BufferIsPinned(bufnum)
Definition: bufmgr.c:448
static PgChecksumMode mode
Definition: pg_checksums.c:65
#define BUFFER_LOCK_UNLOCK
Definition: bufmgr.h:96
BufferDesc * StrategyGetBuffer(BufferAccessStrategy strategy, uint32 *buf_state)
Definition: freelist.c:201
void BufTableDelete(BufferTag *tagPtr, uint32 hashcode)
Definition: buf_table.c:149
void CheckpointWriteDelay(int flags, double progress)
Definition: checkpointer.c:687
void LockBufferForCleanup(Buffer buffer)
Definition: bufmgr.c:4064
Definition: lwlock.h:31
#define relpathperm(rnode, forknum)
Definition: relpath.h:83
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
void CheckPointBuffers(int flags)
Definition: bufmgr.c:2724
PgStat_Counter m_buf_alloc
Definition: pgstat.h:462
#define BM_PERMANENT
Definition: buf_internals.h:67
bool LWLockHeldByMeInMode(LWLock *l, LWLockMode mode)
Definition: lwlock.c:1937
int StrategySyncStart(uint32 *complete_passes, uint32 *num_buf_alloc)
Definition: freelist.c:395
int64 VacuumPageMiss
Definition: globals.c:148
#define CHECKPOINT_FLUSH_ALL
Definition: xlog.h:201
#define BufMappingPartitionLock(hashcode)
#define DEBUG1
Definition: elog.h:25
int MyProcPid
Definition: globals.c:43
#define VALGRIND_MAKE_MEM_DEFINED(addr, size)
Definition: memdebug.h:26
int errhint(const char *fmt,...)
Definition: elog.c:1156
BackendId MyBackendId
Definition: globals.c:84
TimestampTz GetOldSnapshotThresholdTimestamp(void)
Definition: snapmgr.c:1675
int maintenance_io_concurrency
Definition: bufmgr.c:150
#define BM_TAG_VALID
Definition: buf_internals.h:61
Oid tsId
Definition: bufmgr.c:97
static int32 next
Definition: blutils.c:219
int VacuumCostBalance
Definition: globals.c:151
bool BgBufferSync(WritebackContext *wb_context)
Definition: bufmgr.c:2209
#define binaryheap_empty(h)
Definition: binaryheap.h:52
void PrintBufferLeakWarning(Buffer buffer)
Definition: bufmgr.c:2681
int BgWriterDelay
Definition: bgwriter.c:61
int wait_backend_pid
#define RelFileNodeBackendIsTemp(rnode)
Definition: relfilenode.h:78
ForkNumber forkNum
Definition: buf_internals.h:94
#define HASH_ELEM
Definition: hsearch.h:95
PgStat_MsgBgWriter PendingBgWriterStats
Definition: pgstat.c:131
static uint32 PrivateRefCountClock
Definition: bufmgr.c:200
void MarkBufferDirtyHint(Buffer buffer, bool buffer_std)
Definition: bufmgr.c:3838
static int32 PrivateRefCountOverflowed
Definition: bufmgr.c:199
bool LWLockHeldByMe(LWLock *l)
Definition: lwlock.c:1919
instr_time blk_read_time
Definition: instrument.h:36
bool update_process_title
Definition: ps_status.c:36
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1580
static void InvalidateBuffer(BufferDesc *buf)
Definition: bufmgr.c:1467
static void local_buffer_write_error_callback(void *arg)
Definition: bufmgr.c:4541
static bool pg_atomic_compare_exchange_u32(volatile pg_atomic_uint32 *ptr, uint32 *expected, uint32 newval)
Definition: atomics.h:311
bool XLogNeedsFlush(XLogRecPtr record)
Definition: xlog.c:3209
void MarkBufferDirty(Buffer buffer)
Definition: bufmgr.c:1565
PGPROC * MyProc
Definition: proc.c:68
int64 TimestampTz
Definition: timestamp.h:39
int backend_flush_after
Definition: bufmgr.c:158
int64 shared_blks_read
Definition: instrument.h:27
#define PointerGetDatum(X)
Definition: postgres.h:600
void AtEOXact_Buffers(bool isCommit)
Definition: bufmgr.c:2579
#define VALGRIND_MAKE_MEM_NOACCESS(addr, size)
Definition: memdebug.h:27
ResourceOwner CurrentResourceOwner
Definition: resowner.c:146
PgStat_Counter m_maxwritten_clean
Definition: pgstat.h:461
#define RELS_BSEARCH_THRESHOLD
Definition: bufmgr.c:71
Buffer ReadBufferExtended(Relation reln, ForkNumber forkNum, BlockNumber blockNum, ReadBufferMode mode, BufferAccessStrategy strategy)
Definition: bufmgr.c:741
#define RelationAllowsEarlyPruning(rel)
Definition: snapmgr.h:38
XLogRecPtr XLogSaveBufferForHint(Buffer buffer, bool buffer_std)
Definition: xloginsert.c:972
struct timeval instr_time
Definition: instr_time.h:150
#define BM_CHECKPOINT_NEEDED
Definition: buf_internals.h:66
static void WaitIO(BufferDesc *buf)
Definition: bufmgr.c:4351
int64 VacuumPageHit
Definition: globals.c:147
uint32 BufTableHashCode(BufferTag *tagPtr)
Definition: buf_table.c:79
void ProcessProcSignalBarrier(void)
Definition: procsignal.c:453
static int ts_ckpt_progress_comparator(Datum a, Datum b, void *arg)
Definition: bufmgr.c:4699
PrefetchBufferResult PrefetchLocalBuffer(SMgrRelation smgr, ForkNumber forkNum, BlockNumber blockNum)
Definition: localbuf.c:64
static void ForgetPrivateRefCountEntry(PrivateRefCountEntry *ref)
Definition: bufmgr.c:410
PgStat_Counter m_buf_written_clean
Definition: pgstat.h:460
#define InvalidBuffer
Definition: buf.h:25
Size entrysize
Definition: hsearch.h:76
void LogRecoveryConflict(ProcSignalReason reason, TimestampTz wait_start, TimestampTz now, VirtualTransactionId *wait_list, bool still_waiting)
Definition: standby.c:249
void DropRelFileNodeLocalBuffers(RelFileNode rnode, ForkNumber forkNum, BlockNumber firstDelBlock)
Definition: localbuf.c:326
#define GetLocalBufferDescriptor(id)
Buffer ReadBufferWithoutRelcache(RelFileNode rnode, ForkNumber forkNum, BlockNumber blockNum, ReadBufferMode mode, BufferAccessStrategy strategy)
Definition: bufmgr.c:780
char * PageSetChecksumCopy(Page page, BlockNumber blkno)
Definition: bufpage.c:1503
int checkpoint_flush_after
Definition: bufmgr.c:156
struct cursor * cur
Definition: ecpg.c:28
void ConditionVariableBroadcast(ConditionVariable *cv)
int errcode(int sqlerrcode)
Definition: elog.c:698
#define MemSet(start, val, len)
Definition: c.h:1008
void binaryheap_replace_first(binaryheap *heap, Datum d)
Definition: binaryheap.c:204
void StrategyFreeBuffer(BufferDesc *buf)
Definition: freelist.c:364
int64 VacuumPageDirty
Definition: globals.c:149
uint32 BlockNumber
Definition: block.h:31
void ReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3768
#define P_NEW
Definition: bufmgr.h:91
double bgwriter_lru_multiplier
Definition: bufmgr.c:134
bool smgrexists(SMgrRelation reln, ForkNumber forknum)
Definition: smgr.c:247
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:954
int BufTableLookup(BufferTag *tagPtr, uint32 hashcode)
Definition: buf_table.c:91
#define BUFFER_LOCK_EXCLUSIVE
Definition: bufmgr.h:98
#define LOG
Definition: elog.h:26
int64 shared_blks_dirtied
Definition: instrument.h:28
Form_pg_class rd_rel
Definition: rel.h:109
unsigned int Oid
Definition: postgres_ext.h:31
bool RecoveryInProgress(void)
Definition: xlog.c:8341
#define BM_DIRTY
Definition: buf_internals.h:59
void FlushRelationsAllBuffers(SMgrRelation *smgrs, int nrels)
Definition: bufmgr.c:3601
int VacuumCostPageDirty
Definition: globals.c:143
void(* callback)(void *arg)
Definition: elog.h:247
bool TimestampDifferenceExceeds(TimestampTz start_time, TimestampTz stop_time, int msec)
Definition: timestamp.c:1711
struct ErrorContextCallback * previous
Definition: elog.h:246
void ResourceOwnerRememberBuffer(ResourceOwner owner, Buffer buffer)
Definition: resowner.c:959
void binaryheap_add_unordered(binaryheap *heap, Datum d)
Definition: binaryheap.c:110
Buffer recent_buffer
Definition: bufmgr.h:54
#define BUF_DROP_FULL_SCAN_THRESHOLD
Definition: bufmgr.c:79
void XLogFlush(XLogRecPtr record)
Definition: xlog.c:2888
static void FlushBuffer(BufferDesc *buf, SMgrRelation reln)
Definition: bufmgr.c:2808
int effective_io_concurrency
Definition: bufmgr.c:143
static int SyncOneBuffer(int buf_id, bool skip_recently_used, WritebackContext *wb_context)
Definition: bufmgr.c:2512
void IssuePendingWritebacks(WritebackContext *context)
Definition: bufmgr.c:4775
static BufferDesc * InProgressBuf
Definition: bufmgr.c:161
signed int int32
Definition: c.h:429
void WritebackContextInit(WritebackContext *context, int *max_pending)
Definition: bufmgr.c:4722
static void FindAndDropRelFileNodeBuffers(RelFileNode rnode, ForkNumber forkNum, BlockNumber nForkBlock, BlockNumber firstDelBlock)
Definition: bufmgr.c:3347
bool ReadRecentBuffer(RelFileNode rnode, ForkNumber forkNum, BlockNumber blockNum, Buffer recent_buffer)
Definition: bufmgr.c:618
int bgwriter_flush_after
Definition: bufmgr.c:157
int64 local_blks_read
Definition: instrument.h:31
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1803
struct SMgrSortArray SMgrSortArray
void smgrread(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum, char *buffer)
Definition: smgr.c:501
static PrivateRefCountEntry * NewPrivateRefCountEntry(Buffer buffer)
Definition: bufmgr.c:281
ErrorContextCallback * error_context_stack
Definition: elog.c:93
void ConditionVariablePrepareToSleep(ConditionVariable *cv)
void set_ps_display(const char *activity)
Definition: ps_status.c:349
void ProcSendSignal(int pid)
Definition: proc.c:1909
#define SmgrIsTemp(smgr)
Definition: smgr.h:77
#define BUF_REUSABLE
Definition: bufmgr.c:69
Definition: dynahash.c:219
static bool StartBufferIO(BufferDesc *buf, bool forInput)
Definition: bufmgr.c:4394
void DropRelFileNodeAllLocalBuffers(RelFileNode rnode)
Definition: localbuf.c:373
void pfree(void *pointer)
Definition: mcxt.c:1169
void ConditionVariableCancelSleep(void)
int BufTableInsert(BufferTag *tagPtr, uint32 hashcode, int buf_id)
Definition: buf_table.c:119
void InitBufferPoolAccess(void)
Definition: bufmgr.c:2596
void UnlockReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3791
bool ConditionalLockBufferForCleanup(Buffer buffer)
Definition: bufmgr.c:4241
int64 local_blks_hit
Definition: instrument.h:30
#define ERROR
Definition: elog.h:46
double float8
Definition: c.h:565
bool delayChkpt
Definition: proc.h:187
#define PIV_LOG_WARNING
Definition: bufpage.h:413
#define RelationIsValid(relation)
Definition: rel.h:450
void ResolveRecoveryConflictWithBufferPin(void)
Definition: standby.c:753
#define INSTR_TIME_SUBTRACT(x, y)
Definition: instr_time.h:170
void ScheduleBufferTagForWriteback(WritebackContext *context, BufferTag *tag)
Definition: bufmgr.c:4734
Datum binaryheap_first(binaryheap *heap)
Definition: binaryheap.c:159
#define BUF_FLAG_MASK
Definition: buf_internals.h:46
int bgwriter_lru_maxpages
Definition: bufmgr.c:133
BlockNumber smgrnblocks_cached(SMgrRelation reln, ForkNumber forknum)
Definition: smgr.c:572
int NLocBuffer
Definition: localbuf.c:41
RelFileNodeBackend smgr_rnode
Definition: smgr.h:42
#define pgstat_count_buffer_read(rel)
Definition: pgstat.h:1077
void finish_spin_delay(SpinDelayStatus *status)
Definition: s_lock.c:174
#define DEBUG2
Definition: elog.h:24
WritebackContext BackendWritebackContext
Definition: buf_init.c:23
PendingWriteback pending_writebacks[WRITEBACK_MAX_PENDING_FLUSHES]
SMgrRelation srel
Definition: bufmgr.c:128
int num_to_scan
Definition: bufmgr.c:110
const char * get_ps_display(int *displen)
Definition: ps_status.c:430
void AtProcExit_LocalBuffers(void)
Definition: localbuf.c:588
void on_shmem_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:361
float8 progress_slice
Definition: bufmgr.c:107
XLogRecPtr BufferGetLSNAtomic(Buffer buffer)
Definition: bufmgr.c:3008
bool LWLockConditionalAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1370
void SetStartupBufferPinWaitBufId(int bufid)
Definition: proc.c:650
static char * buf
Definition: pg_test_fsync.c:68
int index
Definition: bufmgr.c:115
float8 progress
Definition: bufmgr.c:106
void FlushDatabaseBuffers(Oid dbid)
Definition: bufmgr.c:3705
#define INSTR_TIME_ADD(x, y)
Definition: instr_time.h:158
#define InHotStandby
Definition: xlogutils.h:57
void smgrwrite(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum, char *buffer, bool skipFsync)
Definition: smgr.c:523
static uint64 table_relation_size(Relation rel, ForkNumber forkNumber)
Definition: tableam.h:1838
#define PIV_REPORT_STAT
Definition: bufpage.h:414
int errdetail(const char *fmt,...)
Definition: elog.c:1042
#define CHECKPOINT_END_OF_RECOVERY
Definition: xlog.h:197
#define BUF_USAGECOUNT_ONE
Definition: buf_internals.h:44
#define GetBufferDescriptor(id)
#define BufferDescriptorGetIOCV(bdesc)
#define PG_WAIT_BUFFER_PIN
Definition: wait_event.h:20
PgStat_Counter m_buf_written_checkpoints
Definition: pgstat.h:475
#define BM_JUST_DIRTIED
Definition: buf_internals.h:64
HTAB * hash_create(const char *tabname, long nelem, const HASHCTL *info, int flags)
Definition: dynahash.c:349
static int32 GetPrivateRefCount(Buffer buffer)
Definition: bufmgr.c:387
void DropRelFileNodeBuffers(SMgrRelation smgr_reln, ForkNumber *forkNum, int nforks, BlockNumber *firstDelBlock)
Definition: bufmgr.c:3054
unsigned int uint32
Definition: c.h:441
void smgrwriteback(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum, BlockNumber nblocks)
Definition: smgr.c:536
bool BufferIsPermanent(Buffer buffer)
Definition: bufmgr.c:2978
#define BUF_WRITTEN
Definition: bufmgr.c:68
#define BufferGetPage(buffer)
Definition: bufmgr.h:169
static bool IsForInput
Definition: bufmgr.c:162
bool PageIsVerifiedExtended(Page page, BlockNumber blkno, int flags)
Definition: bufpage.c:88
bool log_recovery_conflict_waits
Definition: standby.c:42
static struct PrivateRefCountEntry PrivateRefCountArray[REFCOUNT_ARRAY_ENTRIES]
Definition: bufmgr.c:197
bool ConditionalLockBuffer(Buffer buffer)
Definition: bufmgr.c:4033
int VacuumCostPageHit
Definition: globals.c:141
static void BufferSync(int flags)
Definition: bufmgr.c:1933
#define BUFFERTAGS_EQUAL(a, b)
SMgrRelation smgropen(RelFileNode rnode, BackendId backend)
Definition: smgr.c:146
bool IsBufferCleanupOK(Buffer buffer)
Definition: bufmgr.c:4297
ForkNumber
Definition: relpath.h:40
void MarkLocalBufferDirty(Buffer buffer)
Definition: localbuf.c:286
#define ERRCODE_DATA_CORRUPTED
Definition: pg_basebackup.c:47
static void UnpinBuffer(BufferDesc *buf, bool fixOwner)
Definition: bufmgr.c:1834
void ProcWaitForSignal(uint32 wait_event_info)
Definition: proc.c:1897
void ResourceOwnerEnlargeBuffers(ResourceOwner owner)
Definition: resowner.c:946
int ckpt_bufs_written
Definition: xlog.h:227
PrefetchBufferResult PrefetchSharedBuffer(SMgrRelation smgr_reln, ForkNumber forkNum, BlockNumber blockNum)
Definition: bufmgr.c:500
#define XLogRecPtrIsInvalid(r)
Definition: xlogdefs.h:29
static PrivateRefCountEntry * ReservedRefCountEntry
Definition: bufmgr.c:201
#define WARNING
Definition: elog.h:40
ReadBufferMode
Definition: bufmgr.h:37
int GetStartupBufferPinWaitBufId(void)
Definition: proc.c:662
#define BUF_REFCOUNT_ONE
Definition: buf_internals.h:41
#define BM_LOCKED
Definition: buf_internals.h:58
#define pgstat_count_buffer_hit(rel)
Definition: pgstat.h:1082
void UnlockBuffers(void)
Definition: bufmgr.c:3979
static void TerminateBufferIO(BufferDesc *buf, bool clear_dirty, uint32 set_flag_bits)
Definition: bufmgr.c:4445
#define HASH_BLOBS
Definition: hsearch.h:97
static int rnode_comparator(const void *p1, const void *p2)
Definition: bufmgr.c:4560
#define InvalidBackendId
Definition: backendid.h:23
#define BM_VALID
Definition: buf_internals.h:60
BlockNumber blockNum
#define BufHdrGetBlock(bufHdr)
Definition: bufmgr.c:60
uintptr_t Datum
Definition: postgres.h:411
int BackendId
Definition: backendid.h:21
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:4007
Size keysize
Definition: hsearch.h:75
static Buffer ReadBuffer_common(SMgrRelation reln, char relpersistence, ForkNumber forkNum, BlockNumber blockNum, ReadBufferMode mode, BufferAccessStrategy strategy, bool *hit)
Definition: bufmgr.c:801
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:157
bool StrategyRejectBuffer(BufferAccessStrategy strategy, BufferDesc *buf)
Definition: freelist.c:686
#define BlockNumberIsValid(blockNumber)
Definition: block.h:70
void binaryheap_build(binaryheap *heap)
Definition: binaryheap.c:126
RelFileNode node
Definition: relfilenode.h:74
bool InRecovery
Definition: xlogutils.c:52
#define free(a)
Definition: header.h:65
BlockNumber RelationGetNumberOfBlocksInFork(Relation relation, ForkNumber forkNum)
Definition: bufmgr.c:2935
static BufferDesc * BufferAlloc(SMgrRelation smgr, char relpersistence, ForkNumber forkNum, BlockNumber blockNum, BufferAccessStrategy strategy, bool *foundPtr)
Definition: bufmgr.c:1101
RelFileNode rd_node
Definition: rel.h:56
void ConditionVariableSleep(ConditionVariable *cv, uint32 wait_event_info)
#define BufferDescriptorGetContentLock(bdesc)
uint32 LockBufHdr(BufferDesc *desc)
Definition: bufmgr.c:4587
BlockNumber smgrnblocks(SMgrRelation reln, ForkNumber forknum)
Definition: smgr.c:548
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define Assert(condition)
Definition: c.h:804
#define pgstat_count_buffer_read_time(n)
Definition: pgstat.h:1087
#define CLEAR_BUFFERTAG(a)
Definition: buf_internals.h:98
static void CheckForBufferLeaks(void)
Definition: bufmgr.c:2640
static int buffertag_comparator(const BufferTag *a, const BufferTag *b)
Definition: bufmgr.c:4639
#define RELATION_IS_OTHER_TEMP(relation)
Definition: rel.h:631
#define INIT_BUFFERTAG(a, xx_rnode, xx_forkNum, xx_blockNum)
volatile sig_atomic_t ProcSignalBarrierPending
Definition: globals.c:37
bool HoldingBufferPinThatDelaysRecovery(void)
Definition: bufmgr.c:4215
#define INSTR_TIME_GET_MICROSEC(t)
Definition: instr_time.h:205
#define REFCOUNT_ARRAY_ENTRIES
Definition: bufmgr.c:88
static SMgrRelation RelationGetSmgr(Relation rel)
Definition: rel.h:544
void FlushRelationBuffers(Relation rel)
Definition: bufmgr.c:3512
CheckpointStatsData CheckpointStats
Definition: xlog.c:189
instr_time blk_write_time
Definition: instrument.h:37
Buffer ReadBuffer(Relation reln, BlockNumber blockNum)
Definition: bufmgr.c:694
static void PinBuffer_Locked(BufferDesc *buf)
Definition: bufmgr.c:1789
CkptSortItem * CkptBufferIds
Definition: buf_init.c:24
size_t Size
Definition: c.h:540
void binaryheap_free(binaryheap *heap)
Definition: binaryheap.c:69
#define BUF_USAGECOUNT_MASK
Definition: buf_internals.h:43
BackendId backend
Definition: relfilenode.h:75
#define InvalidBlockNumber
Definition: block.h:33
void pg_qsort(void *base, size_t nel, size_t elsize, int(*cmp)(const void *, const void *))
#define BufferIsLocal(buffer)
Definition: buf.h:37
#define BufferDescriptorGetBuffer(bdesc)
#define MAX_FORKNUM
Definition: relpath.h:55
#define pgstat_count_buffer_write_time(n)
Definition: pgstat.h:1089
void PageSetChecksumInplace(Page page, BlockNumber blkno)
Definition: bufpage.c:1532
Buffer ReleaseAndReadBuffer(Buffer buffer, Relation relation, BlockNumber blockNum)
Definition: bufmgr.c:1628
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1199
void AbortBufferIO(void)
Definition: bufmgr.c:4477
BlockNumber blockNum
Definition: buf_internals.h:95
#define BufferIsValid(bufnum)
Definition: bufmgr.h:123
static uint32 WaitBufHdrUnlocked(BufferDesc *buf)
Definition: bufmgr.c:4615
void * hash_seq_search(HASH_SEQ_STATUS *status)
Definition: dynahash.c:1436
bool smgrprefetch(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum)
Definition: smgr.c:487
RelFileNode rnode
Definition: buf_internals.h:93
bool RelFileNodeSkippingWAL(RelFileNode rnode)
Definition: storage.c:513
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1182
void hash_seq_init(HASH_SEQ_STATUS *status, HTAB *hashp)
Definition: dynahash.c:1426
#define INSTR_TIME_SET_CURRENT(t)
Definition: instr_time.h:156
void FlushOneBuffer(Buffer buffer)
Definition: bufmgr.c:3748
#define BM_MAX_USAGE_COUNT
Definition: buf_internals.h:77
binaryheap * binaryheap_allocate(int capacity, binaryheap_comparator compare, void *arg)
Definition: binaryheap.c:33
#define RelationUsesLocalBuffers(relation)
Definition: rel.h:610
#define BM_IO_ERROR
Definition: buf_internals.h:63
#define PageGetLSN(page)
Definition: bufpage.h:366
#define DatumGetPointer(X)
Definition: postgres.h:593
void smgrextend(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum, char *buffer, bool skipFsync)
Definition: smgr.c:462
BufferTag tag
void DropRelFileNodesAllBuffers(SMgrRelation *smgr_reln, int nnodes)
Definition: bufmgr.c:3178
BlockNumber BufferGetBlockNumber(Buffer buffer)
Definition: bufmgr.c:2748
int64 local_blks_written
Definition: instrument.h:33
#define PageIsNew(page)
Definition: bufpage.h:229
static int ckpt_buforder_comparator(const CkptSortItem *a, const CkptSortItem *b)
Definition: bufmgr.c:4668
void * palloc(Size size)
Definition: mcxt.c:1062
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define UnlockBufHdr(desc, s)
static HTAB * PrivateRefCountHash
Definition: bufmgr.c:198
int64 shared_blks_hit
Definition: instrument.h:26
#define elog(elevel,...)
Definition: elog.h:232
int i
PrefetchBufferResult PrefetchBuffer(Relation reln, ForkNumber forkNum, BlockNumber blockNum)
Definition: bufmgr.c:587
static BufferDesc * PinCountWaitBuf
Definition: bufmgr.c:165
#define relpath(rnode, forknum)
Definition: relpath.h:87
#define errcontext
Definition: elog.h:204
int NBuffers
Definition: globals.c:135
#define BUFFER_LOCK_SHARE
Definition: bufmgr.h:97
static void pg_atomic_unlocked_write_u32(volatile pg_atomic_uint32 *ptr, uint32 val)
Definition: atomics.h:277
static void ReservePrivateRefCountEntry(void)
Definition: bufmgr.c:215
pg_atomic_uint32 state
#define WRITEBACK_MAX_PENDING_FLUSHES
void * arg
Datum binaryheap_remove_first(binaryheap *heap)
Definition: binaryheap.c:174
static uint32 pg_atomic_fetch_or_u32(volatile pg_atomic_uint32 *ptr, uint32 or_)
Definition: atomics.h:372
int DeadlockTimeout
Definition: proc.c:60
int num_scanned
Definition: bufmgr.c:112
#define BM_IO_IN_PROGRESS
Definition: buf_internals.h:62
int VacuumCostPageMiss
Definition: globals.c:142
#define BUF_STATE_GET_USAGECOUNT(state)
Definition: buf_internals.h:50
RelFileNode rnode
Definition: bufmgr.c:127
#define BufferGetLSN(bufHdr)
Definition: bufmgr.c:61
static void pg_atomic_write_u32(volatile pg_atomic_uint32 *ptr, uint32 val)
Definition: atomics.h:258
void BufferGetTag(Buffer buffer, RelFileNode *rnode, ForkNumber *forknum, BlockNumber *blknum)
Definition: bufmgr.c:2769
int64 shared_blks_written
Definition: instrument.h:29
void DropDatabaseBuffers(Oid dbid)
Definition: bufmgr.c:3408
#define relpathbackend(rnode, backend, forknum)
Definition: relpath.h:78
#define PageSetLSN(page, lsn)
Definition: bufpage.h:368
static void shared_buffer_write_error_callback(void *arg)
Definition: bufmgr.c:4522
int Buffer
Definition: buf.h:23
void TestForOldSnapshot_impl(Snapshot snapshot, Relation relation)
Definition: bufmgr.c:4848
ForkNumber forkNum
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1544
struct CkptTsStatus CkptTsStatus
void BufmgrCommit(void)
Definition: bufmgr.c:2734
void IncrBufferRefCount(Buffer buffer)
Definition: bufmgr.c:3806
#define XLogHintBitIsNeeded()
Definition: xlog.h:177
bool track_io_timing
Definition: bufmgr.c:135
int32 * LocalRefCount
Definition: localbuf.c:45
Pointer Page
Definition: bufpage.h:78
void AtEOXact_LocalBuffers(bool isCommit)
Definition: localbuf.c:577
#define CHECKPOINT_IS_SHUTDOWN
Definition: xlog.h:196
#define RelFileNodeEquals(node1, node2)
Definition: relfilenode.h:88
BufferUsage pgBufferUsage
Definition: instrument.c:20
#define BUF_STATE_GET_REFCOUNT(state)
Definition: buf_internals.h:49
void perform_spin_delay(SpinDelayStatus *status)
Definition: s_lock.c:124
void * Block
Definition: bufmgr.h:24
dlist_node node
Definition: smgr.h:72
bool VacuumCostActive
Definition: globals.c:152
static uint32 pg_atomic_read_u32(volatile pg_atomic_uint32 *ptr)
Definition: atomics.h:241
bool zero_damaged_pages
Definition: bufmgr.c:132
void ResourceOwnerForgetBuffer(ResourceOwner owner, Buffer buffer)
Definition: resowner.c:968
#define BM_PIN_COUNT_WAITER
Definition: buf_internals.h:65
static void AtProcExit_Buffers(int code, Datum arg)
Definition: bufmgr.c:2621