Age Owner Branch data TLA Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * bufmgr.c
4 : : * buffer manager interface routines
5 : : *
6 : : * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
7 : : * Portions Copyright (c) 1994, Regents of the University of California
8 : : *
9 : : *
10 : : * IDENTIFICATION
11 : : * src/backend/storage/buffer/bufmgr.c
12 : : *
13 : : *-------------------------------------------------------------------------
14 : : */
15 : : /*
16 : : * Principal entry points:
17 : : *
18 : : * ReadBuffer() -- find or create a buffer holding the requested page,
19 : : * and pin it so that no one can destroy it while this process
20 : : * is using it.
21 : : *
22 : : * StartReadBuffer() -- as above, with separate wait step
23 : : * StartReadBuffers() -- multiple block version
24 : : * WaitReadBuffers() -- second step of above
25 : : *
26 : : * ReleaseBuffer() -- unpin a buffer
27 : : *
28 : : * MarkBufferDirty() -- mark a pinned buffer's contents as "dirty".
29 : : * The disk write is delayed until buffer replacement or checkpoint.
30 : : *
31 : : * See also these files:
32 : : * freelist.c -- chooses victim for buffer replacement
33 : : * buf_table.c -- manages the buffer lookup table
34 : : */
35 : : #include "postgres.h"
36 : :
37 : : #include <sys/file.h>
38 : : #include <unistd.h>
39 : :
40 : : #include "access/tableam.h"
41 : : #include "access/xloginsert.h"
42 : : #include "access/xlogutils.h"
43 : : #ifdef USE_ASSERT_CHECKING
44 : : #include "catalog/pg_tablespace_d.h"
45 : : #endif
46 : : #include "catalog/storage.h"
47 : : #include "catalog/storage_xlog.h"
48 : : #include "common/hashfn.h"
49 : : #include "executor/instrument.h"
50 : : #include "lib/binaryheap.h"
51 : : #include "miscadmin.h"
52 : : #include "pg_trace.h"
53 : : #include "pgstat.h"
54 : : #include "postmaster/bgwriter.h"
55 : : #include "storage/aio.h"
56 : : #include "storage/buf_internals.h"
57 : : #include "storage/bufmgr.h"
58 : : #include "storage/fd.h"
59 : : #include "storage/ipc.h"
60 : : #include "storage/lmgr.h"
61 : : #include "storage/proc.h"
62 : : #include "storage/proclist.h"
63 : : #include "storage/procsignal.h"
64 : : #include "storage/read_stream.h"
65 : : #include "storage/smgr.h"
66 : : #include "storage/standby.h"
67 : : #include "utils/memdebug.h"
68 : : #include "utils/ps_status.h"
69 : : #include "utils/rel.h"
70 : : #include "utils/resowner.h"
71 : : #include "utils/timestamp.h"
72 : : #include "utils/wait_event.h"
73 : :
74 : :
75 : : /* Note: these two macros only work on shared buffers, not local ones! */
76 : : #define BufHdrGetBlock(bufHdr) ((Block) (BufferBlocks + ((Size) (bufHdr)->buf_id) * BLCKSZ))
77 : : #define BufferGetLSN(bufHdr) (PageGetLSN(BufHdrGetBlock(bufHdr)))
78 : :
79 : : /* Note: this macro only works on local buffers, not shared ones! */
80 : : #define LocalBufHdrGetBlock(bufHdr) \
81 : : LocalBufferBlockPointers[-((bufHdr)->buf_id + 2)]
82 : :
83 : : /* Bits in SyncOneBuffer's return value */
84 : : #define BUF_WRITTEN 0x01
85 : : #define BUF_REUSABLE 0x02
86 : :
87 : : #define RELS_BSEARCH_THRESHOLD 20
88 : :
89 : : /*
90 : : * This is the size (in the number of blocks) above which we scan the
91 : : * entire buffer pool to remove the buffers for all the pages of relation
92 : : * being dropped. For the relations with size below this threshold, we find
93 : : * the buffers by doing lookups in BufMapping table.
94 : : */
95 : : #define BUF_DROP_FULL_SCAN_THRESHOLD (uint64) (NBuffers / 32)
96 : :
97 : : /*
98 : : * This is separated out from PrivateRefCountEntry to allow for copying all
99 : : * the data members via struct assignment.
100 : : */
101 : : typedef struct PrivateRefCountData
102 : : {
103 : : /*
104 : : * How many times has the buffer been pinned by this backend.
105 : : */
106 : : int32 refcount;
107 : :
108 : : /*
109 : : * Is the buffer locked by this backend? BUFFER_LOCK_UNLOCK indicates that
110 : : * the buffer is not locked.
111 : : */
112 : : BufferLockMode lockmode;
113 : : } PrivateRefCountData;
114 : :
115 : : typedef struct PrivateRefCountEntry
116 : : {
117 : : /*
118 : : * Note that this needs to be same as the entry's corresponding
119 : : * PrivateRefCountArrayKeys[i], if the entry is stored in the array. We
120 : : * store it in both places as this is used for the hashtable key and
121 : : * because it is more convenient (passing around a PrivateRefCountEntry
122 : : * suffices to identify the buffer) and faster (checking the keys array is
123 : : * faster when checking many entries, checking the entry is faster if just
124 : : * checking a single entry).
125 : : */
126 : : Buffer buffer;
127 : :
128 : : char status;
129 : :
130 : : PrivateRefCountData data;
131 : : } PrivateRefCountEntry;
132 : :
133 : : #define SH_PREFIX refcount
134 : : #define SH_ELEMENT_TYPE PrivateRefCountEntry
135 : : #define SH_KEY_TYPE Buffer
136 : : #define SH_KEY buffer
137 : : #define SH_HASH_KEY(tb, key) murmurhash32((uint32) (key))
138 : : #define SH_EQUAL(tb, a, b) ((a) == (b))
139 : : #define SH_SCOPE static inline
140 : : #define SH_DECLARE
141 : : #define SH_DEFINE
142 : : #include "lib/simplehash.h"
143 : :
144 : : /* 64 bytes, about the size of a cache line on common systems */
145 : : #define REFCOUNT_ARRAY_ENTRIES 8
146 : :
147 : : /*
148 : : * Status of buffers to checkpoint for a particular tablespace, used
149 : : * internally in BufferSync.
150 : : */
151 : : typedef struct CkptTsStatus
152 : : {
153 : : /* oid of the tablespace */
154 : : Oid tsId;
155 : :
156 : : /*
157 : : * Checkpoint progress for this tablespace. To make progress comparable
158 : : * between tablespaces the progress is, for each tablespace, measured as a
159 : : * number between 0 and the total number of to-be-checkpointed pages. Each
160 : : * page checkpointed in this tablespace increments this space's progress
161 : : * by progress_slice.
162 : : */
163 : : float8 progress;
164 : : float8 progress_slice;
165 : :
166 : : /* number of to-be checkpointed pages in this tablespace */
167 : : int num_to_scan;
168 : : /* already processed pages in this tablespace */
169 : : int num_scanned;
170 : :
171 : : /* current offset in CkptBufferIds for this tablespace */
172 : : int index;
173 : : } CkptTsStatus;
174 : :
175 : : /*
176 : : * Type for array used to sort SMgrRelations
177 : : *
178 : : * FlushRelationsAllBuffers shares the same comparator function with
179 : : * DropRelationsAllBuffers. Pointer to this struct and RelFileLocator must be
180 : : * compatible.
181 : : */
182 : : typedef struct SMgrSortArray
183 : : {
184 : : RelFileLocator rlocator; /* This must be the first member */
185 : : SMgrRelation srel;
186 : : } SMgrSortArray;
187 : :
188 : : /* GUC variables */
189 : : bool zero_damaged_pages = false;
190 : : int bgwriter_lru_maxpages = 100;
191 : : double bgwriter_lru_multiplier = 2.0;
192 : : bool track_io_timing = false;
193 : :
194 : : /*
195 : : * How many buffers PrefetchBuffer callers should try to stay ahead of their
196 : : * ReadBuffer calls by. Zero means "never prefetch". This value is only used
197 : : * for buffers not belonging to tablespaces that have their
198 : : * effective_io_concurrency parameter set.
199 : : */
200 : : int effective_io_concurrency = DEFAULT_EFFECTIVE_IO_CONCURRENCY;
201 : :
202 : : /*
203 : : * Like effective_io_concurrency, but used by maintenance code paths that might
204 : : * benefit from a higher setting because they work on behalf of many sessions.
205 : : * Overridden by the tablespace setting of the same name.
206 : : */
207 : : int maintenance_io_concurrency = DEFAULT_MAINTENANCE_IO_CONCURRENCY;
208 : :
209 : : /*
210 : : * Limit on how many blocks should be handled in single I/O operations.
211 : : * StartReadBuffers() callers should respect it, as should other operations
212 : : * that call smgr APIs directly. It is computed as the minimum of underlying
213 : : * GUCs io_combine_limit_guc and io_max_combine_limit.
214 : : */
215 : : int io_combine_limit = DEFAULT_IO_COMBINE_LIMIT;
216 : : int io_combine_limit_guc = DEFAULT_IO_COMBINE_LIMIT;
217 : : int io_max_combine_limit = DEFAULT_IO_COMBINE_LIMIT;
218 : :
219 : : /*
220 : : * GUC variables about triggering kernel writeback for buffers written; OS
221 : : * dependent defaults are set via the GUC mechanism.
222 : : */
223 : : int checkpoint_flush_after = DEFAULT_CHECKPOINT_FLUSH_AFTER;
224 : : int bgwriter_flush_after = DEFAULT_BGWRITER_FLUSH_AFTER;
225 : : int backend_flush_after = DEFAULT_BACKEND_FLUSH_AFTER;
226 : :
227 : : /* local state for LockBufferForCleanup */
228 : : static BufferDesc *PinCountWaitBuf = NULL;
229 : :
230 : : /*
231 : : * Backend-Private refcount management:
232 : : *
233 : : * Each buffer also has a private refcount that keeps track of the number of
234 : : * times the buffer is pinned in the current process. This is so that the
235 : : * shared refcount needs to be modified only once if a buffer is pinned more
236 : : * than once by an individual backend. It's also used to check that no
237 : : * buffers are still pinned at the end of transactions and when exiting. We
238 : : * also use this mechanism to track whether this backend has a buffer locked,
239 : : * and, if so, in what mode.
240 : : *
241 : : *
242 : : * To avoid - as we used to - requiring an array with NBuffers entries to keep
243 : : * track of local buffers, we use a small sequentially searched array
244 : : * (PrivateRefCountArrayKeys, with the corresponding data stored in
245 : : * PrivateRefCountArray) and an overflow hash table (PrivateRefCountHash) to
246 : : * keep track of backend local pins.
247 : : *
248 : : * Until no more than REFCOUNT_ARRAY_ENTRIES buffers are pinned at once, all
249 : : * refcounts are kept track of in the array; after that, new array entries
250 : : * displace old ones into the hash table. That way a frequently used entry
251 : : * can't get "stuck" in the hashtable while infrequent ones clog the array.
252 : : *
253 : : * Note that in most scenarios the number of pinned buffers will not exceed
254 : : * REFCOUNT_ARRAY_ENTRIES.
255 : : *
256 : : *
257 : : * To enter a buffer into the refcount tracking mechanism first reserve a free
258 : : * entry using ReservePrivateRefCountEntry() and then later, if necessary,
259 : : * fill it with NewPrivateRefCountEntry(). That split lets us avoid doing
260 : : * memory allocations in NewPrivateRefCountEntry() which can be important
261 : : * because in some scenarios it's called with a spinlock held...
262 : : */
263 : : static Buffer PrivateRefCountArrayKeys[REFCOUNT_ARRAY_ENTRIES];
264 : : static struct PrivateRefCountEntry PrivateRefCountArray[REFCOUNT_ARRAY_ENTRIES];
265 : : static refcount_hash *PrivateRefCountHash = NULL;
266 : : static int32 PrivateRefCountOverflowed = 0;
267 : : static uint32 PrivateRefCountClock = 0;
268 : : static int ReservedRefCountSlot = -1;
269 : : static int PrivateRefCountEntryLast = -1;
270 : :
271 : : static uint32 MaxProportionalPins;
272 : :
273 : : static WritebackContext BackendWritebackContext;
274 : :
275 : : static void ReservePrivateRefCountEntry(void);
276 : : static PrivateRefCountEntry *NewPrivateRefCountEntry(Buffer buffer);
277 : : static PrivateRefCountEntry *GetPrivateRefCountEntry(Buffer buffer, bool do_move);
278 : : static inline int32 GetPrivateRefCount(Buffer buffer);
279 : : static void ForgetPrivateRefCountEntry(PrivateRefCountEntry *ref);
280 : :
281 : : /* ResourceOwner callbacks to hold in-progress I/Os and buffer pins */
282 : : static void ResOwnerReleaseBufferIO(Datum res);
283 : : static char *ResOwnerPrintBufferIO(Datum res);
284 : : static void ResOwnerReleaseBuffer(Datum res);
285 : : static char *ResOwnerPrintBuffer(Datum res);
286 : :
287 : : const ResourceOwnerDesc buffer_io_resowner_desc =
288 : : {
289 : : .name = "buffer io",
290 : : .release_phase = RESOURCE_RELEASE_BEFORE_LOCKS,
291 : : .release_priority = RELEASE_PRIO_BUFFER_IOS,
292 : : .ReleaseResource = ResOwnerReleaseBufferIO,
293 : : .DebugPrint = ResOwnerPrintBufferIO
294 : : };
295 : :
296 : : const ResourceOwnerDesc buffer_resowner_desc =
297 : : {
298 : : .name = "buffer",
299 : : .release_phase = RESOURCE_RELEASE_BEFORE_LOCKS,
300 : : .release_priority = RELEASE_PRIO_BUFFER_PINS,
301 : : .ReleaseResource = ResOwnerReleaseBuffer,
302 : : .DebugPrint = ResOwnerPrintBuffer
303 : : };
304 : :
305 : : /*
306 : : * Ensure that the PrivateRefCountArray has sufficient space to store one more
307 : : * entry. This has to be called before using NewPrivateRefCountEntry() to fill
308 : : * a new entry - but it's perfectly fine to not use a reserved entry.
309 : : */
310 : : static void
4284 andres@anarazel.de 311 :CBC 87276155 : ReservePrivateRefCountEntry(void)
312 : : {
313 : : /* Already reserved (or freed), nothing to do */
302 314 [ + + ]: 87276155 : if (ReservedRefCountSlot != -1)
4284 315 : 81032425 : return;
316 : :
317 : : /*
318 : : * First search for a free entry the array, that'll be sufficient in the
319 : : * majority of cases.
320 : : */
321 : : {
322 : : int i;
323 : :
324 [ + + ]: 56193570 : for (i = 0; i < REFCOUNT_ARRAY_ENTRIES; i++)
325 : : {
302 326 [ + + ]: 49949840 : if (PrivateRefCountArrayKeys[i] == InvalidBuffer)
327 : : {
328 : 37193202 : ReservedRefCountSlot = i;
329 : :
330 : : /*
331 : : * We could return immediately, but iterating till the end of
332 : : * the array allows compiler-autovectorization.
333 : : */
334 : : }
335 : : }
336 : :
337 [ + + ]: 6243730 : if (ReservedRefCountSlot != -1)
338 : 6064547 : return;
339 : : }
340 : :
341 : : /*
342 : : * No luck. All array entries are full. Move one array entry into the hash
343 : : * table.
344 : : */
345 : : {
346 : : /*
347 : : * Move entry from the current clock position in the array into the
348 : : * hashtable. Use that slot.
349 : : */
350 : : int victim_slot;
351 : : PrivateRefCountEntry *victim_entry;
352 : : PrivateRefCountEntry *hashent;
353 : : bool found;
354 : :
355 : : /* select victim slot */
356 : 179183 : victim_slot = PrivateRefCountClock++ % REFCOUNT_ARRAY_ENTRIES;
357 : 179183 : victim_entry = &PrivateRefCountArray[victim_slot];
358 : 179183 : ReservedRefCountSlot = victim_slot;
359 : :
360 : : /* Better be used, otherwise we shouldn't get here. */
361 [ - + ]: 179183 : Assert(PrivateRefCountArrayKeys[victim_slot] != InvalidBuffer);
362 [ - + ]: 179183 : Assert(PrivateRefCountArray[victim_slot].buffer != InvalidBuffer);
363 [ - + ]: 179183 : Assert(PrivateRefCountArrayKeys[victim_slot] == PrivateRefCountArray[victim_slot].buffer);
364 : :
365 : : /* enter victim array entry into hashtable */
214 pg@bowt.ie 366 : 179183 : hashent = refcount_insert(PrivateRefCountHash,
367 : : PrivateRefCountArrayKeys[victim_slot],
368 : : &found);
4284 andres@anarazel.de 369 [ - + ]: 179183 : Assert(!found);
370 : : /* move data from the entry in the array to the hash entry */
302 371 : 179183 : hashent->data = victim_entry->data;
372 : :
373 : : /* clear the now free array slot */
374 : 179183 : PrivateRefCountArrayKeys[victim_slot] = InvalidBuffer;
375 : 179183 : victim_entry->buffer = InvalidBuffer;
376 : :
377 : : /* clear the whole data member, just for future proofing */
378 : 179183 : memset(&victim_entry->data, 0, sizeof(victim_entry->data));
379 : 179183 : victim_entry->data.refcount = 0;
270 380 : 179183 : victim_entry->data.lockmode = BUFFER_LOCK_UNLOCK;
381 : :
4284 382 : 179183 : PrivateRefCountOverflowed++;
383 : : }
384 : : }
385 : :
386 : : /*
387 : : * Fill a previously reserved refcount entry.
388 : : */
389 : : static PrivateRefCountEntry *
390 : 75590348 : NewPrivateRefCountEntry(Buffer buffer)
391 : : {
392 : : PrivateRefCountEntry *res;
393 : :
394 : : /* only allowed to be called when a reservation has been made */
302 395 [ - + ]: 75590348 : Assert(ReservedRefCountSlot != -1);
396 : :
397 : : /* use up the reserved entry */
398 : 75590348 : res = &PrivateRefCountArray[ReservedRefCountSlot];
399 : :
400 : : /* and fill it */
401 : 75590348 : PrivateRefCountArrayKeys[ReservedRefCountSlot] = buffer;
4284 402 : 75590348 : res->buffer = buffer;
302 403 : 75590348 : res->data.refcount = 0;
270 404 : 75590348 : res->data.lockmode = BUFFER_LOCK_UNLOCK;
405 : :
406 : : /* update cache for the next lookup */
302 407 : 75590348 : PrivateRefCountEntryLast = ReservedRefCountSlot;
408 : :
409 : 75590348 : ReservedRefCountSlot = -1;
410 : :
4284 411 : 75590348 : return res;
412 : : }
413 : :
414 : : /*
415 : : * Slow-path for GetPrivateRefCountEntry(). This is big enough to not be worth
416 : : * inlining. This particularly seems to be true if the compiler is capable of
417 : : * auto-vectorizing the code, as that imposes additional stack-alignment
418 : : * requirements etc.
419 : : */
420 : : static pg_noinline PrivateRefCountEntry *
302 421 : 125459126 : GetPrivateRefCountEntrySlow(Buffer buffer, bool do_move)
422 : : {
423 : : PrivateRefCountEntry *res;
424 : 125459126 : int match = -1;
425 : : int i;
426 : :
427 : : /*
428 : : * First search for references in the array, that'll be sufficient in the
429 : : * majority of cases.
430 : : */
4426 431 [ + + ]: 1129132134 : for (i = 0; i < REFCOUNT_ARRAY_ENTRIES; i++)
432 : : {
302 433 [ + + ]: 1003673008 : if (PrivateRefCountArrayKeys[i] == buffer)
434 : : {
435 : 50715400 : match = i;
436 : : /* see ReservePrivateRefCountEntry() for why we don't return */
437 : : }
438 : : }
439 : :
440 [ + + ]: 125459126 : if (likely(match != -1))
441 : : {
442 : : /* update cache for the next lookup */
443 : 50715400 : PrivateRefCountEntryLast = match;
444 : :
445 : 50715400 : return &PrivateRefCountArray[match];
446 : : }
447 : :
448 : : /*
449 : : * By here we know that the buffer, if already pinned, isn't residing in
450 : : * the array.
451 : : *
452 : : * Only look up the buffer in the hashtable if we've previously overflowed
453 : : * into it.
454 : : */
4284 455 [ + + ]: 74743726 : if (PrivateRefCountOverflowed == 0)
456 : 73053072 : return NULL;
457 : :
214 pg@bowt.ie 458 : 1690654 : res = refcount_lookup(PrivateRefCountHash, buffer);
459 : :
4284 andres@anarazel.de 460 [ + + ]: 1690654 : if (res == NULL)
461 : 382749 : return NULL;
462 [ + + ]: 1307905 : else if (!do_move)
463 : : {
464 : : /* caller doesn't want us to move the hash entry into the array */
465 : 1214795 : return res;
466 : : }
467 : : else
468 : : {
469 : : /* move buffer from hashtable into the free array slot */
470 : : PrivateRefCountEntry *free;
471 : : PrivateRefCountData data;
472 : :
473 : : /* Save data and delete from hashtable while res is still valid */
214 pg@bowt.ie 474 : 93110 : data = res->data;
475 : 93110 : refcount_delete_item(PrivateRefCountHash, res);
476 [ - + ]: 93110 : Assert(PrivateRefCountOverflowed > 0);
477 : 93110 : PrivateRefCountOverflowed--;
478 : :
479 : : /* Ensure there's a free array slot */
4284 andres@anarazel.de 480 : 93110 : ReservePrivateRefCountEntry();
481 : :
482 : : /* Use up the reserved slot */
302 483 [ - + ]: 93110 : Assert(ReservedRefCountSlot != -1);
484 : 93110 : free = &PrivateRefCountArray[ReservedRefCountSlot];
485 [ - + ]: 93110 : Assert(PrivateRefCountArrayKeys[ReservedRefCountSlot] == free->buffer);
4284 486 [ - + ]: 93110 : Assert(free->buffer == InvalidBuffer);
487 : :
488 : : /* and fill it */
489 : 93110 : free->buffer = buffer;
214 pg@bowt.ie 490 : 93110 : free->data = data;
302 andres@anarazel.de 491 : 93110 : PrivateRefCountArrayKeys[ReservedRefCountSlot] = buffer;
492 : : /* update cache for the next lookup */
215 493 : 93110 : PrivateRefCountEntryLast = ReservedRefCountSlot;
494 : :
302 495 : 93110 : ReservedRefCountSlot = -1;
496 : :
4284 497 : 93110 : return free;
498 : : }
499 : : }
500 : :
501 : : /*
502 : : * Return the PrivateRefCount entry for the passed buffer.
503 : : *
504 : : * Returns NULL if a buffer doesn't have a refcount entry. Otherwise, if
505 : : * do_move is true, and the entry resides in the hashtable the entry is
506 : : * optimized for frequent access by moving it to the array.
507 : : */
508 : : static inline PrivateRefCountEntry *
302 509 : 1294809392 : GetPrivateRefCountEntry(Buffer buffer, bool do_move)
510 : : {
511 [ - + ]: 1294809392 : Assert(BufferIsValid(buffer));
512 [ - + ]: 1294809392 : Assert(!BufferIsLocal(buffer));
513 : :
514 : : /*
515 : : * It's very common to look up the same buffer repeatedly. To make that
516 : : * fast, we have a one-entry cache.
517 : : *
518 : : * In contrast to the loop in GetPrivateRefCountEntrySlow(), here it
519 : : * faster to check PrivateRefCountArray[].buffer, as in the case of a hit
520 : : * fewer addresses are computed and fewer cachelines are accessed. Whereas
521 : : * in GetPrivateRefCountEntrySlow()'s case, checking
522 : : * PrivateRefCountArrayKeys saves a lot of memory accesses.
523 : : */
524 [ + + ]: 1294809392 : if (likely(PrivateRefCountEntryLast != -1) &&
525 [ + + ]: 1294793461 : likely(PrivateRefCountArray[PrivateRefCountEntryLast].buffer == buffer))
526 : : {
527 : 1169350266 : return &PrivateRefCountArray[PrivateRefCountEntryLast];
528 : : }
529 : :
530 : : /*
531 : : * The code for the cached lookup is small enough to be worth inlining
532 : : * into the caller. In the miss case however, that empirically doesn't
533 : : * seem worth it.
534 : : */
535 : 125459126 : return GetPrivateRefCountEntrySlow(buffer, do_move);
536 : : }
537 : :
538 : : /*
539 : : * Returns how many times the passed buffer is pinned by this backend.
540 : : *
541 : : * Only works for shared memory buffers!
542 : : */
543 : : static inline int32
4426 544 : 705558529 : GetPrivateRefCount(Buffer buffer)
545 : : {
546 : : PrivateRefCountEntry *ref;
547 : :
548 [ - + ]: 705558529 : Assert(BufferIsValid(buffer));
549 [ - + ]: 705558529 : Assert(!BufferIsLocal(buffer));
550 : :
551 : : /*
552 : : * Not moving the entry - that's ok for the current users, but we might
553 : : * want to change this one day.
554 : : */
4284 555 : 705558529 : ref = GetPrivateRefCountEntry(buffer, false);
556 : :
4426 557 [ + + ]: 705558529 : if (ref == NULL)
558 : 34 : return 0;
302 559 : 705558495 : return ref->data.refcount;
560 : : }
561 : :
562 : : /*
563 : : * Release resources used to track the reference count of a buffer which we no
564 : : * longer have pinned and don't want to pin again immediately.
565 : : */
566 : : static void
4426 567 : 75590348 : ForgetPrivateRefCountEntry(PrivateRefCountEntry *ref)
568 : : {
302 569 [ - + ]: 75590348 : Assert(ref->data.refcount == 0);
270 570 [ - + ]: 75590348 : Assert(ref->data.lockmode == BUFFER_LOCK_UNLOCK);
571 : :
4426 572 [ + - + + ]: 75590348 : if (ref >= &PrivateRefCountArray[0] &&
573 : : ref < &PrivateRefCountArray[REFCOUNT_ARRAY_ENTRIES])
574 : : {
575 : 75504275 : ref->buffer = InvalidBuffer;
302 576 : 75504275 : PrivateRefCountArrayKeys[ref - PrivateRefCountArray] = InvalidBuffer;
577 : :
578 : :
579 : : /*
580 : : * Mark the just used entry as reserved - in many scenarios that
581 : : * allows us to avoid ever having to search the array/hash for free
582 : : * entries.
583 : : */
584 : 75504275 : ReservedRefCountSlot = ref - PrivateRefCountArray;
585 : : }
586 : : else
587 : : {
214 pg@bowt.ie 588 : 86073 : refcount_delete_item(PrivateRefCountHash, ref);
4426 andres@anarazel.de 589 [ - + ]: 86073 : Assert(PrivateRefCountOverflowed > 0);
590 : 86073 : PrivateRefCountOverflowed--;
591 : : }
592 : 75590348 : }
593 : :
594 : : /*
595 : : * BufferIsPinned
596 : : * True iff the buffer is pinned (also checks for valid buffer number).
597 : : *
598 : : * NOTE: what we check here is that *this* backend holds a pin on
599 : : * the buffer. We do not care whether some other backend does.
600 : : */
601 : : #define BufferIsPinned(bufnum) \
602 : : ( \
603 : : !BufferIsValid(bufnum) ? \
604 : : false \
605 : : : \
606 : : BufferIsLocal(bufnum) ? \
607 : : (LocalRefCount[-(bufnum) - 1] > 0) \
608 : : : \
609 : : (GetPrivateRefCount(bufnum) > 0) \
610 : : )
611 : :
612 : :
613 : : static Buffer ReadBuffer_common(Relation rel,
614 : : SMgrRelation smgr, char smgr_persistence,
615 : : ForkNumber forkNum, BlockNumber blockNum,
616 : : ReadBufferMode mode, BufferAccessStrategy strategy);
617 : : static BlockNumber ExtendBufferedRelCommon(BufferManagerRelation bmr,
618 : : ForkNumber fork,
619 : : BufferAccessStrategy strategy,
620 : : uint32 flags,
621 : : uint32 extend_by,
622 : : BlockNumber extend_upto,
623 : : Buffer *buffers,
624 : : uint32 *extended_by);
625 : : static BlockNumber ExtendBufferedRelShared(BufferManagerRelation bmr,
626 : : ForkNumber fork,
627 : : BufferAccessStrategy strategy,
628 : : uint32 flags,
629 : : uint32 extend_by,
630 : : BlockNumber extend_upto,
631 : : Buffer *buffers,
632 : : uint32 *extended_by);
633 : : static bool PinBuffer(BufferDesc *buf, BufferAccessStrategy strategy,
634 : : bool skip_if_not_valid);
635 : : static void PinBuffer_Locked(BufferDesc *buf);
636 : : static void UnpinBuffer(BufferDesc *buf);
637 : : static void UnpinBufferNoOwner(BufferDesc *buf);
638 : : static void BufferSync(int flags);
639 : : static int SyncOneBuffer(int buf_id, bool skip_recently_used,
640 : : WritebackContext *wb_context);
641 : : static void WaitIO(BufferDesc *buf);
642 : : static void AbortBufferIO(Buffer buffer);
643 : : static void shared_buffer_write_error_callback(void *arg);
644 : : static void local_buffer_write_error_callback(void *arg);
645 : : static inline BufferDesc *BufferAlloc(SMgrRelation smgr,
646 : : char relpersistence,
647 : : ForkNumber forkNum,
648 : : BlockNumber blockNum,
649 : : BufferAccessStrategy strategy,
650 : : bool *foundPtr, IOContext io_context);
651 : : static bool AsyncReadBuffers(ReadBuffersOperation *operation, int *nblocks_progress);
652 : : static void CheckReadBuffersOperation(ReadBuffersOperation *operation, bool is_complete);
653 : :
654 : : static pg_always_inline void TrackBufferHit(IOObject io_object,
655 : : IOContext io_context,
656 : : Relation rel, char persistence, SMgrRelation smgr,
657 : : ForkNumber forknum, BlockNumber blocknum);
658 : : static Buffer GetVictimBuffer(BufferAccessStrategy strategy, IOContext io_context);
659 : : static void FlushUnlockedBuffer(BufferDesc *buf, SMgrRelation reln,
660 : : IOObject io_object, IOContext io_context);
661 : : static void FlushBuffer(BufferDesc *buf, SMgrRelation reln,
662 : : IOObject io_object, IOContext io_context);
663 : : static void FindAndDropRelationBuffers(RelFileLocator rlocator,
664 : : ForkNumber forkNum,
665 : : BlockNumber nForkBlock,
666 : : BlockNumber firstDelBlock);
667 : : static void RelationCopyStorageUsingBuffer(RelFileLocator srclocator,
668 : : RelFileLocator dstlocator,
669 : : ForkNumber forkNum, bool permanent);
670 : : static void AtProcExit_Buffers(int code, Datum arg);
671 : : static void CheckForBufferLeaks(void);
672 : : #ifdef USE_ASSERT_CHECKING
673 : : static void AssertNotCatalogBufferLock(Buffer buffer, BufferLockMode mode);
674 : : #endif
675 : : static int rlocator_comparator(const void *p1, const void *p2);
676 : : static inline int buffertag_comparator(const BufferTag *ba, const BufferTag *bb);
677 : : static inline int ckpt_buforder_comparator(const CkptSortItem *a, const CkptSortItem *b);
678 : : static int ts_ckpt_progress_comparator(Datum a, Datum b, void *arg);
679 : :
680 : : static void BufferLockAcquire(Buffer buffer, BufferDesc *buf_hdr, BufferLockMode mode);
681 : : static void BufferLockUnlock(Buffer buffer, BufferDesc *buf_hdr);
682 : : static bool BufferLockConditional(Buffer buffer, BufferDesc *buf_hdr, BufferLockMode mode);
683 : : static bool BufferLockHeldByMeInMode(BufferDesc *buf_hdr, BufferLockMode mode);
684 : : static bool BufferLockHeldByMe(BufferDesc *buf_hdr);
685 : : static inline void BufferLockDisown(Buffer buffer, BufferDesc *buf_hdr);
686 : : static inline int BufferLockDisownInternal(Buffer buffer, BufferDesc *buf_hdr);
687 : : static inline bool BufferLockAttempt(BufferDesc *buf_hdr, BufferLockMode mode);
688 : : static void BufferLockQueueSelf(BufferDesc *buf_hdr, BufferLockMode mode);
689 : : static void BufferLockDequeueSelf(BufferDesc *buf_hdr);
690 : : static void BufferLockWakeup(BufferDesc *buf_hdr, bool wake_exclusive);
691 : : static void BufferLockProcessRelease(BufferDesc *buf_hdr, BufferLockMode mode, uint64 lockstate);
692 : : static inline uint64 BufferLockReleaseSub(BufferLockMode mode);
693 : :
694 : :
695 : : /*
696 : : * Implementation of PrefetchBuffer() for shared buffers.
697 : : */
698 : : PrefetchBufferResult
2378 tmunro@postgresql.or 699 : 40502 : PrefetchSharedBuffer(SMgrRelation smgr_reln,
700 : : ForkNumber forkNum,
701 : : BlockNumber blockNum)
702 : : {
703 : 40502 : PrefetchBufferResult result = {InvalidBuffer, false};
704 : : BufferTag newTag; /* identity of requested block */
705 : : uint32 newHash; /* hash value for newTag */
706 : : LWLock *newPartitionLock; /* buffer partition lock for it */
707 : : int buf_id;
708 : :
709 [ - + ]: 40502 : Assert(BlockNumberIsValid(blockNum));
710 : :
711 : : /* create a tag so we can lookup the buffer */
1538 rhaas@postgresql.org 712 : 40502 : InitBufferTag(&newTag, &smgr_reln->smgr_rlocator.locator,
713 : : forkNum, blockNum);
714 : :
715 : : /* determine its hash code and partition lock ID */
2378 tmunro@postgresql.or 716 : 40502 : newHash = BufTableHashCode(&newTag);
717 : 40502 : newPartitionLock = BufMappingPartitionLock(newHash);
718 : :
719 : : /* see if the block is in the buffer pool already */
720 : 40502 : LWLockAcquire(newPartitionLock, LW_SHARED);
721 : 40502 : buf_id = BufTableLookup(&newTag, newHash);
722 : 40502 : LWLockRelease(newPartitionLock);
723 : :
724 : : /* If not in buffers, initiate prefetch */
725 [ + + ]: 40502 : if (buf_id < 0)
726 : : {
727 : : #ifdef USE_PREFETCH
728 : : /*
729 : : * Try to initiate an asynchronous read. This returns false in
730 : : * recovery if the relation file doesn't exist.
731 : : */
1283 732 [ + + + - ]: 19352 : if ((io_direct_flags & IO_DIRECT_DATA) == 0 &&
1031 733 : 9549 : smgrprefetch(smgr_reln, forkNum, blockNum, 1))
734 : : {
2378 735 : 9549 : result.initiated_io = true;
736 : : }
737 : : #endif /* USE_PREFETCH */
738 : : }
739 : : else
740 : : {
741 : : /*
742 : : * Report the buffer it was in at that time. The caller may be able
743 : : * to avoid a buffer table lookup, but it's not pinned and it must be
744 : : * rechecked!
745 : : */
746 : 30699 : result.recent_buffer = buf_id + 1;
747 : : }
748 : :
749 : : /*
750 : : * If the block *is* in buffers, we do nothing. This is not really ideal:
751 : : * the block might be just about to be evicted, which would be stupid
752 : : * since we know we are going to need it soon. But the only easy answer
753 : : * is to bump the usage_count, which does not seem like a great solution:
754 : : * when the caller does ultimately touch the block, usage_count would get
755 : : * bumped again, resulting in too much favoritism for blocks that are
756 : : * involved in a prefetch sequence. A real fix would involve some
757 : : * additional per-buffer state, and it's not clear that there's enough of
758 : : * a problem to justify that.
759 : : */
760 : :
761 : 40502 : return result;
762 : : }
763 : :
764 : : /*
765 : : * PrefetchBuffer -- initiate asynchronous read of a block of a relation
766 : : *
767 : : * This is named by analogy to ReadBuffer but doesn't actually allocate a
768 : : * buffer. Instead it tries to ensure that a future ReadBuffer for the given
769 : : * block will not be delayed by the I/O. Prefetching is optional.
770 : : *
771 : : * There are three possible outcomes:
772 : : *
773 : : * 1. If the block is already cached, the result includes a valid buffer that
774 : : * could be used by the caller to avoid the need for a later buffer lookup, but
775 : : * it's not pinned, so the caller must recheck it.
776 : : *
777 : : * 2. If the kernel has been asked to initiate I/O, the initiated_io member is
778 : : * true. Currently there is no way to know if the data was already cached by
779 : : * the kernel and therefore didn't really initiate I/O, and no way to know when
780 : : * the I/O completes other than using synchronous ReadBuffer().
781 : : *
782 : : * 3. Otherwise, the buffer wasn't already cached by PostgreSQL, and
783 : : * USE_PREFETCH is not defined (this build doesn't support prefetching due to
784 : : * lack of a kernel facility), direct I/O is enabled, or the underlying
785 : : * relation file wasn't found and we are in recovery. (If the relation file
786 : : * wasn't found and we are not in recovery, an error is raised).
787 : : */
788 : : PrefetchBufferResult
6482 tgl@sss.pgh.pa.us 789 : 29084 : PrefetchBuffer(Relation reln, ForkNumber forkNum, BlockNumber blockNum)
790 : : {
791 [ - + ]: 29084 : Assert(RelationIsValid(reln));
792 [ - + ]: 29084 : Assert(BlockNumberIsValid(blockNum));
793 : :
5782 rhaas@postgresql.org 794 [ + + ]: 29084 : if (RelationUsesLocalBuffers(reln))
795 : : {
796 : : /* see comments in ReadBuffer_common */
6404 tgl@sss.pgh.pa.us 797 [ + - - + ]: 1357 : if (RELATION_IS_OTHER_TEMP(reln))
6404 tgl@sss.pgh.pa.us 798 [ # # ]:UBC 0 : ereport(ERROR,
799 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
800 : : errmsg("cannot access temporary tables of other sessions")));
801 : :
802 : : /* pass it off to localbuf.c */
1918 tgl@sss.pgh.pa.us 803 :CBC 1357 : return PrefetchLocalBuffer(RelationGetSmgr(reln), forkNum, blockNum);
804 : : }
805 : : else
806 : : {
807 : : /* pass it to the shared buffer version */
808 : 27727 : return PrefetchSharedBuffer(RelationGetSmgr(reln), forkNum, blockNum);
809 : : }
810 : : }
811 : :
812 : : /*
813 : : * ReadRecentBuffer -- try to pin a block in a recently observed buffer
814 : : *
815 : : * Compared to ReadBuffer(), this avoids a buffer mapping lookup when it's
816 : : * successful. Return true if the buffer is valid and still has the expected
817 : : * tag. In that case, the buffer is pinned and the usage count is bumped.
818 : : */
819 : : bool
1559 rhaas@postgresql.org 820 : 5187 : ReadRecentBuffer(RelFileLocator rlocator, ForkNumber forkNum, BlockNumber blockNum,
821 : : Buffer recent_buffer)
822 : : {
823 : : BufferDesc *bufHdr;
824 : : BufferTag tag;
825 : : uint64 buf_state;
826 : :
2013 tmunro@postgresql.or 827 [ - + ]: 5187 : Assert(BufferIsValid(recent_buffer));
828 : :
1069 heikki.linnakangas@i 829 : 5187 : ResourceOwnerEnlarge(CurrentResourceOwner);
2013 tmunro@postgresql.or 830 : 5187 : ReservePrivateRefCountEntry();
1538 rhaas@postgresql.org 831 : 5187 : InitBufferTag(&tag, &rlocator, forkNum, blockNum);
832 : :
2013 tmunro@postgresql.or 833 [ + + ]: 5187 : if (BufferIsLocal(recent_buffer))
834 : : {
1540 heikki.linnakangas@i 835 : 140 : int b = -recent_buffer - 1;
836 : :
837 : 140 : bufHdr = GetLocalBufferDescriptor(b);
270 andres@anarazel.de 838 : 140 : buf_state = pg_atomic_read_u64(&bufHdr->state);
839 : :
840 : : /* Is it still valid and holding the right tag? */
1538 rhaas@postgresql.org 841 [ + - + - ]: 140 : if ((buf_state & BM_VALID) && BufferTagsEqual(&tag, &bufHdr->tag))
842 : : {
1286 andres@anarazel.de 843 : 140 : PinLocalBuffer(bufHdr, true);
844 : :
1649 tmunro@postgresql.or 845 : 140 : pgBufferUsage.local_blks_hit++;
846 : :
2013 847 : 140 : return true;
848 : : }
849 : : }
850 : : else
851 : : {
852 : 5047 : bufHdr = GetBufferDescriptor(recent_buffer - 1);
853 : :
854 : : /*
855 : : * Is it still valid and holding the right tag? We do an unlocked tag
856 : : * comparison first, to make it unlikely that we'll increment the
857 : : * usage counter of the wrong buffer, if someone calls us with a very
858 : : * out of date recent_buffer. Then we'll check it again if we get the
859 : : * pin.
860 : : */
369 andres@anarazel.de 861 [ + + + + ]: 10062 : if (BufferTagsEqual(&tag, &bufHdr->tag) &&
862 : 5015 : PinBuffer(bufHdr, NULL, true))
863 : : {
864 [ + - ]: 5009 : if (BufferTagsEqual(&tag, &bufHdr->tag))
865 : : {
866 : 5009 : pgBufferUsage.shared_blks_hit++;
867 : 5009 : return true;
868 : : }
369 andres@anarazel.de 869 :UBC 0 : UnpinBuffer(bufHdr);
870 : : }
871 : : }
872 : :
2013 tmunro@postgresql.or 873 :CBC 38 : return false;
874 : : }
875 : :
876 : : /*
877 : : * ReadBuffer -- a shorthand for ReadBufferExtended, for reading from main
878 : : * fork with RBM_NORMAL mode and default strategy.
879 : : */
880 : : Buffer
6555 heikki.linnakangas@i 881 : 62665052 : ReadBuffer(Relation reln, BlockNumber blockNum)
882 : : {
883 : 62665052 : return ReadBufferExtended(reln, MAIN_FORKNUM, blockNum, RBM_NORMAL, NULL);
884 : : }
885 : :
886 : : /*
887 : : * ReadBufferExtended -- returns a buffer containing the requested
888 : : * block of the requested relation. If the blknum
889 : : * requested is P_NEW, extend the relation file and
890 : : * allocate a new block. (Caller is responsible for
891 : : * ensuring that only one backend tries to extend a
892 : : * relation at the same time!)
893 : : *
894 : : * Returns: the buffer number for the buffer containing
895 : : * the block read. The returned buffer has been pinned.
896 : : * Does not return on error --- elog's instead.
897 : : *
898 : : * Assume when this function is called, that reln has been opened already.
899 : : *
900 : : * In RBM_NORMAL mode, the page is read from disk, and the page header is
901 : : * validated. An error is thrown if the page header is not valid. (But
902 : : * note that an all-zero page is considered "valid"; see
903 : : * PageIsVerified().)
904 : : *
905 : : * RBM_ZERO_ON_ERROR is like the normal mode, but if the page header is not
906 : : * valid, the page is zeroed instead of throwing an error. This is intended
907 : : * for non-critical data, where the caller is prepared to repair errors.
908 : : *
909 : : * In RBM_ZERO_AND_LOCK mode, if the page isn't in buffer cache already, it's
910 : : * filled with zeros instead of reading it from disk. Useful when the caller
911 : : * is going to fill the page from scratch, since this saves I/O and avoids
912 : : * unnecessary failure if the page-on-disk has corrupt page headers.
913 : : * The page is returned locked to ensure that the caller has a chance to
914 : : * initialize the page before it's made visible to others.
915 : : * Caution: do not use this mode to read a page that is beyond the relation's
916 : : * current physical EOF; that is likely to cause problems in md.c when
917 : : * the page is modified and written out. P_NEW is OK, though.
918 : : *
919 : : * RBM_ZERO_AND_CLEANUP_LOCK is the same as RBM_ZERO_AND_LOCK, but acquires
920 : : * a cleanup-strength lock on the page.
921 : : *
922 : : * RBM_NORMAL_NO_LOG mode is treated the same as RBM_NORMAL here.
923 : : *
924 : : * If strategy is not NULL, a nondefault buffer access strategy is used.
925 : : * See buffer/README for details.
926 : : */
927 : : inline Buffer
928 : 73985264 : ReadBufferExtended(Relation reln, ForkNumber forkNum, BlockNumber blockNum,
929 : : ReadBufferMode mode, BufferAccessStrategy strategy)
930 : : {
931 : : Buffer buf;
932 : :
933 : : /*
934 : : * Read the buffer, and update pgstat counters to reflect a cache hit or
935 : : * miss. The other-session temp-relation check is enforced by
936 : : * ReadBuffer_common().
937 : : */
922 tmunro@postgresql.or 938 : 73985264 : buf = ReadBuffer_common(reln, RelationGetSmgr(reln), 0,
939 : : forkNum, blockNum, mode, strategy);
940 : :
6696 heikki.linnakangas@i 941 : 73985239 : return buf;
942 : : }
943 : :
944 : :
945 : : /*
946 : : * ReadBufferWithoutRelcache -- like ReadBufferExtended, but doesn't require
947 : : * a relcache entry for the relation.
948 : : *
949 : : * Pass permanent = true for a RELPERSISTENCE_PERMANENT relation, and
950 : : * permanent = false for a RELPERSISTENCE_UNLOGGED relation. This function
951 : : * cannot be used for temporary relations (and making that work might be
952 : : * difficult, unless we only want to read temporary relations for our own
953 : : * ProcNumber).
954 : : */
955 : : Buffer
1559 rhaas@postgresql.org 956 : 5937488 : ReadBufferWithoutRelcache(RelFileLocator rlocator, ForkNumber forkNum,
957 : : BlockNumber blockNum, ReadBufferMode mode,
958 : : BufferAccessStrategy strategy, bool permanent)
959 : : {
953 heikki.linnakangas@i 960 : 5937488 : SMgrRelation smgr = smgropen(rlocator, INVALID_PROC_NUMBER);
961 : :
922 tmunro@postgresql.or 962 [ + - ]: 5937488 : return ReadBuffer_common(NULL, smgr,
963 : : permanent ? RELPERSISTENCE_PERMANENT : RELPERSISTENCE_UNLOGGED,
964 : : forkNum, blockNum,
965 : : mode, strategy);
966 : : }
967 : :
968 : : /*
969 : : * Convenience wrapper around ExtendBufferedRelBy() extending by one block.
970 : : */
971 : : Buffer
1146 972 : 56092 : ExtendBufferedRel(BufferManagerRelation bmr,
973 : : ForkNumber forkNum,
974 : : BufferAccessStrategy strategy,
975 : : uint32 flags)
976 : : {
977 : : Buffer buf;
1286 andres@anarazel.de 978 : 56092 : uint32 extend_by = 1;
979 : :
1146 tmunro@postgresql.or 980 : 56092 : ExtendBufferedRelBy(bmr, forkNum, strategy, flags, extend_by,
981 : : &buf, &extend_by);
982 : :
1286 andres@anarazel.de 983 : 56092 : return buf;
984 : : }
985 : :
986 : : /*
987 : : * Extend relation by multiple blocks.
988 : : *
989 : : * Tries to extend the relation by extend_by blocks. Depending on the
990 : : * availability of resources the relation may end up being extended by a
991 : : * smaller number of pages (unless an error is thrown, always by at least one
992 : : * page). *extended_by is updated to the number of pages the relation has been
993 : : * extended to.
994 : : *
995 : : * buffers needs to be an array that is at least extend_by long. Upon
996 : : * completion, the first extend_by array elements will point to a pinned
997 : : * buffer.
998 : : *
999 : : * If EB_LOCK_FIRST is part of flags, the first returned buffer is
1000 : : * locked. This is useful for callers that want a buffer that is guaranteed to
1001 : : * be empty.
1002 : : */
1003 : : BlockNumber
1146 tmunro@postgresql.or 1004 : 206799 : ExtendBufferedRelBy(BufferManagerRelation bmr,
1005 : : ForkNumber fork,
1006 : : BufferAccessStrategy strategy,
1007 : : uint32 flags,
1008 : : uint32 extend_by,
1009 : : Buffer *buffers,
1010 : : uint32 *extended_by)
1011 : : {
1012 [ - + ]: 206799 : Assert((bmr.rel != NULL) != (bmr.smgr != NULL));
356 alvherre@kurilemu.de 1013 [ - + - - ]: 206799 : Assert(bmr.smgr == NULL || bmr.relpersistence != '\0');
1286 andres@anarazel.de 1014 [ - + ]: 206799 : Assert(extend_by > 0);
1015 : :
356 alvherre@kurilemu.de 1016 [ + - ]: 206799 : if (bmr.relpersistence == '\0')
1146 tmunro@postgresql.or 1017 : 206799 : bmr.relpersistence = bmr.rel->rd_rel->relpersistence;
1018 : :
1019 : 206799 : return ExtendBufferedRelCommon(bmr, fork, strategy, flags,
1020 : : extend_by, InvalidBlockNumber,
1021 : : buffers, extended_by);
1022 : : }
1023 : :
1024 : : /*
1025 : : * Extend the relation so it is at least extend_to blocks large, return buffer
1026 : : * (extend_to - 1).
1027 : : *
1028 : : * This is useful for callers that want to write a specific page, regardless
1029 : : * of the current size of the relation (e.g. useful for visibilitymap and for
1030 : : * crash recovery).
1031 : : */
1032 : : Buffer
1033 : 55600 : ExtendBufferedRelTo(BufferManagerRelation bmr,
1034 : : ForkNumber fork,
1035 : : BufferAccessStrategy strategy,
1036 : : uint32 flags,
1037 : : BlockNumber extend_to,
1038 : : ReadBufferMode mode)
1039 : : {
1040 : : BlockNumber current_size;
1286 andres@anarazel.de 1041 : 55600 : uint32 extended_by = 0;
1042 : 55600 : Buffer buffer = InvalidBuffer;
1043 : : Buffer buffers[64];
1044 : :
1146 tmunro@postgresql.or 1045 [ - + ]: 55600 : Assert((bmr.rel != NULL) != (bmr.smgr != NULL));
356 alvherre@kurilemu.de 1046 [ + + - + ]: 55600 : Assert(bmr.smgr == NULL || bmr.relpersistence != '\0');
1286 andres@anarazel.de 1047 [ + - - + ]: 55600 : Assert(extend_to != InvalidBlockNumber && extend_to > 0);
1048 : :
356 alvherre@kurilemu.de 1049 [ + + ]: 55600 : if (bmr.relpersistence == '\0')
1146 tmunro@postgresql.or 1050 : 9772 : bmr.relpersistence = bmr.rel->rd_rel->relpersistence;
1051 : :
1052 : : /*
1053 : : * If desired, create the file if it doesn't exist. If
1054 : : * smgr_cached_nblocks[fork] is positive then it must exist, no need for
1055 : : * an smgrexists call.
1056 : : */
1286 andres@anarazel.de 1057 [ + + ]: 55600 : if ((flags & EB_CREATE_FORK_IF_NEEDED) &&
356 alvherre@kurilemu.de 1058 [ + - + + ]: 9772 : (BMR_GET_SMGR(bmr)->smgr_cached_nblocks[fork] == 0 ||
1059 [ + - - + ]: 35 : BMR_GET_SMGR(bmr)->smgr_cached_nblocks[fork] == InvalidBlockNumber) &&
1060 [ + - + + ]: 9737 : !smgrexists(BMR_GET_SMGR(bmr), fork))
1061 : : {
1146 tmunro@postgresql.or 1062 : 9701 : LockRelationForExtension(bmr.rel, ExclusiveLock);
1063 : :
1064 : : /* recheck, fork might have been created concurrently */
356 alvherre@kurilemu.de 1065 [ + - + + ]: 9701 : if (!smgrexists(BMR_GET_SMGR(bmr), fork))
1066 [ + - ]: 9700 : smgrcreate(BMR_GET_SMGR(bmr), fork, flags & EB_PERFORMING_RECOVERY);
1067 : :
1146 tmunro@postgresql.or 1068 : 9701 : UnlockRelationForExtension(bmr.rel, ExclusiveLock);
1069 : : }
1070 : :
1071 : : /*
1072 : : * If requested, invalidate size cache, so that smgrnblocks asks the
1073 : : * kernel.
1074 : : */
1286 andres@anarazel.de 1075 [ + + ]: 55600 : if (flags & EB_CLEAR_SIZE_CACHE)
356 alvherre@kurilemu.de 1076 [ + - ]: 9772 : BMR_GET_SMGR(bmr)->smgr_cached_nblocks[fork] = InvalidBlockNumber;
1077 : :
1078 : : /*
1079 : : * Estimate how many pages we'll need to extend by. This avoids acquiring
1080 : : * unnecessarily many victim buffers.
1081 : : */
1082 [ + + ]: 55600 : current_size = smgrnblocks(BMR_GET_SMGR(bmr), fork);
1083 : :
1084 : : /*
1085 : : * Since no-one else can be looking at the page contents yet, there is no
1086 : : * difference between an exclusive lock and a cleanup-strength lock. Note
1087 : : * that we pass the original mode to ReadBuffer_common() below, when
1088 : : * falling back to reading the buffer to a concurrent relation extension.
1089 : : */
1277 andres@anarazel.de 1090 [ + + - + ]: 55600 : if (mode == RBM_ZERO_AND_LOCK || mode == RBM_ZERO_AND_CLEANUP_LOCK)
1286 1091 : 45414 : flags |= EB_LOCK_TARGET;
1092 : :
1093 [ + + ]: 113513 : while (current_size < extend_to)
1094 : : {
1095 : 57913 : uint32 num_pages = lengthof(buffers);
1096 : : BlockNumber first_block;
1097 : :
1098 [ + + ]: 57913 : if ((uint64) current_size + num_pages > extend_to)
1099 : 57847 : num_pages = extend_to - current_size;
1100 : :
1146 tmunro@postgresql.or 1101 : 57913 : first_block = ExtendBufferedRelCommon(bmr, fork, strategy, flags,
1102 : : num_pages, extend_to,
1103 : : buffers, &extended_by);
1104 : :
1286 andres@anarazel.de 1105 : 57913 : current_size = first_block + extended_by;
1106 [ - + - - ]: 57913 : Assert(num_pages != 0 || current_size >= extend_to);
1107 : :
1119 peter@eisentraut.org 1108 [ + + ]: 125076 : for (uint32 i = 0; i < extended_by; i++)
1109 : : {
1286 andres@anarazel.de 1110 [ + + ]: 67163 : if (first_block + i != extend_to - 1)
1111 : 11567 : ReleaseBuffer(buffers[i]);
1112 : : else
1113 : 55596 : buffer = buffers[i];
1114 : : }
1115 : : }
1116 : :
1117 : : /*
1118 : : * It's possible that another backend concurrently extended the relation.
1119 : : * In that case read the buffer.
1120 : : *
1121 : : * XXX: Should we control this via a flag?
1122 : : */
1123 [ + + ]: 55600 : if (buffer == InvalidBuffer)
1124 : : {
1125 [ - + ]: 4 : Assert(extended_by == 0);
356 alvherre@kurilemu.de 1126 [ + - ]: 4 : buffer = ReadBuffer_common(bmr.rel, BMR_GET_SMGR(bmr), bmr.relpersistence,
1127 : : fork, extend_to - 1, mode, strategy);
1128 : : }
1129 : :
1286 andres@anarazel.de 1130 : 55600 : return buffer;
1131 : : }
1132 : :
1133 : : /*
1134 : : * Lock and optionally zero a buffer, as part of the implementation of
1135 : : * RBM_ZERO_AND_LOCK or RBM_ZERO_AND_CLEANUP_LOCK. The buffer must be already
1136 : : * pinned. If the buffer is not already valid, it is zeroed and made valid.
1137 : : */
1138 : : static void
854 tmunro@postgresql.or 1139 : 356882 : ZeroAndLockBuffer(Buffer buffer, ReadBufferMode mode, bool already_valid)
1140 : : {
1141 : : BufferDesc *bufHdr;
1142 : : bool need_to_zero;
1143 : 356882 : bool isLocalBuf = BufferIsLocal(buffer);
1144 : : StartBufferIOResult sbres;
1145 : :
922 1146 [ + + - + ]: 356882 : Assert(mode == RBM_ZERO_AND_LOCK || mode == RBM_ZERO_AND_CLEANUP_LOCK);
1147 : :
854 1148 [ + + ]: 356882 : if (already_valid)
1149 : : {
1150 : : /*
1151 : : * If the caller already knew the buffer was valid, we can skip some
1152 : : * header interaction. The caller just wants to lock the buffer.
1153 : : */
1154 : 38192 : need_to_zero = false;
1155 : : }
1156 : : else
1157 : : {
199 andres@anarazel.de 1158 [ + + ]: 318690 : if (isLocalBuf)
1159 : : {
1160 : : /* Simple case for non-shared buffers. */
1161 : 30 : bufHdr = GetLocalBufferDescriptor(-buffer - 1);
1162 : 30 : sbres = StartLocalBufferIO(bufHdr, true, true, NULL);
1163 : : }
1164 : : else
1165 : : {
1166 : : /*
1167 : : * Take BM_IO_IN_PROGRESS, or discover that BM_VALID has been set
1168 : : * concurrently. Even though we aren't doing I/O, that ensures
1169 : : * that we don't zero a page that someone else has pinned. An
1170 : : * exclusive content lock wouldn't be enough, because readers are
1171 : : * allowed to drop the content lock after determining that a tuple
1172 : : * is visible (see buffer access rules in README).
1173 : : */
1174 : 318660 : bufHdr = GetBufferDescriptor(buffer - 1);
1175 : 318660 : sbres = StartSharedBufferIO(bufHdr, true, true, NULL);
1176 : : }
1177 : :
1178 [ - + ]: 318690 : Assert(sbres != BUFFER_IO_IN_PROGRESS);
1179 : 318690 : need_to_zero = sbres == BUFFER_IO_READY_FOR_IO;
1180 : : }
1181 : :
854 tmunro@postgresql.or 1182 [ + + ]: 356882 : if (need_to_zero)
1183 : : {
1184 : 318690 : memset(BufferGetPage(buffer), 0, BLCKSZ);
1185 : :
1186 : : /*
1187 : : * Grab the buffer content lock before marking the page as valid, to
1188 : : * make sure that no other backend sees the zeroed page before the
1189 : : * caller has had a chance to initialize it.
1190 : : *
1191 : : * Since no-one else can be looking at the page contents yet, there is
1192 : : * no difference between an exclusive lock and a cleanup-strength
1193 : : * lock. (Note that we cannot use LockBuffer() or
1194 : : * LockBufferForCleanup() here, because they assert that the buffer is
1195 : : * already valid.)
1196 : : */
1197 [ + + ]: 318690 : if (!isLocalBuf)
369 andres@anarazel.de 1198 : 318660 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
1199 : :
1200 : : /* Set BM_VALID, terminate IO, and wake up any waiters */
854 tmunro@postgresql.or 1201 [ + + ]: 318690 : if (isLocalBuf)
561 andres@anarazel.de 1202 : 30 : TerminateLocalBufferIO(bufHdr, false, BM_VALID, false);
1203 : : else
1204 : 318660 : TerminateBufferIO(bufHdr, false, BM_VALID, true, false);
1205 : : }
854 tmunro@postgresql.or 1206 [ + + ]: 38192 : else if (!isLocalBuf)
1207 : : {
1208 : : /*
1209 : : * The buffer is valid, so we can't zero it. The caller still expects
1210 : : * the page to be locked on return.
1211 : : */
1212 [ + + ]: 38172 : if (mode == RBM_ZERO_AND_LOCK)
1213 : 38116 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
1214 : : else
1215 : 56 : LockBufferForCleanup(buffer);
1216 : : }
922 1217 : 356882 : }
1218 : :
1219 : : /*
1220 : : * Pin a buffer for a given block. *foundPtr is set to true if the block was
1221 : : * already present, or false if more work is required to either read it in or
1222 : : * zero it.
1223 : : */
1224 : : static pg_always_inline Buffer
1225 : 83925794 : PinBufferForBlock(Relation rel,
1226 : : SMgrRelation smgr,
1227 : : char persistence,
1228 : : ForkNumber forkNum,
1229 : : BlockNumber blockNum,
1230 : : BufferAccessStrategy strategy,
1231 : : IOObject io_object,
1232 : : IOContext io_context,
1233 : : bool *foundPtr)
1234 : : {
1235 : : BufferDesc *bufHdr;
1236 : :
1237 [ - + ]: 83925794 : Assert(blockNum != P_NEW);
1238 : :
1239 : : /* Persistence should be set before */
814 noah@leadboat.com 1240 [ + + + + : 83925794 : Assert((persistence == RELPERSISTENCE_TEMP ||
- + ]
1241 : : persistence == RELPERSISTENCE_PERMANENT ||
1242 : : persistence == RELPERSISTENCE_UNLOGGED));
1243 : :
1244 : : TRACE_POSTGRESQL_BUFFER_READ_START(forkNum, blockNum,
1245 : : smgr->smgr_rlocator.locator.spcOid,
1246 : : smgr->smgr_rlocator.locator.dbOid,
1247 : : smgr->smgr_rlocator.locator.relNumber,
1248 : : smgr->smgr_rlocator.backend);
1249 : :
922 tmunro@postgresql.or 1250 [ + + ]: 83925794 : if (persistence == RELPERSISTENCE_TEMP)
1251 : 1790897 : bufHdr = LocalBufferAlloc(smgr, forkNum, blockNum, foundPtr);
1252 : : else
1253 : 82134897 : bufHdr = BufferAlloc(smgr, persistence, forkNum, blockNum,
1254 : : strategy, foundPtr, io_context);
1255 : :
200 andres@anarazel.de 1256 [ + + ]: 83925786 : if (*foundPtr)
1257 : 82057054 : TrackBufferHit(io_object, io_context, rel, persistence, smgr, forkNum, blockNum);
1258 : :
922 tmunro@postgresql.or 1259 [ + + ]: 83925786 : if (rel)
1260 : : {
1261 : : /*
1262 : : * While pgBufferUsage's "read" counter isn't bumped unless we reach
1263 : : * WaitReadBuffers() (so, not for hits, and not for buffers that are
1264 : : * zeroed instead), the per-relation stats always count them.
1265 : : */
1266 [ + + + + : 77730616 : pgstat_count_buffer_read(rel);
+ + + + ]
1267 : : }
1268 : :
1269 : 83925786 : return BufferDescriptorGetBuffer(bufHdr);
1270 : : }
1271 : :
1272 : : /*
1273 : : * ReadBuffer_common -- common logic for all ReadBuffer variants
1274 : : *
1275 : : * smgr is required, rel is optional unless using P_NEW.
1276 : : */
1277 : : static pg_always_inline Buffer
1278 : 79922756 : ReadBuffer_common(Relation rel, SMgrRelation smgr, char smgr_persistence,
1279 : : ForkNumber forkNum,
1280 : : BlockNumber blockNum, ReadBufferMode mode,
1281 : : BufferAccessStrategy strategy)
1282 : : {
1283 : : ReadBuffersOperation operation;
1284 : : Buffer buffer;
1285 : : int readflags;
1286 : : char persistence;
1287 : :
1288 : : /*
1289 : : * Reject attempts to read non-local temporary relations; we would be
1290 : : * likely to get wrong data since we have no visibility into the owning
1291 : : * session's local buffers. This is the canonical place for the check,
1292 : : * covering the ReadBufferExtended() entry point and any other caller that
1293 : : * supplies a Relation.
1294 : : */
151 akorotkov@postgresql 1295 [ + + + + : 79922756 : if (rel && RELATION_IS_OTHER_TEMP(rel))
+ + ]
1296 [ + - ]: 2 : ereport(ERROR,
1297 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1298 : : errmsg("cannot access temporary tables of other sessions")));
1299 : :
1300 : : /*
1301 : : * Backward compatibility path, most code should use ExtendBufferedRel()
1302 : : * instead, as acquiring the extension lock inside ExtendBufferedRel()
1303 : : * scales a lot better.
1304 : : */
922 tmunro@postgresql.or 1305 [ + + ]: 79922754 : if (unlikely(blockNum == P_NEW))
1306 : : {
34 peter@eisentraut.org 1307 :GNC 322 : uint32 ebflags = EB_SKIP_EXTENSION_LOCK;
1308 : :
1309 : : /*
1310 : : * Since no-one else can be looking at the page contents yet, there is
1311 : : * no difference between an exclusive lock and a cleanup-strength
1312 : : * lock.
1313 : : */
922 tmunro@postgresql.or 1314 [ + - - + ]:CBC 322 : if (mode == RBM_ZERO_AND_LOCK || mode == RBM_ZERO_AND_CLEANUP_LOCK)
34 peter@eisentraut.org 1315 :UNC 0 : ebflags |= EB_LOCK_FIRST;
1316 : :
34 peter@eisentraut.org 1317 :GNC 322 : return ExtendBufferedRel(BMR_REL(rel), forkNum, strategy, ebflags);
1318 : : }
1319 : :
814 noah@leadboat.com 1320 [ + + ]:CBC 79922432 : if (rel)
1321 : 73984944 : persistence = rel->rd_rel->relpersistence;
1322 : : else
1323 : 5937488 : persistence = smgr_persistence;
1324 : :
922 tmunro@postgresql.or 1325 [ + + + + : 79922432 : if (unlikely(mode == RBM_ZERO_AND_CLEANUP_LOCK ||
+ + ]
1326 : : mode == RBM_ZERO_AND_LOCK))
1327 : : {
1328 : : bool found;
1329 : : IOContext io_context;
1330 : : IOObject io_object;
1331 : :
200 andres@anarazel.de 1332 [ + + ]: 356882 : if (persistence == RELPERSISTENCE_TEMP)
1333 : : {
1334 : 50 : io_context = IOCONTEXT_NORMAL;
1335 : 50 : io_object = IOOBJECT_TEMP_RELATION;
1336 : : }
1337 : : else
1338 : : {
1339 : 356832 : io_context = IOContextForStrategy(strategy);
1340 : 356832 : io_object = IOOBJECT_RELATION;
1341 : : }
1342 : :
814 noah@leadboat.com 1343 : 356882 : buffer = PinBufferForBlock(rel, smgr, persistence,
1344 : : forkNum, blockNum, strategy,
1345 : : io_object, io_context, &found);
854 tmunro@postgresql.or 1346 : 356882 : ZeroAndLockBuffer(buffer, mode, found);
922 1347 : 356882 : return buffer;
1348 : : }
1349 : :
1350 : : /*
1351 : : * Signal that we are going to immediately wait. If we're immediately
1352 : : * waiting, there is no benefit in actually executing the IO
1353 : : * asynchronously, it would just add dispatch overhead.
1354 : : */
34 peter@eisentraut.org 1355 :GNC 79565550 : readflags = READ_BUFFERS_SYNCHRONOUSLY;
922 tmunro@postgresql.or 1356 [ + + ]:CBC 79565550 : if (mode == RBM_ZERO_ON_ERROR)
34 peter@eisentraut.org 1357 :GNC 1627036 : readflags |= READ_BUFFERS_ZERO_ON_ERROR;
922 tmunro@postgresql.or 1358 :CBC 79565550 : operation.smgr = smgr;
1359 : 79565550 : operation.rel = rel;
814 noah@leadboat.com 1360 : 79565550 : operation.persistence = persistence;
922 tmunro@postgresql.or 1361 : 79565550 : operation.forknum = forkNum;
1362 : 79565550 : operation.strategy = strategy;
1363 [ + + ]: 79565550 : if (StartReadBuffer(&operation,
1364 : : &buffer,
1365 : : blockNum,
1366 : : readflags))
1367 : 766489 : WaitReadBuffers(&operation);
1368 : :
1369 : 79565527 : return buffer;
1370 : : }
1371 : :
1372 : : static pg_always_inline bool
1373 : 83394100 : StartReadBuffersImpl(ReadBuffersOperation *operation,
1374 : : Buffer *buffers,
1375 : : BlockNumber blockNum,
1376 : : int *nblocks,
1377 : : int flags,
1378 : : bool allow_forwarding)
1379 : : {
1380 : 83394100 : int actual_nblocks = *nblocks;
734 andres@anarazel.de 1381 : 83394100 : int maxcombine = 0;
1382 : : bool did_start_io;
1383 : : IOContext io_context;
1384 : : IOObject io_object;
1385 : :
570 tmunro@postgresql.or 1386 [ + + - + ]: 83394100 : Assert(*nblocks == 1 || allow_forwarding);
922 1387 [ - + ]: 83394100 : Assert(*nblocks > 0);
1388 [ - + ]: 83394100 : Assert(*nblocks <= MAX_IO_COMBINE_LIMIT);
1389 : :
1390 : : /* see comments in ReadBuffer_common */
151 akorotkov@postgresql 1391 [ + + + + : 83394100 : if (operation->rel && RELATION_IS_OTHER_TEMP(operation->rel))
- + ]
151 akorotkov@postgresql 1392 [ # # ]:UBC 0 : ereport(ERROR,
1393 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1394 : : errmsg("cannot access temporary tables of other sessions")));
1395 : :
200 andres@anarazel.de 1396 [ + + ]:CBC 83394100 : if (operation->persistence == RELPERSISTENCE_TEMP)
1397 : : {
1398 : 1782635 : io_context = IOCONTEXT_NORMAL;
1399 : 1782635 : io_object = IOOBJECT_TEMP_RELATION;
1400 : : }
1401 : : else
1402 : : {
1403 : 81611465 : io_context = IOContextForStrategy(operation->strategy);
1404 : 81611465 : io_object = IOOBJECT_RELATION;
1405 : : }
1406 : :
922 tmunro@postgresql.or 1407 [ + + ]: 84944156 : for (int i = 0; i < actual_nblocks; ++i)
1408 : : {
1409 : : bool found;
1410 : :
570 1411 [ + + + + ]: 83571046 : if (allow_forwarding && buffers[i] != InvalidBuffer)
1412 : 2134 : {
1413 : : BufferDesc *bufHdr;
1414 : :
1415 : : /*
1416 : : * This is a buffer that was pinned by an earlier call to
1417 : : * StartReadBuffers(), but couldn't be handled in one operation at
1418 : : * that time. The operation was split, and the caller has passed
1419 : : * an already pinned buffer back to us to handle the rest of the
1420 : : * operation. It must continue at the expected block number.
1421 : : */
1422 [ - + ]: 2134 : Assert(BufferGetBlockNumber(buffers[i]) == blockNum + i);
1423 : :
1424 : : /*
1425 : : * It might be an already valid buffer (a hit) that followed the
1426 : : * final contiguous block of an earlier I/O (a miss) marking the
1427 : : * end of it, or a buffer that some other backend has since made
1428 : : * valid by performing the I/O for us, in which case we can handle
1429 : : * it as a hit now. It is safe to check for a BM_VALID flag with
1430 : : * a relaxed load, because we got a fresh view of it while pinning
1431 : : * it in the previous call.
1432 : : *
1433 : : * On the other hand if we don't see BM_VALID yet, it must be an
1434 : : * I/O that was split by the previous call and we need to try to
1435 : : * start a new I/O from this block. We're also racing against any
1436 : : * other backend that might start the I/O or even manage to mark
1437 : : * it BM_VALID after this check, but StartBufferIO() will handle
1438 : : * those cases.
1439 : : */
1440 [ + + ]: 2134 : if (BufferIsLocal(buffers[i]))
1441 : 16 : bufHdr = GetLocalBufferDescriptor(-buffers[i] - 1);
1442 : : else
1443 : 2118 : bufHdr = GetBufferDescriptor(buffers[i] - 1);
270 andres@anarazel.de 1444 [ - + ]: 2134 : Assert(pg_atomic_read_u64(&bufHdr->state) & BM_TAG_VALID);
1445 : 2134 : found = pg_atomic_read_u64(&bufHdr->state) & BM_VALID;
1446 : : }
1447 : : else
1448 : : {
570 tmunro@postgresql.or 1449 : 83568904 : buffers[i] = PinBufferForBlock(operation->rel,
1450 : : operation->smgr,
1451 : 83568912 : operation->persistence,
1452 : : operation->forknum,
1453 : : blockNum + i,
1454 : : operation->strategy,
1455 : : io_object, io_context,
1456 : : &found);
1457 : : }
1458 : :
922 1459 [ + + ]: 83571038 : if (found)
1460 : : {
1461 : : /*
1462 : : * We have a hit. If it's the first block in the requested range,
1463 : : * we can return it immediately and report that WaitReadBuffers()
1464 : : * does not need to be called. If the initial value of *nblocks
1465 : : * was larger, the caller will have to call again for the rest.
1466 : : */
570 1467 [ + + ]: 82020982 : if (i == 0)
1468 : : {
1469 : 82018861 : *nblocks = 1;
1470 : :
1471 : : #ifdef USE_ASSERT_CHECKING
1472 : :
1473 : : /*
1474 : : * Initialize enough of ReadBuffersOperation to make
1475 : : * CheckReadBuffersOperation() work. Outside of assertions
1476 : : * that's not necessary when no IO is issued.
1477 : : */
561 andres@anarazel.de 1478 : 82018861 : operation->buffers = buffers;
1479 : 82018861 : operation->blocknum = blockNum;
1480 : 82018861 : operation->nblocks = 1;
1481 : 82018861 : operation->nblocks_done = 1;
1482 : 82018861 : CheckReadBuffersOperation(operation, true);
1483 : : #endif
570 tmunro@postgresql.or 1484 : 82018861 : return false;
1485 : : }
1486 : :
1487 : : /*
1488 : : * Otherwise we already have an I/O to perform, but this block
1489 : : * can't be included as it is already valid. Split the I/O here.
1490 : : * There may or may not be more blocks requiring I/O after this
1491 : : * one, we haven't checked, but they can't be contiguous with this
1492 : : * one in the way. We'll leave this buffer pinned, forwarding it
1493 : : * to the next call, avoiding the need to unpin it here and re-pin
1494 : : * it in the next call.
1495 : : */
1496 : 2121 : actual_nblocks = i;
922 1497 : 2121 : break;
1498 : : }
1499 : : else
1500 : : {
1501 : : /*
1502 : : * Check how many blocks we can cover with the same IO. The smgr
1503 : : * implementation might e.g. be limited due to a segment boundary.
1504 : : */
734 andres@anarazel.de 1505 [ + + + + ]: 1550056 : if (i == 0 && actual_nblocks > 1)
1506 : : {
1507 : 37638 : maxcombine = smgrmaxcombine(operation->smgr,
1508 : : operation->forknum,
1509 : : blockNum);
1510 [ - + ]: 37638 : if (unlikely(maxcombine < actual_nblocks))
1511 : : {
734 andres@anarazel.de 1512 [ # # ]:UBC 0 : elog(DEBUG2, "limiting nblocks at %u from %u to %u",
1513 : : blockNum, actual_nblocks, maxcombine);
1514 : 0 : actual_nblocks = maxcombine;
1515 : : }
1516 : : }
1517 : : }
1518 : : }
922 tmunro@postgresql.or 1519 :CBC 1375231 : *nblocks = actual_nblocks;
1520 : :
1521 : : /* Populate information needed for I/O. */
1522 : 1375231 : operation->buffers = buffers;
1523 : 1375231 : operation->blocknum = blockNum;
1524 : 1375231 : operation->flags = flags;
1525 : 1375231 : operation->nblocks = actual_nblocks;
561 andres@anarazel.de 1526 : 1375231 : operation->nblocks_done = 0;
1527 : 1375231 : pgaio_wref_clear(&operation->io_wref);
1528 : :
1529 : : /*
1530 : : * When using AIO, start the IO in the background. If not, issue prefetch
1531 : : * requests if desired by the caller.
1532 : : *
1533 : : * The reason we have a dedicated path for IOMETHOD_SYNC here is to
1534 : : * de-risk the introduction of AIO somewhat. It's a large architectural
1535 : : * change, with lots of chances for unanticipated performance effects.
1536 : : *
1537 : : * Use of IOMETHOD_SYNC already leads to not actually performing IO
1538 : : * asynchronously, but without the check here we'd execute IO earlier than
1539 : : * we used to. Eventually this IOMETHOD_SYNC specific path should go away.
1540 : : */
1541 [ + + ]: 1375231 : if (io_method != IOMETHOD_SYNC)
1542 : : {
1543 : : /*
1544 : : * Try to start IO asynchronously. It's possible that no IO needs to
1545 : : * be started, if another backend already performed the IO.
1546 : : *
1547 : : * Note that if an IO is started, it might not cover the entire
1548 : : * requested range, e.g. because an intermediary block has been read
1549 : : * in by another backend. In that case any "trailing" buffers we
1550 : : * already pinned above will be "forwarded" by read_stream.c to the
1551 : : * next call to StartReadBuffers().
1552 : : *
1553 : : * This is signalled to the caller by decrementing *nblocks *and*
1554 : : * reducing operation->nblocks. The latter is done here, but not below
1555 : : * WaitReadBuffers(), as in WaitReadBuffers() we can't "shorten" the
1556 : : * overall read size anymore, we need to retry until done in its
1557 : : * entirety or until failed.
1558 : : */
1559 : 1373877 : did_start_io = AsyncReadBuffers(operation, nblocks);
1560 : :
1561 : 1373862 : operation->nblocks = *nblocks;
1562 : : }
1563 : : else
1564 : : {
1565 : 1354 : operation->flags |= READ_BUFFERS_SYNCHRONOUSLY;
1566 : :
1567 [ + + ]: 1354 : if (flags & READ_BUFFERS_ISSUE_ADVICE)
1568 : : {
1569 : : /*
1570 : : * In theory we should only do this if PinBufferForBlock() had to
1571 : : * allocate new buffers above. That way, if two calls to
1572 : : * StartReadBuffers() were made for the same blocks before
1573 : : * WaitReadBuffers(), only the first would issue the advice.
1574 : : * That'd be a better simulation of true asynchronous I/O, which
1575 : : * would only start the I/O once, but isn't done here for
1576 : : * simplicity.
1577 : : */
1578 : 19 : smgrprefetch(operation->smgr,
1579 : : operation->forknum,
1580 : : blockNum,
1581 : : actual_nblocks);
1582 : : }
1583 : :
1584 : : /*
1585 : : * Indicate that WaitReadBuffers() should be called. WaitReadBuffers()
1586 : : * will initiate the necessary IO.
1587 : : */
1588 : 1354 : did_start_io = true;
1589 : : }
1590 : :
1591 : 1375216 : CheckReadBuffersOperation(operation, !did_start_io);
1592 : :
1593 : 1375216 : return did_start_io;
1594 : : }
1595 : :
1596 : : /*
1597 : : * Begin reading a range of blocks beginning at blockNum and extending for
1598 : : * *nblocks. *nblocks and the buffers array are in/out parameters. On entry,
1599 : : * the buffers elements covered by *nblocks must hold either InvalidBuffer or
1600 : : * buffers forwarded by an earlier call to StartReadBuffers() that was split
1601 : : * and is now being continued. On return, *nblocks holds the number of blocks
1602 : : * accepted by this operation. If it is less than the original number then
1603 : : * this operation has been split, but buffer elements up to the original
1604 : : * requested size may hold forwarded buffers to be used for a continuing
1605 : : * operation. The caller must either start a new I/O beginning at the block
1606 : : * immediately following the blocks accepted by this call and pass those
1607 : : * buffers back in, or release them if it chooses not to. It shouldn't make
1608 : : * any other use of or assumptions about forwarded buffers.
1609 : : *
1610 : : * If false is returned, no I/O is necessary and the buffers covered by
1611 : : * *nblocks on exit are valid and ready to be accessed. If true is returned,
1612 : : * an I/O has been started, and WaitReadBuffers() must be called with the same
1613 : : * operation object before the buffers covered by *nblocks on exit can be
1614 : : * accessed. Along with the operation object, the caller-supplied array of
1615 : : * buffers must remain valid until WaitReadBuffers() is called, and any
1616 : : * forwarded buffers must also be preserved for a continuing call unless
1617 : : * they are explicitly released.
1618 : : */
1619 : : bool
922 tmunro@postgresql.or 1620 : 1682595 : StartReadBuffers(ReadBuffersOperation *operation,
1621 : : Buffer *buffers,
1622 : : BlockNumber blockNum,
1623 : : int *nblocks,
1624 : : int flags)
1625 : : {
570 1626 : 1682595 : return StartReadBuffersImpl(operation, buffers, blockNum, nblocks, flags,
1627 : : true /* expect forwarded buffers */ );
1628 : : }
1629 : :
1630 : : /*
1631 : : * Single block version of the StartReadBuffers(). This might save a few
1632 : : * instructions when called from another translation unit, because it is
1633 : : * specialized for nblocks == 1.
1634 : : *
1635 : : * This version does not support "forwarded" buffers: they cannot be created
1636 : : * by reading only one block and *buffer is ignored on entry.
1637 : : */
1638 : : bool
922 1639 : 81711505 : StartReadBuffer(ReadBuffersOperation *operation,
1640 : : Buffer *buffer,
1641 : : BlockNumber blocknum,
1642 : : int flags)
1643 : : {
1644 : 81711505 : int nblocks = 1;
1645 : : bool result;
1646 : :
570 1647 : 81711505 : result = StartReadBuffersImpl(operation, buffer, blocknum, &nblocks, flags,
1648 : : false /* single block, no forwarding */ );
922 1649 [ - + ]: 81711490 : Assert(nblocks == 1); /* single block can't be short */
1650 : :
1651 : 81711490 : return result;
1652 : : }
1653 : :
1654 : : /*
1655 : : * Perform sanity checks on the ReadBuffersOperation.
1656 : : */
1657 : : static void
561 andres@anarazel.de 1658 : 86144171 : CheckReadBuffersOperation(ReadBuffersOperation *operation, bool is_complete)
1659 : : {
1660 : : #ifdef USE_ASSERT_CHECKING
1661 [ - + ]: 86144171 : Assert(operation->nblocks_done <= operation->nblocks);
1662 [ + + - + ]: 86144171 : Assert(!is_complete || operation->nblocks == operation->nblocks_done);
1663 : :
1664 [ + + ]: 172815115 : for (int i = 0; i < operation->nblocks; i++)
1665 : : {
1666 : 86670944 : Buffer buffer = operation->buffers[i];
1667 : 86670944 : BufferDesc *buf_hdr = BufferIsLocal(buffer) ?
1668 [ + + ]: 86670944 : GetLocalBufferDescriptor(-buffer - 1) :
1669 : 84858387 : GetBufferDescriptor(buffer - 1);
1670 : :
1671 [ - + ]: 86670944 : Assert(BufferGetBlockNumber(buffer) == operation->blocknum + i);
270 1672 [ - + ]: 86670944 : Assert(pg_atomic_read_u64(&buf_hdr->state) & BM_TAG_VALID);
1673 : :
561 1674 [ + + ]: 86670944 : if (i < operation->nblocks_done)
270 1675 [ - + ]: 83569223 : Assert(pg_atomic_read_u64(&buf_hdr->state) & BM_VALID);
1676 : : }
1677 : : #endif
561 1678 : 86144171 : }
1679 : :
1680 : : /*
1681 : : * We track various stats related to buffer hits. Because this is done in a
1682 : : * few separate places, this helper exists for convenience.
1683 : : */
1684 : : static pg_always_inline void
200 1685 : 82059005 : TrackBufferHit(IOObject io_object, IOContext io_context,
1686 : : Relation rel, char persistence, SMgrRelation smgr,
1687 : : ForkNumber forknum, BlockNumber blocknum)
1688 : : {
1689 : : TRACE_POSTGRESQL_BUFFER_READ_DONE(forknum,
1690 : : blocknum,
1691 : : smgr->smgr_rlocator.locator.spcOid,
1692 : : smgr->smgr_rlocator.locator.dbOid,
1693 : : smgr->smgr_rlocator.locator.relNumber,
1694 : : smgr->smgr_rlocator.backend,
1695 : : true);
1696 : :
1697 [ + + ]: 82059005 : if (persistence == RELPERSISTENCE_TEMP)
1698 : 1779631 : pgBufferUsage.local_blks_hit += 1;
1699 : : else
1700 : 80279374 : pgBufferUsage.shared_blks_hit += 1;
1701 : :
1702 : 82059005 : pgstat_count_io_op(io_object, io_context, IOOP_HIT, 1, 0);
1703 : :
1704 [ + + ]: 82059005 : if (VacuumCostActive)
1705 : 284072 : VacuumCostBalance += VacuumCostPageHit;
1706 : :
1707 [ + + ]: 82059005 : if (rel)
1708 [ + + + + : 76385266 : pgstat_count_buffer_hit(rel);
+ + + + ]
1709 : 82059005 : }
1710 : :
1711 : : /*
1712 : : * Helper for WaitReadBuffers() that processes the results of a readv
1713 : : * operation, raising an error if necessary.
1714 : : */
1715 : : static void
561 1716 : 1372982 : ProcessReadBuffersResult(ReadBuffersOperation *operation)
1717 : : {
1718 : 1372982 : PgAioReturn *aio_ret = &operation->io_return;
1719 : 1372982 : PgAioResultStatus rs = aio_ret->result.status;
1720 : 1372982 : int newly_read_blocks = 0;
1721 : :
1722 [ - + ]: 1372982 : Assert(pgaio_wref_valid(&operation->io_wref));
1723 [ - + ]: 1372982 : Assert(aio_ret->result.status != PGAIO_RS_UNKNOWN);
1724 : :
1725 : : /*
1726 : : * SMGR reports the number of blocks successfully read as the result of
1727 : : * the IO operation. Thus we can simply add that to ->nblocks_done.
1728 : : */
1729 : :
1730 [ + + ]: 1372982 : if (likely(rs != PGAIO_RS_ERROR))
1731 : 1372953 : newly_read_blocks = aio_ret->result.result;
1732 : :
1733 [ + + + + ]: 1372982 : if (rs == PGAIO_RS_ERROR || rs == PGAIO_RS_WARNING)
1734 [ + + ]: 45 : pgaio_result_report(aio_ret->result, &aio_ret->target_data,
1735 : : rs == PGAIO_RS_ERROR ? ERROR : WARNING);
1736 [ + + ]: 1372937 : else if (aio_ret->result.status == PGAIO_RS_PARTIAL)
1737 : : {
1738 : : /*
1739 : : * We'll retry, so we just emit a debug message to the server log (or
1740 : : * not even that in prod scenarios).
1741 : : */
1742 : 109 : pgaio_result_report(aio_ret->result, &aio_ret->target_data, DEBUG1);
1743 [ + - ]: 109 : elog(DEBUG3, "partial read, will retry");
1744 : : }
1745 : :
1746 [ - + ]: 1372953 : Assert(newly_read_blocks > 0);
1747 [ - + ]: 1372953 : Assert(newly_read_blocks <= MAX_IO_COMBINE_LIMIT);
1748 : :
1749 : 1372953 : operation->nblocks_done += newly_read_blocks;
1750 : :
1751 [ - + ]: 1372953 : Assert(operation->nblocks_done <= operation->nblocks);
1752 : 1372953 : }
1753 : :
1754 : : /*
1755 : : * Wait for the IO operation initiated by StartReadBuffers() et al to
1756 : : * complete.
1757 : : *
1758 : : * Returns true if we needed to wait for the IO operation, false otherwise.
1759 : : */
1760 : : bool
922 tmunro@postgresql.or 1761 : 1374328 : WaitReadBuffers(ReadBuffersOperation *operation)
1762 : : {
561 andres@anarazel.de 1763 : 1374328 : PgAioReturn *aio_ret = &operation->io_return;
1764 : : IOContext io_context;
1765 : : IOObject io_object;
194 1766 : 1374328 : bool needed_wait = false;
1767 : :
561 1768 [ + + ]: 1374328 : if (operation->persistence == RELPERSISTENCE_TEMP)
1769 : : {
922 tmunro@postgresql.or 1770 : 2630 : io_context = IOCONTEXT_NORMAL;
1771 : 2630 : io_object = IOOBJECT_TEMP_RELATION;
1772 : : }
1773 : : else
1774 : : {
1775 : 1371698 : io_context = IOContextForStrategy(operation->strategy);
1776 : 1371698 : io_object = IOOBJECT_RELATION;
1777 : : }
1778 : :
1779 : : /*
1780 : : * If we get here without an IO operation having been issued, the
1781 : : * io_method == IOMETHOD_SYNC path must have been used. Otherwise the
1782 : : * caller should not have called WaitReadBuffers().
1783 : : *
1784 : : * In the case of IOMETHOD_SYNC, we start - as we used to before the
1785 : : * introducing of AIO - the IO in WaitReadBuffers(). This is done as part
1786 : : * of the retry logic below, no extra code is required.
1787 : : *
1788 : : * This path is expected to eventually go away.
1789 : : */
561 andres@anarazel.de 1790 [ + + + - ]: 1374328 : if (!pgaio_wref_valid(&operation->io_wref) && io_method != IOMETHOD_SYNC)
561 andres@anarazel.de 1791 [ # # ]:UBC 0 : elog(ERROR, "waiting for read operation that didn't read");
1792 : :
1793 : : /*
1794 : : * To handle partial reads, and IOMETHOD_SYNC, we re-issue IO until we're
1795 : : * done. We may need multiple retries, not just because we could get
1796 : : * multiple partial reads, but also because some of the remaining
1797 : : * to-be-read buffers may have been read in by other backends, limiting
1798 : : * the IO size.
1799 : : */
1800 : : while (true)
922 tmunro@postgresql.or 1801 :CBC 1468 : {
1802 : : int ignored_nblocks_progress;
1803 : :
561 andres@anarazel.de 1804 : 1375796 : CheckReadBuffersOperation(operation, false);
1805 : :
1806 : : /*
1807 : : * If there is an IO associated with the operation, we may need to
1808 : : * wait for it.
1809 : : */
1810 [ + + ]: 1375796 : if (pgaio_wref_valid(&operation->io_wref))
1811 : : {
1812 : : /*
1813 : : * Track the time spent waiting for the IO to complete. As
1814 : : * tracking a wait even if we don't actually need to wait
1815 : : *
1816 : : * a) is not cheap, due to the timestamping overhead
1817 : : *
1818 : : * b) reports some time as waiting, even if we never waited
1819 : : *
1820 : : * we first check if we already know the IO is complete.
1821 : : *
1822 : : * Note that operation->io_return is uninitialized for foreign IO,
1823 : : * so we cannot use the cheaper PGAIO_RS_UNKNOWN pre-check.
1824 : : */
199 1825 [ + + + + ]: 1374433 : if ((operation->foreign_io || aio_ret->result.status == PGAIO_RS_UNKNOWN) &&
561 1826 [ + + ]: 585060 : !pgaio_wref_check_done(&operation->io_wref))
1827 : 217143 : {
1828 : 217144 : instr_time io_start = pgstat_prepare_io_time(track_io_timing);
1829 : :
1830 : 217144 : pgaio_wref_wait(&operation->io_wref);
194 1831 : 217143 : needed_wait = true;
1832 : :
1833 : : /*
1834 : : * This just accounts for the wait time. The IO operation
1835 : : * itself was already counted earlier in AsyncReadBuffers() --
1836 : : * either by us or by another backend if this is a foreign IO.
1837 : : */
561 1838 : 217143 : pgstat_count_io_op_time(io_object, io_context, IOOP_READ,
1839 : : io_start, 0, 0);
1840 : : }
1841 : : else
1842 : : {
1843 [ - + ]: 1157289 : Assert(pgaio_wref_check_done(&operation->io_wref));
1844 : : }
1845 : :
199 1846 [ + + ]: 1374432 : if (unlikely(operation->foreign_io))
1847 : : {
1848 : 1450 : Buffer buffer = operation->buffers[operation->nblocks_done];
1849 : 1450 : BufferDesc *desc = BufferIsLocal(buffer) ?
1850 [ - + ]: 1450 : GetLocalBufferDescriptor(-buffer - 1) :
1851 : 1450 : GetBufferDescriptor(buffer - 1);
1852 : 1450 : uint64 buf_state = pg_atomic_read_u64(&desc->state);
1853 : :
1854 [ + + ]: 1450 : if (buf_state & BM_VALID)
1855 : : {
1856 : 1448 : BlockNumber blocknum = operation->blocknum + operation->nblocks_done;
1857 : :
1858 : 1448 : operation->nblocks_done += 1;
1859 [ - + ]: 1448 : Assert(operation->nblocks_done <= operation->nblocks);
1860 : :
1861 : : /*
1862 : : * Track this as a 'hit' for this backend. The backend
1863 : : * performing the IO will track it as a 'read'.
1864 : : */
1865 : 1448 : TrackBufferHit(io_object, io_context,
1866 : 1448 : operation->rel, operation->persistence,
1867 : : operation->smgr, operation->forknum,
1868 : : blocknum);
1869 : : }
1870 : :
1871 : : /*
1872 : : * If the foreign IO failed and left the buffer invalid,
1873 : : * nblocks_done is not incremented. The retry loop below will
1874 : : * call AsyncReadBuffers() which will attempt the IO itself.
1875 : : */
1876 : : }
1877 : : else
1878 : : {
1879 : : /*
1880 : : * We now are sure the IO completed. Check the results. This
1881 : : * includes reporting on errors if there were any.
1882 : : */
1883 : 1372982 : ProcessReadBuffersResult(operation);
1884 : : }
1885 : : }
1886 : :
1887 : : /*
1888 : : * Most of the time, the one IO we already started, will read in
1889 : : * everything. But we need to deal with partial reads and buffers not
1890 : : * needing IO anymore.
1891 : : */
561 1892 [ + + ]: 1375766 : if (operation->nblocks_done == operation->nblocks)
1893 : 1374298 : break;
1894 : :
1895 [ - + ]: 1468 : CHECK_FOR_INTERRUPTS();
1896 : :
1897 : : /*
1898 : : * If the IO completed only partially, we need to perform additional
1899 : : * work, consider that a form of having had to wait.
1900 : : */
194 1901 : 1468 : needed_wait = true;
1902 : :
1903 : : /*
1904 : : * This may only complete the IO partially, either because some
1905 : : * buffers were already valid, or because of a partial read.
1906 : : *
1907 : : * NB: In contrast to after the AsyncReadBuffers() call in
1908 : : * StartReadBuffers(), we do *not* reduce
1909 : : * ReadBuffersOperation->nblocks here, callers expect the full
1910 : : * operation to be completed at this point (as more operations may
1911 : : * have been queued).
1912 : : */
561 1913 : 1468 : AsyncReadBuffers(operation, &ignored_nblocks_progress);
1914 : : }
1915 : :
1916 : 1374298 : CheckReadBuffersOperation(operation, true);
1917 : :
1918 : : /* NB: READ_DONE tracepoint was already executed in completion callback */
194 1919 : 1374298 : return needed_wait;
1920 : : }
1921 : :
1922 : : /*
1923 : : * Initiate IO for the ReadBuffersOperation
1924 : : *
1925 : : * This function only starts a single IO at a time. The size of the IO may be
1926 : : * limited to below the to-be-read blocks, if one of the buffers has
1927 : : * concurrently been read in. If the first to-be-read buffer is already valid,
1928 : : * no IO will be issued.
1929 : : *
1930 : : * To support retries after partial reads, the first operation->nblocks_done
1931 : : * buffers are skipped.
1932 : : *
1933 : : * On return *nblocks_progress is updated to reflect the number of buffers
1934 : : * affected by the call. If the first buffer is valid, *nblocks_progress is
1935 : : * set to 1 and operation->nblocks_done is incremented.
1936 : : *
1937 : : * Returns true if IO was initiated or is already in progress (foreign IO),
1938 : : * false if the buffer was already valid.
1939 : : */
1940 : : static bool
561 1941 : 1375345 : AsyncReadBuffers(ReadBuffersOperation *operation, int *nblocks_progress)
1942 : : {
1943 : 1375345 : Buffer *buffers = &operation->buffers[0];
1944 : 1375345 : int flags = operation->flags;
1945 : 1375345 : ForkNumber forknum = operation->forknum;
1946 : 1375345 : char persistence = operation->persistence;
1947 : 1375345 : int16 nblocks_done = operation->nblocks_done;
200 1948 : 1375345 : BlockNumber blocknum = operation->blocknum + nblocks_done;
561 1949 : 1375345 : Buffer *io_buffers = &operation->buffers[nblocks_done];
1950 : 1375345 : int io_buffers_len = 0;
1951 : : PgAioHandle *ioh;
1952 : 1375345 : uint32 ioh_flags = 0;
1953 : : void *io_pages[MAX_IO_COMBINE_LIMIT];
1954 : : IOContext io_context;
1955 : : IOObject io_object;
1956 : : instr_time io_start;
1957 : : StartBufferIOResult status;
1958 : :
1959 [ + + ]: 1375345 : if (persistence == RELPERSISTENCE_TEMP)
1960 : : {
1961 : 3018 : io_context = IOCONTEXT_NORMAL;
1962 : 3018 : io_object = IOOBJECT_TEMP_RELATION;
1963 : : }
1964 : : else
1965 : : {
1966 : 1372327 : io_context = IOContextForStrategy(operation->strategy);
1967 : 1372327 : io_object = IOOBJECT_RELATION;
1968 : : }
1969 : :
1970 : : /*
1971 : : * When this IO is executed synchronously, either because the caller will
1972 : : * immediately block waiting for the IO or because IOMETHOD_SYNC is used,
1973 : : * the AIO subsystem needs to know.
1974 : : */
200 1975 [ + + ]: 1375345 : if (flags & READ_BUFFERS_SYNCHRONOUSLY)
1976 : 781108 : ioh_flags |= PGAIO_HF_SYNCHRONOUS;
1977 : :
1978 [ + + ]: 1375345 : if (persistence == RELPERSISTENCE_TEMP)
1979 : 3018 : ioh_flags |= PGAIO_HF_REFERENCES_LOCAL;
1980 : :
1981 : : /*
1982 : : * If zero_damaged_pages is enabled, add the READ_BUFFERS_ZERO_ON_ERROR
1983 : : * flag. The reason for that is that, hopefully, zero_damaged_pages isn't
1984 : : * set globally, but on a per-session basis. The completion callback,
1985 : : * which may be run in other processes, e.g. in IO workers, may have a
1986 : : * different value of the zero_damaged_pages GUC.
1987 : : *
1988 : : * XXX: We probably should eventually use a different flag for
1989 : : * zero_damaged_pages, so we can report different log levels / error codes
1990 : : * for zero_damaged_pages and ZERO_ON_ERROR.
1991 : : */
561 1992 [ + + ]: 1375345 : if (zero_damaged_pages)
1993 : 16 : flags |= READ_BUFFERS_ZERO_ON_ERROR;
1994 : :
1995 : : /*
1996 : : * For the same reason as with zero_damaged_pages we need to use this
1997 : : * backend's ignore_checksum_failure value.
1998 : : */
1999 [ + + ]: 1375345 : if (ignore_checksum_failure)
2000 : 8 : flags |= READ_BUFFERS_IGNORE_CHECKSUM_FAILURES;
2001 : :
2002 : :
2003 : : /*
2004 : : * To be allowed to report stats in the local completion callback we need
2005 : : * to prepare to report stats now. This ensures we can safely report the
2006 : : * checksum failure even in a critical section.
2007 : : */
2008 : 1375345 : pgstat_prepare_report_checksum_failure(operation->smgr->smgr_rlocator.locator.dbOid);
2009 : :
2010 : : /*
2011 : : * We must get an IO handle before StartBufferIO(), as pgaio_io_acquire()
2012 : : * might block, which we don't want after setting IO_IN_PROGRESS. If we
2013 : : * don't need to do the IO, we'll release the handle.
2014 : : *
2015 : : * If we need to wait for IO before we can get a handle, submit
2016 : : * already-staged IO first, so that other backends don't need to wait.
2017 : : * There wouldn't be a deadlock risk, as pgaio_io_acquire() just needs to
2018 : : * wait for already submitted IO, which doesn't require additional locks,
2019 : : * but it could still cause undesirable waits.
2020 : : *
2021 : : * A secondary benefit is that this would allow us to measure the time in
2022 : : * pgaio_io_acquire() without causing undue timer overhead in the common,
2023 : : * non-blocking, case. However, currently the pgstats infrastructure
2024 : : * doesn't really allow that because it doesn't have an API to report
2025 : : * "accumulated" time.
2026 : : */
2027 : 1375345 : ioh = pgaio_io_acquire_nb(CurrentResourceOwner, &operation->io_return);
2028 [ + + ]: 1375345 : if (unlikely(!ioh))
2029 : : {
2030 : 3486 : pgaio_submit_staged();
2031 : 3486 : ioh = pgaio_io_acquire(CurrentResourceOwner, &operation->io_return);
2032 : : }
2033 : :
199 2034 : 1375345 : operation->foreign_io = false;
2035 : 1375345 : pgaio_wref_clear(&operation->io_wref);
2036 : :
2037 : : /*
2038 : : * Try to start IO on the first buffer in a new run of blocks. If AIO is
2039 : : * in progress, be it in this backend or another backend, we just
2040 : : * associate the wait reference with the operation and wait in
2041 : : * WaitReadBuffers(). This turns out to be important for performance in
2042 : : * two workloads:
2043 : : *
2044 : : * 1) A read stream that has to read the same block multiple times within
2045 : : * the readahead distance. This can happen e.g. for the table accesses of
2046 : : * an index scan.
2047 : : *
2048 : : * 2) Concurrent scans by multiple backends on the same relation.
2049 : : *
2050 : : * If we were to synchronously wait for the in-progress IO, we'd not be
2051 : : * able to keep enough I/O in flight.
2052 : : *
2053 : : * If we do find there is ongoing I/O for the buffer, we set up a 1-block
2054 : : * ReadBuffersOperation that WaitReadBuffers then can wait on.
2055 : : *
2056 : : * It's possible that another backend has started IO on the buffer but not
2057 : : * yet set its wait reference. In this case, we have no choice but to wait
2058 : : * for either the wait reference to be valid or the IO to be done.
2059 : : */
2060 : 1375345 : status = StartBufferIO(buffers[nblocks_done], true, true,
2061 : : &operation->io_wref);
2062 [ + + ]: 1375345 : if (status != BUFFER_IO_READY_FOR_IO)
2063 : : {
2064 : 1953 : pgaio_io_release(ioh);
561 2065 : 1953 : *nblocks_progress = 1;
199 2066 [ + + ]: 1953 : if (status == BUFFER_IO_ALREADY_DONE)
2067 : : {
2068 : : /*
2069 : : * Someone has already completed this block, we're done.
2070 : : *
2071 : : * When IO is necessary, ->nblocks_done is updated in
2072 : : * ProcessReadBuffersResult(), but that is not called if no IO is
2073 : : * necessary. Thus update here.
2074 : : */
2075 : 503 : operation->nblocks_done += 1;
2076 [ - + ]: 503 : Assert(operation->nblocks_done <= operation->nblocks);
2077 : :
2078 [ - + ]: 503 : Assert(!pgaio_wref_valid(&operation->io_wref));
2079 : :
2080 : : /*
2081 : : * Report and track this as a 'hit' for this backend, even though
2082 : : * it must have started out as a miss in PinBufferForBlock(). The
2083 : : * other backend will track this as a 'read'.
2084 : : */
2085 : 503 : TrackBufferHit(io_object, io_context,
2086 : 503 : operation->rel, operation->persistence,
2087 : : operation->smgr, operation->forknum,
2088 : : blocknum);
2089 : 503 : return false;
2090 : : }
2091 : :
2092 : : /* The IO is already in-progress */
2093 [ - + ]: 1450 : Assert(status == BUFFER_IO_IN_PROGRESS);
2094 [ - + ]: 1450 : Assert(pgaio_wref_valid(&operation->io_wref));
2095 : 1450 : operation->foreign_io = true;
2096 : :
2097 : 1450 : return true;
2098 : : }
2099 : :
200 2100 [ - + ]: 1373392 : Assert(io_buffers[0] == buffers[nblocks_done]);
2101 : 1373392 : io_pages[0] = BufferGetBlock(buffers[nblocks_done]);
2102 : 1373392 : io_buffers_len = 1;
2103 : :
2104 : : /*
2105 : : * NB: As little code as possible should be added between the
2106 : : * StartBufferIO() above, the further StartBufferIO()s below and the
2107 : : * smgrstartreadv(), as some of the buffers are now marked as
2108 : : * IO_IN_PROGRESS and will thus cause other backends to wait.
2109 : : */
2110 : :
2111 : : /*
2112 : : * How many neighboring-on-disk blocks can we scatter-read into other
2113 : : * buffers at the same time? In this case we don't wait if we see an I/O
2114 : : * already in progress (see comment above).
2115 : : */
2116 [ + + ]: 1548847 : for (int i = nblocks_done + 1; i < operation->nblocks; i++)
2117 : : {
2118 : : /* Must be consecutive block numbers. */
2119 [ - + ]: 175459 : Assert(BufferGetBlockNumber(buffers[i - 1]) ==
2120 : : BufferGetBlockNumber(buffers[i]) - 1);
2121 : :
199 2122 : 175459 : status = StartBufferIO(buffers[i], true, false, NULL);
2123 [ + + ]: 175459 : if (status != BUFFER_IO_READY_FOR_IO)
200 2124 : 4 : break;
2125 : :
2126 [ - + ]: 175455 : Assert(io_buffers[io_buffers_len] == buffers[i]);
2127 : :
2128 : 175455 : io_pages[io_buffers_len++] = BufferGetBlock(buffers[i]);
2129 : : }
2130 : :
2131 : : /* get a reference to wait for in WaitReadBuffers() */
2132 : 1373392 : pgaio_io_get_wref(ioh, &operation->io_wref);
2133 : :
2134 : : /* provide the list of buffers to the completion callbacks */
2135 : 1373392 : pgaio_io_set_handle_data_32(ioh, (uint32 *) io_buffers, io_buffers_len);
2136 : :
2137 [ + + ]: 1373392 : pgaio_io_register_callbacks(ioh,
2138 : : persistence == RELPERSISTENCE_TEMP ?
2139 : : PGAIO_HCB_LOCAL_BUFFER_READV :
2140 : : PGAIO_HCB_SHARED_BUFFER_READV,
2141 : : flags);
2142 : :
2143 : 1373392 : pgaio_io_set_flag(ioh, ioh_flags);
2144 : :
2145 : : /* ---
2146 : : * Even though we're trying to issue IO asynchronously, track the time
2147 : : * in smgrstartreadv():
2148 : : * - if io_method == IOMETHOD_SYNC, we will always perform the IO
2149 : : * immediately
2150 : : * - the io method might not support the IO (e.g. worker IO for a temp
2151 : : * table)
2152 : : * ---
2153 : : */
2154 : 1373392 : io_start = pgstat_prepare_io_time(track_io_timing);
2155 : 1373392 : smgrstartreadv(ioh, operation->smgr, forknum,
2156 : : blocknum,
2157 : : io_pages, io_buffers_len);
2158 : 1373377 : pgstat_count_io_op_time(io_object, io_context, IOOP_READ,
2159 : 1373377 : io_start, 1, io_buffers_len * BLCKSZ);
2160 : :
2161 [ + + ]: 1373377 : if (persistence == RELPERSISTENCE_TEMP)
2162 : 3016 : pgBufferUsage.local_blks_read += io_buffers_len;
2163 : : else
2164 : 1370361 : pgBufferUsage.shared_blks_read += io_buffers_len;
2165 : :
2166 : : /*
2167 : : * Track vacuum cost when issuing IO, not after waiting for it. Otherwise
2168 : : * we could end up issuing a lot of IO in a short timespan, despite a low
2169 : : * cost limit.
2170 : : */
2171 [ + + ]: 1373377 : if (VacuumCostActive)
2172 : 24184 : VacuumCostBalance += VacuumCostPageMiss * io_buffers_len;
2173 : :
2174 : 1373377 : *nblocks_progress = io_buffers_len;
2175 : :
2176 : 1373377 : return true;
2177 : : }
2178 : :
2179 : : /*
2180 : : * BufferAlloc -- subroutine for PinBufferForBlock. Handles lookup of a shared
2181 : : * buffer. If no buffer exists already, selects a replacement victim and
2182 : : * evicts the old page, but does NOT read in new page.
2183 : : *
2184 : : * "strategy" can be a buffer replacement strategy object, or NULL for
2185 : : * the default strategy. The selected buffer's usage_count is advanced when
2186 : : * using the default strategy, but otherwise possibly not (see PinBuffer).
2187 : : *
2188 : : * The returned buffer is pinned and is already marked as holding the
2189 : : * desired page. If it already did have the desired page, *foundPtr is
2190 : : * set true. Otherwise, *foundPtr is set false.
2191 : : *
2192 : : * io_context is passed as an output parameter to avoid calling
2193 : : * IOContextForStrategy() when there is a shared buffers hit and no IO
2194 : : * statistics need be captured.
2195 : : *
2196 : : * No locks are held either at entry or exit.
2197 : : */
2198 : : static pg_always_inline BufferDesc *
5766 rhaas@postgresql.org 2199 : 82134897 : BufferAlloc(SMgrRelation smgr, char relpersistence, ForkNumber forkNum,
2200 : : BlockNumber blockNum,
2201 : : BufferAccessStrategy strategy,
2202 : : bool *foundPtr, IOContext io_context)
2203 : : {
2204 : : BufferTag newTag; /* identity of requested block */
2205 : : uint32 newHash; /* hash value for newTag */
2206 : : LWLock *newPartitionLock; /* buffer partition lock for it */
2207 : : int existing_buf_id;
2208 : : Buffer victim_buffer;
2209 : : BufferDesc *victim_buf_hdr;
2210 : : uint64 victim_buf_state;
270 andres@anarazel.de 2211 : 82134897 : uint64 set_bits = 0;
2212 : :
2213 : : /* Make sure we will have room to remember the buffer pin */
1069 heikki.linnakangas@i 2214 : 82134897 : ResourceOwnerEnlarge(CurrentResourceOwner);
2215 : 82134897 : ReservePrivateRefCountEntry();
2216 : :
2217 : : /* create a tag so we can lookup the buffer */
1538 rhaas@postgresql.org 2218 : 82134897 : InitBufferTag(&newTag, &smgr->smgr_rlocator.locator, forkNum, blockNum);
2219 : :
2220 : : /* determine its hash code and partition lock ID */
7386 tgl@sss.pgh.pa.us 2221 : 82134897 : newHash = BufTableHashCode(&newTag);
2222 : 82134897 : newPartitionLock = BufMappingPartitionLock(newHash);
2223 : :
2224 : : /* see if the block is in the buffer pool already */
2225 : 82134897 : LWLockAcquire(newPartitionLock, LW_SHARED);
1286 andres@anarazel.de 2226 : 82134897 : existing_buf_id = BufTableLookup(&newTag, newHash);
2227 [ + + ]: 82134897 : if (existing_buf_id >= 0)
2228 : : {
2229 : : BufferDesc *buf;
2230 : : bool valid;
2231 : :
2232 : : /*
2233 : : * Found it. Now, pin the buffer so no one can steal it from the
2234 : : * buffer pool, and check to see if the correct data has been loaded
2235 : : * into the buffer.
2236 : : */
2237 : 80278765 : buf = GetBufferDescriptor(existing_buf_id);
2238 : :
369 2239 : 80278765 : valid = PinBuffer(buf, strategy, false);
2240 : :
2241 : : /* Can release the mapping lock as soon as we've pinned it */
7386 tgl@sss.pgh.pa.us 2242 : 80278765 : LWLockRelease(newPartitionLock);
2243 : :
3344 peter_e@gmx.net 2244 : 80278765 : *foundPtr = true;
2245 : :
7892 tgl@sss.pgh.pa.us 2246 [ + + ]: 80278765 : if (!valid)
2247 : : {
2248 : : /*
2249 : : * We can only get here if (a) someone else is still reading in
2250 : : * the page, (b) a previous read attempt failed, or (c) someone
2251 : : * called StartReadBuffers() but not yet WaitReadBuffers().
2252 : : */
922 tmunro@postgresql.or 2253 : 1599 : *foundPtr = false;
2254 : : }
2255 : :
10268 bruce@momjian.us 2256 : 80278765 : return buf;
2257 : : }
2258 : :
2259 : : /*
2260 : : * Didn't find it in the buffer pool. We'll have to initialize a new
2261 : : * buffer. Remember to unlock the mapping lock while doing the work.
2262 : : */
7386 tgl@sss.pgh.pa.us 2263 : 1856132 : LWLockRelease(newPartitionLock);
2264 : :
2265 : : /*
2266 : : * Acquire a victim buffer. Somebody else might try to do the same, we
2267 : : * don't hold any conflicting locks. If so we'll have to undo our work
2268 : : * later.
2269 : : */
1286 andres@anarazel.de 2270 : 1856132 : victim_buffer = GetVictimBuffer(strategy, io_context);
2271 : 1856132 : victim_buf_hdr = GetBufferDescriptor(victim_buffer - 1);
2272 : :
2273 : : /*
2274 : : * Try to make a hashtable entry for the buffer under its new tag. If
2275 : : * somebody else inserted another buffer for the tag, we'll release the
2276 : : * victim buffer we acquired and use the already inserted one.
2277 : : */
2278 : 1856132 : LWLockAcquire(newPartitionLock, LW_EXCLUSIVE);
2279 : 1856132 : existing_buf_id = BufTableInsert(&newTag, newHash, victim_buf_hdr->buf_id);
2280 [ + + ]: 1856132 : if (existing_buf_id >= 0)
2281 : : {
2282 : : BufferDesc *existing_buf_hdr;
2283 : : bool valid;
2284 : :
2285 : : /*
2286 : : * Got a collision. Someone has already done what we were about to do.
2287 : : * We'll just handle this as if it were found in the buffer pool in
2288 : : * the first place. First, give up the buffer we were planning to
2289 : : * use.
2290 : : *
2291 : : * We could do this after releasing the partition lock, but then we'd
2292 : : * have to call ResourceOwnerEnlarge() & ReservePrivateRefCountEntry()
2293 : : * before acquiring the lock, for the rare case of such a collision.
2294 : : */
2295 : 664 : UnpinBuffer(victim_buf_hdr);
2296 : :
2297 : : /* remaining code should match code at top of routine */
2298 : :
2299 : 664 : existing_buf_hdr = GetBufferDescriptor(existing_buf_id);
2300 : :
369 2301 : 664 : valid = PinBuffer(existing_buf_hdr, strategy, false);
2302 : :
2303 : : /* Can release the mapping lock as soon as we've pinned it */
1286 2304 : 664 : LWLockRelease(newPartitionLock);
2305 : :
2306 : 664 : *foundPtr = true;
2307 : :
2308 [ + + ]: 664 : if (!valid)
2309 : : {
2310 : : /*
2311 : : * We can only get here if (a) someone else is still reading in
2312 : : * the page, (b) a previous read attempt failed, or (c) someone
2313 : : * called StartReadBuffers() but not yet WaitReadBuffers().
2314 : : */
922 tmunro@postgresql.or 2315 : 405 : *foundPtr = false;
2316 : : }
2317 : :
1286 andres@anarazel.de 2318 : 664 : return existing_buf_hdr;
2319 : : }
2320 : :
2321 : : /*
2322 : : * Need to lock the buffer header too in order to change its tag.
2323 : : */
2324 : 1855468 : victim_buf_state = LockBufHdr(victim_buf_hdr);
2325 : :
2326 : : /* some sanity checks while we hold the buffer header lock */
2327 [ - + ]: 1855468 : Assert(BUF_STATE_GET_REFCOUNT(victim_buf_state) == 1);
2328 [ - + ]: 1855468 : Assert(!(victim_buf_state & (BM_TAG_VALID | BM_VALID | BM_DIRTY | BM_IO_IN_PROGRESS)));
2329 : :
2330 : 1855468 : victim_buf_hdr->tag = newTag;
2331 : :
2332 : : /*
2333 : : * Make sure BM_PERMANENT is set for buffers that must be written at every
2334 : : * checkpoint. Unlogged buffers only need to be written at shutdown
2335 : : * checkpoints, except for their "init" forks, which need to be treated
2336 : : * just like permanent relations.
2337 : : */
340 2338 : 1855468 : set_bits |= BM_TAG_VALID | BUF_USAGECOUNT_ONE;
3499 rhaas@postgresql.org 2339 [ + + + + ]: 1855468 : if (relpersistence == RELPERSISTENCE_PERMANENT || forkNum == INIT_FORKNUM)
340 andres@anarazel.de 2340 : 1855075 : set_bits |= BM_PERMANENT;
2341 : :
2342 : 1855468 : UnlockBufHdrExt(victim_buf_hdr, victim_buf_state,
2343 : : set_bits, 0, 0);
2344 : :
7386 tgl@sss.pgh.pa.us 2345 : 1855468 : LWLockRelease(newPartitionLock);
2346 : :
2347 : : /*
2348 : : * Buffer contents are currently invalid.
2349 : : */
922 tmunro@postgresql.or 2350 : 1855468 : *foundPtr = false;
2351 : :
1286 andres@anarazel.de 2352 : 1855468 : return victim_buf_hdr;
2353 : : }
2354 : :
2355 : : /*
2356 : : * InvalidateBuffer -- mark a shared buffer invalid.
2357 : : *
2358 : : * The buffer header spinlock must be held at entry. We drop it before
2359 : : * returning. (This is sane because the caller must have locked the
2360 : : * buffer in order to be sure it should be dropped.)
2361 : : *
2362 : : * This is used only in contexts such as dropping a relation. We assume
2363 : : * that no other backend could possibly be interested in using the page,
2364 : : * so the only reason the buffer might be pinned is if someone else is
2365 : : * trying to write it out. We have to let them finish before we can
2366 : : * reclaim the buffer.
2367 : : *
2368 : : * The buffer could get reclaimed by someone else while we are waiting
2369 : : * to acquire the necessary locks; if so, don't mess it up.
2370 : : */
2371 : : static void
3983 rhaas@postgresql.org 2372 : 131676 : InvalidateBuffer(BufferDesc *buf)
2373 : : {
2374 : : BufferTag oldTag;
2375 : : uint32 oldHash; /* hash value for oldTag */
2376 : : LWLock *oldPartitionLock; /* buffer partition lock for it */
2377 : : uint32 oldFlags;
2378 : : uint64 buf_state;
2379 : :
2380 : : /* Save the original buffer tag before dropping the spinlock */
7892 tgl@sss.pgh.pa.us 2381 : 131676 : oldTag = buf->tag;
2382 : :
340 andres@anarazel.de 2383 : 131676 : UnlockBufHdr(buf);
2384 : :
2385 : : /*
2386 : : * Need to compute the old tag's hashcode and partition lock ID. XXX is it
2387 : : * worth storing the hashcode in BufferDesc so we need not recompute it
2388 : : * here? Probably not.
2389 : : */
7386 tgl@sss.pgh.pa.us 2390 : 131676 : oldHash = BufTableHashCode(&oldTag);
2391 : 131676 : oldPartitionLock = BufMappingPartitionLock(oldHash);
2392 : :
7892 2393 : 131680 : retry:
2394 : :
2395 : : /*
2396 : : * Acquire exclusive mapping lock in preparation for changing the buffer's
2397 : : * association.
2398 : : */
7386 2399 : 131680 : LWLockAcquire(oldPartitionLock, LW_EXCLUSIVE);
2400 : :
2401 : : /* Re-lock the buffer header */
3837 andres@anarazel.de 2402 : 131680 : buf_state = LockBufHdr(buf);
2403 : :
2404 : : /* If it's changed while we were waiting for lock, do nothing */
1538 rhaas@postgresql.org 2405 [ + + ]: 131680 : if (!BufferTagsEqual(&buf->tag, &oldTag))
2406 : : {
340 andres@anarazel.de 2407 : 4 : UnlockBufHdr(buf);
7386 tgl@sss.pgh.pa.us 2408 : 4 : LWLockRelease(oldPartitionLock);
7892 2409 : 4 : return;
2410 : : }
2411 : :
2412 : : /*
2413 : : * We assume the reason for it to be pinned is that either we were
2414 : : * asynchronously reading the page in before erroring out or someone else
2415 : : * is flushing the page out. Wait for the IO to finish. (This could be
2416 : : * an infinite loop if the refcount is messed up... it would be nice to
2417 : : * time out after awhile, but there seems no way to be sure how many loops
2418 : : * may be needed. Note that if the other guy has pinned the buffer but
2419 : : * not yet done StartBufferIO, WaitIO will fall through and we'll
2420 : : * effectively be busy-looping here.)
2421 : : */
3837 andres@anarazel.de 2422 [ + + ]: 131676 : if (BUF_STATE_GET_REFCOUNT(buf_state) != 0)
2423 : : {
340 2424 : 4 : UnlockBufHdr(buf);
7386 tgl@sss.pgh.pa.us 2425 : 4 : LWLockRelease(oldPartitionLock);
2426 : : /* safety check: should definitely not be our *own* pin */
4079 andres@anarazel.de 2427 [ - + ]: 4 : if (GetPrivateRefCount(BufferDescriptorGetBuffer(buf)) > 0)
7878 tgl@sss.pgh.pa.us 2428 [ # # ]:UBC 0 : elog(ERROR, "buffer is pinned in InvalidateBuffer");
7892 tgl@sss.pgh.pa.us 2429 :CBC 4 : WaitIO(buf);
2430 : 4 : goto retry;
2431 : : }
2432 : :
2433 : : /*
2434 : : * An invalidated buffer should not have any backends waiting to lock the
2435 : : * buffer, therefore BM_LOCK_WAKE_IN_PROGRESS should not be set.
2436 : : */
270 andres@anarazel.de 2437 [ - + ]: 131672 : Assert(!(buf_state & BM_LOCK_WAKE_IN_PROGRESS));
2438 : :
2439 : : /*
2440 : : * Clear out the buffer's tag and flags. We must do this to ensure that
2441 : : * linear scans of the buffer array don't think the buffer is valid.
2442 : : */
3837 2443 : 131672 : oldFlags = buf_state & BUF_FLAG_MASK;
1538 rhaas@postgresql.org 2444 : 131672 : ClearBufferTag(&buf->tag);
2445 : :
340 andres@anarazel.de 2446 : 131672 : UnlockBufHdrExt(buf, buf_state,
2447 : : 0,
2448 : : BUF_FLAG_MASK | BUF_USAGECOUNT_MASK,
2449 : : 0);
2450 : :
2451 : : /*
2452 : : * Remove the buffer from the lookup hashtable, if it was in there.
2453 : : */
7892 tgl@sss.pgh.pa.us 2454 [ + - ]: 131672 : if (oldFlags & BM_TAG_VALID)
7386 2455 : 131672 : BufTableDelete(&oldTag, oldHash);
2456 : :
2457 : : /*
2458 : : * Done with mapping lock.
2459 : : */
2460 : 131672 : LWLockRelease(oldPartitionLock);
2461 : : }
2462 : :
2463 : : /*
2464 : : * Helper routine for GetVictimBuffer()
2465 : : *
2466 : : * Needs to be called on a buffer with a valid tag, pinned, but without the
2467 : : * buffer header spinlock held.
2468 : : *
2469 : : * Returns true if the buffer can be reused, in which case the buffer is only
2470 : : * pinned by this backend and marked as invalid, false otherwise.
2471 : : */
2472 : : static bool
1286 andres@anarazel.de 2473 : 1309769 : InvalidateVictimBuffer(BufferDesc *buf_hdr)
2474 : : {
2475 : : uint64 buf_state;
2476 : : uint32 hash;
2477 : : LWLock *partition_lock;
2478 : : BufferTag tag;
2479 : :
2480 [ - + ]: 1309769 : Assert(GetPrivateRefCount(BufferDescriptorGetBuffer(buf_hdr)) == 1);
2481 : :
2482 : : /* have buffer pinned, so it's safe to read tag without lock */
2483 : 1309769 : tag = buf_hdr->tag;
2484 : :
2485 : 1309769 : hash = BufTableHashCode(&tag);
2486 : 1309769 : partition_lock = BufMappingPartitionLock(hash);
2487 : :
2488 : 1309769 : LWLockAcquire(partition_lock, LW_EXCLUSIVE);
2489 : :
2490 : : /* lock the buffer header */
2491 : 1309769 : buf_state = LockBufHdr(buf_hdr);
2492 : :
2493 : : /*
2494 : : * We have the buffer pinned nobody else should have been able to unset
2495 : : * this concurrently.
2496 : : */
2497 [ - + ]: 1309769 : Assert(buf_state & BM_TAG_VALID);
2498 [ - + ]: 1309769 : Assert(BUF_STATE_GET_REFCOUNT(buf_state) > 0);
2499 [ - + ]: 1309769 : Assert(BufferTagsEqual(&buf_hdr->tag, &tag));
2500 : :
2501 : : /*
2502 : : * If somebody else pinned the buffer since, or even worse, dirtied it,
2503 : : * give up on this buffer: It's clearly in use.
2504 : : */
2505 [ + + + + ]: 1309769 : if (BUF_STATE_GET_REFCOUNT(buf_state) != 1 || (buf_state & BM_DIRTY))
2506 : : {
2507 [ - + ]: 382 : Assert(BUF_STATE_GET_REFCOUNT(buf_state) > 0);
2508 : :
340 2509 : 382 : UnlockBufHdr(buf_hdr);
1286 2510 : 382 : LWLockRelease(partition_lock);
2511 : :
2512 : 382 : return false;
2513 : : }
2514 : :
2515 : : /*
2516 : : * An invalidated buffer should not have any backends waiting to lock the
2517 : : * buffer, therefore BM_LOCK_WAKE_IN_PROGRESS should not be set.
2518 : : */
270 2519 [ - + ]: 1309387 : Assert(!(buf_state & BM_LOCK_WAKE_IN_PROGRESS));
2520 : :
2521 : : /*
2522 : : * Clear out the buffer's tag and flags and usagecount. This is not
2523 : : * strictly required, as BM_TAG_VALID/BM_VALID needs to be checked before
2524 : : * doing anything with the buffer. But currently it's beneficial, as the
2525 : : * cheaper pre-check for several linear scans of shared buffers use the
2526 : : * tag (see e.g. FlushDatabaseBuffers()).
2527 : : */
1286 2528 : 1309387 : ClearBufferTag(&buf_hdr->tag);
340 2529 : 1309387 : UnlockBufHdrExt(buf_hdr, buf_state,
2530 : : 0,
2531 : : BUF_FLAG_MASK | BUF_USAGECOUNT_MASK,
2532 : : 0);
2533 : :
1286 2534 [ - + ]: 1309387 : Assert(BUF_STATE_GET_REFCOUNT(buf_state) > 0);
2535 : :
2536 : : /* finally delete buffer from the buffer mapping table */
2537 : 1309387 : BufTableDelete(&tag, hash);
2538 : :
2539 : 1309387 : LWLockRelease(partition_lock);
2540 : :
270 2541 : 1309387 : buf_state = pg_atomic_read_u64(&buf_hdr->state);
1286 2542 [ - + ]: 1309387 : Assert(!(buf_state & (BM_DIRTY | BM_VALID | BM_TAG_VALID)));
2543 [ - + ]: 1309387 : Assert(BUF_STATE_GET_REFCOUNT(buf_state) > 0);
270 2544 [ - + ]: 1309387 : Assert(BUF_STATE_GET_REFCOUNT(pg_atomic_read_u64(&buf_hdr->state)) > 0);
2545 : :
1286 2546 : 1309387 : return true;
2547 : : }
2548 : :
2549 : : static Buffer
2550 : 2132455 : GetVictimBuffer(BufferAccessStrategy strategy, IOContext io_context)
2551 : : {
2552 : : BufferDesc *buf_hdr;
2553 : : Buffer buf;
2554 : : uint64 buf_state;
2555 : : bool from_ring;
2556 : :
2557 : : /*
2558 : : * Ensure, before we pin a victim buffer, that there's a free refcount
2559 : : * entry and resource owner slot for the pin.
2560 : : */
2561 : 2132455 : ReservePrivateRefCountEntry();
1069 heikki.linnakangas@i 2562 : 2132455 : ResourceOwnerEnlarge(CurrentResourceOwner);
2563 : :
2564 : : /* we return here if a prospective victim buffer gets used concurrently */
1286 andres@anarazel.de 2565 : 22112 : again:
2566 : :
2567 : : /*
2568 : : * Select a victim buffer. The buffer is returned pinned and owned by
2569 : : * this backend.
2570 : : */
2571 : 2154567 : buf_hdr = StrategyGetBuffer(strategy, &buf_state, &from_ring);
2572 : 2154567 : buf = BufferDescriptorGetBuffer(buf_hdr);
2573 : :
2574 : : /*
2575 : : * We shouldn't have any other pins for this buffer.
2576 : : */
2577 : 2154567 : CheckBufferIsPinnedOnce(buf);
2578 : :
2579 : : /*
2580 : : * If the buffer was dirty, try to write it out. There is a race
2581 : : * condition here, another backend could dirty the buffer between
2582 : : * StrategyGetBuffer() checking that it is not in use and invalidating the
2583 : : * buffer below. That's addressed by InvalidateVictimBuffer() verifying
2584 : : * that the buffer is not dirty.
2585 : : */
2586 [ + + ]: 2154567 : if (buf_state & BM_DIRTY)
2587 : : {
2588 [ - + ]: 354404 : Assert(buf_state & BM_TAG_VALID);
2589 [ - + ]: 354404 : Assert(buf_state & BM_VALID);
2590 : :
2591 : : /*
2592 : : * We need a share-exclusive lock on the buffer contents to write it
2593 : : * out (else we might write invalid data, eg because someone else is
2594 : : * compacting the page contents while we write). We must use a
2595 : : * conditional lock acquisition here to avoid deadlock. Even though
2596 : : * the buffer was not pinned (and therefore surely not locked) when
2597 : : * StrategyGetBuffer returned it, someone else could have pinned and
2598 : : * (share-)exclusive-locked it by the time we get here. If we try to
2599 : : * get the lock unconditionally, we'd block waiting for them; if they
2600 : : * later block waiting for us, deadlock ensues. (This has been
2601 : : * observed to happen when two backends are both trying to split btree
2602 : : * index pages, and the second one just happens to be trying to split
2603 : : * the page the first one got from StrategyGetBuffer.)
2604 : : */
216 2605 [ - + ]: 354404 : if (!BufferLockConditional(buf, buf_hdr, BUFFER_LOCK_SHARE_EXCLUSIVE))
2606 : : {
2607 : : /*
2608 : : * Someone else has locked the buffer, so give it up and loop back
2609 : : * to get another one.
2610 : : */
1286 andres@anarazel.de 2611 :UBC 0 : UnpinBuffer(buf_hdr);
2612 : 0 : goto again;
2613 : : }
2614 : :
2615 : : /*
2616 : : * If using a nondefault strategy, and this victim came from the
2617 : : * strategy ring, let the strategy decide whether to reject it when
2618 : : * reusing it would require a WAL flush. This only applies to
2619 : : * permanent buffers; unlogged buffers can have fake LSNs, so
2620 : : * XLogNeedsFlush() is not meaningful for them.
2621 : : *
2622 : : * We need to hold the content lock in at least share-exclusive mode
2623 : : * to safely inspect the page LSN, so this couldn't have been done
2624 : : * inside StrategyGetBuffer().
2625 : : */
215 melanieplageman@gmai 2626 [ + + + + ]:CBC 354404 : if (strategy && from_ring &&
2627 [ + + + + ]: 197870 : buf_state & BM_PERMANENT &&
2628 [ + + ]: 125302 : XLogNeedsFlush(BufferGetLSN(buf_hdr)) &&
2629 : 26380 : StrategyRejectBuffer(strategy, buf_hdr, from_ring))
2630 : : {
199 andres@anarazel.de 2631 : 21730 : UnlockReleaseBuffer(buf);
215 melanieplageman@gmai 2632 : 21730 : goto again;
2633 : : }
2634 : :
2635 : : /* OK, do the I/O */
1286 andres@anarazel.de 2636 : 332674 : FlushBuffer(buf_hdr, NULL, IOOBJECT_RELATION, io_context);
270 2637 : 332674 : LockBuffer(buf, BUFFER_LOCK_UNLOCK);
2638 : :
1244 2639 : 332674 : ScheduleBufferTagForWriteback(&BackendWritebackContext, io_context,
2640 : : &buf_hdr->tag);
2641 : : }
2642 : :
2643 : :
1286 2644 [ + + ]: 2132837 : if (buf_state & BM_VALID)
2645 : : {
2646 : : /*
2647 : : * When a BufferAccessStrategy is in use, blocks evicted from shared
2648 : : * buffers are counted as IOOP_EVICT in the corresponding context
2649 : : * (e.g. IOCONTEXT_BULKWRITE). Shared buffers are evicted by a
2650 : : * strategy in two cases: 1) while initially claiming buffers for the
2651 : : * strategy ring 2) to replace an existing strategy ring buffer
2652 : : * because it is pinned or in use and cannot be reused.
2653 : : *
2654 : : * Blocks evicted from buffers already in the strategy ring are
2655 : : * counted as IOOP_REUSE in the corresponding strategy context.
2656 : : *
2657 : : * At this point, we can accurately count evictions and reuses,
2658 : : * because we have successfully claimed the valid buffer. Previously,
2659 : : * we may have been forced to release the buffer due to concurrent
2660 : : * pinners or erroring out.
2661 : : */
2662 : 1307293 : pgstat_count_io_op(IOOBJECT_RELATION, io_context,
636 michael@paquier.xyz 2663 [ + + ]: 1307293 : from_ring ? IOOP_REUSE : IOOP_EVICT, 1, 0);
2664 : : }
2665 : :
2666 : : /*
2667 : : * If the buffer has an entry in the buffer mapping table, delete it. This
2668 : : * can fail because another backend could have pinned or dirtied the
2669 : : * buffer.
2670 : : */
1286 andres@anarazel.de 2671 [ + + + + ]: 2132837 : if ((buf_state & BM_TAG_VALID) && !InvalidateVictimBuffer(buf_hdr))
2672 : : {
2673 : 382 : UnpinBuffer(buf_hdr);
2674 : 382 : goto again;
2675 : : }
2676 : :
2677 : : /* a final set of sanity checks */
2678 : : #ifdef USE_ASSERT_CHECKING
270 2679 : 2132455 : buf_state = pg_atomic_read_u64(&buf_hdr->state);
2680 : :
1286 2681 [ - + ]: 2132455 : Assert(BUF_STATE_GET_REFCOUNT(buf_state) == 1);
2682 [ - + ]: 2132455 : Assert(!(buf_state & (BM_TAG_VALID | BM_VALID | BM_DIRTY)));
2683 : :
2684 : 2132455 : CheckBufferIsPinnedOnce(buf);
2685 : : #endif
2686 : :
2687 : 2132455 : return buf;
2688 : : }
2689 : :
2690 : : /*
2691 : : * Return the maximum number of buffers that a backend should try to pin once,
2692 : : * to avoid exceeding its fair share. This is the highest value that
2693 : : * GetAdditionalPinLimit() could ever return. Note that it may be zero on a
2694 : : * system with a very small buffer pool relative to max_connections.
2695 : : */
2696 : : uint32
577 tmunro@postgresql.or 2697 : 628754 : GetPinLimit(void)
2698 : : {
2699 : 628754 : return MaxProportionalPins;
2700 : : }
2701 : :
2702 : : /*
2703 : : * Return the maximum number of additional buffers that this backend should
2704 : : * pin if it wants to stay under the per-backend limit, considering the number
2705 : : * of buffers it has already pinned. Unlike LimitAdditionalPins(), the limit
2706 : : * return by this function can be zero.
2707 : : */
2708 : : uint32
2709 : 3345355 : GetAdditionalPinLimit(void)
2710 : : {
2711 : : uint32 estimated_pins_held;
2712 : :
2713 : : /*
2714 : : * We get the number of "overflowed" pins for free, but don't know the
2715 : : * number of pins in PrivateRefCountArray. The cost of calculating that
2716 : : * exactly doesn't seem worth it, so just assume the max.
2717 : : */
2718 : 3345355 : estimated_pins_held = PrivateRefCountOverflowed + REFCOUNT_ARRAY_ENTRIES;
2719 : :
2720 : : /* Is this backend already holding more than its fair share? */
2721 [ + + ]: 3345355 : if (estimated_pins_held > MaxProportionalPins)
2722 : 1317171 : return 0;
2723 : :
2724 : 2028184 : return MaxProportionalPins - estimated_pins_held;
2725 : : }
2726 : :
2727 : : /*
2728 : : * Limit the number of pins a batch operation may additionally acquire, to
2729 : : * avoid running out of pinnable buffers.
2730 : : *
2731 : : * One additional pin is always allowed, on the assumption that the operation
2732 : : * requires at least one to make progress.
2733 : : */
2734 : : void
1286 andres@anarazel.de 2735 : 249123 : LimitAdditionalPins(uint32 *additional_pins)
2736 : : {
2737 : : uint32 limit;
2738 : :
2739 [ + + ]: 249123 : if (*additional_pins <= 1)
2740 : 233264 : return;
2741 : :
577 tmunro@postgresql.or 2742 : 15859 : limit = GetAdditionalPinLimit();
2743 : 15859 : limit = Max(limit, 1);
2744 [ + + ]: 15859 : if (limit < *additional_pins)
2745 : 10237 : *additional_pins = limit;
2746 : : }
2747 : :
2748 : : /*
2749 : : * Logic shared between ExtendBufferedRelBy(), ExtendBufferedRelTo(). Just to
2750 : : * avoid duplicating the tracing and relpersistence related logic.
2751 : : */
2752 : : static BlockNumber
1146 2753 : 264712 : ExtendBufferedRelCommon(BufferManagerRelation bmr,
2754 : : ForkNumber fork,
2755 : : BufferAccessStrategy strategy,
2756 : : uint32 flags,
2757 : : uint32 extend_by,
2758 : : BlockNumber extend_upto,
2759 : : Buffer *buffers,
2760 : : uint32 *extended_by)
2761 : : {
2762 : : BlockNumber first_block;
2763 : :
2764 : : TRACE_POSTGRESQL_BUFFER_EXTEND_START(fork,
2765 : : BMR_GET_SMGR(bmr)->smgr_rlocator.locator.spcOid,
2766 : : BMR_GET_SMGR(bmr)->smgr_rlocator.locator.dbOid,
2767 : : BMR_GET_SMGR(bmr)->smgr_rlocator.locator.relNumber,
2768 : : BMR_GET_SMGR(bmr)->smgr_rlocator.backend,
2769 : : extend_by);
2770 : :
2771 [ + + ]: 264712 : if (bmr.relpersistence == RELPERSISTENCE_TEMP)
2772 : : {
2773 : : /*
2774 : : * Reject attempts to extend non-local temporary relations; we have no
2775 : : * ability to transfer about-to-be-created local buffers into the
2776 : : * owning session's local buffers. This is the canonical place for
2777 : : * the check, covering any attempt to extend a non-local temporary
2778 : : * relation.
2779 : : */
101 akorotkov@postgresql 2780 [ + - + - : 15589 : if (bmr.rel && RELATION_IS_OTHER_TEMP(bmr.rel))
+ + ]
2781 [ + - ]: 1 : ereport(ERROR,
2782 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2783 : : errmsg("cannot access temporary tables of other sessions")));
2784 : :
1146 tmunro@postgresql.or 2785 : 15588 : first_block = ExtendBufferedRelLocal(bmr, fork, flags,
2786 : : extend_by, extend_upto,
2787 : : buffers, &extend_by);
2788 : : }
2789 : : else
2790 : 249123 : first_block = ExtendBufferedRelShared(bmr, fork, strategy, flags,
2791 : : extend_by, extend_upto,
2792 : : buffers, &extend_by);
1286 andres@anarazel.de 2793 : 264711 : *extended_by = extend_by;
2794 : :
2795 : : TRACE_POSTGRESQL_BUFFER_EXTEND_DONE(fork,
2796 : : BMR_GET_SMGR(bmr)->smgr_rlocator.locator.spcOid,
2797 : : BMR_GET_SMGR(bmr)->smgr_rlocator.locator.dbOid,
2798 : : BMR_GET_SMGR(bmr)->smgr_rlocator.locator.relNumber,
2799 : : BMR_GET_SMGR(bmr)->smgr_rlocator.backend,
2800 : : *extended_by,
2801 : : first_block);
2802 : :
2803 : 264711 : return first_block;
2804 : : }
2805 : :
2806 : : /*
2807 : : * Implementation of ExtendBufferedRelBy() and ExtendBufferedRelTo() for
2808 : : * shared buffers.
2809 : : */
2810 : : static BlockNumber
1146 tmunro@postgresql.or 2811 : 249123 : ExtendBufferedRelShared(BufferManagerRelation bmr,
2812 : : ForkNumber fork,
2813 : : BufferAccessStrategy strategy,
2814 : : uint32 flags,
2815 : : uint32 extend_by,
2816 : : BlockNumber extend_upto,
2817 : : Buffer *buffers,
2818 : : uint32 *extended_by)
2819 : : {
2820 : : BlockNumber first_block;
1286 andres@anarazel.de 2821 : 249123 : IOContext io_context = IOContextForStrategy(strategy);
2822 : : instr_time io_start;
2823 : :
2824 : 249123 : LimitAdditionalPins(&extend_by);
2825 : :
2826 : : /*
2827 : : * Acquire victim buffers for extension without holding extension lock.
2828 : : * Writing out victim buffers is the most expensive part of extending the
2829 : : * relation, particularly when doing so requires WAL flushes. Zeroing out
2830 : : * the buffers is also quite expensive, so do that before holding the
2831 : : * extension lock as well.
2832 : : *
2833 : : * These pages are pinned by us and not valid. While we hold the pin they
2834 : : * can't be acquired as victim buffers by another backend.
2835 : : */
2836 [ + + ]: 525446 : for (uint32 i = 0; i < extend_by; i++)
2837 : : {
2838 : : Block buf_block;
2839 : :
2840 : 276323 : buffers[i] = GetVictimBuffer(strategy, io_context);
2841 : 276323 : buf_block = BufHdrGetBlock(GetBufferDescriptor(buffers[i] - 1));
2842 : :
2843 : : /* new buffers are zero-filled */
607 peter@eisentraut.org 2844 [ + - + - : 276323 : MemSet(buf_block, 0, BLCKSZ);
+ - - + -
- ]
2845 : : }
2846 : :
2847 : : /*
2848 : : * Lock relation against concurrent extensions, unless requested not to.
2849 : : *
2850 : : * We use the same extension lock for all forks. That's unnecessarily
2851 : : * restrictive, but currently extensions for forks don't happen often
2852 : : * enough to make it worth locking more granularly.
2853 : : *
2854 : : * Note that another backend might have extended the relation by the time
2855 : : * we get the lock.
2856 : : */
1286 andres@anarazel.de 2857 [ + + ]: 249123 : if (!(flags & EB_SKIP_EXTENSION_LOCK))
1146 tmunro@postgresql.or 2858 : 194107 : LockRelationForExtension(bmr.rel, ExclusiveLock);
2859 : :
2860 : : /*
2861 : : * If requested, invalidate size cache, so that smgrnblocks asks the
2862 : : * kernel.
2863 : : */
1286 andres@anarazel.de 2864 [ + + ]: 249123 : if (flags & EB_CLEAR_SIZE_CACHE)
356 alvherre@kurilemu.de 2865 [ + - ]: 10250 : BMR_GET_SMGR(bmr)->smgr_cached_nblocks[fork] = InvalidBlockNumber;
2866 : :
2867 [ + + ]: 249123 : first_block = smgrnblocks(BMR_GET_SMGR(bmr), fork);
2868 : :
2869 : : /*
2870 : : * Now that we have the accurate relation size, check if the caller wants
2871 : : * us to extend to only up to a specific size. If there were concurrent
2872 : : * extensions, we might have acquired too many buffers and need to release
2873 : : * them.
2874 : : */
1286 andres@anarazel.de 2875 [ + + ]: 249123 : if (extend_upto != InvalidBlockNumber)
2876 : : {
2877 : 57440 : uint32 orig_extend_by = extend_by;
2878 : :
2879 [ - + ]: 57440 : if (first_block > extend_upto)
1286 andres@anarazel.de 2880 :UBC 0 : extend_by = 0;
1286 andres@anarazel.de 2881 [ + + ]:CBC 57440 : else if ((uint64) first_block + extend_by > extend_upto)
2882 : 4 : extend_by = extend_upto - first_block;
2883 : :
2884 [ + + ]: 57444 : for (uint32 i = extend_by; i < orig_extend_by; i++)
2885 : : {
2886 : 4 : BufferDesc *buf_hdr = GetBufferDescriptor(buffers[i] - 1);
2887 : :
2888 : 4 : UnpinBuffer(buf_hdr);
2889 : : }
2890 : :
2891 [ + + ]: 57440 : if (extend_by == 0)
2892 : : {
2893 [ + - ]: 4 : if (!(flags & EB_SKIP_EXTENSION_LOCK))
1146 tmunro@postgresql.or 2894 : 4 : UnlockRelationForExtension(bmr.rel, ExclusiveLock);
1286 andres@anarazel.de 2895 : 4 : *extended_by = extend_by;
2896 : 4 : return first_block;
2897 : : }
2898 : : }
2899 : :
2900 : : /* Fail if relation is already at maximum possible length */
2901 [ - + ]: 249119 : if ((uint64) first_block + extend_by >= MaxBlockNumber)
1286 andres@anarazel.de 2902 [ # # # # :UBC 0 : ereport(ERROR,
# # # # #
# ]
2903 : : (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
2904 : : errmsg("cannot extend relation %s beyond %u blocks",
2905 : : relpath(BMR_GET_SMGR(bmr)->smgr_rlocator, fork).str,
2906 : : MaxBlockNumber)));
2907 : :
2908 : : /*
2909 : : * Insert buffers into buffer table, mark as IO_IN_PROGRESS.
2910 : : *
2911 : : * This needs to happen before we extend the relation, because as soon as
2912 : : * we do, other backends can start to read in those pages.
2913 : : */
1119 peter@eisentraut.org 2914 [ + + ]:CBC 525438 : for (uint32 i = 0; i < extend_by; i++)
2915 : : {
1286 andres@anarazel.de 2916 : 276319 : Buffer victim_buf = buffers[i];
2917 : 276319 : BufferDesc *victim_buf_hdr = GetBufferDescriptor(victim_buf - 1);
2918 : : BufferTag tag;
2919 : : uint32 hash;
2920 : : LWLock *partition_lock;
2921 : : int existing_id;
2922 : :
2923 : : /* in case we need to pin an existing buffer below */
1069 heikki.linnakangas@i 2924 : 276319 : ResourceOwnerEnlarge(CurrentResourceOwner);
2925 : 276319 : ReservePrivateRefCountEntry();
2926 : :
356 alvherre@kurilemu.de 2927 [ + + ]: 276319 : InitBufferTag(&tag, &BMR_GET_SMGR(bmr)->smgr_rlocator.locator, fork,
2928 : : first_block + i);
1286 andres@anarazel.de 2929 : 276319 : hash = BufTableHashCode(&tag);
2930 : 276319 : partition_lock = BufMappingPartitionLock(hash);
2931 : :
2932 : 276319 : LWLockAcquire(partition_lock, LW_EXCLUSIVE);
2933 : :
2934 : 276319 : existing_id = BufTableInsert(&tag, hash, victim_buf_hdr->buf_id);
2935 : :
2936 : : /*
2937 : : * We get here only in the corner case where we are trying to extend
2938 : : * the relation but we found a pre-existing buffer. This can happen
2939 : : * because a prior attempt at extending the relation failed, and
2940 : : * because mdread doesn't complain about reads beyond EOF (when
2941 : : * zero_damaged_pages is ON) and so a previous attempt to read a block
2942 : : * beyond EOF could have left a "valid" zero-filled buffer.
2943 : : *
2944 : : * This has also been observed when relation was overwritten by
2945 : : * external process. Since the legitimate cases should always have
2946 : : * left a zero-filled buffer, complain if not PageIsNew.
2947 : : */
2948 [ - + ]: 276319 : if (existing_id >= 0)
2949 : : {
1286 andres@anarazel.de 2950 :UBC 0 : BufferDesc *existing_hdr = GetBufferDescriptor(existing_id);
2951 : : Block buf_block;
2952 : : bool valid;
2953 : :
2954 : : /*
2955 : : * Pin the existing buffer before releasing the partition lock,
2956 : : * preventing it from being evicted.
2957 : : */
369 2958 : 0 : valid = PinBuffer(existing_hdr, strategy, false);
2959 : :
1286 2960 : 0 : LWLockRelease(partition_lock);
2961 : 0 : UnpinBuffer(victim_buf_hdr);
2962 : :
2963 : 0 : buffers[i] = BufferDescriptorGetBuffer(existing_hdr);
2964 : 0 : buf_block = BufHdrGetBlock(existing_hdr);
2965 : :
2966 [ # # # # ]: 0 : if (valid && !PageIsNew((Page) buf_block))
2967 [ # # # # : 0 : ereport(ERROR,
# # # # #
# ]
2968 : : (errmsg("unexpected data beyond EOF in block %u of relation \"%s\"",
2969 : : existing_hdr->tag.blockNum,
2970 : : relpath(BMR_GET_SMGR(bmr)->smgr_rlocator, fork).str)));
2971 : :
2972 : : /*
2973 : : * We *must* do smgr[zero]extend before succeeding, else the page
2974 : : * will not be reserved by the kernel, and the next P_NEW call
2975 : : * will decide to return the same page. Clear the BM_VALID bit,
2976 : : * do StartSharedBufferIO() and proceed.
2977 : : *
2978 : : * Loop to handle the very small possibility that someone re-sets
2979 : : * BM_VALID between our clearing it and StartSharedBufferIO
2980 : : * inspecting it.
2981 : : */
2982 : : while (true)
2983 : 0 : {
2984 : : StartBufferIOResult sbres;
2985 : :
270 2986 : 0 : pg_atomic_fetch_and_u64(&existing_hdr->state, ~BM_VALID);
2987 : :
199 2988 : 0 : sbres = StartSharedBufferIO(existing_hdr, true, true, NULL);
2989 : :
2990 [ # # ]: 0 : if (sbres != BUFFER_IO_ALREADY_DONE)
2991 : 0 : break;
2992 : : }
2993 : : }
2994 : : else
2995 : : {
2996 : : uint64 buf_state;
270 andres@anarazel.de 2997 :CBC 276319 : uint64 set_bits = 0;
2998 : :
1286 2999 : 276319 : buf_state = LockBufHdr(victim_buf_hdr);
3000 : :
3001 : : /* some sanity checks while we hold the buffer header lock */
215 3002 [ - + ]: 276319 : Assert(!(buf_state & (BM_VALID | BM_TAG_VALID | BM_DIRTY)));
1286 3003 [ - + ]: 276319 : Assert(BUF_STATE_GET_REFCOUNT(buf_state) == 1);
3004 : :
3005 : 276319 : victim_buf_hdr->tag = tag;
3006 : :
340 3007 : 276319 : set_bits |= BM_TAG_VALID | BUF_USAGECOUNT_ONE;
1146 tmunro@postgresql.or 3008 [ + + + + ]: 276319 : if (bmr.relpersistence == RELPERSISTENCE_PERMANENT || fork == INIT_FORKNUM)
340 andres@anarazel.de 3009 : 270901 : set_bits |= BM_PERMANENT;
3010 : :
3011 : 276319 : UnlockBufHdrExt(victim_buf_hdr, buf_state,
3012 : : set_bits, 0,
3013 : : 0);
3014 : :
1286 3015 : 276319 : LWLockRelease(partition_lock);
3016 : :
3017 : : /* XXX: could combine the locked operations in it with the above */
199 3018 : 276319 : StartSharedBufferIO(victim_buf_hdr, true, true, NULL);
3019 : : }
3020 : : }
3021 : :
593 michael@paquier.xyz 3022 : 249119 : io_start = pgstat_prepare_io_time(track_io_timing);
3023 : :
3024 : : /*
3025 : : * Note: if smgrzeroextend fails, we will end up with buffers that are
3026 : : * allocated but not marked BM_VALID. The next relation extension will
3027 : : * still select the same block number (because the relation didn't get any
3028 : : * longer on disk) and so future attempts to extend the relation will find
3029 : : * the same buffers (if they have not been recycled) but come right back
3030 : : * here to try smgrzeroextend again.
3031 : : *
3032 : : * We don't need to set checksum for all-zero pages.
3033 : : */
356 alvherre@kurilemu.de 3034 [ + + ]: 249119 : smgrzeroextend(BMR_GET_SMGR(bmr), fork, first_block, extend_by, false);
3035 : :
3036 : : /*
3037 : : * Release the file-extension lock; it's now OK for someone else to extend
3038 : : * the relation some more.
3039 : : *
3040 : : * We remove IO_IN_PROGRESS after this, as waking up waiting backends can
3041 : : * take noticeable time.
3042 : : */
1286 andres@anarazel.de 3043 [ + + ]: 249119 : if (!(flags & EB_SKIP_EXTENSION_LOCK))
1146 tmunro@postgresql.or 3044 : 194103 : UnlockRelationForExtension(bmr.rel, ExclusiveLock);
3045 : :
1284 andres@anarazel.de 3046 : 249119 : pgstat_count_io_op_time(IOOBJECT_RELATION, io_context, IOOP_EXTEND,
636 michael@paquier.xyz 3047 : 249119 : io_start, 1, extend_by * BLCKSZ);
3048 : :
3049 : : /* Set BM_VALID, terminate IO, and wake up any waiters */
1119 peter@eisentraut.org 3050 [ + + ]: 525438 : for (uint32 i = 0; i < extend_by; i++)
3051 : : {
1286 andres@anarazel.de 3052 : 276319 : Buffer buf = buffers[i];
3053 : 276319 : BufferDesc *buf_hdr = GetBufferDescriptor(buf - 1);
3054 : 276319 : bool lock = false;
3055 : :
3056 [ + + + + ]: 276319 : if (flags & EB_LOCK_FIRST && i == 0)
3057 : 191355 : lock = true;
3058 [ + + ]: 84964 : else if (flags & EB_LOCK_TARGET)
3059 : : {
3060 [ - + ]: 45994 : Assert(extend_upto != InvalidBlockNumber);
3061 [ + + ]: 45994 : if (first_block + i + 1 == extend_upto)
3062 : 45414 : lock = true;
3063 : : }
3064 : :
3065 [ + + ]: 276319 : if (lock)
369 3066 : 236769 : LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
3067 : :
561 3068 : 276319 : TerminateBufferIO(buf_hdr, false, BM_VALID, true, false);
3069 : : }
3070 : :
1286 3071 : 249119 : pgBufferUsage.shared_blks_written += extend_by;
3072 : :
3073 : 249119 : *extended_by = extend_by;
3074 : :
3075 : 249119 : return first_block;
3076 : : }
3077 : :
3078 : : /*
3079 : : * BufferIsLockedByMe
3080 : : *
3081 : : * Checks if this backend has the buffer locked in any mode.
3082 : : *
3083 : : * Buffer must be pinned.
3084 : : */
3085 : : bool
369 3086 : 110 : BufferIsLockedByMe(Buffer buffer)
3087 : : {
3088 : : BufferDesc *bufHdr;
3089 : :
3090 [ - + - + : 110 : Assert(BufferIsPinned(buffer));
- + ]
3091 : :
3092 [ - + ]: 110 : if (BufferIsLocal(buffer))
3093 : : {
3094 : : /* Content locks are not maintained for local buffers. */
369 andres@anarazel.de 3095 :UBC 0 : return true;
3096 : : }
3097 : : else
3098 : : {
369 andres@anarazel.de 3099 :CBC 110 : bufHdr = GetBufferDescriptor(buffer - 1);
270 3100 : 110 : return BufferLockHeldByMe(bufHdr);
3101 : : }
3102 : : }
3103 : :
3104 : : /*
3105 : : * BufferIsLockedByMeInMode
3106 : : *
3107 : : * Checks if this backend has the buffer locked in the specified mode.
3108 : : *
3109 : : * Buffer must be pinned.
3110 : : */
3111 : : bool
313 3112 : 116216694 : BufferIsLockedByMeInMode(Buffer buffer, BufferLockMode mode)
3113 : : {
3114 : : BufferDesc *bufHdr;
3115 : :
621 tgl@sss.pgh.pa.us 3116 [ - + + + : 116216694 : Assert(BufferIsPinned(buffer));
- + ]
3117 : :
1085 jdavis@postgresql.or 3118 [ + + ]: 116216694 : if (BufferIsLocal(buffer))
3119 : : {
3120 : : /* Content locks are not maintained for local buffers. */
621 tgl@sss.pgh.pa.us 3121 : 12256 : return true;
3122 : : }
3123 : : else
3124 : : {
1085 jdavis@postgresql.or 3125 : 116204438 : bufHdr = GetBufferDescriptor(buffer - 1);
270 andres@anarazel.de 3126 : 116204438 : return BufferLockHeldByMeInMode(bufHdr, mode);
3127 : : }
3128 : : }
3129 : :
3130 : : /*
3131 : : * BufferIsDirty
3132 : : *
3133 : : * Checks if buffer is already dirty.
3134 : : *
3135 : : * Buffer must be pinned and [share-]exclusive-locked. (Without such a lock,
3136 : : * the result may be stale before it's returned.)
3137 : : */
3138 : : bool
1085 jdavis@postgresql.or 3139 : 27763262 : BufferIsDirty(Buffer buffer)
3140 : : {
3141 : : BufferDesc *bufHdr;
3142 : :
621 tgl@sss.pgh.pa.us 3143 [ - + - + : 27763262 : Assert(BufferIsPinned(buffer));
- + ]
3144 : :
1085 jdavis@postgresql.or 3145 [ - + ]: 27763262 : if (BufferIsLocal(buffer))
3146 : : {
1085 jdavis@postgresql.or 3147 :UBC 0 : int bufid = -buffer - 1;
3148 : :
3149 : 0 : bufHdr = GetLocalBufferDescriptor(bufid);
3150 : : /* Content locks are not maintained for local buffers. */
3151 : : }
3152 : : else
3153 : : {
1085 jdavis@postgresql.or 3154 :CBC 27763262 : bufHdr = GetBufferDescriptor(buffer - 1);
216 andres@anarazel.de 3155 [ + + - + ]: 27763262 : Assert(BufferIsLockedByMeInMode(buffer, BUFFER_LOCK_SHARE_EXCLUSIVE) ||
3156 : : BufferIsLockedByMeInMode(buffer, BUFFER_LOCK_EXCLUSIVE));
3157 : : }
3158 : :
270 3159 : 27763262 : return pg_atomic_read_u64(&bufHdr->state) & BM_DIRTY;
3160 : : }
3161 : :
3162 : : /*
3163 : : * MarkBufferDirty
3164 : : *
3165 : : * Marks buffer contents as dirty (actual write happens later).
3166 : : *
3167 : : * Buffer must be pinned and exclusive-locked. (If caller does not hold
3168 : : * exclusive lock, then somebody could be in process of writing the buffer,
3169 : : * leading to risk of bad data written to disk.)
3170 : : */
3171 : : void
7500 tgl@sss.pgh.pa.us 3172 : 34496510 : MarkBufferDirty(Buffer buffer)
3173 : : {
3174 : : BufferDesc *bufHdr;
3175 : : uint64 buf_state;
3176 : : uint64 old_buf_state;
3177 : :
8032 3178 [ - + ]: 34496510 : if (!BufferIsValid(buffer))
5594 peter_e@gmx.net 3179 [ # # ]:UBC 0 : elog(ERROR, "bad buffer ID: %d", buffer);
3180 : :
9691 tgl@sss.pgh.pa.us 3181 [ + + ]:CBC 34496510 : if (BufferIsLocal(buffer))
3182 : : {
7500 3183 : 1702428 : MarkLocalBufferDirty(buffer);
8885 bruce@momjian.us 3184 : 1702428 : return;
3185 : : }
3186 : :
4274 andres@anarazel.de 3187 : 32794082 : bufHdr = GetBufferDescriptor(buffer - 1);
3188 : :
4426 3189 [ - + - + : 32794082 : Assert(BufferIsPinned(buffer));
- + ]
369 3190 [ - + ]: 32794082 : Assert(BufferIsLockedByMeInMode(buffer, BUFFER_LOCK_EXCLUSIVE));
3191 : :
3192 : : /*
3193 : : * NB: We have to wait for the buffer header spinlock to be not held, as
3194 : : * TerminateBufferIO() relies on the spinlock.
3195 : : */
270 3196 : 32794082 : old_buf_state = pg_atomic_read_u64(&bufHdr->state);
3197 : : for (;;)
3198 : : {
3837 3199 [ + + ]: 32794320 : if (old_buf_state & BM_LOCKED)
3200 : 484 : old_buf_state = WaitBufHdrUnlocked(bufHdr);
3201 : :
3202 : 32794320 : buf_state = old_buf_state;
3203 : :
3204 [ - + ]: 32794320 : Assert(BUF_STATE_GET_REFCOUNT(buf_state) > 0);
215 3205 : 32794320 : buf_state |= BM_DIRTY;
3206 : :
270 3207 [ + + ]: 32794320 : if (pg_atomic_compare_exchange_u64(&bufHdr->state, &old_buf_state,
3208 : : buf_state))
3837 3209 : 32794082 : break;
3210 : : }
3211 : :
3212 : : /*
3213 : : * If the buffer was not dirty already, do vacuum accounting.
3214 : : */
3215 [ + + ]: 32794082 : if (!(old_buf_state & BM_DIRTY))
3216 : : {
5346 rhaas@postgresql.org 3217 : 817598 : pgBufferUsage.shared_blks_dirtied++;
5435 alvherre@alvh.no-ip. 3218 [ + + ]: 817598 : if (VacuumCostActive)
3219 : 13855 : VacuumCostBalance += VacuumCostPageDirty;
3220 : : }
3221 : : }
3222 : :
3223 : : /*
3224 : : * ReleaseAndReadBuffer -- combine ReleaseBuffer() and ReadBuffer()
3225 : : *
3226 : : * Formerly, this saved one cycle of acquiring/releasing the BufMgrLock
3227 : : * compared to calling the two routines separately. Now it's mainly just
3228 : : * a convenience function. However, if the passed buffer is valid and
3229 : : * already contains the desired block, we just return it as-is; and that
3230 : : * does save considerable work compared to a full release and reacquire.
3231 : : *
3232 : : * Note: it is OK to pass buffer == InvalidBuffer, indicating that no old
3233 : : * buffer actually needs to be released. This case is the same as ReadBuffer,
3234 : : * but can save some tests in the caller.
3235 : : */
3236 : : Buffer
11052 scrappy@hub.org 3237 : 3647 : ReleaseAndReadBuffer(Buffer buffer,
3238 : : Relation relation,
3239 : : BlockNumber blockNum)
3240 : : {
6332 bruce@momjian.us 3241 : 3647 : ForkNumber forkNum = MAIN_FORKNUM;
3242 : : BufferDesc *bufHdr;
3243 : :
9284 tgl@sss.pgh.pa.us 3244 [ + - ]: 3647 : if (BufferIsValid(buffer))
3245 : : {
4426 andres@anarazel.de 3246 [ - + + + : 3647 : Assert(BufferIsPinned(buffer));
- + ]
9284 tgl@sss.pgh.pa.us 3247 [ + + ]: 3647 : if (BufferIsLocal(buffer))
3248 : : {
4274 andres@anarazel.de 3249 : 51 : bufHdr = GetLocalBufferDescriptor(-buffer - 1);
9256 tgl@sss.pgh.pa.us 3250 [ - + - - ]: 51 : if (bufHdr->tag.blockNum == blockNum &&
1510 rhaas@postgresql.org 3251 [ # # ]:UBC 0 : BufTagMatchesRelFileLocator(&bufHdr->tag, &relation->rd_locator) &&
3252 : 0 : BufTagGetForkNum(&bufHdr->tag) == forkNum)
9256 tgl@sss.pgh.pa.us 3253 : 0 : return buffer;
1286 andres@anarazel.de 3254 :CBC 51 : UnpinLocalBuffer(buffer);
3255 : : }
3256 : : else
3257 : : {
4274 3258 : 3596 : bufHdr = GetBufferDescriptor(buffer - 1);
3259 : : /* we have pin, so it's ok to examine tag without spinlock */
9256 tgl@sss.pgh.pa.us 3260 [ - + - - ]: 3596 : if (bufHdr->tag.blockNum == blockNum &&
1510 rhaas@postgresql.org 3261 [ # # ]:UBC 0 : BufTagMatchesRelFileLocator(&bufHdr->tag, &relation->rd_locator) &&
3262 : 0 : BufTagGetForkNum(&bufHdr->tag) == forkNum)
9256 tgl@sss.pgh.pa.us 3263 : 0 : return buffer;
1473 michael@paquier.xyz 3264 :CBC 3596 : UnpinBuffer(bufHdr);
3265 : : }
3266 : : }
3267 : :
7892 tgl@sss.pgh.pa.us 3268 : 3647 : return ReadBuffer(relation, blockNum);
3269 : : }
3270 : :
3271 : : /*
3272 : : * PinBuffer -- make buffer unavailable for replacement.
3273 : : *
3274 : : * For the default access strategy, the buffer's usage_count is incremented
3275 : : * when we first pin it; for other strategies we just make sure the usage_count
3276 : : * isn't zero. (The idea of the latter is that we don't want synchronized
3277 : : * heap scans to inflate the count, but we need it to not be zero to discourage
3278 : : * other backends from stealing buffers from our ring. As long as we cycle
3279 : : * through the ring faster than the global clock-sweep cycles, buffers in
3280 : : * our ring won't be chosen as victims for replacement by other backends.)
3281 : : *
3282 : : * This should be applied only to shared buffers, never local ones.
3283 : : *
3284 : : * Since buffers are pinned/unpinned very frequently, pin buffers without
3285 : : * taking the buffer header lock; instead update the state variable in loop of
3286 : : * CAS operations. Hopefully it's just a single CAS.
3287 : : *
3288 : : * Note that ResourceOwnerEnlarge() and ReservePrivateRefCountEntry()
3289 : : * must have been done already.
3290 : : *
3291 : : * Returns true if buffer is BM_VALID, else false. This provision allows
3292 : : * some callers to avoid an extra spinlock cycle. If skip_if_not_valid is
3293 : : * true, then a false return value also indicates that the buffer was
3294 : : * (recently) invalid and has not been pinned.
3295 : : */
3296 : : static bool
369 andres@anarazel.de 3297 : 80284444 : PinBuffer(BufferDesc *buf, BufferAccessStrategy strategy,
3298 : : bool skip_if_not_valid)
3299 : : {
4079 3300 : 80284444 : Buffer b = BufferDescriptorGetBuffer(buf);
3301 : : bool result;
3302 : : PrivateRefCountEntry *ref;
3303 : :
1286 3304 [ - + ]: 80284444 : Assert(!BufferIsLocal(b));
302 3305 [ - + ]: 80284444 : Assert(ReservedRefCountSlot != -1);
3306 : :
4079 3307 : 80284444 : ref = GetPrivateRefCountEntry(b, true);
3308 : :
4284 3309 [ + + ]: 80284444 : if (ref == NULL)
3310 : : {
3311 : : uint64 buf_state;
3312 : : uint64 old_buf_state;
3313 : :
270 3314 : 73054139 : old_buf_state = pg_atomic_read_u64(&buf->state);
3315 : : for (;;)
3316 : : {
369 3317 [ + + + + : 73059877 : if (unlikely(skip_if_not_valid && !(old_buf_state & BM_VALID)))
+ + ]
3318 : 6 : return false;
3319 : :
3320 : : /*
3321 : : * We're not allowed to increase the refcount while the buffer
3322 : : * header spinlock is held. Wait for the lock to be released.
3323 : : */
195 3324 [ + + ]: 73059871 : if (unlikely(old_buf_state & BM_LOCKED))
3325 : : {
3837 3326 : 214 : old_buf_state = WaitBufHdrUnlocked(buf);
3327 : :
3328 : : /* perform checks at the top of the loop again */
195 3329 : 214 : continue;
3330 : : }
3331 : :
3837 3332 : 73059657 : buf_state = old_buf_state;
3333 : :
3334 : : /* increase refcount */
3335 : 73059657 : buf_state += BUF_REFCOUNT_ONE;
3336 : :
3493 teodor@sigaev.ru 3337 [ + + ]: 73059657 : if (strategy == NULL)
3338 : : {
3339 : : /* Default case: increase usagecount unless already max. */
3340 [ + + ]: 72477796 : if (BUF_STATE_GET_USAGECOUNT(buf_state) < BM_MAX_USAGE_COUNT)
3341 : 3752125 : buf_state += BUF_USAGECOUNT_ONE;
3342 : : }
3343 : : else
3344 : : {
3345 : : /*
3346 : : * Ring buffers shouldn't evict others from pool. Thus we
3347 : : * don't make usagecount more than 1.
3348 : : */
3349 [ + + ]: 581861 : if (BUF_STATE_GET_USAGECOUNT(buf_state) == 0)
3350 : 28676 : buf_state += BUF_USAGECOUNT_ONE;
3351 : : }
3352 : :
270 andres@anarazel.de 3353 [ + + ]: 73059657 : if (pg_atomic_compare_exchange_u64(&buf->state, &old_buf_state,
3354 : : buf_state))
3355 : : {
3837 3356 : 73054133 : result = (buf_state & BM_VALID) != 0;
3357 : :
369 3358 : 73054133 : TrackNewBufferPin(b);
3837 3359 : 73054133 : break;
3360 : : }
3361 : : }
3362 : : }
3363 : : else
3364 : : {
3365 : : /*
3366 : : * If we previously pinned the buffer, it is likely to be valid, but
3367 : : * it may not be if StartReadBuffers() was called and
3368 : : * WaitReadBuffers() hasn't been called yet. We'll check by loading
3369 : : * the flags without locking. This is racy, but it's OK to return
3370 : : * false spuriously: when WaitReadBuffers() calls StartBufferIO(),
3371 : : * it'll see that it's now valid.
3372 : : *
3373 : : * Note: We deliberately avoid a Valgrind client request here.
3374 : : * Individual access methods can optionally superimpose buffer page
3375 : : * client requests on top of our client requests to enforce that
3376 : : * buffers are only accessed while locked (and pinned). It's possible
3377 : : * that the buffer page is legitimately non-accessible here. We
3378 : : * cannot meddle with that.
3379 : : */
270 3380 : 7230305 : result = (pg_atomic_read_u64(&buf->state) & BM_VALID) != 0;
3381 : :
302 3382 [ - + ]: 7230305 : Assert(ref->data.refcount > 0);
3383 : 7230305 : ref->data.refcount++;
369 3384 : 7230305 : ResourceOwnerRememberBuffer(CurrentResourceOwner, b);
3385 : : }
3386 : :
7892 tgl@sss.pgh.pa.us 3387 : 80284438 : return result;
3388 : : }
3389 : :
3390 : : /*
3391 : : * PinBuffer_Locked -- as above, but caller already locked the buffer header.
3392 : : * The spinlock is released before return.
3393 : : *
3394 : : * As this function is called with the spinlock held, the caller has to
3395 : : * previously call ReservePrivateRefCountEntry() and
3396 : : * ResourceOwnerEnlarge(CurrentResourceOwner);
3397 : : *
3398 : : * Currently, no callers of this function want to modify the buffer's
3399 : : * usage_count at all, so there's no need for a strategy parameter.
3400 : : * Also we don't bother with a BM_VALID test (the caller could check that for
3401 : : * itself).
3402 : : *
3403 : : * Also all callers only ever use this function when it's known that the
3404 : : * buffer can't have a preexisting pin by this backend. That allows us to skip
3405 : : * searching the private refcount array & hash, which is a boon, because the
3406 : : * spinlock is still held.
3407 : : *
3408 : : * Note: use of this routine is frequently mandatory, not just an optimization
3409 : : * to save a spin lock/unlock cycle, because we need to pin a buffer before
3410 : : * its state can change under us.
3411 : : */
3412 : : static void
3983 rhaas@postgresql.org 3413 : 381648 : PinBuffer_Locked(BufferDesc *buf)
3414 : : {
3415 : : uint64 old_buf_state;
3416 : :
3417 : : /*
3418 : : * As explained, We don't expect any preexisting pins. That allows us to
3419 : : * manipulate the PrivateRefCount after releasing the spinlock
3420 : : */
4079 andres@anarazel.de 3421 [ - + ]: 381648 : Assert(GetPrivateRefCountEntry(BufferDescriptorGetBuffer(buf), false) == NULL);
3422 : :
3423 : : /*
3424 : : * Since we hold the buffer spinlock, we can update the buffer state and
3425 : : * release the lock in one operation.
3426 : : */
270 3427 : 381648 : old_buf_state = pg_atomic_read_u64(&buf->state);
3428 : :
340 3429 : 381648 : UnlockBufHdrExt(buf, old_buf_state,
3430 : : 0, 0, 1);
3431 : :
369 3432 : 381648 : TrackNewBufferPin(BufferDescriptorGetBuffer(buf));
8211 tgl@sss.pgh.pa.us 3433 : 381648 : }
3434 : :
3435 : : /*
3436 : : * Support for waking up another backend that is waiting for the cleanup lock
3437 : : * to be released using BM_PIN_COUNT_WAITER.
3438 : : *
3439 : : * See LockBufferForCleanup().
3440 : : *
3441 : : * Expected to be called just after releasing a buffer pin (in a BufferDesc,
3442 : : * not just reducing the backend-local pincount for the buffer).
3443 : : */
3444 : : static void
561 andres@anarazel.de 3445 : 56 : WakePinCountWaiter(BufferDesc *buf)
3446 : : {
3447 : : /*
3448 : : * Acquire the buffer header lock, re-check that there's a waiter. Another
3449 : : * backend could have unpinned this buffer, and already woken up the
3450 : : * waiter.
3451 : : *
3452 : : * There's no danger of the buffer being replaced after we unpinned it
3453 : : * above, as it's pinned by the waiter. The waiter removes
3454 : : * BM_PIN_COUNT_WAITER if it stops waiting for a reason other than this
3455 : : * backend waking it up.
3456 : : */
270 3457 : 56 : uint64 buf_state = LockBufHdr(buf);
3458 : :
561 3459 [ + - ]: 56 : if ((buf_state & BM_PIN_COUNT_WAITER) &&
3460 [ + - ]: 56 : BUF_STATE_GET_REFCOUNT(buf_state) == 1)
3461 : 56 : {
3462 : : /* we just released the last pin other than the waiter's */
3463 : 56 : int wait_backend_pgprocno = buf->wait_backend_pgprocno;
3464 : :
340 3465 : 56 : UnlockBufHdrExt(buf, buf_state,
3466 : : 0, BM_PIN_COUNT_WAITER,
3467 : : 0);
561 3468 : 56 : ProcSendSignal(wait_backend_pgprocno);
3469 : : }
3470 : : else
340 andres@anarazel.de 3471 :LBC (9) : UnlockBufHdr(buf);
561 andres@anarazel.de 3472 :CBC 56 : }
3473 : :
3474 : : /*
3475 : : * UnpinBuffer -- make buffer available for replacement.
3476 : : *
3477 : : * This should be applied only to shared buffers, never local ones. This
3478 : : * always adjusts CurrentResourceOwner.
3479 : : */
3480 : : static void
1473 michael@paquier.xyz 3481 : 39927082 : UnpinBuffer(BufferDesc *buf)
3482 : : {
1069 heikki.linnakangas@i 3483 : 39927082 : Buffer b = BufferDescriptorGetBuffer(buf);
3484 : :
3485 : 39927082 : ResourceOwnerForgetBuffer(CurrentResourceOwner, b);
3486 : 39927082 : UnpinBufferNoOwner(buf);
3487 : 39927082 : }
3488 : :
3489 : : static void
3490 : 39933759 : UnpinBufferNoOwner(BufferDesc *buf)
3491 : : {
3492 : : PrivateRefCountEntry *ref;
4079 andres@anarazel.de 3493 : 39933759 : Buffer b = BufferDescriptorGetBuffer(buf);
3494 : :
1286 3495 [ - + ]: 39933759 : Assert(!BufferIsLocal(b));
3496 : :
3497 : : /* not moving as we're likely deleting it soon anyway */
4079 3498 : 39933759 : ref = GetPrivateRefCountEntry(b, false);
4426 3499 [ - + ]: 39933759 : Assert(ref != NULL);
302 3500 [ - + ]: 39933759 : Assert(ref->data.refcount > 0);
3501 : 39933759 : ref->data.refcount--;
3502 [ + + ]: 39933759 : if (ref->data.refcount == 0)
3503 : : {
3504 : : uint64 old_buf_state;
3505 : :
3506 : : /*
3507 : : * Mark buffer non-accessible to Valgrind.
3508 : : *
3509 : : * Note that the buffer may have already been marked non-accessible
3510 : : * within access method code that enforces that buffers are only
3511 : : * accessed while a buffer lock is held.
3512 : : */
3513 : : VALGRIND_MAKE_MEM_NOACCESS(BufHdrGetBlock(buf), BLCKSZ);
3514 : :
3515 : : /*
3516 : : * I'd better not still hold the buffer content lock. Can't use
3517 : : * BufferIsLockedByMe(), as that asserts the buffer is pinned.
3518 : : */
270 3519 [ - + ]: 21772295 : Assert(!BufferLockHeldByMe(buf));
3520 : :
3521 : : /* decrement the shared reference count */
3522 : 21772295 : old_buf_state = pg_atomic_fetch_sub_u64(&buf->state, BUF_REFCOUNT_ONE);
3523 : :
3524 : : /* Support LockBufferForCleanup() */
340 3525 [ + + ]: 21772295 : if (old_buf_state & BM_PIN_COUNT_WAITER)
561 3526 : 55 : WakePinCountWaiter(buf);
3527 : :
4426 3528 : 21772295 : ForgetPrivateRefCountEntry(ref);
3529 : : }
8211 tgl@sss.pgh.pa.us 3530 : 39933759 : }
3531 : :
3532 : : /*
3533 : : * Set up backend-local tracking of a buffer pinned the first time by this
3534 : : * backend.
3535 : : */
3536 : : inline void
369 andres@anarazel.de 3537 : 75590348 : TrackNewBufferPin(Buffer buf)
3538 : : {
3539 : : PrivateRefCountEntry *ref;
3540 : :
3541 : 75590348 : ref = NewPrivateRefCountEntry(buf);
302 3542 : 75590348 : ref->data.refcount++;
3543 : :
369 3544 : 75590348 : ResourceOwnerRememberBuffer(CurrentResourceOwner, buf);
3545 : :
3546 : : /*
3547 : : * This is the first pin for this page by this backend, mark its page as
3548 : : * defined to valgrind. While the page contents might not actually be
3549 : : * valid yet, we don't currently guarantee that such pages are marked
3550 : : * undefined or non-accessible.
3551 : : *
3552 : : * It's not necessarily the prettiest to do this here, but otherwise we'd
3553 : : * need this block of code in multiple places.
3554 : : */
3555 : : VALGRIND_MAKE_MEM_DEFINED(BufHdrGetBlock(GetBufferDescriptor(buf - 1)),
3556 : : BLCKSZ);
3557 : 75590348 : }
3558 : :
3559 : : #define ST_SORT sort_checkpoint_bufferids
3560 : : #define ST_ELEMENT_TYPE CkptSortItem
3561 : : #define ST_COMPARE(a, b) ckpt_buforder_comparator(a, b)
3562 : : #define ST_SCOPE static
3563 : : #define ST_DEFINE
3564 : : #include "lib/sort_template.h"
3565 : :
3566 : : /*
3567 : : * BufferSync -- Write out all dirty buffers in the pool.
3568 : : *
3569 : : * This is called at checkpoint time to write out all dirty shared buffers.
3570 : : * The checkpoint request flags should be passed in. If CHECKPOINT_FAST is
3571 : : * set, we disable delays between writes; if CHECKPOINT_IS_SHUTDOWN,
3572 : : * CHECKPOINT_END_OF_RECOVERY or CHECKPOINT_FLUSH_UNLOGGED is set, we write
3573 : : * even unlogged buffers, which are otherwise skipped. The remaining flags
3574 : : * currently have no effect here.
3575 : : */
3576 : : static void
7046 tgl@sss.pgh.pa.us 3577 : 1998 : BufferSync(int flags)
3578 : : {
3579 : : uint64 buf_state;
3580 : : int buf_id;
3581 : : int num_to_scan;
3582 : : int num_spaces;
3583 : : int num_processed;
3584 : : int num_written;
3888 andres@anarazel.de 3585 : 1998 : CkptTsStatus *per_ts_stat = NULL;
3586 : : Oid last_tsid;
3587 : : binaryheap *ts_heap;
3588 : : int i;
270 3589 : 1998 : uint64 mask = BM_DIRTY;
3590 : : WritebackContext wb_context;
3591 : :
3592 : : /*
3593 : : * Unless this is a shutdown checkpoint or we have been explicitly told,
3594 : : * we write only permanent, dirty buffers. But at shutdown or end of
3595 : : * recovery, we write all dirty buffers.
3596 : : */
4375 3597 [ + + ]: 1998 : if (!((flags & (CHECKPOINT_IS_SHUTDOWN | CHECKPOINT_END_OF_RECOVERY |
3598 : : CHECKPOINT_FLUSH_UNLOGGED))))
5393 rhaas@postgresql.org 3599 : 1102 : mask |= BM_PERMANENT;
3600 : :
3601 : : /*
3602 : : * Loop over all buffers, and mark the ones that need to be written with
3603 : : * BM_CHECKPOINT_NEEDED. Count them as we go (num_to_scan), so that we
3604 : : * can estimate how much work needs to be done.
3605 : : *
3606 : : * This allows us to write only those pages that were dirty when the
3607 : : * checkpoint began, and not those that get dirtied while it proceeds.
3608 : : * Whenever a page with BM_CHECKPOINT_NEEDED is written out, either by us
3609 : : * later in this function, or by normal backends or the bgwriter cleaning
3610 : : * scan, the flag is cleared. Any buffer dirtied after this point won't
3611 : : * have the flag set.
3612 : : *
3613 : : * Note that if we fail to write some buffer, we may leave buffers with
3614 : : * BM_CHECKPOINT_NEEDED still set. This is OK since any such buffer would
3615 : : * certainly need to be written for the next checkpoint attempt, too.
3616 : : */
3888 andres@anarazel.de 3617 : 1998 : num_to_scan = 0;
7046 tgl@sss.pgh.pa.us 3618 [ + + ]: 14270110 : for (buf_id = 0; buf_id < NBuffers; buf_id++)
3619 : : {
3983 rhaas@postgresql.org 3620 : 14268112 : BufferDesc *bufHdr = GetBufferDescriptor(buf_id);
270 andres@anarazel.de 3621 : 14268112 : uint64 set_bits = 0;
3622 : :
3623 : : /*
3624 : : * Header spinlock is enough to examine BM_DIRTY, see comment in
3625 : : * SyncOneBuffer.
3626 : : */
3837 3627 : 14268112 : buf_state = LockBufHdr(bufHdr);
3628 : :
3629 [ + + ]: 14268112 : if ((buf_state & mask) == mask)
3630 : : {
3631 : : CkptSortItem *item;
3632 : :
340 3633 : 345409 : set_bits = BM_CHECKPOINT_NEEDED;
3634 : :
3888 3635 : 345409 : item = &CkptBufferIds[num_to_scan++];
3636 : 345409 : item->buf_id = buf_id;
1510 rhaas@postgresql.org 3637 : 345409 : item->tsId = bufHdr->tag.spcOid;
3638 : 345409 : item->relNumber = BufTagGetRelNumber(&bufHdr->tag);
3639 : 345409 : item->forkNum = BufTagGetForkNum(&bufHdr->tag);
3888 andres@anarazel.de 3640 : 345409 : item->blockNum = bufHdr->tag.blockNum;
3641 : : }
3642 : :
340 3643 : 14268112 : UnlockBufHdrExt(bufHdr, buf_state,
3644 : : set_bits, 0,
3645 : : 0);
3646 : :
3647 : : /* Check for barrier events in case NBuffers is large. */
2489 rhaas@postgresql.org 3648 [ - + ]: 14268112 : if (ProcSignalBarrierPending)
2489 rhaas@postgresql.org 3649 :UBC 0 : ProcessProcSignalBarrier();
3650 : : }
3651 : :
3888 andres@anarazel.de 3652 [ + + ]:CBC 1998 : if (num_to_scan == 0)
7046 tgl@sss.pgh.pa.us 3653 : 739 : return; /* nothing to do */
3654 : :
3888 andres@anarazel.de 3655 : 1259 : WritebackContextInit(&wb_context, &checkpoint_flush_after);
3656 : :
3657 : : TRACE_POSTGRESQL_BUFFER_SYNC_START(NBuffers, num_to_scan);
3658 : :
3659 : : /*
3660 : : * Sort buffers that need to be written to reduce the likelihood of random
3661 : : * IO. The sorting is also important for the implementation of balancing
3662 : : * writes between tablespaces. Without balancing writes we'd potentially
3663 : : * end up writing to the tablespaces one-by-one; possibly overloading the
3664 : : * underlying system.
3665 : : */
2040 tmunro@postgresql.or 3666 : 1259 : sort_checkpoint_bufferids(CkptBufferIds, num_to_scan);
3667 : :
3888 andres@anarazel.de 3668 : 1259 : num_spaces = 0;
3669 : :
3670 : : /*
3671 : : * Allocate progress status for each tablespace with buffers that need to
3672 : : * be flushed. This requires the to-be-flushed array to be sorted.
3673 : : */
3674 : 1259 : last_tsid = InvalidOid;
3675 [ + + ]: 346668 : for (i = 0; i < num_to_scan; i++)
3676 : : {
3677 : : CkptTsStatus *s;
3678 : : Oid cur_tsid;
3679 : :
3680 : 345409 : cur_tsid = CkptBufferIds[i].tsId;
3681 : :
3682 : : /*
3683 : : * Grow array of per-tablespace status structs, every time a new
3684 : : * tablespace is found.
3685 : : */
3686 [ + + + + ]: 345409 : if (last_tsid == InvalidOid || last_tsid != cur_tsid)
3687 : 1878 : {
3688 : : Size sz;
3689 : :
3690 : 1878 : num_spaces++;
3691 : :
3692 : : /*
3693 : : * Not worth adding grow-by-power-of-2 logic here - even with a
3694 : : * few hundred tablespaces this should be fine.
3695 : : */
3696 : 1878 : sz = sizeof(CkptTsStatus) * num_spaces;
3697 : :
3698 [ + + ]: 1878 : if (per_ts_stat == NULL)
3699 : 1259 : per_ts_stat = (CkptTsStatus *) palloc(sz);
3700 : : else
3701 : 619 : per_ts_stat = (CkptTsStatus *) repalloc(per_ts_stat, sz);
3702 : :
3703 : 1878 : s = &per_ts_stat[num_spaces - 1];
3704 : 1878 : memset(s, 0, sizeof(*s));
3705 : 1878 : s->tsId = cur_tsid;
3706 : :
3707 : : /*
3708 : : * The first buffer in this tablespace. As CkptBufferIds is sorted
3709 : : * by tablespace all (s->num_to_scan) buffers in this tablespace
3710 : : * will follow afterwards.
3711 : : */
3712 : 1878 : s->index = i;
3713 : :
3714 : : /*
3715 : : * progress_slice will be determined once we know how many buffers
3716 : : * are in each tablespace, i.e. after this loop.
3717 : : */
3718 : :
3719 : 1878 : last_tsid = cur_tsid;
3720 : : }
3721 : : else
3722 : : {
3723 : 343531 : s = &per_ts_stat[num_spaces - 1];
3724 : : }
3725 : :
3726 : 345409 : s->num_to_scan++;
3727 : :
3728 : : /* Check for barrier events. */
2489 rhaas@postgresql.org 3729 [ - + ]: 345409 : if (ProcSignalBarrierPending)
2489 rhaas@postgresql.org 3730 :UBC 0 : ProcessProcSignalBarrier();
3731 : : }
3732 : :
3888 andres@anarazel.de 3733 [ - + ]:CBC 1259 : Assert(num_spaces > 0);
3734 : :
3735 : : /*
3736 : : * Build a min-heap over the write-progress in the individual tablespaces,
3737 : : * and compute how large a portion of the total progress a single
3738 : : * processed buffer is.
3739 : : */
3740 : 1259 : ts_heap = binaryheap_allocate(num_spaces,
3741 : : ts_ckpt_progress_comparator,
3742 : : NULL);
3743 : :
3744 [ + + ]: 3137 : for (i = 0; i < num_spaces; i++)
3745 : : {
3746 : 1878 : CkptTsStatus *ts_stat = &per_ts_stat[i];
3747 : :
3748 : 1878 : ts_stat->progress_slice = (float8) num_to_scan / ts_stat->num_to_scan;
3749 : :
3750 : 1878 : binaryheap_add_unordered(ts_heap, PointerGetDatum(ts_stat));
3751 : : }
3752 : :
3753 : 1259 : binaryheap_build(ts_heap);
3754 : :
3755 : : /*
3756 : : * Iterate through to-be-checkpointed buffers and write the ones (still)
3757 : : * marked with BM_CHECKPOINT_NEEDED. The writes are balanced between
3758 : : * tablespaces; otherwise the sorting would lead to only one tablespace
3759 : : * receiving writes at a time, making inefficient use of the hardware.
3760 : : */
3761 : 1259 : num_processed = 0;
7046 tgl@sss.pgh.pa.us 3762 : 1259 : num_written = 0;
3888 andres@anarazel.de 3763 [ + + ]: 346668 : while (!binaryheap_empty(ts_heap))
3764 : : {
3765 : 345409 : BufferDesc *bufHdr = NULL;
3766 : : CkptTsStatus *ts_stat = (CkptTsStatus *)
1242 tgl@sss.pgh.pa.us 3767 : 345409 : DatumGetPointer(binaryheap_first(ts_heap));
3768 : :
3888 andres@anarazel.de 3769 : 345409 : buf_id = CkptBufferIds[ts_stat->index].buf_id;
3770 [ - + ]: 345409 : Assert(buf_id != -1);
3771 : :
3772 : 345409 : bufHdr = GetBufferDescriptor(buf_id);
3773 : :
3774 : 345409 : num_processed++;
3775 : :
3776 : : /*
3777 : : * We don't need to acquire the lock here, because we're only looking
3778 : : * at a single bit. It's possible that someone else writes the buffer
3779 : : * and clears the flag right after we check, but that doesn't matter
3780 : : * since SyncOneBuffer will then do nothing. However, there is a
3781 : : * further race condition: it's conceivable that between the time we
3782 : : * examine the bit here and the time SyncOneBuffer acquires the lock,
3783 : : * someone else not only wrote the buffer but replaced it with another
3784 : : * page and dirtied it. In that improbable case, SyncOneBuffer will
3785 : : * write the buffer though we didn't need to. It doesn't seem worth
3786 : : * guarding against this, though.
3787 : : */
270 3788 [ + + ]: 345409 : if (pg_atomic_read_u64(&bufHdr->state) & BM_CHECKPOINT_NEEDED)
3789 : : {
3888 3790 [ + + ]: 324111 : if (SyncOneBuffer(buf_id, false, &wb_context) & BUF_WRITTEN)
3791 : : {
3792 : : TRACE_POSTGRESQL_BUFFER_SYNC_WRITTEN(buf_id);
1078 michael@paquier.xyz 3793 : 324110 : PendingCheckpointerStats.buffers_written++;
7046 tgl@sss.pgh.pa.us 3794 : 324110 : num_written++;
3795 : : }
3796 : : }
3797 : :
3798 : : /*
3799 : : * Measure progress independent of actually having to flush the buffer
3800 : : * - otherwise writing become unbalanced.
3801 : : */
3888 andres@anarazel.de 3802 : 345409 : ts_stat->progress += ts_stat->progress_slice;
3803 : 345409 : ts_stat->num_scanned++;
3804 : 345409 : ts_stat->index++;
3805 : :
3806 : : /* Have all the buffers from the tablespace been processed? */
3807 [ + + ]: 345409 : if (ts_stat->num_scanned == ts_stat->num_to_scan)
3808 : : {
3809 : 1878 : binaryheap_remove_first(ts_heap);
3810 : : }
3811 : : else
3812 : : {
3813 : : /* update heap with the new progress */
3814 : 343531 : binaryheap_replace_first(ts_heap, PointerGetDatum(ts_stat));
3815 : : }
3816 : :
3817 : : /*
3818 : : * Sleep to throttle our I/O rate.
3819 : : *
3820 : : * (This will check for barrier events even if it doesn't sleep.)
3821 : : */
3822 : 345409 : CheckpointWriteDelay(flags, (double) num_processed / num_to_scan);
3823 : : }
3824 : :
3825 : : /*
3826 : : * Issue all pending flushes. Only checkpointer calls BufferSync(), so
3827 : : * IOContext will always be IOCONTEXT_NORMAL.
3828 : : */
1244 3829 : 1259 : IssuePendingWritebacks(&wb_context, IOCONTEXT_NORMAL);
3830 : :
3888 3831 : 1259 : pfree(per_ts_stat);
3832 : 1259 : per_ts_stat = NULL;
3833 : 1259 : binaryheap_free(ts_heap);
3834 : :
3835 : : /*
3836 : : * Update checkpoint statistics. As noted above, this doesn't include
3837 : : * buffers written by other backends or bgwriter scan.
3838 : : */
7044 tgl@sss.pgh.pa.us 3839 : 1259 : CheckpointStats.ckpt_bufs_written += num_written;
3840 : :
3841 : : TRACE_POSTGRESQL_BUFFER_SYNC_DONE(NBuffers, num_written, num_to_scan);
3842 : : }
3843 : :
3844 : : /*
3845 : : * BgBufferSync -- Write out some dirty buffers in the pool.
3846 : : *
3847 : : * This is called periodically by the background writer process.
3848 : : *
3849 : : * Returns true if it's appropriate for the bgwriter process to go into
3850 : : * low-power hibernation mode. (This happens if the strategy clock-sweep
3851 : : * has been "lapped" and no buffer allocations have occurred recently,
3852 : : * or if the bgwriter has been effectively disabled by setting
3853 : : * bgwriter_lru_maxpages to 0.)
3854 : : */
3855 : : bool
3888 andres@anarazel.de 3856 : 21858 : BgBufferSync(WritebackContext *wb_context)
3857 : : {
3858 : : /* info obtained from freelist.c */
3859 : : int strategy_buf_id;
3860 : : uint32 strategy_passes;
3861 : : uint32 recent_alloc;
3862 : :
3863 : : /*
3864 : : * Information saved between calls so we can determine the strategy
3865 : : * point's advance rate and avoid scanning already-cleaned buffers.
3866 : : */
3867 : : static bool saved_info_valid = false;
3868 : : static int prev_strategy_buf_id;
3869 : : static uint32 prev_strategy_passes;
3870 : : static int next_to_clean;
3871 : : static uint32 next_passes;
3872 : :
3873 : : /* Moving averages of allocation rate and clean-buffer density */
3874 : : static float smoothed_alloc = 0;
3875 : : static float smoothed_density = 10.0;
3876 : :
3877 : : /* Potentially these could be tunables, but for now, not */
6957 tgl@sss.pgh.pa.us 3878 : 21858 : float smoothing_samples = 16;
3879 : 21858 : float scan_whole_pool_milliseconds = 120000.0;
3880 : :
3881 : : /* Used to compute how far we scan ahead */
3882 : : long strategy_delta;
3883 : : int bufs_to_lap;
3884 : : int bufs_ahead;
3885 : : float scans_per_alloc;
3886 : : int reusable_buffers_est;
3887 : : int upcoming_alloc_est;
3888 : : int min_scan_buffers;
3889 : :
3890 : : /* Variables for the scanning loop proper */
3891 : : int num_to_scan;
3892 : : int num_written;
3893 : : int reusable_buffers;
3894 : :
3895 : : /* Variables for final smoothed_density update */
3896 : : long new_strategy_delta;
3897 : : uint32 new_recent_alloc;
3898 : :
3899 : : /*
3900 : : * Find out where the clock-sweep currently is, and how many buffer
3901 : : * allocations have happened since our last call.
3902 : : */
3903 : 21858 : strategy_buf_id = StrategySyncStart(&strategy_passes, &recent_alloc);
3904 : :
3905 : : /* Report buffer alloc counts to pgstat */
1650 andres@anarazel.de 3906 : 21858 : PendingBgWriterStats.buf_alloc += recent_alloc;
3907 : :
3908 : : /*
3909 : : * If we're not running the LRU scan, just stop after doing the stats
3910 : : * stuff. We mark the saved state invalid so that we can recover sanely
3911 : : * if LRU scan is turned back on later.
3912 : : */
6957 tgl@sss.pgh.pa.us 3913 [ + + ]: 21858 : if (bgwriter_lru_maxpages <= 0)
3914 : : {
3915 : 72 : saved_info_valid = false;
5373 heikki.linnakangas@i 3916 : 72 : return true;
3917 : : }
3918 : :
3919 : : /*
3920 : : * Compute strategy_delta = how many buffers have been scanned by the
3921 : : * clock-sweep since last time. If first time through, assume none. Then
3922 : : * see if we are still ahead of the clock-sweep, and if so, how many
3923 : : * buffers we could scan before we'd catch up with it and "lap" it. Note:
3924 : : * weird-looking coding of xxx_passes comparisons are to avoid bogus
3925 : : * behavior when the passes counts wrap around.
3926 : : */
6957 tgl@sss.pgh.pa.us 3927 [ + + ]: 21786 : if (saved_info_valid)
3928 : : {
6906 bruce@momjian.us 3929 : 21142 : int32 passes_delta = strategy_passes - prev_strategy_passes;
3930 : :
6957 tgl@sss.pgh.pa.us 3931 : 21142 : strategy_delta = strategy_buf_id - prev_strategy_buf_id;
3400 3932 : 21142 : strategy_delta += (long) passes_delta * NBuffers;
3933 : :
6957 3934 [ - + ]: 21142 : Assert(strategy_delta >= 0);
3935 : :
3936 [ + + ]: 21142 : if ((int32) (next_passes - strategy_passes) > 0)
3937 : : {
3938 : : /* we're one pass ahead of the strategy point */
3939 : 7139 : bufs_to_lap = strategy_buf_id - next_to_clean;
3940 : : #ifdef BGW_DEBUG
3941 : : elog(DEBUG2, "bgwriter ahead: bgw %u-%u strategy %u-%u delta=%ld lap=%d",
3942 : : next_passes, next_to_clean,
3943 : : strategy_passes, strategy_buf_id,
3944 : : strategy_delta, bufs_to_lap);
3945 : : #endif
3946 : : }
3947 [ + + ]: 14003 : else if (next_passes == strategy_passes &&
3948 [ + + ]: 10063 : next_to_clean >= strategy_buf_id)
3949 : : {
3950 : : /* on same pass, but ahead or at least not behind */
3951 : 8799 : bufs_to_lap = NBuffers - (next_to_clean - strategy_buf_id);
3952 : : #ifdef BGW_DEBUG
3953 : : elog(DEBUG2, "bgwriter ahead: bgw %u-%u strategy %u-%u delta=%ld lap=%d",
3954 : : next_passes, next_to_clean,
3955 : : strategy_passes, strategy_buf_id,
3956 : : strategy_delta, bufs_to_lap);
3957 : : #endif
3958 : : }
3959 : : else
3960 : : {
3961 : : /*
3962 : : * We're behind, so skip forward to the strategy point and start
3963 : : * cleaning from there.
3964 : : */
3965 : : #ifdef BGW_DEBUG
3966 : : elog(DEBUG2, "bgwriter behind: bgw %u-%u strategy %u-%u delta=%ld",
3967 : : next_passes, next_to_clean,
3968 : : strategy_passes, strategy_buf_id,
3969 : : strategy_delta);
3970 : : #endif
3971 : 5204 : next_to_clean = strategy_buf_id;
3972 : 5204 : next_passes = strategy_passes;
3973 : 5204 : bufs_to_lap = NBuffers;
3974 : : }
3975 : : }
3976 : : else
3977 : : {
3978 : : /*
3979 : : * Initializing at startup or after LRU scanning had been off. Always
3980 : : * start at the strategy point.
3981 : : */
3982 : : #ifdef BGW_DEBUG
3983 : : elog(DEBUG2, "bgwriter initializing: strategy %u-%u",
3984 : : strategy_passes, strategy_buf_id);
3985 : : #endif
3986 : 644 : strategy_delta = 0;
3987 : 644 : next_to_clean = strategy_buf_id;
3988 : 644 : next_passes = strategy_passes;
3989 : 644 : bufs_to_lap = NBuffers;
3990 : : }
3991 : :
3992 : : /* Update saved info for next time */
3993 : 21786 : prev_strategy_buf_id = strategy_buf_id;
3994 : 21786 : prev_strategy_passes = strategy_passes;
3995 : 21786 : saved_info_valid = true;
3996 : :
3997 : : /*
3998 : : * Compute how many buffers had to be scanned for each new allocation, ie,
3999 : : * 1/density of reusable buffers, and track a moving average of that.
4000 : : *
4001 : : * If the strategy point didn't move, we don't update the density estimate
4002 : : */
4003 [ + + + - ]: 21786 : if (strategy_delta > 0 && recent_alloc > 0)
4004 : : {
4005 : 15327 : scans_per_alloc = (float) strategy_delta / (float) recent_alloc;
4006 : 15327 : smoothed_density += (scans_per_alloc - smoothed_density) /
4007 : : smoothing_samples;
4008 : : }
4009 : :
4010 : : /*
4011 : : * Estimate how many reusable buffers there are between the current
4012 : : * strategy point and where we've scanned ahead to, based on the smoothed
4013 : : * density estimate.
4014 : : */
4015 : 21786 : bufs_ahead = NBuffers - bufs_to_lap;
4016 : 21786 : reusable_buffers_est = (float) bufs_ahead / smoothed_density;
4017 : :
4018 : : /*
4019 : : * Track a moving average of recent buffer allocations. Here, rather than
4020 : : * a true average we want a fast-attack, slow-decline behavior: we
4021 : : * immediately follow any increase.
4022 : : */
4023 [ + + ]: 21786 : if (smoothed_alloc <= (float) recent_alloc)
4024 : 3939 : smoothed_alloc = recent_alloc;
4025 : : else
4026 : 17847 : smoothed_alloc += ((float) recent_alloc - smoothed_alloc) /
4027 : : smoothing_samples;
4028 : :
4029 : : /* Scale the estimate by a GUC to allow more aggressive tuning. */
5441 4030 : 21786 : upcoming_alloc_est = (int) (smoothed_alloc * bgwriter_lru_multiplier);
4031 : :
4032 : : /*
4033 : : * If recent_alloc remains at zero for many cycles, smoothed_alloc will
4034 : : * eventually underflow to zero, and the underflows produce annoying
4035 : : * kernel warnings on some platforms. Once upcoming_alloc_est has gone to
4036 : : * zero, there's no point in tracking smaller and smaller values of
4037 : : * smoothed_alloc, so just reset it to exactly zero to avoid this
4038 : : * syndrome. It will pop back up as soon as recent_alloc increases.
4039 : : */
4040 [ + + ]: 21786 : if (upcoming_alloc_est == 0)
4041 : 1329 : smoothed_alloc = 0;
4042 : :
4043 : : /*
4044 : : * Even in cases where there's been little or no buffer allocation
4045 : : * activity, we want to make a small amount of progress through the buffer
4046 : : * cache so that as many reusable buffers as possible are clean after an
4047 : : * idle period.
4048 : : *
4049 : : * (scan_whole_pool_milliseconds / BgWriterDelay) computes how many times
4050 : : * the BGW will be called during the scan_whole_pool time; slice the
4051 : : * buffer pool into that many sections.
4052 : : */
6957 4053 : 21786 : min_scan_buffers = (int) (NBuffers / (scan_whole_pool_milliseconds / BgWriterDelay));
4054 : :
4055 [ + + ]: 21786 : if (upcoming_alloc_est < (min_scan_buffers + reusable_buffers_est))
4056 : : {
4057 : : #ifdef BGW_DEBUG
4058 : : elog(DEBUG2, "bgwriter: alloc_est=%d too small, using min=%d + reusable_est=%d",
4059 : : upcoming_alloc_est, min_scan_buffers, reusable_buffers_est);
4060 : : #endif
4061 : 11500 : upcoming_alloc_est = min_scan_buffers + reusable_buffers_est;
4062 : : }
4063 : :
4064 : : /*
4065 : : * Now write out dirty reusable buffers, working forward from the
4066 : : * next_to_clean point, until we have lapped the strategy scan, or cleaned
4067 : : * enough buffers to match our estimate of the next cycle's allocation
4068 : : * requirements, or hit the bgwriter_lru_maxpages limit.
4069 : : */
4070 : :
4071 : 21786 : num_to_scan = bufs_to_lap;
4072 : 21786 : num_written = 0;
4073 : 21786 : reusable_buffers = reusable_buffers_est;
4074 : :
4075 : : /* Execute the LRU scan */
4076 [ + + + + ]: 2326281 : while (num_to_scan > 0 && reusable_buffers < upcoming_alloc_est)
4077 : : {
3837 andres@anarazel.de 4078 : 2304497 : int sync_state = SyncOneBuffer(next_to_clean, true,
4079 : : wb_context);
4080 : :
6957 tgl@sss.pgh.pa.us 4081 [ + + ]: 2304497 : if (++next_to_clean >= NBuffers)
4082 : : {
4083 : 5335 : next_to_clean = 0;
4084 : 5335 : next_passes++;
4085 : : }
4086 : 2304497 : num_to_scan--;
4087 : :
3837 andres@anarazel.de 4088 [ + + ]: 2304497 : if (sync_state & BUF_WRITTEN)
4089 : : {
6957 tgl@sss.pgh.pa.us 4090 : 52540 : reusable_buffers++;
4091 [ + + ]: 52540 : if (++num_written >= bgwriter_lru_maxpages)
4092 : : {
1650 andres@anarazel.de 4093 : 2 : PendingBgWriterStats.maxwritten_clean++;
6957 tgl@sss.pgh.pa.us 4094 : 2 : break;
4095 : : }
4096 : : }
3837 andres@anarazel.de 4097 [ + + ]: 2251957 : else if (sync_state & BUF_REUSABLE)
6957 tgl@sss.pgh.pa.us 4098 : 1569414 : reusable_buffers++;
4099 : : }
4100 : :
1650 andres@anarazel.de 4101 : 21786 : PendingBgWriterStats.buf_written_clean += num_written;
4102 : :
4103 : : #ifdef BGW_DEBUG
4104 : : 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",
4105 : : recent_alloc, smoothed_alloc, strategy_delta, bufs_ahead,
4106 : : smoothed_density, reusable_buffers_est, upcoming_alloc_est,
4107 : : bufs_to_lap - num_to_scan,
4108 : : num_written,
4109 : : reusable_buffers - reusable_buffers_est);
4110 : : #endif
4111 : :
4112 : : /*
4113 : : * Consider the above scan as being like a new allocation scan.
4114 : : * Characterize its density and update the smoothed one based on it. This
4115 : : * effectively halves the moving average period in cases where both the
4116 : : * strategy and the background writer are doing some useful scanning,
4117 : : * which is helpful because a long memory isn't as desirable on the
4118 : : * density estimates.
4119 : : */
5269 tgl@sss.pgh.pa.us 4120 : 21786 : new_strategy_delta = bufs_to_lap - num_to_scan;
4121 : 21786 : new_recent_alloc = reusable_buffers - reusable_buffers_est;
4122 [ + + + + ]: 21786 : if (new_strategy_delta > 0 && new_recent_alloc > 0)
4123 : : {
4124 : 17205 : scans_per_alloc = (float) new_strategy_delta / (float) new_recent_alloc;
6957 4125 : 17205 : smoothed_density += (scans_per_alloc - smoothed_density) /
4126 : : smoothing_samples;
4127 : :
4128 : : #ifdef BGW_DEBUG
4129 : : elog(DEBUG2, "bgwriter: cleaner density alloc=%u scan=%ld density=%.2f new smoothed=%.2f",
4130 : : new_recent_alloc, new_strategy_delta,
4131 : : scans_per_alloc, smoothed_density);
4132 : : #endif
4133 : : }
4134 : :
4135 : : /* Return true if OK to hibernate */
5269 4136 [ + + + - ]: 21786 : return (bufs_to_lap == 0 && recent_alloc == 0);
4137 : : }
4138 : :
4139 : : /*
4140 : : * SyncOneBuffer -- process a single buffer during syncing.
4141 : : *
4142 : : * If skip_recently_used is true, we don't write currently-pinned buffers, nor
4143 : : * buffers marked recently used, as these are not replacement candidates.
4144 : : *
4145 : : * Returns a bitmask containing the following flag bits:
4146 : : * BUF_WRITTEN: we wrote the buffer.
4147 : : * BUF_REUSABLE: buffer is available for replacement, ie, it has
4148 : : * pin count 0 and usage count 0.
4149 : : *
4150 : : * (BUF_WRITTEN could be set in error if FlushBuffer finds the buffer clean
4151 : : * after locking it, but we don't care all that much.)
4152 : : */
4153 : : static int
3888 andres@anarazel.de 4154 : 2628608 : SyncOneBuffer(int buf_id, bool skip_recently_used, WritebackContext *wb_context)
4155 : : {
3983 rhaas@postgresql.org 4156 : 2628608 : BufferDesc *bufHdr = GetBufferDescriptor(buf_id);
6906 bruce@momjian.us 4157 : 2628608 : int result = 0;
4158 : : uint64 buf_state;
4159 : : BufferTag tag;
4160 : :
4161 : : /* Make sure we can handle the pin */
4284 andres@anarazel.de 4162 : 2628608 : ReservePrivateRefCountEntry();
1069 heikki.linnakangas@i 4163 : 2628608 : ResourceOwnerEnlarge(CurrentResourceOwner);
4164 : :
4165 : : /*
4166 : : * Check whether buffer needs writing.
4167 : : *
4168 : : * We can make this check without taking the buffer content lock so long
4169 : : * as we mark pages dirty in access methods *before* logging changes with
4170 : : * XLogInsert(): if someone marks the buffer dirty just after our check we
4171 : : * don't worry because our checkpoint.redo points before log record for
4172 : : * upcoming changes and so we are not required to write such dirty buffer.
4173 : : */
3837 andres@anarazel.de 4174 : 2628608 : buf_state = LockBufHdr(bufHdr);
4175 : :
4176 [ + + ]: 2628608 : if (BUF_STATE_GET_REFCOUNT(buf_state) == 0 &&
4177 [ + + ]: 2617400 : BUF_STATE_GET_USAGECOUNT(buf_state) == 0)
4178 : : {
6957 tgl@sss.pgh.pa.us 4179 : 1623599 : result |= BUF_REUSABLE;
4180 : : }
4181 [ + + ]: 1005009 : else if (skip_recently_used)
4182 : : {
4183 : : /* Caller told us not to write recently-used buffers */
340 andres@anarazel.de 4184 : 682543 : UnlockBufHdr(bufHdr);
6957 tgl@sss.pgh.pa.us 4185 : 682543 : return result;
4186 : : }
4187 : :
3837 andres@anarazel.de 4188 [ + + + + ]: 1946065 : if (!(buf_state & BM_VALID) || !(buf_state & BM_DIRTY))
4189 : : {
4190 : : /* It's clean, so nothing to do */
340 4191 : 1569415 : UnlockBufHdr(bufHdr);
6957 tgl@sss.pgh.pa.us 4192 : 1569415 : return result;
4193 : : }
4194 : :
4195 : : /*
4196 : : * Pin it, share-exclusive-lock it, write it. (FlushBuffer will do
4197 : : * nothing if the buffer is clean by the time we've locked it.)
4198 : : */
7892 4199 : 376650 : PinBuffer_Locked(bufHdr);
4200 : :
369 andres@anarazel.de 4201 : 376650 : FlushUnlockedBuffer(bufHdr, NULL, IOOBJECT_RELATION, IOCONTEXT_NORMAL);
4202 : :
3888 4203 : 376650 : tag = bufHdr->tag;
4204 : :
1473 michael@paquier.xyz 4205 : 376650 : UnpinBuffer(bufHdr);
4206 : :
4207 : : /*
4208 : : * SyncOneBuffer() is only called by checkpointer and bgwriter, so
4209 : : * IOContext will always be IOCONTEXT_NORMAL.
4210 : : */
1244 andres@anarazel.de 4211 : 376650 : ScheduleBufferTagForWriteback(wb_context, IOCONTEXT_NORMAL, &tag);
4212 : :
6957 tgl@sss.pgh.pa.us 4213 : 376650 : return result | BUF_WRITTEN;
4214 : : }
4215 : :
4216 : : /*
4217 : : * AtEOXact_Buffers - clean up at end of transaction.
4218 : : *
4219 : : * As of PostgreSQL 8.0, buffer pins should get released by the
4220 : : * ResourceOwner mechanism. This routine is just a debugging
4221 : : * cross-check that no pins remain.
4222 : : */
4223 : : void
8833 4224 : 427069 : AtEOXact_Buffers(bool isCommit)
4225 : : {
4497 andres@anarazel.de 4226 : 427069 : CheckForBufferLeaks();
4227 : :
8031 tgl@sss.pgh.pa.us 4228 : 427069 : AtEOXact_LocalBuffers(isCommit);
4229 : :
4426 andres@anarazel.de 4230 [ - + ]: 427069 : Assert(PrivateRefCountOverflowed == 0);
4231 : 427069 : }
4232 : :
4233 : : /*
4234 : : * Initialize access to shared buffer pool
4235 : : *
4236 : : * This is called during backend startup (whether standalone or under the
4237 : : * postmaster). It sets up for this backend's access to the already-existing
4238 : : * buffer pool.
4239 : : */
4240 : : void
774 heikki.linnakangas@i 4241 : 23932 : InitBufferManagerAccess(void)
4242 : : {
4243 : : /*
4244 : : * An advisory limit on the number of pins each backend should hold, based
4245 : : * on shared_buffers and the maximum number of connections possible.
4246 : : * That's very pessimistic, but outside toy-sized shared_buffers it should
4247 : : * allow plenty of pins. LimitAdditionalPins() and
4248 : : * GetAdditionalPinLimit() can be used to check the remaining balance.
4249 : : */
577 tmunro@postgresql.or 4250 : 23932 : MaxProportionalPins = NBuffers / (MaxBackends + NUM_AUXILIARY_PROCS);
4251 : :
4426 andres@anarazel.de 4252 : 23932 : memset(&PrivateRefCountArray, 0, sizeof(PrivateRefCountArray));
302 4253 : 23932 : memset(&PrivateRefCountArrayKeys, 0, sizeof(PrivateRefCountArrayKeys));
4254 : :
214 pg@bowt.ie 4255 : 23932 : PrivateRefCountHash = refcount_create(CurrentMemoryContext, 100, NULL);
4256 : :
4257 : : /* Initialize per-backend file flush context */
2 heikki.linnakangas@i 4258 : 23932 : WritebackContextInit(&BackendWritebackContext,
4259 : : &backend_flush_after);
4260 : :
4261 : : /*
4262 : : * AtProcExit_Buffers needs LWLock access, and thereby has to be called at
4263 : : * the corresponding phase of backend shutdown.
4264 : : */
1894 andres@anarazel.de 4265 [ - + ]: 23932 : Assert(MyProc != NULL);
7735 tgl@sss.pgh.pa.us 4266 : 23932 : on_shmem_exit(AtProcExit_Buffers, 0);
4267 : 23932 : }
4268 : :
4269 : : /*
4270 : : * During backend exit, ensure that we released all shared-buffer locks and
4271 : : * assert that we have no remaining pins.
4272 : : */
4273 : : static void
4274 : 23932 : AtProcExit_Buffers(int code, Datum arg)
4275 : : {
8031 4276 : 23932 : UnlockBuffers();
4277 : :
4497 andres@anarazel.de 4278 : 23932 : CheckForBufferLeaks();
4279 : :
4280 : : /* localbuf.c needs a chance too */
4281 : 23932 : AtProcExit_LocalBuffers();
4282 : 23932 : }
4283 : :
4284 : : /*
4285 : : * CheckForBufferLeaks - ensure this backend holds no buffer pins
4286 : : *
4287 : : * As of PostgreSQL 8.0, buffer pins should get released by the
4288 : : * ResourceOwner mechanism. This routine is just a debugging
4289 : : * cross-check that no pins remain.
4290 : : */
4291 : : static void
4292 : 451001 : CheckForBufferLeaks(void)
4293 : : {
4294 : : #ifdef USE_ASSERT_CHECKING
4295 : 451001 : int RefCountErrors = 0;
4296 : : PrivateRefCountEntry *res;
4297 : : int i;
4298 : : char *s;
4299 : :
4300 : : /* check the array */
4426 4301 [ + + ]: 4059009 : for (i = 0; i < REFCOUNT_ARRAY_ENTRIES; i++)
4302 : : {
302 4303 [ - + ]: 3608008 : if (PrivateRefCountArrayKeys[i] != InvalidBuffer)
4304 : : {
302 andres@anarazel.de 4305 :UBC 0 : res = &PrivateRefCountArray[i];
4306 : :
1069 heikki.linnakangas@i 4307 : 0 : s = DebugPrintBufferRefcount(res->buffer);
4308 [ # # ]: 0 : elog(WARNING, "buffer refcount leak: %s", s);
4309 : 0 : pfree(s);
4310 : :
4426 andres@anarazel.de 4311 : 0 : RefCountErrors++;
4312 : : }
4313 : : }
4314 : :
4315 : : /* if necessary search the hash */
4426 andres@anarazel.de 4316 [ - + ]:CBC 451001 : if (PrivateRefCountOverflowed)
4317 : : {
4318 : : refcount_iterator iter;
4319 : :
214 pg@bowt.ie 4320 :UBC 0 : refcount_start_iterate(PrivateRefCountHash, &iter);
4321 [ # # ]: 0 : while ((res = refcount_iterate(PrivateRefCountHash, &iter)) != NULL)
4322 : : {
1069 heikki.linnakangas@i 4323 : 0 : s = DebugPrintBufferRefcount(res->buffer);
4324 [ # # ]: 0 : elog(WARNING, "buffer refcount leak: %s", s);
4325 : 0 : pfree(s);
4497 andres@anarazel.de 4326 : 0 : RefCountErrors++;
4327 : : }
4328 : : }
4329 : :
4497 andres@anarazel.de 4330 [ - + ]:CBC 451001 : Assert(RefCountErrors == 0);
4331 : : #endif
8031 tgl@sss.pgh.pa.us 4332 : 451001 : }
4333 : :
4334 : : #ifdef USE_ASSERT_CHECKING
4335 : : /*
4336 : : * Check for exclusive-locked catalog buffers. This is the core of
4337 : : * AssertCouldGetRelation().
4338 : : *
4339 : : * A backend would self-deadlock on the content lock if the catalog scan read
4340 : : * the exclusive-locked buffer. The main threat is exclusive-locked buffers
4341 : : * of catalogs used in relcache, because a catcache search on any catalog may
4342 : : * build that catalog's relcache entry. We don't have an inventory of
4343 : : * catalogs relcache uses, so just check buffers of most catalogs.
4344 : : *
4345 : : * It's better to minimize waits while holding an exclusive buffer lock, so it
4346 : : * would be nice to broaden this check not to be catalog-specific. However,
4347 : : * bttextcmp() accesses pg_collation, and non-core opclasses might similarly
4348 : : * read tables. That is deadlock-free as long as there's no loop in the
4349 : : * dependency graph: modifying table A may cause an opclass to read table B,
4350 : : * but it must not cause a read of table A.
4351 : : */
4352 : : void
543 noah@leadboat.com 4353 : 140842690 : AssertBufferLocksPermitCatalogRead(void)
4354 : : {
4355 : : PrivateRefCountEntry *res;
4356 : :
4357 : : /* check the array */
270 andres@anarazel.de 4358 [ + + ]: 1267584210 : for (int i = 0; i < REFCOUNT_ARRAY_ENTRIES; i++)
4359 : : {
4360 [ + + ]: 1126741520 : if (PrivateRefCountArrayKeys[i] != InvalidBuffer)
4361 : : {
4362 : 40635646 : res = &PrivateRefCountArray[i];
4363 : :
4364 [ - + ]: 40635646 : if (res->buffer == InvalidBuffer)
270 andres@anarazel.de 4365 :UBC 0 : continue;
4366 : :
270 andres@anarazel.de 4367 :CBC 40635646 : AssertNotCatalogBufferLock(res->buffer, res->data.lockmode);
4368 : : }
4369 : : }
4370 : :
4371 : : /* if necessary search the hash */
4372 [ + + ]: 140842690 : if (PrivateRefCountOverflowed)
4373 : : {
4374 : : refcount_iterator iter;
4375 : :
214 pg@bowt.ie 4376 : 152047 : refcount_start_iterate(PrivateRefCountHash, &iter);
4377 [ + + ]: 388264 : while ((res = refcount_iterate(PrivateRefCountHash, &iter)) != NULL)
4378 : : {
270 andres@anarazel.de 4379 : 236217 : AssertNotCatalogBufferLock(res->buffer, res->data.lockmode);
4380 : : }
4381 : : }
543 noah@leadboat.com 4382 : 140842690 : }
4383 : :
4384 : : static void
270 andres@anarazel.de 4385 : 40871863 : AssertNotCatalogBufferLock(Buffer buffer, BufferLockMode mode)
4386 : : {
4387 : 40871863 : BufferDesc *bufHdr = GetBufferDescriptor(buffer - 1);
4388 : : BufferTag tag;
4389 : : Oid relid;
4390 : :
4391 [ + + ]: 40871863 : if (mode != BUFFER_LOCK_EXCLUSIVE)
543 noah@leadboat.com 4392 : 40860523 : return;
4393 : :
4394 : 11340 : tag = bufHdr->tag;
4395 : :
4396 : : /*
4397 : : * This relNumber==relid assumption holds until a catalog experiences
4398 : : * VACUUM FULL or similar. After a command like that, relNumber will be
4399 : : * in the normal (non-catalog) range, and we lose the ability to detect
4400 : : * hazardous access to that catalog. Calling RelidByRelfilenumber() would
4401 : : * close that gap, but RelidByRelfilenumber() might then deadlock with a
4402 : : * held lock.
4403 : : */
4404 : 11340 : relid = tag.relNumber;
4405 : :
4406 [ - + ]: 11340 : if (IsCatalogTextUniqueIndexOid(relid)) /* see comments at the callee */
543 noah@leadboat.com 4407 :UBC 0 : return;
4408 : :
543 noah@leadboat.com 4409 [ - + ]:CBC 11340 : Assert(!IsCatalogRelationOid(relid));
4410 : : }
4411 : : #endif
4412 : :
4413 : :
4414 : : /*
4415 : : * Helper routine to issue warnings when a buffer is unexpectedly pinned
4416 : : */
4417 : : char *
1069 heikki.linnakangas@i 4418 : 46 : DebugPrintBufferRefcount(Buffer buffer)
4419 : : {
4420 : : BufferDesc *buf;
4421 : : int32 loccount;
4422 : : char *result;
4423 : : ProcNumber backend;
4424 : : uint64 buf_state;
4425 : :
8031 tgl@sss.pgh.pa.us 4426 [ - + ]: 46 : Assert(BufferIsValid(buffer));
4427 [ + + ]: 46 : if (BufferIsLocal(buffer))
4428 : : {
4274 andres@anarazel.de 4429 : 16 : buf = GetLocalBufferDescriptor(-buffer - 1);
8031 tgl@sss.pgh.pa.us 4430 : 16 : loccount = LocalRefCount[-buffer - 1];
953 heikki.linnakangas@i 4431 : 16 : backend = MyProcNumber;
4432 : : }
4433 : : else
4434 : : {
4274 andres@anarazel.de 4435 : 30 : buf = GetBufferDescriptor(buffer - 1);
4426 4436 : 30 : loccount = GetPrivateRefCount(buffer);
953 heikki.linnakangas@i 4437 : 30 : backend = INVALID_PROC_NUMBER;
4438 : : }
4439 : :
4440 : : /* theoretically we should lock the bufHdr here */
270 andres@anarazel.de 4441 : 46 : buf_state = pg_atomic_read_u64(&buf->state);
4442 : :
4443 : 46 : result = psprintf("[%03d] (rel=%s, blockNum=%u, flags=0x%" PRIx64 ", refcount=%u %d)",
4444 : : buffer,
594 4445 : 46 : relpathbackend(BufTagGetRelFileLocator(&buf->tag), backend,
4446 : : BufTagGetForkNum(&buf->tag)).str,
4447 : : buf->tag.blockNum, buf_state & BUF_FLAG_MASK,
4448 : : BUF_STATE_GET_REFCOUNT(buf_state), loccount);
1069 heikki.linnakangas@i 4449 : 46 : return result;
4450 : : }
4451 : :
4452 : : /*
4453 : : * CheckPointBuffers
4454 : : *
4455 : : * Flush all dirty blocks in buffer pool to disk at checkpoint time.
4456 : : *
4457 : : * Note: temporary relations do not participate in checkpoints, so they don't
4458 : : * need to be flushed.
4459 : : */
4460 : : void
7046 tgl@sss.pgh.pa.us 4461 : 1998 : CheckPointBuffers(int flags)
4462 : : {
4463 : 1998 : BufferSync(flags);
9447 vadim4o@yahoo.com 4464 : 1998 : }
4465 : :
4466 : : /*
4467 : : * BufferGetBlockNumber
4468 : : * Returns the block number associated with a buffer.
4469 : : *
4470 : : * Note:
4471 : : * Assumes that the buffer is valid and pinned, else the
4472 : : * value may be obsolete immediately...
4473 : : */
4474 : : BlockNumber
11052 scrappy@hub.org 4475 : 224381753 : BufferGetBlockNumber(Buffer buffer)
4476 : : {
4477 : : BufferDesc *bufHdr;
4478 : :
8946 bruce@momjian.us 4479 [ - + + + : 224381753 : Assert(BufferIsPinned(buffer));
- + ]
4480 : :
10627 4481 [ + + ]: 224381753 : if (BufferIsLocal(buffer))
4274 andres@anarazel.de 4482 : 5008204 : bufHdr = GetLocalBufferDescriptor(-buffer - 1);
4483 : : else
4484 : 219373549 : bufHdr = GetBufferDescriptor(buffer - 1);
4485 : :
4486 : : /* pinned, so OK to read tag without spinlock */
7892 tgl@sss.pgh.pa.us 4487 : 224381753 : return bufHdr->tag.blockNum;
4488 : : }
4489 : :
4490 : : /*
4491 : : * BufferGetTag
4492 : : * Returns the relfilelocator, fork number and block number associated with
4493 : : * a buffer.
4494 : : */
4495 : : void
1559 rhaas@postgresql.org 4496 : 27713085 : BufferGetTag(Buffer buffer, RelFileLocator *rlocator, ForkNumber *forknum,
4497 : : BlockNumber *blknum)
4498 : : {
4499 : : BufferDesc *bufHdr;
4500 : :
4501 : : /* Do the same checks as BufferGetBlockNumber. */
6636 heikki.linnakangas@i 4502 [ - + - + : 27713085 : Assert(BufferIsPinned(buffer));
- + ]
4503 : :
8211 tgl@sss.pgh.pa.us 4504 [ - + ]: 27713085 : if (BufferIsLocal(buffer))
4274 andres@anarazel.de 4505 :UBC 0 : bufHdr = GetLocalBufferDescriptor(-buffer - 1);
4506 : : else
4274 andres@anarazel.de 4507 :CBC 27713085 : bufHdr = GetBufferDescriptor(buffer - 1);
4508 : :
4509 : : /* pinned, so OK to read tag without spinlock */
1510 rhaas@postgresql.org 4510 : 27713085 : *rlocator = BufTagGetRelFileLocator(&bufHdr->tag);
4511 : 27713085 : *forknum = BufTagGetForkNum(&bufHdr->tag);
6636 heikki.linnakangas@i 4512 : 27713085 : *blknum = bufHdr->tag.blockNum;
8211 tgl@sss.pgh.pa.us 4513 : 27713085 : }
4514 : :
4515 : : /*
4516 : : * FlushBuffer
4517 : : * Physically write out a shared buffer.
4518 : : *
4519 : : * NOTE: this actually just passes the buffer contents to the kernel; the
4520 : : * real write to disk won't happen until the kernel feels like it. This
4521 : : * is okay from our point of view since we can redo the changes from WAL.
4522 : : * However, we will need to force the changes to disk via fsync before
4523 : : * we can checkpoint WAL.
4524 : : *
4525 : : * The caller must hold a pin on the buffer and have
4526 : : * (share-)exclusively-locked the buffer contents.
4527 : : *
4528 : : * If the caller has an smgr reference for the buffer's relation, pass it
4529 : : * as the second parameter. If not, pass NULL.
4530 : : */
4531 : : static void
1341 andres@anarazel.de 4532 : 712972 : FlushBuffer(BufferDesc *buf, SMgrRelation reln, IOObject io_object,
4533 : : IOContext io_context)
4534 : : {
4535 : : XLogRecPtr recptr;
4536 : : ErrorContextCallback errcallback;
4537 : : instr_time io_start;
4538 : : Block bufBlock;
4539 : :
216 4540 [ + + - + ]: 712972 : Assert(BufferLockHeldByMeInMode(buf, BUFFER_LOCK_EXCLUSIVE) ||
4541 : : BufferLockHeldByMeInMode(buf, BUFFER_LOCK_SHARE_EXCLUSIVE));
4542 : :
4543 : : /*
4544 : : * Try to start an I/O operation. If StartBufferIO returns false, then
4545 : : * someone else flushed the buffer before we could, so we need not do
4546 : : * anything.
4547 : : */
199 4548 [ + + ]: 712972 : if (StartSharedBufferIO(buf, false, true, NULL) == BUFFER_IO_ALREADY_DONE)
7892 tgl@sss.pgh.pa.us 4549 : 2 : return;
4550 : :
4551 : : /* Setup error traceback support for ereport() */
5082 heikki.linnakangas@i 4552 : 712970 : errcallback.callback = shared_buffer_write_error_callback;
683 peter@eisentraut.org 4553 : 712970 : errcallback.arg = buf;
5082 heikki.linnakangas@i 4554 : 712970 : errcallback.previous = error_context_stack;
4555 : 712970 : error_context_stack = &errcallback;
4556 : :
4557 : : /* Find smgr relation for buffer */
8209 tgl@sss.pgh.pa.us 4558 [ + + ]: 712970 : if (reln == NULL)
953 heikki.linnakangas@i 4559 : 710533 : reln = smgropen(BufTagGetRelFileLocator(&buf->tag), INVALID_PROC_NUMBER);
4560 : :
4561 : : TRACE_POSTGRESQL_BUFFER_FLUSH_START(BufTagGetForkNum(&buf->tag),
4562 : : buf->tag.blockNum,
4563 : : reln->smgr_rlocator.locator.spcOid,
4564 : : reln->smgr_rlocator.locator.dbOid,
4565 : : reln->smgr_rlocator.locator.relNumber);
4566 : :
4567 : : /*
4568 : : * As we hold at least a share-exclusive lock on the buffer, the LSN
4569 : : * cannot change during the flush (and thus can't be torn).
4570 : : */
4952 simon@2ndQuadrant.co 4571 : 712970 : recptr = BufferGetLSN(buf);
4572 : :
4573 : : /*
4574 : : * Force XLOG flush up to buffer's LSN. This implements the basic WAL
4575 : : * rule that log updates must hit disk before any of the data-file changes
4576 : : * they describe do.
4577 : : *
4578 : : * However, this rule does not apply to unlogged relations, which will be
4579 : : * lost after a crash anyway. Most unlogged relation pages do not bear
4580 : : * LSNs since we never emit WAL records for them, and therefore flushing
4581 : : * up through the buffer LSN would be useless, but harmless. However,
4582 : : * some index AMs use LSNs internally to detect concurrent page
4583 : : * modifications, and therefore unlogged index pages bear "fake" LSNs
4584 : : * generated by XLogGetFakeLSN. It is unlikely but possible that the fake
4585 : : * LSN counter could advance past the WAL insertion point; and if it did
4586 : : * happen, attempting to flush WAL through that location would fail, with
4587 : : * disastrous system-wide consequences. To make sure that can't happen,
4588 : : * skip the flush if the buffer isn't permanent.
4589 : : */
215 andres@anarazel.de 4590 [ + + ]: 712970 : if (pg_atomic_read_u64(&buf->state) & BM_PERMANENT)
4991 heikki.linnakangas@i 4591 : 711088 : XLogFlush(recptr);
4592 : :
4593 : : /*
4594 : : * Now it's safe to write the buffer to disk. Note that no one else should
4595 : : * have been able to write it, while we were busy with log flushing,
4596 : : * because we got the exclusive right to perform I/O by setting the
4597 : : * BM_IO_IN_PROGRESS bit.
4598 : : */
4952 simon@2ndQuadrant.co 4599 : 712970 : bufBlock = BufHdrGetBlock(buf);
4600 : :
4601 : : /* Update page checksum if desired. */
199 andres@anarazel.de 4602 : 712970 : PageSetChecksum((Page) bufBlock, buf->tag.blockNum);
4603 : :
593 michael@paquier.xyz 4604 : 712970 : io_start = pgstat_prepare_io_time(track_io_timing);
4605 : :
8280 tgl@sss.pgh.pa.us 4606 : 712970 : smgrwrite(reln,
1510 rhaas@postgresql.org 4607 : 712970 : BufTagGetForkNum(&buf->tag),
4608 : : buf->tag.blockNum,
4609 : : bufBlock,
4610 : : false);
4611 : :
4612 : : /*
4613 : : * When a strategy is in use, only flushes of dirty buffers already in the
4614 : : * strategy ring are counted as strategy writes (IOCONTEXT
4615 : : * [BULKREAD|BULKWRITE|VACUUM] IOOP_WRITE) for the purpose of IO
4616 : : * statistics tracking.
4617 : : *
4618 : : * If a shared buffer initially added to the ring must be flushed before
4619 : : * being used, this is counted as an IOCONTEXT_NORMAL IOOP_WRITE.
4620 : : *
4621 : : * If a shared buffer which was added to the ring later because the
4622 : : * current strategy buffer is pinned or in use or because all strategy
4623 : : * buffers were dirty and rejected (for BAS_BULKREAD operations only)
4624 : : * requires flushing, this is counted as an IOCONTEXT_NORMAL IOOP_WRITE
4625 : : * (from_ring will be false).
4626 : : *
4627 : : * When a strategy is not in use, the write can only be a "regular" write
4628 : : * of a dirty shared buffer (IOCONTEXT_NORMAL IOOP_WRITE).
4629 : : */
174 melanieplageman@gmai 4630 : 712970 : pgstat_count_io_op_time(io_object, io_context,
4631 : : IOOP_WRITE, io_start, 1, BLCKSZ);
4632 : :
6145 rhaas@postgresql.org 4633 : 712970 : pgBufferUsage.shared_blks_written++;
4634 : :
4635 : : /*
4636 : : * Mark the buffer as clean and end the BM_IO_IN_PROGRESS state.
4637 : : */
561 andres@anarazel.de 4638 : 712970 : TerminateBufferIO(buf, true, 0, true, false);
4639 : :
4640 : : TRACE_POSTGRESQL_BUFFER_FLUSH_DONE(BufTagGetForkNum(&buf->tag),
4641 : : buf->tag.blockNum,
4642 : : reln->smgr_rlocator.locator.spcOid,
4643 : : reln->smgr_rlocator.locator.dbOid,
4644 : : reln->smgr_rlocator.locator.relNumber);
4645 : :
4646 : : /* Pop the error context stack */
5082 heikki.linnakangas@i 4647 : 712970 : error_context_stack = errcallback.previous;
4648 : : }
4649 : :
4650 : : /*
4651 : : * Convenience wrapper around FlushBuffer() that locks/unlocks the buffer
4652 : : * before/after calling FlushBuffer().
4653 : : */
4654 : : static void
369 andres@anarazel.de 4655 : 380188 : FlushUnlockedBuffer(BufferDesc *buf, SMgrRelation reln,
4656 : : IOObject io_object, IOContext io_context)
4657 : : {
270 4658 : 380188 : Buffer buffer = BufferDescriptorGetBuffer(buf);
4659 : :
216 4660 : 380188 : BufferLockAcquire(buffer, buf, BUFFER_LOCK_SHARE_EXCLUSIVE);
174 melanieplageman@gmai 4661 : 380188 : FlushBuffer(buf, reln, io_object, io_context);
270 andres@anarazel.de 4662 : 380188 : BufferLockUnlock(buffer, buf);
369 4663 : 380188 : }
4664 : :
4665 : : /*
4666 : : * RelationGetNumberOfBlocksInFork
4667 : : * Determines the current number of pages in the specified relation fork.
4668 : : *
4669 : : * Note that the accuracy of the result will depend on the details of the
4670 : : * relation's storage. For builtin AMs it'll be accurate, but for external AMs
4671 : : * it might not be.
4672 : : */
4673 : : BlockNumber
5766 rhaas@postgresql.org 4674 : 2280519 : RelationGetNumberOfBlocksInFork(Relation relation, ForkNumber forkNum)
4675 : : {
1774 peter@eisentraut.org 4676 [ + + + + : 2280519 : if (RELKIND_HAS_TABLE_AM(relation->rd_rel->relkind))
+ + ]
4677 : : {
4678 : : /*
4679 : : * Not every table AM uses BLCKSZ wide fixed size blocks. Therefore
4680 : : * tableam returns the size in bytes - but for the purpose of this
4681 : : * routine, we want the number of blocks. Therefore divide, rounding
4682 : : * up.
4683 : : */
4684 : : uint64 szbytes;
4685 : :
4686 : 1586107 : szbytes = table_relation_size(relation, forkNum);
4687 : :
4688 : 1586088 : return (szbytes + (BLCKSZ - 1)) / BLCKSZ;
4689 : : }
4690 [ + - + + : 694412 : else if (RELKIND_HAS_STORAGE(relation->rd_rel->relkind))
- + - - -
- ]
4691 : : {
1614 tgl@sss.pgh.pa.us 4692 : 694412 : return smgrnblocks(RelationGetSmgr(relation), forkNum);
4693 : : }
4694 : : else
1774 peter@eisentraut.org 4695 :UBC 0 : Assert(false);
4696 : :
4697 : : return 0; /* keep compiler quiet */
4698 : : }
4699 : :
4700 : : /*
4701 : : * BufferIsPermanent
4702 : : * Determines whether a buffer will potentially still be around after
4703 : : * a crash. Caller must hold a buffer pin.
4704 : : */
4705 : : bool
5463 rhaas@postgresql.org 4706 :CBC 17572096 : BufferIsPermanent(Buffer buffer)
4707 : : {
4708 : : BufferDesc *bufHdr;
4709 : :
4710 : : /* Local buffers are used only for temp relations. */
4711 [ + + ]: 17572096 : if (BufferIsLocal(buffer))
4712 : 925146 : return false;
4713 : :
4714 : : /* Make sure we've got a real buffer, and that we hold a pin on it. */
4715 [ - + ]: 16646950 : Assert(BufferIsValid(buffer));
4716 [ - + - + : 16646950 : Assert(BufferIsPinned(buffer));
- + ]
4717 : :
4718 : : /*
4719 : : * BM_PERMANENT can't be changed while we hold a pin on the buffer, so we
4720 : : * need not bother with the buffer header spinlock. Even if someone else
4721 : : * changes the buffer header state while we're doing this, the state is
4722 : : * changed atomically, so we'll read the old value or the new value, but
4723 : : * not random garbage.
4724 : : */
4274 andres@anarazel.de 4725 : 16646950 : bufHdr = GetBufferDescriptor(buffer - 1);
270 4726 : 16646950 : return (pg_atomic_read_u64(&bufHdr->state) & BM_PERMANENT) != 0;
4727 : : }
4728 : :
4729 : : /*
4730 : : * BufferGetLSNAtomic
4731 : : * Retrieves the LSN of the buffer atomically.
4732 : : *
4733 : : * This is necessary for some callers who may only hold a share lock on
4734 : : * the buffer. A share lock allows a concurrent backend to set hint bits
4735 : : * on the page, which in turn may require a WAL record to be emitted.
4736 : : *
4737 : : * On platforms with 8 byte atomic reads/writes, we don't need to do any
4738 : : * additional locking. On platforms not supporting such 8 byte atomic
4739 : : * reads/writes, we need to actually take the header lock.
4740 : : */
4741 : : XLogRecPtr
4952 simon@2ndQuadrant.co 4742 : 8220699 : BufferGetLSNAtomic(Buffer buffer)
4743 : : {
4744 : : /* Make sure we've got a real buffer, and that we hold a pin on it. */
4745 [ - + ]: 8220699 : Assert(BufferIsValid(buffer));
4746 [ - + + + : 8220699 : Assert(BufferIsPinned(buffer));
- + ]
4747 : :
4748 : : #ifdef PG_HAVE_8BYTE_SINGLE_COPY_ATOMICITY
215 tomas.vondra@postgre 4749 : 8220699 : return PageGetLSN(BufferGetPage(buffer));
4750 : : #else
4751 : : {
4752 : : char *page = BufferGetPage(buffer);
4753 : : BufferDesc *bufHdr;
4754 : : XLogRecPtr lsn;
4755 : :
4756 : : /*
4757 : : * If we don't need locking for correctness, fastpath out.
4758 : : */
4759 : : if (!XLogHintBitIsNeeded() || BufferIsLocal(buffer))
4760 : : return PageGetLSN(page);
4761 : :
4762 : : bufHdr = GetBufferDescriptor(buffer - 1);
4763 : : LockBufHdr(bufHdr);
4764 : : lsn = PageGetLSN(page);
4765 : : UnlockBufHdr(bufHdr);
4766 : :
4767 : : return lsn;
4768 : : }
4769 : : #endif
4770 : : }
4771 : :
4772 : : /* ---------------------------------------------------------------------
4773 : : * DropRelationBuffers
4774 : : *
4775 : : * This function removes from the buffer pool all the pages of the
4776 : : * specified relation forks that have block numbers >= firstDelBlock.
4777 : : * (In particular, with firstDelBlock = 0, all pages are removed.)
4778 : : * Dirty pages are simply dropped, without bothering to write them
4779 : : * out first. Therefore, this is NOT rollback-able, and so should be
4780 : : * used only with extreme caution!
4781 : : *
4782 : : * Currently, this is called only from smgr.c when the underlying file
4783 : : * is about to be deleted or truncated (firstDelBlock is needed for
4784 : : * the truncation case). The data in the affected pages would therefore
4785 : : * be deleted momentarily anyway, and there is no point in writing it.
4786 : : * It is the responsibility of higher-level code to ensure that the
4787 : : * deletion or truncation does not lose any data that could be needed
4788 : : * later. It is also the responsibility of higher-level code to ensure
4789 : : * that no other process could be trying to load more pages of the
4790 : : * relation into buffers.
4791 : : * --------------------------------------------------------------------
4792 : : */
4793 : : void
1553 rhaas@postgresql.org 4794 : 819 : DropRelationBuffers(SMgrRelation smgr_reln, ForkNumber *forkNum,
4795 : : int nforks, BlockNumber *firstDelBlock)
4796 : : {
4797 : : int i;
4798 : : int j;
4799 : : RelFileLocatorBackend rlocator;
4800 : : BlockNumber nForkBlock[MAX_FORKNUM];
1979 tgl@sss.pgh.pa.us 4801 : 819 : uint64 nBlocksToInvalidate = 0;
4802 : :
1559 rhaas@postgresql.org 4803 : 819 : rlocator = smgr_reln->smgr_rlocator;
4804 : :
4805 : : /* If it's a local relation, it's localbuf.c's problem. */
4806 [ + + ]: 819 : if (RelFileLocatorBackendIsTemp(rlocator))
4807 : : {
953 heikki.linnakangas@i 4808 [ + - ]: 498 : if (rlocator.backend == MyProcNumber)
465 fujii@postgresql.org 4809 : 498 : DropRelationLocalBuffers(rlocator.locator, forkNum, nforks,
4810 : : firstDelBlock);
4811 : :
8833 tgl@sss.pgh.pa.us 4812 : 543 : return;
4813 : : }
4814 : :
4815 : : /*
4816 : : * To remove all the pages of the specified relation forks from the buffer
4817 : : * pool, we need to scan the entire buffer pool but we can optimize it by
4818 : : * finding the buffers from BufMapping table provided we know the exact
4819 : : * size of each fork of the relation. The exact size is required to ensure
4820 : : * that we don't leave any buffer for the relation being dropped as
4821 : : * otherwise the background writer or checkpointer can lead to a PANIC
4822 : : * error while flushing buffers corresponding to files that don't exist.
4823 : : *
4824 : : * To know the exact size, we rely on the size cached for each fork by us
4825 : : * during recovery which limits the optimization to recovery and on
4826 : : * standbys but we can easily extend it once we have shared cache for
4827 : : * relation size.
4828 : : *
4829 : : * In recovery, we cache the value returned by the first lseek(SEEK_END)
4830 : : * and the future writes keeps the cached value up-to-date. See
4831 : : * smgrextend. It is possible that the value of the first lseek is smaller
4832 : : * than the actual number of existing blocks in the file due to buggy
4833 : : * Linux kernels that might not have accounted for the recent write. But
4834 : : * that should be fine because there must not be any buffers after that
4835 : : * file size.
4836 : : */
2099 akapila@postgresql.o 4837 [ + + ]: 434 : for (i = 0; i < nforks; i++)
4838 : : {
4839 : : /* Get the number of blocks for a relation's fork */
4840 : 376 : nForkBlock[i] = smgrnblocks_cached(smgr_reln, forkNum[i]);
4841 : :
4842 [ + + ]: 376 : if (nForkBlock[i] == InvalidBlockNumber)
4843 : : {
4844 : 263 : nBlocksToInvalidate = InvalidBlockNumber;
4845 : 263 : break;
4846 : : }
4847 : :
4848 : : /* calculate the number of blocks to be invalidated */
4849 : 113 : nBlocksToInvalidate += (nForkBlock[i] - firstDelBlock[i]);
4850 : : }
4851 : :
4852 : : /*
4853 : : * We apply the optimization iff the total number of blocks to invalidate
4854 : : * is below the BUF_DROP_FULL_SCAN_THRESHOLD.
4855 : : */
4856 [ + + ]: 321 : if (BlockNumberIsValid(nBlocksToInvalidate) &&
4857 [ + + ]: 58 : nBlocksToInvalidate < BUF_DROP_FULL_SCAN_THRESHOLD)
4858 : : {
4859 [ + + ]: 126 : for (j = 0; j < nforks; j++)
1553 rhaas@postgresql.org 4860 : 81 : FindAndDropRelationBuffers(rlocator.locator, forkNum[j],
4861 : 81 : nForkBlock[j], firstDelBlock[j]);
2099 akapila@postgresql.o 4862 : 45 : return;
4863 : : }
4864 : :
7892 tgl@sss.pgh.pa.us 4865 [ + + ]: 3660692 : for (i = 0; i < NBuffers; i++)
4866 : : {
3983 rhaas@postgresql.org 4867 : 3660416 : BufferDesc *bufHdr = GetBufferDescriptor(i);
4868 : :
4869 : : /*
4870 : : * We can make this a tad faster by prechecking the buffer tag before
4871 : : * we attempt to lock the buffer; this saves a lot of lock
4872 : : * acquisitions in typical cases. It should be safe because the
4873 : : * caller must have AccessExclusiveLock on the relation, or some other
4874 : : * reason to be certain that no one is loading new pages of the rel
4875 : : * into the buffer pool. (Otherwise we might well miss such pages
4876 : : * entirely.) Therefore, while the tag might be changing while we
4877 : : * look at it, it can't be changing *to* a value we care about, only
4878 : : * *away* from such a value. So false negatives are impossible, and
4879 : : * false positives are safe because we'll recheck after getting the
4880 : : * buffer lock.
4881 : : *
4882 : : * We could check forkNum and blockNum as well as the rlocator, but
4883 : : * the incremental win from doing so seems small.
4884 : : */
1510 4885 [ + + ]: 3660416 : if (!BufTagMatchesRelFileLocator(&bufHdr->tag, &rlocator.locator))
5240 tgl@sss.pgh.pa.us 4886 : 3646676 : continue;
4887 : :
340 andres@anarazel.de 4888 : 13740 : LockBufHdr(bufHdr);
4889 : :
2575 fujii@postgresql.org 4890 [ + + ]: 34554 : for (j = 0; j < nforks; j++)
4891 : : {
1510 rhaas@postgresql.org 4892 [ + - ]: 24325 : if (BufTagMatchesRelFileLocator(&bufHdr->tag, &rlocator.locator) &&
4893 [ + + ]: 24325 : BufTagGetForkNum(&bufHdr->tag) == forkNum[j] &&
2575 fujii@postgresql.org 4894 [ + + ]: 13576 : bufHdr->tag.blockNum >= firstDelBlock[j])
4895 : : {
2342 tgl@sss.pgh.pa.us 4896 : 3511 : InvalidateBuffer(bufHdr); /* releases spinlock */
2575 fujii@postgresql.org 4897 : 3511 : break;
4898 : : }
4899 : : }
4900 [ + + ]: 13740 : if (j >= nforks)
340 andres@anarazel.de 4901 : 10229 : UnlockBufHdr(bufHdr);
4902 : : }
4903 : : }
4904 : :
4905 : : /* ---------------------------------------------------------------------
4906 : : * DropRelationsAllBuffers
4907 : : *
4908 : : * This function removes from the buffer pool all the pages of all
4909 : : * forks of the specified relations. It's equivalent to calling
4910 : : * DropRelationBuffers once per fork per relation with firstDelBlock = 0.
4911 : : * --------------------------------------------------------------------
4912 : : */
4913 : : void
1553 rhaas@postgresql.org 4914 : 17554 : DropRelationsAllBuffers(SMgrRelation *smgr_reln, int nlocators)
4915 : : {
4916 : : int i;
2098 akapila@postgresql.o 4917 : 17554 : int n = 0;
4918 : : SMgrRelation *rels;
4919 : : BlockNumber (*block)[MAX_FORKNUM + 1];
1979 tgl@sss.pgh.pa.us 4920 : 17554 : uint64 nBlocksToInvalidate = 0;
4921 : : RelFileLocator *locators;
2098 akapila@postgresql.o 4922 : 17554 : bool cached = true;
4923 : : bool use_bsearch;
4924 : :
1559 rhaas@postgresql.org 4925 [ - + ]: 17554 : if (nlocators == 0)
5016 alvherre@alvh.no-ip. 4926 :UBC 0 : return;
4927 : :
305 michael@paquier.xyz 4928 :CBC 17554 : rels = palloc_array(SMgrRelation, nlocators); /* non-local relations */
4929 : :
4930 : : /* If it's a local relation, it's localbuf.c's problem. */
1559 rhaas@postgresql.org 4931 [ + + ]: 77017 : for (i = 0; i < nlocators; i++)
4932 : : {
4933 [ + + ]: 59463 : if (RelFileLocatorBackendIsTemp(smgr_reln[i]->smgr_rlocator))
4934 : : {
953 heikki.linnakangas@i 4935 [ + + ]: 4562 : if (smgr_reln[i]->smgr_rlocator.backend == MyProcNumber)
1553 rhaas@postgresql.org 4936 : 4560 : DropRelationAllLocalBuffers(smgr_reln[i]->smgr_rlocator.locator);
4937 : : }
4938 : : else
2098 akapila@postgresql.o 4939 : 54901 : rels[n++] = smgr_reln[i];
4940 : : }
4941 : :
4942 : : /*
4943 : : * If there are no non-local relations, then we're done. Release the
4944 : : * memory and return.
4945 : : */
5016 alvherre@alvh.no-ip. 4946 [ + + ]: 17554 : if (n == 0)
4947 : : {
2098 akapila@postgresql.o 4948 : 1196 : pfree(rels);
5240 tgl@sss.pgh.pa.us 4949 : 1196 : return;
4950 : : }
4951 : :
4952 : : /*
4953 : : * This is used to remember the number of blocks for all the relations
4954 : : * forks.
4955 : : */
4956 : : block = (BlockNumber (*)[MAX_FORKNUM + 1])
56 michael@paquier.xyz 4957 :GNC 16358 : palloc_array(BlockNumber, n * (MAX_FORKNUM + 1));
4958 : :
4959 : : /*
4960 : : * We can avoid scanning the entire buffer pool if we know the exact size
4961 : : * of each of the given relation forks. See DropRelationBuffers.
4962 : : */
2098 akapila@postgresql.o 4963 [ + + + + ]:CBC 34047 : for (i = 0; i < n && cached; i++)
4964 : : {
1510 drowley@postgresql.o 4965 [ + + ]: 26487 : for (int j = 0; j <= MAX_FORKNUM; j++)
4966 : : {
4967 : : /* Get the number of blocks for a relation's fork. */
2098 akapila@postgresql.o 4968 : 24302 : block[i][j] = smgrnblocks_cached(rels[i], j);
4969 : :
4970 : : /* We need to only consider the relation forks that exists. */
4971 [ + + ]: 24302 : if (block[i][j] == InvalidBlockNumber)
4972 : : {
4973 [ + + ]: 21894 : if (!smgrexists(rels[i], j))
4974 : 6390 : continue;
4975 : 15504 : cached = false;
4976 : 15504 : break;
4977 : : }
4978 : :
4979 : : /* calculate the total number of blocks to be invalidated */
4980 : 2408 : nBlocksToInvalidate += block[i][j];
4981 : : }
4982 : : }
4983 : :
4984 : : /*
4985 : : * We apply the optimization iff the total number of blocks to invalidate
4986 : : * is below the BUF_DROP_FULL_SCAN_THRESHOLD.
4987 : : */
4988 [ + + + + ]: 16358 : if (cached && nBlocksToInvalidate < BUF_DROP_FULL_SCAN_THRESHOLD)
4989 : : {
4990 [ + + ]: 1398 : for (i = 0; i < n; i++)
4991 : : {
1510 drowley@postgresql.o 4992 [ + + ]: 3845 : for (int j = 0; j <= MAX_FORKNUM; j++)
4993 : : {
4994 : : /* ignore relation forks that doesn't exist */
2098 akapila@postgresql.o 4995 [ + + ]: 3076 : if (!BlockNumberIsValid(block[i][j]))
4996 : 2296 : continue;
4997 : :
4998 : : /* drop all the buffers for a particular relation fork */
1553 rhaas@postgresql.org 4999 : 780 : FindAndDropRelationBuffers(rels[i]->smgr_rlocator.locator,
5000 : 780 : j, block[i][j], 0);
5001 : : }
5002 : : }
5003 : :
2098 akapila@postgresql.o 5004 : 629 : pfree(block);
5005 : 629 : pfree(rels);
5006 : 629 : return;
5007 : : }
5008 : :
5009 : 15729 : pfree(block);
305 michael@paquier.xyz 5010 : 15729 : locators = palloc_array(RelFileLocator, n); /* non-local relations */
2098 akapila@postgresql.o 5011 [ + + ]: 69861 : for (i = 0; i < n; i++)
1559 rhaas@postgresql.org 5012 : 54132 : locators[i] = rels[i]->smgr_rlocator.locator;
5013 : :
5014 : : /*
5015 : : * For low number of relations to drop just use a simple walk through, to
5016 : : * save the bsearch overhead. The threshold to use is rather a guess than
5017 : : * an exactly determined value, as it depends on many factors (CPU and RAM
5018 : : * speeds, amount of shared buffers etc.).
5019 : : */
2382 noah@leadboat.com 5020 : 15729 : use_bsearch = n > RELS_BSEARCH_THRESHOLD;
5021 : :
5022 : : /* sort the list of rlocators if necessary */
5016 alvherre@alvh.no-ip. 5023 [ + + ]: 15729 : if (use_bsearch)
969 nathan@postgresql.or 5024 : 218 : qsort(locators, n, sizeof(RelFileLocator), rlocator_comparator);
5025 : :
5240 tgl@sss.pgh.pa.us 5026 [ + + ]: 183120881 : for (i = 0; i < NBuffers; i++)
5027 : : {
1559 rhaas@postgresql.org 5028 : 183105152 : RelFileLocator *rlocator = NULL;
3983 5029 : 183105152 : BufferDesc *bufHdr = GetBufferDescriptor(i);
5030 : :
5031 : : /*
5032 : : * As in DropRelationBuffers, an unlocked precheck should be safe and
5033 : : * saves some cycles.
5034 : : */
5035 : :
5016 alvherre@alvh.no-ip. 5036 [ + + ]: 183105152 : if (!use_bsearch)
5037 : : {
5038 : : int j;
5039 : :
5040 [ + + ]: 722475991 : for (j = 0; j < n; j++)
5041 : : {
1510 rhaas@postgresql.org 5042 [ + + ]: 541976751 : if (BufTagMatchesRelFileLocator(&bufHdr->tag, &locators[j]))
5043 : : {
1559 5044 : 107096 : rlocator = &locators[j];
5016 alvherre@alvh.no-ip. 5045 : 107096 : break;
5046 : : }
5047 : : }
5048 : : }
5049 : : else
5050 : : {
5051 : : RelFileLocator locator;
5052 : :
1510 rhaas@postgresql.org 5053 : 2498816 : locator = BufTagGetRelFileLocator(&bufHdr->tag);
675 peter@eisentraut.org 5054 : 2498816 : rlocator = bsearch(&locator,
5055 : : locators, n, sizeof(RelFileLocator),
5056 : : rlocator_comparator);
5057 : : }
5058 : :
5059 : : /* buffer doesn't belong to any of the given relfilelocators; skip it */
1559 rhaas@postgresql.org 5060 [ + + ]: 183105152 : if (rlocator == NULL)
5240 tgl@sss.pgh.pa.us 5061 : 182996314 : continue;
5062 : :
340 andres@anarazel.de 5063 : 108838 : LockBufHdr(bufHdr);
1510 rhaas@postgresql.org 5064 [ + - ]: 108838 : if (BufTagMatchesRelFileLocator(&bufHdr->tag, rlocator))
5240 tgl@sss.pgh.pa.us 5065 : 108838 : InvalidateBuffer(bufHdr); /* releases spinlock */
5066 : : else
340 andres@anarazel.de 5067 :UBC 0 : UnlockBufHdr(bufHdr);
5068 : : }
5069 : :
1559 rhaas@postgresql.org 5070 :CBC 15729 : pfree(locators);
2098 akapila@postgresql.o 5071 : 15729 : pfree(rels);
5072 : : }
5073 : :
5074 : : /* ---------------------------------------------------------------------
5075 : : * FindAndDropRelationBuffers
5076 : : *
5077 : : * This function performs look up in BufMapping table and removes from the
5078 : : * buffer pool all the pages of the specified relation fork that has block
5079 : : * number >= firstDelBlock. (In particular, with firstDelBlock = 0, all
5080 : : * pages are removed.)
5081 : : * --------------------------------------------------------------------
5082 : : */
5083 : : static void
1553 rhaas@postgresql.org 5084 : 861 : FindAndDropRelationBuffers(RelFileLocator rlocator, ForkNumber forkNum,
5085 : : BlockNumber nForkBlock,
5086 : : BlockNumber firstDelBlock)
5087 : : {
5088 : : BlockNumber curBlock;
5089 : :
2099 akapila@postgresql.o 5090 [ + + ]: 2063 : for (curBlock = firstDelBlock; curBlock < nForkBlock; curBlock++)
5091 : : {
5092 : : uint32 bufHash; /* hash value for tag */
5093 : : BufferTag bufTag; /* identity of requested block */
5094 : : LWLock *bufPartitionLock; /* buffer partition lock for it */
5095 : : int buf_id;
5096 : : BufferDesc *bufHdr;
5097 : :
5098 : : /* create a tag so we can lookup the buffer */
1538 rhaas@postgresql.org 5099 : 1202 : InitBufferTag(&bufTag, &rlocator, forkNum, curBlock);
5100 : :
5101 : : /* determine its hash code and partition lock ID */
2099 akapila@postgresql.o 5102 : 1202 : bufHash = BufTableHashCode(&bufTag);
5103 : 1202 : bufPartitionLock = BufMappingPartitionLock(bufHash);
5104 : :
5105 : : /* Check that it is in the buffer pool. If not, do nothing. */
5106 : 1202 : LWLockAcquire(bufPartitionLock, LW_SHARED);
5107 : 1202 : buf_id = BufTableLookup(&bufTag, bufHash);
5108 : 1202 : LWLockRelease(bufPartitionLock);
5109 : :
5110 [ + + ]: 1202 : if (buf_id < 0)
5111 : 120 : continue;
5112 : :
5113 : 1082 : bufHdr = GetBufferDescriptor(buf_id);
5114 : :
5115 : : /*
5116 : : * We need to lock the buffer header and recheck if the buffer is
5117 : : * still associated with the same block because the buffer could be
5118 : : * evicted by some other backend loading blocks for a different
5119 : : * relation after we release lock on the BufMapping table.
5120 : : */
340 andres@anarazel.de 5121 : 1082 : LockBufHdr(bufHdr);
5122 : :
1510 rhaas@postgresql.org 5123 [ + - + - ]: 2164 : if (BufTagMatchesRelFileLocator(&bufHdr->tag, &rlocator) &&
5124 : 1082 : BufTagGetForkNum(&bufHdr->tag) == forkNum &&
2099 akapila@postgresql.o 5125 [ + - ]: 1082 : bufHdr->tag.blockNum >= firstDelBlock)
5126 : 1082 : InvalidateBuffer(bufHdr); /* releases spinlock */
5127 : : else
340 andres@anarazel.de 5128 :UBC 0 : UnlockBufHdr(bufHdr);
5129 : : }
2099 akapila@postgresql.o 5130 :CBC 861 : }
5131 : :
5132 : : /* ---------------------------------------------------------------------
5133 : : * DropDatabaseBuffers
5134 : : *
5135 : : * This function removes all the buffers in the buffer cache for a
5136 : : * particular database. Dirty pages are simply dropped, without
5137 : : * bothering to write them out first. This is used when we destroy a
5138 : : * database, to avoid trying to flush data to disk when the directory
5139 : : * tree no longer exists. Implementation is pretty similar to
5140 : : * DropRelationBuffers() which is for destroying just one relation.
5141 : : * --------------------------------------------------------------------
5142 : : */
5143 : : void
7502 tgl@sss.pgh.pa.us 5144 : 87 : DropDatabaseBuffers(Oid dbid)
5145 : : {
5146 : : int i;
5147 : :
5148 : : /*
5149 : : * We needn't consider local buffers, since by assumption the target
5150 : : * database isn't our own.
5151 : : */
5152 : :
7892 5153 [ + + ]: 677719 : for (i = 0; i < NBuffers; i++)
5154 : : {
3983 rhaas@postgresql.org 5155 : 677632 : BufferDesc *bufHdr = GetBufferDescriptor(i);
5156 : :
5157 : : /*
5158 : : * As in DropRelationBuffers, an unlocked precheck should be safe and
5159 : : * saves some cycles.
5160 : : */
1510 5161 [ + + ]: 677632 : if (bufHdr->tag.dbOid != dbid)
5240 tgl@sss.pgh.pa.us 5162 : 659387 : continue;
5163 : :
340 andres@anarazel.de 5164 : 18245 : LockBufHdr(bufHdr);
1510 rhaas@postgresql.org 5165 [ + - ]: 18245 : if (bufHdr->tag.dbOid == dbid)
7667 bruce@momjian.us 5166 : 18245 : InvalidateBuffer(bufHdr); /* releases spinlock */
5167 : : else
340 andres@anarazel.de 5168 :UBC 0 : UnlockBufHdr(bufHdr);
5169 : : }
11052 scrappy@hub.org 5170 :CBC 87 : }
5171 : :
5172 : : /* ---------------------------------------------------------------------
5173 : : * FlushRelationBuffers
5174 : : *
5175 : : * This function writes all dirty pages of a relation out to disk
5176 : : * (or more accurately, out to kernel disk buffers), ensuring that the
5177 : : * kernel has an up-to-date view of the relation.
5178 : : *
5179 : : * Generally, the caller should be holding AccessExclusiveLock on the
5180 : : * target relation to ensure that no other backend is busy dirtying
5181 : : * more blocks of the relation; the effects can't be expected to last
5182 : : * after the lock is released.
5183 : : *
5184 : : * XXX currently it sequentially searches the buffer pool, should be
5185 : : * changed to more clever ways of searching. This routine is not
5186 : : * used in any performance-critical code paths, so it's not worth
5187 : : * adding additional overhead to normal paths to make it go faster.
5188 : : * --------------------------------------------------------------------
5189 : : */
5190 : : void
7876 tgl@sss.pgh.pa.us 5191 : 181 : FlushRelationBuffers(Relation rel)
5192 : : {
5193 : : int i;
5194 : : BufferDesc *bufHdr;
985 heikki.linnakangas@i 5195 : 181 : SMgrRelation srel = RelationGetSmgr(rel);
5196 : :
5782 rhaas@postgresql.org 5197 [ + + ]: 181 : if (RelationUsesLocalBuffers(rel))
5198 : : {
10612 vadim4o@yahoo.com 5199 [ + + ]: 1212 : for (i = 0; i < NLocBuffer; i++)
5200 : : {
5201 : : uint64 buf_state;
5202 : :
4274 andres@anarazel.de 5203 : 1200 : bufHdr = GetLocalBufferDescriptor(i);
1510 rhaas@postgresql.org 5204 [ + + ]: 1200 : if (BufTagMatchesRelFileLocator(&bufHdr->tag, &rel->rd_locator) &&
270 andres@anarazel.de 5205 [ + + ]: 400 : ((buf_state = pg_atomic_read_u64(&bufHdr->state)) &
5206 : : (BM_VALID | BM_DIRTY)) == (BM_VALID | BM_DIRTY))
5207 : : {
5208 : : ErrorContextCallback errcallback;
5209 : :
5210 : : /* Setup error traceback support for ereport() */
5082 heikki.linnakangas@i 5211 : 396 : errcallback.callback = local_buffer_write_error_callback;
683 peter@eisentraut.org 5212 : 396 : errcallback.arg = bufHdr;
5082 heikki.linnakangas@i 5213 : 396 : errcallback.previous = error_context_stack;
5214 : 396 : error_context_stack = &errcallback;
5215 : :
5216 : : /* Make sure we can handle the pin */
553 andres@anarazel.de 5217 : 396 : ReservePrivateRefCountEntry();
5218 : 396 : ResourceOwnerEnlarge(CurrentResourceOwner);
5219 : :
5220 : : /*
5221 : : * Pin/unpin mostly to make valgrind work, but it also seems
5222 : : * like the right thing to do.
5223 : : */
5224 : 396 : PinLocalBuffer(bufHdr, false);
5225 : :
5226 : :
576 5227 : 396 : FlushLocalBuffer(bufHdr, srel);
5228 : :
553 5229 : 396 : UnpinLocalBuffer(BufferDescriptorGetBuffer(bufHdr));
5230 : :
5231 : : /* Pop the error context stack */
5082 heikki.linnakangas@i 5232 : 396 : error_context_stack = errcallback.previous;
5233 : : }
5234 : : }
5235 : :
8169 tgl@sss.pgh.pa.us 5236 : 12 : return;
5237 : : }
5238 : :
10612 vadim4o@yahoo.com 5239 [ + + ]: 1940009 : for (i = 0; i < NBuffers; i++)
5240 : : {
5241 : : uint64 buf_state;
5242 : :
4274 andres@anarazel.de 5243 : 1939840 : bufHdr = GetBufferDescriptor(i);
5244 : :
5245 : : /*
5246 : : * As in DropRelationBuffers, an unlocked precheck should be safe and
5247 : : * saves some cycles.
5248 : : */
1510 rhaas@postgresql.org 5249 [ + + ]: 1939840 : if (!BufTagMatchesRelFileLocator(&bufHdr->tag, &rel->rd_locator))
5240 tgl@sss.pgh.pa.us 5250 : 1939592 : continue;
5251 : :
5252 : : /* Make sure we can handle the pin */
4284 andres@anarazel.de 5253 : 248 : ReservePrivateRefCountEntry();
1069 heikki.linnakangas@i 5254 : 248 : ResourceOwnerEnlarge(CurrentResourceOwner);
5255 : :
3837 andres@anarazel.de 5256 : 248 : buf_state = LockBufHdr(bufHdr);
1510 rhaas@postgresql.org 5257 [ + - ]: 248 : if (BufTagMatchesRelFileLocator(&bufHdr->tag, &rel->rd_locator) &&
3837 andres@anarazel.de 5258 [ + + ]: 248 : (buf_state & (BM_VALID | BM_DIRTY)) == (BM_VALID | BM_DIRTY))
5259 : : {
7876 tgl@sss.pgh.pa.us 5260 : 206 : PinBuffer_Locked(bufHdr);
369 andres@anarazel.de 5261 : 206 : FlushUnlockedBuffer(bufHdr, srel, IOOBJECT_RELATION, IOCONTEXT_NORMAL);
1473 michael@paquier.xyz 5262 : 206 : UnpinBuffer(bufHdr);
5263 : : }
5264 : : else
340 andres@anarazel.de 5265 : 42 : UnlockBufHdr(bufHdr);
5266 : : }
5267 : : }
5268 : :
5269 : : /* ---------------------------------------------------------------------
5270 : : * FlushRelationsAllBuffers
5271 : : *
5272 : : * This function flushes out of the buffer pool all the pages of all
5273 : : * forks of the specified smgr relations. It's equivalent to calling
5274 : : * FlushRelationBuffers once per relation. The relations are assumed not
5275 : : * to use local buffers.
5276 : : * --------------------------------------------------------------------
5277 : : */
5278 : : void
2382 noah@leadboat.com 5279 : 4 : FlushRelationsAllBuffers(SMgrRelation *smgrs, int nrels)
5280 : : {
5281 : : int i;
5282 : : SMgrSortArray *srels;
5283 : : bool use_bsearch;
5284 : :
5285 [ - + ]: 4 : if (nrels == 0)
2382 noah@leadboat.com 5286 :UBC 0 : return;
5287 : :
5288 : : /* fill-in array for qsort */
305 michael@paquier.xyz 5289 :CBC 4 : srels = palloc_array(SMgrSortArray, nrels);
5290 : :
2382 noah@leadboat.com 5291 [ + + ]: 8 : for (i = 0; i < nrels; i++)
5292 : : {
1559 rhaas@postgresql.org 5293 [ - + ]: 4 : Assert(!RelFileLocatorBackendIsTemp(smgrs[i]->smgr_rlocator));
5294 : :
5295 : 4 : srels[i].rlocator = smgrs[i]->smgr_rlocator.locator;
2382 noah@leadboat.com 5296 : 4 : srels[i].srel = smgrs[i];
5297 : : }
5298 : :
5299 : : /*
5300 : : * Save the bsearch overhead for low number of relations to sync. See
5301 : : * DropRelationsAllBuffers for details.
5302 : : */
5303 : 4 : use_bsearch = nrels > RELS_BSEARCH_THRESHOLD;
5304 : :
5305 : : /* sort the list of SMgrRelations if necessary */
5306 [ - + ]: 4 : if (use_bsearch)
969 nathan@postgresql.or 5307 :UBC 0 : qsort(srels, nrels, sizeof(SMgrSortArray), rlocator_comparator);
5308 : :
2382 noah@leadboat.com 5309 [ + + ]:CBC 65540 : for (i = 0; i < NBuffers; i++)
5310 : : {
5311 : 65536 : SMgrSortArray *srelent = NULL;
5312 : 65536 : BufferDesc *bufHdr = GetBufferDescriptor(i);
5313 : : uint64 buf_state;
5314 : :
5315 : : /*
5316 : : * As in DropRelationBuffers, an unlocked precheck should be safe and
5317 : : * saves some cycles.
5318 : : */
5319 : :
5320 [ + - ]: 65536 : if (!use_bsearch)
5321 : : {
5322 : : int j;
5323 : :
5324 [ + + ]: 128807 : for (j = 0; j < nrels; j++)
5325 : : {
1510 rhaas@postgresql.org 5326 [ + + ]: 65536 : if (BufTagMatchesRelFileLocator(&bufHdr->tag, &srels[j].rlocator))
5327 : : {
2382 noah@leadboat.com 5328 : 2265 : srelent = &srels[j];
5329 : 2265 : break;
5330 : : }
5331 : : }
5332 : : }
5333 : : else
5334 : : {
5335 : : RelFileLocator rlocator;
5336 : :
1510 rhaas@postgresql.org 5337 :UBC 0 : rlocator = BufTagGetRelFileLocator(&bufHdr->tag);
675 peter@eisentraut.org 5338 : 0 : srelent = bsearch(&rlocator,
5339 : : srels, nrels, sizeof(SMgrSortArray),
5340 : : rlocator_comparator);
5341 : : }
5342 : :
5343 : : /* buffer doesn't belong to any of the given relfilelocators; skip it */
2382 noah@leadboat.com 5344 [ + + ]:CBC 65536 : if (srelent == NULL)
5345 : 63271 : continue;
5346 : :
5347 : : /* Make sure we can handle the pin */
5348 : 2265 : ReservePrivateRefCountEntry();
1069 heikki.linnakangas@i 5349 : 2265 : ResourceOwnerEnlarge(CurrentResourceOwner);
5350 : :
2382 noah@leadboat.com 5351 : 2265 : buf_state = LockBufHdr(bufHdr);
1510 rhaas@postgresql.org 5352 [ + - ]: 2265 : if (BufTagMatchesRelFileLocator(&bufHdr->tag, &srelent->rlocator) &&
2382 noah@leadboat.com 5353 [ + + ]: 2265 : (buf_state & (BM_VALID | BM_DIRTY)) == (BM_VALID | BM_DIRTY))
5354 : : {
5355 : 2231 : PinBuffer_Locked(bufHdr);
369 andres@anarazel.de 5356 : 2231 : FlushUnlockedBuffer(bufHdr, srelent->srel, IOOBJECT_RELATION, IOCONTEXT_NORMAL);
1473 michael@paquier.xyz 5357 : 2231 : UnpinBuffer(bufHdr);
5358 : : }
5359 : : else
340 andres@anarazel.de 5360 : 34 : UnlockBufHdr(bufHdr);
5361 : : }
5362 : :
2382 noah@leadboat.com 5363 : 4 : pfree(srels);
5364 : : }
5365 : :
5366 : : /* ---------------------------------------------------------------------
5367 : : * RelationCopyStorageUsingBuffer
5368 : : *
5369 : : * Copy fork's data using bufmgr. Same as RelationCopyStorage but instead
5370 : : * of using smgrread and smgrextend this will copy using bufmgr APIs.
5371 : : *
5372 : : * Refer comments atop CreateAndCopyRelationData() for details about
5373 : : * 'permanent' parameter.
5374 : : * --------------------------------------------------------------------
5375 : : */
5376 : : static void
1522 rhaas@postgresql.org 5377 : 81684 : RelationCopyStorageUsingBuffer(RelFileLocator srclocator,
5378 : : RelFileLocator dstlocator,
5379 : : ForkNumber forkNum, bool permanent)
5380 : : {
5381 : : Buffer srcBuf;
5382 : : Buffer dstBuf;
5383 : : Page srcPage;
5384 : : Page dstPage;
5385 : : bool use_wal;
5386 : : BlockNumber nblocks;
5387 : : BlockNumber blkno;
5388 : : PGIOAlignedBlock buf;
5389 : : BufferAccessStrategy bstrategy_src;
5390 : : BufferAccessStrategy bstrategy_dst;
5391 : : BlockRangeReadStreamPrivate p;
5392 : : ReadStream *src_stream;
5393 : : SMgrRelation src_smgr;
5394 : :
5395 : : /*
5396 : : * In general, we want to write WAL whenever wal_level > 'minimal', but we
5397 : : * can skip it when copying any fork of an unlogged relation other than
5398 : : * the init fork.
5399 : : */
1658 5400 [ + + - + : 81684 : use_wal = XLogIsNeeded() && (permanent || forkNum == INIT_FORKNUM);
- - ]
5401 : :
5402 : : /* Get number of blocks in the source relation. */
953 heikki.linnakangas@i 5403 : 81684 : nblocks = smgrnblocks(smgropen(srclocator, INVALID_PROC_NUMBER),
5404 : : forkNum);
5405 : :
5406 : : /* Nothing to copy; just return. */
1658 rhaas@postgresql.org 5407 [ + + ]: 81684 : if (nblocks == 0)
5408 : 14251 : return;
5409 : :
5410 : : /*
5411 : : * Bulk extend the destination relation of the same size as the source
5412 : : * relation before starting to copy block by block.
5413 : : */
1516 5414 : 67433 : memset(buf.data, 0, BLCKSZ);
953 heikki.linnakangas@i 5415 : 67433 : smgrextend(smgropen(dstlocator, INVALID_PROC_NUMBER), forkNum, nblocks - 1,
5416 : : buf.data, true);
5417 : :
5418 : : /* This is a bulk operation, so use buffer access strategies. */
1658 rhaas@postgresql.org 5419 : 67433 : bstrategy_src = GetAccessStrategy(BAS_BULKREAD);
5420 : 67433 : bstrategy_dst = GetAccessStrategy(BAS_BULKWRITE);
5421 : :
5422 : : /* Initialize streaming read */
769 noah@leadboat.com 5423 : 67433 : p.current_blocknum = 0;
5424 : 67433 : p.last_exclusive = nblocks;
814 5425 : 67433 : src_smgr = smgropen(srclocator, INVALID_PROC_NUMBER);
5426 : :
5427 : : /*
5428 : : * It is safe to use batchmode as block_range_read_stream_cb takes no
5429 : : * locks.
5430 : : */
561 andres@anarazel.de 5431 [ + - ]: 67433 : src_stream = read_stream_begin_smgr_relation(READ_STREAM_FULL |
5432 : : READ_STREAM_USE_BATCHING,
5433 : : bstrategy_src,
5434 : : src_smgr,
5435 : : permanent ? RELPERSISTENCE_PERMANENT : RELPERSISTENCE_UNLOGGED,
5436 : : forkNum,
5437 : : block_range_read_stream_cb,
5438 : : &p,
5439 : : 0);
5440 : :
5441 : : /* Iterate over each block of the source relation file. */
1658 rhaas@postgresql.org 5442 [ + + ]: 325111 : for (blkno = 0; blkno < nblocks; blkno++)
5443 : : {
5444 [ - + ]: 257680 : CHECK_FOR_INTERRUPTS();
5445 : :
5446 : : /* Read block from source relation. */
814 noah@leadboat.com 5447 : 257680 : srcBuf = read_stream_next_buffer(src_stream, NULL);
1528 tgl@sss.pgh.pa.us 5448 : 257678 : LockBuffer(srcBuf, BUFFER_LOCK_SHARE);
1658 rhaas@postgresql.org 5449 : 257678 : srcPage = BufferGetPage(srcBuf);
5450 : :
814 noah@leadboat.com 5451 : 257678 : dstBuf = ReadBufferWithoutRelcache(dstlocator, forkNum,
5452 : : BufferGetBlockNumber(srcBuf),
5453 : : RBM_ZERO_AND_LOCK, bstrategy_dst,
5454 : : permanent);
1528 tgl@sss.pgh.pa.us 5455 : 257678 : dstPage = BufferGetPage(dstBuf);
5456 : :
1658 rhaas@postgresql.org 5457 : 257678 : START_CRIT_SECTION();
5458 : :
5459 : : /* Copy page data from the source to the destination. */
5460 : 257678 : memcpy(dstPage, srcPage, BLCKSZ);
5461 : 257678 : MarkBufferDirty(dstBuf);
5462 : :
5463 : : /* WAL-log the copied page. */
5464 [ + + ]: 257678 : if (use_wal)
5465 : 147673 : log_newpage_buffer(dstBuf, true);
5466 : :
5467 [ - + ]: 257678 : END_CRIT_SECTION();
5468 : :
5469 : 257678 : UnlockReleaseBuffer(dstBuf);
1528 tgl@sss.pgh.pa.us 5470 : 257678 : UnlockReleaseBuffer(srcBuf);
5471 : : }
814 noah@leadboat.com 5472 [ - + ]: 67431 : Assert(read_stream_next_buffer(src_stream, NULL) == InvalidBuffer);
5473 : 67431 : read_stream_end(src_stream);
5474 : :
1302 andres@anarazel.de 5475 : 67431 : FreeAccessStrategy(bstrategy_src);
5476 : 67431 : FreeAccessStrategy(bstrategy_dst);
5477 : : }
5478 : :
5479 : : /* ---------------------------------------------------------------------
5480 : : * CreateAndCopyRelationData
5481 : : *
5482 : : * Create destination relation storage and copy all forks from the
5483 : : * source relation to the destination.
5484 : : *
5485 : : * Pass permanent as true for permanent relations and false for
5486 : : * unlogged relations. Currently this API is not supported for
5487 : : * temporary relations.
5488 : : * --------------------------------------------------------------------
5489 : : */
5490 : : void
1559 rhaas@postgresql.org 5491 : 61404 : CreateAndCopyRelationData(RelFileLocator src_rlocator,
5492 : : RelFileLocator dst_rlocator, bool permanent)
5493 : : {
5494 : : char relpersistence;
5495 : : SMgrRelation src_rel;
5496 : : SMgrRelation dst_rel;
5497 : :
5498 : : /* Set the relpersistence. */
1658 5499 [ + - ]: 61404 : relpersistence = permanent ?
5500 : : RELPERSISTENCE_PERMANENT : RELPERSISTENCE_UNLOGGED;
5501 : :
953 heikki.linnakangas@i 5502 : 61404 : src_rel = smgropen(src_rlocator, INVALID_PROC_NUMBER);
5503 : 61404 : dst_rel = smgropen(dst_rlocator, INVALID_PROC_NUMBER);
5504 : :
5505 : : /*
5506 : : * Create and copy all forks of the relation. During create database we
5507 : : * have a separate cleanup mechanism which deletes complete database
5508 : : * directory. Therefore, each individual relation doesn't need to be
5509 : : * registered for cleanup.
5510 : : */
1559 rhaas@postgresql.org 5511 : 61404 : RelationCreateStorage(dst_rlocator, relpersistence, false);
5512 : :
5513 : : /* copy main fork. */
1522 5514 : 61404 : RelationCopyStorageUsingBuffer(src_rlocator, dst_rlocator, MAIN_FORKNUM,
5515 : : permanent);
5516 : :
5517 : : /* copy those extra forks that exist */
1658 5518 : 61402 : for (ForkNumber forkNum = MAIN_FORKNUM + 1;
5519 [ + + ]: 245608 : forkNum <= MAX_FORKNUM; forkNum++)
5520 : : {
985 heikki.linnakangas@i 5521 [ + + ]: 184206 : if (smgrexists(src_rel, forkNum))
5522 : : {
5523 : 20280 : smgrcreate(dst_rel, forkNum, false);
5524 : :
5525 : : /*
5526 : : * WAL log creation if the relation is persistent, or this is the
5527 : : * init fork of an unlogged relation.
5528 : : */
1658 rhaas@postgresql.org 5529 [ - + - - ]: 20280 : if (permanent || forkNum == INIT_FORKNUM)
1559 5530 : 20280 : log_smgrcreate(&dst_rlocator, forkNum);
5531 : :
5532 : : /* Copy a fork's data, block by block. */
1522 5533 : 20280 : RelationCopyStorageUsingBuffer(src_rlocator, dst_rlocator, forkNum,
5534 : : permanent);
5535 : : }
5536 : : }
1658 5537 : 61402 : }
5538 : :
5539 : : /* ---------------------------------------------------------------------
5540 : : * FlushDatabaseBuffers
5541 : : *
5542 : : * This function writes all dirty pages of a database out to disk
5543 : : * (or more accurately, out to kernel disk buffers), ensuring that the
5544 : : * kernel has an up-to-date view of the database.
5545 : : *
5546 : : * Generally, the caller should be holding an appropriate lock to ensure
5547 : : * no other backend is active in the target database; otherwise more
5548 : : * pages could get dirtied.
5549 : : *
5550 : : * Note we don't worry about flushing any pages of temporary relations.
5551 : : * It's assumed these wouldn't be interesting.
5552 : : * --------------------------------------------------------------------
5553 : : */
5554 : : void
7046 tgl@sss.pgh.pa.us 5555 : 5 : FlushDatabaseBuffers(Oid dbid)
5556 : : {
5557 : : int i;
5558 : : BufferDesc *bufHdr;
5559 : :
5560 [ + + ]: 645 : for (i = 0; i < NBuffers; i++)
5561 : : {
5562 : : uint64 buf_state;
5563 : :
4274 andres@anarazel.de 5564 : 640 : bufHdr = GetBufferDescriptor(i);
5565 : :
5566 : : /*
5567 : : * As in DropRelationBuffers, an unlocked precheck should be safe and
5568 : : * saves some cycles.
5569 : : */
1510 rhaas@postgresql.org 5570 [ + + ]: 640 : if (bufHdr->tag.dbOid != dbid)
5240 tgl@sss.pgh.pa.us 5571 : 482 : continue;
5572 : :
5573 : : /* Make sure we can handle the pin */
4284 andres@anarazel.de 5574 : 158 : ReservePrivateRefCountEntry();
1069 heikki.linnakangas@i 5575 : 158 : ResourceOwnerEnlarge(CurrentResourceOwner);
5576 : :
3837 andres@anarazel.de 5577 : 158 : buf_state = LockBufHdr(bufHdr);
1510 rhaas@postgresql.org 5578 [ + - ]: 158 : if (bufHdr->tag.dbOid == dbid &&
3837 andres@anarazel.de 5579 [ + + ]: 158 : (buf_state & (BM_VALID | BM_DIRTY)) == (BM_VALID | BM_DIRTY))
5580 : : {
7046 tgl@sss.pgh.pa.us 5581 : 50 : PinBuffer_Locked(bufHdr);
369 andres@anarazel.de 5582 : 50 : FlushUnlockedBuffer(bufHdr, NULL, IOOBJECT_RELATION, IOCONTEXT_NORMAL);
1473 michael@paquier.xyz 5583 : 50 : UnpinBuffer(bufHdr);
5584 : : }
5585 : : else
340 andres@anarazel.de 5586 : 108 : UnlockBufHdr(bufHdr);
5587 : : }
7046 tgl@sss.pgh.pa.us 5588 : 5 : }
5589 : :
5590 : : /*
5591 : : * Flush a previously, share-exclusively or exclusively, locked and pinned
5592 : : * buffer to the OS.
5593 : : */
5594 : : void
3959 andres@anarazel.de 5595 : 110 : FlushOneBuffer(Buffer buffer)
5596 : : {
5597 : : BufferDesc *bufHdr;
5598 : :
5599 : : /* currently not needed, but no fundamental reason not to support */
5600 [ - + ]: 110 : Assert(!BufferIsLocal(buffer));
5601 : :
5602 [ - + - + : 110 : Assert(BufferIsPinned(buffer));
- + ]
5603 : :
5604 : 110 : bufHdr = GetBufferDescriptor(buffer - 1);
5605 : :
369 5606 [ - + ]: 110 : Assert(BufferIsLockedByMe(buffer));
5607 : :
1341 5608 : 110 : FlushBuffer(bufHdr, NULL, IOOBJECT_RELATION, IOCONTEXT_NORMAL);
3959 5609 : 110 : }
5610 : :
5611 : : /*
5612 : : * ReleaseBuffer -- release the pin on a buffer
5613 : : */
5614 : : void
8833 tgl@sss.pgh.pa.us 5615 : 40355300 : ReleaseBuffer(Buffer buffer)
5616 : : {
8032 5617 [ - + ]: 40355300 : if (!BufferIsValid(buffer))
5594 peter_e@gmx.net 5618 [ # # ]:UBC 0 : elog(ERROR, "bad buffer ID: %d", buffer);
5619 : :
10627 bruce@momjian.us 5620 [ + + ]:CBC 40355300 : if (BufferIsLocal(buffer))
1286 andres@anarazel.de 5621 : 814512 : UnpinLocalBuffer(buffer);
5622 : : else
5623 : 39540788 : UnpinBuffer(GetBufferDescriptor(buffer - 1));
11052 scrappy@hub.org 5624 : 40355300 : }
5625 : :
5626 : : /*
5627 : : * UnlockReleaseBuffer -- release the content lock and pin on a buffer
5628 : : *
5629 : : * This is just a, more efficient, shorthand for a common combination.
5630 : : */
5631 : : void
7500 tgl@sss.pgh.pa.us 5632 : 57859054 : UnlockReleaseBuffer(Buffer buffer)
5633 : : {
5634 : : int mode;
5635 : : BufferDesc *buf;
5636 : : PrivateRefCountEntry *ref;
5637 : : uint64 sub;
5638 : : uint64 lockstate;
5639 : :
199 andres@anarazel.de 5640 [ - + + + : 57859054 : Assert(BufferIsPinned(buffer));
- + ]
5641 : :
5642 [ + + ]: 57859054 : if (BufferIsLocal(buffer))
5643 : : {
5644 : 1459174 : UnpinLocalBuffer(buffer);
5645 : 1459174 : return;
5646 : : }
5647 : :
5648 : 56399880 : ResourceOwnerForgetBuffer(CurrentResourceOwner, buffer);
5649 : :
5650 : 56399880 : buf = GetBufferDescriptor(buffer - 1);
5651 : :
5652 : 56399880 : mode = BufferLockDisownInternal(buffer, buf);
5653 : :
5654 : : /* compute state modification for lock release */
5655 : 56399880 : sub = BufferLockReleaseSub(mode);
5656 : :
5657 : : /* compute state modification for pin release */
5658 : 56399880 : ref = GetPrivateRefCountEntry(buffer, false);
5659 [ - + ]: 56399880 : Assert(ref != NULL);
5660 [ - + ]: 56399880 : Assert(ref->data.refcount > 0);
5661 : 56399880 : ref->data.refcount--;
5662 : :
5663 : : /* no more backend local pins, reduce shared pin count */
5664 [ + + ]: 56399880 : if (likely(ref->data.refcount == 0))
5665 : : {
5666 : : /* See comment in UnpinBufferNoOwner() */
5667 : : VALGRIND_MAKE_MEM_NOACCESS(BufHdrGetBlock(buf), BLCKSZ);
5668 : :
5669 : 53818053 : sub |= BUF_REFCOUNT_ONE;
5670 : 53818053 : ForgetPrivateRefCountEntry(ref);
5671 : : }
5672 : :
5673 : : /* perform the lock and pin release in one atomic op */
5674 : 56399880 : lockstate = pg_atomic_sub_fetch_u64(&buf->state, sub);
5675 : :
5676 : : /* wake up waiters for the lock */
5677 : 56399880 : BufferLockProcessRelease(buf, mode, lockstate);
5678 : :
5679 : : /* wake up waiter for the pin release */
5680 [ + + ]: 56399880 : if (lockstate & BM_PIN_COUNT_WAITER)
5681 : 1 : WakePinCountWaiter(buf);
5682 : :
5683 : : /*
5684 : : * Now okay to allow cancel/die interrupts again, which were held when the
5685 : : * lock was acquired.
5686 : : */
5687 [ - + ]: 56399880 : RESUME_INTERRUPTS();
5688 : : }
5689 : :
5690 : : /*
5691 : : * IncrBufferRefCount
5692 : : * Increment the pin count on a buffer that we have *already* pinned
5693 : : * at least once.
5694 : : *
5695 : : * This function cannot be used on a buffer we do not have pinned,
5696 : : * because it doesn't change the shared buffer state.
5697 : : */
5698 : : void
8122 tgl@sss.pgh.pa.us 5699 : 13980654 : IncrBufferRefCount(Buffer buffer)
5700 : : {
7992 neilc@samurai.com 5701 [ - + + + : 13980654 : Assert(BufferIsPinned(buffer));
- + ]
1069 heikki.linnakangas@i 5702 : 13980654 : ResourceOwnerEnlarge(CurrentResourceOwner);
8122 tgl@sss.pgh.pa.us 5703 [ + + ]: 13980654 : if (BufferIsLocal(buffer))
5704 : 467668 : LocalRefCount[-buffer - 1]++;
5705 : : else
5706 : : {
5707 : : PrivateRefCountEntry *ref;
5708 : :
4284 andres@anarazel.de 5709 : 13512986 : ref = GetPrivateRefCountEntry(buffer, true);
4426 5710 [ - + ]: 13512986 : Assert(ref != NULL);
302 5711 : 13512986 : ref->data.refcount++;
5712 : : }
3260 tgl@sss.pgh.pa.us 5713 : 13980654 : ResourceOwnerRememberBuffer(CurrentResourceOwner, buffer);
8122 5714 : 13980654 : }
5715 : :
5716 : : /*
5717 : : * Shared-buffer only helper for MarkBufferDirtyHint() and
5718 : : * BufferSetHintBits16().
5719 : : *
5720 : : * This is separated out because it turns out that the repeated checks for
5721 : : * local buffers, repeated GetBufferDescriptor() and repeated reading of the
5722 : : * buffer's state sufficiently hurts the performance of BufferSetHintBits16().
5723 : : */
5724 : : static inline void
216 andres@anarazel.de 5725 : 15650592 : MarkSharedBufferDirtyHint(Buffer buffer, BufferDesc *bufHdr, uint64 lockstate,
5726 : : bool buffer_std)
5727 : : {
3827 kgrittn@postgresql.o 5728 : 15650592 : Page page = BufferGetPage(buffer);
5729 : :
4426 andres@anarazel.de 5730 [ - + ]: 15650592 : Assert(GetPrivateRefCount(buffer) > 0);
5731 : :
5732 : : /* here, either share-exclusive or exclusive lock is OK */
216 5733 [ + + - + ]: 15650592 : Assert(BufferLockHeldByMeInMode(bufHdr, BUFFER_LOCK_EXCLUSIVE) ||
5734 : : BufferLockHeldByMeInMode(bufHdr, BUFFER_LOCK_SHARE_EXCLUSIVE));
5735 : :
5736 : : /*
5737 : : * This routine might get called many times on the same page, if we are
5738 : : * making the first scan after commit of an xact that added/deleted many
5739 : : * tuples. So, be as quick as we can if the buffer is already dirty.
5740 : : *
5741 : : * As we are holding (at least) a share-exclusive lock, nobody could have
5742 : : * cleaned or dirtied the page concurrently, so we can just rely on the
5743 : : * previously fetched value here without any danger of races.
5744 : : */
215 5745 [ + + ]: 15650592 : if (unlikely(!(lockstate & BM_DIRTY)))
5746 : : {
4952 simon@2ndQuadrant.co 5747 : 667337 : XLogRecPtr lsn = InvalidXLogRecPtr;
215 andres@anarazel.de 5748 : 667337 : bool wal_log = false;
5749 : : uint64 buf_state;
5750 : :
5751 : : /*
5752 : : * If we need to protect hint bit updates from torn writes, WAL-log a
5753 : : * full page image of the page. This full page image is only necessary
5754 : : * if the hint bit update is the first change to the page since the
5755 : : * last checkpoint.
5756 : : *
5757 : : * We don't check full_page_writes here because that logic is included
5758 : : * when we call XLogInsert() since the value changes dynamically.
5759 : : */
216 5760 [ + + + + : 667337 : if (XLogHintBitIsNeeded() && (lockstate & BM_PERMANENT))
+ + ]
5761 : : {
5762 : : /*
5763 : : * If we must not write WAL, due to a relfilelocator-specific
5764 : : * condition or being in recovery, don't dirty the page. We can
5765 : : * set the hint, just not dirty the page as a result so the hint
5766 : : * is lost when we evict the page or shutdown.
5767 : : *
5768 : : * See src/backend/storage/page/README for longer discussion.
5769 : : */
2382 noah@leadboat.com 5770 [ + + + + ]: 748217 : if (RecoveryInProgress() ||
1510 rhaas@postgresql.org 5771 : 83006 : RelFileLocatorSkippingWAL(BufTagGetRelFileLocator(&bufHdr->tag)))
4952 simon@2ndQuadrant.co 5772 : 583453 : return;
5773 : :
215 andres@anarazel.de 5774 : 81758 : wal_log = true;
5775 : : }
5776 : :
5777 : : /*
5778 : : * We must mark the page dirty before we emit the WAL record, as per
5779 : : * the usual rules, to ensure that BufferSync()/SyncOneBuffer() try to
5780 : : * flush the buffer, even if we haven't inserted the WAL record yet.
5781 : : * As we hold at least a share-exclusive lock, checkpoints will wait
5782 : : * for this backend to be done with the buffer before continuing. If
5783 : : * we did it the other way round, a checkpoint could start between
5784 : : * writing the WAL record and marking the buffer dirty.
5785 : : */
3837 5786 : 83884 : buf_state = LockBufHdr(bufHdr);
5787 : :
5788 : : /*
5789 : : * It should not be possible for the buffer to already be dirty, see
5790 : : * comment above.
5791 : : */
216 5792 [ - + ]: 83884 : Assert(!(buf_state & BM_DIRTY));
3837 5793 [ - + ]: 83884 : Assert(BUF_STATE_GET_REFCOUNT(buf_state) > 0);
215 5794 : 83884 : UnlockBufHdrExt(bufHdr, buf_state,
5795 : : BM_DIRTY,
5796 : : 0, 0);
5797 : :
5798 : : /*
5799 : : * If the block is already dirty because we either made a change or
5800 : : * set a hint already, then we don't need to write a full page image.
5801 : : * Note that aggressive cleaning of blocks dirtied by hint bit setting
5802 : : * would increase the call rate. Bulk setting of hint bits would
5803 : : * reduce the call rate...
5804 : : */
5805 [ + + ]: 83884 : if (wal_log)
5806 : 81758 : lsn = XLogSaveBufferForHint(buffer, buffer_std);
5807 : :
216 5808 [ + + ]: 83884 : if (XLogRecPtrIsValid(lsn))
5809 : : {
5810 : : /*
5811 : : * Set the page LSN if we wrote a backup block. To allow backends
5812 : : * that only hold a share lock on the buffer to read the LSN in a
5813 : : * tear-free manner, we set the page LSN while holding the buffer
5814 : : * header lock. This allows any reader of an LSN who holds only a
5815 : : * share lock to also obtain a buffer header lock before using
5816 : : * PageGetLSN() to read the LSN in a tear free way. This is done
5817 : : * in BufferGetLSNAtomic().
5818 : : *
5819 : : * If checksums are enabled, you might think we should reset the
5820 : : * checksum here. That will happen when the page is written
5821 : : * sometime later in this checkpoint cycle.
5822 : : */
215 5823 : 56960 : buf_state = LockBufHdr(bufHdr);
216 5824 : 56960 : PageSetLSN(page, lsn);
215 5825 : 56960 : UnlockBufHdr(bufHdr);
5826 : : }
5827 : :
216 5828 : 83884 : pgBufferUsage.shared_blks_dirtied++;
5829 [ + + ]: 83884 : if (VacuumCostActive)
5830 : 4142 : VacuumCostBalance += VacuumCostPageDirty;
5831 : : }
5832 : : }
5833 : :
5834 : : /*
5835 : : * MarkBufferDirtyHint
5836 : : *
5837 : : * Mark a buffer dirty for non-critical changes.
5838 : : *
5839 : : * This is essentially the same as MarkBufferDirty, except:
5840 : : *
5841 : : * 1. The caller does not write WAL; so if checksums are enabled, we may need
5842 : : * to write an XLOG_FPI_FOR_HINT WAL record to protect against torn pages.
5843 : : * 2. The caller might have only a share-exclusive-lock instead of an
5844 : : * exclusive-lock on the buffer's content lock.
5845 : : * 3. This function does not guarantee that the buffer is always marked dirty
5846 : : * (it e.g. can't always on a hot standby), so it cannot be used for
5847 : : * important changes.
5848 : : */
5849 : : inline void
5850 : 727179 : MarkBufferDirtyHint(Buffer buffer, bool buffer_std)
5851 : : {
5852 : : BufferDesc *bufHdr;
5853 : :
5854 [ - + ]: 727179 : if (!BufferIsValid(buffer))
216 andres@anarazel.de 5855 [ # # ]:UBC 0 : elog(ERROR, "bad buffer ID: %d", buffer);
5856 : :
216 andres@anarazel.de 5857 [ + + ]:CBC 727179 : if (BufferIsLocal(buffer))
5858 : : {
5859 : 13433 : MarkLocalBufferDirty(buffer);
5860 : 13433 : return;
5861 : : }
5862 : :
124 michael@paquier.xyz 5863 : 713746 : bufHdr = GetBufferDescriptor(buffer - 1);
5864 : :
216 andres@anarazel.de 5865 : 713746 : MarkSharedBufferDirtyHint(buffer, bufHdr,
5866 : 713746 : pg_atomic_read_u64(&bufHdr->state),
5867 : : buffer_std);
5868 : : }
5869 : :
5870 : : /*
5871 : : * Release buffer content locks for shared buffers.
5872 : : *
5873 : : * Used to clean up after errors.
5874 : : *
5875 : : * Currently, we can expect that resource owner cleanup, via
5876 : : * ResOwnerReleaseBuffer(), took care of releasing buffer content locks per
5877 : : * se; the only thing we need to deal with here is clearing any PIN_COUNT
5878 : : * request that was in progress.
5879 : : */
5880 : : void
9404 tgl@sss.pgh.pa.us 5881 : 65008 : UnlockBuffers(void)
5882 : : {
3983 rhaas@postgresql.org 5883 : 65008 : BufferDesc *buf = PinCountWaitBuf;
5884 : :
8031 tgl@sss.pgh.pa.us 5885 [ - + ]: 65008 : if (buf)
5886 : : {
5887 : : uint64 buf_state;
270 andres@anarazel.de 5888 :UBC 0 : uint64 unset_bits = 0;
5889 : :
3837 5890 : 0 : buf_state = LockBufHdr(buf);
5891 : :
5892 : : /*
5893 : : * Don't complain if flag bit not set; it could have been reset but we
5894 : : * got a cancel/die interrupt before getting the signal.
5895 : : */
5896 [ # # ]: 0 : if ((buf_state & BM_PIN_COUNT_WAITER) != 0 &&
963 heikki.linnakangas@i 5897 [ # # ]: 0 : buf->wait_backend_pgprocno == MyProcNumber)
340 andres@anarazel.de 5898 : 0 : unset_bits = BM_PIN_COUNT_WAITER;
5899 : :
5900 : 0 : UnlockBufHdrExt(buf, buf_state,
5901 : : 0, unset_bits,
5902 : : 0);
5903 : :
7892 tgl@sss.pgh.pa.us 5904 : 0 : PinCountWaitBuf = NULL;
5905 : : }
10163 vadim4o@yahoo.com 5906 :CBC 65008 : }
5907 : :
5908 : : /*
5909 : : * Acquire the buffer content lock in the specified mode
5910 : : *
5911 : : * If the lock is not available, sleep until it is.
5912 : : *
5913 : : * Side effect: cancel/die interrupts are held off until lock release.
5914 : : *
5915 : : * This uses almost the same locking approach as lwlock.c's
5916 : : * LWLockAcquire(). See documentation at the top of lwlock.c for a more
5917 : : * detailed discussion.
5918 : : *
5919 : : * The reason that this, and most of the other BufferLock* functions, get both
5920 : : * the Buffer and BufferDesc* as parameters, is that looking up one from the
5921 : : * other repeatedly shows up noticeably in profiles.
5922 : : *
5923 : : * Callers should provide a constant for mode, for more efficient code
5924 : : * generation.
5925 : : */
5926 : : static inline void
270 andres@anarazel.de 5927 : 109741182 : BufferLockAcquire(Buffer buffer, BufferDesc *buf_hdr, BufferLockMode mode)
5928 : : {
5929 : : PrivateRefCountEntry *entry;
5930 : 109741182 : int extraWaits = 0;
5931 : :
5932 : : /*
5933 : : * Get reference to the refcount entry before we hold the lock, it seems
5934 : : * better to do before holding the lock.
5935 : : */
5936 : 109741182 : entry = GetPrivateRefCountEntry(buffer, true);
5937 : :
5938 : : /*
5939 : : * We better not already hold a lock on the buffer.
5940 : : */
5941 [ - + ]: 109741182 : Assert(entry->data.lockmode == BUFFER_LOCK_UNLOCK);
5942 : :
5943 : : /*
5944 : : * Lock out cancel/die interrupts until we exit the code section protected
5945 : : * by the content lock. This ensures that interrupts will not interfere
5946 : : * with manipulations of data structures in shared memory.
5947 : : */
5948 : 109741182 : HOLD_INTERRUPTS();
5949 : :
5950 : : for (;;)
5951 : 37582 : {
269 5952 : 109778764 : uint32 wait_event = 0; /* initialized to avoid compiler warning */
5953 : : bool mustwait;
5954 : :
5955 : : /*
5956 : : * Try to grab the lock the first time, we're not in the waitqueue
5957 : : * yet/anymore.
5958 : : */
270 5959 : 109778764 : mustwait = BufferLockAttempt(buf_hdr, mode);
5960 : :
5961 [ + + ]: 109778764 : if (likely(!mustwait))
5962 : : {
5963 : 109740028 : break;
5964 : : }
5965 : :
5966 : : /*
5967 : : * Ok, at this point we couldn't grab the lock on the first try. We
5968 : : * cannot simply queue ourselves to the end of the list and wait to be
5969 : : * woken up because by now the lock could long have been released.
5970 : : * Instead add us to the queue and try to grab the lock again. If we
5971 : : * succeed we need to revert the queuing and be happy, otherwise we
5972 : : * recheck the lock. If we still couldn't grab it, we know that the
5973 : : * other locker will see our queue entries when releasing since they
5974 : : * existed before we checked for the lock.
5975 : : */
5976 : :
5977 : : /* add to the queue */
5978 : 38736 : BufferLockQueueSelf(buf_hdr, mode);
5979 : :
5980 : : /* we're now guaranteed to be woken up if necessary */
5981 : 38736 : mustwait = BufferLockAttempt(buf_hdr, mode);
5982 : :
5983 : : /* ok, grabbed the lock the second time round, need to undo queueing */
5984 [ + + ]: 38736 : if (!mustwait)
5985 : : {
5986 : 1154 : BufferLockDequeueSelf(buf_hdr);
5987 : 1154 : break;
5988 : : }
5989 : :
5990 [ + + + - : 37582 : switch (mode)
- ]
5991 : : {
5992 : 20808 : case BUFFER_LOCK_EXCLUSIVE:
5993 : 20808 : wait_event = WAIT_EVENT_BUFFER_EXCLUSIVE;
5994 : 20808 : break;
5995 : 94 : case BUFFER_LOCK_SHARE_EXCLUSIVE:
5996 : 94 : wait_event = WAIT_EVENT_BUFFER_SHARE_EXCLUSIVE;
5997 : 94 : break;
5998 : 16680 : case BUFFER_LOCK_SHARE:
5999 : 16680 : wait_event = WAIT_EVENT_BUFFER_SHARED;
6000 : 16680 : break;
270 andres@anarazel.de 6001 :UBC 0 : case BUFFER_LOCK_UNLOCK:
6002 : 0 : pg_unreachable();
6003 : :
6004 : : }
270 andres@anarazel.de 6005 :CBC 37582 : pgstat_report_wait_start(wait_event);
6006 : :
6007 : : /*
6008 : : * Wait until awakened.
6009 : : *
6010 : : * It is possible that we get awakened for a reason other than being
6011 : : * signaled by BufferLockWakeup(). If so, loop back and wait again.
6012 : : * Once we've gotten the lock, re-increment the sema by the number of
6013 : : * additional signals received.
6014 : : */
6015 : : for (;;)
6016 : : {
6017 : 37582 : PGSemaphoreLock(MyProc->sem);
6018 [ + - ]: 37582 : if (MyProc->lwWaiting == LW_WS_NOT_WAITING)
6019 : 37582 : break;
270 andres@anarazel.de 6020 :UBC 0 : extraWaits++;
6021 : : }
6022 : :
270 andres@anarazel.de 6023 :CBC 37582 : pgstat_report_wait_end();
6024 : :
6025 : : /* Retrying, allow BufferLockReleaseSub to release waiters again. */
6026 : 37582 : pg_atomic_fetch_and_u64(&buf_hdr->state, ~BM_LOCK_WAKE_IN_PROGRESS);
6027 : : }
6028 : :
6029 : : /* Remember that we now hold this lock */
6030 : 109741182 : entry->data.lockmode = mode;
6031 : :
6032 : : /*
6033 : : * Fix the process wait semaphore's count for any absorbed wakeups.
6034 : : */
6035 [ - + ]: 109741182 : while (unlikely(extraWaits-- > 0))
270 andres@anarazel.de 6036 :UBC 0 : PGSemaphoreUnlock(MyProc->sem);
270 andres@anarazel.de 6037 :CBC 109741182 : }
6038 : :
6039 : : /*
6040 : : * Release a previously acquired buffer content lock.
6041 : : */
6042 : : static void
6043 : 55080579 : BufferLockUnlock(Buffer buffer, BufferDesc *buf_hdr)
6044 : : {
6045 : : BufferLockMode mode;
6046 : : uint64 oldstate;
6047 : : uint64 sub;
6048 : :
6049 : 55080579 : mode = BufferLockDisownInternal(buffer, buf_hdr);
6050 : :
6051 : : /*
6052 : : * Release my hold on lock, after that it can immediately be acquired by
6053 : : * others, even if we still have to wakeup other waiters.
6054 : : */
6055 : 55080579 : sub = BufferLockReleaseSub(mode);
6056 : :
6057 : 55080579 : oldstate = pg_atomic_sub_fetch_u64(&buf_hdr->state, sub);
6058 : :
6059 : 55080579 : BufferLockProcessRelease(buf_hdr, mode, oldstate);
6060 : :
6061 : : /*
6062 : : * Now okay to allow cancel/die interrupts.
6063 : : */
6064 [ - + ]: 55080579 : RESUME_INTERRUPTS();
6065 : 55080579 : }
6066 : :
6067 : :
6068 : : /*
6069 : : * Acquire the content lock for the buffer, but only if we don't have to wait.
6070 : : *
6071 : : * It is allowed to try to conditionally acquire a lock on a buffer that this
6072 : : * backend has already locked, but the lock acquisition will always fail, even
6073 : : * if the new lock acquisition does not conflict with an already held lock
6074 : : * (e.g. two share locks). This is because we currently do not have space to
6075 : : * track multiple lock ownerships of the same buffer within one backend. That
6076 : : * is ok for the current uses of BufferLockConditional().
6077 : : */
6078 : : static bool
6079 : 1741002 : BufferLockConditional(Buffer buffer, BufferDesc *buf_hdr, BufferLockMode mode)
6080 : : {
6081 : 1741002 : PrivateRefCountEntry *entry = GetPrivateRefCountEntry(buffer, true);
6082 : : bool mustwait;
6083 : :
6084 : : /*
6085 : : * As described above, if we're trying to lock a buffer this backend
6086 : : * already has locked, return false, independent of the existing and
6087 : : * desired lock level.
6088 : : */
256 6089 [ - + ]: 1741002 : if (entry->data.lockmode != BUFFER_LOCK_UNLOCK)
256 andres@anarazel.de 6090 :UBC 0 : return false;
6091 : :
6092 : : /*
6093 : : * Lock out cancel/die interrupts until we exit the code section protected
6094 : : * by the content lock. This ensures that interrupts will not interfere
6095 : : * with manipulations of data structures in shared memory.
6096 : : */
270 andres@anarazel.de 6097 :CBC 1741002 : HOLD_INTERRUPTS();
6098 : :
6099 : : /* Check for the lock */
6100 : 1741002 : mustwait = BufferLockAttempt(buf_hdr, mode);
6101 : :
6102 [ + + ]: 1741002 : if (mustwait)
6103 : : {
6104 : : /* Failed to get lock, so release interrupt holdoff */
6105 [ - + ]: 1725 : RESUME_INTERRUPTS();
6106 : : }
6107 : : else
6108 : : {
6109 : 1739277 : entry->data.lockmode = mode;
6110 : : }
6111 : :
6112 : 1741002 : return !mustwait;
6113 : : }
6114 : :
6115 : : /*
6116 : : * Internal function that tries to atomically acquire the content lock in the
6117 : : * passed in mode.
6118 : : *
6119 : : * This function will not block waiting for a lock to become free - that's the
6120 : : * caller's job.
6121 : : *
6122 : : * Similar to LWLockAttemptLock().
6123 : : */
6124 : : static inline bool
6125 : 111558502 : BufferLockAttempt(BufferDesc *buf_hdr, BufferLockMode mode)
6126 : : {
6127 : : uint64 old_state;
6128 : :
6129 : : /*
6130 : : * Read once outside the loop, later iterations will get the newer value
6131 : : * via compare & exchange.
6132 : : */
6133 : 111558502 : old_state = pg_atomic_read_u64(&buf_hdr->state);
6134 : :
6135 : : /* loop until we've determined whether we could acquire the lock or not */
6136 : : while (true)
6137 : 6720 : {
6138 : : uint64 desired_state;
6139 : : bool lock_free;
6140 : :
6141 : 111565222 : desired_state = old_state;
6142 : :
6143 [ + + ]: 111565222 : if (mode == BUFFER_LOCK_EXCLUSIVE)
6144 : : {
6145 : 38100731 : lock_free = (old_state & BM_LOCK_MASK) == 0;
6146 [ + + ]: 38100731 : if (lock_free)
6147 : 38056439 : desired_state += BM_LOCK_VAL_EXCLUSIVE;
6148 : : }
6149 [ + + ]: 73464491 : else if (mode == BUFFER_LOCK_SHARE_EXCLUSIVE)
6150 : : {
6151 : 734783 : lock_free = (old_state & (BM_LOCK_VAL_EXCLUSIVE | BM_LOCK_VAL_SHARE_EXCLUSIVE)) == 0;
6152 [ + + ]: 734783 : if (lock_free)
6153 : 734594 : desired_state += BM_LOCK_VAL_SHARE_EXCLUSIVE;
6154 : : }
6155 : : else
6156 : : {
6157 : 72729708 : lock_free = (old_state & BM_LOCK_VAL_EXCLUSIVE) == 0;
6158 [ + + ]: 72729708 : if (lock_free)
6159 : 72695697 : desired_state += BM_LOCK_VAL_SHARED;
6160 : : }
6161 : :
6162 : : /*
6163 : : * Attempt to swap in the state we are expecting. If we didn't see
6164 : : * lock to be free, that's just the old value. If we saw it as free,
6165 : : * we'll attempt to mark it acquired. The reason that we always swap
6166 : : * in the value is that this doubles as a memory barrier. We could try
6167 : : * to be smarter and only swap in values if we saw the lock as free,
6168 : : * but benchmark haven't shown it as beneficial so far.
6169 : : *
6170 : : * Retry if the value changed since we last looked at it.
6171 : : */
6172 [ + + ]: 111565222 : if (likely(pg_atomic_compare_exchange_u64(&buf_hdr->state,
6173 : : &old_state, desired_state)))
6174 : : {
6175 [ + + ]: 111558502 : if (lock_free)
6176 : : {
6177 : : /* Great! Got the lock. */
6178 : 111480459 : return false;
6179 : : }
6180 : : else
6181 : 78043 : return true; /* somebody else has the lock */
6182 : : }
6183 : : }
6184 : :
6185 : : pg_unreachable();
6186 : : }
6187 : :
6188 : : /*
6189 : : * Add ourselves to the end of the content lock's wait queue.
6190 : : */
6191 : : static void
6192 : 38736 : BufferLockQueueSelf(BufferDesc *buf_hdr, BufferLockMode mode)
6193 : : {
6194 : : /*
6195 : : * If we don't have a PGPROC structure, there's no way to wait. This
6196 : : * should never occur, since MyProc should only be null during shared
6197 : : * memory initialization.
6198 : : */
6199 [ - + ]: 38736 : if (MyProc == NULL)
270 andres@anarazel.de 6200 [ # # ]:UBC 0 : elog(PANIC, "cannot wait without a PGPROC structure");
6201 : :
270 andres@anarazel.de 6202 [ - + ]:CBC 38736 : if (MyProc->lwWaiting != LW_WS_NOT_WAITING)
270 andres@anarazel.de 6203 [ # # ]:UBC 0 : elog(PANIC, "queueing for lock while waiting on another one");
6204 : :
270 andres@anarazel.de 6205 :CBC 38736 : LockBufHdr(buf_hdr);
6206 : :
6207 : : /* setting the flag is protected by the spinlock */
6208 : 38736 : pg_atomic_fetch_or_u64(&buf_hdr->state, BM_LOCK_HAS_WAITERS);
6209 : :
6210 : : /*
6211 : : * These are currently used both for lwlocks and buffer content locks,
6212 : : * which is acceptable, although not pretty, because a backend can't wait
6213 : : * for both types of locks at the same time.
6214 : : */
6215 : 38736 : MyProc->lwWaiting = LW_WS_WAITING;
6216 : 38736 : MyProc->lwWaitMode = mode;
6217 : :
6218 : 38736 : proclist_push_tail(&buf_hdr->lock_waiters, MyProcNumber, lwWaitLink);
6219 : :
6220 : : /* Can release the mutex now */
6221 : 38736 : UnlockBufHdr(buf_hdr);
6222 : 38736 : }
6223 : :
6224 : : /*
6225 : : * Remove ourselves from the waitlist.
6226 : : *
6227 : : * This is used if we queued ourselves because we thought we needed to sleep
6228 : : * but, after further checking, we discovered that we don't actually need to
6229 : : * do so.
6230 : : */
6231 : : static void
6232 : 1154 : BufferLockDequeueSelf(BufferDesc *buf_hdr)
6233 : : {
6234 : : bool on_waitlist;
6235 : :
6236 : 1154 : LockBufHdr(buf_hdr);
6237 : :
6238 : 1154 : on_waitlist = MyProc->lwWaiting == LW_WS_WAITING;
6239 [ + + ]: 1154 : if (on_waitlist)
6240 : 644 : proclist_delete(&buf_hdr->lock_waiters, MyProcNumber, lwWaitLink);
6241 : :
6242 [ + + ]: 1154 : if (proclist_is_empty(&buf_hdr->lock_waiters) &&
6243 [ + + ]: 1077 : (pg_atomic_read_u64(&buf_hdr->state) & BM_LOCK_HAS_WAITERS) != 0)
6244 : : {
6245 : 567 : pg_atomic_fetch_and_u64(&buf_hdr->state, ~BM_LOCK_HAS_WAITERS);
6246 : : }
6247 : :
6248 : : /* XXX: combine with fetch_and above? */
6249 : 1154 : UnlockBufHdr(buf_hdr);
6250 : :
6251 : : /* clear waiting state again, nice for debugging */
6252 [ + + ]: 1154 : if (on_waitlist)
6253 : 644 : MyProc->lwWaiting = LW_WS_NOT_WAITING;
6254 : : else
6255 : : {
6256 : 510 : int extraWaits = 0;
6257 : :
6258 : :
6259 : : /*
6260 : : * Somebody else dequeued us and has or will wake us up. Deal with the
6261 : : * superfluous absorption of a wakeup.
6262 : : */
6263 : :
6264 : : /*
6265 : : * Clear BM_LOCK_WAKE_IN_PROGRESS if somebody woke us before we
6266 : : * removed ourselves - they'll have set it.
6267 : : */
6268 : 510 : pg_atomic_fetch_and_u64(&buf_hdr->state, ~BM_LOCK_WAKE_IN_PROGRESS);
6269 : :
6270 : : /*
6271 : : * Now wait for the scheduled wakeup, otherwise our ->lwWaiting would
6272 : : * get reset at some inconvenient point later. Most of the time this
6273 : : * will immediately return.
6274 : : */
6275 : : for (;;)
6276 : : {
6277 : 510 : PGSemaphoreLock(MyProc->sem);
6278 [ + - ]: 510 : if (MyProc->lwWaiting == LW_WS_NOT_WAITING)
6279 : 510 : break;
270 andres@anarazel.de 6280 :UBC 0 : extraWaits++;
6281 : : }
6282 : :
6283 : : /*
6284 : : * Fix the process wait semaphore's count for any absorbed wakeups.
6285 : : */
270 andres@anarazel.de 6286 [ - + ]:CBC 510 : while (extraWaits-- > 0)
270 andres@anarazel.de 6287 :UBC 0 : PGSemaphoreUnlock(MyProc->sem);
6288 : : }
270 andres@anarazel.de 6289 :CBC 1154 : }
6290 : :
6291 : : /*
6292 : : * Stop treating lock as held by current backend.
6293 : : *
6294 : : * After calling this function it's the callers responsibility to ensure that
6295 : : * the lock gets released, even in case of an error. This only is desirable if
6296 : : * the lock is going to be released in a different process than the process
6297 : : * that acquired it.
6298 : : */
6299 : : static inline void
270 andres@anarazel.de 6300 :UBC 0 : BufferLockDisown(Buffer buffer, BufferDesc *buf_hdr)
6301 : : {
6302 : 0 : BufferLockDisownInternal(buffer, buf_hdr);
6303 [ # # ]: 0 : RESUME_INTERRUPTS();
6304 : 0 : }
6305 : :
6306 : : /*
6307 : : * Stop treating lock as held by current backend.
6308 : : *
6309 : : * This is the code that can be shared between actually releasing a lock
6310 : : * (BufferLockUnlock()) and just not tracking ownership of the lock anymore
6311 : : * without releasing the lock (BufferLockDisown()).
6312 : : */
6313 : : static inline int
270 andres@anarazel.de 6314 :CBC 111480459 : BufferLockDisownInternal(Buffer buffer, BufferDesc *buf_hdr)
6315 : : {
6316 : : BufferLockMode mode;
6317 : : PrivateRefCountEntry *ref;
6318 : :
6319 : 111480459 : ref = GetPrivateRefCountEntry(buffer, false);
6320 [ - + ]: 111480459 : if (ref == NULL)
270 andres@anarazel.de 6321 [ # # ]:UBC 0 : elog(ERROR, "lock %d is not held", buffer);
270 andres@anarazel.de 6322 :CBC 111480459 : mode = ref->data.lockmode;
6323 : 111480459 : ref->data.lockmode = BUFFER_LOCK_UNLOCK;
6324 : :
6325 : 111480459 : return mode;
6326 : : }
6327 : :
6328 : : /*
6329 : : * Wakeup all the lockers that currently have a chance to acquire the lock.
6330 : : *
6331 : : * wake_exclusive indicates whether exclusive lock waiters should be woken up.
6332 : : */
6333 : : static void
6334 : 35982 : BufferLockWakeup(BufferDesc *buf_hdr, bool wake_exclusive)
6335 : : {
6336 : 35982 : bool new_wake_in_progress = false;
6337 : 35982 : bool wake_share_exclusive = true;
6338 : : proclist_head wakeup;
6339 : : proclist_mutable_iter iter;
6340 : :
6341 : 35982 : proclist_init(&wakeup);
6342 : :
6343 : : /* lock wait list while collecting backends to wake up */
6344 : 35982 : LockBufHdr(buf_hdr);
6345 : :
6346 [ + + + + : 54337 : proclist_foreach_modify(iter, &buf_hdr->lock_waiters, lwWaitLink)
+ + ]
6347 : : {
6348 : 39441 : PGPROC *waiter = GetPGProcByNumber(iter.cur);
6349 : :
6350 : : /*
6351 : : * Already woke up a conflicting lock, so skip over this wait list
6352 : : * entry.
6353 : : */
6354 [ + + + + ]: 39441 : if (!wake_exclusive && waiter->lwWaitMode == BUFFER_LOCK_EXCLUSIVE)
6355 : 1348 : continue;
6356 [ + + - + ]: 38093 : if (!wake_share_exclusive && waiter->lwWaitMode == BUFFER_LOCK_SHARE_EXCLUSIVE)
270 andres@anarazel.de 6357 :UBC 0 : continue;
6358 : :
270 andres@anarazel.de 6359 :CBC 38093 : proclist_delete(&buf_hdr->lock_waiters, iter.cur, lwWaitLink);
6360 : 38093 : proclist_push_tail(&wakeup, iter.cur, lwWaitLink);
6361 : :
6362 : : /*
6363 : : * Prevent additional wakeups until retryer gets to run. Backends that
6364 : : * are just waiting for the lock to become free don't retry
6365 : : * automatically.
6366 : : */
6367 : 38093 : new_wake_in_progress = true;
6368 : :
6369 : : /*
6370 : : * Signal that the process isn't on the wait list anymore. This allows
6371 : : * BufferLockDequeueSelf() to remove itself from the waitlist with a
6372 : : * proclist_delete(), rather than having to check if it has been
6373 : : * removed from the list.
6374 : : */
6375 [ - + ]: 38093 : Assert(waiter->lwWaiting == LW_WS_WAITING);
6376 : 38093 : waiter->lwWaiting = LW_WS_PENDING_WAKEUP;
6377 : :
6378 : : /*
6379 : : * Don't wakeup further waiters after waking a conflicting waiter.
6380 : : */
6381 [ + + ]: 38093 : if (waiter->lwWaitMode == BUFFER_LOCK_SHARE)
6382 : : {
6383 : : /*
6384 : : * Share locks conflict with exclusive locks.
6385 : : */
6386 : 16909 : wake_exclusive = false;
6387 : : }
6388 [ + + ]: 21184 : else if (waiter->lwWaitMode == BUFFER_LOCK_SHARE_EXCLUSIVE)
6389 : : {
6390 : : /*
6391 : : * Share-exclusive locks conflict with share-exclusive and
6392 : : * exclusive locks.
6393 : : */
6394 : 98 : wake_exclusive = false;
6395 : 98 : wake_share_exclusive = false;
6396 : : }
6397 [ + - ]: 21086 : else if (waiter->lwWaitMode == BUFFER_LOCK_EXCLUSIVE)
6398 : : {
6399 : : /*
6400 : : * Exclusive locks conflict with all other locks, there's no point
6401 : : * in waking up anybody else.
6402 : : */
6403 : 21086 : break;
6404 : : }
6405 : : }
6406 : :
6407 [ + + - + ]: 35982 : Assert(proclist_is_empty(&wakeup) || pg_atomic_read_u64(&buf_hdr->state) & BM_LOCK_HAS_WAITERS);
6408 : :
6409 : : /* unset required flags, and release lock, in one fell swoop */
6410 : : {
6411 : : uint64 old_state;
6412 : : uint64 desired_state;
6413 : :
6414 : 35982 : old_state = pg_atomic_read_u64(&buf_hdr->state);
6415 : : while (true)
6416 : : {
6417 : 36008 : desired_state = old_state;
6418 : :
6419 : : /* compute desired flags */
6420 : :
6421 [ + + ]: 36008 : if (new_wake_in_progress)
6422 : 35941 : desired_state |= BM_LOCK_WAKE_IN_PROGRESS;
6423 : : else
6424 : 67 : desired_state &= ~BM_LOCK_WAKE_IN_PROGRESS;
6425 : :
6426 [ + + ]: 36008 : if (proclist_is_empty(&buf_hdr->lock_waiters))
6427 : 31574 : desired_state &= ~BM_LOCK_HAS_WAITERS;
6428 : :
6429 : 36008 : desired_state &= ~BM_LOCKED; /* release lock */
6430 : :
6431 [ + + ]: 36008 : if (pg_atomic_compare_exchange_u64(&buf_hdr->state, &old_state,
6432 : : desired_state))
6433 : 35982 : break;
6434 : : }
6435 : : }
6436 : :
6437 : : /* Awaken any waiters I removed from the queue. */
6438 [ + + + + : 74075 : proclist_foreach_modify(iter, &wakeup, lwWaitLink)
+ + ]
6439 : : {
6440 : 38093 : PGPROC *waiter = GetPGProcByNumber(iter.cur);
6441 : :
6442 : 38093 : proclist_delete(&wakeup, iter.cur, lwWaitLink);
6443 : :
6444 : : /*
6445 : : * Guarantee that lwWaiting being unset only becomes visible once the
6446 : : * unlink from the link has completed. Otherwise the target backend
6447 : : * could be woken up for other reason and enqueue for a new lock - if
6448 : : * that happens before the list unlink happens, the list would end up
6449 : : * being corrupted.
6450 : : *
6451 : : * The barrier pairs with the LockBufHdr() when enqueuing for another
6452 : : * lock.
6453 : : */
6454 : 38093 : pg_write_barrier();
6455 : 38093 : waiter->lwWaiting = LW_WS_NOT_WAITING;
6456 : 38093 : PGSemaphoreUnlock(waiter->sem);
6457 : : }
6458 : 35982 : }
6459 : :
6460 : : /*
6461 : : * Compute subtraction from buffer state for a release of a held lock in
6462 : : * `mode`.
6463 : : *
6464 : : * This is separated from BufferLockUnlock() as we want to combine the lock
6465 : : * release with other atomic operations when possible, leading to the lock
6466 : : * release being done in multiple places, each needing to compute what to
6467 : : * subtract from the lock state.
6468 : : */
6469 : : static inline uint64
6470 : 111480459 : BufferLockReleaseSub(BufferLockMode mode)
6471 : : {
6472 : : /*
6473 : : * Turns out that a switch() leads gcc to generate sufficiently worse code
6474 : : * for this to show up in profiles...
6475 : : */
6476 [ + + ]: 111480459 : if (mode == BUFFER_LOCK_EXCLUSIVE)
6477 : 38056030 : return BM_LOCK_VAL_EXCLUSIVE;
6478 [ + + ]: 73424429 : else if (mode == BUFFER_LOCK_SHARE_EXCLUSIVE)
6479 : 4159038 : return BM_LOCK_VAL_SHARE_EXCLUSIVE;
6480 : : else
6481 : : {
6482 [ - + ]: 69265391 : Assert(mode == BUFFER_LOCK_SHARE);
6483 : 69265391 : return BM_LOCK_VAL_SHARED;
6484 : : }
6485 : :
6486 : : return 0; /* keep compiler quiet */
6487 : : }
6488 : :
6489 : : /*
6490 : : * Handle work that needs to be done after releasing a lock that was held in
6491 : : * `mode`, where `lockstate` is the result of the atomic operation modifying
6492 : : * the state variable.
6493 : : *
6494 : : * This is separated from BufferLockUnlock() as we want to combine the lock
6495 : : * release with other atomic operations when possible, leading to the lock
6496 : : * release being done in multiple places.
6497 : : */
6498 : : static void
6499 : 111480459 : BufferLockProcessRelease(BufferDesc *buf_hdr, BufferLockMode mode, uint64 lockstate)
6500 : : {
6501 : 111480459 : bool check_waiters = false;
6502 : 111480459 : bool wake_exclusive = false;
6503 : :
6504 : : /* nobody else can have that kind of lock */
6505 [ - + ]: 111480459 : Assert(!(lockstate & BM_LOCK_VAL_EXCLUSIVE));
6506 : :
6507 : : /*
6508 : : * If we're still waiting for backends to get scheduled, don't wake them
6509 : : * up again. Otherwise check if we need to look through the waitqueue to
6510 : : * wake other backends.
6511 : : */
6512 [ + + ]: 111480459 : if ((lockstate & BM_LOCK_HAS_WAITERS) &&
6513 [ + + ]: 106781 : !(lockstate & BM_LOCK_WAKE_IN_PROGRESS))
6514 : : {
6515 [ + + ]: 62323 : if ((lockstate & BM_LOCK_MASK) == 0)
6516 : : {
6517 : : /*
6518 : : * We released a lock and the lock was, in that moment, free. We
6519 : : * therefore can wake waiters for any kind of lock.
6520 : : */
6521 : 35973 : check_waiters = true;
6522 : 35973 : wake_exclusive = true;
6523 : : }
6524 [ + + ]: 26350 : else if (mode == BUFFER_LOCK_SHARE_EXCLUSIVE)
6525 : : {
6526 : : /*
6527 : : * We released the lock, but another backend still holds a lock.
6528 : : * We can't have released an exclusive lock, as there couldn't
6529 : : * have been other lock holders. If we released a share lock, no
6530 : : * waiters need to be woken up, as there must be other share
6531 : : * lockers. However, if we held a share-exclusive lock, another
6532 : : * backend now could acquire a share-exclusive lock.
6533 : : */
6534 : 9 : check_waiters = true;
6535 : 9 : wake_exclusive = false;
6536 : : }
6537 : : }
6538 : :
6539 : : /*
6540 : : * As waking up waiters requires the spinlock to be acquired, only do so
6541 : : * if necessary.
6542 : : */
6543 [ + + ]: 111480459 : if (check_waiters)
6544 : 35982 : BufferLockWakeup(buf_hdr, wake_exclusive);
6545 : 111480459 : }
6546 : :
6547 : : /*
6548 : : * BufferLockHeldByMeInMode - test whether my process holds the content lock
6549 : : * in the specified mode
6550 : : *
6551 : : * This is meant as debug support only.
6552 : : */
6553 : : static bool
6554 : 138758906 : BufferLockHeldByMeInMode(BufferDesc *buf_hdr, BufferLockMode mode)
6555 : : {
6556 : : PrivateRefCountEntry *entry =
6557 : 138758906 : GetPrivateRefCountEntry(BufferDescriptorGetBuffer(buf_hdr), false);
6558 : :
6559 [ - + ]: 138758906 : if (!entry)
270 andres@anarazel.de 6560 :UBC 0 : return false;
6561 : : else
270 andres@anarazel.de 6562 :CBC 138758906 : return entry->data.lockmode == mode;
6563 : : }
6564 : :
6565 : : /*
6566 : : * BufferLockHeldByMe - test whether my process holds the content lock in any
6567 : : * mode
6568 : : *
6569 : : * This is meant as debug support only.
6570 : : */
6571 : : static bool
6572 : 21772405 : BufferLockHeldByMe(BufferDesc *buf_hdr)
6573 : : {
6574 : : PrivateRefCountEntry *entry =
6575 : 21772405 : GetPrivateRefCountEntry(BufferDescriptorGetBuffer(buf_hdr), false);
6576 : :
6577 [ - + ]: 21772405 : if (!entry)
270 andres@anarazel.de 6578 :UBC 0 : return false;
6579 : : else
270 andres@anarazel.de 6580 :CBC 21772405 : return entry->data.lockmode != BUFFER_LOCK_UNLOCK;
6581 : : }
6582 : :
6583 : : /*
6584 : : * Release the content lock for the buffer.
6585 : : */
6586 : : void
6587 : 60111903 : UnlockBuffer(Buffer buffer)
6588 : : {
6589 : : BufferDesc *buf_hdr;
6590 : :
2275 pg@bowt.ie 6591 [ - + + + : 60111903 : Assert(BufferIsPinned(buffer));
- + ]
10163 vadim4o@yahoo.com 6592 [ + + ]: 60111903 : if (BufferIsLocal(buffer))
7500 tgl@sss.pgh.pa.us 6593 : 5411652 : return; /* local buffers need no lock */
6594 : :
270 andres@anarazel.de 6595 : 54700251 : buf_hdr = GetBufferDescriptor(buffer - 1);
6596 : 54700251 : BufferLockUnlock(buffer, buf_hdr);
6597 : : }
6598 : :
6599 : : /*
6600 : : * Acquire the content_lock for the buffer.
6601 : : */
6602 : : void
6603 : 116118618 : LockBufferInternal(Buffer buffer, BufferLockMode mode)
6604 : : {
6605 : : BufferDesc *buf_hdr;
6606 : :
6607 : : /*
6608 : : * We can't wait if we haven't got a PGPROC. This should only occur
6609 : : * during bootstrap or shared memory initialization. Put an Assert here
6610 : : * to catch unsafe coding practices.
6611 : : */
6612 [ - + - - ]: 116118618 : Assert(!(MyProc == NULL && IsUnderPostmaster));
6613 : :
6614 : : /* handled in LockBuffer() wrapper */
6615 [ - + ]: 116118618 : Assert(mode != BUFFER_LOCK_UNLOCK);
6616 : :
6617 [ - + + + : 116118618 : Assert(BufferIsPinned(buffer));
- + ]
6618 [ + + ]: 116118618 : if (BufferIsLocal(buffer))
6619 : 6757640 : return; /* local buffers need no lock */
6620 : :
6621 : 109360978 : buf_hdr = GetBufferDescriptor(buffer - 1);
6622 : :
6623 : : /*
6624 : : * Test the most frequent lock modes first. While a switch (mode) would be
6625 : : * nice, at least gcc generates considerably worse code for it.
6626 : : *
6627 : : * Call BufferLockAcquire() with a constant argument for mode, to generate
6628 : : * more efficient code for the different lock modes.
6629 : : */
6630 [ + + ]: 109360978 : if (mode == BUFFER_LOCK_SHARE)
6631 : 72689837 : BufferLockAcquire(buffer, buf_hdr, BUFFER_LOCK_SHARE);
10163 vadim4o@yahoo.com 6632 [ + - ]: 36671141 : else if (mode == BUFFER_LOCK_EXCLUSIVE)
270 andres@anarazel.de 6633 : 36671141 : BufferLockAcquire(buffer, buf_hdr, BUFFER_LOCK_EXCLUSIVE);
270 andres@anarazel.de 6634 [ # # ]:UBC 0 : else if (mode == BUFFER_LOCK_SHARE_EXCLUSIVE)
6635 : 0 : BufferLockAcquire(buffer, buf_hdr, BUFFER_LOCK_SHARE_EXCLUSIVE);
6636 : : else
8481 tgl@sss.pgh.pa.us 6637 [ # # ]: 0 : elog(ERROR, "unrecognized buffer lock mode: %d", mode);
6638 : : }
6639 : :
6640 : : /*
6641 : : * Acquire the content_lock for the buffer, but only if we don't have to wait.
6642 : : *
6643 : : * This assumes the caller wants BUFFER_LOCK_EXCLUSIVE mode.
6644 : : */
6645 : : bool
8464 tgl@sss.pgh.pa.us 6646 :CBC 1472770 : ConditionalLockBuffer(Buffer buffer)
6647 : : {
6648 : : BufferDesc *buf;
6649 : :
2275 pg@bowt.ie 6650 [ - + + + : 1472770 : Assert(BufferIsPinned(buffer));
- + ]
8464 tgl@sss.pgh.pa.us 6651 [ + + ]: 1472770 : if (BufferIsLocal(buffer))
6652 : 86172 : return true; /* act as though we got it */
6653 : :
4274 andres@anarazel.de 6654 : 1386598 : buf = GetBufferDescriptor(buffer - 1);
6655 : :
270 6656 : 1386598 : return BufferLockConditional(buffer, buf, BUFFER_LOCK_EXCLUSIVE);
6657 : : }
6658 : :
6659 : : /*
6660 : : * Verify that this backend is pinning the buffer exactly once.
6661 : : *
6662 : : * NOTE: Like in BufferIsPinned(), what we check here is that *this* backend
6663 : : * holds a pin on the buffer. We do not care whether some other backend does.
6664 : : */
6665 : : void
1286 6666 : 4417029 : CheckBufferIsPinnedOnce(Buffer buffer)
6667 : : {
6668 [ + + ]: 4417029 : if (BufferIsLocal(buffer))
6669 : : {
6670 [ - + ]: 1619 : if (LocalRefCount[-buffer - 1] != 1)
1286 andres@anarazel.de 6671 [ # # ]:UBC 0 : elog(ERROR, "incorrect local pin count: %d",
6672 : : LocalRefCount[-buffer - 1]);
6673 : : }
6674 : : else
6675 : : {
1286 andres@anarazel.de 6676 [ - + ]:CBC 4415410 : if (GetPrivateRefCount(buffer) != 1)
1286 andres@anarazel.de 6677 [ # # ]:UBC 0 : elog(ERROR, "incorrect local pin count: %d",
6678 : : GetPrivateRefCount(buffer));
6679 : : }
1286 andres@anarazel.de 6680 :CBC 4417029 : }
6681 : :
6682 : : /*
6683 : : * LockBufferForCleanup - lock a buffer in preparation for deleting items
6684 : : *
6685 : : * Items may be deleted from a disk page only when the caller (a) holds an
6686 : : * exclusive lock on the buffer and (b) has observed that no other backend
6687 : : * holds a pin on the buffer. If there is a pin, then the other backend
6688 : : * might have a pointer into the buffer (for example, a heapscan reference
6689 : : * to an item --- see README for more details). It's OK if a pin is added
6690 : : * after the cleanup starts, however; the newly-arrived backend will be
6691 : : * unable to look at the page until we release the exclusive lock.
6692 : : *
6693 : : * To implement this protocol, a would-be deleter must pin the buffer and
6694 : : * then call LockBufferForCleanup(). LockBufferForCleanup() is similar to
6695 : : * LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE), except that it loops until
6696 : : * it has successfully observed pin count = 1.
6697 : : */
6698 : : void
9229 tgl@sss.pgh.pa.us 6699 : 34930 : LockBufferForCleanup(Buffer buffer)
6700 : : {
6701 : : BufferDesc *bufHdr;
2103 fujii@postgresql.org 6702 : 34930 : TimestampTz waitStart = 0;
1330 drowley@postgresql.o 6703 : 34930 : bool waiting = false;
2103 fujii@postgresql.org 6704 : 34930 : bool logged_recovery_conflict = false;
6705 : :
2275 pg@bowt.ie 6706 [ - + + + : 34930 : Assert(BufferIsPinned(buffer));
- + ]
8031 tgl@sss.pgh.pa.us 6707 [ - + ]: 34930 : Assert(PinCountWaitBuf == NULL);
6708 : :
1286 andres@anarazel.de 6709 : 34930 : CheckBufferIsPinnedOnce(buffer);
6710 : :
6711 : : /*
6712 : : * We do not yet need to be worried about in-progress AIOs holding a pin,
6713 : : * as we, so far, only support doing reads via AIO and this function can
6714 : : * only be called once the buffer is valid (i.e. no read can be in
6715 : : * flight).
6716 : : */
6717 : :
6718 : : /* Nobody else to wait for */
9229 tgl@sss.pgh.pa.us 6719 [ + + ]: 34930 : if (BufferIsLocal(buffer))
6720 : 21 : return;
6721 : :
4274 andres@anarazel.de 6722 : 34909 : bufHdr = GetBufferDescriptor(buffer - 1);
6723 : :
6724 : : for (;;)
9229 tgl@sss.pgh.pa.us 6725 : 62 : {
6726 : : uint64 buf_state;
270 andres@anarazel.de 6727 : 34971 : uint64 unset_bits = 0;
6728 : :
6729 : : /* Try to acquire lock */
9229 tgl@sss.pgh.pa.us 6730 : 34971 : LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE);
3837 andres@anarazel.de 6731 : 34971 : buf_state = LockBufHdr(bufHdr);
6732 : :
6733 [ - + ]: 34971 : Assert(BUF_STATE_GET_REFCOUNT(buf_state) > 0);
6734 [ + + ]: 34971 : if (BUF_STATE_GET_REFCOUNT(buf_state) == 1)
6735 : : {
6736 : : /* Successfully acquired exclusive lock with pincount 1 */
340 6737 : 34909 : UnlockBufHdr(bufHdr);
104 fujii@postgresql.org 6738 : 34909 : goto cleanup_lock_acquired;
6739 : : }
6740 : : /* Failed, so mark myself as waiting for pincount 1 */
3837 andres@anarazel.de 6741 [ - + ]: 62 : if (buf_state & BM_PIN_COUNT_WAITER)
6742 : : {
340 andres@anarazel.de 6743 :UBC 0 : UnlockBufHdr(bufHdr);
9229 tgl@sss.pgh.pa.us 6744 : 0 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
8481 6745 [ # # ]: 0 : elog(ERROR, "multiple backends attempting to wait for pincount 1");
6746 : : }
963 heikki.linnakangas@i 6747 :CBC 62 : bufHdr->wait_backend_pgprocno = MyProcNumber;
8031 tgl@sss.pgh.pa.us 6748 : 62 : PinCountWaitBuf = bufHdr;
6749 : :
6750 : : /*
6751 : : * Publish BM_PIN_COUNT_WAITER while retaining the buffer header lock.
6752 : : * The shared refcount can be decremented while BM_LOCKED is set, so
6753 : : * use an atomic operation that preserves concurrent refcount changes.
6754 : : */
104 fujii@postgresql.org 6755 : 62 : pg_atomic_fetch_or_u64(&bufHdr->state, BM_PIN_COUNT_WAITER);
6756 : :
6757 : : /*
6758 : : * Recheck the refcount after publishing the waiter flag, while shared
6759 : : * refcount increments are still prevented by BM_LOCKED. If only our
6760 : : * pin remains, the cleanup-lock condition has already been satisfied,
6761 : : * so remove the waiter state and return without sleeping.
6762 : : */
6763 : 62 : buf_state = pg_atomic_read_u64(&bufHdr->state);
6764 : :
6765 [ - + ]: 62 : if (BUF_STATE_GET_REFCOUNT(buf_state) == 1)
6766 : : {
104 fujii@postgresql.org 6767 :UBC 0 : UnlockBufHdrExt(bufHdr, buf_state,
6768 : : 0, BM_PIN_COUNT_WAITER,
6769 : : 0);
6770 : 0 : PinCountWaitBuf = NULL;
6771 : 0 : goto cleanup_lock_acquired;
6772 : : }
6773 : :
104 fujii@postgresql.org 6774 :CBC 62 : UnlockBufHdr(bufHdr);
9229 tgl@sss.pgh.pa.us 6775 : 62 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
6776 : :
6777 : : /* Wait to be signaled by UnpinBuffer() */
6106 simon@2ndQuadrant.co 6778 [ + + ]: 62 : if (InHotStandby)
6779 : : {
1330 drowley@postgresql.o 6780 [ + + ]: 8 : if (!waiting)
6781 : : {
6782 : : /* adjust the process title to indicate that it's waiting */
6783 : 2 : set_ps_display_suffix("waiting");
6784 : 2 : waiting = true;
6785 : : }
6786 : :
6787 : : /*
6788 : : * Emit the log message if the startup process is waiting longer
6789 : : * than deadlock_timeout for recovery conflict on buffer pin.
6790 : : *
6791 : : * Skip this if first time through because the startup process has
6792 : : * not started waiting yet in this case. So, the wait start
6793 : : * timestamp is set after this logic.
6794 : : */
2103 fujii@postgresql.org 6795 [ + + + + ]: 8 : if (waitStart != 0 && !logged_recovery_conflict)
6796 : : {
6797 : 3 : TimestampTz now = GetCurrentTimestamp();
6798 : :
6799 [ + + ]: 3 : if (TimestampDifferenceExceeds(waitStart, now,
6800 : : DeadlockTimeout))
6801 : : {
244 heikki.linnakangas@i 6802 : 2 : LogRecoveryConflict(RECOVERY_CONFLICT_BUFFERPIN,
6803 : : waitStart, now, NULL, true);
2103 fujii@postgresql.org 6804 : 2 : logged_recovery_conflict = true;
6805 : : }
6806 : : }
6807 : :
6808 : : /*
6809 : : * Set the wait start timestamp if logging is enabled and first
6810 : : * time through.
6811 : : */
6812 [ + - + + ]: 8 : if (log_recovery_conflict_waits && waitStart == 0)
6813 : 2 : waitStart = GetCurrentTimestamp();
6814 : :
6815 : : /* Publish the buffer that Startup process waits on */
39 nathan@postgresql.or 6816 :GNC 8 : SetStartupBufferPinWaitBuf(buffer);
6817 : : /* Set alarm and then wait to be signaled by UnpinBuffer() */
6106 simon@2ndQuadrant.co 6818 :CBC 8 : ResolveRecoveryConflictWithBufferPin();
6819 : : /* Reset the published buffer */
39 nathan@postgresql.or 6820 :GNC 8 : SetStartupBufferPinWaitBuf(InvalidBuffer);
6821 : : }
6822 : : else
313 andres@anarazel.de 6823 :CBC 54 : ProcWaitForSignal(WAIT_EVENT_BUFFER_CLEANUP);
6824 : :
6825 : : /*
6826 : : * Remove flag marking us as waiter. Normally this will not be set
6827 : : * anymore, but ProcWaitForSignal() can return for other signals as
6828 : : * well. We take care to only reset the flag if we're the waiter, as
6829 : : * theoretically another backend could have started waiting. That's
6830 : : * impossible with the current usages due to table level locking, but
6831 : : * better be safe.
6832 : : */
3837 6833 : 62 : buf_state = LockBufHdr(bufHdr);
6834 [ + + ]: 62 : if ((buf_state & BM_PIN_COUNT_WAITER) != 0 &&
963 heikki.linnakangas@i 6835 [ + - ]: 6 : bufHdr->wait_backend_pgprocno == MyProcNumber)
340 andres@anarazel.de 6836 : 6 : unset_bits |= BM_PIN_COUNT_WAITER;
6837 : :
6838 : 62 : UnlockBufHdrExt(bufHdr, buf_state,
6839 : : 0, unset_bits,
6840 : : 0);
6841 : :
8031 tgl@sss.pgh.pa.us 6842 : 62 : PinCountWaitBuf = NULL;
6843 : : /* Loop back and try again */
6844 : : }
6845 : :
104 fujii@postgresql.org 6846 : 34909 : cleanup_lock_acquired:
6847 : :
6848 : : /*
6849 : : * Emit the log message if recovery conflict on buffer pin was resolved
6850 : : * but the startup process waited longer than deadlock_timeout for it.
6851 : : */
6852 [ + + ]: 34909 : if (logged_recovery_conflict)
6853 : 2 : LogRecoveryConflict(RECOVERY_CONFLICT_BUFFERPIN,
6854 : : waitStart, GetCurrentTimestamp(),
6855 : : NULL, false);
6856 : :
6857 [ + + ]: 34909 : if (waiting)
6858 : : {
6859 : : /* reset ps display to remove the suffix if we added one */
6860 : 2 : set_ps_display_remove_suffix();
6861 : 2 : waiting = false;
6862 : : }
6863 : :
6864 : 34909 : return;
6865 : : }
6866 : :
6867 : : /*
6868 : : * Check called from ProcessRecoveryConflictInterrupts() when Startup process
6869 : : * requests cancellation of all pin holders that are blocking it.
6870 : : */
6871 : : bool
6106 simon@2ndQuadrant.co 6872 : 4 : HoldingBufferPinThatDelaysRecovery(void)
6873 : : {
39 nathan@postgresql.or 6874 :GNC 4 : Buffer buffer = GetStartupBufferPinWaitBuf();
6875 : :
6876 : : /*
6877 : : * If we get woken slowly then it's possible that the Startup process was
6878 : : * already woken by other backends before we got here. Also possible that
6879 : : * we get here by multiple interrupts or interrupts at inappropriate
6880 : : * times, so make sure we do nothing if the buffer is not set.
6881 : : */
6882 [ + + ]: 4 : if (buffer == InvalidBuffer)
6106 simon@2ndQuadrant.co 6883 :CBC 2 : return false;
6884 : :
39 nathan@postgresql.or 6885 [ + - ]:GNC 2 : if (GetPrivateRefCount(buffer) > 0)
6106 simon@2ndQuadrant.co 6886 :CBC 2 : return true;
6887 : :
6106 simon@2ndQuadrant.co 6888 :UBC 0 : return false;
6889 : : }
6890 : :
6891 : : /*
6892 : : * ConditionalLockBufferForCleanup - as above, but don't wait to get the lock
6893 : : *
6894 : : * We won't loop, but just check once to see if the pin count is OK. If
6895 : : * not, return false with no lock held.
6896 : : */
6897 : : bool
6962 tgl@sss.pgh.pa.us 6898 :CBC 228688 : ConditionalLockBufferForCleanup(Buffer buffer)
6899 : : {
6900 : : BufferDesc *bufHdr;
6901 : : uint64 buf_state,
6902 : : refcount;
6903 : :
6904 [ - + ]: 228688 : Assert(BufferIsValid(buffer));
6905 : :
6906 : : /* see AIO related comment in LockBufferForCleanup() */
6907 : :
6908 [ + + ]: 228688 : if (BufferIsLocal(buffer))
6909 : : {
3837 andres@anarazel.de 6910 : 13333 : refcount = LocalRefCount[-buffer - 1];
6911 : : /* There should be exactly one pin */
6912 [ - + ]: 13333 : Assert(refcount > 0);
6913 [ + + ]: 13333 : if (refcount != 1)
6962 tgl@sss.pgh.pa.us 6914 : 1504 : return false;
6915 : : /* Nobody else to wait for */
6916 : 11829 : return true;
6917 : : }
6918 : :
6919 : : /* There should be exactly one local pin */
3837 andres@anarazel.de 6920 : 215355 : refcount = GetPrivateRefCount(buffer);
6921 [ - + ]: 215355 : Assert(refcount);
6922 [ + + ]: 215355 : if (refcount != 1)
6962 tgl@sss.pgh.pa.us 6923 : 185 : return false;
6924 : :
6925 : : /* Try to acquire lock */
6926 [ + + ]: 215170 : if (!ConditionalLockBuffer(buffer))
6927 : 58 : return false;
6928 : :
4274 andres@anarazel.de 6929 : 215112 : bufHdr = GetBufferDescriptor(buffer - 1);
3837 6930 : 215112 : buf_state = LockBufHdr(bufHdr);
6931 : 215112 : refcount = BUF_STATE_GET_REFCOUNT(buf_state);
6932 : :
6933 [ - + ]: 215112 : Assert(refcount > 0);
6934 [ + + ]: 215112 : if (refcount == 1)
6935 : : {
6936 : : /* Successfully acquired exclusive lock with pincount 1 */
340 6937 : 214872 : UnlockBufHdr(bufHdr);
6962 tgl@sss.pgh.pa.us 6938 : 214872 : return true;
6939 : : }
6940 : :
6941 : : /* Failed, so release the lock */
340 andres@anarazel.de 6942 : 240 : UnlockBufHdr(bufHdr);
6962 tgl@sss.pgh.pa.us 6943 : 240 : LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
6944 : 240 : return false;
6945 : : }
6946 : :
6947 : : /*
6948 : : * IsBufferCleanupOK - as above, but we already have the lock
6949 : : *
6950 : : * Check whether it's OK to perform cleanup on a buffer we've already
6951 : : * locked. If we observe that the pin count is 1, our exclusive lock
6952 : : * happens to be a cleanup lock, and we can proceed with anything that
6953 : : * would have been allowable had we sought a cleanup lock originally.
6954 : : */
6955 : : bool
3629 rhaas@postgresql.org 6956 : 2702 : IsBufferCleanupOK(Buffer buffer)
6957 : : {
6958 : : BufferDesc *bufHdr;
6959 : : uint64 buf_state;
6960 : :
6961 [ - + ]: 2702 : Assert(BufferIsValid(buffer));
6962 : :
6963 : : /* see AIO related comment in LockBufferForCleanup() */
6964 : :
6965 [ - + ]: 2702 : if (BufferIsLocal(buffer))
6966 : : {
6967 : : /* There should be exactly one pin */
3629 rhaas@postgresql.org 6968 [ # # ]:UBC 0 : if (LocalRefCount[-buffer - 1] != 1)
6969 : 0 : return false;
6970 : : /* Nobody else to wait for */
6971 : 0 : return true;
6972 : : }
6973 : :
6974 : : /* There should be exactly one local pin */
3629 rhaas@postgresql.org 6975 [ - + ]:CBC 2702 : if (GetPrivateRefCount(buffer) != 1)
3629 rhaas@postgresql.org 6976 :UBC 0 : return false;
6977 : :
3629 rhaas@postgresql.org 6978 :CBC 2702 : bufHdr = GetBufferDescriptor(buffer - 1);
6979 : :
6980 : : /* caller must hold exclusive lock on buffer */
369 andres@anarazel.de 6981 [ - + ]: 2702 : Assert(BufferIsLockedByMeInMode(buffer, BUFFER_LOCK_EXCLUSIVE));
6982 : :
3629 rhaas@postgresql.org 6983 : 2702 : buf_state = LockBufHdr(bufHdr);
6984 : :
6985 [ - + ]: 2702 : Assert(BUF_STATE_GET_REFCOUNT(buf_state) > 0);
6986 [ + - ]: 2702 : if (BUF_STATE_GET_REFCOUNT(buf_state) == 1)
6987 : : {
6988 : : /* pincount is OK. */
340 andres@anarazel.de 6989 : 2702 : UnlockBufHdr(bufHdr);
3629 rhaas@postgresql.org 6990 : 2702 : return true;
6991 : : }
6992 : :
340 andres@anarazel.de 6993 :UBC 0 : UnlockBufHdr(bufHdr);
3629 rhaas@postgresql.org 6994 : 0 : return false;
6995 : : }
6996 : :
6997 : : /*
6998 : : * Helper for BufferBeginSetHintBits() and BufferSetHintBits16().
6999 : : *
7000 : : * This checks if the current lock mode already suffices to allow hint bits
7001 : : * being set and, if not, whether the current lock can be upgraded.
7002 : : *
7003 : : * Updates *lockstate when returning true.
7004 : : */
7005 : : static inline bool
216 andres@anarazel.de 7006 :CBC 15237515 : SharedBufferBeginSetHintBits(Buffer buffer, BufferDesc *buf_hdr, uint64 *lockstate)
7007 : : {
7008 : : uint64 old_state;
7009 : : PrivateRefCountEntry *ref;
7010 : : BufferLockMode mode;
7011 : :
7012 : 15237515 : ref = GetPrivateRefCountEntry(buffer, true);
7013 : :
7014 [ - + ]: 15237515 : if (ref == NULL)
216 andres@anarazel.de 7015 [ # # ]:UBC 0 : elog(ERROR, "buffer is not pinned");
7016 : :
216 andres@anarazel.de 7017 :CBC 15237515 : mode = ref->data.lockmode;
7018 [ - + ]: 15237515 : if (mode == BUFFER_LOCK_UNLOCK)
216 andres@anarazel.de 7019 [ # # ]:UBC 0 : elog(ERROR, "buffer is not locked");
7020 : :
7021 : : /* we're done if we are already holding a sufficient lock level */
216 andres@anarazel.de 7022 [ + + + + ]:CBC 15237515 : if (mode == BUFFER_LOCK_EXCLUSIVE || mode == BUFFER_LOCK_SHARE_EXCLUSIVE)
7023 : : {
7024 : 11812942 : *lockstate = pg_atomic_read_u64(&buf_hdr->state);
7025 : 11812942 : return true;
7026 : : }
7027 : :
7028 : : /*
7029 : : * We are only holding a share lock right now, try to upgrade it to
7030 : : * SHARE_EXCLUSIVE.
7031 : : */
7032 [ - + ]: 3424573 : Assert(mode == BUFFER_LOCK_SHARE);
7033 : :
7034 : 3424573 : old_state = pg_atomic_read_u64(&buf_hdr->state);
7035 : : while (true)
7036 : 5 : {
7037 : : uint64 desired_state;
7038 : :
7039 : 3424578 : desired_state = old_state;
7040 : :
7041 : : /*
7042 : : * Can't upgrade if somebody else holds the lock in exclusive or
7043 : : * share-exclusive mode.
7044 : : */
7045 [ + + ]: 3424578 : if (unlikely((old_state & (BM_LOCK_VAL_EXCLUSIVE | BM_LOCK_VAL_SHARE_EXCLUSIVE)) != 0))
7046 : : {
7047 : 127 : return false;
7048 : : }
7049 : :
7050 : : /* currently held lock state */
7051 : 3424451 : desired_state -= BM_LOCK_VAL_SHARED;
7052 : :
7053 : : /* new lock level */
7054 : 3424451 : desired_state += BM_LOCK_VAL_SHARE_EXCLUSIVE;
7055 : :
7056 [ + + ]: 3424451 : if (likely(pg_atomic_compare_exchange_u64(&buf_hdr->state,
7057 : : &old_state, desired_state)))
7058 : : {
7059 : 3424446 : ref->data.lockmode = BUFFER_LOCK_SHARE_EXCLUSIVE;
7060 : 3424446 : *lockstate = desired_state;
7061 : :
7062 : 3424446 : return true;
7063 : : }
7064 : : }
7065 : : }
7066 : :
7067 : : /*
7068 : : * Try to acquire the right to set hint bits on the buffer.
7069 : : *
7070 : : * To be allowed to set hint bits, this backend needs to hold either a
7071 : : * share-exclusive or an exclusive lock. In case this backend only holds a
7072 : : * share lock, this function will try to upgrade the lock to
7073 : : * share-exclusive. The caller is only allowed to set hint bits if true is
7074 : : * returned.
7075 : : *
7076 : : * Once BufferBeginSetHintBits() has returned true, hint bits may be set
7077 : : * without further calls to BufferBeginSetHintBits(), until the buffer is
7078 : : * unlocked.
7079 : : *
7080 : : *
7081 : : * Requiring a share-exclusive lock to set hint bits prevents setting hint
7082 : : * bits on buffers that are currently being written out, which could corrupt
7083 : : * the checksum on the page. Flushing buffers also requires a share-exclusive
7084 : : * lock.
7085 : : *
7086 : : * Due to a lock >= share-exclusive being required to set hint bits, only one
7087 : : * backend can set hint bits at a time. Allowing multiple backends to set hint
7088 : : * bits would require more complicated locking: For setting hint bits we'd
7089 : : * need to store the count of backends currently setting hint bits, for I/O we
7090 : : * would need another lock-level conflicting with the hint-setting
7091 : : * lock-level. Given that the share-exclusive lock for setting hint bits is
7092 : : * only held for a short time, that backends often would just set the same
7093 : : * hint bits and that the cost of occasionally not setting hint bits in hotly
7094 : : * accessed pages is fairly low, this seems like an acceptable tradeoff.
7095 : : */
7096 : : bool
7097 : 303037 : BufferBeginSetHintBits(Buffer buffer)
7098 : : {
7099 : : BufferDesc *buf_hdr;
7100 : : uint64 lockstate;
7101 : :
7102 [ + + ]: 303037 : if (BufferIsLocal(buffer))
7103 : : {
7104 : : /*
7105 : : * NB: Will need to check if there is a write in progress, once it is
7106 : : * possible for writes to be done asynchronously.
7107 : : */
7108 : 2484 : return true;
7109 : : }
7110 : :
7111 : 300553 : buf_hdr = GetBufferDescriptor(buffer - 1);
7112 : :
7113 : 300553 : return SharedBufferBeginSetHintBits(buffer, buf_hdr, &lockstate);
7114 : : }
7115 : :
7116 : : /*
7117 : : * End a phase of setting hint bits on this buffer, started with
7118 : : * BufferBeginSetHintBits().
7119 : : *
7120 : : * This would strictly speaking not be required (i.e. the caller could do
7121 : : * MarkBufferDirtyHint() if so desired), but allows us to perform some sanity
7122 : : * checks.
7123 : : */
7124 : : void
7125 : 303026 : BufferFinishSetHintBits(Buffer buffer, bool mark_dirty, bool buffer_std)
7126 : : {
7127 [ + + ]: 303026 : if (!BufferIsLocal(buffer))
7128 [ + + - + ]: 300542 : Assert(BufferIsLockedByMeInMode(buffer, BUFFER_LOCK_SHARE_EXCLUSIVE) ||
7129 : : BufferIsLockedByMeInMode(buffer, BUFFER_LOCK_EXCLUSIVE));
7130 : :
7131 [ + + ]: 303026 : if (mark_dirty)
7132 : 223592 : MarkBufferDirtyHint(buffer, buffer_std);
7133 : 303026 : }
7134 : :
7135 : : /*
7136 : : * Try to set hint bits on a single 16bit value in a buffer.
7137 : : *
7138 : : * If hint bits are allowed to be set, set *ptr = val, try to mark the buffer
7139 : : * dirty and return true. Otherwise false is returned.
7140 : : *
7141 : : * *ptr needs to be a pointer to memory within the buffer.
7142 : : *
7143 : : * This is a bit faster than BufferBeginSetHintBits() /
7144 : : * BufferFinishSetHintBits() when setting hints once in a buffer, but slower
7145 : : * than the former when setting hint bits multiple times in the same buffer.
7146 : : */
7147 : : bool
7148 : 15836403 : BufferSetHintBits16(uint16 *ptr, uint16 val, Buffer buffer)
7149 : : {
7150 : : BufferDesc *buf_hdr;
7151 : : uint64 lockstate;
7152 : : #ifdef USE_ASSERT_CHECKING
7153 : : char *page;
7154 : :
7155 : : /* verify that the address is on the page */
7156 : 15836403 : page = BufferGetPage(buffer);
7157 [ + - - + ]: 15836403 : Assert((char *) ptr >= page && (char *) ptr < (page + BLCKSZ));
7158 : : #endif
7159 : :
7160 [ + + ]: 15836403 : if (BufferIsLocal(buffer))
7161 : : {
7162 : 899441 : *ptr = val;
7163 : :
7164 : 899441 : MarkLocalBufferDirty(buffer);
7165 : :
7166 : 899441 : return true;
7167 : : }
7168 : :
7169 : 14936962 : buf_hdr = GetBufferDescriptor(buffer - 1);
7170 : :
7171 [ + + ]: 14936962 : if (SharedBufferBeginSetHintBits(buffer, buf_hdr, &lockstate))
7172 : : {
7173 : 14936846 : *ptr = val;
7174 : :
7175 : 14936846 : MarkSharedBufferDirtyHint(buffer, buf_hdr, lockstate, true);
7176 : :
7177 : 14936846 : return true;
7178 : : }
7179 : :
7180 : 116 : return false;
7181 : : }
7182 : :
7183 : :
7184 : : /*
7185 : : * Functions for buffer I/O handling
7186 : : *
7187 : : * Also note that these are used only for shared buffers, not local ones.
7188 : : */
7189 : :
7190 : : /*
7191 : : * WaitIO -- Block until the IO_IN_PROGRESS flag on 'buf' is cleared.
7192 : : */
7193 : : static void
3983 rhaas@postgresql.org 7194 : 237 : WaitIO(BufferDesc *buf)
7195 : : {
2041 tmunro@postgresql.or 7196 : 237 : ConditionVariable *cv = BufferDescriptorGetIOCV(buf);
7197 : :
7198 : : /*
7199 : : * Should never end up here with unsubmitted IO, as no AIO unaware code
7200 : : * may be used while in batch mode and AIO aware code needs to have
7201 : : * submitted all staged IO to avoid deadlocks & slowness.
7202 : : */
199 andres@anarazel.de 7203 [ - + ]: 237 : Assert(!pgaio_have_staged());
7204 : :
2041 tmunro@postgresql.or 7205 : 237 : ConditionVariablePrepareToSleep(cv);
7206 : : for (;;)
7892 tgl@sss.pgh.pa.us 7207 : 237 : {
7208 : : uint64 buf_state;
7209 : : PgAioWaitRef iow;
7210 : :
7211 : : /*
7212 : : * It may not be necessary to acquire the spinlock to check the flag
7213 : : * here, but since this test is essential for correctness, we'd better
7214 : : * play it safe.
7215 : : */
3837 andres@anarazel.de 7216 : 474 : buf_state = LockBufHdr(buf);
7217 : :
7218 : : /*
7219 : : * Copy the wait reference while holding the spinlock. This protects
7220 : : * against a concurrent TerminateBufferIO() in another backend from
7221 : : * clearing the wref while it's being read.
7222 : : */
561 7223 : 474 : iow = buf->io_wref;
340 7224 : 474 : UnlockBufHdr(buf);
7225 : :
7226 : : /* no IO in progress, we don't need to wait */
3837 7227 [ + + ]: 474 : if (!(buf_state & BM_IO_IN_PROGRESS))
7892 tgl@sss.pgh.pa.us 7228 : 237 : break;
7229 : :
7230 : : /*
7231 : : * The buffer has asynchronous IO in progress, wait for it to
7232 : : * complete.
7233 : : */
561 andres@anarazel.de 7234 [ + + ]: 237 : if (pgaio_wref_valid(&iow))
7235 : : {
7236 : 43 : pgaio_wref_wait(&iow);
7237 : :
7238 : : /*
7239 : : * The AIO subsystem internally uses condition variables and thus
7240 : : * might remove this backend from the BufferDesc's CV. While that
7241 : : * wouldn't cause a correctness issue (the first CV sleep just
7242 : : * immediately returns if not already registered), it seems worth
7243 : : * avoiding unnecessary loop iterations, given that we take care
7244 : : * to do so at the start of the function.
7245 : : */
7246 : 43 : ConditionVariablePrepareToSleep(cv);
7247 : 43 : continue;
7248 : : }
7249 : :
7250 : : /* wait on BufferDesc->cv, e.g. for concurrent synchronous IO */
2041 tmunro@postgresql.or 7251 : 194 : ConditionVariableSleep(cv, WAIT_EVENT_BUFFER_IO);
7252 : : }
7253 : 237 : ConditionVariableCancelSleep();
7892 tgl@sss.pgh.pa.us 7254 : 237 : }
7255 : :
7256 : : /*
7257 : : * StartSharedBufferIO: begin I/O on this buffer
7258 : : * (Assumptions)
7259 : : * The buffer is Pinned
7260 : : *
7261 : : * In several scenarios the buffer may already be undergoing I/O in this or
7262 : : * another backend. How to best handle that depends on the caller's
7263 : : * situation. It might be appropriate to wait synchronously (e.g., because the
7264 : : * buffer is about to be invalidated); wait asynchronously, using the buffer's
7265 : : * IO wait reference (e.g., because the caller is doing readahead and doesn't
7266 : : * need the buffer to be ready immediately); or to not wait at all (e.g.,
7267 : : * because the caller is trying to combine IO for this buffer with another
7268 : : * buffer).
7269 : : *
7270 : : * How and whether to wait is controlled by the wait and io_wref
7271 : : * parameters. In detail:
7272 : : *
7273 : : * - If the caller passes a non-NULL io_wref and the buffer has an I/O wait
7274 : : * reference, the *io_wref is set to the buffer's io_wref and
7275 : : * BUFFER_IO_IN_PROGRESS is returned. This is done regardless of the wait
7276 : : * parameter.
7277 : : *
7278 : : * - If the caller passes a NULL io_wref (i.e. the caller does not want to
7279 : : * asynchronously wait for the completion of the IO), wait = false and the
7280 : : * buffer is undergoing IO, BUFFER_IO_IN_PROGRESS is returned.
7281 : : *
7282 : : * - If wait = true and either the buffer does not have a wait reference,
7283 : : * or the caller passes io_wref = NULL, WaitIO() is used to wait for the IO
7284 : : * to complete. To avoid the potential of deadlocks and unnecessary delays,
7285 : : * all staged I/O is submitted before waiting.
7286 : : *
7287 : : * Input operations are only attempted on buffers that are not BM_VALID, and
7288 : : * output operations only on buffers that are BM_VALID and BM_DIRTY, so we can
7289 : : * always tell if the work is already done. If no I/O is necessary,
7290 : : * BUFFER_IO_ALREADY_DONE is returned.
7291 : : *
7292 : : * If we successfully marked the buffer as BM_IO_IN_PROGRESS,
7293 : : * BUFFER_IO_READY_FOR_IO is returned.
7294 : : */
7295 : : StartBufferIOResult
199 andres@anarazel.de 7296 : 2847643 : StartSharedBufferIO(BufferDesc *buf, bool forInput, bool wait, PgAioWaitRef *io_wref)
7297 : : {
7298 : : uint64 buf_state;
7299 : :
1069 heikki.linnakangas@i 7300 : 2847643 : ResourceOwnerEnlarge(CurrentResourceOwner);
7301 : :
7302 : : for (;;)
7303 : : {
3837 andres@anarazel.de 7304 : 2847876 : buf_state = LockBufHdr(buf);
7305 : :
7306 [ + + ]: 2847876 : if (!(buf_state & BM_IO_IN_PROGRESS))
7892 tgl@sss.pgh.pa.us 7307 : 2846185 : break;
7308 : :
7309 : : /* Join the existing IO */
199 andres@anarazel.de 7310 [ + + + + ]: 1691 : if (io_wref != NULL && pgaio_wref_valid(&buf->io_wref))
7311 : : {
7312 : 1450 : *io_wref = buf->io_wref;
7313 : 1450 : UnlockBufHdr(buf);
7314 : :
7315 : 1450 : return BUFFER_IO_IN_PROGRESS;
7316 : : }
7317 [ + + ]: 241 : else if (!wait)
7318 : : {
7319 : 8 : UnlockBufHdr(buf);
7320 : 8 : return BUFFER_IO_IN_PROGRESS;
7321 : : }
7322 : : else
7323 : : {
7324 : : /*
7325 : : * With wait = true, we always have to wait if the caller has
7326 : : * passed io_wref = NULL.
7327 : : *
7328 : : * Even with io_wref != NULL, we have to wait if the buffer's wait
7329 : : * ref is not valid but the IO is in progress, someone else
7330 : : * started IO but hasn't set the wait ref yet. We have no choice
7331 : : * but to wait until the IO completes.
7332 : : */
7333 : 233 : UnlockBufHdr(buf);
7334 : :
7335 : : /*
7336 : : * If this backend currently has staged IO, submit it before
7337 : : * waiting for in-progress IO, to avoid potential deadlocks and
7338 : : * unnecessary delays.
7339 : : */
7340 : 233 : pgaio_submit_staged();
7341 : :
7342 : 233 : WaitIO(buf);
7343 : : }
7344 : : }
7345 : :
7346 : : /* Once we get here, there is definitely no I/O active on this buffer */
7347 : :
7348 : : /* Check if someone else already did the I/O */
3837 7349 [ + + + + ]: 2846185 : if (forInput ? (buf_state & BM_VALID) : !(buf_state & BM_DIRTY))
7350 : : {
340 7351 : 505 : UnlockBufHdr(buf);
199 7352 : 505 : return BUFFER_IO_ALREADY_DONE;
7353 : : }
7354 : :
7355 : : /*
7356 : : * No IO in progress and not already done; we will start IO. It's possible
7357 : : * that the IO was in progress but we're not done, because the IO errored
7358 : : * out. We'll do the IO ourselves.
7359 : : */
340 7360 : 2845680 : UnlockBufHdrExt(buf, buf_state,
7361 : : BM_IO_IN_PROGRESS, 0,
7362 : : 0);
7363 : :
1286 7364 : 2845680 : ResourceOwnerRememberBufferIO(CurrentResourceOwner,
7365 : : BufferDescriptorGetBuffer(buf));
7366 : :
199 7367 : 2845680 : return BUFFER_IO_READY_FOR_IO;
7368 : : }
7369 : :
7370 : : /*
7371 : : * Wrapper around StartSharedBufferIO / StartLocalBufferIO. Only to be used
7372 : : * when the caller doesn't otherwise need to care about local vs shared. See
7373 : : * StartSharedBufferIO() for details.
7374 : : */
7375 : : StartBufferIOResult
7376 : 1550804 : StartBufferIO(Buffer buffer, bool forInput, bool wait, PgAioWaitRef *io_wref)
7377 : : {
7378 : : BufferDesc *buf_hdr;
7379 : :
7380 [ + + ]: 1550804 : if (BufferIsLocal(buffer))
7381 : : {
7382 : 11230 : buf_hdr = GetLocalBufferDescriptor(-buffer - 1);
7383 : :
7384 : 11230 : return StartLocalBufferIO(buf_hdr, forInput, wait, io_wref);
7385 : : }
7386 : : else
7387 : : {
7388 : 1539574 : buf_hdr = GetBufferDescriptor(buffer - 1);
7389 : :
7390 : 1539574 : return StartSharedBufferIO(buf_hdr, forInput, wait, io_wref);
7391 : : }
7392 : : }
7393 : :
7394 : : /*
7395 : : * TerminateBufferIO: release a buffer we were doing I/O on
7396 : : * (Assumptions)
7397 : : * My process is executing IO for the buffer
7398 : : * BM_IO_IN_PROGRESS bit is set for the buffer
7399 : : * The buffer is Pinned
7400 : : *
7401 : : * If clear_dirty is true, we clear the buffer's BM_DIRTY flag. This is
7402 : : * appropriate when terminating a successful write.
7403 : : *
7404 : : * set_flag_bits gets ORed into the buffer's flags. It must include
7405 : : * BM_IO_ERROR in a failure case. For successful completion it could
7406 : : * be 0, or BM_VALID if we just finished reading in the page.
7407 : : *
7408 : : * If forget_owner is true, we release the buffer I/O from the current
7409 : : * resource owner. (forget_owner=false is used when the resource owner itself
7410 : : * is being released)
7411 : : */
7412 : : void
270 7413 : 2674338 : TerminateBufferIO(BufferDesc *buf, bool clear_dirty, uint64 set_flag_bits,
7414 : : bool forget_owner, bool release_aio)
7415 : : {
7416 : : uint64 buf_state;
7417 : 2674338 : uint64 unset_flag_bits = 0;
340 7418 : 2674338 : int refcount_change = 0;
7419 : :
3837 7420 : 2674338 : buf_state = LockBufHdr(buf);
7421 : :
7422 [ - + ]: 2674338 : Assert(buf_state & BM_IO_IN_PROGRESS);
340 7423 : 2674338 : unset_flag_bits |= BM_IO_IN_PROGRESS;
7424 : :
7425 : : /* Clear earlier errors, if this IO failed, it'll be marked again */
7426 : 2674338 : unset_flag_bits |= BM_IO_ERROR;
7427 : :
215 7428 [ + + ]: 2674338 : if (clear_dirty)
340 7429 : 712970 : unset_flag_bits |= BM_DIRTY | BM_CHECKPOINT_NEEDED;
7430 : :
561 7431 [ + + ]: 2674338 : if (release_aio)
7432 : : {
7433 : : /* release ownership by the AIO subsystem */
7434 [ - + ]: 1366366 : Assert(BUF_STATE_GET_REFCOUNT(buf_state) > 0);
340 7435 : 1366366 : refcount_change = -1;
561 7436 : 1366366 : pgaio_wref_clear(&buf->io_wref);
7437 : : }
7438 : :
340 7439 : 2674338 : buf_state = UnlockBufHdrExt(buf, buf_state,
7440 : : set_flag_bits, unset_flag_bits,
7441 : : refcount_change);
7442 : :
1069 heikki.linnakangas@i 7443 [ + + ]: 2674338 : if (forget_owner)
7444 : 1307949 : ResourceOwnerForgetBufferIO(CurrentResourceOwner,
7445 : : BufferDescriptorGetBuffer(buf));
7446 : :
2041 tmunro@postgresql.or 7447 : 2674338 : ConditionVariableBroadcast(BufferDescriptorGetIOCV(buf));
7448 : :
7449 : : /*
7450 : : * Support LockBufferForCleanup()
7451 : : *
7452 : : * We may have just released the last pin other than the waiter's. In most
7453 : : * cases, this backend holds another pin on the buffer. But, if, for
7454 : : * example, this backend is completing an IO issued by another backend, it
7455 : : * may be time to wake the waiter.
7456 : : */
561 andres@anarazel.de 7457 [ + + - + ]: 2674338 : if (release_aio && (buf_state & BM_PIN_COUNT_WAITER))
561 andres@anarazel.de 7458 :UBC 0 : WakePinCountWaiter(buf);
9765 inoue@tpf.co.jp 7459 :CBC 2674338 : }
7460 : :
7461 : : /*
7462 : : * AbortBufferIO: Clean up active buffer I/O after an error.
7463 : : *
7464 : : * All LWLocks & content locks we might have held have been released, but we
7465 : : * haven't yet released buffer pins, so the buffer is still pinned.
7466 : : *
7467 : : * If I/O was in progress, we always set BM_IO_ERROR, even though it's
7468 : : * possible the error condition wasn't related to the I/O.
7469 : : *
7470 : : * Note: this does not remove the buffer I/O from the resource owner.
7471 : : * That's correct when we're releasing the whole resource owner, but
7472 : : * beware if you use this in other contexts.
7473 : : */
7474 : : static void
1278 pg@bowt.ie 7475 : 15 : AbortBufferIO(Buffer buffer)
7476 : : {
7477 : 15 : BufferDesc *buf_hdr = GetBufferDescriptor(buffer - 1);
7478 : : uint64 buf_state;
7479 : :
1286 andres@anarazel.de 7480 : 15 : buf_state = LockBufHdr(buf_hdr);
7481 [ - + ]: 15 : Assert(buf_state & (BM_IO_IN_PROGRESS | BM_TAG_VALID));
7482 : :
7483 [ + - ]: 15 : if (!(buf_state & BM_VALID))
7484 : : {
7485 [ - + ]: 15 : Assert(!(buf_state & BM_DIRTY));
340 7486 : 15 : UnlockBufHdr(buf_hdr);
7487 : : }
7488 : : else
7489 : : {
1284 andres@anarazel.de 7490 [ # # ]:UBC 0 : Assert(buf_state & BM_DIRTY);
340 7491 : 0 : UnlockBufHdr(buf_hdr);
7492 : :
7493 : : /* Issue notice if this is not the first failure... */
1286 7494 [ # # ]: 0 : if (buf_state & BM_IO_ERROR)
7495 : : {
7496 : : /* Buffer is pinned, so we can read tag without spinlock */
7497 [ # # ]: 0 : ereport(WARNING,
7498 : : (errcode(ERRCODE_IO_ERROR),
7499 : : errmsg("could not write block %u of %s",
7500 : : buf_hdr->tag.blockNum,
7501 : : relpathperm(BufTagGetRelFileLocator(&buf_hdr->tag),
7502 : : BufTagGetForkNum(&buf_hdr->tag)).str),
7503 : : errdetail("Multiple failures --- write error might be permanent.")));
7504 : : }
7505 : : }
7506 : :
561 andres@anarazel.de 7507 :CBC 15 : TerminateBufferIO(buf_hdr, false, BM_IO_ERROR, false, false);
9765 inoue@tpf.co.jp 7508 : 15 : }
7509 : :
7510 : : /*
7511 : : * Error context callback for errors occurring during shared buffer writes.
7512 : : */
7513 : : static void
5904 rhaas@postgresql.org 7514 : 43 : shared_buffer_write_error_callback(void *arg)
7515 : : {
3983 7516 : 43 : BufferDesc *bufHdr = (BufferDesc *) arg;
7517 : :
7518 : : /* Buffer is pinned, so we can read the tag without locking the spinlock */
8556 tgl@sss.pgh.pa.us 7519 [ + - ]: 43 : if (bufHdr != NULL)
412 peter@eisentraut.org 7520 : 86 : errcontext("writing block %u of relation \"%s\"",
7521 : : bufHdr->tag.blockNum,
594 andres@anarazel.de 7522 : 43 : relpathperm(BufTagGetRelFileLocator(&bufHdr->tag),
7523 : : BufTagGetForkNum(&bufHdr->tag)).str);
5904 rhaas@postgresql.org 7524 : 43 : }
7525 : :
7526 : : /*
7527 : : * Error context callback for errors occurring during local buffer writes.
7528 : : */
7529 : : static void
5904 rhaas@postgresql.org 7530 :UBC 0 : local_buffer_write_error_callback(void *arg)
7531 : : {
3983 7532 : 0 : BufferDesc *bufHdr = (BufferDesc *) arg;
7533 : :
5904 7534 [ # # ]: 0 : if (bufHdr != NULL)
412 peter@eisentraut.org 7535 : 0 : errcontext("writing block %u of relation \"%s\"",
7536 : : bufHdr->tag.blockNum,
594 andres@anarazel.de 7537 : 0 : relpathbackend(BufTagGetRelFileLocator(&bufHdr->tag),
7538 : : MyProcNumber,
7539 : : BufTagGetForkNum(&bufHdr->tag)).str);
8556 tgl@sss.pgh.pa.us 7540 : 0 : }
7541 : :
7542 : : /*
7543 : : * RelFileLocator qsort/bsearch comparator; see RelFileLocatorEquals.
7544 : : */
7545 : : static int
1559 rhaas@postgresql.org 7546 :CBC 13306953 : rlocator_comparator(const void *p1, const void *p2)
7547 : : {
7548 : 13306953 : RelFileLocator n1 = *(const RelFileLocator *) p1;
7549 : 13306953 : RelFileLocator n2 = *(const RelFileLocator *) p2;
7550 : :
7551 [ + + ]: 13306953 : if (n1.relNumber < n2.relNumber)
5016 alvherre@alvh.no-ip. 7552 : 13261855 : return -1;
1559 rhaas@postgresql.org 7553 [ + + ]: 45098 : else if (n1.relNumber > n2.relNumber)
5016 alvherre@alvh.no-ip. 7554 : 43356 : return 1;
7555 : :
1559 rhaas@postgresql.org 7556 [ - + ]: 1742 : if (n1.dbOid < n2.dbOid)
5016 alvherre@alvh.no-ip. 7557 :UBC 0 : return -1;
1559 rhaas@postgresql.org 7558 [ - + ]:CBC 1742 : else if (n1.dbOid > n2.dbOid)
5016 alvherre@alvh.no-ip. 7559 :UBC 0 : return 1;
7560 : :
1559 rhaas@postgresql.org 7561 [ - + ]:CBC 1742 : if (n1.spcOid < n2.spcOid)
5016 alvherre@alvh.no-ip. 7562 :UBC 0 : return -1;
1559 rhaas@postgresql.org 7563 [ - + ]:CBC 1742 : else if (n1.spcOid > n2.spcOid)
5016 alvherre@alvh.no-ip. 7564 :UBC 0 : return 1;
7565 : : else
5016 alvherre@alvh.no-ip. 7566 :CBC 1742 : return 0;
7567 : : }
7568 : :
7569 : : /*
7570 : : * Lock buffer header - set BM_LOCKED in buffer state.
7571 : : */
7572 : : uint64
3837 andres@anarazel.de 7573 : 28278256 : LockBufHdr(BufferDesc *desc)
7574 : : {
7575 : : uint64 old_buf_state;
7576 : :
1286 7577 [ - + ]: 28278256 : Assert(!BufferIsLocal(BufferDescriptorGetBuffer(desc)));
7578 : :
7579 : : while (true)
7580 : : {
7581 : : /*
7582 : : * Always try once to acquire the lock directly, without setting up
7583 : : * the spin-delay infrastructure. The work necessary for that shows up
7584 : : * in profiles and is rarely necessary.
7585 : : */
270 7586 : 28279032 : old_buf_state = pg_atomic_fetch_or_u64(&desc->state, BM_LOCKED);
297 7587 [ + + ]: 28279032 : if (likely(!(old_buf_state & BM_LOCKED)))
7588 : 28278256 : break; /* got lock */
7589 : :
7590 : : /* and then spin without atomic operations until lock is released */
7591 : : {
7592 : : SpinDelayStatus delayStatus;
7593 : :
7594 : 776 : init_local_spin_delay(&delayStatus);
7595 : :
7596 [ + + ]: 8341 : while (old_buf_state & BM_LOCKED)
7597 : : {
7598 : 7565 : perform_spin_delay(&delayStatus);
270 7599 : 7565 : old_buf_state = pg_atomic_read_u64(&desc->state);
7600 : : }
297 7601 : 776 : finish_spin_delay(&delayStatus);
7602 : : }
7603 : :
7604 : : /*
7605 : : * Retry. The lock might obviously already be re-acquired by the time
7606 : : * we're attempting to get it again.
7607 : : */
7608 : : }
7609 : :
3837 7610 : 28278256 : return old_buf_state | BM_LOCKED;
7611 : : }
7612 : :
7613 : : /*
7614 : : * Wait until the BM_LOCKED flag isn't set anymore and return the buffer's
7615 : : * state at that point.
7616 : : *
7617 : : * Obviously the buffer could be locked by the time the value is returned, so
7618 : : * this is primarily useful in CAS style loops.
7619 : : */
7620 : : pg_noinline uint64
7621 : 706 : WaitBufHdrUnlocked(BufferDesc *buf)
7622 : : {
7623 : : SpinDelayStatus delayStatus;
7624 : : uint64 buf_state;
7625 : :
3833 7626 : 706 : init_local_spin_delay(&delayStatus);
7627 : :
270 7628 : 706 : buf_state = pg_atomic_read_u64(&buf->state);
7629 : :
3837 7630 [ + + ]: 17448 : while (buf_state & BM_LOCKED)
7631 : : {
7632 : 16742 : perform_spin_delay(&delayStatus);
270 7633 : 16742 : buf_state = pg_atomic_read_u64(&buf->state);
7634 : : }
7635 : :
3837 7636 : 706 : finish_spin_delay(&delayStatus);
7637 : :
7638 : 706 : return buf_state;
7639 : : }
7640 : :
7641 : : /*
7642 : : * BufferTag comparator.
7643 : : */
7644 : : static inline int
2040 tmunro@postgresql.or 7645 :UBC 0 : buffertag_comparator(const BufferTag *ba, const BufferTag *bb)
7646 : : {
7647 : : int ret;
7648 : : RelFileLocator rlocatora;
7649 : : RelFileLocator rlocatorb;
7650 : :
1510 rhaas@postgresql.org 7651 : 0 : rlocatora = BufTagGetRelFileLocator(ba);
7652 : 0 : rlocatorb = BufTagGetRelFileLocator(bb);
7653 : :
7654 : 0 : ret = rlocator_comparator(&rlocatora, &rlocatorb);
7655 : :
3888 andres@anarazel.de 7656 [ # # ]: 0 : if (ret != 0)
7657 : 0 : return ret;
7658 : :
1510 rhaas@postgresql.org 7659 [ # # ]: 0 : if (BufTagGetForkNum(ba) < BufTagGetForkNum(bb))
3888 andres@anarazel.de 7660 : 0 : return -1;
1510 rhaas@postgresql.org 7661 [ # # ]: 0 : if (BufTagGetForkNum(ba) > BufTagGetForkNum(bb))
3888 andres@anarazel.de 7662 : 0 : return 1;
7663 : :
7664 [ # # ]: 0 : if (ba->blockNum < bb->blockNum)
7665 : 0 : return -1;
7666 [ # # ]: 0 : if (ba->blockNum > bb->blockNum)
7667 : 0 : return 1;
7668 : :
7669 : 0 : return 0;
7670 : : }
7671 : :
7672 : : /*
7673 : : * Comparator determining the writeout order in a checkpoint.
7674 : : *
7675 : : * It is important that tablespaces are compared first, the logic balancing
7676 : : * writes between tablespaces relies on it.
7677 : : */
7678 : : static inline int
2040 tmunro@postgresql.or 7679 :CBC 3541047 : ckpt_buforder_comparator(const CkptSortItem *a, const CkptSortItem *b)
7680 : : {
7681 : : /* compare tablespace */
3888 andres@anarazel.de 7682 [ + + ]: 3541047 : if (a->tsId < b->tsId)
7683 : 9441 : return -1;
7684 [ + + ]: 3531606 : else if (a->tsId > b->tsId)
7685 : 28991 : return 1;
7686 : : /* compare relation */
1559 rhaas@postgresql.org 7687 [ + + ]: 3502615 : if (a->relNumber < b->relNumber)
3888 andres@anarazel.de 7688 : 992846 : return -1;
1559 rhaas@postgresql.org 7689 [ + + ]: 2509769 : else if (a->relNumber > b->relNumber)
3888 andres@anarazel.de 7690 : 948240 : return 1;
7691 : : /* compare fork */
7692 [ + + ]: 1561529 : else if (a->forkNum < b->forkNum)
7693 : 69678 : return -1;
7694 [ + + ]: 1491851 : else if (a->forkNum > b->forkNum)
7695 : 74222 : return 1;
7696 : : /* compare block number */
7697 [ + + ]: 1417629 : else if (a->blockNum < b->blockNum)
7698 : 701472 : return -1;
3197 tgl@sss.pgh.pa.us 7699 [ + + ]: 716157 : else if (a->blockNum > b->blockNum)
3888 andres@anarazel.de 7700 : 663566 : return 1;
7701 : : /* equal page IDs are unlikely, but not impossible */
3197 tgl@sss.pgh.pa.us 7702 : 52591 : return 0;
7703 : : }
7704 : :
7705 : : /*
7706 : : * Comparator for a Min-Heap over the per-tablespace checkpoint completion
7707 : : * progress.
7708 : : */
7709 : : static int
3888 andres@anarazel.de 7710 : 288593 : ts_ckpt_progress_comparator(Datum a, Datum b, void *arg)
7711 : : {
430 peter@eisentraut.org 7712 : 288593 : CkptTsStatus *sa = (CkptTsStatus *) DatumGetPointer(a);
7713 : 288593 : CkptTsStatus *sb = (CkptTsStatus *) DatumGetPointer(b);
7714 : :
7715 : : /* we want a min-heap, so return 1 for the a < b */
3888 andres@anarazel.de 7716 [ + + ]: 288593 : if (sa->progress < sb->progress)
7717 : 261905 : return 1;
7718 [ + + ]: 26688 : else if (sa->progress == sb->progress)
7719 : 826 : return 0;
7720 : : else
7721 : 25862 : return -1;
7722 : : }
7723 : :
7724 : : /*
7725 : : * Initialize a writeback context, discarding potential previous state.
7726 : : *
7727 : : * *max_pending is a pointer instead of an immediate value, so the coalesce
7728 : : * limits can easily changed by the GUC mechanism, and so calling code does
7729 : : * not have to check the current configuration. A value of 0 means that no
7730 : : * writeback control will be performed.
7731 : : */
7732 : : void
7733 : 25843 : WritebackContextInit(WritebackContext *context, int *max_pending)
7734 : : {
7735 [ - + ]: 25843 : Assert(*max_pending <= WRITEBACK_MAX_PENDING_FLUSHES);
7736 : :
7737 : 25843 : context->max_pending = max_pending;
7738 : 25843 : context->nr_pending = 0;
7739 : 25843 : }
7740 : :
7741 : : /*
7742 : : * Add buffer to list of pending writeback requests.
7743 : : */
7744 : : void
1244 7745 : 709324 : ScheduleBufferTagForWriteback(WritebackContext *wb_context, IOContext io_context,
7746 : : BufferTag *tag)
7747 : : {
7748 : : PendingWriteback *pending;
7749 : :
7750 : : /*
7751 : : * As pg_flush_data() doesn't do anything with fsync disabled, there's no
7752 : : * point in tracking in that case.
7753 : : */
734 7754 [ + + ]: 709324 : if (io_direct_flags & IO_DIRECT_DATA ||
7755 [ + + ]: 708807 : !enableFsync)
1283 tmunro@postgresql.or 7756 : 709323 : return;
7757 : :
7758 : : /*
7759 : : * Add buffer to the pending writeback array, unless writeback control is
7760 : : * disabled.
7761 : : */
1244 andres@anarazel.de 7762 [ - + ]: 1 : if (*wb_context->max_pending > 0)
7763 : : {
1244 andres@anarazel.de 7764 [ # # ]:UBC 0 : Assert(*wb_context->max_pending <= WRITEBACK_MAX_PENDING_FLUSHES);
7765 : :
7766 : 0 : pending = &wb_context->pending_writebacks[wb_context->nr_pending++];
7767 : :
3888 7768 : 0 : pending->tag = *tag;
7769 : : }
7770 : :
7771 : : /*
7772 : : * Perform pending flushes if the writeback limit is exceeded. This
7773 : : * includes the case where previously an item has been added, but control
7774 : : * is now disabled.
7775 : : */
1244 andres@anarazel.de 7776 [ + - ]:CBC 1 : if (wb_context->nr_pending >= *wb_context->max_pending)
7777 : 1 : IssuePendingWritebacks(wb_context, io_context);
7778 : : }
7779 : :
7780 : : #define ST_SORT sort_pending_writebacks
7781 : : #define ST_ELEMENT_TYPE PendingWriteback
7782 : : #define ST_COMPARE(a, b) buffertag_comparator(&a->tag, &b->tag)
7783 : : #define ST_SCOPE static
7784 : : #define ST_DEFINE
7785 : : #include "lib/sort_template.h"
7786 : :
7787 : : /*
7788 : : * Issue all pending writeback requests, previously scheduled with
7789 : : * ScheduleBufferTagForWriteback, to the OS.
7790 : : *
7791 : : * Because this is only used to improve the OSs IO scheduling we try to never
7792 : : * error out - it's just a hint.
7793 : : */
7794 : : void
7795 : 1260 : IssuePendingWritebacks(WritebackContext *wb_context, IOContext io_context)
7796 : : {
7797 : : instr_time io_start;
7798 : : int i;
7799 : :
7800 [ + - ]: 1260 : if (wb_context->nr_pending == 0)
3888 7801 : 1260 : return;
7802 : :
7803 : : /*
7804 : : * Executing the writes in-order can make them a lot faster, and allows to
7805 : : * merge writeback requests to consecutive blocks into larger writebacks.
7806 : : */
1244 andres@anarazel.de 7807 :UBC 0 : sort_pending_writebacks(wb_context->pending_writebacks,
7808 : 0 : wb_context->nr_pending);
7809 : :
593 michael@paquier.xyz 7810 : 0 : io_start = pgstat_prepare_io_time(track_io_timing);
7811 : :
7812 : : /*
7813 : : * Coalesce neighbouring writes, but nothing else. For that we iterate
7814 : : * through the, now sorted, array of pending flushes, and look forward to
7815 : : * find all neighbouring (or identical) writes.
7816 : : */
1244 andres@anarazel.de 7817 [ # # ]: 0 : for (i = 0; i < wb_context->nr_pending; i++)
7818 : : {
7819 : : PendingWriteback *cur;
7820 : : PendingWriteback *next;
7821 : : SMgrRelation reln;
7822 : : int ahead;
7823 : : BufferTag tag;
7824 : : RelFileLocator currlocator;
3888 7825 : 0 : Size nblocks = 1;
7826 : :
1244 7827 : 0 : cur = &wb_context->pending_writebacks[i];
3888 7828 : 0 : tag = cur->tag;
1510 rhaas@postgresql.org 7829 : 0 : currlocator = BufTagGetRelFileLocator(&tag);
7830 : :
7831 : : /*
7832 : : * Peek ahead, into following writeback requests, to see if they can
7833 : : * be combined with the current one.
7834 : : */
1244 andres@anarazel.de 7835 [ # # ]: 0 : for (ahead = 0; i + ahead + 1 < wb_context->nr_pending; ahead++)
7836 : : {
7837 : :
7838 : 0 : next = &wb_context->pending_writebacks[i + ahead + 1];
7839 : :
7840 : : /* different file, stop */
1510 rhaas@postgresql.org 7841 [ # # # # : 0 : if (!RelFileLocatorEquals(currlocator,
# # ]
7842 [ # # ]: 0 : BufTagGetRelFileLocator(&next->tag)) ||
7843 : 0 : BufTagGetForkNum(&cur->tag) != BufTagGetForkNum(&next->tag))
7844 : : break;
7845 : :
7846 : : /* ok, block queued twice, skip */
3888 andres@anarazel.de 7847 [ # # ]: 0 : if (cur->tag.blockNum == next->tag.blockNum)
7848 : 0 : continue;
7849 : :
7850 : : /* only merge consecutive writes */
7851 [ # # ]: 0 : if (cur->tag.blockNum + 1 != next->tag.blockNum)
7852 : 0 : break;
7853 : :
7854 : 0 : nblocks++;
7855 : 0 : cur = next;
7856 : : }
7857 : :
7858 : 0 : i += ahead;
7859 : :
7860 : : /* and finally tell the kernel to write the data to storage */
953 heikki.linnakangas@i 7861 : 0 : reln = smgropen(currlocator, INVALID_PROC_NUMBER);
1510 rhaas@postgresql.org 7862 : 0 : smgrwriteback(reln, BufTagGetForkNum(&tag), tag.blockNum, nblocks);
7863 : : }
7864 : :
7865 : : /*
7866 : : * Assume that writeback requests are only issued for buffers containing
7867 : : * blocks of permanent relations.
7868 : : */
1244 andres@anarazel.de 7869 : 0 : pgstat_count_io_op_time(IOOBJECT_RELATION, io_context,
636 michael@paquier.xyz 7870 : 0 : IOOP_WRITEBACK, io_start, wb_context->nr_pending, 0);
7871 : :
1244 andres@anarazel.de 7872 : 0 : wb_context->nr_pending = 0;
7873 : : }
7874 : :
7875 : : /* ResourceOwner callbacks */
7876 : :
7877 : : static void
1069 heikki.linnakangas@i 7878 :CBC 15 : ResOwnerReleaseBufferIO(Datum res)
7879 : : {
7880 : 15 : Buffer buffer = DatumGetInt32(res);
7881 : :
7882 : 15 : AbortBufferIO(buffer);
7883 : 15 : }
7884 : :
7885 : : static char *
1069 heikki.linnakangas@i 7886 :UBC 0 : ResOwnerPrintBufferIO(Datum res)
7887 : : {
7888 : 0 : Buffer buffer = DatumGetInt32(res);
7889 : :
7890 : 0 : return psprintf("lost track of buffer IO on buffer %d", buffer);
7891 : : }
7892 : :
7893 : : /*
7894 : : * Release buffer as part of resource owner cleanup. This will only be called
7895 : : * if the buffer is pinned. If this backend held the content lock at the time
7896 : : * of the error we also need to release that (note that it is not possible to
7897 : : * hold a content lock without a pin).
7898 : : */
7899 : : static void
270 andres@anarazel.de 7900 :CBC 11764 : ResOwnerReleaseBuffer(Datum res)
7901 : : {
1069 heikki.linnakangas@i 7902 : 11764 : Buffer buffer = DatumGetInt32(res);
7903 : :
7904 : : /* Like ReleaseBuffer, but don't call ResourceOwnerForgetBuffer */
7905 [ - + ]: 11764 : if (!BufferIsValid(buffer))
1069 heikki.linnakangas@i 7906 [ # # ]:UBC 0 : elog(ERROR, "bad buffer ID: %d", buffer);
7907 : :
1069 heikki.linnakangas@i 7908 [ + + ]:CBC 11764 : if (BufferIsLocal(buffer))
7909 : 5087 : UnpinLocalBufferNoOwner(buffer);
7910 : : else
7911 : : {
7912 : : PrivateRefCountEntry *ref;
7913 : :
270 andres@anarazel.de 7914 : 6677 : ref = GetPrivateRefCountEntry(buffer, false);
7915 : :
7916 : : /* not having a private refcount would imply resowner corruption */
7917 [ - + ]: 6677 : Assert(ref != NULL);
7918 : :
7919 : : /*
7920 : : * If the buffer was locked at the time of the resowner release,
7921 : : * release the lock now. This should only happen after errors.
7922 : : */
7923 [ + + ]: 6677 : if (ref->data.lockmode != BUFFER_LOCK_UNLOCK)
7924 : : {
7925 : 124 : BufferDesc *buf = GetBufferDescriptor(buffer - 1);
7926 : :
7927 : 124 : HOLD_INTERRUPTS(); /* match the upcoming RESUME_INTERRUPTS */
7928 : 124 : BufferLockUnlock(buffer, buf);
7929 : : }
7930 : :
1069 heikki.linnakangas@i 7931 : 6677 : UnpinBufferNoOwner(GetBufferDescriptor(buffer - 1));
7932 : : }
7933 : 11764 : }
7934 : :
7935 : : static char *
270 andres@anarazel.de 7936 :UBC 0 : ResOwnerPrintBuffer(Datum res)
7937 : : {
1069 heikki.linnakangas@i 7938 : 0 : return DebugPrintBufferRefcount(DatumGetInt32(res));
7939 : : }
7940 : :
7941 : : /*
7942 : : * Helper function to evict unpinned buffer whose buffer header lock is
7943 : : * already acquired.
7944 : : */
7945 : : static bool
552 andres@anarazel.de 7946 :CBC 2476 : EvictUnpinnedBufferInternal(BufferDesc *desc, bool *buffer_flushed)
7947 : : {
7948 : : uint64 buf_state;
7949 : : bool result;
7950 : :
7951 : 2476 : *buffer_flushed = false;
7952 : :
270 7953 : 2476 : buf_state = pg_atomic_read_u64(&(desc->state));
552 7954 [ - + ]: 2476 : Assert(buf_state & BM_LOCKED);
7955 : :
918 tmunro@postgresql.or 7956 [ - + ]: 2476 : if ((buf_state & BM_VALID) == 0)
7957 : : {
340 andres@anarazel.de 7958 :UBC 0 : UnlockBufHdr(desc);
918 tmunro@postgresql.or 7959 : 0 : return false;
7960 : : }
7961 : :
7962 : : /* Check that it's not pinned already. */
918 tmunro@postgresql.or 7963 [ - + ]:CBC 2476 : if (BUF_STATE_GET_REFCOUNT(buf_state) > 0)
7964 : : {
340 andres@anarazel.de 7965 :UBC 0 : UnlockBufHdr(desc);
918 tmunro@postgresql.or 7966 : 0 : return false;
7967 : : }
7968 : :
918 tmunro@postgresql.or 7969 :CBC 2476 : PinBuffer_Locked(desc); /* releases spinlock */
7970 : :
7971 : : /* If it was dirty, try to clean it once. */
7972 [ + + ]: 2476 : if (buf_state & BM_DIRTY)
7973 : : {
369 andres@anarazel.de 7974 : 1051 : FlushUnlockedBuffer(desc, NULL, IOOBJECT_RELATION, IOCONTEXT_NORMAL);
552 7975 : 1051 : *buffer_flushed = true;
7976 : : }
7977 : :
7978 : : /* This will return false if it becomes dirty or someone else pins it. */
918 tmunro@postgresql.or 7979 : 2476 : result = InvalidateVictimBuffer(desc);
7980 : :
7981 : 2476 : UnpinBuffer(desc);
7982 : :
7983 : 2476 : return result;
7984 : : }
7985 : :
7986 : : /*
7987 : : * Try to evict the current block in a shared buffer.
7988 : : *
7989 : : * This function is intended for testing/development use only!
7990 : : *
7991 : : * To succeed, the buffer must not be pinned on entry, so if the caller had a
7992 : : * particular block in mind, it might already have been replaced by some other
7993 : : * block by the time this function runs. It's also unpinned on return, so the
7994 : : * buffer might be occupied again by the time control is returned, potentially
7995 : : * even by the same block. This inherent raciness without other interlocking
7996 : : * makes the function unsuitable for non-testing usage.
7997 : : *
7998 : : * *buffer_flushed is set to true if the buffer was dirty and has been
7999 : : * flushed, false otherwise. However, *buffer_flushed=true does not
8000 : : * necessarily mean that we flushed the buffer, it could have been flushed by
8001 : : * someone else.
8002 : : *
8003 : : * Returns true if the buffer was valid and it has now been made invalid.
8004 : : * Returns false if it wasn't valid, if it couldn't be evicted due to a pin,
8005 : : * or if the buffer becomes dirty again while we're trying to write it out.
8006 : : */
8007 : : bool
552 andres@anarazel.de 8008 : 137 : EvictUnpinnedBuffer(Buffer buf, bool *buffer_flushed)
8009 : : {
8010 : : BufferDesc *desc;
8011 : :
8012 [ + - - + ]: 137 : Assert(BufferIsValid(buf) && !BufferIsLocal(buf));
8013 : :
8014 : : /* Make sure we can pin the buffer. */
8015 : 137 : ResourceOwnerEnlarge(CurrentResourceOwner);
8016 : 137 : ReservePrivateRefCountEntry();
8017 : :
8018 : 137 : desc = GetBufferDescriptor(buf - 1);
8019 : 137 : LockBufHdr(desc);
8020 : :
8021 : 137 : return EvictUnpinnedBufferInternal(desc, buffer_flushed);
8022 : : }
8023 : :
8024 : : /*
8025 : : * Try to evict all the shared buffers.
8026 : : *
8027 : : * This function is intended for testing/development use only! See
8028 : : * EvictUnpinnedBuffer().
8029 : : *
8030 : : * The buffers_* parameters are mandatory and indicate the total count of
8031 : : * buffers that:
8032 : : * - buffers_evicted - were evicted
8033 : : * - buffers_flushed - were flushed
8034 : : * - buffers_skipped - could not be evicted
8035 : : */
8036 : : void
8037 : 1 : EvictAllUnpinnedBuffers(int32 *buffers_evicted, int32 *buffers_flushed,
8038 : : int32 *buffers_skipped)
8039 : : {
8040 : 1 : *buffers_evicted = 0;
8041 : 1 : *buffers_skipped = 0;
8042 : 1 : *buffers_flushed = 0;
8043 : :
8044 [ + + ]: 16385 : for (int buf = 1; buf <= NBuffers; buf++)
8045 : : {
8046 : 16384 : BufferDesc *desc = GetBufferDescriptor(buf - 1);
8047 : : uint64 buf_state;
8048 : : bool buffer_flushed;
8049 : :
342 msawada@postgresql.o 8050 [ - + ]: 16384 : CHECK_FOR_INTERRUPTS();
8051 : :
270 andres@anarazel.de 8052 : 16384 : buf_state = pg_atomic_read_u64(&desc->state);
552 8053 [ + + ]: 16384 : if (!(buf_state & BM_VALID))
8054 : 14393 : continue;
8055 : :
8056 : 1991 : ResourceOwnerEnlarge(CurrentResourceOwner);
8057 : 1991 : ReservePrivateRefCountEntry();
8058 : :
8059 : 1991 : LockBufHdr(desc);
8060 : :
8061 [ + - ]: 1991 : if (EvictUnpinnedBufferInternal(desc, &buffer_flushed))
8062 : 1991 : (*buffers_evicted)++;
8063 : : else
552 andres@anarazel.de 8064 :UBC 0 : (*buffers_skipped)++;
8065 : :
552 andres@anarazel.de 8066 [ + + ]:CBC 1991 : if (buffer_flushed)
8067 : 954 : (*buffers_flushed)++;
8068 : : }
8069 : 1 : }
8070 : :
8071 : : /*
8072 : : * Try to evict all the shared buffers containing provided relation's pages.
8073 : : *
8074 : : * This function is intended for testing/development use only! See
8075 : : * EvictUnpinnedBuffer().
8076 : : *
8077 : : * The caller must hold at least AccessShareLock on the relation to prevent
8078 : : * the relation from being dropped.
8079 : : *
8080 : : * The buffers_* parameters are mandatory and indicate the total count of
8081 : : * buffers that:
8082 : : * - buffers_evicted - were evicted
8083 : : * - buffers_flushed - were flushed
8084 : : * - buffers_skipped - could not be evicted
8085 : : */
8086 : : void
8087 : 29 : EvictRelUnpinnedBuffers(Relation rel, int32 *buffers_evicted,
8088 : : int32 *buffers_flushed, int32 *buffers_skipped)
8089 : : {
8090 [ - + ]: 29 : Assert(!RelationUsesLocalBuffers(rel));
8091 : :
8092 : 29 : *buffers_skipped = 0;
8093 : 29 : *buffers_evicted = 0;
8094 : 29 : *buffers_flushed = 0;
8095 : :
8096 [ + + ]: 475165 : for (int buf = 1; buf <= NBuffers; buf++)
8097 : : {
8098 : 475136 : BufferDesc *desc = GetBufferDescriptor(buf - 1);
270 8099 : 475136 : uint64 buf_state = pg_atomic_read_u64(&(desc->state));
8100 : : bool buffer_flushed;
8101 : :
342 msawada@postgresql.o 8102 [ - + ]: 475136 : CHECK_FOR_INTERRUPTS();
8103 : :
8104 : : /* An unlocked precheck should be safe and saves some cycles. */
552 andres@anarazel.de 8105 [ + + ]: 475136 : if ((buf_state & BM_VALID) == 0 ||
8106 [ + + ]: 61159 : !BufTagMatchesRelFileLocator(&desc->tag, &rel->rd_locator))
8107 : 474788 : continue;
8108 : :
8109 : : /* Make sure we can pin the buffer. */
8110 : 348 : ResourceOwnerEnlarge(CurrentResourceOwner);
8111 : 348 : ReservePrivateRefCountEntry();
8112 : :
8113 : 348 : buf_state = LockBufHdr(desc);
8114 : :
8115 : : /* recheck, could have changed without the lock */
8116 [ + - ]: 348 : if ((buf_state & BM_VALID) == 0 ||
8117 [ - + ]: 348 : !BufTagMatchesRelFileLocator(&desc->tag, &rel->rd_locator))
8118 : : {
340 andres@anarazel.de 8119 :UBC 0 : UnlockBufHdr(desc);
552 8120 : 0 : continue;
8121 : : }
8122 : :
552 andres@anarazel.de 8123 [ + - ]:CBC 348 : if (EvictUnpinnedBufferInternal(desc, &buffer_flushed))
8124 : 348 : (*buffers_evicted)++;
8125 : : else
552 andres@anarazel.de 8126 :UBC 0 : (*buffers_skipped)++;
8127 : :
552 andres@anarazel.de 8128 [ + + ]:CBC 348 : if (buffer_flushed)
8129 : 78 : (*buffers_flushed)++;
8130 : : }
8131 : 29 : }
8132 : :
8133 : : /*
8134 : : * Helper function to mark unpinned buffer dirty whose buffer header lock is
8135 : : * already acquired.
8136 : : */
8137 : : static bool
318 michael@paquier.xyz 8138 : 36 : MarkDirtyUnpinnedBufferInternal(Buffer buf, BufferDesc *desc,
8139 : : bool *buffer_already_dirty)
8140 : : {
8141 : : uint64 buf_state;
8142 : 36 : bool result = false;
8143 : :
8144 : 36 : *buffer_already_dirty = false;
8145 : :
270 andres@anarazel.de 8146 : 36 : buf_state = pg_atomic_read_u64(&(desc->state));
318 michael@paquier.xyz 8147 [ - + ]: 36 : Assert(buf_state & BM_LOCKED);
8148 : :
8149 [ + + ]: 36 : if ((buf_state & BM_VALID) == 0)
8150 : : {
8151 : 1 : UnlockBufHdr(desc);
8152 : 1 : return false;
8153 : : }
8154 : :
8155 : : /* Check that it's not pinned already. */
8156 [ - + ]: 35 : if (BUF_STATE_GET_REFCOUNT(buf_state) > 0)
8157 : : {
318 michael@paquier.xyz 8158 :UBC 0 : UnlockBufHdr(desc);
8159 : 0 : return false;
8160 : : }
8161 : :
8162 : : /* Pin the buffer and then release the buffer spinlock */
318 michael@paquier.xyz 8163 :CBC 35 : PinBuffer_Locked(desc);
8164 : :
8165 : : /* If it was not already dirty, mark it as dirty. */
8166 [ + + ]: 35 : if (!(buf_state & BM_DIRTY))
8167 : : {
270 andres@anarazel.de 8168 : 16 : BufferLockAcquire(buf, desc, BUFFER_LOCK_EXCLUSIVE);
318 michael@paquier.xyz 8169 : 16 : MarkBufferDirty(buf);
8170 : 16 : result = true;
270 andres@anarazel.de 8171 : 16 : BufferLockUnlock(buf, desc);
8172 : : }
8173 : : else
318 michael@paquier.xyz 8174 : 19 : *buffer_already_dirty = true;
8175 : :
8176 : 35 : UnpinBuffer(desc);
8177 : :
8178 : 35 : return result;
8179 : : }
8180 : :
8181 : : /*
8182 : : * Try to mark the provided shared buffer as dirty.
8183 : : *
8184 : : * This function is intended for testing/development use only!
8185 : : *
8186 : : * Same as EvictUnpinnedBuffer() but with MarkBufferDirty() call inside.
8187 : : *
8188 : : * The buffer_already_dirty parameter is mandatory and indicate if the buffer
8189 : : * could not be dirtied because it is already dirty.
8190 : : *
8191 : : * Returns true if the buffer has successfully been marked as dirty.
8192 : : */
8193 : : bool
8194 : 1 : MarkDirtyUnpinnedBuffer(Buffer buf, bool *buffer_already_dirty)
8195 : : {
8196 : : BufferDesc *desc;
8197 : 1 : bool buffer_dirtied = false;
8198 : :
8199 [ - + ]: 1 : Assert(!BufferIsLocal(buf));
8200 : :
8201 : : /* Make sure we can pin the buffer. */
8202 : 1 : ResourceOwnerEnlarge(CurrentResourceOwner);
8203 : 1 : ReservePrivateRefCountEntry();
8204 : :
8205 : 1 : desc = GetBufferDescriptor(buf - 1);
8206 : 1 : LockBufHdr(desc);
8207 : :
8208 : 1 : buffer_dirtied = MarkDirtyUnpinnedBufferInternal(buf, desc, buffer_already_dirty);
8209 : : /* Both can not be true at the same time */
8210 [ - + - - ]: 1 : Assert(!(buffer_dirtied && *buffer_already_dirty));
8211 : :
8212 : 1 : return buffer_dirtied;
8213 : : }
8214 : :
8215 : : /*
8216 : : * Try to mark all the shared buffers containing provided relation's pages as
8217 : : * dirty.
8218 : : *
8219 : : * This function is intended for testing/development use only! See
8220 : : * MarkDirtyUnpinnedBuffer().
8221 : : *
8222 : : * The buffers_* parameters are mandatory and indicate the total count of
8223 : : * buffers that:
8224 : : * - buffers_dirtied - were dirtied
8225 : : * - buffers_already_dirty - were already dirty
8226 : : * - buffers_skipped - could not be dirtied because of a reason different
8227 : : * than a buffer being already dirty.
8228 : : */
8229 : : void
8230 : 1 : MarkDirtyRelUnpinnedBuffers(Relation rel,
8231 : : int32 *buffers_dirtied,
8232 : : int32 *buffers_already_dirty,
8233 : : int32 *buffers_skipped)
8234 : : {
8235 [ - + ]: 1 : Assert(!RelationUsesLocalBuffers(rel));
8236 : :
8237 : 1 : *buffers_dirtied = 0;
8238 : 1 : *buffers_already_dirty = 0;
8239 : 1 : *buffers_skipped = 0;
8240 : :
8241 [ + + ]: 16385 : for (int buf = 1; buf <= NBuffers; buf++)
8242 : : {
8243 : 16384 : BufferDesc *desc = GetBufferDescriptor(buf - 1);
270 andres@anarazel.de 8244 : 16384 : uint64 buf_state = pg_atomic_read_u64(&(desc->state));
8245 : : bool buffer_already_dirty;
8246 : :
318 michael@paquier.xyz 8247 [ - + ]: 16384 : CHECK_FOR_INTERRUPTS();
8248 : :
8249 : : /* An unlocked precheck should be safe and saves some cycles. */
8250 [ + + ]: 16384 : if ((buf_state & BM_VALID) == 0 ||
8251 [ + - ]: 27 : !BufTagMatchesRelFileLocator(&desc->tag, &rel->rd_locator))
8252 : 16384 : continue;
8253 : :
8254 : : /* Make sure we can pin the buffer. */
318 michael@paquier.xyz 8255 :UBC 0 : ResourceOwnerEnlarge(CurrentResourceOwner);
8256 : 0 : ReservePrivateRefCountEntry();
8257 : :
8258 : 0 : buf_state = LockBufHdr(desc);
8259 : :
8260 : : /* recheck, could have changed without the lock */
8261 [ # # ]: 0 : if ((buf_state & BM_VALID) == 0 ||
8262 [ # # ]: 0 : !BufTagMatchesRelFileLocator(&desc->tag, &rel->rd_locator))
8263 : : {
8264 : 0 : UnlockBufHdr(desc);
8265 : 0 : continue;
8266 : : }
8267 : :
8268 [ # # ]: 0 : if (MarkDirtyUnpinnedBufferInternal(buf, desc, &buffer_already_dirty))
8269 : 0 : (*buffers_dirtied)++;
8270 [ # # ]: 0 : else if (buffer_already_dirty)
8271 : 0 : (*buffers_already_dirty)++;
8272 : : else
8273 : 0 : (*buffers_skipped)++;
8274 : : }
318 michael@paquier.xyz 8275 :CBC 1 : }
8276 : :
8277 : : /*
8278 : : * Try to mark all the shared buffers as dirty.
8279 : : *
8280 : : * This function is intended for testing/development use only! See
8281 : : * MarkDirtyUnpinnedBuffer().
8282 : : *
8283 : : * See MarkDirtyRelUnpinnedBuffers() above for details about the buffers_*
8284 : : * parameters.
8285 : : */
8286 : : void
8287 : 1 : MarkDirtyAllUnpinnedBuffers(int32 *buffers_dirtied,
8288 : : int32 *buffers_already_dirty,
8289 : : int32 *buffers_skipped)
8290 : : {
8291 : 1 : *buffers_dirtied = 0;
8292 : 1 : *buffers_already_dirty = 0;
8293 : 1 : *buffers_skipped = 0;
8294 : :
8295 [ + + ]: 16385 : for (int buf = 1; buf <= NBuffers; buf++)
8296 : : {
8297 : 16384 : BufferDesc *desc = GetBufferDescriptor(buf - 1);
8298 : : uint64 buf_state;
8299 : : bool buffer_already_dirty;
8300 : :
8301 [ - + ]: 16384 : CHECK_FOR_INTERRUPTS();
8302 : :
270 andres@anarazel.de 8303 : 16384 : buf_state = pg_atomic_read_u64(&desc->state);
318 michael@paquier.xyz 8304 [ + + ]: 16384 : if (!(buf_state & BM_VALID))
8305 : 16349 : continue;
8306 : :
8307 : 35 : ResourceOwnerEnlarge(CurrentResourceOwner);
8308 : 35 : ReservePrivateRefCountEntry();
8309 : :
8310 : 35 : LockBufHdr(desc);
8311 : :
8312 [ + + ]: 35 : if (MarkDirtyUnpinnedBufferInternal(buf, desc, &buffer_already_dirty))
8313 : 16 : (*buffers_dirtied)++;
8314 [ + - ]: 19 : else if (buffer_already_dirty)
8315 : 19 : (*buffers_already_dirty)++;
8316 : : else
318 michael@paquier.xyz 8317 :UBC 0 : (*buffers_skipped)++;
8318 : : }
318 michael@paquier.xyz 8319 :CBC 1 : }
8320 : :
8321 : : /*
8322 : : * Generic implementation of the AIO handle staging callback for readv/writev
8323 : : * on local/shared buffers.
8324 : : *
8325 : : * Each readv/writev can target multiple buffers. The buffers have already
8326 : : * been registered with the IO handle.
8327 : : *
8328 : : * To make the IO ready for execution ("staging"), we need to ensure that the
8329 : : * targeted buffers are in an appropriate state while the IO is ongoing. For
8330 : : * that the AIO subsystem needs to have its own buffer pin, otherwise an error
8331 : : * in this backend could lead to this backend's buffer pin being released as
8332 : : * part of error handling, which in turn could lead to the buffer being
8333 : : * replaced while IO is ongoing.
8334 : : */
8335 : : static pg_always_inline void
561 andres@anarazel.de 8336 : 1373471 : buffer_stage_common(PgAioHandle *ioh, bool is_write, bool is_temp)
8337 : : {
8338 : : uint64 *io_data;
8339 : : uint8 handle_data_len;
8340 : : PgAioWaitRef io_ref;
8341 : 1373471 : BufferTag first PG_USED_FOR_ASSERTS_ONLY = {0};
8342 : :
8343 : 1373471 : io_data = pgaio_io_get_handle_data(ioh, &handle_data_len);
8344 : :
8345 : 1373471 : pgaio_io_get_wref(ioh, &io_ref);
8346 : :
8347 : : /* iterate over all buffers affected by the vectored readv/writev */
8348 [ + + ]: 2922455 : for (int i = 0; i < handle_data_len; i++)
8349 : : {
8350 : 1548984 : Buffer buffer = (Buffer) io_data[i];
8351 : 1548984 : BufferDesc *buf_hdr = is_temp ?
8352 : 11276 : GetLocalBufferDescriptor(-buffer - 1)
8353 [ + + ]: 1548984 : : GetBufferDescriptor(buffer - 1);
8354 : : uint64 buf_state;
8355 : :
8356 : : /*
8357 : : * Check that all the buffers are actually ones that could conceivably
8358 : : * be done in one IO, i.e. are sequential. This is the last
8359 : : * buffer-aware code before IO is actually executed and confusion
8360 : : * about which buffers are targeted by IO can be hard to debug, making
8361 : : * it worth doing extra-paranoid checks.
8362 : : */
8363 [ + + ]: 1548984 : if (i == 0)
8364 : 1373471 : first = buf_hdr->tag;
8365 : : else
8366 : : {
8367 [ - + ]: 175513 : Assert(buf_hdr->tag.relNumber == first.relNumber);
8368 [ - + ]: 175513 : Assert(buf_hdr->tag.blockNum == first.blockNum + i);
8369 : : }
8370 : :
8371 [ + + ]: 1548984 : if (is_temp)
270 8372 : 11276 : buf_state = pg_atomic_read_u64(&buf_hdr->state);
8373 : : else
561 8374 : 1537708 : buf_state = LockBufHdr(buf_hdr);
8375 : :
8376 : : /* verify the buffer is in the expected state */
8377 [ - + ]: 1548984 : Assert(buf_state & BM_TAG_VALID);
8378 [ - + ]: 1548984 : if (is_write)
8379 : : {
561 andres@anarazel.de 8380 [ # # ]:UBC 0 : Assert(buf_state & BM_VALID);
8381 [ # # ]: 0 : Assert(buf_state & BM_DIRTY);
8382 : : }
8383 : : else
8384 : : {
561 andres@anarazel.de 8385 [ - + ]:CBC 1548984 : Assert(!(buf_state & BM_VALID));
8386 [ - + ]: 1548984 : Assert(!(buf_state & BM_DIRTY));
8387 : : }
8388 : :
8389 : : /* temp buffers don't use BM_IO_IN_PROGRESS */
8390 [ + + ]: 1548984 : if (!is_temp)
8391 [ - + ]: 1537708 : Assert(buf_state & BM_IO_IN_PROGRESS);
8392 : :
8393 [ - + ]: 1548984 : Assert(BUF_STATE_GET_REFCOUNT(buf_state) >= 1);
8394 : :
8395 : : /*
8396 : : * Reflect that the buffer is now owned by the AIO subsystem.
8397 : : *
8398 : : * For local buffers: This can't be done just via LocalRefCount, as
8399 : : * one might initially think, as this backend could error out while
8400 : : * AIO is still in progress, releasing all the pins by the backend
8401 : : * itself.
8402 : : *
8403 : : * This pin is released again in TerminateBufferIO().
8404 : : */
8405 : 1548984 : buf_hdr->io_wref = io_ref;
8406 : :
8407 [ + + ]: 1548984 : if (is_temp)
8408 : : {
340 8409 : 11276 : buf_state += BUF_REFCOUNT_ONE;
270 8410 : 11276 : pg_atomic_unlocked_write_u64(&buf_hdr->state, buf_state);
8411 : : }
8412 : : else
340 8413 : 1537708 : UnlockBufHdrExt(buf_hdr, buf_state, 0, 0, 1);
8414 : :
8415 : : /*
8416 : : * Ensure the content lock that prevents buffer modifications while
8417 : : * the buffer is being written out is not released early due to an
8418 : : * error.
8419 : : */
561 8420 [ - + - - ]: 1548984 : if (is_write && !is_temp)
8421 : : {
270 andres@anarazel.de 8422 [ # # ]:UBC 0 : Assert(BufferLockHeldByMe(buf_hdr));
8423 : :
8424 : : /*
8425 : : * Lock is now owned by AIO subsystem.
8426 : : */
8427 : 0 : BufferLockDisown(buffer, buf_hdr);
8428 : : }
8429 : :
8430 : : /*
8431 : : * Stop tracking this buffer via the resowner - the AIO system now
8432 : : * keeps track.
8433 : : */
561 andres@anarazel.de 8434 [ + + ]:CBC 1548984 : if (!is_temp)
8435 : 1537708 : ResourceOwnerForgetBufferIO(CurrentResourceOwner, buffer);
8436 : : }
8437 : 1373471 : }
8438 : :
8439 : : /*
8440 : : * Decode readv errors as encoded by buffer_readv_encode_error().
8441 : : */
8442 : : static inline void
8443 : 642 : buffer_readv_decode_error(PgAioResult result,
8444 : : bool *zeroed_any,
8445 : : bool *ignored_any,
8446 : : uint8 *zeroed_or_error_count,
8447 : : uint8 *checkfail_count,
8448 : : uint8 *first_off)
8449 : : {
8450 : 642 : uint32 rem_error = result.error_data;
8451 : :
8452 : : /* see static asserts in buffer_readv_encode_error */
8453 : : #define READV_COUNT_BITS 7
8454 : : #define READV_COUNT_MASK ((1 << READV_COUNT_BITS) - 1)
8455 : :
8456 : 642 : *zeroed_any = rem_error & 1;
8457 : 642 : rem_error >>= 1;
8458 : :
8459 : 642 : *ignored_any = rem_error & 1;
8460 : 642 : rem_error >>= 1;
8461 : :
8462 : 642 : *zeroed_or_error_count = rem_error & READV_COUNT_MASK;
8463 : 642 : rem_error >>= READV_COUNT_BITS;
8464 : :
8465 : 642 : *checkfail_count = rem_error & READV_COUNT_MASK;
8466 : 642 : rem_error >>= READV_COUNT_BITS;
8467 : :
8468 : 642 : *first_off = rem_error & READV_COUNT_MASK;
8469 : 642 : rem_error >>= READV_COUNT_BITS;
8470 : 642 : }
8471 : :
8472 : : /*
8473 : : * Helper to encode errors for buffer_readv_complete()
8474 : : *
8475 : : * Errors are encoded as follows:
8476 : : * - bit 0 indicates whether any page was zeroed (1) or not (0)
8477 : : * - bit 1 indicates whether any checksum failure was ignored (1) or not (0)
8478 : : * - next READV_COUNT_BITS bits indicate the number of errored or zeroed pages
8479 : : * - next READV_COUNT_BITS bits indicate the number of checksum failures
8480 : : * - next READV_COUNT_BITS bits indicate the first offset of the first page
8481 : : * that was errored or zeroed or, if no errors/zeroes, the first ignored
8482 : : * checksum
8483 : : */
8484 : : static inline void
8485 : 192 : buffer_readv_encode_error(PgAioResult *result,
8486 : : bool is_temp,
8487 : : bool zeroed_any,
8488 : : bool ignored_any,
8489 : : uint8 error_count,
8490 : : uint8 zeroed_count,
8491 : : uint8 checkfail_count,
8492 : : uint8 first_error_off,
8493 : : uint8 first_zeroed_off,
8494 : : uint8 first_ignored_off)
8495 : : {
8496 : :
8497 : 192 : uint8 shift = 0;
8498 [ + + ]: 192 : uint8 zeroed_or_error_count =
8499 : : error_count > 0 ? error_count : zeroed_count;
8500 : : uint8 first_off;
8501 : :
8502 : : StaticAssertDecl(PG_IOV_MAX <= 1 << READV_COUNT_BITS,
8503 : : "PG_IOV_MAX is bigger than reserved space for error data");
8504 : : StaticAssertDecl((1 + 1 + 3 * READV_COUNT_BITS) <= PGAIO_RESULT_ERROR_BITS,
8505 : : "PGAIO_RESULT_ERROR_BITS is insufficient for buffer_readv");
8506 : :
8507 : : /*
8508 : : * We only have space to encode one offset - but luckily that's good
8509 : : * enough. If there is an error, the error is the interesting offset, same
8510 : : * with a zeroed buffer vs an ignored buffer.
8511 : : */
8512 [ + + ]: 192 : if (error_count > 0)
8513 : 94 : first_off = first_error_off;
8514 [ + + ]: 98 : else if (zeroed_count > 0)
8515 : 80 : first_off = first_zeroed_off;
8516 : : else
8517 : 18 : first_off = first_ignored_off;
8518 : :
8519 [ + + - + ]: 192 : Assert(!zeroed_any || error_count == 0);
8520 : :
8521 : 192 : result->error_data = 0;
8522 : :
8523 : 192 : result->error_data |= zeroed_any << shift;
8524 : 192 : shift += 1;
8525 : :
8526 : 192 : result->error_data |= ignored_any << shift;
8527 : 192 : shift += 1;
8528 : :
8529 : 192 : result->error_data |= ((uint32) zeroed_or_error_count) << shift;
8530 : 192 : shift += READV_COUNT_BITS;
8531 : :
8532 : 192 : result->error_data |= ((uint32) checkfail_count) << shift;
8533 : 192 : shift += READV_COUNT_BITS;
8534 : :
8535 : 192 : result->error_data |= ((uint32) first_off) << shift;
8536 : 192 : shift += READV_COUNT_BITS;
8537 : :
8538 [ + + ]: 192 : result->id = is_temp ? PGAIO_HCB_LOCAL_BUFFER_READV :
8539 : : PGAIO_HCB_SHARED_BUFFER_READV;
8540 : :
8541 [ + + ]: 192 : if (error_count > 0)
8542 : 94 : result->status = PGAIO_RS_ERROR;
8543 : : else
8544 : 98 : result->status = PGAIO_RS_WARNING;
8545 : :
8546 : : /*
8547 : : * The encoding is complicated enough to warrant cross-checking it against
8548 : : * the decode function.
8549 : : */
8550 : : #ifdef USE_ASSERT_CHECKING
8551 : : {
8552 : : bool zeroed_any_2,
8553 : : ignored_any_2;
8554 : : uint8 zeroed_or_error_count_2,
8555 : : checkfail_count_2,
8556 : : first_off_2;
8557 : :
8558 : 192 : buffer_readv_decode_error(*result,
8559 : : &zeroed_any_2, &ignored_any_2,
8560 : : &zeroed_or_error_count_2,
8561 : : &checkfail_count_2,
8562 : : &first_off_2);
8563 [ - + ]: 192 : Assert(zeroed_any == zeroed_any_2);
8564 [ - + ]: 192 : Assert(ignored_any == ignored_any_2);
8565 [ - + ]: 192 : Assert(zeroed_or_error_count == zeroed_or_error_count_2);
8566 [ - + ]: 192 : Assert(checkfail_count == checkfail_count_2);
8567 [ - + ]: 192 : Assert(first_off == first_off_2);
8568 : : }
8569 : : #endif
8570 : :
8571 : : #undef READV_COUNT_BITS
8572 : : #undef READV_COUNT_MASK
8573 : 192 : }
8574 : :
8575 : : /*
8576 : : * Helper for AIO readv completion callbacks, supporting both shared and temp
8577 : : * buffers. Gets called once for each buffer in a multi-page read.
8578 : : */
8579 : : static pg_always_inline void
8580 : 1377642 : buffer_readv_complete_one(PgAioTargetData *td, uint8 buf_off, Buffer buffer,
8581 : : uint8 flags, bool failed, bool is_temp,
8582 : : bool *buffer_invalid,
8583 : : bool *failed_checksum,
8584 : : bool *ignored_checksum,
8585 : : bool *zeroed_buffer)
8586 : : {
8587 : 1377642 : BufferDesc *buf_hdr = is_temp ?
8588 : 11276 : GetLocalBufferDescriptor(-buffer - 1)
8589 [ + + ]: 1377642 : : GetBufferDescriptor(buffer - 1);
8590 : 1377642 : BufferTag tag = buf_hdr->tag;
8591 : 1377642 : char *bufdata = BufferGetBlock(buffer);
8592 : : uint64 set_flag_bits;
8593 : : int piv_flags;
8594 : :
8595 : : /* check that the buffer is in the expected state for a read */
8596 : : #ifdef USE_ASSERT_CHECKING
8597 : : {
270 8598 : 1377642 : uint64 buf_state = pg_atomic_read_u64(&buf_hdr->state);
8599 : :
561 8600 [ - + ]: 1377642 : Assert(buf_state & BM_TAG_VALID);
8601 [ - + ]: 1377642 : Assert(!(buf_state & BM_VALID));
8602 : : /* temp buffers don't use BM_IO_IN_PROGRESS */
8603 [ + + ]: 1377642 : if (!is_temp)
8604 [ - + ]: 1366366 : Assert(buf_state & BM_IO_IN_PROGRESS);
8605 [ - + ]: 1377642 : Assert(!(buf_state & BM_DIRTY));
8606 : : }
8607 : : #endif
8608 : :
8609 : 1377642 : *buffer_invalid = false;
8610 : 1377642 : *failed_checksum = false;
8611 : 1377642 : *ignored_checksum = false;
8612 : 1377642 : *zeroed_buffer = false;
8613 : :
8614 : : /*
8615 : : * We ask PageIsVerified() to only log the message about checksum errors,
8616 : : * as the completion might be run in any backend (or IO workers). We will
8617 : : * report checksum errors in buffer_readv_report().
8618 : : */
8619 : 1377642 : piv_flags = PIV_LOG_LOG;
8620 : :
8621 : : /* the local zero_damaged_pages may differ from the definer's */
8622 [ + + ]: 1377642 : if (flags & READ_BUFFERS_IGNORE_CHECKSUM_FAILURES)
8623 : 38 : piv_flags |= PIV_IGNORE_CHECKSUM_FAILURE;
8624 : :
8625 : : /*
8626 : : * If the buffers are marked for zero on error, we want to log that in
8627 : : * case of a checksum failure.
8628 : : */
192 dgustafsson@postgres 8629 [ + + ]: 1377642 : if (flags & READ_BUFFERS_ZERO_ON_ERROR)
8630 : 45744 : piv_flags |= PIV_ZERO_BUFFERS_ON_ERROR;
8631 : :
8632 : : /* Check for garbage data. */
561 andres@anarazel.de 8633 [ + + ]: 1377642 : if (!failed)
8634 : : {
8635 : : /*
8636 : : * If the buffer is not currently pinned by this backend, e.g. because
8637 : : * we're completing this IO after an error, the buffer data will have
8638 : : * been marked as inaccessible when the buffer was unpinned. The AIO
8639 : : * subsystem holds a pin, but that doesn't prevent the buffer from
8640 : : * having been marked as inaccessible. The completion might also be
8641 : : * executed in a different process.
8642 : : */
8643 : : #ifdef USE_VALGRIND
8644 : : if (!BufferIsPinned(buffer))
8645 : : VALGRIND_MAKE_MEM_DEFINED(bufdata, BLCKSZ);
8646 : : #endif
8647 : :
8648 [ + + ]: 1376870 : if (!PageIsVerified((Page) bufdata, tag.blockNum, piv_flags,
8649 : : failed_checksum))
8650 : : {
8651 [ + + ]: 96 : if (flags & READ_BUFFERS_ZERO_ON_ERROR)
8652 : : {
8653 : 46 : memset(bufdata, 0, BLCKSZ);
8654 : 46 : *zeroed_buffer = true;
8655 : : }
8656 : : else
8657 : : {
8658 : 50 : *buffer_invalid = true;
8659 : : /* mark buffer as having failed */
8660 : 50 : failed = true;
8661 : : }
8662 : : }
8663 [ + + ]: 1376774 : else if (*failed_checksum)
8664 : 12 : *ignored_checksum = true;
8665 : :
8666 : : /* undo what we did above */
8667 : : #ifdef USE_VALGRIND
8668 : : if (!BufferIsPinned(buffer))
8669 : : VALGRIND_MAKE_MEM_NOACCESS(bufdata, BLCKSZ);
8670 : : #endif
8671 : :
8672 : : /*
8673 : : * Immediately log a message about the invalid page, but only to the
8674 : : * server log. The reason to do so immediately is that this may be
8675 : : * executed in a different backend than the one that originated the
8676 : : * request. The reason to do so immediately is that the originator
8677 : : * might not process the query result immediately (because it is busy
8678 : : * doing another part of query processing) or at all (e.g. if it was
8679 : : * cancelled or errored out due to another IO also failing). The
8680 : : * definer of the IO will emit an ERROR or WARNING when processing the
8681 : : * IO's results
8682 : : *
8683 : : * To avoid duplicating the code to emit these log messages, we reuse
8684 : : * buffer_readv_report().
8685 : : */
8686 [ + + + + : 1376870 : if (*buffer_invalid || *failed_checksum || *zeroed_buffer)
+ + ]
8687 : : {
556 8688 : 108 : PgAioResult result_one = {0};
8689 : :
561 8690 : 108 : buffer_readv_encode_error(&result_one, is_temp,
8691 : 108 : *zeroed_buffer,
8692 : 108 : *ignored_checksum,
8693 : 108 : *buffer_invalid,
8694 : 108 : *zeroed_buffer ? 1 : 0,
8695 : 108 : *failed_checksum ? 1 : 0,
8696 : : buf_off, buf_off, buf_off);
8697 : 108 : pgaio_result_report(result_one, td, LOG_SERVER_ONLY);
8698 : : }
8699 : : }
8700 : :
8701 : : /* Terminate I/O and set BM_VALID. */
8702 [ + + ]: 1377642 : set_flag_bits = failed ? BM_IO_ERROR : BM_VALID;
8703 [ + + ]: 1377642 : if (is_temp)
8704 : 11276 : TerminateLocalBufferIO(buf_hdr, false, set_flag_bits, true);
8705 : : else
8706 : 1366366 : TerminateBufferIO(buf_hdr, false, set_flag_bits, false, true);
8707 : :
8708 : : /*
8709 : : * Call the BUFFER_READ_DONE tracepoint in the callback, even though the
8710 : : * callback may not be executed in the same backend that called
8711 : : * BUFFER_READ_START. The alternative would be to defer calling the
8712 : : * tracepoint to a later point (e.g. the local completion callback for
8713 : : * shared buffer reads), which seems even less helpful.
8714 : : */
8715 : : TRACE_POSTGRESQL_BUFFER_READ_DONE(tag.forkNum,
8716 : : tag.blockNum,
8717 : : tag.spcOid,
8718 : : tag.dbOid,
8719 : : tag.relNumber,
8720 : : is_temp ? MyProcNumber : INVALID_PROC_NUMBER,
8721 : : false);
8722 : 1377642 : }
8723 : :
8724 : : /*
8725 : : * Perform completion handling of a single AIO read. This read may cover
8726 : : * multiple blocks / buffers.
8727 : : *
8728 : : * Shared between shared and local buffers, to reduce code duplication.
8729 : : */
8730 : : static pg_always_inline PgAioResult
8731 : 1235670 : buffer_readv_complete(PgAioHandle *ioh, PgAioResult prior_result,
8732 : : uint8 cb_data, bool is_temp)
8733 : : {
8734 : 1235670 : PgAioResult result = prior_result;
8735 : 1235670 : PgAioTargetData *td = pgaio_io_get_target_data(ioh);
8736 : 1235670 : uint8 first_error_off = 0;
8737 : 1235670 : uint8 first_zeroed_off = 0;
8738 : 1235670 : uint8 first_ignored_off = 0;
8739 : 1235670 : uint8 error_count = 0;
8740 : 1235670 : uint8 zeroed_count = 0;
8741 : 1235670 : uint8 ignored_count = 0;
8742 : 1235670 : uint8 checkfail_count = 0;
8743 : : uint64 *io_data;
8744 : : uint8 handle_data_len;
8745 : :
8746 [ + + ]: 1235670 : if (is_temp)
8747 : : {
8748 [ - + ]: 3044 : Assert(td->smgr.is_temp);
8749 [ - + ]: 3044 : Assert(pgaio_io_get_owner(ioh) == MyProcNumber);
8750 : : }
8751 : : else
8752 [ - + ]: 1232626 : Assert(!td->smgr.is_temp);
8753 : :
8754 : : /*
8755 : : * Iterate over all the buffers affected by this IO and call the
8756 : : * per-buffer completion function for each buffer.
8757 : : */
8758 : 1235670 : io_data = pgaio_io_get_handle_data(ioh, &handle_data_len);
8759 [ + + ]: 2613312 : for (uint8 buf_off = 0; buf_off < handle_data_len; buf_off++)
8760 : : {
8761 : 1377642 : Buffer buf = io_data[buf_off];
8762 : : bool failed;
8763 : 1377642 : bool failed_verification = false;
8764 : 1377642 : bool failed_checksum = false;
8765 : 1377642 : bool zeroed_buffer = false;
8766 : 1377642 : bool ignored_checksum = false;
8767 : :
8768 [ - + ]: 1377642 : Assert(BufferIsValid(buf));
8769 : :
8770 : : /*
8771 : : * If the entire I/O failed on a lower-level, each buffer needs to be
8772 : : * marked as failed. In case of a partial read, the first few buffers
8773 : : * may be ok.
8774 : : */
8775 : 1377642 : failed =
8776 : 1377642 : prior_result.status == PGAIO_RS_ERROR
8777 [ + + + + ]: 1377642 : || prior_result.result <= buf_off;
8778 : :
8779 : 1377642 : buffer_readv_complete_one(td, buf_off, buf, cb_data, failed, is_temp,
8780 : : &failed_verification,
8781 : : &failed_checksum,
8782 : : &ignored_checksum,
8783 : : &zeroed_buffer);
8784 : :
8785 : : /*
8786 : : * Track information about the number of different kinds of error
8787 : : * conditions across all pages, as there can be multiple pages failing
8788 : : * verification as part of one IO.
8789 : : */
8790 [ + + + - : 1377642 : if (failed_verification && !zeroed_buffer && error_count++ == 0)
+ + ]
8791 : 44 : first_error_off = buf_off;
8792 [ + + + + ]: 1377642 : if (zeroed_buffer && zeroed_count++ == 0)
8793 : 34 : first_zeroed_off = buf_off;
8794 [ + + + + ]: 1377642 : if (ignored_checksum && ignored_count++ == 0)
8795 : 10 : first_ignored_off = buf_off;
8796 [ + + ]: 1377642 : if (failed_checksum)
8797 : 32 : checkfail_count++;
8798 : : }
8799 : :
8800 : : /*
8801 : : * If the smgr read succeeded [partially] and page verification failed for
8802 : : * some of the pages, adjust the IO's result state appropriately.
8803 : : */
8804 [ + + + + ]: 1235670 : if (prior_result.status != PGAIO_RS_ERROR &&
8805 [ + + + + ]: 1235615 : (error_count > 0 || ignored_count > 0 || zeroed_count > 0))
8806 : : {
8807 : 84 : buffer_readv_encode_error(&result, is_temp,
8808 : : zeroed_count > 0, ignored_count > 0,
8809 : : error_count, zeroed_count, checkfail_count,
8810 : : first_error_off, first_zeroed_off,
8811 : : first_ignored_off);
8812 : 84 : pgaio_result_report(result, td, DEBUG1);
8813 : : }
8814 : :
8815 : : /*
8816 : : * For shared relations this reporting is done in
8817 : : * shared_buffer_readv_complete_local().
8818 : : */
8819 [ + + + + ]: 1235670 : if (is_temp && checkfail_count > 0)
8820 : 2 : pgstat_report_checksum_failures_in_db(td->smgr.rlocator.dbOid,
8821 : : checkfail_count);
8822 : :
8823 : 1235670 : return result;
8824 : : }
8825 : :
8826 : : /*
8827 : : * AIO error reporting callback for aio_shared_buffer_readv_cb and
8828 : : * aio_local_buffer_readv_cb.
8829 : : *
8830 : : * The error is encoded / decoded in buffer_readv_encode_error() /
8831 : : * buffer_readv_decode_error().
8832 : : */
8833 : : static void
8834 : 272 : buffer_readv_report(PgAioResult result, const PgAioTargetData *td,
8835 : : int elevel)
8836 : : {
8837 : 272 : int nblocks = td->smgr.nblocks;
8838 : 272 : BlockNumber first = td->smgr.blockNum;
8839 : 272 : BlockNumber last = first + nblocks - 1;
8840 : 272 : ProcNumber errProc =
8841 [ + + ]: 272 : td->smgr.is_temp ? MyProcNumber : INVALID_PROC_NUMBER;
8842 : : RelPathStr rpath =
8843 : 272 : relpathbackend(td->smgr.rlocator, errProc, td->smgr.forkNum);
8844 : : bool zeroed_any,
8845 : : ignored_any;
8846 : : uint8 zeroed_or_error_count,
8847 : : checkfail_count,
8848 : : first_off;
8849 : : uint8 affected_count;
8850 : : const char *msg_one,
8851 : : *msg_mult,
8852 : : *det_mult,
8853 : : *hint_mult;
8854 : :
8855 : 272 : buffer_readv_decode_error(result, &zeroed_any, &ignored_any,
8856 : : &zeroed_or_error_count,
8857 : : &checkfail_count,
8858 : : &first_off);
8859 : :
8860 : : /*
8861 : : * Treat a read that had both zeroed buffers *and* ignored checksums as a
8862 : : * special case, it's too irregular to be emitted the same way as the
8863 : : * other cases.
8864 : : */
8865 [ + + + + ]: 272 : if (zeroed_any && ignored_any)
8866 : : {
8867 [ + - - + ]: 4 : Assert(zeroed_any && ignored_any);
8868 [ - + ]: 4 : Assert(nblocks > 1); /* same block can't be both zeroed and ignored */
8869 [ - + ]: 4 : Assert(result.status != PGAIO_RS_ERROR);
8870 : 4 : affected_count = zeroed_or_error_count;
8871 : :
8872 [ + - + - ]: 4 : ereport(elevel,
8873 : : errcode(ERRCODE_DATA_CORRUPTED),
8874 : : errmsg("zeroing %u page(s) and ignoring %u checksum failure(s) among blocks %u..%u of relation \"%s\"",
8875 : : affected_count, checkfail_count, first, last, rpath.str),
8876 : : affected_count > 1 ?
8877 : : errdetail("Block %u held the first zeroed page.",
8878 : : first + first_off) : 0,
8879 : : errhint_plural("See server log for details about the other %d invalid block.",
8880 : : "See server log for details about the other %d invalid blocks.",
8881 : : affected_count + checkfail_count - 1,
8882 : : affected_count + checkfail_count - 1));
8883 : 4 : return;
8884 : : }
8885 : :
8886 : : /*
8887 : : * The other messages are highly repetitive. To avoid duplicating a long
8888 : : * and complicated ereport(), gather the translated format strings
8889 : : * separately and then do one common ereport.
8890 : : */
8891 [ + + ]: 268 : if (result.status == PGAIO_RS_ERROR)
8892 : : {
8893 [ - + ]: 136 : Assert(!zeroed_any); /* can't have invalid pages when zeroing them */
8894 : 136 : affected_count = zeroed_or_error_count;
412 peter@eisentraut.org 8895 : 136 : msg_one = _("invalid page in block %u of relation \"%s\"");
8896 : 136 : msg_mult = _("%u invalid pages among blocks %u..%u of relation \"%s\"");
8897 : 136 : det_mult = _("Block %u held the first invalid page.");
561 andres@anarazel.de 8898 : 136 : hint_mult = _("See server log for the other %u invalid block(s).");
8899 : : }
8900 [ + + + - ]: 132 : else if (zeroed_any && !ignored_any)
8901 : : {
8902 : 108 : affected_count = zeroed_or_error_count;
412 peter@eisentraut.org 8903 : 108 : msg_one = _("invalid page in block %u of relation \"%s\"; zeroing out page");
8904 : 108 : msg_mult = _("zeroing out %u invalid pages among blocks %u..%u of relation \"%s\"");
8905 : 108 : det_mult = _("Block %u held the first zeroed page.");
561 andres@anarazel.de 8906 : 108 : hint_mult = _("See server log for the other %u zeroed block(s).");
8907 : : }
8908 [ + - + - ]: 24 : else if (!zeroed_any && ignored_any)
8909 : : {
8910 : 24 : affected_count = checkfail_count;
412 peter@eisentraut.org 8911 : 24 : msg_one = _("ignoring checksum failure in block %u of relation \"%s\"");
8912 : 24 : msg_mult = _("ignoring %u checksum failures among blocks %u..%u of relation \"%s\"");
8913 : 24 : det_mult = _("Block %u held the first ignored page.");
561 andres@anarazel.de 8914 : 24 : hint_mult = _("See server log for the other %u ignored block(s).");
8915 : : }
8916 : : else
561 andres@anarazel.de 8917 :UBC 0 : pg_unreachable();
8918 : :
561 andres@anarazel.de 8919 [ + - + + :CBC 268 : ereport(elevel,
+ + + + ]
8920 : : errcode(ERRCODE_DATA_CORRUPTED),
8921 : : affected_count == 1 ?
8922 : : errmsg_internal(msg_one, first + first_off, rpath.str) :
8923 : : errmsg_internal(msg_mult, affected_count, first, last, rpath.str),
8924 : : affected_count > 1 ? errdetail_internal(det_mult, first + first_off) : 0,
8925 : : affected_count > 1 ? errhint_internal(hint_mult, affected_count - 1) : 0);
8926 : : }
8927 : :
8928 : : static void
8929 : 1370427 : shared_buffer_readv_stage(PgAioHandle *ioh, uint8 cb_data)
8930 : : {
8931 : 1370427 : buffer_stage_common(ioh, false, false);
8932 : 1370427 : }
8933 : :
8934 : : static PgAioResult
8935 : 1232626 : shared_buffer_readv_complete(PgAioHandle *ioh, PgAioResult prior_result,
8936 : : uint8 cb_data)
8937 : : {
8938 : 1232626 : return buffer_readv_complete(ioh, prior_result, cb_data, false);
8939 : : }
8940 : :
8941 : : /*
8942 : : * We need a backend-local completion callback for shared buffers, to be able
8943 : : * to report checksum errors correctly. Unfortunately that can only safely
8944 : : * happen if the reporting backend has previously called
8945 : : * pgstat_prepare_report_checksum_failure(), which we can only guarantee in
8946 : : * the backend that started the IO. Hence this callback.
8947 : : */
8948 : : static PgAioResult
8949 : 1370427 : shared_buffer_readv_complete_local(PgAioHandle *ioh, PgAioResult prior_result,
8950 : : uint8 cb_data)
8951 : : {
8952 : : bool zeroed_any,
8953 : : ignored_any;
8954 : : uint8 zeroed_or_error_count,
8955 : : checkfail_count,
8956 : : first_off;
8957 : :
8958 [ + + ]: 1370427 : if (prior_result.status == PGAIO_RS_OK)
8959 : 1370249 : return prior_result;
8960 : :
8961 : 178 : buffer_readv_decode_error(prior_result,
8962 : : &zeroed_any,
8963 : : &ignored_any,
8964 : : &zeroed_or_error_count,
8965 : : &checkfail_count,
8966 : : &first_off);
8967 : :
8968 [ + + ]: 178 : if (checkfail_count)
8969 : : {
8970 : 24 : PgAioTargetData *td = pgaio_io_get_target_data(ioh);
8971 : :
8972 : 24 : pgstat_report_checksum_failures_in_db(td->smgr.rlocator.dbOid,
8973 : : checkfail_count);
8974 : : }
8975 : :
8976 : 178 : return prior_result;
8977 : : }
8978 : :
8979 : : static void
8980 : 3044 : local_buffer_readv_stage(PgAioHandle *ioh, uint8 cb_data)
8981 : : {
8982 : 3044 : buffer_stage_common(ioh, false, true);
8983 : 3044 : }
8984 : :
8985 : : static PgAioResult
8986 : 3044 : local_buffer_readv_complete(PgAioHandle *ioh, PgAioResult prior_result,
8987 : : uint8 cb_data)
8988 : : {
8989 : 3044 : return buffer_readv_complete(ioh, prior_result, cb_data, true);
8990 : : }
8991 : :
8992 : : /* readv callback is passed READ_BUFFERS_* flags as callback data */
8993 : : const PgAioHandleCallbacks aio_shared_buffer_readv_cb = {
8994 : : .stage = shared_buffer_readv_stage,
8995 : : .complete_shared = shared_buffer_readv_complete,
8996 : : /* need a local callback to report checksum failures */
8997 : : .complete_local = shared_buffer_readv_complete_local,
8998 : : .report = buffer_readv_report,
8999 : : };
9000 : :
9001 : : /* readv callback is passed READ_BUFFERS_* flags as callback data */
9002 : : const PgAioHandleCallbacks aio_local_buffer_readv_cb = {
9003 : : .stage = local_buffer_readv_stage,
9004 : :
9005 : : /*
9006 : : * Note that this, in contrast to the shared_buffers case, uses
9007 : : * complete_local, as only the issuing backend has access to the required
9008 : : * datastructures. This is important in case the IO completion may be
9009 : : * consumed incidentally by another backend.
9010 : : */
9011 : : .complete_local = local_buffer_readv_complete,
9012 : : .report = buffer_readv_report,
9013 : : };
|