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-2019, 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 "miscadmin.h"
29#include "access/xlogutils.h"
30#include "access/xlog.h"
31#include "pgstat.h"
32#include "postmaster/bgwriter.h"
33#include "storage/fd.h"
34#include "storage/bufmgr.h"
35#include "storage/md.h"
36#include "storage/relfilenode.h"
37#include "storage/smgr.h"
38#include "storage/sync.h"
39#include "utils/hsearch.h"
40#include "utils/memutils.h"
41#include "pg_trace.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
81typedef 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
87static 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_rnode,xx_forknum,xx_segno) \
92( \
93 memset(&(a), 0, sizeof(FileTag)), \
94 (a).handler = SYNC_HANDLER_MD, \
95 (a).rnode = (xx_rnode), \
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/*
111 * Allow opening segments which are preceded by segments smaller than
112 * RELSEG_SIZE, e.g. inactive segments (see above). Note that this breaks
113 * mdnblocks() and related functionality henceforth - which currently is ok,
114 * because this is only required in the checkpointer which never uses
115 * mdnblocks().
116 */
117#define EXTENSION_DONT_CHECK_SIZE (1 << 4)
118
119
120/* local routines */
121static void mdunlinkfork(RelFileNodeBackend rnode, ForkNumber forkNum,
122 bool isRedo);
123static MdfdVec *mdopen(SMgrRelation reln, ForkNumber forknum, int behavior);
124static void register_dirty_segment(SMgrRelation reln, ForkNumber forknum,
125 MdfdVec *seg);
126static void register_unlink_segment(RelFileNodeBackend rnode, ForkNumber forknum,
127 BlockNumber segno);
128static void register_forget_request(RelFileNodeBackend rnode, ForkNumber forknum,
129 BlockNumber segno);
130static void _fdvec_resize(SMgrRelation reln,
131 ForkNumber forknum,
132 int nseg);
133static char *_mdfd_segpath(SMgrRelation reln, ForkNumber forknum,
134 BlockNumber segno);
135static MdfdVec *_mdfd_openseg(SMgrRelation reln, ForkNumber forkno,
136 BlockNumber segno, int oflags);
137static MdfdVec *_mdfd_getseg(SMgrRelation reln, ForkNumber forkno,
138 BlockNumber blkno, bool skipFsync, int behavior);
139static BlockNumber _mdnblocks(SMgrRelation reln, ForkNumber forknum,
140 MdfdVec *seg);
141
142
143/*
144 * mdinit() -- Initialize private state for magnetic disk storage manager.
145 */
146void
147mdinit(void)
148{
149 MdCxt = AllocSetContextCreate(TopMemoryContext,
150 "MdSmgr",
151 ALLOCSET_DEFAULT_SIZES);
152}
153
154/*
155 * mdexists() -- Does the physical file exist?
156 *
157 * Note: this will return true for lingering files, with pending deletions
158 */
159bool
160mdexists(SMgrRelation reln, ForkNumber forkNum)
161{
162 /*
163 * Close it first, to ensure that we notice if the fork has been unlinked
164 * since we opened it.
165 */
166 mdclose(reln, forkNum);
167
168 return (mdopen(reln, forkNum, EXTENSION_RETURN_NULL) != NULL);
169}
170
171/*
172 * mdcreate() -- Create a new relation on magnetic disk.
173 *
174 * If isRedo is true, it's okay for the relation to exist already.
175 */
176void
177mdcreate(SMgrRelation reln, ForkNumber forkNum, bool isRedo)
178{
179 MdfdVec *mdfd;
180 char *path;
181 File fd;
182
183 if (isRedo && reln->md_num_open_segs[forkNum] > 0)
184 return; /* created and opened already... */
185
186 Assert(reln->md_num_open_segs[forkNum] == 0);
187
188 path = relpath(reln->smgr_rnode, forkNum);
189
190 fd = PathNameOpenFile(path, O_RDWR | O_CREAT | O_EXCL | PG_BINARY);
191
192 if (fd < 0)
193 {
194 int save_errno = errno;
195
196 if (isRedo)
197 fd = PathNameOpenFile(path, O_RDWR | PG_BINARY);
198 if (fd < 0)
199 {
200 /* be sure to report the error reported by create, not open */
201 errno = save_errno;
202 ereport(ERROR,
203 (errcode_for_file_access(),
204 errmsg("could not create file \"%s\": %m", path)));
205 }
206 }
207
208 pfree(path);
209
210 _fdvec_resize(reln, forkNum, 1);
211 mdfd = &reln->md_seg_fds[forkNum][0];
212 mdfd->mdfd_vfd = fd;
213 mdfd->mdfd_segno = 0;
214}
215
216/*
217 * mdunlink() -- Unlink a relation.
218 *
219 * Note that we're passed a RelFileNodeBackend --- by the time this is called,
220 * there won't be an SMgrRelation hashtable entry anymore.
221 *
222 * forkNum can be a fork number to delete a specific fork, or InvalidForkNumber
223 * to delete all forks.
224 *
225 * For regular relations, we don't unlink the first segment file of the rel,
226 * but just truncate it to zero length, and record a request to unlink it after
227 * the next checkpoint. Additional segments can be unlinked immediately,
228 * however. Leaving the empty file in place prevents that relfilenode
229 * number from being reused. The scenario this protects us from is:
230 * 1. We delete a relation (and commit, and actually remove its file).
231 * 2. We create a new relation, which by chance gets the same relfilenode as
232 * the just-deleted one (OIDs must've wrapped around for that to happen).
233 * 3. We crash before another checkpoint occurs.
234 * During replay, we would delete the file and then recreate it, which is fine
235 * if the contents of the file were repopulated by subsequent WAL entries.
236 * But if we didn't WAL-log insertions, but instead relied on fsyncing the
237 * file after populating it (as for instance CLUSTER and CREATE INDEX do),
238 * the contents of the file would be lost forever. By leaving the empty file
239 * until after the next checkpoint, we prevent reassignment of the relfilenode
240 * number until it's safe, because relfilenode assignment skips over any
241 * existing file.
242 *
243 * We do not need to go through this dance for temp relations, though, because
244 * we never make WAL entries for temp rels, and so a temp rel poses no threat
245 * to the health of a regular rel that has taken over its relfilenode number.
246 * The fact that temp rels and regular rels have different file naming
247 * patterns provides additional safety.
248 *
249 * All the above applies only to the relation's main fork; other forks can
250 * just be removed immediately, since they are not needed to prevent the
251 * relfilenode number from being recycled. Also, we do not carefully
252 * track whether other forks have been created or not, but just attempt to
253 * unlink them unconditionally; so we should never complain about ENOENT.
254 *
255 * If isRedo is true, it's unsurprising for the relation to be already gone.
256 * Also, we should remove the file immediately instead of queuing a request
257 * for later, since during redo there's no possibility of creating a
258 * conflicting relation.
259 *
260 * Note: any failure should be reported as WARNING not ERROR, because
261 * we are usually not in a transaction anymore when this is called.
262 */
263void
264mdunlink(RelFileNodeBackend rnode, ForkNumber forkNum, bool isRedo)
265{
266 /* Now do the per-fork work */
267 if (forkNum == InvalidForkNumber)
268 {
269 for (forkNum = 0; forkNum <= MAX_FORKNUM; forkNum++)
270 mdunlinkfork(rnode, forkNum, isRedo);
271 }
272 else
273 mdunlinkfork(rnode, forkNum, isRedo);
274}
275
276static void
277mdunlinkfork(RelFileNodeBackend rnode, ForkNumber forkNum, bool isRedo)
278{
279 char *path;
280 int ret;
281
282 path = relpath(rnode, forkNum);
283
284 /*
285 * Delete or truncate the first segment.
286 */
287 if (isRedo || forkNum != MAIN_FORKNUM || RelFileNodeBackendIsTemp(rnode))
288 {
289 /* First, forget any pending sync requests for the first segment */
290 if (!RelFileNodeBackendIsTemp(rnode))
291 register_forget_request(rnode, forkNum, 0 /* first seg */ );
292
293 /* Next unlink the file */
294 ret = unlink(path);
295 if (ret < 0 && errno != ENOENT)
296 ereport(WARNING,
297 (errcode_for_file_access(),
298 errmsg("could not remove file \"%s\": %m", path)));
299 }
300 else
301 {
302 /* truncate(2) would be easier here, but Windows hasn't got it */
303 int fd;
304
305 fd = OpenTransientFile(path, O_RDWR | PG_BINARY);
306 if (fd >= 0)
307 {
308 int save_errno;
309
310 ret = ftruncate(fd, 0);
311 save_errno = errno;
312 CloseTransientFile(fd);
313 errno = save_errno;
314 }
315 else
316 ret = -1;
317 if (ret < 0 && errno != ENOENT)
318 ereport(WARNING,
319 (errcode_for_file_access(),
320 errmsg("could not truncate file \"%s\": %m", path)));
321
322 /* Register request to unlink first segment later */
323 register_unlink_segment(rnode, forkNum, 0 /* first seg */ );
324 }
325
326 /*
327 * Delete any additional segments.
328 */
329 if (ret >= 0)
330 {
331 char *segpath = (char *) palloc(strlen(path) + 12);
332 BlockNumber segno;
333
334 /*
335 * Note that because we loop until getting ENOENT, we will correctly
336 * remove all inactive segments as well as active ones.
337 */
338 for (segno = 1;; segno++)
339 {
340 /*
341 * Forget any pending sync requests for this segment before we try
342 * to unlink.
343 */
344 if (!RelFileNodeBackendIsTemp(rnode))
345 register_forget_request(rnode, forkNum, segno);
346
347 sprintf(segpath, "%s.%u", path, segno);
348 if (unlink(segpath) < 0)
349 {
350 /* ENOENT is expected after the last segment... */
351 if (errno != ENOENT)
352 ereport(WARNING,
353 (errcode_for_file_access(),
354 errmsg("could not remove file \"%s\": %m", segpath)));
355 break;
356 }
357 }
358 pfree(segpath);
359 }
360
361 pfree(path);
362}
363
364/*
365 * mdextend() -- Add a block to the specified relation.
366 *
367 * The semantics are nearly the same as mdwrite(): write at the
368 * specified position. However, this is to be used for the case of
369 * extending a relation (i.e., blocknum is at or beyond the current
370 * EOF). Note that we assume writing a block beyond current EOF
371 * causes intervening file space to become filled with zeroes.
372 */
373void
374mdextend(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum,
375 char *buffer, bool skipFsync)
376{
377 off_t seekpos;
378 int nbytes;
379 MdfdVec *v;
380
381 /* This assert is too expensive to have on normally ... */
382#ifdef CHECK_WRITE_VS_EXTEND
383 Assert(blocknum >= mdnblocks(reln, forknum));
384#endif
385
386 /*
387 * If a relation manages to grow to 2^32-1 blocks, refuse to extend it any
388 * more --- we mustn't create a block whose number actually is
389 * InvalidBlockNumber.
390 */
391 if (blocknum == InvalidBlockNumber)
392 ereport(ERROR,
393 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
394 errmsg("cannot extend file \"%s\" beyond %u blocks",
395 relpath(reln->smgr_rnode, forknum),
396 InvalidBlockNumber)));
397
398 v = _mdfd_getseg(reln, forknum, blocknum, skipFsync, EXTENSION_CREATE);
399
400 seekpos = (off_t) BLCKSZ * (blocknum % ((BlockNumber) RELSEG_SIZE));
401
402 Assert(seekpos < (off_t) BLCKSZ * RELSEG_SIZE);
403
404 if ((nbytes = FileWrite(v->mdfd_vfd, buffer, BLCKSZ, seekpos, WAIT_EVENT_DATA_FILE_EXTEND)) != BLCKSZ)
405 {
406 if (nbytes < 0)
407 ereport(ERROR,
408 (errcode_for_file_access(),
409 errmsg("could not extend file \"%s\": %m",
410 FilePathName(v->mdfd_vfd)),
411 errhint("Check free disk space.")));
412 /* short write: complain appropriately */
413 ereport(ERROR,
414 (errcode(ERRCODE_DISK_FULL),
415 errmsg("could not extend file \"%s\": wrote only %d of %d bytes at block %u",
416 FilePathName(v->mdfd_vfd),
417 nbytes, BLCKSZ, blocknum),
418 errhint("Check free disk space.")));
419 }
420
421 if (!skipFsync && !SmgrIsTemp(reln))
422 register_dirty_segment(reln, forknum, v);
423
424 Assert(_mdnblocks(reln, forknum, v) <= ((BlockNumber) RELSEG_SIZE));
425}
426
427/*
428 * mdopen() -- Open the specified relation.
429 *
430 * Note we only open the first segment, when there are multiple segments.
431 *
432 * If first segment is not present, either ereport or return NULL according
433 * to "behavior". We treat EXTENSION_CREATE the same as EXTENSION_FAIL;
434 * EXTENSION_CREATE means it's OK to extend an existing relation, not to
435 * invent one out of whole cloth.
436 */
437static MdfdVec *
438mdopen(SMgrRelation reln, ForkNumber forknum, int behavior)
439{
440 MdfdVec *mdfd;
441 char *path;
442 File fd;
443
444 /* No work if already open */
445 if (reln->md_num_open_segs[forknum] > 0)
446 return &reln->md_seg_fds[forknum][0];
447
448 path = relpath(reln->smgr_rnode, forknum);
449
450 fd = PathNameOpenFile(path, O_RDWR | PG_BINARY);
451
452 if (fd < 0)
453 {
454 if ((behavior & EXTENSION_RETURN_NULL) &&
455 FILE_POSSIBLY_DELETED(errno))
456 {
457 pfree(path);
458 return NULL;
459 }
460 ereport(ERROR,
461 (errcode_for_file_access(),
462 errmsg("could not open file \"%s\": %m", path)));
463 }
464
465 pfree(path);
466
467 _fdvec_resize(reln, forknum, 1);
468 mdfd = &reln->md_seg_fds[forknum][0];
469 mdfd->mdfd_vfd = fd;
470 mdfd->mdfd_segno = 0;
471
472 Assert(_mdnblocks(reln, forknum, mdfd) <= ((BlockNumber) RELSEG_SIZE));
473
474 return mdfd;
475}
476
477/*
478 * mdclose() -- Close the specified relation, if it isn't closed already.
479 */
480void
481mdclose(SMgrRelation reln, ForkNumber forknum)
482{
483 int nopensegs = reln->md_num_open_segs[forknum];
484
485 /* No work if already closed */
486 if (nopensegs == 0)
487 return;
488
489 /* close segments starting from the end */
490 while (nopensegs > 0)
491 {
492 MdfdVec *v = &reln->md_seg_fds[forknum][nopensegs - 1];
493
494 /* if not closed already */
495 if (v->mdfd_vfd >= 0)
496 {
497 FileClose(v->mdfd_vfd);
498 v->mdfd_vfd = -1;
499 }
500
501 nopensegs--;
502 }
503
504 /* resize just once, avoids pointless reallocations */
505 _fdvec_resize(reln, forknum, 0);
506}
507
508/*
509 * mdprefetch() -- Initiate asynchronous read of the specified block of a relation
510 */
511void
512mdprefetch(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum)
513{
514#ifdef USE_PREFETCH
515 off_t seekpos;
516 MdfdVec *v;
517
518 v = _mdfd_getseg(reln, forknum, blocknum, false, EXTENSION_FAIL);
519
520 seekpos = (off_t) BLCKSZ * (blocknum % ((BlockNumber) RELSEG_SIZE));
521
522 Assert(seekpos < (off_t) BLCKSZ * RELSEG_SIZE);
523
524 (void) FilePrefetch(v->mdfd_vfd, seekpos, BLCKSZ, WAIT_EVENT_DATA_FILE_PREFETCH);
525#endif /* USE_PREFETCH */
526}
527
528/*
529 * mdwriteback() -- Tell the kernel to write pages back to storage.
530 *
531 * This accepts a range of blocks because flushing several pages at once is
532 * considerably more efficient than doing so individually.
533 */
534void
535mdwriteback(SMgrRelation reln, ForkNumber forknum,
536 BlockNumber blocknum, BlockNumber nblocks)
537{
538 /*
539 * Issue flush requests in as few requests as possible; have to split at
540 * segment boundaries though, since those are actually separate files.
541 */
542 while (nblocks > 0)
543 {
544 BlockNumber nflush = nblocks;
545 off_t seekpos;
546 MdfdVec *v;
547 int segnum_start,
548 segnum_end;
549
550 v = _mdfd_getseg(reln, forknum, blocknum, true /* not used */ ,
551 EXTENSION_RETURN_NULL);
552
553 /*
554 * We might be flushing buffers of already removed relations, that's
555 * ok, just ignore that case.
556 */
557 if (!v)
558 return;
559
560 /* compute offset inside the current segment */
561 segnum_start = blocknum / RELSEG_SIZE;
562
563 /* compute number of desired writes within the current segment */
564 segnum_end = (blocknum + nblocks - 1) / RELSEG_SIZE;
565 if (segnum_start != segnum_end)
566 nflush = RELSEG_SIZE - (blocknum % ((BlockNumber) RELSEG_SIZE));
567
568 Assert(nflush >= 1);
569 Assert(nflush <= nblocks);
570
571 seekpos = (off_t) BLCKSZ * (blocknum % ((BlockNumber) RELSEG_SIZE));
572
573 FileWriteback(v->mdfd_vfd, seekpos, (off_t) BLCKSZ * nflush, WAIT_EVENT_DATA_FILE_FLUSH);
574
575 nblocks -= nflush;
576 blocknum += nflush;
577 }
578}
579
580/*
581 * mdread() -- Read the specified block from a relation.
582 */
583void
584mdread(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum,
585 char *buffer)
586{
587 off_t seekpos;
588 int nbytes;
589 MdfdVec *v;
590
591 TRACE_POSTGRESQL_SMGR_MD_READ_START(forknum, blocknum,
592 reln->smgr_rnode.node.spcNode,
593 reln->smgr_rnode.node.dbNode,
594 reln->smgr_rnode.node.relNode,
595 reln->smgr_rnode.backend);
596
597 v = _mdfd_getseg(reln, forknum, blocknum, false,
598 EXTENSION_FAIL | EXTENSION_CREATE_RECOVERY);
599
600 seekpos = (off_t) BLCKSZ * (blocknum % ((BlockNumber) RELSEG_SIZE));
601
602 Assert(seekpos < (off_t) BLCKSZ * RELSEG_SIZE);
603
604 nbytes = FileRead(v->mdfd_vfd, buffer, BLCKSZ, seekpos, WAIT_EVENT_DATA_FILE_READ);
605
606 TRACE_POSTGRESQL_SMGR_MD_READ_DONE(forknum, blocknum,
607 reln->smgr_rnode.node.spcNode,
608 reln->smgr_rnode.node.dbNode,
609 reln->smgr_rnode.node.relNode,
610 reln->smgr_rnode.backend,
611 nbytes,
612 BLCKSZ);
613
614 if (nbytes != BLCKSZ)
615 {
616 if (nbytes < 0)
617 ereport(ERROR,
618 (errcode_for_file_access(),
619 errmsg("could not read block %u in file \"%s\": %m",
620 blocknum, FilePathName(v->mdfd_vfd))));
621
622 /*
623 * Short read: we are at or past EOF, or we read a partial block at
624 * EOF. Normally this is an error; upper levels should never try to
625 * read a nonexistent block. However, if zero_damaged_pages is ON or
626 * we are InRecovery, we should instead return zeroes without
627 * complaining. This allows, for example, the case of trying to
628 * update a block that was later truncated away.
629 */
630 if (zero_damaged_pages || InRecovery)
631 MemSet(buffer, 0, BLCKSZ);
632 else
633 ereport(ERROR,
634 (errcode(ERRCODE_DATA_CORRUPTED),
635 errmsg("could not read block %u in file \"%s\": read only %d of %d bytes",
636 blocknum, FilePathName(v->mdfd_vfd),
637 nbytes, BLCKSZ)));
638 }
639}
640
641/*
642 * mdwrite() -- Write the supplied block at the appropriate location.
643 *
644 * This is to be used only for updating already-existing blocks of a
645 * relation (ie, those before the current EOF). To extend a relation,
646 * use mdextend().
647 */
648void
649mdwrite(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum,
650 char *buffer, bool skipFsync)
651{
652 off_t seekpos;
653 int nbytes;
654 MdfdVec *v;
655
656 /* This assert is too expensive to have on normally ... */
657#ifdef CHECK_WRITE_VS_EXTEND
658 Assert(blocknum < mdnblocks(reln, forknum));
659#endif
660
661 TRACE_POSTGRESQL_SMGR_MD_WRITE_START(forknum, blocknum,
662 reln->smgr_rnode.node.spcNode,
663 reln->smgr_rnode.node.dbNode,
664 reln->smgr_rnode.node.relNode,
665 reln->smgr_rnode.backend);
666
667 v = _mdfd_getseg(reln, forknum, blocknum, skipFsync,
668 EXTENSION_FAIL | EXTENSION_CREATE_RECOVERY);
669
670 seekpos = (off_t) BLCKSZ * (blocknum % ((BlockNumber) RELSEG_SIZE));
671
672 Assert(seekpos < (off_t) BLCKSZ * RELSEG_SIZE);
673
674 nbytes = FileWrite(v->mdfd_vfd, buffer, BLCKSZ, seekpos, WAIT_EVENT_DATA_FILE_WRITE);
675
676 TRACE_POSTGRESQL_SMGR_MD_WRITE_DONE(forknum, blocknum,
677 reln->smgr_rnode.node.spcNode,
678 reln->smgr_rnode.node.dbNode,
679 reln->smgr_rnode.node.relNode,
680 reln->smgr_rnode.backend,
681 nbytes,
682 BLCKSZ);
683
684 if (nbytes != BLCKSZ)
685 {
686 if (nbytes < 0)
687 ereport(ERROR,
688 (errcode_for_file_access(),
689 errmsg("could not write block %u in file \"%s\": %m",
690 blocknum, FilePathName(v->mdfd_vfd))));
691 /* short write: complain appropriately */
692 ereport(ERROR,
693 (errcode(ERRCODE_DISK_FULL),
694 errmsg("could not write block %u in file \"%s\": wrote only %d of %d bytes",
695 blocknum,
696 FilePathName(v->mdfd_vfd),
697 nbytes, BLCKSZ),
698 errhint("Check free disk space.")));
699 }
700
701 if (!skipFsync && !SmgrIsTemp(reln))
702 register_dirty_segment(reln, forknum, v);
703}
704
705/*
706 * mdnblocks() -- Get the number of blocks stored in a relation.
707 *
708 * Important side effect: all active segments of the relation are opened
709 * and added to the mdfd_seg_fds array. If this routine has not been
710 * called, then only segments up to the last one actually touched
711 * are present in the array.
712 */
713BlockNumber
714mdnblocks(SMgrRelation reln, ForkNumber forknum)
715{
716 MdfdVec *v = mdopen(reln, forknum, EXTENSION_FAIL);
717 BlockNumber nblocks;
718 BlockNumber segno = 0;
719
720 /* mdopen has opened the first segment */
721 Assert(reln->md_num_open_segs[forknum] > 0);
722
723 /*
724 * Start from the last open segments, to avoid redundant seeks. We have
725 * previously verified that these segments are exactly RELSEG_SIZE long,
726 * and it's useless to recheck that each time.
727 *
728 * NOTE: this assumption could only be wrong if another backend has
729 * truncated the relation. We rely on higher code levels to handle that
730 * scenario by closing and re-opening the md fd, which is handled via
731 * relcache flush. (Since the checkpointer doesn't participate in
732 * relcache flush, it could have segment entries for inactive segments;
733 * that's OK because the checkpointer never needs to compute relation
734 * size.)
735 */
736 segno = reln->md_num_open_segs[forknum] - 1;
737 v = &reln->md_seg_fds[forknum][segno];
738
739 for (;;)
740 {
741 nblocks = _mdnblocks(reln, forknum, v);
742 if (nblocks > ((BlockNumber) RELSEG_SIZE))
743 elog(FATAL, "segment too big");
744 if (nblocks < ((BlockNumber) RELSEG_SIZE))
745 return (segno * ((BlockNumber) RELSEG_SIZE)) + nblocks;
746
747 /*
748 * If segment is exactly RELSEG_SIZE, advance to next one.
749 */
750 segno++;
751
752 /*
753 * We used to pass O_CREAT here, but that has the disadvantage that it
754 * might create a segment which has vanished through some operating
755 * system misadventure. In such a case, creating the segment here
756 * undermines _mdfd_getseg's attempts to notice and report an error
757 * upon access to a missing segment.
758 */
759 v = _mdfd_openseg(reln, forknum, segno, 0);
760 if (v == NULL)
761 return segno * ((BlockNumber) RELSEG_SIZE);
762 }
763}
764
765/*
766 * mdtruncate() -- Truncate relation to specified number of blocks.
767 */
768void
769mdtruncate(SMgrRelation reln, ForkNumber forknum, BlockNumber nblocks)
770{
771 BlockNumber curnblk;
772 BlockNumber priorblocks;
773 int curopensegs;
774
775 /*
776 * NOTE: mdnblocks makes sure we have opened all active segments, so that
777 * truncation loop will get them all!
778 */
779 curnblk = mdnblocks(reln, forknum);
780 if (nblocks > curnblk)
781 {
782 /* Bogus request ... but no complaint if InRecovery */
783 if (InRecovery)
784 return;
785 ereport(ERROR,
786 (errmsg("could not truncate file \"%s\" to %u blocks: it's only %u blocks now",
787 relpath(reln->smgr_rnode, forknum),
788 nblocks, curnblk)));
789 }
790 if (nblocks == curnblk)
791 return; /* no work */
792
793 /*
794 * Truncate segments, starting at the last one. Starting at the end makes
795 * managing the memory for the fd array easier, should there be errors.
796 */
797 curopensegs = reln->md_num_open_segs[forknum];
798 while (curopensegs > 0)
799 {
800 MdfdVec *v;
801
802 priorblocks = (curopensegs - 1) * RELSEG_SIZE;
803
804 v = &reln->md_seg_fds[forknum][curopensegs - 1];
805
806 if (priorblocks > nblocks)
807 {
808 /*
809 * This segment is no longer active. We truncate the file, but do
810 * not delete it, for reasons explained in the header comments.
811 */
812 if (FileTruncate(v->mdfd_vfd, 0, WAIT_EVENT_DATA_FILE_TRUNCATE) < 0)
813 ereport(ERROR,
814 (errcode_for_file_access(),
815 errmsg("could not truncate file \"%s\": %m",
816 FilePathName(v->mdfd_vfd))));
817
818 if (!SmgrIsTemp(reln))
819 register_dirty_segment(reln, forknum, v);
820
821 /* we never drop the 1st segment */
822 Assert(v != &reln->md_seg_fds[forknum][0]);
823
824 FileClose(v->mdfd_vfd);
825 _fdvec_resize(reln, forknum, curopensegs - 1);
826 }
827 else if (priorblocks + ((BlockNumber) RELSEG_SIZE) > nblocks)
828 {
829 /*
830 * This is the last segment we want to keep. Truncate the file to
831 * the right length. NOTE: if nblocks is exactly a multiple K of
832 * RELSEG_SIZE, we will truncate the K+1st segment to 0 length but
833 * keep it. This adheres to the invariant given in the header
834 * comments.
835 */
836 BlockNumber lastsegblocks = nblocks - priorblocks;
837
838 if (FileTruncate(v->mdfd_vfd, (off_t) lastsegblocks * BLCKSZ, WAIT_EVENT_DATA_FILE_TRUNCATE) < 0)
839 ereport(ERROR,
840 (errcode_for_file_access(),
841 errmsg("could not truncate file \"%s\" to %u blocks: %m",
842 FilePathName(v->mdfd_vfd),
843 nblocks)));
844 if (!SmgrIsTemp(reln))
845 register_dirty_segment(reln, forknum, v);
846 }
847 else
848 {
849 /*
850 * We still need this segment, so nothing to do for this and any
851 * earlier segment.
852 */
853 break;
854 }
855 curopensegs--;
856 }
857}
858
859/*
860 * mdimmedsync() -- Immediately sync a relation to stable storage.
861 *
862 * Note that only writes already issued are synced; this routine knows
863 * nothing of dirty buffers that may exist inside the buffer manager.
864 */
865void
866mdimmedsync(SMgrRelation reln, ForkNumber forknum)
867{
868 int segno;
869
870 /*
871 * NOTE: mdnblocks makes sure we have opened all active segments, so that
872 * fsync loop will get them all!
873 */
874 mdnblocks(reln, forknum);
875
876 segno = reln->md_num_open_segs[forknum];
877
878 while (segno > 0)
879 {
880 MdfdVec *v = &reln->md_seg_fds[forknum][segno - 1];
881
882 if (FileSync(v->mdfd_vfd, WAIT_EVENT_DATA_FILE_IMMEDIATE_SYNC) < 0)
883 ereport(data_sync_elevel(ERROR),
884 (errcode_for_file_access(),
885 errmsg("could not fsync file \"%s\": %m",
886 FilePathName(v->mdfd_vfd))));
887 segno--;
888 }
889}
890
891/*
892 * register_dirty_segment() -- Mark a relation segment as needing fsync
893 *
894 * If there is a local pending-ops table, just make an entry in it for
895 * ProcessSyncRequests to process later. Otherwise, try to pass off the
896 * fsync request to the checkpointer process. If that fails, just do the
897 * fsync locally before returning (we hope this will not happen often
898 * enough to be a performance problem).
899 */
900static void
901register_dirty_segment(SMgrRelation reln, ForkNumber forknum, MdfdVec *seg)
902{
903 FileTag tag;
904
905 INIT_MD_FILETAG(tag, reln->smgr_rnode.node, forknum, seg->mdfd_segno);
906
907 /* Temp relations should never be fsync'd */
908 Assert(!SmgrIsTemp(reln));
909
910 if (!RegisterSyncRequest(&tag, SYNC_REQUEST, false /* retryOnError */ ))
911 {
912 ereport(DEBUG1,
913 (errmsg("could not forward fsync request because request queue is full")));
914
915 if (FileSync(seg->mdfd_vfd, WAIT_EVENT_DATA_FILE_SYNC) < 0)
916 ereport(data_sync_elevel(ERROR),
917 (errcode_for_file_access(),
918 errmsg("could not fsync file \"%s\": %m",
919 FilePathName(seg->mdfd_vfd))));
920 }
921}
922
923/*
924 * register_unlink_segment() -- Schedule a file to be deleted after next checkpoint
925 */
926static void
927register_unlink_segment(RelFileNodeBackend rnode, ForkNumber forknum,
928 BlockNumber segno)
929{
930 FileTag tag;
931
932 INIT_MD_FILETAG(tag, rnode.node, forknum, segno);
933
934 /* Should never be used with temp relations */
935 Assert(!RelFileNodeBackendIsTemp(rnode));
936
937 RegisterSyncRequest(&tag, SYNC_UNLINK_REQUEST, true /* retryOnError */ );
938}
939
940/*
941 * register_forget_request() -- forget any fsyncs for a relation fork's segment
942 */
943static void
944register_forget_request(RelFileNodeBackend rnode, ForkNumber forknum,
945 BlockNumber segno)
946{
947 FileTag tag;
948
949 INIT_MD_FILETAG(tag, rnode.node, forknum, segno);
950
951 RegisterSyncRequest(&tag, SYNC_FORGET_REQUEST, true /* retryOnError */ );
952}
953
954/*
955 * ForgetDatabaseSyncRequests -- forget any fsyncs and unlinks for a DB
956 */
957void
958ForgetDatabaseSyncRequests(Oid dbid)
959{
960 FileTag tag;
961 RelFileNode rnode;
962
963 rnode.dbNode = dbid;
964 rnode.spcNode = 0;
965 rnode.relNode = 0;
966
967 INIT_MD_FILETAG(tag, rnode, InvalidForkNumber, InvalidBlockNumber);
968
969 RegisterSyncRequest(&tag, SYNC_FILTER_REQUEST, true /* retryOnError */ );
970}
971
972/*
973 * DropRelationFiles -- drop files of all given relations
974 */
975void
976DropRelationFiles(RelFileNode *delrels, int ndelrels, bool isRedo)
977{
978 SMgrRelation *srels;
979 int i;
980
981 srels = palloc(sizeof(SMgrRelation) * ndelrels);
982 for (i = 0; i < ndelrels; i++)
983 {
984 SMgrRelation srel = smgropen(delrels[i], InvalidBackendId);
985
986 if (isRedo)
987 {
988 ForkNumber fork;
989
990 for (fork = 0; fork <= MAX_FORKNUM; fork++)
991 XLogDropRelation(delrels[i], fork);
992 }
993 srels[i] = srel;
994 }
995
996 smgrdounlinkall(srels, ndelrels, isRedo);
997
998 for (i = 0; i < ndelrels; i++)
999 smgrclose(srels[i]);
1000 pfree(srels);
1001}
1002
1003
1004/*
1005 * _fdvec_resize() -- Resize the fork's open segments array
1006 */
1007static void
1008_fdvec_resize(SMgrRelation reln,
1009 ForkNumber forknum,
1010 int nseg)
1011{
1012 if (nseg == 0)
1013 {
1014 if (reln->md_num_open_segs[forknum] > 0)
1015 {
1016 pfree(reln->md_seg_fds[forknum]);
1017 reln->md_seg_fds[forknum] = NULL;
1018 }
1019 }
1020 else if (reln->md_num_open_segs[forknum] == 0)
1021 {
1022 reln->md_seg_fds[forknum] =
1023 MemoryContextAlloc(MdCxt, sizeof(MdfdVec) * nseg);
1024 }
1025 else
1026 {
1027 /*
1028 * It doesn't seem worthwhile complicating the code by having a more
1029 * aggressive growth strategy here; the number of segments doesn't
1030 * grow that fast, and the memory context internally will sometimes
1031 * avoid doing an actual reallocation.
1032 */
1033 reln->md_seg_fds[forknum] =
1034 repalloc(reln->md_seg_fds[forknum],
1035 sizeof(MdfdVec) * nseg);
1036 }
1037
1038 reln->md_num_open_segs[forknum] = nseg;
1039}
1040
1041/*
1042 * Return the filename for the specified segment of the relation. The
1043 * returned string is palloc'd.
1044 */
1045static char *
1046_mdfd_segpath(SMgrRelation reln, ForkNumber forknum, BlockNumber segno)
1047{
1048 char *path,
1049 *fullpath;
1050
1051 path = relpath(reln->smgr_rnode, forknum);
1052
1053 if (segno > 0)
1054 {
1055 fullpath = psprintf("%s.%u", path, segno);
1056 pfree(path);
1057 }
1058 else
1059 fullpath = path;
1060
1061 return fullpath;
1062}
1063
1064/*
1065 * Open the specified segment of the relation,
1066 * and make a MdfdVec object for it. Returns NULL on failure.
1067 */
1068static MdfdVec *
1069_mdfd_openseg(SMgrRelation reln, ForkNumber forknum, BlockNumber segno,
1070 int oflags)
1071{
1072 MdfdVec *v;
1073 int fd;
1074 char *fullpath;
1075
1076 fullpath = _mdfd_segpath(reln, forknum, segno);
1077
1078 /* open the file */
1079 fd = PathNameOpenFile(fullpath, O_RDWR | PG_BINARY | oflags);
1080
1081 pfree(fullpath);
1082
1083 if (fd < 0)
1084 return NULL;
1085
1086 if (segno <= reln->md_num_open_segs[forknum])
1087 _fdvec_resize(reln, forknum, segno + 1);
1088
1089 /* fill the entry */
1090 v = &reln->md_seg_fds[forknum][segno];
1091 v->mdfd_vfd = fd;
1092 v->mdfd_segno = segno;
1093
1094 Assert(_mdnblocks(reln, forknum, v) <= ((BlockNumber) RELSEG_SIZE));
1095
1096 /* all done */
1097 return v;
1098}
1099
1100/*
1101 * _mdfd_getseg() -- Find the segment of the relation holding the
1102 * specified block.
1103 *
1104 * If the segment doesn't exist, we ereport, return NULL, or create the
1105 * segment, according to "behavior". Note: skipFsync is only used in the
1106 * EXTENSION_CREATE case.
1107 */
1108static MdfdVec *
1109_mdfd_getseg(SMgrRelation reln, ForkNumber forknum, BlockNumber blkno,
1110 bool skipFsync, int behavior)
1111{
1112 MdfdVec *v;
1113 BlockNumber targetseg;
1114 BlockNumber nextsegno;
1115
1116 /* some way to handle non-existent segments needs to be specified */
1117 Assert(behavior &
1118 (EXTENSION_FAIL | EXTENSION_CREATE | EXTENSION_RETURN_NULL));
1119
1120 targetseg = blkno / ((BlockNumber) RELSEG_SIZE);
1121
1122 /* if an existing and opened segment, we're done */
1123 if (targetseg < reln->md_num_open_segs[forknum])
1124 {
1125 v = &reln->md_seg_fds[forknum][targetseg];
1126 return v;
1127 }
1128
1129 /*
1130 * The target segment is not yet open. Iterate over all the segments
1131 * between the last opened and the target segment. This way missing
1132 * segments either raise an error, or get created (according to
1133 * 'behavior'). Start with either the last opened, or the first segment if
1134 * none was opened before.
1135 */
1136 if (reln->md_num_open_segs[forknum] > 0)
1137 v = &reln->md_seg_fds[forknum][reln->md_num_open_segs[forknum] - 1];
1138 else
1139 {
1140 v = mdopen(reln, forknum, behavior);
1141 if (!v)
1142 return NULL; /* if behavior & EXTENSION_RETURN_NULL */
1143 }
1144
1145 for (nextsegno = reln->md_num_open_segs[forknum];
1146 nextsegno <= targetseg; nextsegno++)
1147 {
1148 BlockNumber nblocks = _mdnblocks(reln, forknum, v);
1149 int flags = 0;
1150
1151 Assert(nextsegno == v->mdfd_segno + 1);
1152
1153 if (nblocks > ((BlockNumber) RELSEG_SIZE))
1154 elog(FATAL, "segment too big");
1155
1156 if ((behavior & EXTENSION_CREATE) ||
1157 (InRecovery && (behavior & EXTENSION_CREATE_RECOVERY)))
1158 {
1159 /*
1160 * Normally we will create new segments only if authorized by the
1161 * caller (i.e., we are doing mdextend()). But when doing WAL
1162 * recovery, create segments anyway; this allows cases such as
1163 * replaying WAL data that has a write into a high-numbered
1164 * segment of a relation that was later deleted. We want to go
1165 * ahead and create the segments so we can finish out the replay.
1166 * However if the caller has specified
1167 * EXTENSION_REALLY_RETURN_NULL, then extension is not desired
1168 * even in recovery; we won't reach this point in that case.
1169 *
1170 * We have to maintain the invariant that segments before the last
1171 * active segment are of size RELSEG_SIZE; therefore, if
1172 * extending, pad them out with zeroes if needed. (This only
1173 * matters if in recovery, or if the caller is extending the
1174 * relation discontiguously, but that can happen in hash indexes.)
1175 */
1176 if (nblocks < ((BlockNumber) RELSEG_SIZE))
1177 {
1178 char *zerobuf = palloc0(BLCKSZ);
1179
1180 mdextend(reln, forknum,
1181 nextsegno * ((BlockNumber) RELSEG_SIZE) - 1,
1182 zerobuf, skipFsync);
1183 pfree(zerobuf);
1184 }
1185 flags = O_CREAT;
1186 }
1187 else if (!(behavior & EXTENSION_DONT_CHECK_SIZE) &&
1188 nblocks < ((BlockNumber) RELSEG_SIZE))
1189 {
1190 /*
1191 * When not extending (or explicitly including truncated
1192 * segments), only open the next segment if the current one is
1193 * exactly RELSEG_SIZE. If not (this branch), either return NULL
1194 * or fail.
1195 */
1196 if (behavior & EXTENSION_RETURN_NULL)
1197 {
1198 /*
1199 * Some callers discern between reasons for _mdfd_getseg()
1200 * returning NULL based on errno. As there's no failing
1201 * syscall involved in this case, explicitly set errno to
1202 * ENOENT, as that seems the closest interpretation.
1203 */
1204 errno = ENOENT;
1205 return NULL;
1206 }
1207
1208 ereport(ERROR,
1209 (errcode_for_file_access(),
1210 errmsg("could not open file \"%s\" (target block %u): previous segment is only %u blocks",
1211 _mdfd_segpath(reln, forknum, nextsegno),
1212 blkno, nblocks)));
1213 }
1214
1215 v = _mdfd_openseg(reln, forknum, nextsegno, flags);
1216
1217 if (v == NULL)
1218 {
1219 if ((behavior & EXTENSION_RETURN_NULL) &&
1220 FILE_POSSIBLY_DELETED(errno))
1221 return NULL;
1222 ereport(ERROR,
1223 (errcode_for_file_access(),
1224 errmsg("could not open file \"%s\" (target block %u): %m",
1225 _mdfd_segpath(reln, forknum, nextsegno),
1226 blkno)));
1227 }
1228 }
1229
1230 return v;
1231}
1232
1233/*
1234 * Get number of blocks present in a single disk file
1235 */
1236static BlockNumber
1237_mdnblocks(SMgrRelation reln, ForkNumber forknum, MdfdVec *seg)
1238{
1239 off_t len;
1240
1241 len = FileSize(seg->mdfd_vfd);
1242 if (len < 0)
1243 ereport(ERROR,
1244 (errcode_for_file_access(),
1245 errmsg("could not seek to end of file \"%s\": %m",
1246 FilePathName(seg->mdfd_vfd))));
1247 /* note that this calculation will ignore any partial block at EOF */
1248 return (BlockNumber) (len / BLCKSZ);
1249}
1250
1251/*
1252 * Sync a file to disk, given a file tag. Write the path into an output
1253 * buffer so the caller can use it in error messages.
1254 *
1255 * Return 0 on success, -1 on failure, with errno set.
1256 */
1257int
1258mdsyncfiletag(const FileTag *ftag, char *path)
1259{
1260 SMgrRelation reln = smgropen(ftag->rnode, InvalidBackendId);
1261 MdfdVec *v;
1262 char *p;
1263
1264 /* Provide the path for informational messages. */
1265 p = _mdfd_segpath(reln, ftag->forknum, ftag->segno);
1266 strlcpy(path, p, MAXPGPATH);
1267 pfree(p);
1268
1269 /* Try to open the requested segment. */
1270 v = _mdfd_getseg(reln,
1271 ftag->forknum,
1272 ftag->segno * (BlockNumber) RELSEG_SIZE,
1273 false,
1274 EXTENSION_RETURN_NULL | EXTENSION_DONT_CHECK_SIZE);
1275 if (v == NULL)
1276 return -1;
1277
1278 /* Try to fsync the file. */
1279 return FileSync(v->mdfd_vfd, WAIT_EVENT_DATA_FILE_SYNC);
1280}
1281
1282/*
1283 * Unlink a file, given a file tag. Write the path into an output
1284 * buffer so the caller can use it in error messages.
1285 *
1286 * Return 0 on success, -1 on failure, with errno set.
1287 */
1288int
1289mdunlinkfiletag(const FileTag *ftag, char *path)
1290{
1291 char *p;
1292
1293 /* Compute the path. */
1294 p = relpathperm(ftag->rnode, MAIN_FORKNUM);
1295 strlcpy(path, p, MAXPGPATH);
1296 pfree(p);
1297
1298 /* Try to unlink the file. */
1299 return unlink(path);
1300}
1301
1302/*
1303 * Check if a given candidate request matches a given tag, when processing
1304 * a SYNC_FILTER_REQUEST request. This will be called for all pending
1305 * requests to find out whether to forget them.
1306 */
1307bool
1308mdfiletagmatches(const FileTag *ftag, const FileTag *candidate)
1309{
1310 /*
1311 * For now we only use filter requests as a way to drop all scheduled
1312 * callbacks relating to a given database, when dropping the database.
1313 * We'll return true for all candidates that have the same database OID as
1314 * the ftag from the SYNC_FILTER_REQUEST request, so they're forgotten.
1315 */
1316 return ftag->rnode.dbNode == candidate->rnode.dbNode;
1317}
1318