Debian Codegraph @

src/backend/storage/smgr/md.c

raw
1 /*-------------------------------------------------------------------------
2 *
3 * md.c
4 * This code manages relations that reside on magnetic disk.
5 *
6 * Or at least, that was what the Berkeley folk had in mind when they named
7 * this file. In reality, what this code provides is an interface from
8 * the smgr API to Unix-like filesystem APIs, so it will work with any type
9 * of device for which the operating system provides filesystem support.
10 * It doesn't matter whether the bits are on spinning rust or some other
11 * storage technology.
12 *
13 * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
14 * Portions Copyright (c) 1994, Regents of the University of California
15 *
16 *
17 * IDENTIFICATION
18 * src/backend/storage/smgr/md.c
19 *
20 *-------------------------------------------------------------------------
21 */
22 #include "postgres.h"
23
24 #include <unistd.h>
25 #include <fcntl.h>
26 #include <sys/file.h>
27
28 #include "access/xlogutils.h"
29 #include "commands/tablespace.h"
30 #include "common/file_utils.h"
31 #include "miscadmin.h"
32 #include "pg_trace.h"
33 #include "pgstat.h"
34 #include "storage/aio.h"
35 #include "storage/bufmgr.h"
36 #include "storage/fd.h"
37 #include "storage/md.h"
38 #include "storage/relfilelocator.h"
39 #include "storage/smgr.h"
40 #include "storage/sync.h"
41 #include "utils/memutils.h"
42
43 /*
44 * The magnetic disk storage manager keeps track of open file
45 * descriptors in its own descriptor pool. This is done to make it
46 * easier to support relations that are larger than the operating
47 * system's file size limit (often 2GBytes). In order to do that,
48 * we break relations up into "segment" files that are each shorter than
49 * the OS file size limit. The segment size is set by the RELSEG_SIZE
50 * configuration constant in pg_config.h.
51 *
52 * On disk, a relation must consist of consecutively numbered segment
53 * files in the pattern
54 * -- Zero or more full segments of exactly RELSEG_SIZE blocks each
55 * -- Exactly one partial segment of size 0 <= size < RELSEG_SIZE blocks
56 * -- Optionally, any number of inactive segments of size 0 blocks.
57 * The full and partial segments are collectively the "active" segments.
58 * Inactive segments are those that once contained data but are currently
59 * not needed because of an mdtruncate() operation. The reason for leaving
60 * them present at size zero, rather than unlinking them, is that other
61 * backends and/or the checkpointer might be holding open file references to
62 * such segments. If the relation expands again after mdtruncate(), such
63 * that a deactivated segment becomes active again, it is important that
64 * such file references still be valid --- else data might get written
65 * out to an unlinked old copy of a segment file that will eventually
66 * disappear.
67 *
68 * File descriptors are stored in the per-fork md_seg_fds arrays inside
69 * SMgrRelation. The length of these arrays is stored in md_num_open_segs.
70 * Note that a fork's md_num_open_segs having a specific value does not
71 * necessarily mean the relation doesn't have additional segments; we may
72 * just not have opened the next segment yet. (We could not have "all
73 * segments are in the array" as an invariant anyway, since another backend
74 * could extend the relation while we aren't looking.) We do not have
75 * entries for inactive segments, however; as soon as we find a partial
76 * segment, we assume that any subsequent segments are inactive.
77 *
78 * The entire MdfdVec array is palloc'd in the MdCxt memory context.
79 */
80
81 typedef struct _MdfdVec
82 {
83 File mdfd_vfd; /* fd number in fd.c's pool */
84 BlockNumber mdfd_segno; /* segment number, from 0 */
85 } MdfdVec;
86
87 static MemoryContext MdCxt; /* context for all MdfdVec objects */
88
89
90 /* Populate a file tag describing an md.c segment file. */
91 #define INIT_MD_FILETAG(a,xx_rlocator,xx_forknum,xx_segno) \
92 ( \
93 memset(&(a), 0, sizeof(FileTag)), \
94 (a).handler = SYNC_HANDLER_MD, \
95 (a).rlocator = (xx_rlocator), \
96 (a).forknum = (xx_forknum), \
97 (a).segno = (xx_segno) \
98 )
99
100
101 /*** behavior for mdopen & _mdfd_getseg ***/
102 /* ereport if segment not present */
103 #define EXTENSION_FAIL (1 << 0)
104 /* return NULL if segment not present */
105 #define EXTENSION_RETURN_NULL (1 << 1)
106 /* create new segments as needed */
107 #define EXTENSION_CREATE (1 << 2)
108 /* create new segments if needed during recovery */
109 #define EXTENSION_CREATE_RECOVERY (1 << 3)
110 /* don't try to open a segment, if not already open */
111 #define EXTENSION_DONT_OPEN (1 << 5)
112
113
114 /*
115 * Fixed-length string to represent paths to files that need to be built by
116 * md.c.
117 *
118 * The maximum number of segments is MaxBlockNumber / RELSEG_SIZE, where
119 * RELSEG_SIZE can be set to 1 (for testing only).
120 */
121 #define SEGMENT_CHARS OIDCHARS
122 #define MD_PATH_STR_MAXLEN \
123 (\
124 REL_PATH_STR_MAXLEN \
125 + sizeof((char)'.') \
126 + SEGMENT_CHARS \
127 )
128 typedef struct MdPathStr
129 {
130 char str[MD_PATH_STR_MAXLEN + 1];
131 } MdPathStr;
132
133
134 /* local routines */
135 static void mdunlinkfork(RelFileLocatorBackend rlocator, ForkNumber forknum,
136 bool isRedo);
137 static MdfdVec *mdopenfork(SMgrRelation reln, ForkNumber forknum, int behavior);
138 static void register_dirty_segment(SMgrRelation reln, ForkNumber forknum,
139 MdfdVec *seg);
140 static void register_unlink_segment(RelFileLocatorBackend rlocator, ForkNumber forknum,
141 BlockNumber segno);
142 static void register_forget_request(RelFileLocatorBackend rlocator, ForkNumber forknum,
143 BlockNumber segno);
144 static void _fdvec_resize(SMgrRelation reln,
145 ForkNumber forknum,
146 int nseg);
147 static MdPathStr _mdfd_segpath(SMgrRelation reln, ForkNumber forknum,
148 BlockNumber segno);
149 static MdfdVec *_mdfd_openseg(SMgrRelation reln, ForkNumber forknum,
150 BlockNumber segno, int oflags);
151 static MdfdVec *_mdfd_getseg(SMgrRelation reln, ForkNumber forknum,
152 BlockNumber blkno, bool skipFsync, int behavior);
153 static BlockNumber _mdnblocks(SMgrRelation reln, ForkNumber forknum,
154 MdfdVec *seg);
155
156 static PgAioResult md_readv_complete(PgAioHandle *ioh, PgAioResult prior_result, uint8 cb_data);
157 static void md_readv_report(PgAioResult result, const PgAioTargetData *td, int elevel);
158
159 const PgAioHandleCallbacks aio_md_readv_cb = {
160 .complete_shared = md_readv_complete,
161 .report = md_readv_report,
162 };
163
164
165 static inline int
166 _mdfd_open_flags(void)
167 {
168 int flags = O_RDWR | PG_BINARY;
169
170 if (io_direct_flags & IO_DIRECT_DATA)
171 flags |= PG_O_DIRECT;
172
173 return flags;
174 }
175
176 /*
177 * mdinit() -- Initialize private state for magnetic disk storage manager.
178 */
179 void
180 mdinit(void)
181 {
182 MdCxt = AllocSetContextCreate(TopMemoryContext,
183 "MdSmgr",
184 ALLOCSET_DEFAULT_SIZES);
185 }
186
187 /*
188 * mdexists() -- Does the physical file exist?
189 *
190 * Note: this will return true for lingering files, with pending deletions
191 */
192 bool
193 mdexists(SMgrRelation reln, ForkNumber forknum)
194 {
195 /*
196 * Close it first, to ensure that we notice if the fork has been unlinked
197 * since we opened it. As an optimization, we can skip that in recovery,
198 * which already closes relations when dropping them.
199 */
200 if (!InRecovery)
201 mdclose(reln, forknum);
202
203 return (mdopenfork(reln, forknum, EXTENSION_RETURN_NULL) != NULL);
204 }
205
206 /*
207 * mdcreate() -- Create a new relation on magnetic disk.
208 *
209 * If isRedo is true, it's okay for the relation to exist already.
210 */
211 void
212 mdcreate(SMgrRelation reln, ForkNumber forknum, bool isRedo)
213 {
214 MdfdVec *mdfd;
215 RelPathStr path;
216 File fd;
217
218 if (isRedo && reln->md_num_open_segs[forknum] > 0)
219 return; /* created and opened already... */
220
221 Assert(reln->md_num_open_segs[forknum] == 0);
222
223 /*
224 * We may be using the target table space for the first time in this
225 * database, so create a per-database subdirectory if needed.
226 *
227 * XXX this is a fairly ugly violation of module layering, but this seems
228 * to be the best place to put the check. Maybe TablespaceCreateDbspace
229 * should be here and not in commands/tablespace.c? But that would imply
230 * importing a lot of stuff that smgr.c oughtn't know, either.
231 */
232 TablespaceCreateDbspace(reln->smgr_rlocator.locator.spcOid,
233 reln->smgr_rlocator.locator.dbOid,
234 isRedo);
235
236 path = relpath(reln->smgr_rlocator, forknum);
237
238 fd = PathNameOpenFile(path.str, _mdfd_open_flags() | O_CREAT | O_EXCL);
239
240 if (fd < 0)
241 {
242 int save_errno = errno;
243
244 if (isRedo)
245 fd = PathNameOpenFile(path.str, _mdfd_open_flags());
246 if (fd < 0)
247 {
248 /* be sure to report the error reported by create, not open */
249 errno = save_errno;
250 ereport(ERROR,
251 (errcode_for_file_access(),
252 errmsg("could not create file \"%s\": %m", path.str)));
253 }
254 }
255
256 _fdvec_resize(reln, forknum, 1);
257 mdfd = &reln->md_seg_fds[forknum][0];
258 mdfd->mdfd_vfd = fd;
259 mdfd->mdfd_segno = 0;
260
261 if (!SmgrIsTemp(reln))
262 register_dirty_segment(reln, forknum, mdfd);
263 }
264
265 /*
266 * mdunlink() -- Unlink a relation.
267 *
268 * Note that we're passed a RelFileLocatorBackend --- by the time this is called,
269 * there won't be an SMgrRelation hashtable entry anymore.
270 *
271 * forknum can be a fork number to delete a specific fork, or InvalidForkNumber
272 * to delete all forks.
273 *
274 * For regular relations, we don't unlink the first segment file of the rel,
275 * but just truncate it to zero length, and record a request to unlink it after
276 * the next checkpoint. Additional segments can be unlinked immediately,
277 * however. Leaving the empty file in place prevents that relfilenumber
278 * from being reused. The scenario this protects us from is:
279 * 1. We delete a relation (and commit, and actually remove its file).
280 * 2. We create a new relation, which by chance gets the same relfilenumber as
281 * the just-deleted one (OIDs must've wrapped around for that to happen).
282 * 3. We crash before another checkpoint occurs.
283 * During replay, we would delete the file and then recreate it, which is fine
284 * if the contents of the file were repopulated by subsequent WAL entries.
285 * But if we didn't WAL-log insertions, but instead relied on fsyncing the
286 * file after populating it (as we do at wal_level=minimal), the contents of
287 * the file would be lost forever. By leaving the empty file until after the
288 * next checkpoint, we prevent reassignment of the relfilenumber until it's
289 * safe, because relfilenumber assignment skips over any existing file.
290 *
291 * Additional segments, if any, are truncated and then unlinked. The reason
292 * for truncating is that other backends may still hold open FDs for these at
293 * the smgr level, so that the kernel can't remove the file yet. We want to
294 * reclaim the disk space right away despite that.
295 *
296 * We do not need to go through this dance for temp relations, though, because
297 * we never make WAL entries for temp rels, and so a temp rel poses no threat
298 * to the health of a regular rel that has taken over its relfilenumber.
299 * The fact that temp rels and regular rels have different file naming
300 * patterns provides additional safety. Other backends shouldn't have open
301 * FDs for them, either.
302 *
303 * We also don't do it while performing a binary upgrade. There is no reuse
304 * hazard in that case, since after a crash or even a simple ERROR, the
305 * upgrade fails and the whole cluster must be recreated from scratch.
306 * Furthermore, it is important to remove the files from disk immediately,
307 * because we may be about to reuse the same relfilenumber.
308 *
309 * All the above applies only to the relation's main fork; other forks can
310 * just be removed immediately, since they are not needed to prevent the
311 * relfilenumber from being recycled. Also, we do not carefully
312 * track whether other forks have been created or not, but just attempt to
313 * unlink them unconditionally; so we should never complain about ENOENT.
314 *
315 * If isRedo is true, it's unsurprising for the relation to be already gone.
316 * Also, we should remove the file immediately instead of queuing a request
317 * for later, since during redo there's no possibility of creating a
318 * conflicting relation.
319 *
320 * Note: we currently just never warn about ENOENT at all. We could warn in
321 * the main-fork, non-isRedo case, but it doesn't seem worth the trouble.
322 *
323 * Note: any failure should be reported as WARNING not ERROR, because
324 * we are usually not in a transaction anymore when this is called.
325 */
326 void
327 mdunlink(RelFileLocatorBackend rlocator, ForkNumber forknum, bool isRedo)
328 {
329 /* Now do the per-fork work */
330 if (forknum == InvalidForkNumber)
331 {
332 for (forknum = 0; forknum <= MAX_FORKNUM; forknum++)
333 mdunlinkfork(rlocator, forknum, isRedo);
334 }
335 else
336 mdunlinkfork(rlocator, forknum, isRedo);
337 }
338
339 /*
340 * Truncate a file to release disk space.
341 */
342 static int
343 do_truncate(const char *path)
344 {
345 int save_errno;
346 int ret;
347
348 ret = pg_truncate(path, 0);
349
350 /* Log a warning here to avoid repetition in callers. */
351 if (ret < 0 && errno != ENOENT)
352 {
353 save_errno = errno;
354 ereport(WARNING,
355 (errcode_for_file_access(),
356 errmsg("could not truncate file \"%s\": %m", path)));
357 errno = save_errno;
358 }
359
360 return ret;
361 }
362
363 static void
364 mdunlinkfork(RelFileLocatorBackend rlocator, ForkNumber forknum, bool isRedo)
365 {
366 RelPathStr path;
367 int ret;
368 int save_errno;
369
370 path = relpath(rlocator, forknum);
371
372 /*
373 * Truncate and then unlink the first segment, or just register a request
374 * to unlink it later, as described in the comments for mdunlink().
375 */
376 if (isRedo || IsBinaryUpgrade || forknum != MAIN_FORKNUM ||
377 RelFileLocatorBackendIsTemp(rlocator))
378 {
379 if (!RelFileLocatorBackendIsTemp(rlocator))
380 {
381 /* Prevent other backends' fds from holding on to the disk space */
382 ret = do_truncate(path.str);
383
384 /* Forget any pending sync requests for the first segment */
385 save_errno = errno;
386 register_forget_request(rlocator, forknum, 0 /* first seg */ );
387 errno = save_errno;
388 }
389 else
390 ret = 0;
391
392 /* Next unlink the file, unless it was already found to be missing */
393 if (ret >= 0 || errno != ENOENT)
394 {
395 ret = unlink(path.str);
396 if (ret < 0 && errno != ENOENT)
397 {
398 save_errno = errno;
399 ereport(WARNING,
400 (errcode_for_file_access(),
401 errmsg("could not remove file \"%s\": %m", path.str)));
402 errno = save_errno;
403 }
404 }
405 }
406 else
407 {
408 /* Prevent other backends' fds from holding on to the disk space */
409 ret = do_truncate(path.str);
410
411 /* Register request to unlink first segment later */
412 save_errno = errno;
413 register_unlink_segment(rlocator, forknum, 0 /* first seg */ );
414 errno = save_errno;
415 }
416
417 /*
418 * Delete any additional segments.
419 *
420 * Note that because we loop until getting ENOENT, we will correctly
421 * remove all inactive segments as well as active ones. Ideally we'd
422 * continue the loop until getting exactly that errno, but that risks an
423 * infinite loop if the problem is directory-wide (for instance, if we
424 * suddenly can't read the data directory itself). We compromise by
425 * continuing after a non-ENOENT truncate error, but stopping after any
426 * unlink error. If there is indeed a directory-wide problem, additional
427 * unlink attempts wouldn't work anyway.
428 */
429 if (ret >= 0 || errno != ENOENT)
430 {
431 MdPathStr segpath;
432 BlockNumber segno;
433
434 for (segno = 1;; segno++)
435 {
436 sprintf(segpath.str, "%s.%u", path.str, segno);
437
438 if (!RelFileLocatorBackendIsTemp(rlocator))
439 {
440 /*
441 * Prevent other backends' fds from holding on to the disk
442 * space. We're done if we see ENOENT, though.
443 */
444 if (do_truncate(segpath.str) < 0 && errno == ENOENT)
445 break;
446
447 /*
448 * Forget any pending sync requests for this segment before we
449 * try to unlink.
450 */
451 register_forget_request(rlocator, forknum, segno);
452 }
453
454 if (unlink(segpath.str) < 0)
455 {
456 /* ENOENT is expected after the last segment... */
457 if (errno != ENOENT)
458 ereport(WARNING,
459 (errcode_for_file_access(),
460 errmsg("could not remove file \"%s\": %m", segpath.str)));
461 break;
462 }
463 }
464 }
465 }
466
467 /*
468 * mdextend() -- Add a block to the specified relation.
469 *
470 * The semantics are nearly the same as mdwrite(): write at the
471 * specified position. However, this is to be used for the case of
472 * extending a relation (i.e., blocknum is at or beyond the current
473 * EOF). Note that we assume writing a block beyond current EOF
474 * causes intervening file space to become filled with zeroes.
475 */
476 void
477 mdextend(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum,
478 const void *buffer, bool skipFsync)
479 {
480 off_t seekpos;
481 int nbytes;
482 MdfdVec *v;
483
484 /* If this build supports direct I/O, the buffer must be I/O aligned. */
485 if (PG_O_DIRECT != 0 && PG_IO_ALIGN_SIZE <= BLCKSZ)
486 Assert((uintptr_t) buffer == TYPEALIGN(PG_IO_ALIGN_SIZE, buffer));
487
488 /* This assert is too expensive to have on normally ... */
489 #ifdef CHECK_WRITE_VS_EXTEND
490 Assert(blocknum >= mdnblocks(reln, forknum));
491 #endif
492
493 /*
494 * If a relation manages to grow to 2^32-1 blocks, refuse to extend it any
495 * more --- we mustn't create a block whose number actually is
496 * InvalidBlockNumber. (Note that this failure should be unreachable
497 * because of upstream checks in bufmgr.c.)
498 */
499 if (blocknum == InvalidBlockNumber)
500 ereport(ERROR,
501 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
502 errmsg("cannot extend file \"%s\" beyond %u blocks",
503 relpath(reln->smgr_rlocator, forknum).str,
504 InvalidBlockNumber)));
505
506 v = _mdfd_getseg(reln, forknum, blocknum, skipFsync, EXTENSION_CREATE);
507
508 seekpos = (off_t) BLCKSZ * (blocknum % ((BlockNumber) RELSEG_SIZE));
509
510 Assert(seekpos < (off_t) BLCKSZ * RELSEG_SIZE);
511
512 if ((nbytes = FileWrite(v->mdfd_vfd, buffer, BLCKSZ, seekpos, WAIT_EVENT_DATA_FILE_EXTEND)) != BLCKSZ)
513 {
514 if (nbytes < 0)
515 ereport(ERROR,
516 (errcode_for_file_access(),
517 errmsg("could not extend file \"%s\": %m",
518 FilePathName(v->mdfd_vfd)),
519 errhint("Check free disk space.")));
520 /* short write: complain appropriately */
521 ereport(ERROR,
522 (errcode(ERRCODE_DISK_FULL),
523 errmsg("could not extend file \"%s\": wrote only %d of %d bytes at block %u",
524 FilePathName(v->mdfd_vfd),
525 nbytes, BLCKSZ, blocknum),
526 errhint("Check free disk space.")));
527 }
528
529 if (!skipFsync && !SmgrIsTemp(reln))
530 register_dirty_segment(reln, forknum, v);
531
532 Assert(_mdnblocks(reln, forknum, v) <= ((BlockNumber) RELSEG_SIZE));
533 }
534
535 /*
536 * mdzeroextend() -- Add new zeroed out blocks to the specified relation.
537 *
538 * Similar to mdextend(), except the relation can be extended by multiple
539 * blocks at once and the added blocks will be filled with zeroes.
540 */
541 void
542 mdzeroextend(SMgrRelation reln, ForkNumber forknum,
543 BlockNumber blocknum, int nblocks, bool skipFsync)
544 {
545 MdfdVec *v;
546 BlockNumber curblocknum = blocknum;
547 int remblocks = nblocks;
548
549 Assert(nblocks > 0);
550
551 /* This assert is too expensive to have on normally ... */
552 #ifdef CHECK_WRITE_VS_EXTEND
553 Assert(blocknum >= mdnblocks(reln, forknum));
554 #endif
555
556 /*
557 * If a relation manages to grow to 2^32-1 blocks, refuse to extend it any
558 * more --- we mustn't create a block whose number actually is
559 * InvalidBlockNumber or larger.
560 */
561 if ((uint64) blocknum + nblocks >= (uint64) InvalidBlockNumber)
562 ereport(ERROR,
563 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
564 errmsg("cannot extend file \"%s\" beyond %u blocks",
565 relpath(reln->smgr_rlocator, forknum).str,
566 InvalidBlockNumber)));
567
568 while (remblocks > 0)
569 {
570 BlockNumber segstartblock = curblocknum % ((BlockNumber) RELSEG_SIZE);
571 off_t seekpos = (off_t) BLCKSZ * segstartblock;
572 int numblocks;
573
574 if (segstartblock + remblocks > RELSEG_SIZE)
575 numblocks = RELSEG_SIZE - segstartblock;
576 else
577 numblocks = remblocks;
578
579 v = _mdfd_getseg(reln, forknum, curblocknum, skipFsync, EXTENSION_CREATE);
580
581 Assert(segstartblock < RELSEG_SIZE);
582 Assert(segstartblock + numblocks <= RELSEG_SIZE);
583
584 /*
585 * If available and useful, use posix_fallocate() (via
586 * FileFallocate()) to extend the relation. That's often more
587 * efficient than using write(), as it commonly won't cause the kernel
588 * to allocate page cache space for the extended pages.
589 *
590 * However, we don't use FileFallocate() for small extensions, as it
591 * defeats delayed allocation on some filesystems. Not clear where
592 * that decision should be made though? For now just use a cutoff of
593 * 8, anything between 4 and 8 worked OK in some local testing.
594 */
595 if (numblocks > 8 &&
596 file_extend_method != FILE_EXTEND_METHOD_WRITE_ZEROS)
597 {
598 int ret = 0;
599
600 #ifdef HAVE_POSIX_FALLOCATE
601 if (file_extend_method == FILE_EXTEND_METHOD_POSIX_FALLOCATE)
602 {
603 ret = FileFallocate(v->mdfd_vfd,
604 seekpos, (off_t) BLCKSZ * numblocks,
605 WAIT_EVENT_DATA_FILE_EXTEND);
606 }
607 else
608 #endif
609 {
610 elog(ERROR, "unsupported file_extend_method: %d",
611 file_extend_method);
612 }
613 if (ret != 0)
614 {
615 ereport(ERROR,
616 errcode_for_file_access(),
617 errmsg("could not extend file \"%s\" with FileFallocate(): %m",
618 FilePathName(v->mdfd_vfd)),
619 errhint("Check free disk space."));
620 }
621 }
622 else
623 {
624 int ret;
625
626 /*
627 * Even if we don't want to use fallocate, we can still extend a
628 * bit more efficiently than writing each 8kB block individually.
629 * pg_pwrite_zeros() (via FileZero()) uses pg_pwritev_with_retry()
630 * to avoid multiple writes or needing a zeroed buffer for the
631 * whole length of the extension.
632 */
633 ret = FileZero(v->mdfd_vfd,
634 seekpos, (off_t) BLCKSZ * numblocks,
635 WAIT_EVENT_DATA_FILE_EXTEND);
636 if (ret < 0)
637 ereport(ERROR,
638 errcode_for_file_access(),
639 errmsg("could not extend file \"%s\": %m",
640 FilePathName(v->mdfd_vfd)),
641 errhint("Check free disk space."));
642 }
643
644 if (!skipFsync && !SmgrIsTemp(reln))
645 register_dirty_segment(reln, forknum, v);
646
647 Assert(_mdnblocks(reln, forknum, v) <= ((BlockNumber) RELSEG_SIZE));
648
649 remblocks -= numblocks;
650 curblocknum += numblocks;
651 }
652 }
653
654 /*
655 * mdopenfork() -- Open one fork of the specified relation.
656 *
657 * Note we only open the first segment, when there are multiple segments.
658 *
659 * If first segment is not present, either ereport or return NULL according
660 * to "behavior". We treat EXTENSION_CREATE the same as EXTENSION_FAIL;
661 * EXTENSION_CREATE means it's OK to extend an existing relation, not to
662 * invent one out of whole cloth.
663 */
664 static MdfdVec *
665 mdopenfork(SMgrRelation reln, ForkNumber forknum, int behavior)
666 {
667 MdfdVec *mdfd;
668 RelPathStr path;
669 File fd;
670
671 /* No work if already open */
672 if (reln->md_num_open_segs[forknum] > 0)
673 return &reln->md_seg_fds[forknum][0];
674
675 path = relpath(reln->smgr_rlocator, forknum);
676
677 fd = PathNameOpenFile(path.str, _mdfd_open_flags());
678
679 if (fd < 0)
680 {
681 if ((behavior & EXTENSION_RETURN_NULL) &&
682 FILE_POSSIBLY_DELETED(errno))
683 return NULL;
684 ereport(ERROR,
685 (errcode_for_file_access(),
686 errmsg("could not open file \"%s\": %m", path.str)));
687 }
688
689 _fdvec_resize(reln, forknum, 1);
690 mdfd = &reln->md_seg_fds[forknum][0];
691 mdfd->mdfd_vfd = fd;
692 mdfd->mdfd_segno = 0;
693
694 Assert(_mdnblocks(reln, forknum, mdfd) <= ((BlockNumber) RELSEG_SIZE));
695
696 return mdfd;
697 }
698
699 /*
700 * mdopen() -- Initialize newly-opened relation.
701 */
702 void
703 mdopen(SMgrRelation reln)
704 {
705 /* mark it not open */
706 for (int forknum = 0; forknum <= MAX_FORKNUM; forknum++)
707 reln->md_num_open_segs[forknum] = 0;
708 }
709
710 /*
711 * mdclose() -- Close the specified relation, if it isn't closed already.
712 */
713 void
714 mdclose(SMgrRelation reln, ForkNumber forknum)
715 {
716 int nopensegs = reln->md_num_open_segs[forknum];
717
718 /* No work if already closed */
719 if (nopensegs == 0)
720 return;
721
722 /* close segments starting from the end */
723 while (nopensegs > 0)
724 {
725 MdfdVec *v = &reln->md_seg_fds[forknum][nopensegs - 1];
726
727 FileClose(v->mdfd_vfd);
728 _fdvec_resize(reln, forknum, nopensegs - 1);
729 nopensegs--;
730 }
731 }
732
733 /*
734 * mdprefetch() -- Initiate asynchronous read of the specified blocks of a relation
735 */
736 bool
737 mdprefetch(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum,
738 int nblocks)
739 {
740 #ifdef USE_PREFETCH
741
742 Assert((io_direct_flags & IO_DIRECT_DATA) == 0);
743
744 if ((uint64) blocknum + nblocks > (uint64) MaxBlockNumber + 1)
745 return false;
746
747 while (nblocks > 0)
748 {
749 off_t seekpos;
750 MdfdVec *v;
751 int nblocks_this_segment;
752
753 v = _mdfd_getseg(reln, forknum, blocknum, false,
754 InRecovery ? EXTENSION_RETURN_NULL : EXTENSION_FAIL);
755 if (v == NULL)
756 return false;
757
758 seekpos = (off_t) BLCKSZ * (blocknum % ((BlockNumber) RELSEG_SIZE));
759
760 Assert(seekpos < (off_t) BLCKSZ * RELSEG_SIZE);
761
762 nblocks_this_segment =
763 Min(nblocks,
764 RELSEG_SIZE - (blocknum % ((BlockNumber) RELSEG_SIZE)));
765
766 (void) FilePrefetch(v->mdfd_vfd, seekpos, BLCKSZ * nblocks_this_segment,
767 WAIT_EVENT_DATA_FILE_PREFETCH);
768
769 blocknum += nblocks_this_segment;
770 nblocks -= nblocks_this_segment;
771 }
772 #endif /* USE_PREFETCH */
773
774 return true;
775 }
776
777 /*
778 * Convert an array of buffer address into an array of iovec objects, and
779 * return the number that were required. 'iov' must have enough space for up
780 * to 'nblocks' elements, but the number used may be less depending on
781 * merging. In the case of a run of fully contiguous buffers, a single iovec
782 * will be populated that can be handled as a plain non-vectored I/O.
783 */
784 static int
785 buffers_to_iovec(struct iovec *iov, void **buffers, int nblocks)
786 {
787 struct iovec *iovp;
788 int iovcnt;
789
790 Assert(nblocks >= 1);
791
792 /* If this build supports direct I/O, buffers must be I/O aligned. */
793 for (int i = 0; i < nblocks; ++i)
794 {
795 if (PG_O_DIRECT != 0 && PG_IO_ALIGN_SIZE <= BLCKSZ)
796 Assert((uintptr_t) buffers[i] ==
797 TYPEALIGN(PG_IO_ALIGN_SIZE, buffers[i]));
798 }
799
800 /* Start the first iovec off with the first buffer. */
801 iovp = &iov[0];
802 iovp->iov_base = buffers[0];
803 iovp->iov_len = BLCKSZ;
804 iovcnt = 1;
805
806 /* Try to merge the rest. */
807 for (int i = 1; i < nblocks; ++i)
808 {
809 void *buffer = buffers[i];
810
811 if (((char *) iovp->iov_base + iovp->iov_len) == buffer)
812 {
813 /* Contiguous with the last iovec. */
814 iovp->iov_len += BLCKSZ;
815 }
816 else
817 {
818 /* Need a new iovec. */
819 iovp++;
820 iovp->iov_base = buffer;
821 iovp->iov_len = BLCKSZ;
822 iovcnt++;
823 }
824 }
825
826 return iovcnt;
827 }
828
829 /*
830 * mdmaxcombine() -- Return the maximum number of total blocks that can be
831 * combined with an IO starting at blocknum.
832 */
833 uint32
834 mdmaxcombine(SMgrRelation reln, ForkNumber forknum,
835 BlockNumber blocknum)
836 {
837 BlockNumber segoff;
838
839 segoff = blocknum % ((BlockNumber) RELSEG_SIZE);
840
841 return RELSEG_SIZE - segoff;
842 }
843
844 /*
845 * mdreadv() -- Read the specified blocks from a relation.
846 */
847 void
848 mdreadv(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum,
849 void **buffers, BlockNumber nblocks)
850 {
851 while (nblocks > 0)
852 {
853 struct iovec iov[PG_IOV_MAX];
854 int iovcnt;
855 off_t seekpos;
856 int nbytes;
857 MdfdVec *v;
858 BlockNumber nblocks_this_segment;
859 size_t transferred_this_segment;
860 size_t size_this_segment;
861
862 v = _mdfd_getseg(reln, forknum, blocknum, false,
863 EXTENSION_FAIL | EXTENSION_CREATE_RECOVERY);
864
865 seekpos = (off_t) BLCKSZ * (blocknum % ((BlockNumber) RELSEG_SIZE));
866
867 Assert(seekpos < (off_t) BLCKSZ * RELSEG_SIZE);
868
869 nblocks_this_segment =
870 Min(nblocks,
871 RELSEG_SIZE - (blocknum % ((BlockNumber) RELSEG_SIZE)));
872 nblocks_this_segment = Min(nblocks_this_segment, lengthof(iov));
873
874 if (nblocks_this_segment != nblocks)
875 elog(ERROR, "read crosses segment boundary");
876
877 iovcnt = buffers_to_iovec(iov, buffers, nblocks_this_segment);
878 size_this_segment = nblocks_this_segment * BLCKSZ;
879 transferred_this_segment = 0;
880
881 /*
882 * Inner loop to continue after a short read. We'll keep going until
883 * we hit EOF rather than assuming that a short read means we hit the
884 * end.
885 */
886 for (;;)
887 {
888 TRACE_POSTGRESQL_SMGR_MD_READ_START(forknum, blocknum,
889 reln->smgr_rlocator.locator.spcOid,
890 reln->smgr_rlocator.locator.dbOid,
891 reln->smgr_rlocator.locator.relNumber,
892 reln->smgr_rlocator.backend);
893 nbytes = FileReadV(v->mdfd_vfd, iov, iovcnt, seekpos,
894 WAIT_EVENT_DATA_FILE_READ);
895 TRACE_POSTGRESQL_SMGR_MD_READ_DONE(forknum, blocknum,
896 reln->smgr_rlocator.locator.spcOid,
897 reln->smgr_rlocator.locator.dbOid,
898 reln->smgr_rlocator.locator.relNumber,
899 reln->smgr_rlocator.backend,
900 nbytes,
901 size_this_segment - transferred_this_segment);
902
903 #ifdef SIMULATE_SHORT_READ
904 nbytes = Min(nbytes, 4096);
905 #endif
906
907 if (nbytes < 0)
908 ereport(ERROR,
909 (errcode_for_file_access(),
910 errmsg("could not read blocks %u..%u in file \"%s\": %m",
911 blocknum,
912 blocknum + nblocks_this_segment - 1,
913 FilePathName(v->mdfd_vfd))));
914
915 if (nbytes == 0)
916 {
917 /*
918 * We are at or past EOF, or we read a partial block at EOF.
919 * Normally this is an error; upper levels should never try to
920 * read a nonexistent block. However, if zero_damaged_pages
921 * is ON or we are InRecovery, we should instead return zeroes
922 * without complaining. This allows, for example, the case of
923 * trying to update a block that was later truncated away.
924 *
925 * NB: We think that this codepath is unreachable in recovery
926 * and incomplete with zero_damaged_pages, as missing segments
927 * are not created. Putting blocks into the buffer-pool that
928 * do not exist on disk is rather problematic, as it will not
929 * be found by scans that rely on smgrnblocks(), as they are
930 * beyond EOF. It also can cause weird problems with relation
931 * extension, as relation extension does not expect blocks
932 * beyond EOF to exist.
933 *
934 * Therefore we do not want to copy the logic into
935 * mdstartreadv(), where it would have to be more complicated
936 * due to potential differences in the zero_damaged_pages
937 * setting between the definer and completor of IO.
938 *
939 * For PG 18, we are putting an Assert(false) in mdreadv()
940 * (triggering failures in assertion-enabled builds, but
941 * continuing to work in production builds). Afterwards we
942 * plan to remove this code entirely.
943 */
944 if (zero_damaged_pages || InRecovery)
945 {
946 Assert(false); /* see comment above */
947
948 for (BlockNumber i = transferred_this_segment / BLCKSZ;
949 i < nblocks_this_segment;
950 ++i)
951 memset(buffers[i], 0, BLCKSZ);
952 break;
953 }
954 else
955 ereport(ERROR,
956 (errcode(ERRCODE_DATA_CORRUPTED),
957 errmsg("could not read blocks %u..%u in file \"%s\": read only %zu of %zu bytes",
958 blocknum,
959 blocknum + nblocks_this_segment - 1,
960 FilePathName(v->mdfd_vfd),
961 transferred_this_segment,
962 size_this_segment)));
963 }
964
965 /* One loop should usually be enough. */
966 transferred_this_segment += nbytes;
967 Assert(transferred_this_segment <= size_this_segment);
968 if (transferred_this_segment == size_this_segment)
969 break;
970
971 /* Adjust position and vectors after a short read. */
972 seekpos += nbytes;
973 iovcnt = compute_remaining_iovec(iov, iov, iovcnt, nbytes);
974 }
975
976 nblocks -= nblocks_this_segment;
977 buffers += nblocks_this_segment;
978 blocknum += nblocks_this_segment;
979 }
980 }
981
982 /*
983 * mdstartreadv() -- Asynchronous version of mdreadv().
984 */
985 void
986 mdstartreadv(PgAioHandle *ioh,
987 SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum,
988 void **buffers, BlockNumber nblocks)
989 {
990 off_t seekpos;
991 MdfdVec *v;
992 BlockNumber nblocks_this_segment;
993 struct iovec *iov;
994 int iovcnt;
995 int ret;
996
997 v = _mdfd_getseg(reln, forknum, blocknum, false,
998 EXTENSION_FAIL | EXTENSION_CREATE_RECOVERY);
999
1000 seekpos = (off_t) BLCKSZ * (blocknum % ((BlockNumber) RELSEG_SIZE));
1001
1002 Assert(seekpos < (off_t) BLCKSZ * RELSEG_SIZE);
1003
1004 nblocks_this_segment =
1005 Min(nblocks,
1006 RELSEG_SIZE - (blocknum % ((BlockNumber) RELSEG_SIZE)));
1007
1008 if (nblocks_this_segment != nblocks)
1009 elog(ERROR, "read crossing segment boundary");
1010
1011 iovcnt = pgaio_io_get_iovec(ioh, &iov);
1012
1013 Assert(nblocks <= iovcnt);
1014
1015 iovcnt = buffers_to_iovec(iov, buffers, nblocks_this_segment);
1016
1017 Assert(iovcnt <= nblocks_this_segment);
1018
1019 if (!(io_direct_flags & IO_DIRECT_DATA))
1020 pgaio_io_set_flag(ioh, PGAIO_HF_BUFFERED);
1021
1022 pgaio_io_set_target_smgr(ioh,
1023 reln,
1024 forknum,
1025 blocknum,
1026 nblocks,
1027 false);
1028 pgaio_io_register_callbacks(ioh, PGAIO_HCB_MD_READV, 0);
1029
1030 ret = FileStartReadV(ioh, v->mdfd_vfd, iovcnt, seekpos, WAIT_EVENT_DATA_FILE_READ);
1031 if (ret != 0)
1032 ereport(ERROR,
1033 (errcode_for_file_access(),
1034 errmsg("could not start reading blocks %u..%u in file \"%s\": %m",
1035 blocknum,
1036 blocknum + nblocks_this_segment - 1,
1037 FilePathName(v->mdfd_vfd))));
1038
1039 /*
1040 * The error checks corresponding to the post-read checks in mdreadv() are
1041 * in md_readv_complete().
1042 *
1043 * However we chose, at least for now, to not implement the
1044 * zero_damaged_pages logic present in mdreadv(). As outlined in mdreadv()
1045 * that logic is rather problematic, and we want to get rid of it. Here
1046 * equivalent logic would have to be more complicated due to potential
1047 * differences in the zero_damaged_pages setting between the definer and
1048 * completor of IO.
1049 */
1050 }
1051
1052 /*
1053 * mdwritev() -- Write the supplied blocks at the appropriate location.
1054 *
1055 * This is to be used only for updating already-existing blocks of a
1056 * relation (ie, those before the current EOF). To extend a relation,
1057 * use mdextend().
1058 */
1059 void
1060 mdwritev(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum,
1061 const void **buffers, BlockNumber nblocks, bool skipFsync)
1062 {
1063 /* This assert is too expensive to have on normally ... */
1064 #ifdef CHECK_WRITE_VS_EXTEND
1065 Assert((uint64) blocknum + (uint64) nblocks <= (uint64) mdnblocks(reln, forknum));
1066 #endif
1067
1068 while (nblocks > 0)
1069 {
1070 struct iovec iov[PG_IOV_MAX];
1071 int iovcnt;
1072 off_t seekpos;
1073 int nbytes;
1074 MdfdVec *v;
1075 BlockNumber nblocks_this_segment;
1076 size_t transferred_this_segment;
1077 size_t size_this_segment;
1078
1079 v = _mdfd_getseg(reln, forknum, blocknum, skipFsync,
1080 EXTENSION_FAIL | EXTENSION_CREATE_RECOVERY);
1081
1082 seekpos = (off_t) BLCKSZ * (blocknum % ((BlockNumber) RELSEG_SIZE));
1083
1084 Assert(seekpos < (off_t) BLCKSZ * RELSEG_SIZE);
1085
1086 nblocks_this_segment =
1087 Min(nblocks,
1088 RELSEG_SIZE - (blocknum % ((BlockNumber) RELSEG_SIZE)));
1089 nblocks_this_segment = Min(nblocks_this_segment, lengthof(iov));
1090
1091 if (nblocks_this_segment != nblocks)
1092 elog(ERROR, "write crosses segment boundary");
1093
1094 iovcnt = buffers_to_iovec(iov, (void **) buffers, nblocks_this_segment);
1095 size_this_segment = nblocks_this_segment * BLCKSZ;
1096 transferred_this_segment = 0;
1097
1098 /*
1099 * Inner loop to continue after a short write. If the reason is that
1100 * we're out of disk space, a future attempt should get an ENOSPC
1101 * error from the kernel.
1102 */
1103 for (;;)
1104 {
1105 TRACE_POSTGRESQL_SMGR_MD_WRITE_START(forknum, blocknum,
1106 reln->smgr_rlocator.locator.spcOid,
1107 reln->smgr_rlocator.locator.dbOid,
1108 reln->smgr_rlocator.locator.relNumber,
1109 reln->smgr_rlocator.backend);
1110 nbytes = FileWriteV(v->mdfd_vfd, iov, iovcnt, seekpos,
1111 WAIT_EVENT_DATA_FILE_WRITE);
1112 TRACE_POSTGRESQL_SMGR_MD_WRITE_DONE(forknum, blocknum,
1113 reln->smgr_rlocator.locator.spcOid,
1114 reln->smgr_rlocator.locator.dbOid,
1115 reln->smgr_rlocator.locator.relNumber,
1116 reln->smgr_rlocator.backend,
1117 nbytes,
1118 size_this_segment - transferred_this_segment);
1119
1120 #ifdef SIMULATE_SHORT_WRITE
1121 nbytes = Min(nbytes, 4096);
1122 #endif
1123
1124 if (nbytes < 0)
1125 {
1126 bool enospc = errno == ENOSPC;
1127
1128 ereport(ERROR,
1129 (errcode_for_file_access(),
1130 errmsg("could not write blocks %u..%u in file \"%s\": %m",
1131 blocknum,
1132 blocknum + nblocks_this_segment - 1,
1133 FilePathName(v->mdfd_vfd)),
1134 enospc ? errhint("Check free disk space.") : 0));
1135 }
1136
1137 /* One loop should usually be enough. */
1138 transferred_this_segment += nbytes;
1139 Assert(transferred_this_segment <= size_this_segment);
1140 if (transferred_this_segment == size_this_segment)
1141 break;
1142
1143 /* Adjust position and iovecs after a short write. */
1144 seekpos += nbytes;
1145 iovcnt = compute_remaining_iovec(iov, iov, iovcnt, nbytes);
1146 }
1147
1148 if (!skipFsync && !SmgrIsTemp(reln))
1149 register_dirty_segment(reln, forknum, v);
1150
1151 nblocks -= nblocks_this_segment;
1152 buffers += nblocks_this_segment;
1153 blocknum += nblocks_this_segment;
1154 }
1155 }
1156
1157
1158 /*
1159 * mdwriteback() -- Tell the kernel to write pages back to storage.
1160 *
1161 * This accepts a range of blocks because flushing several pages at once is
1162 * considerably more efficient than doing so individually.
1163 */
1164 void
1165 mdwriteback(SMgrRelation reln, ForkNumber forknum,
1166 BlockNumber blocknum, BlockNumber nblocks)
1167 {
1168 Assert((io_direct_flags & IO_DIRECT_DATA) == 0);
1169
1170 /*
1171 * Issue flush requests in as few requests as possible; have to split at
1172 * segment boundaries though, since those are actually separate files.
1173 */
1174 while (nblocks > 0)
1175 {
1176 BlockNumber nflush = nblocks;
1177 off_t seekpos;
1178 MdfdVec *v;
1179 int segnum_start,
1180 segnum_end;
1181
1182 v = _mdfd_getseg(reln, forknum, blocknum, true /* not used */ ,
1183 EXTENSION_DONT_OPEN);
1184
1185 /*
1186 * We might be flushing buffers of already removed relations, that's
1187 * ok, just ignore that case. If the segment file wasn't open already
1188 * (ie from a recent mdwrite()), then we don't want to re-open it, to
1189 * avoid a race with PROCSIGNAL_BARRIER_SMGRRELEASE that might leave
1190 * us with a descriptor to a file that is about to be unlinked.
1191 */
1192 if (!v)
1193 return;
1194
1195 /* compute offset inside the current segment */
1196 segnum_start = blocknum / RELSEG_SIZE;
1197
1198 /* compute number of desired writes within the current segment */
1199 segnum_end = (blocknum + nblocks - 1) / RELSEG_SIZE;
1200 if (segnum_start != segnum_end)
1201 nflush = RELSEG_SIZE - (blocknum % ((BlockNumber) RELSEG_SIZE));
1202
1203 Assert(nflush >= 1);
1204 Assert(nflush <= nblocks);
1205
1206 seekpos = (off_t) BLCKSZ * (blocknum % ((BlockNumber) RELSEG_SIZE));
1207
1208 FileWriteback(v->mdfd_vfd, seekpos, (off_t) BLCKSZ * nflush, WAIT_EVENT_DATA_FILE_FLUSH);
1209
1210 nblocks -= nflush;
1211 blocknum += nflush;
1212 }
1213 }
1214
1215 /*
1216 * mdnblocks() -- Get the number of blocks stored in a relation.
1217 *
1218 * Important side effect: all active segments of the relation are opened
1219 * and added to the md_seg_fds array. If this routine has not been
1220 * called, then only segments up to the last one actually touched
1221 * are present in the array.
1222 */
1223 BlockNumber
1224 mdnblocks(SMgrRelation reln, ForkNumber forknum)
1225 {
1226 MdfdVec *v;
1227 BlockNumber nblocks;
1228 BlockNumber segno;
1229
1230 mdopenfork(reln, forknum, EXTENSION_FAIL);
1231
1232 /* mdopen has opened the first segment */
1233 Assert(reln->md_num_open_segs[forknum] > 0);
1234
1235 /*
1236 * Start from the last open segments, to avoid redundant seeks. We have
1237 * previously verified that these segments are exactly RELSEG_SIZE long,
1238 * and it's useless to recheck that each time.
1239 *
1240 * NOTE: this assumption could only be wrong if another backend has
1241 * truncated the relation. We rely on higher code levels to handle that
1242 * scenario by closing and re-opening the md fd, which is handled via
1243 * relcache flush. (Since the checkpointer doesn't participate in
1244 * relcache flush, it could have segment entries for inactive segments;
1245 * that's OK because the checkpointer never needs to compute relation
1246 * size.)
1247 */
1248 segno = reln->md_num_open_segs[forknum] - 1;
1249 v = &reln->md_seg_fds[forknum][segno];
1250
1251 for (;;)
1252 {
1253 nblocks = _mdnblocks(reln, forknum, v);
1254 if (nblocks > ((BlockNumber) RELSEG_SIZE))
1255 elog(FATAL, "segment too big");
1256 if (nblocks < ((BlockNumber) RELSEG_SIZE))
1257 return (segno * ((BlockNumber) RELSEG_SIZE)) + nblocks;
1258
1259 /*
1260 * If segment is exactly RELSEG_SIZE, advance to next one.
1261 */
1262 segno++;
1263
1264 /*
1265 * We used to pass O_CREAT here, but that has the disadvantage that it
1266 * might create a segment which has vanished through some operating
1267 * system misadventure. In such a case, creating the segment here
1268 * undermines _mdfd_getseg's attempts to notice and report an error
1269 * upon access to a missing segment.
1270 */
1271 v = _mdfd_openseg(reln, forknum, segno, 0);
1272 if (v == NULL)
1273 return segno * ((BlockNumber) RELSEG_SIZE);
1274 }
1275 }
1276
1277 /*
1278 * mdtruncate() -- Truncate relation to specified number of blocks.
1279 *
1280 * Guaranteed not to allocate memory, so it can be used in a critical section.
1281 * Caller must have called smgrnblocks() to obtain curnblk while holding a
1282 * sufficient lock to prevent a change in relation size, and not used any smgr
1283 * functions for this relation or handled interrupts in between. This makes
1284 * sure we have opened all active segments, so that truncate loop will get
1285 * them all!
1286 *
1287 * If nblocks > curnblk, the request is ignored when we are InRecovery,
1288 * otherwise, an error is raised.
1289 */
1290 void
1291 mdtruncate(SMgrRelation reln, ForkNumber forknum,
1292 BlockNumber curnblk, BlockNumber nblocks)
1293 {
1294 BlockNumber priorblocks;
1295 int curopensegs;
1296
1297 if (nblocks > curnblk)
1298 {
1299 /* Bogus request ... but no complaint if InRecovery */
1300 if (InRecovery)
1301 return;
1302 ereport(ERROR,
1303 (errmsg("could not truncate file \"%s\" to %u blocks: it's only %u blocks now",
1304 relpath(reln->smgr_rlocator, forknum).str,
1305 nblocks, curnblk)));
1306 }
1307 if (nblocks == curnblk)
1308 return; /* no work */
1309
1310 /*
1311 * Truncate segments, starting at the last one. Starting at the end makes
1312 * managing the memory for the fd array easier, should there be errors.
1313 */
1314 curopensegs = reln->md_num_open_segs[forknum];
1315 while (curopensegs > 0)
1316 {
1317 MdfdVec *v;
1318
1319 priorblocks = (curopensegs - 1) * RELSEG_SIZE;
1320
1321 v = &reln->md_seg_fds[forknum][curopensegs - 1];
1322
1323 if (priorblocks > nblocks)
1324 {
1325 /*
1326 * This segment is no longer active. We truncate the file, but do
1327 * not delete it, for reasons explained in the header comments.
1328 */
1329 if (FileTruncate(v->mdfd_vfd, 0, WAIT_EVENT_DATA_FILE_TRUNCATE) < 0)
1330 ereport(ERROR,
1331 (errcode_for_file_access(),
1332 errmsg("could not truncate file \"%s\": %m",
1333 FilePathName(v->mdfd_vfd))));
1334
1335 if (!SmgrIsTemp(reln))
1336 register_dirty_segment(reln, forknum, v);
1337
1338 /* we never drop the 1st segment */
1339 Assert(v != &reln->md_seg_fds[forknum][0]);
1340
1341 FileClose(v->mdfd_vfd);
1342 _fdvec_resize(reln, forknum, curopensegs - 1);
1343 }
1344 else if (priorblocks + ((BlockNumber) RELSEG_SIZE) > nblocks)
1345 {
1346 /*
1347 * This is the last segment we want to keep. Truncate the file to
1348 * the right length. NOTE: if nblocks is exactly a multiple K of
1349 * RELSEG_SIZE, we will truncate the K+1st segment to 0 length but
1350 * keep it. This adheres to the invariant given in the header
1351 * comments.
1352 */
1353 BlockNumber lastsegblocks = nblocks - priorblocks;
1354
1355 if (FileTruncate(v->mdfd_vfd, (off_t) lastsegblocks * BLCKSZ, WAIT_EVENT_DATA_FILE_TRUNCATE) < 0)
1356 ereport(ERROR,
1357 (errcode_for_file_access(),
1358 errmsg("could not truncate file \"%s\" to %u blocks: %m",
1359 FilePathName(v->mdfd_vfd),
1360 nblocks)));
1361 if (!SmgrIsTemp(reln))
1362 register_dirty_segment(reln, forknum, v);
1363 }
1364 else
1365 {
1366 /*
1367 * We still need this segment, so nothing to do for this and any
1368 * earlier segment.
1369 */
1370 break;
1371 }
1372 curopensegs--;
1373 }
1374 }
1375
1376 /*
1377 * mdregistersync() -- Mark whole relation as needing fsync
1378 */
1379 void
1380 mdregistersync(SMgrRelation reln, ForkNumber forknum)
1381 {
1382 int segno;
1383 int min_inactive_seg;
1384
1385 /*
1386 * NOTE: mdnblocks makes sure we have opened all active segments, so that
1387 * the loop below will get them all!
1388 */
1389 mdnblocks(reln, forknum);
1390
1391 min_inactive_seg = segno = reln->md_num_open_segs[forknum];
1392
1393 /*
1394 * Temporarily open inactive segments, then close them after sync. There
1395 * may be some inactive segments left opened after error, but that is
1396 * harmless. We don't bother to clean them up and take a risk of further
1397 * trouble. The next mdclose() will soon close them.
1398 */
1399 while (_mdfd_openseg(reln, forknum, segno, 0) != NULL)
1400 segno++;
1401
1402 while (segno > 0)
1403 {
1404 MdfdVec *v = &reln->md_seg_fds[forknum][segno - 1];
1405
1406 register_dirty_segment(reln, forknum, v);
1407
1408 /* Close inactive segments immediately */
1409 if (segno > min_inactive_seg)
1410 {
1411 FileClose(v->mdfd_vfd);
1412 _fdvec_resize(reln, forknum, segno - 1);
1413 }
1414
1415 segno--;
1416 }
1417 }
1418
1419 /*
1420 * mdimmedsync() -- Immediately sync a relation to stable storage.
1421 *
1422 * Note that only writes already issued are synced; this routine knows
1423 * nothing of dirty buffers that may exist inside the buffer manager. We
1424 * sync active and inactive segments; smgrDoPendingSyncs() relies on this.
1425 * Consider a relation skipping WAL. Suppose a checkpoint syncs blocks of
1426 * some segment, then mdtruncate() renders that segment inactive. If we
1427 * crash before the next checkpoint syncs the newly-inactive segment, that
1428 * segment may survive recovery, reintroducing unwanted data into the table.
1429 */
1430 void
1431 mdimmedsync(SMgrRelation reln, ForkNumber forknum)
1432 {
1433 int segno;
1434 int min_inactive_seg;
1435
1436 /*
1437 * NOTE: mdnblocks makes sure we have opened all active segments, so that
1438 * the loop below will get them all!
1439 */
1440 mdnblocks(reln, forknum);
1441
1442 min_inactive_seg = segno = reln->md_num_open_segs[forknum];
1443
1444 /*
1445 * Temporarily open inactive segments, then close them after sync. There
1446 * may be some inactive segments left opened after fsync() error, but that
1447 * is harmless. We don't bother to clean them up and take a risk of
1448 * further trouble. The next mdclose() will soon close them.
1449 */
1450 while (_mdfd_openseg(reln, forknum, segno, 0) != NULL)
1451 segno++;
1452
1453 while (segno > 0)
1454 {
1455 MdfdVec *v = &reln->md_seg_fds[forknum][segno - 1];
1456
1457 /*
1458 * fsyncs done through mdimmedsync() should be tracked in a separate
1459 * IOContext than those done through mdsyncfiletag() to differentiate
1460 * between unavoidable client backend fsyncs (e.g. those done during
1461 * index build) and those which ideally would have been done by the
1462 * checkpointer. Since other IO operations bypassing the buffer
1463 * manager could also be tracked in such an IOContext, wait until
1464 * these are also tracked to track immediate fsyncs.
1465 */
1466 if (FileSync(v->mdfd_vfd, WAIT_EVENT_DATA_FILE_IMMEDIATE_SYNC) < 0)
1467 ereport(data_sync_elevel(ERROR),
1468 (errcode_for_file_access(),
1469 errmsg("could not fsync file \"%s\": %m",
1470 FilePathName(v->mdfd_vfd))));
1471
1472 /* Close inactive segments immediately */
1473 if (segno > min_inactive_seg)
1474 {
1475 FileClose(v->mdfd_vfd);
1476 _fdvec_resize(reln, forknum, segno - 1);
1477 }
1478
1479 segno--;
1480 }
1481 }
1482
1483 int
1484 mdfd(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum, uint32 *off)
1485 {
1486 MdfdVec *v = mdopenfork(reln, forknum, EXTENSION_FAIL);
1487
1488 v = _mdfd_getseg(reln, forknum, blocknum, false,
1489 EXTENSION_FAIL);
1490
1491 *off = (off_t) BLCKSZ * (blocknum % ((BlockNumber) RELSEG_SIZE));
1492
1493 Assert(*off < (off_t) BLCKSZ * RELSEG_SIZE);
1494
1495 return FileGetRawDesc(v->mdfd_vfd);
1496 }
1497
1498 /*
1499 * register_dirty_segment() -- Mark a relation segment as needing fsync
1500 *
1501 * If there is a local pending-ops table, just make an entry in it for
1502 * ProcessSyncRequests to process later. Otherwise, try to pass off the
1503 * fsync request to the checkpointer process. If that fails, just do the
1504 * fsync locally before returning (we hope this will not happen often
1505 * enough to be a performance problem).
1506 */
1507 static void
1508 register_dirty_segment(SMgrRelation reln, ForkNumber forknum, MdfdVec *seg)
1509 {
1510 FileTag tag;
1511
1512 INIT_MD_FILETAG(tag, reln->smgr_rlocator.locator, forknum, seg->mdfd_segno);
1513
1514 /* Temp relations should never be fsync'd */
1515 Assert(!SmgrIsTemp(reln));
1516
1517 if (!RegisterSyncRequest(&tag, SYNC_REQUEST, false /* retryOnError */ ))
1518 {
1519 instr_time io_start;
1520
1521 ereport(DEBUG1,
1522 (errmsg_internal("could not forward fsync request because request queue is full")));
1523
1524 io_start = pgstat_prepare_io_time(track_io_timing);
1525
1526 if (FileSync(seg->mdfd_vfd, WAIT_EVENT_DATA_FILE_SYNC) < 0)
1527 ereport(data_sync_elevel(ERROR),
1528 (errcode_for_file_access(),
1529 errmsg("could not fsync file \"%s\": %m",
1530 FilePathName(seg->mdfd_vfd))));
1531
1532 /*
1533 * We have no way of knowing if the current IOContext is
1534 * IOCONTEXT_NORMAL or IOCONTEXT_[BULKREAD, BULKWRITE, VACUUM] at this
1535 * point, so count the fsync as being in the IOCONTEXT_NORMAL
1536 * IOContext. This is probably okay, because the number of backend
1537 * fsyncs doesn't say anything about the efficacy of the
1538 * BufferAccessStrategy. And counting both fsyncs done in
1539 * IOCONTEXT_NORMAL and IOCONTEXT_[BULKREAD, BULKWRITE, VACUUM] under
1540 * IOCONTEXT_NORMAL is likely clearer when investigating the number of
1541 * backend fsyncs.
1542 */
1543 pgstat_count_io_op_time(IOOBJECT_RELATION, IOCONTEXT_NORMAL,
1544 IOOP_FSYNC, io_start, 1, 0);
1545 }
1546 }
1547
1548 /*
1549 * register_unlink_segment() -- Schedule a file to be deleted after next checkpoint
1550 */
1551 static void
1552 register_unlink_segment(RelFileLocatorBackend rlocator, ForkNumber forknum,
1553 BlockNumber segno)
1554 {
1555 FileTag tag;
1556
1557 INIT_MD_FILETAG(tag, rlocator.locator, forknum, segno);
1558
1559 /* Should never be used with temp relations */
1560 Assert(!RelFileLocatorBackendIsTemp(rlocator));
1561
1562 RegisterSyncRequest(&tag, SYNC_UNLINK_REQUEST, true /* retryOnError */ );
1563 }
1564
1565 /*
1566 * register_forget_request() -- forget any fsyncs for a relation fork's segment
1567 */
1568 static void
1569 register_forget_request(RelFileLocatorBackend rlocator, ForkNumber forknum,
1570 BlockNumber segno)
1571 {
1572 FileTag tag;
1573
1574 INIT_MD_FILETAG(tag, rlocator.locator, forknum, segno);
1575
1576 RegisterSyncRequest(&tag, SYNC_FORGET_REQUEST, true /* retryOnError */ );
1577 }
1578
1579 /*
1580 * ForgetDatabaseSyncRequests -- forget any fsyncs and unlinks for a DB
1581 */
1582 void
1583 ForgetDatabaseSyncRequests(Oid dbid)
1584 {
1585 FileTag tag;
1586 RelFileLocator rlocator;
1587
1588 rlocator.dbOid = dbid;
1589 rlocator.spcOid = 0;
1590 rlocator.relNumber = 0;
1591
1592 INIT_MD_FILETAG(tag, rlocator, InvalidForkNumber, InvalidBlockNumber);
1593
1594 RegisterSyncRequest(&tag, SYNC_FILTER_REQUEST, true /* retryOnError */ );
1595 }
1596
1597 /*
1598 * DropRelationFiles -- drop files of all given relations
1599 */
1600 void
1601 DropRelationFiles(RelFileLocator *delrels, int ndelrels, bool isRedo)
1602 {
1603 SMgrRelation *srels;
1604 int i;
1605
1606 srels = palloc(sizeof(SMgrRelation) * ndelrels);
1607 for (i = 0; i < ndelrels; i++)
1608 {
1609 SMgrRelation srel = smgropen(delrels[i], INVALID_PROC_NUMBER);
1610
1611 if (isRedo)
1612 {
1613 ForkNumber fork;
1614
1615 for (fork = 0; fork <= MAX_FORKNUM; fork++)
1616 XLogDropRelation(delrels[i], fork);
1617 }
1618 srels[i] = srel;
1619 }
1620
1621 smgrdounlinkall(srels, ndelrels, isRedo);
1622
1623 for (i = 0; i < ndelrels; i++)
1624 smgrclose(srels[i]);
1625 pfree(srels);
1626 }
1627
1628
1629 /*
1630 * _fdvec_resize() -- Resize the fork's open segments array
1631 */
1632 static void
1633 _fdvec_resize(SMgrRelation reln,
1634 ForkNumber forknum,
1635 int nseg)
1636 {
1637 if (nseg == 0)
1638 {
1639 if (reln->md_num_open_segs[forknum] > 0)
1640 {
1641 pfree(reln->md_seg_fds[forknum]);
1642 reln->md_seg_fds[forknum] = NULL;
1643 }
1644 }
1645 else if (reln->md_num_open_segs[forknum] == 0)
1646 {
1647 reln->md_seg_fds[forknum] =
1648 MemoryContextAlloc(MdCxt, sizeof(MdfdVec) * nseg);
1649 }
1650 else if (nseg > reln->md_num_open_segs[forknum])
1651 {
1652 /*
1653 * It doesn't seem worthwhile complicating the code to amortize
1654 * repalloc() calls. Those are far faster than PathNameOpenFile() or
1655 * FileClose(), and the memory context internally will sometimes avoid
1656 * doing an actual reallocation.
1657 */
1658 reln->md_seg_fds[forknum] =
1659 repalloc(reln->md_seg_fds[forknum],
1660 sizeof(MdfdVec) * nseg);
1661 }
1662 else
1663 {
1664 /*
1665 * We don't reallocate a smaller array, because we want mdtruncate()
1666 * to be able to promise that it won't allocate memory, so that it is
1667 * allowed in a critical section. This means that a bit of space in
1668 * the array is now wasted, until the next time we add a segment and
1669 * reallocate.
1670 */
1671 }
1672
1673 reln->md_num_open_segs[forknum] = nseg;
1674 }
1675
1676 /*
1677 * Return the filename for the specified segment of the relation. The
1678 * returned string is palloc'd.
1679 */
1680 static MdPathStr
1681 _mdfd_segpath(SMgrRelation reln, ForkNumber forknum, BlockNumber segno)
1682 {
1683 RelPathStr path;
1684 MdPathStr fullpath;
1685
1686 path = relpath(reln->smgr_rlocator, forknum);
1687
1688 if (segno > 0)
1689 sprintf(fullpath.str, "%s.%u", path.str, segno);
1690 else
1691 strcpy(fullpath.str, path.str);
1692
1693 return fullpath;
1694 }
1695
1696 /*
1697 * Open the specified segment of the relation,
1698 * and make a MdfdVec object for it. Returns NULL on failure.
1699 */
1700 static MdfdVec *
1701 _mdfd_openseg(SMgrRelation reln, ForkNumber forknum, BlockNumber segno,
1702 int oflags)
1703 {
1704 MdfdVec *v;
1705 File fd;
1706 MdPathStr fullpath;
1707
1708 fullpath = _mdfd_segpath(reln, forknum, segno);
1709
1710 /* open the file */
1711 fd = PathNameOpenFile(fullpath.str, _mdfd_open_flags() | oflags);
1712
1713 if (fd < 0)
1714 return NULL;
1715
1716 /*
1717 * Segments are always opened in order from lowest to highest, so we must
1718 * be adding a new one at the end.
1719 */
1720 Assert(segno == reln->md_num_open_segs[forknum]);
1721
1722 _fdvec_resize(reln, forknum, segno + 1);
1723
1724 /* fill the entry */
1725 v = &reln->md_seg_fds[forknum][segno];
1726 v->mdfd_vfd = fd;
1727 v->mdfd_segno = segno;
1728
1729 Assert(_mdnblocks(reln, forknum, v) <= ((BlockNumber) RELSEG_SIZE));
1730
1731 /* all done */
1732 return v;
1733 }
1734
1735 /*
1736 * _mdfd_getseg() -- Find the segment of the relation holding the
1737 * specified block.
1738 *
1739 * If the segment doesn't exist, we ereport, return NULL, or create the
1740 * segment, according to "behavior". Note: skipFsync is only used in the
1741 * EXTENSION_CREATE case.
1742 */
1743 static MdfdVec *
1744 _mdfd_getseg(SMgrRelation reln, ForkNumber forknum, BlockNumber blkno,
1745 bool skipFsync, int behavior)
1746 {
1747 MdfdVec *v;
1748 BlockNumber targetseg;
1749 BlockNumber nextsegno;
1750
1751 /* some way to handle non-existent segments needs to be specified */
1752 Assert(behavior &
1753 (EXTENSION_FAIL | EXTENSION_CREATE | EXTENSION_RETURN_NULL |
1754 EXTENSION_DONT_OPEN));
1755
1756 targetseg = blkno / ((BlockNumber) RELSEG_SIZE);
1757
1758 /* if an existing and opened segment, we're done */
1759 if (targetseg < reln->md_num_open_segs[forknum])
1760 {
1761 v = &reln->md_seg_fds[forknum][targetseg];
1762 return v;
1763 }
1764
1765 /* The caller only wants the segment if we already had it open. */
1766 if (behavior & EXTENSION_DONT_OPEN)
1767 return NULL;
1768
1769 /*
1770 * The target segment is not yet open. Iterate over all the segments
1771 * between the last opened and the target segment. This way missing
1772 * segments either raise an error, or get created (according to
1773 * 'behavior'). Start with either the last opened, or the first segment if
1774 * none was opened before.
1775 */
1776 if (reln->md_num_open_segs[forknum] > 0)
1777 v = &reln->md_seg_fds[forknum][reln->md_num_open_segs[forknum] - 1];
1778 else
1779 {
1780 v = mdopenfork(reln, forknum, behavior);
1781 if (!v)
1782 return NULL; /* if behavior & EXTENSION_RETURN_NULL */
1783 }
1784
1785 for (nextsegno = reln->md_num_open_segs[forknum];
1786 nextsegno <= targetseg; nextsegno++)
1787 {
1788 BlockNumber nblocks = _mdnblocks(reln, forknum, v);
1789 int flags = 0;
1790
1791 Assert(nextsegno == v->mdfd_segno + 1);
1792
1793 if (nblocks > ((BlockNumber) RELSEG_SIZE))
1794 elog(FATAL, "segment too big");
1795
1796 if ((behavior & EXTENSION_CREATE) ||
1797 (InRecovery && (behavior & EXTENSION_CREATE_RECOVERY)))
1798 {
1799 /*
1800 * Normally we will create new segments only if authorized by the
1801 * caller (i.e., we are doing mdextend()). But when doing WAL
1802 * recovery, create segments anyway; this allows cases such as
1803 * replaying WAL data that has a write into a high-numbered
1804 * segment of a relation that was later deleted. We want to go
1805 * ahead and create the segments so we can finish out the replay.
1806 *
1807 * We have to maintain the invariant that segments before the last
1808 * active segment are of size RELSEG_SIZE; therefore, if
1809 * extending, pad them out with zeroes if needed. (This only
1810 * matters if in recovery, or if the caller is extending the
1811 * relation discontiguously, but that can happen in hash indexes.)
1812 */
1813 if (nblocks < ((BlockNumber) RELSEG_SIZE))
1814 {
1815 char *zerobuf = palloc_aligned(BLCKSZ, PG_IO_ALIGN_SIZE,
1816 MCXT_ALLOC_ZERO);
1817
1818 mdextend(reln, forknum,
1819 nextsegno * ((BlockNumber) RELSEG_SIZE) - 1,
1820 zerobuf, skipFsync);
1821 pfree(zerobuf);
1822 }
1823 flags = O_CREAT;
1824 }
1825 else if (nblocks < ((BlockNumber) RELSEG_SIZE))
1826 {
1827 /*
1828 * When not extending, only open the next segment if the current
1829 * one is exactly RELSEG_SIZE. If not (this branch), either
1830 * return NULL or fail.
1831 */
1832 if (behavior & EXTENSION_RETURN_NULL)
1833 {
1834 /*
1835 * Some callers discern between reasons for _mdfd_getseg()
1836 * returning NULL based on errno. As there's no failing
1837 * syscall involved in this case, explicitly set errno to
1838 * ENOENT, as that seems the closest interpretation.
1839 */
1840 errno = ENOENT;
1841 return NULL;
1842 }
1843
1844 ereport(ERROR,
1845 (errcode_for_file_access(),
1846 errmsg("could not open file \"%s\" (target block %u): previous segment is only %u blocks",
1847 _mdfd_segpath(reln, forknum, nextsegno).str,
1848 blkno, nblocks)));
1849 }
1850
1851 v = _mdfd_openseg(reln, forknum, nextsegno, flags);
1852
1853 if (v == NULL)
1854 {
1855 if ((behavior & EXTENSION_RETURN_NULL) &&
1856 FILE_POSSIBLY_DELETED(errno))
1857 return NULL;
1858 ereport(ERROR,
1859 (errcode_for_file_access(),
1860 errmsg("could not open file \"%s\" (target block %u): %m",
1861 _mdfd_segpath(reln, forknum, nextsegno).str,
1862 blkno)));
1863 }
1864 }
1865
1866 return v;
1867 }
1868
1869 /*
1870 * Get number of blocks present in a single disk file
1871 */
1872 static BlockNumber
1873 _mdnblocks(SMgrRelation reln, ForkNumber forknum, MdfdVec *seg)
1874 {
1875 off_t len;
1876
1877 len = FileSize(seg->mdfd_vfd);
1878 if (len < 0)
1879 ereport(ERROR,
1880 (errcode_for_file_access(),
1881 errmsg("could not seek to end of file \"%s\": %m",
1882 FilePathName(seg->mdfd_vfd))));
1883 /* note that this calculation will ignore any partial block at EOF */
1884 return (BlockNumber) (len / BLCKSZ);
1885 }
1886
1887 /*
1888 * Sync a file to disk, given a file tag. Write the path into an output
1889 * buffer so the caller can use it in error messages.
1890 *
1891 * Return 0 on success, -1 on failure, with errno set.
1892 */
1893 int
1894 mdsyncfiletag(const FileTag *ftag, char *path)
1895 {
1896 SMgrRelation reln = smgropen(ftag->rlocator, INVALID_PROC_NUMBER);
1897 File file;
1898 instr_time io_start;
1899 bool need_to_close;
1900 int result,
1901 save_errno;
1902
1903 /* See if we already have the file open, or need to open it. */
1904 if (ftag->segno < reln->md_num_open_segs[ftag->forknum])
1905 {
1906 file = reln->md_seg_fds[ftag->forknum][ftag->segno].mdfd_vfd;
1907 strlcpy(path, FilePathName(file), MAXPGPATH);
1908 need_to_close = false;
1909 }
1910 else
1911 {
1912 MdPathStr p;
1913
1914 p = _mdfd_segpath(reln, ftag->forknum, ftag->segno);
1915 strlcpy(path, p.str, MD_PATH_STR_MAXLEN);
1916
1917 file = PathNameOpenFile(path, _mdfd_open_flags());
1918 if (file < 0)
1919 return -1;
1920 need_to_close = true;
1921 }
1922
1923 io_start = pgstat_prepare_io_time(track_io_timing);
1924
1925 /* Sync the file. */
1926 result = FileSync(file, WAIT_EVENT_DATA_FILE_SYNC);
1927 save_errno = errno;
1928
1929 if (need_to_close)
1930 FileClose(file);
1931
1932 pgstat_count_io_op_time(IOOBJECT_RELATION, IOCONTEXT_NORMAL,
1933 IOOP_FSYNC, io_start, 1, 0);
1934
1935 errno = save_errno;
1936 return result;
1937 }
1938
1939 /*
1940 * Unlink a file, given a file tag. Write the path into an output
1941 * buffer so the caller can use it in error messages.
1942 *
1943 * Return 0 on success, -1 on failure, with errno set.
1944 */
1945 int
1946 mdunlinkfiletag(const FileTag *ftag, char *path)
1947 {
1948 RelPathStr p;
1949
1950 /* Compute the path. */
1951 p = relpathperm(ftag->rlocator, MAIN_FORKNUM);
1952 strlcpy(path, p.str, MAXPGPATH);
1953
1954 /* Try to unlink the file. */
1955 return unlink(path);
1956 }
1957
1958 /*
1959 * Check if a given candidate request matches a given tag, when processing
1960 * a SYNC_FILTER_REQUEST request. This will be called for all pending
1961 * requests to find out whether to forget them.
1962 */
1963 bool
1964 mdfiletagmatches(const FileTag *ftag, const FileTag *candidate)
1965 {
1966 /*
1967 * For now we only use filter requests as a way to drop all scheduled
1968 * callbacks relating to a given database, when dropping the database.
1969 * We'll return true for all candidates that have the same database OID as
1970 * the ftag from the SYNC_FILTER_REQUEST request, so they're forgotten.
1971 */
1972 return ftag->rlocator.dbOid == candidate->rlocator.dbOid;
1973 }
1974
1975 /*
1976 * AIO completion callback for mdstartreadv().
1977 */
1978 static PgAioResult
1979 md_readv_complete(PgAioHandle *ioh, PgAioResult prior_result, uint8 cb_data)
1980 {
1981 PgAioTargetData *td = pgaio_io_get_target_data(ioh);
1982 PgAioResult result = prior_result;
1983
1984 if (prior_result.result < 0)
1985 {
1986 result.status = PGAIO_RS_ERROR;
1987 result.id = PGAIO_HCB_MD_READV;
1988 /* For "hard" errors, track the error number in error_data */
1989 result.error_data = -prior_result.result;
1990 result.result = 0;
1991
1992 /*
1993 * Immediately log a message about the IO error, but only to the
1994 * server log. The reason to do so immediately is that the originator
1995 * might not process the query result immediately (because it is busy
1996 * doing another part of query processing) or at all (e.g. if it was
1997 * cancelled or errored out due to another IO also failing). The
1998 * definer of the IO will emit an ERROR when processing the IO's
1999 * results
2000 */
2001 pgaio_result_report(result, td, LOG_SERVER_ONLY);
2002
2003 return result;
2004 }
2005
2006 /*
2007 * As explained above smgrstartreadv(), the smgr API operates on the level
2008 * of blocks, rather than bytes. Convert.
2009 */
2010 result.result /= BLCKSZ;
2011
2012 Assert(result.result <= td->smgr.nblocks);
2013
2014 if (result.result == 0)
2015 {
2016 /* consider 0 blocks read a failure */
2017 result.status = PGAIO_RS_ERROR;
2018 result.id = PGAIO_HCB_MD_READV;
2019 result.error_data = 0;
2020
2021 /* see comment above the "hard error" case */
2022 pgaio_result_report(result, td, LOG_SERVER_ONLY);
2023
2024 return result;
2025 }
2026
2027 if (result.status != PGAIO_RS_ERROR &&
2028 result.result < td->smgr.nblocks)
2029 {
2030 /* partial reads should be retried at upper level */
2031 result.status = PGAIO_RS_PARTIAL;
2032 result.id = PGAIO_HCB_MD_READV;
2033 }
2034
2035 return result;
2036 }
2037
2038 /*
2039 * AIO error reporting callback for mdstartreadv().
2040 *
2041 * Errors are encoded as follows:
2042 * - PgAioResult.error_data != 0 encodes IO that failed with that errno
2043 * - PgAioResult.error_data == 0 encodes IO that didn't read all data
2044 */
2045 static void
2046 md_readv_report(PgAioResult result, const PgAioTargetData *td, int elevel)
2047 {
2048 RelPathStr path;
2049
2050 path = relpathbackend(td->smgr.rlocator,
2051 td->smgr.is_temp ? MyProcNumber : INVALID_PROC_NUMBER,
2052 td->smgr.forkNum);
2053
2054 if (result.error_data != 0)
2055 {
2056 /* for errcode_for_file_access() and %m */
2057 errno = result.error_data;
2058
2059 ereport(elevel,
2060 errcode_for_file_access(),
2061 errmsg("could not read blocks %u..%u in file \"%s\": %m",
2062 td->smgr.blockNum,
2063 td->smgr.blockNum + td->smgr.nblocks - 1,
2064 path.str));
2065 }
2066 else
2067 {
2068 /*
2069 * NB: This will typically only be output in debug messages, while
2070 * retrying a partial IO.
2071 */
2072 ereport(elevel,
2073 errcode(ERRCODE_DATA_CORRUPTED),
2074 errmsg("could not read blocks %u..%u in file \"%s\": read only %zu of %zu bytes",
2075 td->smgr.blockNum,
2076 td->smgr.blockNum + td->smgr.nblocks - 1,
2077 path.str,
2078 result.result * (size_t) BLCKSZ,
2079 td->smgr.nblocks * (size_t) BLCKSZ));
2080 }
2081 }