Line data Source code
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-2023, 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/xlog.h"
29 : #include "access/xlogutils.h"
30 : #include "commands/tablespace.h"
31 : #include "miscadmin.h"
32 : #include "pg_trace.h"
33 : #include "pgstat.h"
34 : #include "postmaster/bgwriter.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/hsearch.h"
42 : #include "utils/memutils.h"
43 :
44 : /*
45 : * The magnetic disk storage manager keeps track of open file
46 : * descriptors in its own descriptor pool. This is done to make it
47 : * easier to support relations that are larger than the operating
48 : * system's file size limit (often 2GBytes). In order to do that,
49 : * we break relations up into "segment" files that are each shorter than
50 : * the OS file size limit. The segment size is set by the RELSEG_SIZE
51 : * configuration constant in pg_config.h.
52 : *
53 : * On disk, a relation must consist of consecutively numbered segment
54 : * files in the pattern
55 : * -- Zero or more full segments of exactly RELSEG_SIZE blocks each
56 : * -- Exactly one partial segment of size 0 <= size < RELSEG_SIZE blocks
57 : * -- Optionally, any number of inactive segments of size 0 blocks.
58 : * The full and partial segments are collectively the "active" segments.
59 : * Inactive segments are those that once contained data but are currently
60 : * not needed because of an mdtruncate() operation. The reason for leaving
61 : * them present at size zero, rather than unlinking them, is that other
62 : * backends and/or the checkpointer might be holding open file references to
63 : * such segments. If the relation expands again after mdtruncate(), such
64 : * that a deactivated segment becomes active again, it is important that
65 : * such file references still be valid --- else data might get written
66 : * out to an unlinked old copy of a segment file that will eventually
67 : * disappear.
68 : *
69 : * File descriptors are stored in the per-fork md_seg_fds arrays inside
70 : * SMgrRelation. The length of these arrays is stored in md_num_open_segs.
71 : * Note that a fork's md_num_open_segs having a specific value does not
72 : * necessarily mean the relation doesn't have additional segments; we may
73 : * just not have opened the next segment yet. (We could not have "all
74 : * segments are in the array" as an invariant anyway, since another backend
75 : * could extend the relation while we aren't looking.) We do not have
76 : * entries for inactive segments, however; as soon as we find a partial
77 : * segment, we assume that any subsequent segments are inactive.
78 : *
79 : * The entire MdfdVec array is palloc'd in the MdCxt memory context.
80 : */
81 :
82 : typedef struct _MdfdVec
83 : {
84 : File mdfd_vfd; /* fd number in fd.c's pool */
85 : BlockNumber mdfd_segno; /* segment number, from 0 */
86 : } MdfdVec;
87 :
88 : static MemoryContext MdCxt; /* context for all MdfdVec objects */
89 :
90 :
91 : /* Populate a file tag describing an md.c segment file. */
92 : #define INIT_MD_FILETAG(a,xx_rlocator,xx_forknum,xx_segno) \
93 : ( \
94 : memset(&(a), 0, sizeof(FileTag)), \
95 : (a).handler = SYNC_HANDLER_MD, \
96 : (a).rlocator = (xx_rlocator), \
97 : (a).forknum = (xx_forknum), \
98 : (a).segno = (xx_segno) \
99 : )
100 :
101 :
102 : /*** behavior for mdopen & _mdfd_getseg ***/
103 : /* ereport if segment not present */
104 : #define EXTENSION_FAIL (1 << 0)
105 : /* return NULL if segment not present */
106 : #define EXTENSION_RETURN_NULL (1 << 1)
107 : /* create new segments as needed */
108 : #define EXTENSION_CREATE (1 << 2)
109 : /* create new segments if needed during recovery */
110 : #define EXTENSION_CREATE_RECOVERY (1 << 3)
111 : /*
112 : * Allow opening segments which are preceded by segments smaller than
113 : * RELSEG_SIZE, e.g. inactive segments (see above). Note that this breaks
114 : * mdnblocks() and related functionality henceforth - which currently is ok,
115 : * because this is only required in the checkpointer which never uses
116 : * mdnblocks().
117 : */
118 : #define EXTENSION_DONT_CHECK_SIZE (1 << 4)
119 : /* don't try to open a segment, if not already open */
120 : #define EXTENSION_DONT_OPEN (1 << 5)
121 :
122 :
123 : /* local routines */
124 : static void mdunlinkfork(RelFileLocatorBackend rlocator, ForkNumber forknum,
125 : bool isRedo);
126 : static MdfdVec *mdopenfork(SMgrRelation reln, ForkNumber forknum, int behavior);
127 : static void register_dirty_segment(SMgrRelation reln, ForkNumber forknum,
128 : MdfdVec *seg);
129 : static void register_unlink_segment(RelFileLocatorBackend rlocator, ForkNumber forknum,
130 : BlockNumber segno);
131 : static void register_forget_request(RelFileLocatorBackend rlocator, ForkNumber forknum,
132 : BlockNumber segno);
133 : static void _fdvec_resize(SMgrRelation reln,
134 : ForkNumber forknum,
135 : int nseg);
136 : static char *_mdfd_segpath(SMgrRelation reln, ForkNumber forknum,
137 : BlockNumber segno);
138 : static MdfdVec *_mdfd_openseg(SMgrRelation reln, ForkNumber forknum,
139 : BlockNumber segno, int oflags);
140 : static MdfdVec *_mdfd_getseg(SMgrRelation reln, ForkNumber forknum,
141 : BlockNumber blkno, bool skipFsync, int behavior);
142 : static BlockNumber _mdnblocks(SMgrRelation reln, ForkNumber forknum,
143 : MdfdVec *seg);
144 :
145 : static inline int
146 1878010 : _mdfd_open_flags(void)
147 : {
148 1878010 : int flags = O_RDWR | PG_BINARY;
149 :
150 1878010 : if (io_direct_flags & IO_DIRECT_DATA)
151 604 : flags |= PG_O_DIRECT;
152 :
153 1878010 : return flags;
154 : }
155 :
156 : /*
157 : * mdinit() -- Initialize private state for magnetic disk storage manager.
158 : */
159 : void
160 27816 : mdinit(void)
161 : {
162 27816 : MdCxt = AllocSetContextCreate(TopMemoryContext,
163 : "MdSmgr",
164 : ALLOCSET_DEFAULT_SIZES);
165 27816 : }
166 :
167 : /*
168 : * mdexists() -- Does the physical file exist?
169 : *
170 : * Note: this will return true for lingering files, with pending deletions
171 : */
172 : bool
173 1731224 : mdexists(SMgrRelation reln, ForkNumber forknum)
174 : {
175 : /*
176 : * Close it first, to ensure that we notice if the fork has been unlinked
177 : * since we opened it. As an optimization, we can skip that in recovery,
178 : * which already closes relations when dropping them.
179 : */
180 1731224 : if (!InRecovery)
181 772306 : mdclose(reln, forknum);
182 :
183 1731224 : return (mdopenfork(reln, forknum, EXTENSION_RETURN_NULL) != NULL);
184 : }
185 :
186 : /*
187 : * mdcreate() -- Create a new relation on magnetic disk.
188 : *
189 : * If isRedo is true, it's okay for the relation to exist already.
190 : */
191 : void
192 5386914 : mdcreate(SMgrRelation reln, ForkNumber forknum, bool isRedo)
193 : {
194 : MdfdVec *mdfd;
195 : char *path;
196 : File fd;
197 :
198 5386914 : if (isRedo && reln->md_num_open_segs[forknum] > 0)
199 5131684 : return; /* created and opened already... */
200 :
201 : Assert(reln->md_num_open_segs[forknum] == 0);
202 :
203 : /*
204 : * We may be using the target table space for the first time in this
205 : * database, so create a per-database subdirectory if needed.
206 : *
207 : * XXX this is a fairly ugly violation of module layering, but this seems
208 : * to be the best place to put the check. Maybe TablespaceCreateDbspace
209 : * should be here and not in commands/tablespace.c? But that would imply
210 : * importing a lot of stuff that smgr.c oughtn't know, either.
211 : */
212 255230 : TablespaceCreateDbspace(reln->smgr_rlocator.locator.spcOid,
213 : reln->smgr_rlocator.locator.dbOid,
214 : isRedo);
215 :
216 255230 : path = relpath(reln->smgr_rlocator, forknum);
217 :
218 255230 : fd = PathNameOpenFile(path, _mdfd_open_flags() | O_CREAT | O_EXCL);
219 :
220 255230 : if (fd < 0)
221 : {
222 7252 : int save_errno = errno;
223 :
224 7252 : if (isRedo)
225 7252 : fd = PathNameOpenFile(path, _mdfd_open_flags());
226 7252 : if (fd < 0)
227 : {
228 : /* be sure to report the error reported by create, not open */
229 0 : errno = save_errno;
230 0 : ereport(ERROR,
231 : (errcode_for_file_access(),
232 : errmsg("could not create file \"%s\": %m", path)));
233 : }
234 : }
235 :
236 255230 : pfree(path);
237 :
238 255230 : _fdvec_resize(reln, forknum, 1);
239 255230 : mdfd = &reln->md_seg_fds[forknum][0];
240 255230 : mdfd->mdfd_vfd = fd;
241 255230 : mdfd->mdfd_segno = 0;
242 :
243 255230 : if (!SmgrIsTemp(reln))
244 249312 : register_dirty_segment(reln, forknum, mdfd);
245 : }
246 :
247 : /*
248 : * mdunlink() -- Unlink a relation.
249 : *
250 : * Note that we're passed a RelFileLocatorBackend --- by the time this is called,
251 : * there won't be an SMgrRelation hashtable entry anymore.
252 : *
253 : * forknum can be a fork number to delete a specific fork, or InvalidForkNumber
254 : * to delete all forks.
255 : *
256 : * For regular relations, we don't unlink the first segment file of the rel,
257 : * but just truncate it to zero length, and record a request to unlink it after
258 : * the next checkpoint. Additional segments can be unlinked immediately,
259 : * however. Leaving the empty file in place prevents that relfilenumber
260 : * from being reused. The scenario this protects us from is:
261 : * 1. We delete a relation (and commit, and actually remove its file).
262 : * 2. We create a new relation, which by chance gets the same relfilenumber as
263 : * the just-deleted one (OIDs must've wrapped around for that to happen).
264 : * 3. We crash before another checkpoint occurs.
265 : * During replay, we would delete the file and then recreate it, which is fine
266 : * if the contents of the file were repopulated by subsequent WAL entries.
267 : * But if we didn't WAL-log insertions, but instead relied on fsyncing the
268 : * file after populating it (as we do at wal_level=minimal), the contents of
269 : * the file would be lost forever. By leaving the empty file until after the
270 : * next checkpoint, we prevent reassignment of the relfilenumber until it's
271 : * safe, because relfilenumber assignment skips over any existing file.
272 : *
273 : * Additional segments, if any, are truncated and then unlinked. The reason
274 : * for truncating is that other backends may still hold open FDs for these at
275 : * the smgr level, so that the kernel can't remove the file yet. We want to
276 : * reclaim the disk space right away despite that.
277 : *
278 : * We do not need to go through this dance for temp relations, though, because
279 : * we never make WAL entries for temp rels, and so a temp rel poses no threat
280 : * to the health of a regular rel that has taken over its relfilenumber.
281 : * The fact that temp rels and regular rels have different file naming
282 : * patterns provides additional safety. Other backends shouldn't have open
283 : * FDs for them, either.
284 : *
285 : * We also don't do it while performing a binary upgrade. There is no reuse
286 : * hazard in that case, since after a crash or even a simple ERROR, the
287 : * upgrade fails and the whole cluster must be recreated from scratch.
288 : * Furthermore, it is important to remove the files from disk immediately,
289 : * because we may be about to reuse the same relfilenumber.
290 : *
291 : * All the above applies only to the relation's main fork; other forks can
292 : * just be removed immediately, since they are not needed to prevent the
293 : * relfilenumber from being recycled. Also, we do not carefully
294 : * track whether other forks have been created or not, but just attempt to
295 : * unlink them unconditionally; so we should never complain about ENOENT.
296 : *
297 : * If isRedo is true, it's unsurprising for the relation to be already gone.
298 : * Also, we should remove the file immediately instead of queuing a request
299 : * for later, since during redo there's no possibility of creating a
300 : * conflicting relation.
301 : *
302 : * Note: we currently just never warn about ENOENT at all. We could warn in
303 : * the main-fork, non-isRedo case, but it doesn't seem worth the trouble.
304 : *
305 : * Note: any failure should be reported as WARNING not ERROR, because
306 : * we are usually not in a transaction anymore when this is called.
307 : */
308 : void
309 301928 : mdunlink(RelFileLocatorBackend rlocator, ForkNumber forknum, bool isRedo)
310 : {
311 : /* Now do the per-fork work */
312 301928 : if (forknum == InvalidForkNumber)
313 : {
314 0 : for (forknum = 0; forknum <= MAX_FORKNUM; forknum++)
315 0 : mdunlinkfork(rlocator, forknum, isRedo);
316 : }
317 : else
318 301928 : mdunlinkfork(rlocator, forknum, isRedo);
319 301928 : }
320 :
321 : /*
322 : * Truncate a file to release disk space.
323 : */
324 : static int
325 352198 : do_truncate(const char *path)
326 : {
327 : int save_errno;
328 : int ret;
329 :
330 352198 : ret = pg_truncate(path, 0);
331 :
332 : /* Log a warning here to avoid repetition in callers. */
333 352198 : if (ret < 0 && errno != ENOENT)
334 : {
335 0 : save_errno = errno;
336 0 : ereport(WARNING,
337 : (errcode_for_file_access(),
338 : errmsg("could not truncate file \"%s\": %m", path)));
339 0 : errno = save_errno;
340 : }
341 :
342 352198 : return ret;
343 : }
344 :
345 : static void
346 301928 : mdunlinkfork(RelFileLocatorBackend rlocator, ForkNumber forknum, bool isRedo)
347 : {
348 : char *path;
349 : int ret;
350 : int save_errno;
351 :
352 301928 : path = relpath(rlocator, forknum);
353 :
354 : /*
355 : * Truncate and then unlink the first segment, or just register a request
356 : * to unlink it later, as described in the comments for mdunlink().
357 : */
358 301928 : if (isRedo || IsBinaryUpgrade || forknum != MAIN_FORKNUM ||
359 63290 : RelFileLocatorBackendIsTemp(rlocator))
360 : {
361 244294 : if (!RelFileLocatorBackendIsTemp(rlocator))
362 : {
363 : /* Prevent other backends' fds from holding on to the disk space */
364 221670 : ret = do_truncate(path);
365 :
366 : /* Forget any pending sync requests for the first segment */
367 221670 : save_errno = errno;
368 221670 : register_forget_request(rlocator, forknum, 0 /* first seg */ );
369 221670 : errno = save_errno;
370 : }
371 : else
372 22624 : ret = 0;
373 :
374 : /* Next unlink the file, unless it was already found to be missing */
375 244294 : if (ret >= 0 || errno != ENOENT)
376 : {
377 37892 : ret = unlink(path);
378 37892 : if (ret < 0 && errno != ENOENT)
379 : {
380 0 : save_errno = errno;
381 0 : ereport(WARNING,
382 : (errcode_for_file_access(),
383 : errmsg("could not remove file \"%s\": %m", path)));
384 0 : errno = save_errno;
385 : }
386 : }
387 : }
388 : else
389 : {
390 : /* Prevent other backends' fds from holding on to the disk space */
391 57634 : ret = do_truncate(path);
392 :
393 : /* Register request to unlink first segment later */
394 57634 : save_errno = errno;
395 57634 : register_unlink_segment(rlocator, forknum, 0 /* first seg */ );
396 57634 : errno = save_errno;
397 : }
398 :
399 : /*
400 : * Delete any additional segments.
401 : *
402 : * Note that because we loop until getting ENOENT, we will correctly
403 : * remove all inactive segments as well as active ones. Ideally we'd
404 : * continue the loop until getting exactly that errno, but that risks an
405 : * infinite loop if the problem is directory-wide (for instance, if we
406 : * suddenly can't read the data directory itself). We compromise by
407 : * continuing after a non-ENOENT truncate error, but stopping after any
408 : * unlink error. If there is indeed a directory-wide problem, additional
409 : * unlink attempts wouldn't work anyway.
410 : */
411 301928 : if (ret >= 0 || errno != ENOENT)
412 : {
413 78812 : char *segpath = (char *) palloc(strlen(path) + 12);
414 : BlockNumber segno;
415 :
416 78812 : for (segno = 1;; segno++)
417 : {
418 78812 : sprintf(segpath, "%s.%u", path, segno);
419 :
420 78812 : if (!RelFileLocatorBackendIsTemp(rlocator))
421 : {
422 : /*
423 : * Prevent other backends' fds from holding on to the disk
424 : * space. We're done if we see ENOENT, though.
425 : */
426 72894 : if (do_truncate(segpath) < 0 && errno == ENOENT)
427 72894 : break;
428 :
429 : /*
430 : * Forget any pending sync requests for this segment before we
431 : * try to unlink.
432 : */
433 0 : register_forget_request(rlocator, forknum, segno);
434 : }
435 :
436 5918 : if (unlink(segpath) < 0)
437 : {
438 : /* ENOENT is expected after the last segment... */
439 5918 : if (errno != ENOENT)
440 0 : ereport(WARNING,
441 : (errcode_for_file_access(),
442 : errmsg("could not remove file \"%s\": %m", segpath)));
443 5918 : break;
444 : }
445 : }
446 78812 : pfree(segpath);
447 : }
448 :
449 301928 : pfree(path);
450 301928 : }
451 :
452 : /*
453 : * mdextend() -- Add a block to the specified relation.
454 : *
455 : * The semantics are nearly the same as mdwrite(): write at the
456 : * specified position. However, this is to be used for the case of
457 : * extending a relation (i.e., blocknum is at or beyond the current
458 : * EOF). Note that we assume writing a block beyond current EOF
459 : * causes intervening file space to become filled with zeroes.
460 : */
461 : void
462 195370 : mdextend(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum,
463 : const void *buffer, bool skipFsync)
464 : {
465 : off_t seekpos;
466 : int nbytes;
467 : MdfdVec *v;
468 :
469 : /* If this build supports direct I/O, the buffer must be I/O aligned. */
470 : if (PG_O_DIRECT != 0 && PG_IO_ALIGN_SIZE <= BLCKSZ)
471 : Assert((uintptr_t) buffer == TYPEALIGN(PG_IO_ALIGN_SIZE, buffer));
472 :
473 : /* This assert is too expensive to have on normally ... */
474 : #ifdef CHECK_WRITE_VS_EXTEND
475 : Assert(blocknum >= mdnblocks(reln, forknum));
476 : #endif
477 :
478 : /*
479 : * If a relation manages to grow to 2^32-1 blocks, refuse to extend it any
480 : * more --- we mustn't create a block whose number actually is
481 : * InvalidBlockNumber. (Note that this failure should be unreachable
482 : * because of upstream checks in bufmgr.c.)
483 : */
484 195370 : if (blocknum == InvalidBlockNumber)
485 0 : ereport(ERROR,
486 : (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
487 : errmsg("cannot extend file \"%s\" beyond %u blocks",
488 : relpath(reln->smgr_rlocator, forknum),
489 : InvalidBlockNumber)));
490 :
491 195370 : v = _mdfd_getseg(reln, forknum, blocknum, skipFsync, EXTENSION_CREATE);
492 :
493 195370 : seekpos = (off_t) BLCKSZ * (blocknum % ((BlockNumber) RELSEG_SIZE));
494 :
495 : Assert(seekpos < (off_t) BLCKSZ * RELSEG_SIZE);
496 :
497 195370 : if ((nbytes = FileWrite(v->mdfd_vfd, buffer, BLCKSZ, seekpos, WAIT_EVENT_DATA_FILE_EXTEND)) != BLCKSZ)
498 : {
499 0 : if (nbytes < 0)
500 0 : ereport(ERROR,
501 : (errcode_for_file_access(),
502 : errmsg("could not extend file \"%s\": %m",
503 : FilePathName(v->mdfd_vfd)),
504 : errhint("Check free disk space.")));
505 : /* short write: complain appropriately */
506 0 : ereport(ERROR,
507 : (errcode(ERRCODE_DISK_FULL),
508 : errmsg("could not extend file \"%s\": wrote only %d of %d bytes at block %u",
509 : FilePathName(v->mdfd_vfd),
510 : nbytes, BLCKSZ, blocknum),
511 : errhint("Check free disk space.")));
512 : }
513 :
514 195370 : if (!skipFsync && !SmgrIsTemp(reln))
515 54 : register_dirty_segment(reln, forknum, v);
516 :
517 : Assert(_mdnblocks(reln, forknum, v) <= ((BlockNumber) RELSEG_SIZE));
518 195370 : }
519 :
520 : /*
521 : * mdzeroextend() -- Add new zeroed out blocks to the specified relation.
522 : *
523 : * Similar to mdextend(), except the relation can be extended by multiple
524 : * blocks at once and the added blocks will be filled with zeroes.
525 : */
526 : void
527 350086 : mdzeroextend(SMgrRelation reln, ForkNumber forknum,
528 : BlockNumber blocknum, int nblocks, bool skipFsync)
529 : {
530 : MdfdVec *v;
531 350086 : BlockNumber curblocknum = blocknum;
532 350086 : int remblocks = nblocks;
533 :
534 : Assert(nblocks > 0);
535 :
536 : /* This assert is too expensive to have on normally ... */
537 : #ifdef CHECK_WRITE_VS_EXTEND
538 : Assert(blocknum >= mdnblocks(reln, forknum));
539 : #endif
540 :
541 : /*
542 : * If a relation manages to grow to 2^32-1 blocks, refuse to extend it any
543 : * more --- we mustn't create a block whose number actually is
544 : * InvalidBlockNumber or larger.
545 : */
546 350086 : if ((uint64) blocknum + nblocks >= (uint64) InvalidBlockNumber)
547 0 : ereport(ERROR,
548 : (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
549 : errmsg("cannot extend file \"%s\" beyond %u blocks",
550 : relpath(reln->smgr_rlocator, forknum),
551 : InvalidBlockNumber)));
552 :
553 700172 : while (remblocks > 0)
554 : {
555 350086 : BlockNumber segstartblock = curblocknum % ((BlockNumber) RELSEG_SIZE);
556 350086 : off_t seekpos = (off_t) BLCKSZ * segstartblock;
557 : int numblocks;
558 :
559 350086 : if (segstartblock + remblocks > RELSEG_SIZE)
560 0 : numblocks = RELSEG_SIZE - segstartblock;
561 : else
562 350086 : numblocks = remblocks;
563 :
564 350086 : v = _mdfd_getseg(reln, forknum, curblocknum, skipFsync, EXTENSION_CREATE);
565 :
566 : Assert(segstartblock < RELSEG_SIZE);
567 : Assert(segstartblock + numblocks <= RELSEG_SIZE);
568 :
569 : /*
570 : * If available and useful, use posix_fallocate() (via
571 : * FileFallocate()) to extend the relation. That's often more
572 : * efficient than using write(), as it commonly won't cause the kernel
573 : * to allocate page cache space for the extended pages.
574 : *
575 : * However, we don't use FileFallocate() for small extensions, as it
576 : * defeats delayed allocation on some filesystems. Not clear where
577 : * that decision should be made though? For now just use a cutoff of
578 : * 8, anything between 4 and 8 worked OK in some local testing.
579 : */
580 350086 : if (numblocks > 8)
581 : {
582 : int ret;
583 :
584 1002 : ret = FileFallocate(v->mdfd_vfd,
585 : seekpos, (off_t) BLCKSZ * numblocks,
586 : WAIT_EVENT_DATA_FILE_EXTEND);
587 1002 : if (ret != 0)
588 : {
589 0 : ereport(ERROR,
590 : errcode_for_file_access(),
591 : errmsg("could not extend file \"%s\" with FileFallocate(): %m",
592 : FilePathName(v->mdfd_vfd)),
593 : errhint("Check free disk space."));
594 : }
595 : }
596 : else
597 : {
598 : int ret;
599 :
600 : /*
601 : * Even if we don't want to use fallocate, we can still extend a
602 : * bit more efficiently than writing each 8kB block individually.
603 : * pg_pwrite_zeros() (via FileZero()) uses pg_pwritev_with_retry()
604 : * to avoid multiple writes or needing a zeroed buffer for the
605 : * whole length of the extension.
606 : */
607 349084 : ret = FileZero(v->mdfd_vfd,
608 : seekpos, (off_t) BLCKSZ * numblocks,
609 : WAIT_EVENT_DATA_FILE_EXTEND);
610 349084 : if (ret < 0)
611 0 : ereport(ERROR,
612 : errcode_for_file_access(),
613 : errmsg("could not extend file \"%s\": %m",
614 : FilePathName(v->mdfd_vfd)),
615 : errhint("Check free disk space."));
616 : }
617 :
618 350086 : if (!skipFsync && !SmgrIsTemp(reln))
619 332634 : register_dirty_segment(reln, forknum, v);
620 :
621 : Assert(_mdnblocks(reln, forknum, v) <= ((BlockNumber) RELSEG_SIZE));
622 :
623 350086 : remblocks -= numblocks;
624 350086 : curblocknum += numblocks;
625 : }
626 350086 : }
627 :
628 : /*
629 : * mdopenfork() -- Open one fork of the specified relation.
630 : *
631 : * Note we only open the first segment, when there are multiple segments.
632 : *
633 : * If first segment is not present, either ereport or return NULL according
634 : * to "behavior". We treat EXTENSION_CREATE the same as EXTENSION_FAIL;
635 : * EXTENSION_CREATE means it's OK to extend an existing relation, not to
636 : * invent one out of whole cloth.
637 : */
638 : static MdfdVec *
639 5313164 : mdopenfork(SMgrRelation reln, ForkNumber forknum, int behavior)
640 : {
641 : MdfdVec *mdfd;
642 : char *path;
643 : File fd;
644 :
645 : /* No work if already open */
646 5313164 : if (reln->md_num_open_segs[forknum] > 0)
647 3726696 : return &reln->md_seg_fds[forknum][0];
648 :
649 1586468 : path = relpath(reln->smgr_rlocator, forknum);
650 :
651 1586468 : fd = PathNameOpenFile(path, _mdfd_open_flags());
652 :
653 1586468 : if (fd < 0)
654 : {
655 573736 : if ((behavior & EXTENSION_RETURN_NULL) &&
656 573692 : FILE_POSSIBLY_DELETED(errno))
657 : {
658 573692 : pfree(path);
659 573692 : return NULL;
660 : }
661 44 : ereport(ERROR,
662 : (errcode_for_file_access(),
663 : errmsg("could not open file \"%s\": %m", path)));
664 : }
665 :
666 1012732 : pfree(path);
667 :
668 1012732 : _fdvec_resize(reln, forknum, 1);
669 1012732 : mdfd = &reln->md_seg_fds[forknum][0];
670 1012732 : mdfd->mdfd_vfd = fd;
671 1012732 : mdfd->mdfd_segno = 0;
672 :
673 : Assert(_mdnblocks(reln, forknum, mdfd) <= ((BlockNumber) RELSEG_SIZE));
674 :
675 1012732 : return mdfd;
676 : }
677 :
678 : /*
679 : * mdopen() -- Initialize newly-opened relation.
680 : */
681 : void
682 1709092 : mdopen(SMgrRelation reln)
683 : {
684 : /* mark it not open */
685 8545460 : for (int forknum = 0; forknum <= MAX_FORKNUM; forknum++)
686 6836368 : reln->md_num_open_segs[forknum] = 0;
687 1709092 : }
688 :
689 : /*
690 : * mdclose() -- Close the specified relation, if it isn't closed already.
691 : */
692 : void
693 4270954 : mdclose(SMgrRelation reln, ForkNumber forknum)
694 : {
695 4270954 : int nopensegs = reln->md_num_open_segs[forknum];
696 :
697 : /* No work if already closed */
698 4270954 : if (nopensegs == 0)
699 3477440 : return;
700 :
701 : /* close segments starting from the end */
702 1587028 : while (nopensegs > 0)
703 : {
704 793514 : MdfdVec *v = &reln->md_seg_fds[forknum][nopensegs - 1];
705 :
706 793514 : FileClose(v->mdfd_vfd);
707 793514 : _fdvec_resize(reln, forknum, nopensegs - 1);
708 793514 : nopensegs--;
709 : }
710 : }
711 :
712 : /*
713 : * mdprefetch() -- Initiate asynchronous read of the specified block of a relation
714 : */
715 : bool
716 248790 : mdprefetch(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum)
717 : {
718 : #ifdef USE_PREFETCH
719 : off_t seekpos;
720 : MdfdVec *v;
721 :
722 : Assert((io_direct_flags & IO_DIRECT_DATA) == 0);
723 :
724 248790 : v = _mdfd_getseg(reln, forknum, blocknum, false,
725 248790 : InRecovery ? EXTENSION_RETURN_NULL : EXTENSION_FAIL);
726 248790 : if (v == NULL)
727 0 : return false;
728 :
729 248790 : seekpos = (off_t) BLCKSZ * (blocknum % ((BlockNumber) RELSEG_SIZE));
730 :
731 : Assert(seekpos < (off_t) BLCKSZ * RELSEG_SIZE);
732 :
733 248790 : (void) FilePrefetch(v->mdfd_vfd, seekpos, BLCKSZ, WAIT_EVENT_DATA_FILE_PREFETCH);
734 : #endif /* USE_PREFETCH */
735 :
736 248790 : return true;
737 : }
738 :
739 : /*
740 : * mdread() -- Read the specified block from a relation.
741 : */
742 : void
743 2044574 : mdread(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum,
744 : void *buffer)
745 : {
746 : off_t seekpos;
747 : int nbytes;
748 : MdfdVec *v;
749 :
750 : /* If this build supports direct I/O, the buffer must be I/O aligned. */
751 : if (PG_O_DIRECT != 0 && PG_IO_ALIGN_SIZE <= BLCKSZ)
752 : Assert((uintptr_t) buffer == TYPEALIGN(PG_IO_ALIGN_SIZE, buffer));
753 :
754 : TRACE_POSTGRESQL_SMGR_MD_READ_START(forknum, blocknum,
755 : reln->smgr_rlocator.locator.spcOid,
756 : reln->smgr_rlocator.locator.dbOid,
757 : reln->smgr_rlocator.locator.relNumber,
758 : reln->smgr_rlocator.backend);
759 :
760 2044574 : v = _mdfd_getseg(reln, forknum, blocknum, false,
761 : EXTENSION_FAIL | EXTENSION_CREATE_RECOVERY);
762 :
763 2044544 : seekpos = (off_t) BLCKSZ * (blocknum % ((BlockNumber) RELSEG_SIZE));
764 :
765 : Assert(seekpos < (off_t) BLCKSZ * RELSEG_SIZE);
766 :
767 2044544 : nbytes = FileRead(v->mdfd_vfd, buffer, BLCKSZ, seekpos, WAIT_EVENT_DATA_FILE_READ);
768 :
769 : TRACE_POSTGRESQL_SMGR_MD_READ_DONE(forknum, blocknum,
770 : reln->smgr_rlocator.locator.spcOid,
771 : reln->smgr_rlocator.locator.dbOid,
772 : reln->smgr_rlocator.locator.relNumber,
773 : reln->smgr_rlocator.backend,
774 : nbytes,
775 : BLCKSZ);
776 :
777 2044544 : if (nbytes != BLCKSZ)
778 : {
779 0 : if (nbytes < 0)
780 0 : ereport(ERROR,
781 : (errcode_for_file_access(),
782 : errmsg("could not read block %u in file \"%s\": %m",
783 : blocknum, FilePathName(v->mdfd_vfd))));
784 :
785 : /*
786 : * Short read: we are at or past EOF, or we read a partial block at
787 : * EOF. Normally this is an error; upper levels should never try to
788 : * read a nonexistent block. However, if zero_damaged_pages is ON or
789 : * we are InRecovery, we should instead return zeroes without
790 : * complaining. This allows, for example, the case of trying to
791 : * update a block that was later truncated away.
792 : */
793 0 : if (zero_damaged_pages || InRecovery)
794 0 : MemSet(buffer, 0, BLCKSZ);
795 : else
796 0 : ereport(ERROR,
797 : (errcode(ERRCODE_DATA_CORRUPTED),
798 : errmsg("could not read block %u in file \"%s\": read only %d of %d bytes",
799 : blocknum, FilePathName(v->mdfd_vfd),
800 : nbytes, BLCKSZ)));
801 : }
802 2044544 : }
803 :
804 : /*
805 : * mdwrite() -- Write the supplied block at the appropriate location.
806 : *
807 : * This is to be used only for updating already-existing blocks of a
808 : * relation (ie, those before the current EOF). To extend a relation,
809 : * use mdextend().
810 : */
811 : void
812 846244 : mdwrite(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum,
813 : const void *buffer, bool skipFsync)
814 : {
815 : off_t seekpos;
816 : int nbytes;
817 : MdfdVec *v;
818 :
819 : /* If this build supports direct I/O, the buffer must be I/O aligned. */
820 : if (PG_O_DIRECT != 0 && PG_IO_ALIGN_SIZE <= BLCKSZ)
821 : Assert((uintptr_t) buffer == TYPEALIGN(PG_IO_ALIGN_SIZE, buffer));
822 :
823 : /* This assert is too expensive to have on normally ... */
824 : #ifdef CHECK_WRITE_VS_EXTEND
825 : Assert(blocknum < mdnblocks(reln, forknum));
826 : #endif
827 :
828 : TRACE_POSTGRESQL_SMGR_MD_WRITE_START(forknum, blocknum,
829 : reln->smgr_rlocator.locator.spcOid,
830 : reln->smgr_rlocator.locator.dbOid,
831 : reln->smgr_rlocator.locator.relNumber,
832 : reln->smgr_rlocator.backend);
833 :
834 846244 : v = _mdfd_getseg(reln, forknum, blocknum, skipFsync,
835 : EXTENSION_FAIL | EXTENSION_CREATE_RECOVERY);
836 :
837 846244 : seekpos = (off_t) BLCKSZ * (blocknum % ((BlockNumber) RELSEG_SIZE));
838 :
839 : Assert(seekpos < (off_t) BLCKSZ * RELSEG_SIZE);
840 :
841 846244 : nbytes = FileWrite(v->mdfd_vfd, buffer, BLCKSZ, seekpos, WAIT_EVENT_DATA_FILE_WRITE);
842 :
843 : TRACE_POSTGRESQL_SMGR_MD_WRITE_DONE(forknum, blocknum,
844 : reln->smgr_rlocator.locator.spcOid,
845 : reln->smgr_rlocator.locator.dbOid,
846 : reln->smgr_rlocator.locator.relNumber,
847 : reln->smgr_rlocator.backend,
848 : nbytes,
849 : BLCKSZ);
850 :
851 846244 : if (nbytes != BLCKSZ)
852 : {
853 0 : if (nbytes < 0)
854 0 : ereport(ERROR,
855 : (errcode_for_file_access(),
856 : errmsg("could not write block %u in file \"%s\": %m",
857 : blocknum, FilePathName(v->mdfd_vfd))));
858 : /* short write: complain appropriately */
859 0 : ereport(ERROR,
860 : (errcode(ERRCODE_DISK_FULL),
861 : errmsg("could not write block %u in file \"%s\": wrote only %d of %d bytes",
862 : blocknum,
863 : FilePathName(v->mdfd_vfd),
864 : nbytes, BLCKSZ),
865 : errhint("Check free disk space.")));
866 : }
867 :
868 846244 : if (!skipFsync && !SmgrIsTemp(reln))
869 836114 : register_dirty_segment(reln, forknum, v);
870 846244 : }
871 :
872 : /*
873 : * mdwriteback() -- Tell the kernel to write pages back to storage.
874 : *
875 : * This accepts a range of blocks because flushing several pages at once is
876 : * considerably more efficient than doing so individually.
877 : */
878 : void
879 125648 : mdwriteback(SMgrRelation reln, ForkNumber forknum,
880 : BlockNumber blocknum, BlockNumber nblocks)
881 : {
882 : Assert((io_direct_flags & IO_DIRECT_DATA) == 0);
883 :
884 : /*
885 : * Issue flush requests in as few requests as possible; have to split at
886 : * segment boundaries though, since those are actually separate files.
887 : */
888 250610 : while (nblocks > 0)
889 : {
890 125648 : BlockNumber nflush = nblocks;
891 : off_t seekpos;
892 : MdfdVec *v;
893 : int segnum_start,
894 : segnum_end;
895 :
896 125648 : v = _mdfd_getseg(reln, forknum, blocknum, true /* not used */ ,
897 : EXTENSION_DONT_OPEN);
898 :
899 : /*
900 : * We might be flushing buffers of already removed relations, that's
901 : * ok, just ignore that case. If the segment file wasn't open already
902 : * (ie from a recent mdwrite()), then we don't want to re-open it, to
903 : * avoid a race with PROCSIGNAL_BARRIER_SMGRRELEASE that might leave
904 : * us with a descriptor to a file that is about to be unlinked.
905 : */
906 125648 : if (!v)
907 686 : return;
908 :
909 : /* compute offset inside the current segment */
910 124962 : segnum_start = blocknum / RELSEG_SIZE;
911 :
912 : /* compute number of desired writes within the current segment */
913 124962 : segnum_end = (blocknum + nblocks - 1) / RELSEG_SIZE;
914 124962 : if (segnum_start != segnum_end)
915 0 : nflush = RELSEG_SIZE - (blocknum % ((BlockNumber) RELSEG_SIZE));
916 :
917 : Assert(nflush >= 1);
918 : Assert(nflush <= nblocks);
919 :
920 124962 : seekpos = (off_t) BLCKSZ * (blocknum % ((BlockNumber) RELSEG_SIZE));
921 :
922 124962 : FileWriteback(v->mdfd_vfd, seekpos, (off_t) BLCKSZ * nflush, WAIT_EVENT_DATA_FILE_FLUSH);
923 :
924 124962 : nblocks -= nflush;
925 124962 : blocknum += nflush;
926 : }
927 : }
928 :
929 : /*
930 : * mdnblocks() -- Get the number of blocks stored in a relation.
931 : *
932 : * Important side effect: all active segments of the relation are opened
933 : * and added to the md_seg_fds array. If this routine has not been
934 : * called, then only segments up to the last one actually touched
935 : * are present in the array.
936 : */
937 : BlockNumber
938 3248606 : mdnblocks(SMgrRelation reln, ForkNumber forknum)
939 : {
940 : MdfdVec *v;
941 : BlockNumber nblocks;
942 : BlockNumber segno;
943 :
944 3248606 : mdopenfork(reln, forknum, EXTENSION_FAIL);
945 :
946 : /* mdopen has opened the first segment */
947 : Assert(reln->md_num_open_segs[forknum] > 0);
948 :
949 : /*
950 : * Start from the last open segments, to avoid redundant seeks. We have
951 : * previously verified that these segments are exactly RELSEG_SIZE long,
952 : * and it's useless to recheck that each time.
953 : *
954 : * NOTE: this assumption could only be wrong if another backend has
955 : * truncated the relation. We rely on higher code levels to handle that
956 : * scenario by closing and re-opening the md fd, which is handled via
957 : * relcache flush. (Since the checkpointer doesn't participate in
958 : * relcache flush, it could have segment entries for inactive segments;
959 : * that's OK because the checkpointer never needs to compute relation
960 : * size.)
961 : */
962 3248568 : segno = reln->md_num_open_segs[forknum] - 1;
963 3248568 : v = &reln->md_seg_fds[forknum][segno];
964 :
965 : for (;;)
966 : {
967 3248568 : nblocks = _mdnblocks(reln, forknum, v);
968 3248568 : if (nblocks > ((BlockNumber) RELSEG_SIZE))
969 0 : elog(FATAL, "segment too big");
970 3248568 : if (nblocks < ((BlockNumber) RELSEG_SIZE))
971 3248568 : return (segno * ((BlockNumber) RELSEG_SIZE)) + nblocks;
972 :
973 : /*
974 : * If segment is exactly RELSEG_SIZE, advance to next one.
975 : */
976 0 : segno++;
977 :
978 : /*
979 : * We used to pass O_CREAT here, but that has the disadvantage that it
980 : * might create a segment which has vanished through some operating
981 : * system misadventure. In such a case, creating the segment here
982 : * undermines _mdfd_getseg's attempts to notice and report an error
983 : * upon access to a missing segment.
984 : */
985 0 : v = _mdfd_openseg(reln, forknum, segno, 0);
986 0 : if (v == NULL)
987 0 : return segno * ((BlockNumber) RELSEG_SIZE);
988 : }
989 : }
990 :
991 : /*
992 : * mdtruncate() -- Truncate relation to specified number of blocks.
993 : */
994 : void
995 1586 : mdtruncate(SMgrRelation reln, ForkNumber forknum, BlockNumber nblocks)
996 : {
997 : BlockNumber curnblk;
998 : BlockNumber priorblocks;
999 : int curopensegs;
1000 :
1001 : /*
1002 : * NOTE: mdnblocks makes sure we have opened all active segments, so that
1003 : * truncation loop will get them all!
1004 : */
1005 1586 : curnblk = mdnblocks(reln, forknum);
1006 1586 : if (nblocks > curnblk)
1007 : {
1008 : /* Bogus request ... but no complaint if InRecovery */
1009 0 : if (InRecovery)
1010 0 : return;
1011 0 : ereport(ERROR,
1012 : (errmsg("could not truncate file \"%s\" to %u blocks: it's only %u blocks now",
1013 : relpath(reln->smgr_rlocator, forknum),
1014 : nblocks, curnblk)));
1015 : }
1016 1586 : if (nblocks == curnblk)
1017 666 : return; /* no work */
1018 :
1019 : /*
1020 : * Truncate segments, starting at the last one. Starting at the end makes
1021 : * managing the memory for the fd array easier, should there be errors.
1022 : */
1023 920 : curopensegs = reln->md_num_open_segs[forknum];
1024 1840 : while (curopensegs > 0)
1025 : {
1026 : MdfdVec *v;
1027 :
1028 920 : priorblocks = (curopensegs - 1) * RELSEG_SIZE;
1029 :
1030 920 : v = &reln->md_seg_fds[forknum][curopensegs - 1];
1031 :
1032 920 : if (priorblocks > nblocks)
1033 : {
1034 : /*
1035 : * This segment is no longer active. We truncate the file, but do
1036 : * not delete it, for reasons explained in the header comments.
1037 : */
1038 0 : if (FileTruncate(v->mdfd_vfd, 0, WAIT_EVENT_DATA_FILE_TRUNCATE) < 0)
1039 0 : ereport(ERROR,
1040 : (errcode_for_file_access(),
1041 : errmsg("could not truncate file \"%s\": %m",
1042 : FilePathName(v->mdfd_vfd))));
1043 :
1044 0 : if (!SmgrIsTemp(reln))
1045 0 : register_dirty_segment(reln, forknum, v);
1046 :
1047 : /* we never drop the 1st segment */
1048 : Assert(v != &reln->md_seg_fds[forknum][0]);
1049 :
1050 0 : FileClose(v->mdfd_vfd);
1051 0 : _fdvec_resize(reln, forknum, curopensegs - 1);
1052 : }
1053 920 : else if (priorblocks + ((BlockNumber) RELSEG_SIZE) > nblocks)
1054 : {
1055 : /*
1056 : * This is the last segment we want to keep. Truncate the file to
1057 : * the right length. NOTE: if nblocks is exactly a multiple K of
1058 : * RELSEG_SIZE, we will truncate the K+1st segment to 0 length but
1059 : * keep it. This adheres to the invariant given in the header
1060 : * comments.
1061 : */
1062 920 : BlockNumber lastsegblocks = nblocks - priorblocks;
1063 :
1064 920 : if (FileTruncate(v->mdfd_vfd, (off_t) lastsegblocks * BLCKSZ, WAIT_EVENT_DATA_FILE_TRUNCATE) < 0)
1065 0 : ereport(ERROR,
1066 : (errcode_for_file_access(),
1067 : errmsg("could not truncate file \"%s\" to %u blocks: %m",
1068 : FilePathName(v->mdfd_vfd),
1069 : nblocks)));
1070 920 : if (!SmgrIsTemp(reln))
1071 646 : register_dirty_segment(reln, forknum, v);
1072 : }
1073 : else
1074 : {
1075 : /*
1076 : * We still need this segment, so nothing to do for this and any
1077 : * earlier segment.
1078 : */
1079 0 : break;
1080 : }
1081 920 : curopensegs--;
1082 : }
1083 : }
1084 :
1085 : /*
1086 : * mdimmedsync() -- Immediately sync a relation to stable storage.
1087 : *
1088 : * Note that only writes already issued are synced; this routine knows
1089 : * nothing of dirty buffers that may exist inside the buffer manager. We
1090 : * sync active and inactive segments; smgrDoPendingSyncs() relies on this.
1091 : * Consider a relation skipping WAL. Suppose a checkpoint syncs blocks of
1092 : * some segment, then mdtruncate() renders that segment inactive. If we
1093 : * crash before the next checkpoint syncs the newly-inactive segment, that
1094 : * segment may survive recovery, reintroducing unwanted data into the table.
1095 : */
1096 : void
1097 29060 : mdimmedsync(SMgrRelation reln, ForkNumber forknum)
1098 : {
1099 : int segno;
1100 : int min_inactive_seg;
1101 :
1102 : /*
1103 : * NOTE: mdnblocks makes sure we have opened all active segments, so that
1104 : * fsync loop will get them all!
1105 : */
1106 29060 : mdnblocks(reln, forknum);
1107 :
1108 29060 : min_inactive_seg = segno = reln->md_num_open_segs[forknum];
1109 :
1110 : /*
1111 : * Temporarily open inactive segments, then close them after sync. There
1112 : * may be some inactive segments left opened after fsync() error, but that
1113 : * is harmless. We don't bother to clean them up and take a risk of
1114 : * further trouble. The next mdclose() will soon close them.
1115 : */
1116 29060 : while (_mdfd_openseg(reln, forknum, segno, 0) != NULL)
1117 0 : segno++;
1118 :
1119 58120 : while (segno > 0)
1120 : {
1121 29060 : MdfdVec *v = &reln->md_seg_fds[forknum][segno - 1];
1122 :
1123 : /*
1124 : * fsyncs done through mdimmedsync() should be tracked in a separate
1125 : * IOContext than those done through mdsyncfiletag() to differentiate
1126 : * between unavoidable client backend fsyncs (e.g. those done during
1127 : * index build) and those which ideally would have been done by the
1128 : * checkpointer. Since other IO operations bypassing the buffer
1129 : * manager could also be tracked in such an IOContext, wait until
1130 : * these are also tracked to track immediate fsyncs.
1131 : */
1132 29060 : if (FileSync(v->mdfd_vfd, WAIT_EVENT_DATA_FILE_IMMEDIATE_SYNC) < 0)
1133 0 : ereport(data_sync_elevel(ERROR),
1134 : (errcode_for_file_access(),
1135 : errmsg("could not fsync file \"%s\": %m",
1136 : FilePathName(v->mdfd_vfd))));
1137 :
1138 : /* Close inactive segments immediately */
1139 29060 : if (segno > min_inactive_seg)
1140 : {
1141 0 : FileClose(v->mdfd_vfd);
1142 0 : _fdvec_resize(reln, forknum, segno - 1);
1143 : }
1144 :
1145 29060 : segno--;
1146 : }
1147 29060 : }
1148 :
1149 : /*
1150 : * register_dirty_segment() -- Mark a relation segment as needing fsync
1151 : *
1152 : * If there is a local pending-ops table, just make an entry in it for
1153 : * ProcessSyncRequests to process later. Otherwise, try to pass off the
1154 : * fsync request to the checkpointer process. If that fails, just do the
1155 : * fsync locally before returning (we hope this will not happen often
1156 : * enough to be a performance problem).
1157 : */
1158 : static void
1159 1418760 : register_dirty_segment(SMgrRelation reln, ForkNumber forknum, MdfdVec *seg)
1160 : {
1161 : FileTag tag;
1162 :
1163 1418760 : INIT_MD_FILETAG(tag, reln->smgr_rlocator.locator, forknum, seg->mdfd_segno);
1164 :
1165 : /* Temp relations should never be fsync'd */
1166 : Assert(!SmgrIsTemp(reln));
1167 :
1168 1418760 : if (!RegisterSyncRequest(&tag, SYNC_REQUEST, false /* retryOnError */ ))
1169 : {
1170 : instr_time io_start;
1171 :
1172 54 : ereport(DEBUG1,
1173 : (errmsg_internal("could not forward fsync request because request queue is full")));
1174 :
1175 54 : io_start = pgstat_prepare_io_time();
1176 :
1177 54 : if (FileSync(seg->mdfd_vfd, WAIT_EVENT_DATA_FILE_SYNC) < 0)
1178 0 : ereport(data_sync_elevel(ERROR),
1179 : (errcode_for_file_access(),
1180 : errmsg("could not fsync file \"%s\": %m",
1181 : FilePathName(seg->mdfd_vfd))));
1182 :
1183 : /*
1184 : * We have no way of knowing if the current IOContext is
1185 : * IOCONTEXT_NORMAL or IOCONTEXT_[BULKREAD, BULKWRITE, VACUUM] at this
1186 : * point, so count the fsync as being in the IOCONTEXT_NORMAL
1187 : * IOContext. This is probably okay, because the number of backend
1188 : * fsyncs doesn't say anything about the efficacy of the
1189 : * BufferAccessStrategy. And counting both fsyncs done in
1190 : * IOCONTEXT_NORMAL and IOCONTEXT_[BULKREAD, BULKWRITE, VACUUM] under
1191 : * IOCONTEXT_NORMAL is likely clearer when investigating the number of
1192 : * backend fsyncs.
1193 : */
1194 54 : pgstat_count_io_op_time(IOOBJECT_RELATION, IOCONTEXT_NORMAL,
1195 : IOOP_FSYNC, io_start, 1);
1196 : }
1197 1418760 : }
1198 :
1199 : /*
1200 : * register_unlink_segment() -- Schedule a file to be deleted after next checkpoint
1201 : */
1202 : static void
1203 57634 : register_unlink_segment(RelFileLocatorBackend rlocator, ForkNumber forknum,
1204 : BlockNumber segno)
1205 : {
1206 : FileTag tag;
1207 :
1208 57634 : INIT_MD_FILETAG(tag, rlocator.locator, forknum, segno);
1209 :
1210 : /* Should never be used with temp relations */
1211 : Assert(!RelFileLocatorBackendIsTemp(rlocator));
1212 :
1213 57634 : RegisterSyncRequest(&tag, SYNC_UNLINK_REQUEST, true /* retryOnError */ );
1214 57634 : }
1215 :
1216 : /*
1217 : * register_forget_request() -- forget any fsyncs for a relation fork's segment
1218 : */
1219 : static void
1220 221670 : register_forget_request(RelFileLocatorBackend rlocator, ForkNumber forknum,
1221 : BlockNumber segno)
1222 : {
1223 : FileTag tag;
1224 :
1225 221670 : INIT_MD_FILETAG(tag, rlocator.locator, forknum, segno);
1226 :
1227 221670 : RegisterSyncRequest(&tag, SYNC_FORGET_REQUEST, true /* retryOnError */ );
1228 221670 : }
1229 :
1230 : /*
1231 : * ForgetDatabaseSyncRequests -- forget any fsyncs and unlinks for a DB
1232 : */
1233 : void
1234 70 : ForgetDatabaseSyncRequests(Oid dbid)
1235 : {
1236 : FileTag tag;
1237 : RelFileLocator rlocator;
1238 :
1239 70 : rlocator.dbOid = dbid;
1240 70 : rlocator.spcOid = 0;
1241 70 : rlocator.relNumber = 0;
1242 :
1243 70 : INIT_MD_FILETAG(tag, rlocator, InvalidForkNumber, InvalidBlockNumber);
1244 :
1245 70 : RegisterSyncRequest(&tag, SYNC_FILTER_REQUEST, true /* retryOnError */ );
1246 70 : }
1247 :
1248 : /*
1249 : * DropRelationFiles -- drop files of all given relations
1250 : */
1251 : void
1252 4544 : DropRelationFiles(RelFileLocator *delrels, int ndelrels, bool isRedo)
1253 : {
1254 : SMgrRelation *srels;
1255 : int i;
1256 :
1257 4544 : srels = palloc(sizeof(SMgrRelation) * ndelrels);
1258 16752 : for (i = 0; i < ndelrels; i++)
1259 : {
1260 12208 : SMgrRelation srel = smgropen(delrels[i], InvalidBackendId);
1261 :
1262 12208 : if (isRedo)
1263 : {
1264 : ForkNumber fork;
1265 :
1266 60800 : for (fork = 0; fork <= MAX_FORKNUM; fork++)
1267 48640 : XLogDropRelation(delrels[i], fork);
1268 : }
1269 12208 : srels[i] = srel;
1270 : }
1271 :
1272 4544 : smgrdounlinkall(srels, ndelrels, isRedo);
1273 :
1274 16752 : for (i = 0; i < ndelrels; i++)
1275 12208 : smgrclose(srels[i]);
1276 4544 : pfree(srels);
1277 4544 : }
1278 :
1279 :
1280 : /*
1281 : * _fdvec_resize() -- Resize the fork's open segments array
1282 : */
1283 : static void
1284 2061476 : _fdvec_resize(SMgrRelation reln,
1285 : ForkNumber forknum,
1286 : int nseg)
1287 : {
1288 2061476 : if (nseg == 0)
1289 : {
1290 793514 : if (reln->md_num_open_segs[forknum] > 0)
1291 : {
1292 793514 : pfree(reln->md_seg_fds[forknum]);
1293 793514 : reln->md_seg_fds[forknum] = NULL;
1294 : }
1295 : }
1296 1267962 : else if (reln->md_num_open_segs[forknum] == 0)
1297 : {
1298 1267962 : reln->md_seg_fds[forknum] =
1299 1267962 : MemoryContextAlloc(MdCxt, sizeof(MdfdVec) * nseg);
1300 : }
1301 : else
1302 : {
1303 : /*
1304 : * It doesn't seem worthwhile complicating the code to amortize
1305 : * repalloc() calls. Those are far faster than PathNameOpenFile() or
1306 : * FileClose(), and the memory context internally will sometimes avoid
1307 : * doing an actual reallocation.
1308 : */
1309 0 : reln->md_seg_fds[forknum] =
1310 0 : repalloc(reln->md_seg_fds[forknum],
1311 : sizeof(MdfdVec) * nseg);
1312 : }
1313 :
1314 2061476 : reln->md_num_open_segs[forknum] = nseg;
1315 2061476 : }
1316 :
1317 : /*
1318 : * Return the filename for the specified segment of the relation. The
1319 : * returned string is palloc'd.
1320 : */
1321 : static char *
1322 29084 : _mdfd_segpath(SMgrRelation reln, ForkNumber forknum, BlockNumber segno)
1323 : {
1324 : char *path,
1325 : *fullpath;
1326 :
1327 29084 : path = relpath(reln->smgr_rlocator, forknum);
1328 :
1329 29084 : if (segno > 0)
1330 : {
1331 29084 : fullpath = psprintf("%s.%u", path, segno);
1332 29084 : pfree(path);
1333 : }
1334 : else
1335 0 : fullpath = path;
1336 :
1337 29084 : return fullpath;
1338 : }
1339 :
1340 : /*
1341 : * Open the specified segment of the relation,
1342 : * and make a MdfdVec object for it. Returns NULL on failure.
1343 : */
1344 : static MdfdVec *
1345 29060 : _mdfd_openseg(SMgrRelation reln, ForkNumber forknum, BlockNumber segno,
1346 : int oflags)
1347 : {
1348 : MdfdVec *v;
1349 : File fd;
1350 : char *fullpath;
1351 :
1352 29060 : fullpath = _mdfd_segpath(reln, forknum, segno);
1353 :
1354 : /* open the file */
1355 29060 : fd = PathNameOpenFile(fullpath, _mdfd_open_flags() | oflags);
1356 :
1357 29060 : pfree(fullpath);
1358 :
1359 29060 : if (fd < 0)
1360 29060 : return NULL;
1361 :
1362 : /*
1363 : * Segments are always opened in order from lowest to highest, so we must
1364 : * be adding a new one at the end.
1365 : */
1366 : Assert(segno == reln->md_num_open_segs[forknum]);
1367 :
1368 0 : _fdvec_resize(reln, forknum, segno + 1);
1369 :
1370 : /* fill the entry */
1371 0 : v = &reln->md_seg_fds[forknum][segno];
1372 0 : v->mdfd_vfd = fd;
1373 0 : v->mdfd_segno = segno;
1374 :
1375 : Assert(_mdnblocks(reln, forknum, v) <= ((BlockNumber) RELSEG_SIZE));
1376 :
1377 : /* all done */
1378 0 : return v;
1379 : }
1380 :
1381 : /*
1382 : * _mdfd_getseg() -- Find the segment of the relation holding the
1383 : * specified block.
1384 : *
1385 : * If the segment doesn't exist, we ereport, return NULL, or create the
1386 : * segment, according to "behavior". Note: skipFsync is only used in the
1387 : * EXTENSION_CREATE case.
1388 : */
1389 : static MdfdVec *
1390 3810712 : _mdfd_getseg(SMgrRelation reln, ForkNumber forknum, BlockNumber blkno,
1391 : bool skipFsync, int behavior)
1392 : {
1393 : MdfdVec *v;
1394 : BlockNumber targetseg;
1395 : BlockNumber nextsegno;
1396 :
1397 : /* some way to handle non-existent segments needs to be specified */
1398 : Assert(behavior &
1399 : (EXTENSION_FAIL | EXTENSION_CREATE | EXTENSION_RETURN_NULL |
1400 : EXTENSION_DONT_OPEN));
1401 :
1402 3810712 : targetseg = blkno / ((BlockNumber) RELSEG_SIZE);
1403 :
1404 : /* if an existing and opened segment, we're done */
1405 3810712 : if (targetseg < reln->md_num_open_segs[forknum])
1406 : {
1407 3476668 : v = &reln->md_seg_fds[forknum][targetseg];
1408 3476668 : return v;
1409 : }
1410 :
1411 : /* The caller only wants the segment if we already had it open. */
1412 334044 : if (behavior & EXTENSION_DONT_OPEN)
1413 686 : return NULL;
1414 :
1415 : /*
1416 : * The target segment is not yet open. Iterate over all the segments
1417 : * between the last opened and the target segment. This way missing
1418 : * segments either raise an error, or get created (according to
1419 : * 'behavior'). Start with either the last opened, or the first segment if
1420 : * none was opened before.
1421 : */
1422 333358 : if (reln->md_num_open_segs[forknum] > 0)
1423 24 : v = &reln->md_seg_fds[forknum][reln->md_num_open_segs[forknum] - 1];
1424 : else
1425 : {
1426 333334 : v = mdopenfork(reln, forknum, behavior);
1427 333328 : if (!v)
1428 0 : return NULL; /* if behavior & EXTENSION_RETURN_NULL */
1429 : }
1430 :
1431 333352 : for (nextsegno = reln->md_num_open_segs[forknum];
1432 0 : nextsegno <= targetseg; nextsegno++)
1433 : {
1434 24 : BlockNumber nblocks = _mdnblocks(reln, forknum, v);
1435 24 : int flags = 0;
1436 :
1437 : Assert(nextsegno == v->mdfd_segno + 1);
1438 :
1439 24 : if (nblocks > ((BlockNumber) RELSEG_SIZE))
1440 0 : elog(FATAL, "segment too big");
1441 :
1442 24 : if ((behavior & EXTENSION_CREATE) ||
1443 24 : (InRecovery && (behavior & EXTENSION_CREATE_RECOVERY)))
1444 : {
1445 : /*
1446 : * Normally we will create new segments only if authorized by the
1447 : * caller (i.e., we are doing mdextend()). But when doing WAL
1448 : * recovery, create segments anyway; this allows cases such as
1449 : * replaying WAL data that has a write into a high-numbered
1450 : * segment of a relation that was later deleted. We want to go
1451 : * ahead and create the segments so we can finish out the replay.
1452 : *
1453 : * We have to maintain the invariant that segments before the last
1454 : * active segment are of size RELSEG_SIZE; therefore, if
1455 : * extending, pad them out with zeroes if needed. (This only
1456 : * matters if in recovery, or if the caller is extending the
1457 : * relation discontiguously, but that can happen in hash indexes.)
1458 : */
1459 0 : if (nblocks < ((BlockNumber) RELSEG_SIZE))
1460 : {
1461 0 : char *zerobuf = palloc_aligned(BLCKSZ, PG_IO_ALIGN_SIZE,
1462 : MCXT_ALLOC_ZERO);
1463 :
1464 0 : mdextend(reln, forknum,
1465 0 : nextsegno * ((BlockNumber) RELSEG_SIZE) - 1,
1466 : zerobuf, skipFsync);
1467 0 : pfree(zerobuf);
1468 : }
1469 0 : flags = O_CREAT;
1470 : }
1471 24 : else if (!(behavior & EXTENSION_DONT_CHECK_SIZE) &&
1472 : nblocks < ((BlockNumber) RELSEG_SIZE))
1473 : {
1474 : /*
1475 : * When not extending (or explicitly including truncated
1476 : * segments), only open the next segment if the current one is
1477 : * exactly RELSEG_SIZE. If not (this branch), either return NULL
1478 : * or fail.
1479 : */
1480 24 : if (behavior & EXTENSION_RETURN_NULL)
1481 : {
1482 : /*
1483 : * Some callers discern between reasons for _mdfd_getseg()
1484 : * returning NULL based on errno. As there's no failing
1485 : * syscall involved in this case, explicitly set errno to
1486 : * ENOENT, as that seems the closest interpretation.
1487 : */
1488 0 : errno = ENOENT;
1489 0 : return NULL;
1490 : }
1491 :
1492 24 : ereport(ERROR,
1493 : (errcode_for_file_access(),
1494 : errmsg("could not open file \"%s\" (target block %u): previous segment is only %u blocks",
1495 : _mdfd_segpath(reln, forknum, nextsegno),
1496 : blkno, nblocks)));
1497 : }
1498 :
1499 0 : v = _mdfd_openseg(reln, forknum, nextsegno, flags);
1500 :
1501 0 : if (v == NULL)
1502 : {
1503 0 : if ((behavior & EXTENSION_RETURN_NULL) &&
1504 0 : FILE_POSSIBLY_DELETED(errno))
1505 0 : return NULL;
1506 0 : ereport(ERROR,
1507 : (errcode_for_file_access(),
1508 : errmsg("could not open file \"%s\" (target block %u): %m",
1509 : _mdfd_segpath(reln, forknum, nextsegno),
1510 : blkno)));
1511 : }
1512 : }
1513 :
1514 333328 : return v;
1515 : }
1516 :
1517 : /*
1518 : * Get number of blocks present in a single disk file
1519 : */
1520 : static BlockNumber
1521 3248592 : _mdnblocks(SMgrRelation reln, ForkNumber forknum, MdfdVec *seg)
1522 : {
1523 : off_t len;
1524 :
1525 3248592 : len = FileSize(seg->mdfd_vfd);
1526 3248592 : if (len < 0)
1527 0 : ereport(ERROR,
1528 : (errcode_for_file_access(),
1529 : errmsg("could not seek to end of file \"%s\": %m",
1530 : FilePathName(seg->mdfd_vfd))));
1531 : /* note that this calculation will ignore any partial block at EOF */
1532 3248592 : return (BlockNumber) (len / BLCKSZ);
1533 : }
1534 :
1535 : /*
1536 : * Sync a file to disk, given a file tag. Write the path into an output
1537 : * buffer so the caller can use it in error messages.
1538 : *
1539 : * Return 0 on success, -1 on failure, with errno set.
1540 : */
1541 : int
1542 0 : mdsyncfiletag(const FileTag *ftag, char *path)
1543 : {
1544 0 : SMgrRelation reln = smgropen(ftag->rlocator, InvalidBackendId);
1545 : File file;
1546 : instr_time io_start;
1547 : bool need_to_close;
1548 : int result,
1549 : save_errno;
1550 :
1551 : /* See if we already have the file open, or need to open it. */
1552 0 : if (ftag->segno < reln->md_num_open_segs[ftag->forknum])
1553 : {
1554 0 : file = reln->md_seg_fds[ftag->forknum][ftag->segno].mdfd_vfd;
1555 0 : strlcpy(path, FilePathName(file), MAXPGPATH);
1556 0 : need_to_close = false;
1557 : }
1558 : else
1559 : {
1560 : char *p;
1561 :
1562 0 : p = _mdfd_segpath(reln, ftag->forknum, ftag->segno);
1563 0 : strlcpy(path, p, MAXPGPATH);
1564 0 : pfree(p);
1565 :
1566 0 : file = PathNameOpenFile(path, _mdfd_open_flags());
1567 0 : if (file < 0)
1568 0 : return -1;
1569 0 : need_to_close = true;
1570 : }
1571 :
1572 0 : io_start = pgstat_prepare_io_time();
1573 :
1574 : /* Sync the file. */
1575 0 : result = FileSync(file, WAIT_EVENT_DATA_FILE_SYNC);
1576 0 : save_errno = errno;
1577 :
1578 0 : if (need_to_close)
1579 0 : FileClose(file);
1580 :
1581 0 : pgstat_count_io_op_time(IOOBJECT_RELATION, IOCONTEXT_NORMAL,
1582 : IOOP_FSYNC, io_start, 1);
1583 :
1584 0 : errno = save_errno;
1585 0 : return result;
1586 : }
1587 :
1588 : /*
1589 : * Unlink a file, given a file tag. Write the path into an output
1590 : * buffer so the caller can use it in error messages.
1591 : *
1592 : * Return 0 on success, -1 on failure, with errno set.
1593 : */
1594 : int
1595 55520 : mdunlinkfiletag(const FileTag *ftag, char *path)
1596 : {
1597 : char *p;
1598 :
1599 : /* Compute the path. */
1600 55520 : p = relpathperm(ftag->rlocator, MAIN_FORKNUM);
1601 55520 : strlcpy(path, p, MAXPGPATH);
1602 55520 : pfree(p);
1603 :
1604 : /* Try to unlink the file. */
1605 55520 : return unlink(path);
1606 : }
1607 :
1608 : /*
1609 : * Check if a given candidate request matches a given tag, when processing
1610 : * a SYNC_FILTER_REQUEST request. This will be called for all pending
1611 : * requests to find out whether to forget them.
1612 : */
1613 : bool
1614 12314 : mdfiletagmatches(const FileTag *ftag, const FileTag *candidate)
1615 : {
1616 : /*
1617 : * For now we only use filter requests as a way to drop all scheduled
1618 : * callbacks relating to a given database, when dropping the database.
1619 : * We'll return true for all candidates that have the same database OID as
1620 : * the ftag from the SYNC_FILTER_REQUEST request, so they're forgotten.
1621 : */
1622 12314 : return ftag->rlocator.dbOid == candidate->rlocator.dbOid;
1623 : }
|