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