Branch data Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * read_stream.c
4 : : * Mechanism for accessing buffered relation data with look-ahead
5 : : *
6 : : * Code that needs to access relation data typically pins blocks one at a
7 : : * time, often in a predictable order that might be sequential or data-driven.
8 : : * Calling the simple ReadBuffer() function for each block is inefficient,
9 : : * because blocks that are not yet in the buffer pool require I/O operations
10 : : * that are small and might stall waiting for storage. This mechanism looks
11 : : * into the future and calls StartReadBuffers() and WaitReadBuffers() to read
12 : : * neighboring blocks together and ahead of time, with an adaptive look-ahead
13 : : * distance.
14 : : *
15 : : * A user-provided callback generates a stream of block numbers that is used
16 : : * to form reads of up to io_combine_limit, by attempting to merge them with a
17 : : * pending read. When that isn't possible, the existing pending read is sent
18 : : * to StartReadBuffers() so that a new one can begin to form.
19 : : *
20 : : * The algorithm for controlling the look-ahead distance is based on recent
21 : : * cache / miss history, as well as whether we need to wait for I/O completion
22 : : * after a miss. When no I/O is necessary, there is no benefit in looking
23 : : * ahead more than one block. This is the default initial assumption. When
24 : : * blocks needing I/O are streamed, the combine distance is increased to
25 : : * benefit from I/O combining and the read-ahead distance is increased
26 : : * whenever we need to wait for I/O to try to benefit from increased I/O
27 : : * concurrency. Both are reduced gradually when cached blocks are streamed.
28 : : *
29 : : * The main data structure is a circular queue of buffers of size
30 : : * max_pinned_buffers plus some extra space for technical reasons, ready to be
31 : : * returned by read_stream_next_buffer(). Each buffer also has an optional
32 : : * variable sized object that is passed from the callback to the consumer of
33 : : * buffers.
34 : : *
35 : : * Parallel to the queue of buffers, there is a circular queue of in-progress
36 : : * I/Os that have been started with StartReadBuffers(), and for which
37 : : * WaitReadBuffers() must be called before returning the buffer.
38 : : *
39 : : * For example, if the callback returns block numbers 10, 42, 43, 44, 60 in
40 : : * successive calls, then these data structures might appear as follows:
41 : : *
42 : : * buffers buf/data ios
43 : : *
44 : : * +----+ +-----+ +--------+
45 : : * | | | | +----+ 42..44 | <- oldest_io_index
46 : : * +----+ +-----+ | +--------+
47 : : * oldest_buffer_index -> | 10 | | ? | | +--+ 60..60 |
48 : : * +----+ +-----+ | | +--------+
49 : : * | 42 | | ? |<-+ | | | <- next_io_index
50 : : * +----+ +-----+ | +--------+
51 : : * | 43 | | ? | | | |
52 : : * +----+ +-----+ | +--------+
53 : : * | 44 | | ? | | | |
54 : : * +----+ +-----+ | +--------+
55 : : * | 60 | | ? |<---+
56 : : * +----+ +-----+
57 : : * next_buffer_index -> | | | |
58 : : * +----+ +-----+
59 : : *
60 : : * In the example, 5 buffers are pinned, and the next buffer to be streamed to
61 : : * the client is block 10. Block 10 was a hit and has no associated I/O, but
62 : : * the range 42..44 requires an I/O wait before its buffers are returned, as
63 : : * does block 60.
64 : : *
65 : : *
66 : : * Portions Copyright (c) 2024-2026, PostgreSQL Global Development Group
67 : : * Portions Copyright (c) 1994, Regents of the University of California
68 : : *
69 : : * IDENTIFICATION
70 : : * src/backend/storage/aio/read_stream.c
71 : : *
72 : : *-------------------------------------------------------------------------
73 : : */
74 : : #include "postgres.h"
75 : :
76 : : #include "miscadmin.h"
77 : : #include "executor/instrument_node.h"
78 : : #include "storage/aio.h"
79 : : #include "storage/fd.h"
80 : : #include "storage/smgr.h"
81 : : #include "storage/read_stream.h"
82 : : #include "utils/memdebug.h"
83 : : #include "utils/rel.h"
84 : : #include "utils/spccache.h"
85 : :
86 : : typedef struct InProgressIO
87 : : {
88 : : int16 buffer_index;
89 : : ReadBuffersOperation op;
90 : : } InProgressIO;
91 : :
92 : : /*
93 : : * State for managing a stream of reads.
94 : : */
95 : : struct ReadStream
96 : : {
97 : : int16 max_ios;
98 : : int16 io_combine_limit;
99 : : int16 ios_in_progress;
100 : : int16 queue_size;
101 : : int16 max_pinned_buffers;
102 : : int16 forwarded_buffers;
103 : : int16 pinned_buffers;
104 : :
105 : : /*
106 : : * Limit of how far, in blocks, to look-ahead for IO combining and for
107 : : * read-ahead.
108 : : *
109 : : * The limits for read-ahead and combining are handled separately to allow
110 : : * for IO combining even in cases where the I/O subsystem can keep up at a
111 : : * low read-ahead distance, as doing larger IOs is more efficient.
112 : : *
113 : : * Set to 0 when the end of the stream is reached.
114 : : */
115 : : int16 combine_distance;
116 : : int16 readahead_distance;
117 : : uint16 distance_decay_holdoff;
118 : : int16 initialized_buffers;
119 : : int16 resume_readahead_distance;
120 : : int16 resume_combine_distance;
121 : : int read_buffers_flags;
122 : : bool sync_mode; /* using io_method=sync */
123 : : bool batch_mode; /* READ_STREAM_USE_BATCHING */
124 : : bool advice_enabled;
125 : : bool temporary;
126 : :
127 : : /* scan stats counters */
128 : : IOStats *stats;
129 : :
130 : : /*
131 : : * One-block buffer to support 'ungetting' a block number, to resolve flow
132 : : * control problems when I/Os are split.
133 : : */
134 : : BlockNumber buffered_blocknum;
135 : :
136 : : /*
137 : : * The callback that will tell us which block numbers to read, and an
138 : : * opaque pointer that will be pass to it for its own purposes.
139 : : */
140 : : ReadStreamBlockNumberCB callback;
141 : : void *callback_private_data;
142 : :
143 : : /* Next expected block, for detecting sequential access. */
144 : : BlockNumber seq_blocknum;
145 : : BlockNumber seq_until_processed;
146 : :
147 : : /* The read operation we are currently preparing. */
148 : : BlockNumber pending_read_blocknum;
149 : : int16 pending_read_nblocks;
150 : :
151 : : /* Space for buffers and optional per-buffer private data. */
152 : : size_t per_buffer_data_size;
153 : : void *per_buffer_data;
154 : :
155 : : /* Read operations that have been started but not waited for yet. */
156 : : InProgressIO *ios;
157 : : int16 oldest_io_index;
158 : : int16 next_io_index;
159 : :
160 : : bool fast_path;
161 : :
162 : : /* Circular queue of buffers. */
163 : : int16 oldest_buffer_index; /* Next pinned buffer to return */
164 : : int16 next_buffer_index; /* Index of next buffer to pin */
165 : : Buffer buffers[FLEXIBLE_ARRAY_MEMBER];
166 : : };
167 : :
168 : : /*
169 : : * Return a pointer to the per-buffer data by index.
170 : : */
171 : : static inline void *
172 : 4286181 : get_per_buffer_data(ReadStream *stream, int16 buffer_index)
173 : : {
174 : 8572362 : return (char *) stream->per_buffer_data +
175 : 4286181 : stream->per_buffer_data_size * buffer_index;
176 : : }
177 : :
178 : : /*
179 : : * General-use ReadStreamBlockNumberCB for block range scans. Loops over the
180 : : * blocks [current_blocknum, last_exclusive).
181 : : */
182 : : BlockNumber
183 : 439495 : block_range_read_stream_cb(ReadStream *stream,
184 : : void *callback_private_data,
185 : : void *per_buffer_data)
186 : : {
187 : 439495 : BlockRangeReadStreamPrivate *p = callback_private_data;
188 : :
189 [ + + ]: 439495 : if (p->current_blocknum < p->last_exclusive)
190 : 361148 : return p->current_blocknum++;
191 : :
192 : 78347 : return InvalidBlockNumber;
193 : : }
194 : :
195 : : /*
196 : : * Update stream stats with current pinned buffer depth.
197 : : *
198 : : * Called once per buffer returned to the consumer in read_stream_next_buffer().
199 : : * Records the number of pinned buffers at that moment, so we can compute the
200 : : * average look-ahead depth.
201 : : */
202 : : static inline void
203 : 4514817 : read_stream_count_prefetch(ReadStream *stream)
204 : : {
205 : 4514817 : IOStats *stats = stream->stats;
206 : :
207 [ + + ]: 4514817 : if (stats == NULL)
208 : 4514809 : return;
209 : :
210 : 8 : stats->prefetch_count++;
211 : 8 : stats->distance_sum += stream->pinned_buffers;
212 [ + - ]: 8 : if (stream->pinned_buffers > stats->distance_max)
213 : 8 : stats->distance_max = stream->pinned_buffers;
214 : : }
215 : :
216 : : /*
217 : : * Update stream stats about size of I/O requests.
218 : : *
219 : : * We count the number of I/O requests, size of requests (counted in blocks)
220 : : * and number of in-progress I/Os.
221 : : */
222 : : static inline void
223 : 605445 : read_stream_count_io(ReadStream *stream, int nblocks, int in_progress)
224 : : {
225 : 605445 : IOStats *stats = stream->stats;
226 : :
227 [ + - ]: 605445 : if (stats == NULL)
228 : 605445 : return;
229 : :
230 : 0 : stats->io_count++;
231 : 0 : stats->io_nblocks += nblocks;
232 : 0 : stats->io_in_progress += in_progress;
233 : : }
234 : :
235 : : /*
236 : : * Update stream stats about waits for I/O when consuming buffers.
237 : : *
238 : : * We count the number of I/O waits while pulling buffers out of a stream.
239 : : */
240 : : static inline void
241 : 298769 : read_stream_count_wait(ReadStream *stream)
242 : : {
243 : 298769 : IOStats *stats = stream->stats;
244 : :
245 [ + - ]: 298769 : if (stats == NULL)
246 : 298769 : return;
247 : :
248 : 0 : stats->wait_count++;
249 : : }
250 : :
251 : : /*
252 : : * Enable collection of stats into the provided IOStats.
253 : : */
254 : : void
255 : 8 : read_stream_enable_stats(ReadStream *stream, IOStats *stats)
256 : : {
257 : 8 : stream->stats = stats;
258 : : /* The same accumulator may span recreated streams of different sizes. */
259 [ + - ]: 8 : if (stream->stats &&
260 [ + - ]: 8 : stream->stats->distance_capacity < stream->max_pinned_buffers)
261 : 8 : stream->stats->distance_capacity = stream->max_pinned_buffers;
262 : 8 : }
263 : :
264 : : /*
265 : : * Ask the callback which block it would like us to read next, with a one block
266 : : * buffer in front to allow read_stream_unget_block() to work.
267 : : */
268 : : static inline BlockNumber
269 : 5893740 : read_stream_get_block(ReadStream *stream, void *per_buffer_data)
270 : : {
271 : : BlockNumber blocknum;
272 : :
273 : 5893740 : blocknum = stream->buffered_blocknum;
274 [ - + ]: 5893740 : if (blocknum != InvalidBlockNumber)
275 : 0 : stream->buffered_blocknum = InvalidBlockNumber;
276 : : else
277 : : {
278 : : /*
279 : : * Tell Valgrind that the per-buffer data is undefined. That replaces
280 : : * the "noaccess" state that was set when the consumer moved past this
281 : : * entry last time around the queue, and should also catch callbacks
282 : : * that fail to initialize data that the buffer consumer later
283 : : * accesses. On the first go around, it is undefined already.
284 : : */
285 : : VALGRIND_MAKE_MEM_UNDEFINED(per_buffer_data,
286 : : stream->per_buffer_data_size);
287 : 5893740 : blocknum = stream->callback(stream,
288 : : stream->callback_private_data,
289 : : per_buffer_data);
290 : : }
291 : :
292 : 5893740 : return blocknum;
293 : : }
294 : :
295 : : /*
296 : : * In order to deal with buffer shortages and I/O limits after short reads, we
297 : : * sometimes need to defer handling of a block we've already consumed from the
298 : : * registered callback until later.
299 : : */
300 : : static inline void
301 : 0 : read_stream_unget_block(ReadStream *stream, BlockNumber blocknum)
302 : : {
303 : : /* We shouldn't ever unget more than one block. */
304 : : Assert(stream->buffered_blocknum == InvalidBlockNumber);
305 : : Assert(blocknum != InvalidBlockNumber);
306 : 0 : stream->buffered_blocknum = blocknum;
307 : 0 : }
308 : :
309 : : /*
310 : : * Start as much of the current pending read as we can. If we have to split it
311 : : * because of the per-backend buffer limit, or the buffer manager decides to
312 : : * split it, then the pending read is adjusted to hold the remaining portion.
313 : : *
314 : : * We can always start a read of at least size one if we have no progress yet.
315 : : * Otherwise it's possible that we can't start a read at all because of a lack
316 : : * of buffers, and then false is returned. Buffer shortages also reduce the
317 : : * distance to a level that prevents look-ahead until buffers are released.
318 : : */
319 : : static bool
320 : 2149592 : read_stream_start_pending_read(ReadStream *stream)
321 : : {
322 : : bool need_wait;
323 : : int requested_nblocks;
324 : : int nblocks;
325 : : int flags;
326 : : int forwarded;
327 : : int16 io_index;
328 : : int16 overflow;
329 : : int16 buffer_index;
330 : : int buffer_limit;
331 : :
332 : : /* This should only be called with a pending read. */
333 : : Assert(stream->pending_read_nblocks > 0);
334 : : Assert(stream->pending_read_nblocks <= stream->io_combine_limit);
335 : :
336 : : /* We had better not exceed the per-stream buffer limit with this read. */
337 : : Assert(stream->pinned_buffers + stream->pending_read_nblocks <=
338 : : stream->max_pinned_buffers);
339 : :
340 : : #ifdef USE_ASSERT_CHECKING
341 : : /* We had better not be overwriting an existing pinned buffer. */
342 : : if (stream->pinned_buffers > 0)
343 : : Assert(stream->next_buffer_index != stream->oldest_buffer_index);
344 : : else
345 : : Assert(stream->next_buffer_index == stream->oldest_buffer_index);
346 : :
347 : : /*
348 : : * Pinned buffers forwarded by a preceding StartReadBuffers() call that
349 : : * had to split the operation should match the leading blocks of this
350 : : * following StartReadBuffers() call.
351 : : */
352 : : Assert(stream->forwarded_buffers <= stream->pending_read_nblocks);
353 : : for (int i = 0; i < stream->forwarded_buffers; ++i)
354 : : Assert(BufferGetBlockNumber(stream->buffers[stream->next_buffer_index + i]) ==
355 : : stream->pending_read_blocknum + i);
356 : :
357 : : /*
358 : : * Check that we've cleared the queue/overflow entries corresponding to
359 : : * the rest of the blocks covered by this read, unless it's the first go
360 : : * around and we haven't even initialized them yet.
361 : : */
362 : : for (int i = stream->forwarded_buffers; i < stream->pending_read_nblocks; ++i)
363 : : Assert(stream->next_buffer_index + i >= stream->initialized_buffers ||
364 : : stream->buffers[stream->next_buffer_index + i] == InvalidBuffer);
365 : : #endif
366 : :
367 : : /* Do we need to issue read-ahead advice? */
368 : 2149592 : flags = stream->read_buffers_flags;
369 [ + + ]: 2149592 : if (stream->advice_enabled)
370 : : {
371 [ + + ]: 1674 : if (stream->pending_read_blocknum == stream->seq_blocknum)
372 : : {
373 : : /*
374 : : * Sequential: Issue advice until the preadv() calls have caught
375 : : * up with the first advice issued for this sequential region, and
376 : : * then stay out of the way of the kernel's own read-ahead.
377 : : */
378 [ + + ]: 28 : if (stream->seq_until_processed != InvalidBlockNumber)
379 : 1 : flags |= READ_BUFFERS_ISSUE_ADVICE;
380 : : }
381 : : else
382 : : {
383 : : /*
384 : : * Random jump: Note the starting location of a new potential
385 : : * sequential region and start issuing advice. Skip it this time
386 : : * if the preadv() follows immediately, eg first block in stream.
387 : : */
388 : 1646 : stream->seq_until_processed = stream->pending_read_blocknum;
389 [ + + ]: 1646 : if (stream->pinned_buffers > 0)
390 : 46 : flags |= READ_BUFFERS_ISSUE_ADVICE;
391 : : }
392 : : }
393 : :
394 : : /*
395 : : * How many more buffers is this backend allowed?
396 : : *
397 : : * Forwarded buffers are already pinned and map to the leading blocks of
398 : : * the pending read (the remaining portion of an earlier short read that
399 : : * we're about to continue). They are not counted in pinned_buffers, but
400 : : * they are counted as pins already held by this backend according to the
401 : : * buffer manager, so they must be added to the limit it grants us.
402 : : */
403 [ + + ]: 2149592 : if (stream->temporary)
404 [ + - ]: 18332 : buffer_limit = Min(GetAdditionalLocalPinLimit(), PG_INT16_MAX);
405 : : else
406 [ + - ]: 2131260 : buffer_limit = Min(GetAdditionalPinLimit(), PG_INT16_MAX);
407 : : Assert(stream->forwarded_buffers <= stream->pending_read_nblocks);
408 : :
409 : 2149592 : buffer_limit += stream->forwarded_buffers;
410 : 2149592 : buffer_limit = Min(buffer_limit, PG_INT16_MAX);
411 : :
412 [ + + + - ]: 2149592 : if (buffer_limit == 0 && stream->pinned_buffers == 0)
413 : 647506 : buffer_limit = 1; /* guarantee progress */
414 : :
415 : : /* Does the per-backend limit affect this read? */
416 : 2149592 : nblocks = stream->pending_read_nblocks;
417 [ + + ]: 2149592 : if (buffer_limit < nblocks)
418 : : {
419 : : int16 new_distance;
420 : :
421 : : /* Shrink distance: no more look-ahead until buffers are released. */
422 : 2062 : new_distance = stream->pinned_buffers + buffer_limit;
423 [ + + ]: 2062 : if (stream->readahead_distance > new_distance)
424 : 586 : stream->readahead_distance = new_distance;
425 : :
426 : : /* Unless we have nothing to give the consumer, stop here. */
427 [ + + ]: 2062 : if (stream->pinned_buffers > 0)
428 : 177 : return false;
429 : :
430 : : /* A short read is required to make progress. */
431 : 1885 : nblocks = buffer_limit;
432 : : }
433 : :
434 : : /*
435 : : * We say how many blocks we want to read, but it may be smaller on return
436 : : * if the buffer manager decides to shorten the read. Initialize buffers
437 : : * to InvalidBuffer (= not a forwarded buffer) as input on first use only,
438 : : * and keep the original nblocks number so we can check for forwarded
439 : : * buffers as output, below.
440 : : */
441 : 2149415 : buffer_index = stream->next_buffer_index;
442 : 2149415 : io_index = stream->next_io_index;
443 [ + + ]: 3549411 : while (stream->initialized_buffers < buffer_index + nblocks)
444 : 1399996 : stream->buffers[stream->initialized_buffers++] = InvalidBuffer;
445 : 2149415 : requested_nblocks = nblocks;
446 : 2149415 : need_wait = StartReadBuffers(&stream->ios[io_index].op,
447 : 2149415 : &stream->buffers[buffer_index],
448 : : stream->pending_read_blocknum,
449 : : &nblocks,
450 : : flags);
451 : 2149407 : stream->pinned_buffers += nblocks;
452 : :
453 : : /* Remember whether we need to wait before returning this buffer. */
454 [ + + ]: 2149407 : if (!need_wait)
455 : : {
456 : : /*
457 : : * If there currently is no IO in progress, and we have not needed to
458 : : * issue IO recently, decay the look-ahead distance. We detect if we
459 : : * had to issue IO recently by having a decay holdoff that's set to
460 : : * the max look-ahead distance whenever we need to do IO. This is
461 : : * important to ensure we eventually reach a high enough distance to
462 : : * perform IO asynchronously when starting out with a small look-ahead
463 : : * distance.
464 : : */
465 [ + + ]: 1556280 : if (stream->ios_in_progress == 0)
466 : : {
467 [ + + ]: 1555640 : if (stream->distance_decay_holdoff > 0)
468 : 23104 : stream->distance_decay_holdoff--;
469 : : else
470 : : {
471 [ + + ]: 1532536 : if (stream->readahead_distance > 1)
472 : 16889 : stream->readahead_distance--;
473 : :
474 : : /*
475 : : * For now we reduce the IO combine distance after
476 : : * sufficiently many buffer hits. There is no clear
477 : : * performance argument for doing so, but at the moment we
478 : : * need to do so to make the entrance into fast_path work
479 : : * correctly: We require combine_distance == 1 to enter
480 : : * fast-path, as without that condition we would wrongly
481 : : * re-enter fast-path when readahead_distance == 1 and
482 : : * pinned_buffers == 1, as we would not yet have prepared
483 : : * another IO in that situation.
484 : : */
485 [ + + ]: 1532536 : if (stream->combine_distance > 1)
486 : 16913 : stream->combine_distance--;
487 : : }
488 : : }
489 : : }
490 : : else
491 : : {
492 : : /*
493 : : * Remember to call WaitReadBuffers() before returning head buffer.
494 : : * Look-ahead distance will be adjusted after waiting.
495 : : */
496 : 593127 : stream->ios[io_index].buffer_index = buffer_index;
497 [ + + ]: 593127 : if (++stream->next_io_index == stream->max_ios)
498 : 24159 : stream->next_io_index = 0;
499 : : Assert(stream->ios_in_progress < stream->max_ios);
500 : 593127 : stream->ios_in_progress++;
501 : 593127 : stream->seq_blocknum = stream->pending_read_blocknum + nblocks;
502 : :
503 : : /* update I/O stats */
504 : 593127 : read_stream_count_io(stream, nblocks, stream->ios_in_progress);
505 : : }
506 : :
507 : : /*
508 : : * How many pins were acquired but forwarded to the next call? These need
509 : : * to be passed to the next StartReadBuffers() call by leaving them
510 : : * exactly where they are in the queue, or released if the stream ends
511 : : * early. We need the number for accounting purposes, since they are not
512 : : * counted in stream->pinned_buffers but we already hold them.
513 : : */
514 : 2149407 : forwarded = 0;
515 [ + + ]: 2151848 : while (nblocks + forwarded < requested_nblocks &&
516 [ + + ]: 72534 : stream->buffers[buffer_index + nblocks + forwarded] != InvalidBuffer)
517 : 2441 : forwarded++;
518 : 2149407 : stream->forwarded_buffers = forwarded;
519 : :
520 : : /*
521 : : * We gave a contiguous range of buffer space to StartReadBuffers(), but
522 : : * we want it to wrap around at queue_size. Copy overflowing buffers to
523 : : * the front of the array where they'll be consumed, but also leave a copy
524 : : * in the overflow zone which the I/O operation has a pointer to (it needs
525 : : * a contiguous array). Both copies will be cleared when the buffers are
526 : : * handed to the consumer.
527 : : */
528 : 2149407 : overflow = (buffer_index + nblocks + forwarded) - stream->queue_size;
529 [ + + ]: 2149407 : if (overflow > 0)
530 : : {
531 : : Assert(overflow < stream->queue_size); /* can't overlap */
532 : 522 : memcpy(&stream->buffers[0],
533 : 522 : &stream->buffers[stream->queue_size],
534 : : sizeof(stream->buffers[0]) * overflow);
535 : : }
536 : :
537 : : /* Compute location of start of next read, without using % operator. */
538 : 2149407 : buffer_index += nblocks;
539 [ + + ]: 2149407 : if (buffer_index >= stream->queue_size)
540 : 300386 : buffer_index -= stream->queue_size;
541 : : Assert(buffer_index >= 0 && buffer_index < stream->queue_size);
542 : 2149407 : stream->next_buffer_index = buffer_index;
543 : :
544 : : /* Adjust the pending read to cover the remaining portion, if any. */
545 : 2149407 : stream->pending_read_blocknum += nblocks;
546 : 2149407 : stream->pending_read_nblocks -= nblocks;
547 : :
548 : 2149407 : return true;
549 : : }
550 : :
551 : : /*
552 : : * Should we continue to perform look ahead? Looking ahead may allow us to
553 : : * make the pending IO larger via IO combining or to issue more read-ahead.
554 : : */
555 : : static inline bool
556 : 6213939 : read_stream_should_look_ahead(ReadStream *stream)
557 : : {
558 : : /* If the callback has signaled end-of-stream, we're done */
559 [ + + ]: 6213939 : if (stream->readahead_distance == 0)
560 : 346071 : return false;
561 : :
562 : : /* never start more IOs than our cap */
563 [ - + ]: 5867868 : if (stream->ios_in_progress >= stream->max_ios)
564 : 0 : return false;
565 : :
566 : : /*
567 : : * Allow looking further ahead if we are in the process of building a
568 : : * larger IO, the IO is not yet big enough, and we don't yet have IO in
569 : : * flight.
570 : : *
571 : : * We do so to allow building larger reads when readahead_distance is
572 : : * small (e.g. because the I/O subsystem is keeping up or
573 : : * effective_io_concurrency is small). That's a useful goal because larger
574 : : * reads are more CPU efficient than smaller reads, even if the system is
575 : : * not IO bound.
576 : : *
577 : : * The reason we do *not* do so when we already have a read prepared (i.e.
578 : : * why we check for pinned_buffers == 0) is once we are actually reading
579 : : * ahead, we don't need it:
580 : : *
581 : : * - We won't issue unnecessarily small reads as
582 : : * read_stream_should_issue_now() will return false until the IO is
583 : : * suitably sized. The issuance of the pending read will be delayed until
584 : : * enough buffers have been consumed.
585 : : *
586 : : * - If we are not reading ahead aggressively enough, future
587 : : * WaitReadBuffers() calls will return true, leading to readahead_distance
588 : : * being increased. After that more full-sized IOs can be issued.
589 : : *
590 : : * Furthermore, if we did not have the pinned_buffers == 0 condition, we
591 : : * might end up issuing I/O more aggressively than we need.
592 : : *
593 : : * Note that a return of true here can lead to exceeding the read-ahead
594 : : * limit, but we won't exceed the buffer pin limit (because pinned_buffers
595 : : * == 0 and combine_distance is capped by max_pinned_buffers).
596 : : */
597 [ + + ]: 5867868 : if (stream->pending_read_nblocks > 0 &&
598 [ + + ]: 2678380 : stream->pinned_buffers == 0 &&
599 [ + + ]: 2529039 : stream->pending_read_nblocks < stream->combine_distance)
600 : 495564 : return true;
601 : :
602 : : /*
603 : : * Don't start more read-ahead if that'd put us over the distance limit
604 : : * for doing read-ahead. As stream->readahead_distance is capped by
605 : : * max_pinned_buffers, this prevents us from looking ahead so far that it
606 : : * would put us over the pin limit.
607 : : */
608 [ + + ]: 5372304 : if (stream->pinned_buffers + stream->pending_read_nblocks >= stream->readahead_distance)
609 : 2112533 : return false;
610 : :
611 : 3259771 : return true;
612 : : }
613 : :
614 : : /*
615 : : * We don't start the pending read just because we've hit the distance limit,
616 : : * preferring to give it another chance to grow to full io_combine_limit size
617 : : * once more buffers have been consumed. But this is not desirable in all
618 : : * situations - see below.
619 : : */
620 : : static inline bool
621 : 7123926 : read_stream_should_issue_now(ReadStream *stream)
622 : : {
623 : 7123926 : int16 pending_read_nblocks = stream->pending_read_nblocks;
624 : :
625 : : /* there is no pending IO that could be issued */
626 [ + + ]: 7123926 : if (pending_read_nblocks == 0)
627 : 4582960 : return false;
628 : :
629 : : /* never start more IOs than our cap */
630 [ - + ]: 2540966 : if (stream->ios_in_progress >= stream->max_ios)
631 : 0 : return false;
632 : :
633 : : /*
634 : : * If the callback has signaled end-of-stream, start the pending read
635 : : * immediately. There is no further potential for IO combining.
636 : : */
637 [ + + ]: 2540966 : if (stream->readahead_distance == 0)
638 : 110368 : return true;
639 : :
640 : : /*
641 : : * If we've already reached combine_distance, there's no chance of growing
642 : : * the read further.
643 : : */
644 [ + + ]: 2430598 : if (pending_read_nblocks >= stream->combine_distance)
645 : 2039156 : return true;
646 : :
647 : : /*
648 : : * If we currently have no reads in flight or prepared, issue the IO once
649 : : * we are not looking ahead further. This ensures there's always at least
650 : : * one IO prepared.
651 : : */
652 [ + + ]: 391442 : if (stream->pinned_buffers == 0 &&
653 [ - + ]: 247782 : !read_stream_should_look_ahead(stream))
654 : 0 : return true;
655 : :
656 : 391442 : return false;
657 : : }
658 : :
659 : : static void
660 : 3616373 : read_stream_look_ahead(ReadStream *stream)
661 : : {
662 : : /*
663 : : * Allow amortizing the cost of submitting IO over multiple IOs. This
664 : : * requires that we don't do any operations that could lead to a deadlock
665 : : * with staged-but-unsubmitted IO. The callback needs to opt-in to being
666 : : * careful.
667 : : */
668 [ + + ]: 3616373 : if (stream->batch_mode)
669 : 2970388 : pgaio_enter_batchmode();
670 : :
671 [ + + ]: 5966157 : while (read_stream_should_look_ahead(stream))
672 : : {
673 : : BlockNumber blocknum;
674 : : int16 buffer_index;
675 : : void *per_buffer_data;
676 : :
677 [ + + ]: 3507553 : if (read_stream_should_issue_now(stream))
678 : : {
679 : 2111 : read_stream_start_pending_read(stream);
680 : 2111 : continue;
681 : : }
682 : :
683 : : /*
684 : : * See which block the callback wants next in the stream. We need to
685 : : * compute the index of the Nth block of the pending read including
686 : : * wrap-around, but we don't want to use the expensive % operator.
687 : : */
688 : 3505442 : buffer_index = stream->next_buffer_index + stream->pending_read_nblocks;
689 [ + + ]: 3505442 : if (buffer_index >= stream->queue_size)
690 : 3906 : buffer_index -= stream->queue_size;
691 : : Assert(buffer_index >= 0 && buffer_index < stream->queue_size);
692 : 3505442 : per_buffer_data = get_per_buffer_data(stream, buffer_index);
693 : 3505442 : blocknum = read_stream_get_block(stream, per_buffer_data);
694 [ + + ]: 3505442 : if (blocknum == InvalidBlockNumber)
695 : : {
696 : : /* End of stream. */
697 : 1157769 : stream->readahead_distance = 0;
698 : 1157769 : stream->combine_distance = 0;
699 : 1157769 : break;
700 : : }
701 : :
702 : : /* Can we merge it with the pending read? */
703 [ + + ]: 2347673 : if (stream->pending_read_nblocks > 0 &&
704 [ + + ]: 269010 : stream->pending_read_blocknum + stream->pending_read_nblocks == blocknum)
705 : : {
706 : 268951 : stream->pending_read_nblocks++;
707 : 268951 : continue;
708 : : }
709 : :
710 : : /* We have to start the pending read before we can build another. */
711 [ + + ]: 2078790 : while (stream->pending_read_nblocks > 0)
712 : : {
713 [ + - ]: 68 : if (!read_stream_start_pending_read(stream) ||
714 [ - + ]: 68 : stream->ios_in_progress == stream->max_ios)
715 : : {
716 : : /* We've hit the buffer or I/O limit. Rewind and stop here. */
717 : 0 : read_stream_unget_block(stream, blocknum);
718 [ # # ]: 0 : if (stream->batch_mode)
719 : 0 : pgaio_exit_batchmode();
720 : 0 : return;
721 : : }
722 : : }
723 : :
724 : : /* This is the start of a new pending read. */
725 : 2078722 : stream->pending_read_blocknum = blocknum;
726 : 2078722 : stream->pending_read_nblocks = 1;
727 : : }
728 : :
729 : : /*
730 : : * Check if the pending read should be issued now, or if we should give it
731 : : * another chance to grow to the full size.
732 : : *
733 : : * Note that the pending read can exceed the distance goal, if the latter
734 : : * was reduced after hitting the per-backend buffer limit.
735 : : */
736 [ + + ]: 3616373 : if (read_stream_should_issue_now(stream))
737 : 2147413 : read_stream_start_pending_read(stream);
738 : :
739 : : /*
740 : : * There should always be something pinned when we leave this function,
741 : : * whether started by this call or not, unless we've hit the end of the
742 : : * stream. In the worst case we can always make progress one buffer at a
743 : : * time.
744 : : */
745 : : Assert(stream->pinned_buffers > 0 || stream->readahead_distance == 0);
746 : :
747 [ + + ]: 3616365 : if (stream->batch_mode)
748 : 2970380 : pgaio_exit_batchmode();
749 : : }
750 : :
751 : : /*
752 : : * Create a new read stream object that can be used to perform the equivalent
753 : : * of a series of ReadBuffer() calls for one fork of one relation.
754 : : * Internally, it generates larger vectored reads where possible by looking
755 : : * ahead. The callback should return block numbers or InvalidBlockNumber to
756 : : * signal end-of-stream, and if per_buffer_data_size is non-zero, it may also
757 : : * write extra data for each block into the space provided to it. It will
758 : : * also receive callback_private_data for its own purposes.
759 : : */
760 : : static ReadStream *
761 : 667796 : read_stream_begin_impl(int flags,
762 : : BufferAccessStrategy strategy,
763 : : Relation rel,
764 : : SMgrRelation smgr,
765 : : char persistence,
766 : : ForkNumber forknum,
767 : : ReadStreamBlockNumberCB callback,
768 : : void *callback_private_data,
769 : : size_t per_buffer_data_size)
770 : : {
771 : : ReadStream *stream;
772 : : size_t size;
773 : : int16 queue_size;
774 : : int16 queue_overflow;
775 : : int max_ios;
776 : : int strategy_pin_limit;
777 : : uint32 max_pinned_buffers;
778 : : uint32 max_possible_buffer_limit;
779 : : Oid tablespace_id;
780 : :
781 : : /*
782 : : * Reject attempts to read non-local temporary relations; we would be
783 : : * likely to get wrong data since we have no visibility into the owning
784 : : * session's local buffers.
785 : : */
786 [ + + + + : 667796 : if (rel && RELATION_IS_OTHER_TEMP(rel))
+ + ]
787 [ + - ]: 5 : ereport(ERROR,
788 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
789 : : errmsg("cannot access temporary tables of other sessions")));
790 : :
791 : : /*
792 : : * Decide how many I/Os we will allow to run at the same time. This
793 : : * number also affects how far we look ahead for opportunities to start
794 : : * more I/Os.
795 : : */
796 : 667791 : tablespace_id = smgr->smgr_rlocator.locator.spcOid;
797 [ + + + + ]: 667791 : if (!OidIsValid(MyDatabaseId) ||
798 [ + + + + ]: 783480 : (rel && IsCatalogRelation(rel)) ||
799 : 200361 : IsCatalogRelationOid(smgr->smgr_rlocator.locator.relNumber))
800 : : {
801 : : /*
802 : : * Avoid circularity while trying to look up tablespace settings or
803 : : * before spccache.c is ready.
804 : : */
805 : 534989 : max_ios = effective_io_concurrency;
806 : : }
807 [ + + ]: 132802 : else if (flags & READ_STREAM_MAINTENANCE)
808 : 19702 : max_ios = get_tablespace_maintenance_io_concurrency(tablespace_id);
809 : : else
810 : 113100 : max_ios = get_tablespace_io_concurrency(tablespace_id);
811 : :
812 : : /* Cap to INT16_MAX to avoid overflowing below */
813 : 667791 : max_ios = Min(max_ios, PG_INT16_MAX);
814 : :
815 : : /*
816 : : * If starting a multi-block I/O near the end of the queue, we might
817 : : * temporarily need extra space for overflowing buffers before they are
818 : : * moved to regular circular position. This is the maximum extra space we
819 : : * could need.
820 : : */
821 : 667791 : queue_overflow = io_combine_limit - 1;
822 : :
823 : : /*
824 : : * Choose the maximum number of buffers we're prepared to pin. We try to
825 : : * pin fewer if we can, though. We add one so that we can make progress
826 : : * even if max_ios is set to 0 (see also further down). For max_ios > 0,
827 : : * this also allows an extra full I/O's worth of buffers: after an I/O
828 : : * finishes we don't want to have to wait for its buffers to be consumed
829 : : * before starting a new one.
830 : : *
831 : : * Be careful not to allow int16 to overflow. That is possible with the
832 : : * current GUC range limits, so this is an artificial limit of ~32k
833 : : * buffers and we'd need to adjust the types to exceed that. We also have
834 : : * to allow for the spare entry and the overflow space.
835 : : */
836 : 667791 : max_pinned_buffers = (max_ios + 1) * io_combine_limit;
837 : 667791 : max_pinned_buffers = Min(max_pinned_buffers,
838 : : PG_INT16_MAX - queue_overflow - 1);
839 : :
840 : : /* Give the strategy a chance to limit the number of buffers we pin. */
841 : 667791 : strategy_pin_limit = GetAccessStrategyPinLimit(strategy);
842 : 667791 : max_pinned_buffers = Min(strategy_pin_limit, max_pinned_buffers);
843 : :
844 : : /*
845 : : * Also limit our queue to the maximum number of pins we could ever be
846 : : * allowed to acquire according to the buffer manager. We may not really
847 : : * be able to use them all due to other pins held by this backend, but
848 : : * we'll check that later in read_stream_start_pending_read().
849 : : */
850 [ + + ]: 667791 : if (SmgrIsTemp(smgr))
851 : 9724 : max_possible_buffer_limit = GetLocalPinLimit();
852 : : else
853 : 658067 : max_possible_buffer_limit = GetPinLimit();
854 : 667791 : max_pinned_buffers = Min(max_pinned_buffers, max_possible_buffer_limit);
855 : :
856 : : /*
857 : : * The limit might be zero on a system configured with too few buffers for
858 : : * the number of connections. We need at least one to make progress.
859 : : */
860 [ + + ]: 667791 : max_pinned_buffers = Max(1, max_pinned_buffers);
861 : :
862 : : /*
863 : : * We need one extra entry for buffers and per-buffer data, because users
864 : : * of per-buffer data have access to the object until the next call to
865 : : * read_stream_next_buffer(), so we need a gap between the head and tail
866 : : * of the queue so that we don't clobber it.
867 : : */
868 : 667791 : queue_size = max_pinned_buffers + 1;
869 : :
870 : : /*
871 : : * Allocate the object, the buffers, the ios and per_buffer_data space in
872 : : * one big chunk. Though we have queue_size buffers, we want to be able
873 : : * to assume that all the buffers for a single read are contiguous (i.e.
874 : : * don't wrap around halfway through), so we allow temporary overflows of
875 : : * up to the maximum possible overflow size.
876 : : */
877 : 667791 : size = offsetof(ReadStream, buffers);
878 : 667791 : size += sizeof(Buffer) * (queue_size + queue_overflow);
879 [ + + ]: 667791 : size += sizeof(InProgressIO) * Max(1, max_ios);
880 : 667791 : size += per_buffer_data_size * queue_size;
881 : 667791 : size += MAXIMUM_ALIGNOF * 2;
882 : 667791 : stream = (ReadStream *) palloc(size);
883 : 667791 : memset(stream, 0, offsetof(ReadStream, buffers));
884 : 667791 : stream->ios = (InProgressIO *)
885 : 667791 : MAXALIGN(&stream->buffers[queue_size + queue_overflow]);
886 [ + + ]: 667791 : if (per_buffer_data_size > 0)
887 : 142256 : stream->per_buffer_data = (void *)
888 [ + + ]: 142256 : MAXALIGN(&stream->ios[Max(1, max_ios)]);
889 : :
890 : 667791 : stream->sync_mode = io_method == IOMETHOD_SYNC;
891 : 667791 : stream->batch_mode = flags & READ_STREAM_USE_BATCHING;
892 : :
893 : : #ifdef USE_PREFETCH
894 : :
895 : : /*
896 : : * Read-ahead advice simulating asynchronous I/O with synchronous calls.
897 : : * Issue advice only if AIO is not used, direct I/O isn't enabled, the
898 : : * caller hasn't promised sequential access (overriding our detection
899 : : * heuristics), and max_ios hasn't been set to zero.
900 : : */
901 [ + + ]: 667791 : if (stream->sync_mode &&
902 [ + - ]: 2967 : (io_direct_flags & IO_DIRECT_DATA) == 0 &&
903 [ + + + - ]: 2967 : (flags & READ_STREAM_SEQUENTIAL) == 0 &&
904 : : max_ios > 0)
905 : 702 : stream->advice_enabled = true;
906 : : #endif
907 : :
908 : : /*
909 : : * Setting max_ios to zero disables AIO and advice-based pseudo AIO, but
910 : : * we still need to allocate space to combine and run one I/O. Bump it up
911 : : * to one, and remember to ask for synchronous I/O only.
912 : : */
913 [ + + ]: 667791 : if (max_ios == 0)
914 : : {
915 : 7 : max_ios = 1;
916 : 7 : stream->read_buffers_flags = READ_BUFFERS_SYNCHRONOUSLY;
917 : : }
918 : :
919 : : /*
920 : : * Capture stable values for these two GUC-derived numbers for the
921 : : * lifetime of this stream, so we don't have to worry about the GUCs
922 : : * changing underneath us beyond this point.
923 : : */
924 : 667791 : stream->max_ios = max_ios;
925 : 667791 : stream->io_combine_limit = io_combine_limit;
926 : :
927 : 667791 : stream->per_buffer_data_size = per_buffer_data_size;
928 : 667791 : stream->max_pinned_buffers = max_pinned_buffers;
929 : 667791 : stream->queue_size = queue_size;
930 : 667791 : stream->callback = callback;
931 : 667791 : stream->callback_private_data = callback_private_data;
932 : 667791 : stream->buffered_blocknum = InvalidBlockNumber;
933 : 667791 : stream->seq_blocknum = InvalidBlockNumber;
934 : 667791 : stream->seq_until_processed = InvalidBlockNumber;
935 : 667791 : stream->temporary = SmgrIsTemp(smgr);
936 : 667791 : stream->distance_decay_holdoff = 0;
937 : :
938 : : /*
939 : : * Skip the initial ramp-up phase if the caller says we're going to be
940 : : * reading the whole relation. This way we start out assuming we'll be
941 : : * doing full io_combine_limit sized reads.
942 : : */
943 [ + + ]: 667791 : if (flags & READ_STREAM_FULL)
944 : : {
945 : 79240 : stream->readahead_distance = Min(max_pinned_buffers, stream->io_combine_limit);
946 : 79240 : stream->combine_distance = Min(max_pinned_buffers, stream->io_combine_limit);
947 : : }
948 : : else
949 : : {
950 : 588551 : stream->readahead_distance = 1;
951 : 588551 : stream->combine_distance = 1;
952 : : }
953 : 667791 : stream->resume_readahead_distance = stream->readahead_distance;
954 : 667791 : stream->resume_combine_distance = stream->combine_distance;
955 : :
956 : : /*
957 : : * Since we always access the same relation, we can initialize parts of
958 : : * the ReadBuffersOperation objects and leave them that way, to avoid
959 : : * wasting CPU cycles writing to them for each read.
960 : : */
961 [ + + ]: 11381038 : for (int i = 0; i < max_ios; ++i)
962 : : {
963 : 10713247 : stream->ios[i].op.rel = rel;
964 : 10713247 : stream->ios[i].op.smgr = smgr;
965 : 10713247 : stream->ios[i].op.persistence = persistence;
966 : 10713247 : stream->ios[i].op.forknum = forknum;
967 : 10713247 : stream->ios[i].op.strategy = strategy;
968 : : }
969 : :
970 : 667791 : return stream;
971 : : }
972 : :
973 : : /*
974 : : * Create a new read stream for reading a relation.
975 : : * See read_stream_begin_impl() for the detailed explanation.
976 : : */
977 : : ReadStream *
978 : 595387 : read_stream_begin_relation(int flags,
979 : : BufferAccessStrategy strategy,
980 : : Relation rel,
981 : : ForkNumber forknum,
982 : : ReadStreamBlockNumberCB callback,
983 : : void *callback_private_data,
984 : : size_t per_buffer_data_size)
985 : : {
986 : 595387 : return read_stream_begin_impl(flags,
987 : : strategy,
988 : : rel,
989 : : RelationGetSmgr(rel),
990 : 595387 : rel->rd_rel->relpersistence,
991 : : forknum,
992 : : callback,
993 : : callback_private_data,
994 : : per_buffer_data_size);
995 : : }
996 : :
997 : : /*
998 : : * Create a new read stream for reading a SMgr relation.
999 : : * See read_stream_begin_impl() for the detailed explanation.
1000 : : */
1001 : : ReadStream *
1002 : 72409 : read_stream_begin_smgr_relation(int flags,
1003 : : BufferAccessStrategy strategy,
1004 : : SMgrRelation smgr,
1005 : : char smgr_persistence,
1006 : : ForkNumber forknum,
1007 : : ReadStreamBlockNumberCB callback,
1008 : : void *callback_private_data,
1009 : : size_t per_buffer_data_size)
1010 : : {
1011 : 72409 : return read_stream_begin_impl(flags,
1012 : : strategy,
1013 : : NULL,
1014 : : smgr,
1015 : : smgr_persistence,
1016 : : forknum,
1017 : : callback,
1018 : : callback_private_data,
1019 : : per_buffer_data_size);
1020 : : }
1021 : :
1022 : : /*
1023 : : * Pull one pinned buffer out of a stream. Each call returns successive
1024 : : * blocks in the order specified by the callback. If per_buffer_data_size was
1025 : : * set to a non-zero size, *per_buffer_data receives a pointer to the extra
1026 : : * per-buffer data that the callback had a chance to populate, which remains
1027 : : * valid until the next call to read_stream_next_buffer(). When the stream
1028 : : * runs out of data, InvalidBuffer is returned. The caller may decide to end
1029 : : * the stream early at any time by calling read_stream_end().
1030 : : */
1031 : : Buffer
1032 : 7112610 : read_stream_next_buffer(ReadStream *stream, void **per_buffer_data)
1033 : : {
1034 : : Buffer buffer;
1035 : : int16 oldest_buffer_index;
1036 : :
1037 : : #ifndef READ_STREAM_DISABLE_FAST_PATH
1038 : :
1039 : : /*
1040 : : * A fast path for all-cached scans. This is the same as the usual
1041 : : * algorithm, but it is specialized for no I/O and no per-buffer data, so
1042 : : * we can skip the queue management code, stay in the same buffer slot and
1043 : : * use singular StartReadBuffer().
1044 : : */
1045 [ + + ]: 7112610 : if (likely(stream->fast_path))
1046 : : {
1047 : : BlockNumber next_blocknum;
1048 : :
1049 : : /* Fast path assumptions. */
1050 : : Assert(stream->ios_in_progress == 0);
1051 : : Assert(stream->forwarded_buffers == 0);
1052 : : Assert(stream->pinned_buffers == 1);
1053 : : Assert(stream->readahead_distance == 1);
1054 : : Assert(stream->combine_distance == 1);
1055 : : Assert(stream->pending_read_nblocks == 0);
1056 : : Assert(stream->per_buffer_data_size == 0);
1057 : : Assert(stream->initialized_buffers > stream->oldest_buffer_index);
1058 : :
1059 : : /* We're going to return the buffer we pinned last time. */
1060 : 2388298 : oldest_buffer_index = stream->oldest_buffer_index;
1061 : : Assert((oldest_buffer_index + 1) % stream->queue_size ==
1062 : : stream->next_buffer_index);
1063 : 2388298 : buffer = stream->buffers[oldest_buffer_index];
1064 : : Assert(buffer != InvalidBuffer);
1065 : :
1066 : : /* Choose the next block to pin. */
1067 : 2388298 : next_blocknum = read_stream_get_block(stream, NULL);
1068 : :
1069 [ + + ]: 2388298 : if (likely(next_blocknum != InvalidBlockNumber))
1070 : : {
1071 : 2283280 : int flags = stream->read_buffers_flags;
1072 : :
1073 [ + + ]: 2283280 : if (stream->advice_enabled)
1074 : 543 : flags |= READ_BUFFERS_ISSUE_ADVICE;
1075 : :
1076 : : /*
1077 : : * While in fast-path, execute any IO that we might encounter
1078 : : * synchronously. Because we are, right now, only looking one
1079 : : * block ahead, dispatching any occasional IO to workers would
1080 : : * have the overhead of dispatching to workers, without any
1081 : : * realistic chance of the IO completing before we need it. We
1082 : : * will switch to non-synchronous IO after this.
1083 : : *
1084 : : * Arguably we should do so only for worker, as there's far less
1085 : : * dispatch overhead with io_uring. However, tests so far have not
1086 : : * shown a clear downside and additional io_method awareness here
1087 : : * seems not great from an abstraction POV.
1088 : : */
1089 : 2283280 : flags |= READ_BUFFERS_SYNCHRONOUSLY;
1090 : :
1091 : : /*
1092 : : * Pin a buffer for the next call. Same buffer entry, and
1093 : : * arbitrary I/O entry (they're all free). We don't have to
1094 : : * adjust pinned_buffers because we're transferring one to caller
1095 : : * but pinning one more.
1096 : : *
1097 : : * In the fast path we don't need to check the pin limit. We're
1098 : : * always allowed at least one pin so that progress can be made,
1099 : : * and that's all we need here. Although two pins are momentarily
1100 : : * held at the same time, the model used here is that the stream
1101 : : * holds only one, and the other now belongs to the caller.
1102 : : */
1103 [ + + ]: 2283280 : if (likely(!StartReadBuffer(&stream->ios[0].op,
1104 : : &stream->buffers[oldest_buffer_index],
1105 : : next_blocknum,
1106 : : flags)))
1107 : : {
1108 : : /* Fast return. */
1109 : 2270962 : read_stream_count_prefetch(stream);
1110 : 2270962 : return buffer;
1111 : : }
1112 : :
1113 : : /* Next call must wait for I/O for the newly pinned buffer. */
1114 : 12318 : stream->oldest_io_index = 0;
1115 : 12318 : stream->next_io_index = stream->max_ios > 1 ? 1 : 0;
1116 : 12318 : stream->ios_in_progress = 1;
1117 : 12318 : stream->ios[0].buffer_index = oldest_buffer_index;
1118 : 12318 : stream->seq_blocknum = next_blocknum + 1;
1119 : :
1120 : : /*
1121 : : * XXX: It might be worth triggering additional read-ahead here,
1122 : : * to avoid having to effectively do another synchronous IO for
1123 : : * the next block (if it were also a miss).
1124 : : */
1125 : :
1126 : : /* update I/O stats */
1127 : 12318 : read_stream_count_io(stream, 1, stream->ios_in_progress);
1128 : :
1129 : : /* update prefetch distance */
1130 : 12318 : read_stream_count_prefetch(stream);
1131 : : }
1132 : : else
1133 : : {
1134 : : /* No more blocks, end of stream. */
1135 : 105018 : stream->readahead_distance = 0;
1136 : 105018 : stream->combine_distance = 0;
1137 : 105018 : stream->oldest_buffer_index = stream->next_buffer_index;
1138 : 105018 : stream->pinned_buffers = 0;
1139 : 105018 : stream->buffers[oldest_buffer_index] = InvalidBuffer;
1140 : : }
1141 : :
1142 : 117336 : stream->fast_path = false;
1143 : 117336 : return buffer;
1144 : : }
1145 : : #endif
1146 : :
1147 [ + + ]: 4724312 : if (unlikely(stream->pinned_buffers == 0))
1148 : : {
1149 : : Assert(stream->oldest_buffer_index == stream->next_buffer_index);
1150 : :
1151 : : /* End of stream reached? */
1152 [ + + ]: 3221226 : if (stream->readahead_distance == 0)
1153 : 1836390 : return InvalidBuffer;
1154 : :
1155 : : /*
1156 : : * The usual order of operations is that we look ahead at the bottom
1157 : : * of this function after potentially finishing an I/O and making
1158 : : * space for more, but if we're just starting up we'll need to crank
1159 : : * the handle to get started.
1160 : : */
1161 : 1384836 : read_stream_look_ahead(stream);
1162 : :
1163 : : /* End of stream reached? */
1164 [ + + ]: 1384836 : if (stream->pinned_buffers == 0)
1165 : : {
1166 : : Assert(stream->readahead_distance == 0);
1167 : 656363 : return InvalidBuffer;
1168 : : }
1169 : : }
1170 : :
1171 : : /* Grab the oldest pinned buffer and associated per-buffer data. */
1172 : : Assert(stream->pinned_buffers > 0);
1173 : 2231559 : oldest_buffer_index = stream->oldest_buffer_index;
1174 : : Assert(oldest_buffer_index >= 0 &&
1175 : : oldest_buffer_index < stream->queue_size);
1176 : 2231559 : buffer = stream->buffers[oldest_buffer_index];
1177 [ + + ]: 2231559 : if (per_buffer_data)
1178 : 780739 : *per_buffer_data = get_per_buffer_data(stream, oldest_buffer_index);
1179 : :
1180 : : Assert(BufferIsValid(buffer));
1181 : :
1182 : : /* Do we have to wait for an associated I/O first? */
1183 [ + + ]: 2231559 : if (stream->ios_in_progress > 0 &&
1184 [ + + ]: 658992 : stream->ios[stream->oldest_io_index].buffer_index == oldest_buffer_index)
1185 : : {
1186 : 605051 : int16 io_index = stream->oldest_io_index;
1187 : : bool needed_wait;
1188 : :
1189 : : /* Sanity check that we still agree on the buffers. */
1190 : : Assert(stream->ios[io_index].op.buffers ==
1191 : : &stream->buffers[oldest_buffer_index]);
1192 : :
1193 : 605051 : needed_wait = WaitReadBuffers(&stream->ios[io_index].op);
1194 : :
1195 : : Assert(stream->ios_in_progress > 0);
1196 : 605029 : stream->ios_in_progress--;
1197 [ + + ]: 605029 : if (++stream->oldest_io_index == stream->max_ios)
1198 : 24159 : stream->oldest_io_index = 0;
1199 : :
1200 : : /*
1201 : : * If the IO was executed synchronously, we will never see
1202 : : * WaitReadBuffers() block. Treat it as if it did block. This is
1203 : : * particularly crucial when effective_io_concurrency=0 is used, as
1204 : : * all IO will be synchronous. Without treating synchronous IO as
1205 : : * having waited, we'd never allow the distance to get large enough to
1206 : : * allow for IO combining, resulting in bad performance.
1207 : : */
1208 [ + + ]: 605029 : if (stream->ios[io_index].op.flags & READ_BUFFERS_SYNCHRONOUSLY)
1209 : 12792 : needed_wait = true;
1210 : :
1211 : : /* Count it as a wait if we need to wait for IO */
1212 [ + + ]: 605029 : if (needed_wait)
1213 : 298769 : read_stream_count_wait(stream);
1214 : :
1215 : : /*
1216 : : * Have the read-ahead distance ramp up rapidly after we needed to
1217 : : * wait for IO. We only increase the read-ahead-distance when we
1218 : : * needed to wait, to avoid increasing the distance further than
1219 : : * necessary, as looking ahead too far can be costly, both due to the
1220 : : * cost of unnecessarily pinning many buffers and due to doing IOs
1221 : : * that may never be consumed if the stream is ended/reset before
1222 : : * completion.
1223 : : *
1224 : : * If we did not need to wait, the current distance was evidently
1225 : : * sufficient.
1226 : : *
1227 : : * NB: Must not increase the distance if we already reached the end of
1228 : : * the stream, as stream->readahead_distance == 0 is used to keep
1229 : : * track of having reached the end.
1230 : : */
1231 [ + + + + ]: 605029 : if (stream->readahead_distance > 0 && needed_wait)
1232 : : {
1233 : : /* wider temporary value, due to overflow risk */
1234 : : int32 readahead_distance;
1235 : :
1236 : 270182 : readahead_distance = stream->readahead_distance * 2;
1237 : 270182 : readahead_distance = Min(readahead_distance, stream->max_pinned_buffers);
1238 : 270182 : stream->readahead_distance = readahead_distance;
1239 : : }
1240 : :
1241 : : /*
1242 : : * As we needed IO, prevent distances from being reduced within our
1243 : : * maximum look-ahead window. This avoids collapsing distances too
1244 : : * quickly in workloads where most of the required blocks are cached,
1245 : : * but where the remaining IOs are a sufficient enough factor to cause
1246 : : * a substantial slowdown if executed synchronously.
1247 : : *
1248 : : * There are valid arguments for preventing decay for max_ios or for
1249 : : * max_pinned_buffers. But the argument for max_pinned_buffers seems
1250 : : * clearer - if we can't see any misses within the maximum look-ahead
1251 : : * distance, we can't do any useful read-ahead.
1252 : : */
1253 : 605029 : stream->distance_decay_holdoff = stream->max_pinned_buffers;
1254 : :
1255 : : /*
1256 : : * Whether we needed to wait or not, allow for more IO combining if we
1257 : : * needed to do IO. The reason to do so independent of needing to wait
1258 : : * is that when the data is resident in the kernel page cache, IO
1259 : : * combining reduces the syscall / dispatch overhead, making it
1260 : : * worthwhile regardless of needing to wait.
1261 : : *
1262 : : * It is also important with io_uring as it will never signal the need
1263 : : * to wait for reads if all the data is in the page cache. There are
1264 : : * heuristics to deal with that in method_io_uring.c, but they only
1265 : : * work when the IO gets large enough.
1266 : : */
1267 [ + + ]: 605029 : if (stream->combine_distance > 0 &&
1268 [ + + ]: 554612 : stream->combine_distance < stream->io_combine_limit)
1269 : : {
1270 : : /* wider temporary value, due to overflow risk */
1271 : : int32 combine_distance;
1272 : :
1273 : 546113 : combine_distance = stream->combine_distance * 2;
1274 : 546113 : combine_distance = Min(combine_distance, stream->io_combine_limit);
1275 : 546113 : combine_distance = Min(combine_distance, stream->max_pinned_buffers);
1276 : 546113 : stream->combine_distance = combine_distance;
1277 : : }
1278 : :
1279 : : /*
1280 : : * If we've reached the first block of a sequential region we're
1281 : : * issuing advice for, cancel that until the next jump. The kernel
1282 : : * will see the sequential preadv() pattern starting here.
1283 : : */
1284 [ + + ]: 605029 : if (stream->advice_enabled &&
1285 [ + + ]: 305 : stream->ios[io_index].op.blocknum == stream->seq_until_processed)
1286 : 263 : stream->seq_until_processed = InvalidBlockNumber;
1287 : : }
1288 : :
1289 : : /*
1290 : : * We must zap this queue entry, or else it would appear as a forwarded
1291 : : * buffer. If it's potentially in the overflow zone (ie from a
1292 : : * multi-block I/O that wrapped around the queue), also zap the copy.
1293 : : */
1294 : 2231537 : stream->buffers[oldest_buffer_index] = InvalidBuffer;
1295 [ + + ]: 2231537 : if (oldest_buffer_index < stream->io_combine_limit - 1)
1296 : 1628130 : stream->buffers[stream->queue_size + oldest_buffer_index] =
1297 : : InvalidBuffer;
1298 : :
1299 : : #if defined(CLOBBER_FREED_MEMORY) || defined(USE_VALGRIND)
1300 : :
1301 : : /*
1302 : : * The caller will get access to the per-buffer data, until the next call.
1303 : : * We wipe the one before, which is never occupied because queue_size
1304 : : * allowed one extra element. This will hopefully trip up client code
1305 : : * that is holding a dangling pointer to it.
1306 : : */
1307 : : if (stream->per_buffer_data)
1308 : : {
1309 : : void *prev_per_buffer_data;
1310 : :
1311 : : prev_per_buffer_data = get_per_buffer_data(stream,
1312 : : oldest_buffer_index == 0 ?
1313 : : stream->queue_size - 1 :
1314 : : oldest_buffer_index - 1);
1315 : :
1316 : : #if defined(CLOBBER_FREED_MEMORY)
1317 : : /* This also tells Valgrind the memory is "noaccess". */
1318 : : wipe_mem(prev_per_buffer_data, stream->per_buffer_data_size);
1319 : : #elif defined(USE_VALGRIND)
1320 : : /* Tell it ourselves. */
1321 : : VALGRIND_MAKE_MEM_NOACCESS(prev_per_buffer_data,
1322 : : stream->per_buffer_data_size);
1323 : : #endif
1324 : : }
1325 : : #endif
1326 : :
1327 : 2231537 : read_stream_count_prefetch(stream);
1328 : :
1329 : : /* Pin transferred to caller. */
1330 : : Assert(stream->pinned_buffers > 0);
1331 : 2231537 : stream->pinned_buffers--;
1332 : :
1333 : : /* Advance oldest buffer, with wrap-around. */
1334 : 2231537 : stream->oldest_buffer_index++;
1335 [ + + ]: 2231537 : if (stream->oldest_buffer_index == stream->queue_size)
1336 : 293019 : stream->oldest_buffer_index = 0;
1337 : :
1338 : : /* Prepare for the next call. */
1339 : 2231537 : read_stream_look_ahead(stream);
1340 : :
1341 : : #ifndef READ_STREAM_DISABLE_FAST_PATH
1342 : : /* See if we can take the fast path for all-cached scans next time. */
1343 [ + + ]: 2231529 : if (stream->ios_in_progress == 0 &&
1344 [ + + ]: 1666955 : stream->forwarded_buffers == 0 &&
1345 [ + + ]: 1664398 : stream->pinned_buffers == 1 &&
1346 [ + + ]: 939670 : stream->readahead_distance == 1 &&
1347 [ + + ]: 846789 : stream->combine_distance == 1 &&
1348 [ + + ]: 843994 : stream->pending_read_nblocks == 0 &&
1349 [ + + ]: 842878 : stream->per_buffer_data_size == 0)
1350 : : {
1351 : : /*
1352 : : * The fast path spins on one buffer entry repeatedly instead of
1353 : : * rotating through the whole queue and clearing the entries behind
1354 : : * it. If the buffer it starts with happened to be forwarded between
1355 : : * StartReadBuffers() calls and also wrapped around the circular queue
1356 : : * partway through, then a copy also exists in the overflow zone, and
1357 : : * it won't clear it out as the regular path would. Do that now, so
1358 : : * it doesn't need code for that.
1359 : : */
1360 [ + + ]: 231669 : if (stream->oldest_buffer_index < stream->io_combine_limit - 1)
1361 : 229816 : stream->buffers[stream->queue_size + stream->oldest_buffer_index] =
1362 : : InvalidBuffer;
1363 : :
1364 : 231669 : stream->fast_path = true;
1365 : : }
1366 : : #endif
1367 : :
1368 : 2231529 : return buffer;
1369 : : }
1370 : :
1371 : : /*
1372 : : * Transitional support for code that would like to perform or skip reads
1373 : : * itself, without using the stream. Returns, and consumes, the next block
1374 : : * number that would be read by the stream's look-ahead algorithm, or
1375 : : * InvalidBlockNumber if the end of the stream is reached. Also reports the
1376 : : * strategy that would be used to read it.
1377 : : */
1378 : : BlockNumber
1379 : 0 : read_stream_next_block(ReadStream *stream, BufferAccessStrategy *strategy)
1380 : : {
1381 : 0 : *strategy = stream->ios[0].op.strategy;
1382 : 0 : return read_stream_get_block(stream, NULL);
1383 : : }
1384 : :
1385 : : /*
1386 : : * Temporarily stop consuming block numbers from the block number callback.
1387 : : * If called inside the block number callback, its return value should be
1388 : : * returned by the callback.
1389 : : */
1390 : : BlockNumber
1391 : 0 : read_stream_pause(ReadStream *stream)
1392 : : {
1393 : 0 : stream->resume_readahead_distance = stream->readahead_distance;
1394 : 0 : stream->resume_combine_distance = stream->combine_distance;
1395 : 0 : stream->readahead_distance = 0;
1396 : 0 : stream->combine_distance = 0;
1397 : 0 : return InvalidBlockNumber;
1398 : : }
1399 : :
1400 : : /*
1401 : : * Resume looking ahead after the block number callback reported
1402 : : * end-of-stream. This is useful for streams of self-referential blocks, after
1403 : : * a buffer needed to be consumed and examined to find more block numbers.
1404 : : */
1405 : : void
1406 : 0 : read_stream_resume(ReadStream *stream)
1407 : : {
1408 : 0 : stream->readahead_distance = stream->resume_readahead_distance;
1409 : 0 : stream->combine_distance = stream->resume_combine_distance;
1410 : 0 : }
1411 : :
1412 : : /*
1413 : : * Stop using a buffer access strategy for reads from this stream.
1414 : : *
1415 : : * This clears the strategy for all of the stream's ReadBuffersOperations,
1416 : : * including those with in-progress IOs. The completion of an IO whose
1417 : : * strategy was cleared while it was in flight may have a small amount of its
1418 : : * read time attributed to IOCONTEXT_NORMAL instead of the strategy's
1419 : : * IOContext, because WaitReadBuffers() derives the IOContext from the (now
1420 : : * cleared) strategy. This is bounded by the stream's look-ahead window and
1421 : : * happens at most once, when the strategy is first cleared, so it is not worth
1422 : : * the complexity of preserving the original IOContext for those IOs.
1423 : : *
1424 : : * Note that the caller is responsible for freeing the strategy's memory.
1425 : : */
1426 : : void
1427 : 27014 : read_stream_clear_strategy(ReadStream *stream)
1428 : : {
1429 [ + + ]: 459238 : for (int i = 0; i < stream->max_ios; ++i)
1430 : 432224 : stream->ios[i].op.strategy = NULL;
1431 : 27014 : }
1432 : :
1433 : : /*
1434 : : * Reset a read stream by releasing any queued up buffers, allowing the stream
1435 : : * to be used again for different blocks. This can be used to clear an
1436 : : * end-of-stream condition and start again, or to throw away blocks that were
1437 : : * speculatively read and read some different blocks instead.
1438 : : */
1439 : : void
1440 : 1386247 : read_stream_reset(ReadStream *stream)
1441 : : {
1442 : : int16 index;
1443 : : Buffer buffer;
1444 : :
1445 : : /* Stop looking ahead. */
1446 : 1386247 : stream->readahead_distance = 0;
1447 : 1386247 : stream->combine_distance = 0;
1448 : :
1449 : : /* Forget pending reads. */
1450 : 1386247 : stream->pending_read_nblocks = 0;
1451 : :
1452 : : /* Forget buffered block number and fast path state. */
1453 : 1386247 : stream->buffered_blocknum = InvalidBlockNumber;
1454 : 1386247 : stream->fast_path = false;
1455 : :
1456 : : /* Unpin anything that wasn't consumed. */
1457 [ + + ]: 1521581 : while ((buffer = read_stream_next_buffer(stream, NULL)) != InvalidBuffer)
1458 : 135334 : ReleaseBuffer(buffer);
1459 : :
1460 : : /* Unpin any unused forwarded buffers. */
1461 : 1386247 : index = stream->next_buffer_index;
1462 [ + + ]: 1386247 : while (index < stream->initialized_buffers &&
1463 [ - + ]: 227415 : (buffer = stream->buffers[index]) != InvalidBuffer)
1464 : : {
1465 : : Assert(stream->forwarded_buffers > 0);
1466 : 0 : stream->forwarded_buffers--;
1467 : 0 : ReleaseBuffer(buffer);
1468 : :
1469 : 0 : stream->buffers[index] = InvalidBuffer;
1470 [ # # ]: 0 : if (index < stream->io_combine_limit - 1)
1471 : 0 : stream->buffers[stream->queue_size + index] = InvalidBuffer;
1472 : :
1473 [ # # ]: 0 : if (++index == stream->queue_size)
1474 : 0 : index = 0;
1475 : : }
1476 : :
1477 : : Assert(stream->forwarded_buffers == 0);
1478 : : Assert(stream->pinned_buffers == 0);
1479 : : Assert(stream->ios_in_progress == 0);
1480 : :
1481 : : /* Start off assuming data is cached. */
1482 : 1386247 : stream->readahead_distance = 1;
1483 : 1386247 : stream->combine_distance = 1;
1484 : 1386247 : stream->resume_readahead_distance = stream->readahead_distance;
1485 : 1386247 : stream->resume_combine_distance = stream->combine_distance;
1486 : 1386247 : stream->distance_decay_holdoff = 0;
1487 : 1386247 : }
1488 : :
1489 : : /*
1490 : : * Release and free a read stream.
1491 : : */
1492 : : void
1493 : 664305 : read_stream_end(ReadStream *stream)
1494 : : {
1495 : 664305 : read_stream_reset(stream);
1496 : 664305 : pfree(stream);
1497 : 664305 : }
|