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-2016, 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 "catalog/catalog.h"
32 #include "portability/instr_time.h"
33 #include "postmaster/bgwriter.h"
34 #include "storage/fd.h"
35 #include "storage/bufmgr.h"
36 #include "storage/relfilenode.h"
37 #include "storage/smgr.h"
38 #include "utils/hsearch.h"
39 #include "utils/memutils.h"
40 #include "pg_trace.h"
41 
42 
43 /* intervals for calling AbsorbFsyncRequests in mdsync and mdpostckpt */
44 #define FSYNCS_PER_ABSORB		10
45 #define UNLINKS_PER_ABSORB		10
46 
47 /*
48  * Special values for the segno arg to RememberFsyncRequest.
49  *
50  * Note that CompactCheckpointerRequestQueue assumes that it's OK to remove an
51  * fsync request from the queue if an identical, subsequent request is found.
52  * See comments there before making changes here.
53  */
54 #define FORGET_RELATION_FSYNC	(InvalidBlockNumber)
55 #define FORGET_DATABASE_FSYNC	(InvalidBlockNumber-1)
56 #define UNLINK_RELATION_REQUEST (InvalidBlockNumber-2)
57 
58 /*
59  * On Windows, we have to interpret EACCES as possibly meaning the same as
60  * ENOENT, because if a file is unlinked-but-not-yet-gone on that platform,
61  * that's what you get.  Ugh.  This code is designed so that we don't
62  * actually believe these cases are okay without further evidence (namely,
63  * a pending fsync request getting canceled ... see mdsync).
64  */
65 #ifndef WIN32
66 #define FILE_POSSIBLY_DELETED(err)	((err) == ENOENT)
67 #else
68 #define FILE_POSSIBLY_DELETED(err)	((err) == ENOENT || (err) == EACCES)
69 #endif
70 
71 /*
72  *	The magnetic disk storage manager keeps track of open file
73  *	descriptors in its own descriptor pool.  This is done to make it
74  *	easier to support relations that are larger than the operating
75  *	system's file size limit (often 2GBytes).  In order to do that,
76  *	we break relations up into "segment" files that are each shorter than
77  *	the OS file size limit.  The segment size is set by the RELSEG_SIZE
78  *	configuration constant in pg_config.h.
79  *
80  *	On disk, a relation must consist of consecutively numbered segment
81  *	files in the pattern
82  *		-- Zero or more full segments of exactly RELSEG_SIZE blocks each
83  *		-- Exactly one partial segment of size 0 <= size < RELSEG_SIZE blocks
84  *		-- Optionally, any number of inactive segments of size 0 blocks.
85  *	The full and partial segments are collectively the "active" segments.
86  *	Inactive segments are those that once contained data but are currently
87  *	not needed because of an mdtruncate() operation.  The reason for leaving
88  *	them present at size zero, rather than unlinking them, is that other
89  *	backends and/or the checkpointer might be holding open file references to
90  *	such segments.  If the relation expands again after mdtruncate(), such
91  *	that a deactivated segment becomes active again, it is important that
92  *	such file references still be valid --- else data might get written
93  *	out to an unlinked old copy of a segment file that will eventually
94  *	disappear.
95  *
96  *	The file descriptor pointer (md_fd field) stored in the SMgrRelation
97  *	cache is, therefore, just the head of a list of MdfdVec objects, one
98  *	per segment.  But note the md_fd pointer can be NULL, indicating
99  *	relation not open.
100  *
101  *	Also note that mdfd_chain == NULL does not necessarily mean the relation
102  *	doesn't have another segment after this one; we may just not have
103  *	opened the next segment yet.  (We could not have "all segments are
104  *	in the chain" as an invariant anyway, since another backend could
105  *	extend the relation when we weren't looking.)  We do not make chain
106  *	entries for inactive segments, however; as soon as we find a partial
107  *	segment, we assume that any subsequent segments are inactive.
108  *
109  *	All MdfdVec objects are palloc'd in the MdCxt memory context.
110  */
111 
112 typedef struct _MdfdVec
113 {
114 	File		mdfd_vfd;		/* fd number in fd.c's pool */
115 	BlockNumber mdfd_segno;		/* segment number, from 0 */
116 	struct _MdfdVec *mdfd_chain;	/* next segment, or NULL */
117 } MdfdVec;
118 
119 static MemoryContext MdCxt;		/* context for all MdfdVec objects */
120 
121 
122 /*
123  * In some contexts (currently, standalone backends and the checkpointer)
124  * we keep track of pending fsync operations: we need to remember all relation
125  * segments that have been written since the last checkpoint, so that we can
126  * fsync them down to disk before completing the next checkpoint.  This hash
127  * table remembers the pending operations.  We use a hash table mostly as
128  * a convenient way of merging duplicate requests.
129  *
130  * We use a similar mechanism to remember no-longer-needed files that can
131  * be deleted after the next checkpoint, but we use a linked list instead of
132  * a hash table, because we don't expect there to be any duplicate requests.
133  *
134  * These mechanisms are only used for non-temp relations; we never fsync
135  * temp rels, nor do we need to postpone their deletion (see comments in
136  * mdunlink).
137  *
138  * (Regular backends do not track pending operations locally, but forward
139  * them to the checkpointer.)
140  */
141 typedef uint16 CycleCtr;		/* can be any convenient integer size */
142 
143 typedef struct
144 {
145 	RelFileNode rnode;			/* hash table key (must be first!) */
146 	CycleCtr	cycle_ctr;		/* mdsync_cycle_ctr of oldest request */
147 	/* requests[f] has bit n set if we need to fsync segment n of fork f */
148 	Bitmapset  *requests[MAX_FORKNUM + 1];
149 	/* canceled[f] is true if we canceled fsyncs for fork "recently" */
150 	bool		canceled[MAX_FORKNUM + 1];
151 } PendingOperationEntry;
152 
153 typedef struct
154 {
155 	RelFileNode rnode;			/* the dead relation to delete */
156 	CycleCtr	cycle_ctr;		/* mdckpt_cycle_ctr when request was made */
157 } PendingUnlinkEntry;
158 
159 static HTAB *pendingOpsTable = NULL;
160 static List *pendingUnlinks = NIL;
161 static MemoryContext pendingOpsCxt;		/* context for the above  */
162 
163 static CycleCtr mdsync_cycle_ctr = 0;
164 static CycleCtr mdckpt_cycle_ctr = 0;
165 
166 
167 /*** behavior for mdopen & _mdfd_getseg ***/
168 /* ereport if segment not present */
169 #define EXTENSION_FAIL				(1 << 0)
170 /* return NULL if segment not present */
171 #define EXTENSION_RETURN_NULL		(1 << 1)
172 /* create new segments as needed */
173 #define EXTENSION_CREATE			(1 << 2)
174 /* create new segments if needed during recovery */
175 #define EXTENSION_CREATE_RECOVERY	(1 << 3)
176 /*
177  * Allow opening segments which are preceded by segments smaller than
178  * RELSEG_SIZE, e.g. inactive segments (see above). Note that this is breaks
179  * mdnblocks() and related functionality henceforth - which currently is ok,
180  * because this is only required in the checkpointer which never uses
181  * mdnblocks().
182  */
183 #define EXTENSION_DONT_CHECK_SIZE	(1 << 4)
184 
185 
186 /* local routines */
187 static void mdunlinkfork(RelFileNodeBackend rnode, ForkNumber forkNum,
188 			 bool isRedo);
189 static MdfdVec *mdopen(SMgrRelation reln, ForkNumber forknum, int behavior);
190 static void register_dirty_segment(SMgrRelation reln, ForkNumber forknum,
191 					   MdfdVec *seg);
192 static void register_unlink(RelFileNodeBackend rnode);
193 static MdfdVec *_fdvec_alloc(void);
194 static char *_mdfd_segpath(SMgrRelation reln, ForkNumber forknum,
195 			  BlockNumber segno);
196 static MdfdVec *_mdfd_openseg(SMgrRelation reln, ForkNumber forkno,
197 			  BlockNumber segno, int oflags);
198 static MdfdVec *_mdfd_getseg(SMgrRelation reln, ForkNumber forkno,
199 			 BlockNumber blkno, bool skipFsync, int behavior);
200 static BlockNumber _mdnblocks(SMgrRelation reln, ForkNumber forknum,
201 		   MdfdVec *seg);
202 
203 
204 /*
205  *	mdinit() -- Initialize private state for magnetic disk storage manager.
206  */
207 void
mdinit(void)208 mdinit(void)
209 {
210 	MdCxt = AllocSetContextCreate(TopMemoryContext,
211 								  "MdSmgr",
212 								  ALLOCSET_DEFAULT_SIZES);
213 
214 	/*
215 	 * Create pending-operations hashtable if we need it.  Currently, we need
216 	 * it if we are standalone (not under a postmaster) or if we are a startup
217 	 * or checkpointer auxiliary process.
218 	 */
219 	if (!IsUnderPostmaster || AmStartupProcess() || AmCheckpointerProcess())
220 	{
221 		HASHCTL		hash_ctl;
222 
223 		/*
224 		 * XXX: The checkpointer needs to add entries to the pending ops table
225 		 * when absorbing fsync requests.  That is done within a critical
226 		 * section, which isn't usually allowed, but we make an exception. It
227 		 * means that there's a theoretical possibility that you run out of
228 		 * memory while absorbing fsync requests, which leads to a PANIC.
229 		 * Fortunately the hash table is small so that's unlikely to happen in
230 		 * practice.
231 		 */
232 		pendingOpsCxt = AllocSetContextCreate(MdCxt,
233 											  "Pending ops context",
234 											  ALLOCSET_DEFAULT_SIZES);
235 		MemoryContextAllowInCriticalSection(pendingOpsCxt, true);
236 
237 		MemSet(&hash_ctl, 0, sizeof(hash_ctl));
238 		hash_ctl.keysize = sizeof(RelFileNode);
239 		hash_ctl.entrysize = sizeof(PendingOperationEntry);
240 		hash_ctl.hcxt = pendingOpsCxt;
241 		pendingOpsTable = hash_create("Pending Ops Table",
242 									  100L,
243 									  &hash_ctl,
244 									  HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
245 		pendingUnlinks = NIL;
246 	}
247 }
248 
249 /*
250  * In archive recovery, we rely on checkpointer to do fsyncs, but we will have
251  * already created the pendingOpsTable during initialization of the startup
252  * process.  Calling this function drops the local pendingOpsTable so that
253  * subsequent requests will be forwarded to checkpointer.
254  */
255 void
SetForwardFsyncRequests(void)256 SetForwardFsyncRequests(void)
257 {
258 	/* Perform any pending fsyncs we may have queued up, then drop table */
259 	if (pendingOpsTable)
260 	{
261 		mdsync();
262 		hash_destroy(pendingOpsTable);
263 	}
264 	pendingOpsTable = NULL;
265 
266 	/*
267 	 * We should not have any pending unlink requests, since mdunlink doesn't
268 	 * queue unlink requests when isRedo.
269 	 */
270 	Assert(pendingUnlinks == NIL);
271 }
272 
273 /*
274  *	mdexists() -- Does the physical file exist?
275  *
276  * Note: this will return true for lingering files, with pending deletions
277  */
278 bool
mdexists(SMgrRelation reln,ForkNumber forkNum)279 mdexists(SMgrRelation reln, ForkNumber forkNum)
280 {
281 	/*
282 	 * Close it first, to ensure that we notice if the fork has been unlinked
283 	 * since we opened it.
284 	 */
285 	mdclose(reln, forkNum);
286 
287 	return (mdopen(reln, forkNum, EXTENSION_RETURN_NULL) != NULL);
288 }
289 
290 /*
291  *	mdcreate() -- Create a new relation on magnetic disk.
292  *
293  * If isRedo is true, it's okay for the relation to exist already.
294  */
295 void
mdcreate(SMgrRelation reln,ForkNumber forkNum,bool isRedo)296 mdcreate(SMgrRelation reln, ForkNumber forkNum, bool isRedo)
297 {
298 	char	   *path;
299 	File		fd;
300 
301 	if (isRedo && reln->md_fd[forkNum] != NULL)
302 		return;					/* created and opened already... */
303 
304 	Assert(reln->md_fd[forkNum] == NULL);
305 
306 	path = relpath(reln->smgr_rnode, forkNum);
307 
308 	fd = PathNameOpenFile(path, O_RDWR | O_CREAT | O_EXCL | PG_BINARY, 0600);
309 
310 	if (fd < 0)
311 	{
312 		int			save_errno = errno;
313 
314 		/*
315 		 * During bootstrap, there are cases where a system relation will be
316 		 * accessed (by internal backend processes) before the bootstrap
317 		 * script nominally creates it.  Therefore, allow the file to exist
318 		 * already, even if isRedo is not set.  (See also mdopen)
319 		 */
320 		if (isRedo || IsBootstrapProcessingMode())
321 			fd = PathNameOpenFile(path, O_RDWR | PG_BINARY, 0600);
322 		if (fd < 0)
323 		{
324 			/* be sure to report the error reported by create, not open */
325 			errno = save_errno;
326 			ereport(ERROR,
327 					(errcode_for_file_access(),
328 					 errmsg("could not create file \"%s\": %m", path)));
329 		}
330 	}
331 
332 	pfree(path);
333 
334 	reln->md_fd[forkNum] = _fdvec_alloc();
335 
336 	reln->md_fd[forkNum]->mdfd_vfd = fd;
337 	reln->md_fd[forkNum]->mdfd_segno = 0;
338 	reln->md_fd[forkNum]->mdfd_chain = NULL;
339 }
340 
341 /*
342  *	mdunlink() -- Unlink a relation.
343  *
344  * Note that we're passed a RelFileNodeBackend --- by the time this is called,
345  * there won't be an SMgrRelation hashtable entry anymore.
346  *
347  * forkNum can be a fork number to delete a specific fork, or InvalidForkNumber
348  * to delete all forks.
349  *
350  * For regular relations, we don't unlink the first segment file of the rel,
351  * but just truncate it to zero length, and record a request to unlink it after
352  * the next checkpoint.  Additional segments can be unlinked immediately,
353  * however.  Leaving the empty file in place prevents that relfilenode
354  * number from being reused.  The scenario this protects us from is:
355  * 1. We delete a relation (and commit, and actually remove its file).
356  * 2. We create a new relation, which by chance gets the same relfilenode as
357  *	  the just-deleted one (OIDs must've wrapped around for that to happen).
358  * 3. We crash before another checkpoint occurs.
359  * During replay, we would delete the file and then recreate it, which is fine
360  * if the contents of the file were repopulated by subsequent WAL entries.
361  * But if we didn't WAL-log insertions, but instead relied on fsyncing the
362  * file after populating it (as for instance CLUSTER and CREATE INDEX do),
363  * the contents of the file would be lost forever.  By leaving the empty file
364  * until after the next checkpoint, we prevent reassignment of the relfilenode
365  * number until it's safe, because relfilenode assignment skips over any
366  * existing file.
367  *
368  * We do not need to go through this dance for temp relations, though, because
369  * we never make WAL entries for temp rels, and so a temp rel poses no threat
370  * to the health of a regular rel that has taken over its relfilenode number.
371  * The fact that temp rels and regular rels have different file naming
372  * patterns provides additional safety.
373  *
374  * All the above applies only to the relation's main fork; other forks can
375  * just be removed immediately, since they are not needed to prevent the
376  * relfilenode number from being recycled.  Also, we do not carefully
377  * track whether other forks have been created or not, but just attempt to
378  * unlink them unconditionally; so we should never complain about ENOENT.
379  *
380  * If isRedo is true, it's unsurprising for the relation to be already gone.
381  * Also, we should remove the file immediately instead of queuing a request
382  * for later, since during redo there's no possibility of creating a
383  * conflicting relation.
384  *
385  * Note: any failure should be reported as WARNING not ERROR, because
386  * we are usually not in a transaction anymore when this is called.
387  */
388 void
mdunlink(RelFileNodeBackend rnode,ForkNumber forkNum,bool isRedo)389 mdunlink(RelFileNodeBackend rnode, ForkNumber forkNum, bool isRedo)
390 {
391 	/*
392 	 * We have to clean out any pending fsync requests for the doomed
393 	 * relation, else the next mdsync() will fail.  There can't be any such
394 	 * requests for a temp relation, though.  We can send just one request
395 	 * even when deleting multiple forks, since the fsync queuing code accepts
396 	 * the "InvalidForkNumber = all forks" convention.
397 	 */
398 	if (!RelFileNodeBackendIsTemp(rnode))
399 		ForgetRelationFsyncRequests(rnode.node, forkNum);
400 
401 	/* Now do the per-fork work */
402 	if (forkNum == InvalidForkNumber)
403 	{
404 		for (forkNum = 0; forkNum <= MAX_FORKNUM; forkNum++)
405 			mdunlinkfork(rnode, forkNum, isRedo);
406 	}
407 	else
408 		mdunlinkfork(rnode, forkNum, isRedo);
409 }
410 
411 /*
412  * Truncate a file to release disk space.
413  */
414 static int
do_truncate(char * path)415 do_truncate(char *path)
416 {
417 	int			save_errno;
418 	int			ret;
419 	int			fd;
420 
421 	/* truncate(2) would be easier here, but Windows hasn't got it */
422 	fd = OpenTransientFile(path, O_RDWR | PG_BINARY, 0);
423 	if (fd >= 0)
424 	{
425 		ret = ftruncate(fd, 0);
426 		save_errno = errno;
427 		CloseTransientFile(fd);
428 		errno = save_errno;
429 	}
430 	else
431 		ret = -1;
432 
433 	/* Log a warning here to avoid repetition in callers. */
434 	if (ret < 0 && errno != ENOENT)
435 	{
436 		save_errno = errno;
437 		ereport(WARNING,
438 				(errcode_for_file_access(),
439 				 errmsg("could not truncate file \"%s\": %m", path)));
440 		errno = save_errno;
441 	}
442 
443 	return ret;
444 }
445 
446 static void
mdunlinkfork(RelFileNodeBackend rnode,ForkNumber forkNum,bool isRedo)447 mdunlinkfork(RelFileNodeBackend rnode, ForkNumber forkNum, bool isRedo)
448 {
449 	char	   *path;
450 	int			ret;
451 
452 	path = relpath(rnode, forkNum);
453 
454 	/*
455 	 * Delete or truncate the first segment.
456 	 */
457 	if (isRedo || forkNum != MAIN_FORKNUM || RelFileNodeBackendIsTemp(rnode))
458 	{
459 		if (!RelFileNodeBackendIsTemp(rnode))
460 		{
461 			/* Prevent other backends' fds from holding on to the disk space */
462 			ret = do_truncate(path);
463 		}
464 		else
465 			ret = 0;
466 
467 		/* Next unlink the file, unless it was already found to be missing */
468 		if (ret == 0 || errno != ENOENT)
469 		{
470 			ret = unlink(path);
471 			if (ret < 0 && errno != ENOENT)
472 				ereport(WARNING,
473 						(errcode_for_file_access(),
474 						 errmsg("could not remove file \"%s\": %m", path)));
475 		}
476 	}
477 	else
478 	{
479 		/* Prevent other backends' fds from holding on to the disk space */
480 		ret = do_truncate(path);
481 
482 		/* Register request to unlink first segment later */
483 		register_unlink(rnode);
484 	}
485 
486 	/*
487 	 * Delete any additional segments.
488 	 */
489 	if (ret >= 0)
490 	{
491 		char	   *segpath = (char *) palloc(strlen(path) + 12);
492 		BlockNumber segno;
493 
494 		/*
495 		 * Note that because we loop until getting ENOENT, we will correctly
496 		 * remove all inactive segments as well as active ones.
497 		 */
498 		for (segno = 1;; segno++)
499 		{
500 			sprintf(segpath, "%s.%u", path, segno);
501 
502 			if (!RelFileNodeBackendIsTemp(rnode))
503 			{
504 				/*
505 				 * Prevent other backends' fds from holding on to the disk
506 				 * space.
507 				 */
508 				if (do_truncate(segpath) < 0 && errno == ENOENT)
509 					break;
510 			}
511 
512 			if (unlink(segpath) < 0)
513 			{
514 				/* ENOENT is expected after the last segment... */
515 				if (errno != ENOENT)
516 					ereport(WARNING,
517 							(errcode_for_file_access(),
518 					   errmsg("could not remove file \"%s\": %m", segpath)));
519 				break;
520 			}
521 		}
522 		pfree(segpath);
523 	}
524 
525 	pfree(path);
526 }
527 
528 /*
529  *	mdextend() -- Add a block to the specified relation.
530  *
531  *		The semantics are nearly the same as mdwrite(): write at the
532  *		specified position.  However, this is to be used for the case of
533  *		extending a relation (i.e., blocknum is at or beyond the current
534  *		EOF).  Note that we assume writing a block beyond current EOF
535  *		causes intervening file space to become filled with zeroes.
536  */
537 void
mdextend(SMgrRelation reln,ForkNumber forknum,BlockNumber blocknum,char * buffer,bool skipFsync)538 mdextend(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum,
539 		 char *buffer, bool skipFsync)
540 {
541 	off_t		seekpos;
542 	int			nbytes;
543 	MdfdVec    *v;
544 
545 	/* This assert is too expensive to have on normally ... */
546 #ifdef CHECK_WRITE_VS_EXTEND
547 	Assert(blocknum >= mdnblocks(reln, forknum));
548 #endif
549 
550 	/*
551 	 * If a relation manages to grow to 2^32-1 blocks, refuse to extend it any
552 	 * more --- we mustn't create a block whose number actually is
553 	 * InvalidBlockNumber.  (Note that this failure should be unreachable
554 	 * because of upstream checks in bufmgr.c.)
555 	 */
556 	if (blocknum == InvalidBlockNumber)
557 		ereport(ERROR,
558 				(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
559 				 errmsg("cannot extend file \"%s\" beyond %u blocks",
560 						relpath(reln->smgr_rnode, forknum),
561 						InvalidBlockNumber)));
562 
563 	v = _mdfd_getseg(reln, forknum, blocknum, skipFsync, EXTENSION_CREATE);
564 
565 	seekpos = (off_t) BLCKSZ *(blocknum % ((BlockNumber) RELSEG_SIZE));
566 
567 	Assert(seekpos < (off_t) BLCKSZ * RELSEG_SIZE);
568 
569 	/*
570 	 * Note: because caller usually obtained blocknum by calling mdnblocks,
571 	 * which did a seek(SEEK_END), this seek is often redundant and will be
572 	 * optimized away by fd.c.  It's not redundant, however, if there is a
573 	 * partial page at the end of the file. In that case we want to try to
574 	 * overwrite the partial page with a full page.  It's also not redundant
575 	 * if bufmgr.c had to dump another buffer of the same file to make room
576 	 * for the new page's buffer.
577 	 */
578 	if (FileSeek(v->mdfd_vfd, seekpos, SEEK_SET) != seekpos)
579 		ereport(ERROR,
580 				(errcode_for_file_access(),
581 				 errmsg("could not seek to block %u in file \"%s\": %m",
582 						blocknum, FilePathName(v->mdfd_vfd))));
583 
584 	if ((nbytes = FileWrite(v->mdfd_vfd, buffer, BLCKSZ)) != BLCKSZ)
585 	{
586 		if (nbytes < 0)
587 			ereport(ERROR,
588 					(errcode_for_file_access(),
589 					 errmsg("could not extend file \"%s\": %m",
590 							FilePathName(v->mdfd_vfd)),
591 					 errhint("Check free disk space.")));
592 		/* short write: complain appropriately */
593 		ereport(ERROR,
594 				(errcode(ERRCODE_DISK_FULL),
595 				 errmsg("could not extend file \"%s\": wrote only %d of %d bytes at block %u",
596 						FilePathName(v->mdfd_vfd),
597 						nbytes, BLCKSZ, blocknum),
598 				 errhint("Check free disk space.")));
599 	}
600 
601 	if (!skipFsync && !SmgrIsTemp(reln))
602 		register_dirty_segment(reln, forknum, v);
603 
604 	Assert(_mdnblocks(reln, forknum, v) <= ((BlockNumber) RELSEG_SIZE));
605 }
606 
607 /*
608  *	mdopen() -- Open the specified relation.
609  *
610  * Note we only open the first segment, when there are multiple segments.
611  *
612  * If first segment is not present, either ereport or return NULL according
613  * to "behavior".  We treat EXTENSION_CREATE the same as EXTENSION_FAIL;
614  * EXTENSION_CREATE means it's OK to extend an existing relation, not to
615  * invent one out of whole cloth.
616  */
617 static MdfdVec *
mdopen(SMgrRelation reln,ForkNumber forknum,int behavior)618 mdopen(SMgrRelation reln, ForkNumber forknum, int behavior)
619 {
620 	MdfdVec    *mdfd;
621 	char	   *path;
622 	File		fd;
623 
624 	/* No work if already open */
625 	if (reln->md_fd[forknum])
626 		return reln->md_fd[forknum];
627 
628 	path = relpath(reln->smgr_rnode, forknum);
629 
630 	fd = PathNameOpenFile(path, O_RDWR | PG_BINARY, 0600);
631 
632 	if (fd < 0)
633 	{
634 		/*
635 		 * During bootstrap, there are cases where a system relation will be
636 		 * accessed (by internal backend processes) before the bootstrap
637 		 * script nominally creates it.  Therefore, accept mdopen() as a
638 		 * substitute for mdcreate() in bootstrap mode only. (See mdcreate)
639 		 */
640 		if (IsBootstrapProcessingMode())
641 			fd = PathNameOpenFile(path, O_RDWR | O_CREAT | O_EXCL | PG_BINARY, 0600);
642 		if (fd < 0)
643 		{
644 			if ((behavior & EXTENSION_RETURN_NULL) &&
645 				FILE_POSSIBLY_DELETED(errno))
646 			{
647 				pfree(path);
648 				return NULL;
649 			}
650 			ereport(ERROR,
651 					(errcode_for_file_access(),
652 					 errmsg("could not open file \"%s\": %m", path)));
653 		}
654 	}
655 
656 	pfree(path);
657 
658 	reln->md_fd[forknum] = mdfd = _fdvec_alloc();
659 
660 	mdfd->mdfd_vfd = fd;
661 	mdfd->mdfd_segno = 0;
662 	mdfd->mdfd_chain = NULL;
663 	Assert(_mdnblocks(reln, forknum, mdfd) <= ((BlockNumber) RELSEG_SIZE));
664 
665 	return mdfd;
666 }
667 
668 /*
669  *	mdclose() -- Close the specified relation, if it isn't closed already.
670  */
671 void
mdclose(SMgrRelation reln,ForkNumber forknum)672 mdclose(SMgrRelation reln, ForkNumber forknum)
673 {
674 	MdfdVec    *v = reln->md_fd[forknum];
675 
676 	/* No work if already closed */
677 	if (v == NULL)
678 		return;
679 
680 	reln->md_fd[forknum] = NULL;	/* prevent dangling pointer after error */
681 
682 	while (v != NULL)
683 	{
684 		MdfdVec    *ov = v;
685 
686 		/* if not closed already */
687 		if (v->mdfd_vfd >= 0)
688 			FileClose(v->mdfd_vfd);
689 		/* Now free vector */
690 		v = v->mdfd_chain;
691 		pfree(ov);
692 	}
693 }
694 
695 /*
696  *	mdprefetch() -- Initiate asynchronous read of the specified block of a relation
697  */
698 void
mdprefetch(SMgrRelation reln,ForkNumber forknum,BlockNumber blocknum)699 mdprefetch(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum)
700 {
701 #ifdef USE_PREFETCH
702 	off_t		seekpos;
703 	MdfdVec    *v;
704 
705 	v = _mdfd_getseg(reln, forknum, blocknum, false, EXTENSION_FAIL);
706 
707 	seekpos = (off_t) BLCKSZ *(blocknum % ((BlockNumber) RELSEG_SIZE));
708 
709 	Assert(seekpos < (off_t) BLCKSZ * RELSEG_SIZE);
710 
711 	(void) FilePrefetch(v->mdfd_vfd, seekpos, BLCKSZ);
712 #endif   /* USE_PREFETCH */
713 }
714 
715 /*
716  * mdwriteback() -- Tell the kernel to write pages back to storage.
717  *
718  * This accepts a range of blocks because flushing several pages at once is
719  * considerably more efficient than doing so individually.
720  */
721 void
mdwriteback(SMgrRelation reln,ForkNumber forknum,BlockNumber blocknum,BlockNumber nblocks)722 mdwriteback(SMgrRelation reln, ForkNumber forknum,
723 			BlockNumber blocknum, BlockNumber nblocks)
724 {
725 	/*
726 	 * Issue flush requests in as few requests as possible; have to split at
727 	 * segment boundaries though, since those are actually separate files.
728 	 */
729 	while (nblocks > 0)
730 	{
731 		BlockNumber nflush = nblocks;
732 		off_t		seekpos;
733 		MdfdVec    *v;
734 		int			segnum_start,
735 					segnum_end;
736 
737 		v = _mdfd_getseg(reln, forknum, blocknum, true /* not used */ ,
738 						 EXTENSION_RETURN_NULL);
739 
740 		/*
741 		 * We might be flushing buffers of already removed relations, that's
742 		 * ok, just ignore that case.
743 		 */
744 		if (!v)
745 			return;
746 
747 		/* compute offset inside the current segment */
748 		segnum_start = blocknum / RELSEG_SIZE;
749 
750 		/* compute number of desired writes within the current segment */
751 		segnum_end = (blocknum + nblocks - 1) / RELSEG_SIZE;
752 		if (segnum_start != segnum_end)
753 			nflush = RELSEG_SIZE - (blocknum % ((BlockNumber) RELSEG_SIZE));
754 
755 		Assert(nflush >= 1);
756 		Assert(nflush <= nblocks);
757 
758 		seekpos = (off_t) BLCKSZ *(blocknum % ((BlockNumber) RELSEG_SIZE));
759 
760 		FileWriteback(v->mdfd_vfd, seekpos, (off_t) BLCKSZ * nflush);
761 
762 		nblocks -= nflush;
763 		blocknum += nflush;
764 	}
765 }
766 
767 /*
768  *	mdread() -- Read the specified block from a relation.
769  */
770 void
mdread(SMgrRelation reln,ForkNumber forknum,BlockNumber blocknum,char * buffer)771 mdread(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum,
772 	   char *buffer)
773 {
774 	off_t		seekpos;
775 	int			nbytes;
776 	MdfdVec    *v;
777 
778 	TRACE_POSTGRESQL_SMGR_MD_READ_START(forknum, blocknum,
779 										reln->smgr_rnode.node.spcNode,
780 										reln->smgr_rnode.node.dbNode,
781 										reln->smgr_rnode.node.relNode,
782 										reln->smgr_rnode.backend);
783 
784 	v = _mdfd_getseg(reln, forknum, blocknum, false,
785 					 EXTENSION_FAIL | EXTENSION_CREATE_RECOVERY);
786 
787 	seekpos = (off_t) BLCKSZ *(blocknum % ((BlockNumber) RELSEG_SIZE));
788 
789 	Assert(seekpos < (off_t) BLCKSZ * RELSEG_SIZE);
790 
791 	if (FileSeek(v->mdfd_vfd, seekpos, SEEK_SET) != seekpos)
792 		ereport(ERROR,
793 				(errcode_for_file_access(),
794 				 errmsg("could not seek to block %u in file \"%s\": %m",
795 						blocknum, FilePathName(v->mdfd_vfd))));
796 
797 	nbytes = FileRead(v->mdfd_vfd, buffer, BLCKSZ);
798 
799 	TRACE_POSTGRESQL_SMGR_MD_READ_DONE(forknum, blocknum,
800 									   reln->smgr_rnode.node.spcNode,
801 									   reln->smgr_rnode.node.dbNode,
802 									   reln->smgr_rnode.node.relNode,
803 									   reln->smgr_rnode.backend,
804 									   nbytes,
805 									   BLCKSZ);
806 
807 	if (nbytes != BLCKSZ)
808 	{
809 		if (nbytes < 0)
810 			ereport(ERROR,
811 					(errcode_for_file_access(),
812 					 errmsg("could not read block %u in file \"%s\": %m",
813 							blocknum, FilePathName(v->mdfd_vfd))));
814 
815 		/*
816 		 * Short read: we are at or past EOF, or we read a partial block at
817 		 * EOF.  Normally this is an error; upper levels should never try to
818 		 * read a nonexistent block.  However, if zero_damaged_pages is ON or
819 		 * we are InRecovery, we should instead return zeroes without
820 		 * complaining.  This allows, for example, the case of trying to
821 		 * update a block that was later truncated away.
822 		 */
823 		if (zero_damaged_pages || InRecovery)
824 			MemSet(buffer, 0, BLCKSZ);
825 		else
826 			ereport(ERROR,
827 					(errcode(ERRCODE_DATA_CORRUPTED),
828 					 errmsg("could not read block %u in file \"%s\": read only %d of %d bytes",
829 							blocknum, FilePathName(v->mdfd_vfd),
830 							nbytes, BLCKSZ)));
831 	}
832 }
833 
834 /*
835  *	mdwrite() -- Write the supplied block at the appropriate location.
836  *
837  *		This is to be used only for updating already-existing blocks of a
838  *		relation (ie, those before the current EOF).  To extend a relation,
839  *		use mdextend().
840  */
841 void
mdwrite(SMgrRelation reln,ForkNumber forknum,BlockNumber blocknum,char * buffer,bool skipFsync)842 mdwrite(SMgrRelation reln, ForkNumber forknum, BlockNumber blocknum,
843 		char *buffer, bool skipFsync)
844 {
845 	off_t		seekpos;
846 	int			nbytes;
847 	MdfdVec    *v;
848 
849 	/* This assert is too expensive to have on normally ... */
850 #ifdef CHECK_WRITE_VS_EXTEND
851 	Assert(blocknum < mdnblocks(reln, forknum));
852 #endif
853 
854 	TRACE_POSTGRESQL_SMGR_MD_WRITE_START(forknum, blocknum,
855 										 reln->smgr_rnode.node.spcNode,
856 										 reln->smgr_rnode.node.dbNode,
857 										 reln->smgr_rnode.node.relNode,
858 										 reln->smgr_rnode.backend);
859 
860 	v = _mdfd_getseg(reln, forknum, blocknum, skipFsync,
861 					 EXTENSION_FAIL | EXTENSION_CREATE_RECOVERY);
862 
863 	seekpos = (off_t) BLCKSZ *(blocknum % ((BlockNumber) RELSEG_SIZE));
864 
865 	Assert(seekpos < (off_t) BLCKSZ * RELSEG_SIZE);
866 
867 	if (FileSeek(v->mdfd_vfd, seekpos, SEEK_SET) != seekpos)
868 		ereport(ERROR,
869 				(errcode_for_file_access(),
870 				 errmsg("could not seek to block %u in file \"%s\": %m",
871 						blocknum, FilePathName(v->mdfd_vfd))));
872 
873 	nbytes = FileWrite(v->mdfd_vfd, buffer, BLCKSZ);
874 
875 	TRACE_POSTGRESQL_SMGR_MD_WRITE_DONE(forknum, blocknum,
876 										reln->smgr_rnode.node.spcNode,
877 										reln->smgr_rnode.node.dbNode,
878 										reln->smgr_rnode.node.relNode,
879 										reln->smgr_rnode.backend,
880 										nbytes,
881 										BLCKSZ);
882 
883 	if (nbytes != BLCKSZ)
884 	{
885 		if (nbytes < 0)
886 			ereport(ERROR,
887 					(errcode_for_file_access(),
888 					 errmsg("could not write block %u in file \"%s\": %m",
889 							blocknum, FilePathName(v->mdfd_vfd))));
890 		/* short write: complain appropriately */
891 		ereport(ERROR,
892 				(errcode(ERRCODE_DISK_FULL),
893 				 errmsg("could not write block %u in file \"%s\": wrote only %d of %d bytes",
894 						blocknum,
895 						FilePathName(v->mdfd_vfd),
896 						nbytes, BLCKSZ),
897 				 errhint("Check free disk space.")));
898 	}
899 
900 	if (!skipFsync && !SmgrIsTemp(reln))
901 		register_dirty_segment(reln, forknum, v);
902 }
903 
904 /*
905  *	mdnblocks() -- Get the number of blocks stored in a relation.
906  *
907  *		Important side effect: all active segments of the relation are opened
908  *		and added to the mdfd_chain list.  If this routine has not been
909  *		called, then only segments up to the last one actually touched
910  *		are present in the chain.
911  */
912 BlockNumber
mdnblocks(SMgrRelation reln,ForkNumber forknum)913 mdnblocks(SMgrRelation reln, ForkNumber forknum)
914 {
915 	MdfdVec    *v = mdopen(reln, forknum, EXTENSION_FAIL);
916 	BlockNumber nblocks;
917 	BlockNumber segno = 0;
918 
919 	/*
920 	 * Skip through any segments that aren't the last one, to avoid redundant
921 	 * seeks on them.  We have previously verified that these segments are
922 	 * exactly RELSEG_SIZE long, and it's useless to recheck that each time.
923 	 *
924 	 * NOTE: this assumption could only be wrong if another backend has
925 	 * truncated the relation.  We rely on higher code levels to handle that
926 	 * scenario by closing and re-opening the md fd, which is handled via
927 	 * relcache flush.  (Since the checkpointer doesn't participate in
928 	 * relcache flush, it could have segment chain entries for inactive
929 	 * segments; that's OK because the checkpointer never needs to compute
930 	 * relation size.)
931 	 */
932 	while (v->mdfd_chain != NULL)
933 	{
934 		segno++;
935 		v = v->mdfd_chain;
936 	}
937 
938 	for (;;)
939 	{
940 		nblocks = _mdnblocks(reln, forknum, v);
941 		if (nblocks > ((BlockNumber) RELSEG_SIZE))
942 			elog(FATAL, "segment too big");
943 		if (nblocks < ((BlockNumber) RELSEG_SIZE))
944 			return (segno * ((BlockNumber) RELSEG_SIZE)) + nblocks;
945 
946 		/*
947 		 * If segment is exactly RELSEG_SIZE, advance to next one.
948 		 */
949 		segno++;
950 
951 		if (v->mdfd_chain == NULL)
952 		{
953 			/*
954 			 * We used to pass O_CREAT here, but that's has the disadvantage
955 			 * that it might create a segment which has vanished through some
956 			 * operating system misadventure.  In such a case, creating the
957 			 * segment here undermines _mdfd_getseg's attempts to notice and
958 			 * report an error upon access to a missing segment.
959 			 */
960 			v->mdfd_chain = _mdfd_openseg(reln, forknum, segno, 0);
961 			if (v->mdfd_chain == NULL)
962 				return segno * ((BlockNumber) RELSEG_SIZE);
963 		}
964 
965 		v = v->mdfd_chain;
966 	}
967 }
968 
969 /*
970  *	mdtruncate() -- Truncate relation to specified number of blocks.
971  */
972 void
mdtruncate(SMgrRelation reln,ForkNumber forknum,BlockNumber nblocks)973 mdtruncate(SMgrRelation reln, ForkNumber forknum, BlockNumber nblocks)
974 {
975 	MdfdVec    *v;
976 	BlockNumber curnblk;
977 	BlockNumber priorblocks;
978 
979 	/*
980 	 * NOTE: mdnblocks makes sure we have opened all active segments, so that
981 	 * truncation loop will get them all!
982 	 */
983 	curnblk = mdnblocks(reln, forknum);
984 	if (nblocks > curnblk)
985 	{
986 		/* Bogus request ... but no complaint if InRecovery */
987 		if (InRecovery)
988 			return;
989 		ereport(ERROR,
990 				(errmsg("could not truncate file \"%s\" to %u blocks: it's only %u blocks now",
991 						relpath(reln->smgr_rnode, forknum),
992 						nblocks, curnblk)));
993 	}
994 	if (nblocks == curnblk)
995 		return;					/* no work */
996 
997 	v = mdopen(reln, forknum, EXTENSION_FAIL);
998 
999 	priorblocks = 0;
1000 	while (v != NULL)
1001 	{
1002 		MdfdVec    *ov = v;
1003 
1004 		if (priorblocks > nblocks)
1005 		{
1006 			/*
1007 			 * This segment is no longer active (and has already been unlinked
1008 			 * from the mdfd_chain). We truncate the file, but do not delete
1009 			 * it, for reasons explained in the header comments.
1010 			 */
1011 			if (FileTruncate(v->mdfd_vfd, 0) < 0)
1012 				ereport(ERROR,
1013 						(errcode_for_file_access(),
1014 						 errmsg("could not truncate file \"%s\": %m",
1015 								FilePathName(v->mdfd_vfd))));
1016 
1017 			if (!SmgrIsTemp(reln))
1018 				register_dirty_segment(reln, forknum, v);
1019 			v = v->mdfd_chain;
1020 			Assert(ov != reln->md_fd[forknum]); /* we never drop the 1st
1021 												 * segment */
1022 			FileClose(ov->mdfd_vfd);
1023 			pfree(ov);
1024 		}
1025 		else if (priorblocks + ((BlockNumber) RELSEG_SIZE) > nblocks)
1026 		{
1027 			/*
1028 			 * This is the last segment we want to keep. Truncate the file to
1029 			 * the right length, and clear chain link that points to any
1030 			 * remaining segments (which we shall zap). NOTE: if nblocks is
1031 			 * exactly a multiple K of RELSEG_SIZE, we will truncate the K+1st
1032 			 * segment to 0 length but keep it. This adheres to the invariant
1033 			 * given in the header comments.
1034 			 */
1035 			BlockNumber lastsegblocks = nblocks - priorblocks;
1036 
1037 			if (FileTruncate(v->mdfd_vfd, (off_t) lastsegblocks * BLCKSZ) < 0)
1038 				ereport(ERROR,
1039 						(errcode_for_file_access(),
1040 					errmsg("could not truncate file \"%s\" to %u blocks: %m",
1041 						   FilePathName(v->mdfd_vfd),
1042 						   nblocks)));
1043 			if (!SmgrIsTemp(reln))
1044 				register_dirty_segment(reln, forknum, v);
1045 			v = v->mdfd_chain;
1046 			ov->mdfd_chain = NULL;
1047 		}
1048 		else
1049 		{
1050 			/*
1051 			 * We still need this segment and 0 or more blocks beyond it, so
1052 			 * nothing to do here.
1053 			 */
1054 			v = v->mdfd_chain;
1055 		}
1056 		priorblocks += RELSEG_SIZE;
1057 	}
1058 }
1059 
1060 /*
1061  *	mdimmedsync() -- Immediately sync a relation to stable storage.
1062  *
1063  * Note that only writes already issued are synced; this routine knows
1064  * nothing of dirty buffers that may exist inside the buffer manager.
1065  */
1066 void
mdimmedsync(SMgrRelation reln,ForkNumber forknum)1067 mdimmedsync(SMgrRelation reln, ForkNumber forknum)
1068 {
1069 	MdfdVec    *v;
1070 
1071 	/*
1072 	 * NOTE: mdnblocks makes sure we have opened all active segments, so that
1073 	 * fsync loop will get them all!
1074 	 */
1075 	mdnblocks(reln, forknum);
1076 
1077 	v = mdopen(reln, forknum, EXTENSION_FAIL);
1078 
1079 	while (v != NULL)
1080 	{
1081 		if (FileSync(v->mdfd_vfd) < 0)
1082 			ereport(data_sync_elevel(ERROR),
1083 					(errcode_for_file_access(),
1084 					 errmsg("could not fsync file \"%s\": %m",
1085 							FilePathName(v->mdfd_vfd))));
1086 		v = v->mdfd_chain;
1087 	}
1088 }
1089 
1090 /*
1091  *	mdsync() -- Sync previous writes to stable storage.
1092  */
1093 void
mdsync(void)1094 mdsync(void)
1095 {
1096 	static bool mdsync_in_progress = false;
1097 
1098 	HASH_SEQ_STATUS hstat;
1099 	PendingOperationEntry *entry;
1100 	int			absorb_counter;
1101 
1102 	/* Statistics on sync times */
1103 	int			processed = 0;
1104 	instr_time	sync_start,
1105 				sync_end,
1106 				sync_diff;
1107 	uint64		elapsed;
1108 	uint64		longest = 0;
1109 	uint64		total_elapsed = 0;
1110 
1111 	/*
1112 	 * This is only called during checkpoints, and checkpoints should only
1113 	 * occur in processes that have created a pendingOpsTable.
1114 	 */
1115 	if (!pendingOpsTable)
1116 		elog(ERROR, "cannot sync without a pendingOpsTable");
1117 
1118 	/*
1119 	 * If we are in the checkpointer, the sync had better include all fsync
1120 	 * requests that were queued by backends up to this point.  The tightest
1121 	 * race condition that could occur is that a buffer that must be written
1122 	 * and fsync'd for the checkpoint could have been dumped by a backend just
1123 	 * before it was visited by BufferSync().  We know the backend will have
1124 	 * queued an fsync request before clearing the buffer's dirtybit, so we
1125 	 * are safe as long as we do an Absorb after completing BufferSync().
1126 	 */
1127 	AbsorbFsyncRequests();
1128 
1129 	/*
1130 	 * To avoid excess fsync'ing (in the worst case, maybe a never-terminating
1131 	 * checkpoint), we want to ignore fsync requests that are entered into the
1132 	 * hashtable after this point --- they should be processed next time,
1133 	 * instead.  We use mdsync_cycle_ctr to tell old entries apart from new
1134 	 * ones: new ones will have cycle_ctr equal to the incremented value of
1135 	 * mdsync_cycle_ctr.
1136 	 *
1137 	 * In normal circumstances, all entries present in the table at this point
1138 	 * will have cycle_ctr exactly equal to the current (about to be old)
1139 	 * value of mdsync_cycle_ctr.  However, if we fail partway through the
1140 	 * fsync'ing loop, then older values of cycle_ctr might remain when we
1141 	 * come back here to try again.  Repeated checkpoint failures would
1142 	 * eventually wrap the counter around to the point where an old entry
1143 	 * might appear new, causing us to skip it, possibly allowing a checkpoint
1144 	 * to succeed that should not have.  To forestall wraparound, any time the
1145 	 * previous mdsync() failed to complete, run through the table and
1146 	 * forcibly set cycle_ctr = mdsync_cycle_ctr.
1147 	 *
1148 	 * Think not to merge this loop with the main loop, as the problem is
1149 	 * exactly that that loop may fail before having visited all the entries.
1150 	 * From a performance point of view it doesn't matter anyway, as this path
1151 	 * will never be taken in a system that's functioning normally.
1152 	 */
1153 	if (mdsync_in_progress)
1154 	{
1155 		/* prior try failed, so update any stale cycle_ctr values */
1156 		hash_seq_init(&hstat, pendingOpsTable);
1157 		while ((entry = (PendingOperationEntry *) hash_seq_search(&hstat)) != NULL)
1158 		{
1159 			entry->cycle_ctr = mdsync_cycle_ctr;
1160 		}
1161 	}
1162 
1163 	/* Advance counter so that new hashtable entries are distinguishable */
1164 	mdsync_cycle_ctr++;
1165 
1166 	/* Set flag to detect failure if we don't reach the end of the loop */
1167 	mdsync_in_progress = true;
1168 
1169 	/* Now scan the hashtable for fsync requests to process */
1170 	absorb_counter = FSYNCS_PER_ABSORB;
1171 	hash_seq_init(&hstat, pendingOpsTable);
1172 	while ((entry = (PendingOperationEntry *) hash_seq_search(&hstat)) != NULL)
1173 	{
1174 		ForkNumber	forknum;
1175 
1176 		/*
1177 		 * If the entry is new then don't process it this time; it might
1178 		 * contain multiple fsync-request bits, but they are all new.  Note
1179 		 * "continue" bypasses the hash-remove call at the bottom of the loop.
1180 		 */
1181 		if (entry->cycle_ctr == mdsync_cycle_ctr)
1182 			continue;
1183 
1184 		/* Else assert we haven't missed it */
1185 		Assert((CycleCtr) (entry->cycle_ctr + 1) == mdsync_cycle_ctr);
1186 
1187 		/*
1188 		 * Scan over the forks and segments represented by the entry.
1189 		 *
1190 		 * The bitmap manipulations are slightly tricky, because we can call
1191 		 * AbsorbFsyncRequests() inside the loop and that could result in
1192 		 * bms_add_member() modifying and even re-palloc'ing the bitmapsets.
1193 		 * So we detach it, but if we fail we'll merge it with any new
1194 		 * requests that have arrived in the meantime.
1195 		 */
1196 		for (forknum = 0; forknum <= MAX_FORKNUM; forknum++)
1197 		{
1198 			Bitmapset  *requests = entry->requests[forknum];
1199 			int			segno;
1200 
1201 			entry->requests[forknum] = NULL;
1202 			entry->canceled[forknum] = false;
1203 
1204 			segno = -1;
1205 			while ((segno = bms_next_member(requests, segno)) >= 0)
1206 			{
1207 				int			failures;
1208 
1209 				/*
1210 				 * If fsync is off then we don't have to bother opening the
1211 				 * file at all.  (We delay checking until this point so that
1212 				 * changing fsync on the fly behaves sensibly.)
1213 				 */
1214 				if (!enableFsync)
1215 					continue;
1216 
1217 				/*
1218 				 * If in checkpointer, we want to absorb pending requests
1219 				 * every so often to prevent overflow of the fsync request
1220 				 * queue.  It is unspecified whether newly-added entries will
1221 				 * be visited by hash_seq_search, but we don't care since we
1222 				 * don't need to process them anyway.
1223 				 */
1224 				if (--absorb_counter <= 0)
1225 				{
1226 					AbsorbFsyncRequests();
1227 					absorb_counter = FSYNCS_PER_ABSORB;
1228 				}
1229 
1230 				/*
1231 				 * The fsync table could contain requests to fsync segments
1232 				 * that have been deleted (unlinked) by the time we get to
1233 				 * them. Rather than just hoping an ENOENT (or EACCES on
1234 				 * Windows) error can be ignored, what we do on error is
1235 				 * absorb pending requests and then retry.  Since mdunlink()
1236 				 * queues a "cancel" message before actually unlinking, the
1237 				 * fsync request is guaranteed to be marked canceled after the
1238 				 * absorb if it really was this case. DROP DATABASE likewise
1239 				 * has to tell us to forget fsync requests before it starts
1240 				 * deletions.
1241 				 */
1242 				for (failures = 0;; failures++) /* loop exits at "break" */
1243 				{
1244 					SMgrRelation reln;
1245 					MdfdVec    *seg;
1246 					char	   *path;
1247 					int			save_errno;
1248 
1249 					/*
1250 					 * Find or create an smgr hash entry for this relation.
1251 					 * This may seem a bit unclean -- md calling smgr?	But
1252 					 * it's really the best solution.  It ensures that the
1253 					 * open file reference isn't permanently leaked if we get
1254 					 * an error here. (You may say "but an unreferenced
1255 					 * SMgrRelation is still a leak!" Not really, because the
1256 					 * only case in which a checkpoint is done by a process
1257 					 * that isn't about to shut down is in the checkpointer,
1258 					 * and it will periodically do smgrcloseall(). This fact
1259 					 * justifies our not closing the reln in the success path
1260 					 * either, which is a good thing since in non-checkpointer
1261 					 * cases we couldn't safely do that.)
1262 					 */
1263 					reln = smgropen(entry->rnode, InvalidBackendId);
1264 
1265 					/* Attempt to open and fsync the target segment */
1266 					seg = _mdfd_getseg(reln, forknum,
1267 							 (BlockNumber) segno * (BlockNumber) RELSEG_SIZE,
1268 									   false,
1269 									   EXTENSION_RETURN_NULL
1270 									   | EXTENSION_DONT_CHECK_SIZE);
1271 
1272 					INSTR_TIME_SET_CURRENT(sync_start);
1273 
1274 					if (seg != NULL &&
1275 						FileSync(seg->mdfd_vfd) >= 0)
1276 					{
1277 						/* Success; update statistics about sync timing */
1278 						INSTR_TIME_SET_CURRENT(sync_end);
1279 						sync_diff = sync_end;
1280 						INSTR_TIME_SUBTRACT(sync_diff, sync_start);
1281 						elapsed = INSTR_TIME_GET_MICROSEC(sync_diff);
1282 						if (elapsed > longest)
1283 							longest = elapsed;
1284 						total_elapsed += elapsed;
1285 						processed++;
1286 						requests = bms_del_member(requests, segno);
1287 						if (log_checkpoints)
1288 							elog(DEBUG1, "checkpoint sync: number=%d file=%s time=%.3f msec",
1289 								 processed,
1290 								 FilePathName(seg->mdfd_vfd),
1291 								 (double) elapsed / 1000);
1292 
1293 						break;	/* out of retry loop */
1294 					}
1295 
1296 					/* Compute file name for use in message */
1297 					save_errno = errno;
1298 					path = _mdfd_segpath(reln, forknum, (BlockNumber) segno);
1299 					errno = save_errno;
1300 
1301 					/*
1302 					 * It is possible that the relation has been dropped or
1303 					 * truncated since the fsync request was entered.
1304 					 * Therefore, allow ENOENT, but only if we didn't fail
1305 					 * already on this file.  This applies both for
1306 					 * _mdfd_getseg() and for FileSync, since fd.c might have
1307 					 * closed the file behind our back.
1308 					 *
1309 					 * XXX is there any point in allowing more than one retry?
1310 					 * Don't see one at the moment, but easy to change the
1311 					 * test here if so.
1312 					 */
1313 					if (!FILE_POSSIBLY_DELETED(errno) ||
1314 						failures > 0)
1315 					{
1316 						Bitmapset  *new_requests;
1317 
1318 						/*
1319 						 * We need to merge these unsatisfied requests with
1320 						 * any others that have arrived since we started.
1321 						 */
1322 						new_requests = entry->requests[forknum];
1323 						entry->requests[forknum] =
1324 							bms_join(new_requests, requests);
1325 
1326 						errno = save_errno;
1327 						ereport(data_sync_elevel(ERROR),
1328 								(errcode_for_file_access(),
1329 								 errmsg("could not fsync file \"%s\": %m",
1330 										path)));
1331 					}
1332 					else
1333 						ereport(DEBUG1,
1334 								(errcode_for_file_access(),
1335 						errmsg("could not fsync file \"%s\" but retrying: %m",
1336 							   path)));
1337 					pfree(path);
1338 
1339 					/*
1340 					 * Absorb incoming requests and check to see if a cancel
1341 					 * arrived for this relation fork.
1342 					 */
1343 					AbsorbFsyncRequests();
1344 					absorb_counter = FSYNCS_PER_ABSORB; /* might as well... */
1345 
1346 					if (entry->canceled[forknum])
1347 						break;
1348 				}				/* end retry loop */
1349 			}
1350 			bms_free(requests);
1351 		}
1352 
1353 		/*
1354 		 * We've finished everything that was requested before we started to
1355 		 * scan the entry.  If no new requests have been inserted meanwhile,
1356 		 * remove the entry.  Otherwise, update its cycle counter, as all the
1357 		 * requests now in it must have arrived during this cycle.
1358 		 */
1359 		for (forknum = 0; forknum <= MAX_FORKNUM; forknum++)
1360 		{
1361 			if (entry->requests[forknum] != NULL)
1362 				break;
1363 		}
1364 		if (forknum <= MAX_FORKNUM)
1365 			entry->cycle_ctr = mdsync_cycle_ctr;
1366 		else
1367 		{
1368 			/* Okay to remove it */
1369 			if (hash_search(pendingOpsTable, &entry->rnode,
1370 							HASH_REMOVE, NULL) == NULL)
1371 				elog(ERROR, "pendingOpsTable corrupted");
1372 		}
1373 	}							/* end loop over hashtable entries */
1374 
1375 	/* Return sync performance metrics for report at checkpoint end */
1376 	CheckpointStats.ckpt_sync_rels = processed;
1377 	CheckpointStats.ckpt_longest_sync = longest;
1378 	CheckpointStats.ckpt_agg_sync_time = total_elapsed;
1379 
1380 	/* Flag successful completion of mdsync */
1381 	mdsync_in_progress = false;
1382 }
1383 
1384 /*
1385  * mdpreckpt() -- Do pre-checkpoint work
1386  *
1387  * To distinguish unlink requests that arrived before this checkpoint
1388  * started from those that arrived during the checkpoint, we use a cycle
1389  * counter similar to the one we use for fsync requests. That cycle
1390  * counter is incremented here.
1391  *
1392  * This must be called *before* the checkpoint REDO point is determined.
1393  * That ensures that we won't delete files too soon.
1394  *
1395  * Note that we can't do anything here that depends on the assumption
1396  * that the checkpoint will be completed.
1397  */
1398 void
mdpreckpt(void)1399 mdpreckpt(void)
1400 {
1401 	/*
1402 	 * Any unlink requests arriving after this point will be assigned the next
1403 	 * cycle counter, and won't be unlinked until next checkpoint.
1404 	 */
1405 	mdckpt_cycle_ctr++;
1406 }
1407 
1408 /*
1409  * mdpostckpt() -- Do post-checkpoint work
1410  *
1411  * Remove any lingering files that can now be safely removed.
1412  */
1413 void
mdpostckpt(void)1414 mdpostckpt(void)
1415 {
1416 	int			absorb_counter;
1417 
1418 	absorb_counter = UNLINKS_PER_ABSORB;
1419 	while (pendingUnlinks != NIL)
1420 	{
1421 		PendingUnlinkEntry *entry = (PendingUnlinkEntry *) linitial(pendingUnlinks);
1422 		char	   *path;
1423 
1424 		/*
1425 		 * New entries are appended to the end, so if the entry is new we've
1426 		 * reached the end of old entries.
1427 		 *
1428 		 * Note: if just the right number of consecutive checkpoints fail, we
1429 		 * could be fooled here by cycle_ctr wraparound.  However, the only
1430 		 * consequence is that we'd delay unlinking for one more checkpoint,
1431 		 * which is perfectly tolerable.
1432 		 */
1433 		if (entry->cycle_ctr == mdckpt_cycle_ctr)
1434 			break;
1435 
1436 		/* Unlink the file */
1437 		path = relpathperm(entry->rnode, MAIN_FORKNUM);
1438 		if (unlink(path) < 0)
1439 		{
1440 			/*
1441 			 * There's a race condition, when the database is dropped at the
1442 			 * same time that we process the pending unlink requests. If the
1443 			 * DROP DATABASE deletes the file before we do, we will get ENOENT
1444 			 * here. rmtree() also has to ignore ENOENT errors, to deal with
1445 			 * the possibility that we delete the file first.
1446 			 */
1447 			if (errno != ENOENT)
1448 				ereport(WARNING,
1449 						(errcode_for_file_access(),
1450 						 errmsg("could not remove file \"%s\": %m", path)));
1451 		}
1452 		pfree(path);
1453 
1454 		/* And remove the list entry */
1455 		pendingUnlinks = list_delete_first(pendingUnlinks);
1456 		pfree(entry);
1457 
1458 		/*
1459 		 * As in mdsync, we don't want to stop absorbing fsync requests for a
1460 		 * long time when there are many deletions to be done.  We can safely
1461 		 * call AbsorbFsyncRequests() at this point in the loop (note it might
1462 		 * try to delete list entries).
1463 		 */
1464 		if (--absorb_counter <= 0)
1465 		{
1466 			AbsorbFsyncRequests();
1467 			absorb_counter = UNLINKS_PER_ABSORB;
1468 		}
1469 	}
1470 }
1471 
1472 /*
1473  * register_dirty_segment() -- Mark a relation segment as needing fsync
1474  *
1475  * If there is a local pending-ops table, just make an entry in it for
1476  * mdsync to process later.  Otherwise, try to pass off the fsync request
1477  * to the checkpointer process.  If that fails, just do the fsync
1478  * locally before returning (we hope this will not happen often enough
1479  * to be a performance problem).
1480  */
1481 static void
register_dirty_segment(SMgrRelation reln,ForkNumber forknum,MdfdVec * seg)1482 register_dirty_segment(SMgrRelation reln, ForkNumber forknum, MdfdVec *seg)
1483 {
1484 	/* Temp relations should never be fsync'd */
1485 	Assert(!SmgrIsTemp(reln));
1486 
1487 	if (pendingOpsTable)
1488 	{
1489 		/* push it into local pending-ops table */
1490 		RememberFsyncRequest(reln->smgr_rnode.node, forknum, seg->mdfd_segno);
1491 	}
1492 	else
1493 	{
1494 		if (ForwardFsyncRequest(reln->smgr_rnode.node, forknum, seg->mdfd_segno))
1495 			return;				/* passed it off successfully */
1496 
1497 		ereport(DEBUG1,
1498 				(errmsg("could not forward fsync request because request queue is full")));
1499 
1500 		if (FileSync(seg->mdfd_vfd) < 0)
1501 			ereport(data_sync_elevel(ERROR),
1502 					(errcode_for_file_access(),
1503 					 errmsg("could not fsync file \"%s\": %m",
1504 							FilePathName(seg->mdfd_vfd))));
1505 	}
1506 }
1507 
1508 /*
1509  * register_unlink() -- Schedule a file to be deleted after next checkpoint
1510  *
1511  * We don't bother passing in the fork number, because this is only used
1512  * with main forks.
1513  *
1514  * As with register_dirty_segment, this could involve either a local or
1515  * a remote pending-ops table.
1516  */
1517 static void
register_unlink(RelFileNodeBackend rnode)1518 register_unlink(RelFileNodeBackend rnode)
1519 {
1520 	/* Should never be used with temp relations */
1521 	Assert(!RelFileNodeBackendIsTemp(rnode));
1522 
1523 	if (pendingOpsTable)
1524 	{
1525 		/* push it into local pending-ops table */
1526 		RememberFsyncRequest(rnode.node, MAIN_FORKNUM,
1527 							 UNLINK_RELATION_REQUEST);
1528 	}
1529 	else
1530 	{
1531 		/*
1532 		 * Notify the checkpointer about it.  If we fail to queue the request
1533 		 * message, we have to sleep and try again, because we can't simply
1534 		 * delete the file now.  Ugly, but hopefully won't happen often.
1535 		 *
1536 		 * XXX should we just leave the file orphaned instead?
1537 		 */
1538 		Assert(IsUnderPostmaster);
1539 		while (!ForwardFsyncRequest(rnode.node, MAIN_FORKNUM,
1540 									UNLINK_RELATION_REQUEST))
1541 			pg_usleep(10000L);	/* 10 msec seems a good number */
1542 	}
1543 }
1544 
1545 /*
1546  * RememberFsyncRequest() -- callback from checkpointer side of fsync request
1547  *
1548  * We stuff fsync requests into the local hash table for execution
1549  * during the checkpointer's next checkpoint.  UNLINK requests go into a
1550  * separate linked list, however, because they get processed separately.
1551  *
1552  * The range of possible segment numbers is way less than the range of
1553  * BlockNumber, so we can reserve high values of segno for special purposes.
1554  * We define three:
1555  * - FORGET_RELATION_FSYNC means to cancel pending fsyncs for a relation,
1556  *	 either for one fork, or all forks if forknum is InvalidForkNumber
1557  * - FORGET_DATABASE_FSYNC means to cancel pending fsyncs for a whole database
1558  * - UNLINK_RELATION_REQUEST is a request to delete the file after the next
1559  *	 checkpoint.
1560  * Note also that we're assuming real segment numbers don't exceed INT_MAX.
1561  *
1562  * (Handling FORGET_DATABASE_FSYNC requests is a tad slow because the hash
1563  * table has to be searched linearly, but dropping a database is a pretty
1564  * heavyweight operation anyhow, so we'll live with it.)
1565  */
1566 void
RememberFsyncRequest(RelFileNode rnode,ForkNumber forknum,BlockNumber segno)1567 RememberFsyncRequest(RelFileNode rnode, ForkNumber forknum, BlockNumber segno)
1568 {
1569 	Assert(pendingOpsTable);
1570 
1571 	if (segno == FORGET_RELATION_FSYNC)
1572 	{
1573 		/* Remove any pending requests for the relation (one or all forks) */
1574 		PendingOperationEntry *entry;
1575 
1576 		entry = (PendingOperationEntry *) hash_search(pendingOpsTable,
1577 													  &rnode,
1578 													  HASH_FIND,
1579 													  NULL);
1580 		if (entry)
1581 		{
1582 			/*
1583 			 * We can't just delete the entry since mdsync could have an
1584 			 * active hashtable scan.  Instead we delete the bitmapsets; this
1585 			 * is safe because of the way mdsync is coded.  We also set the
1586 			 * "canceled" flags so that mdsync can tell that a cancel arrived
1587 			 * for the fork(s).
1588 			 */
1589 			if (forknum == InvalidForkNumber)
1590 			{
1591 				/* remove requests for all forks */
1592 				for (forknum = 0; forknum <= MAX_FORKNUM; forknum++)
1593 				{
1594 					bms_free(entry->requests[forknum]);
1595 					entry->requests[forknum] = NULL;
1596 					entry->canceled[forknum] = true;
1597 				}
1598 			}
1599 			else
1600 			{
1601 				/* remove requests for single fork */
1602 				bms_free(entry->requests[forknum]);
1603 				entry->requests[forknum] = NULL;
1604 				entry->canceled[forknum] = true;
1605 			}
1606 		}
1607 	}
1608 	else if (segno == FORGET_DATABASE_FSYNC)
1609 	{
1610 		/* Remove any pending requests for the entire database */
1611 		HASH_SEQ_STATUS hstat;
1612 		PendingOperationEntry *entry;
1613 		ListCell   *cell,
1614 				   *prev,
1615 				   *next;
1616 
1617 		/* Remove fsync requests */
1618 		hash_seq_init(&hstat, pendingOpsTable);
1619 		while ((entry = (PendingOperationEntry *) hash_seq_search(&hstat)) != NULL)
1620 		{
1621 			if (entry->rnode.dbNode == rnode.dbNode)
1622 			{
1623 				/* remove requests for all forks */
1624 				for (forknum = 0; forknum <= MAX_FORKNUM; forknum++)
1625 				{
1626 					bms_free(entry->requests[forknum]);
1627 					entry->requests[forknum] = NULL;
1628 					entry->canceled[forknum] = true;
1629 				}
1630 			}
1631 		}
1632 
1633 		/* Remove unlink requests */
1634 		prev = NULL;
1635 		for (cell = list_head(pendingUnlinks); cell; cell = next)
1636 		{
1637 			PendingUnlinkEntry *entry = (PendingUnlinkEntry *) lfirst(cell);
1638 
1639 			next = lnext(cell);
1640 			if (entry->rnode.dbNode == rnode.dbNode)
1641 			{
1642 				pendingUnlinks = list_delete_cell(pendingUnlinks, cell, prev);
1643 				pfree(entry);
1644 			}
1645 			else
1646 				prev = cell;
1647 		}
1648 	}
1649 	else if (segno == UNLINK_RELATION_REQUEST)
1650 	{
1651 		/* Unlink request: put it in the linked list */
1652 		MemoryContext oldcxt = MemoryContextSwitchTo(pendingOpsCxt);
1653 		PendingUnlinkEntry *entry;
1654 
1655 		/* PendingUnlinkEntry doesn't store forknum, since it's always MAIN */
1656 		Assert(forknum == MAIN_FORKNUM);
1657 
1658 		entry = palloc(sizeof(PendingUnlinkEntry));
1659 		entry->rnode = rnode;
1660 		entry->cycle_ctr = mdckpt_cycle_ctr;
1661 
1662 		pendingUnlinks = lappend(pendingUnlinks, entry);
1663 
1664 		MemoryContextSwitchTo(oldcxt);
1665 	}
1666 	else
1667 	{
1668 		/* Normal case: enter a request to fsync this segment */
1669 		MemoryContext oldcxt = MemoryContextSwitchTo(pendingOpsCxt);
1670 		PendingOperationEntry *entry;
1671 		bool		found;
1672 
1673 		entry = (PendingOperationEntry *) hash_search(pendingOpsTable,
1674 													  &rnode,
1675 													  HASH_ENTER,
1676 													  &found);
1677 		/* if new entry, initialize it */
1678 		if (!found)
1679 		{
1680 			entry->cycle_ctr = mdsync_cycle_ctr;
1681 			MemSet(entry->requests, 0, sizeof(entry->requests));
1682 			MemSet(entry->canceled, 0, sizeof(entry->canceled));
1683 		}
1684 
1685 		/*
1686 		 * NB: it's intentional that we don't change cycle_ctr if the entry
1687 		 * already exists.  The cycle_ctr must represent the oldest fsync
1688 		 * request that could be in the entry.
1689 		 */
1690 
1691 		entry->requests[forknum] = bms_add_member(entry->requests[forknum],
1692 												  (int) segno);
1693 
1694 		MemoryContextSwitchTo(oldcxt);
1695 	}
1696 }
1697 
1698 /*
1699  * ForgetRelationFsyncRequests -- forget any fsyncs for a relation fork
1700  *
1701  * forknum == InvalidForkNumber means all forks, although this code doesn't
1702  * actually know that, since it's just forwarding the request elsewhere.
1703  */
1704 void
ForgetRelationFsyncRequests(RelFileNode rnode,ForkNumber forknum)1705 ForgetRelationFsyncRequests(RelFileNode rnode, ForkNumber forknum)
1706 {
1707 	if (pendingOpsTable)
1708 	{
1709 		/* standalone backend or startup process: fsync state is local */
1710 		RememberFsyncRequest(rnode, forknum, FORGET_RELATION_FSYNC);
1711 	}
1712 	else if (IsUnderPostmaster)
1713 	{
1714 		/*
1715 		 * Notify the checkpointer about it.  If we fail to queue the cancel
1716 		 * message, we have to sleep and try again ... ugly, but hopefully
1717 		 * won't happen often.
1718 		 *
1719 		 * XXX should we CHECK_FOR_INTERRUPTS in this loop?  Escaping with an
1720 		 * error would leave the no-longer-used file still present on disk,
1721 		 * which would be bad, so I'm inclined to assume that the checkpointer
1722 		 * will always empty the queue soon.
1723 		 */
1724 		while (!ForwardFsyncRequest(rnode, forknum, FORGET_RELATION_FSYNC))
1725 			pg_usleep(10000L);	/* 10 msec seems a good number */
1726 
1727 		/*
1728 		 * Note we don't wait for the checkpointer to actually absorb the
1729 		 * cancel message; see mdsync() for the implications.
1730 		 */
1731 	}
1732 }
1733 
1734 /*
1735  * ForgetDatabaseFsyncRequests -- forget any fsyncs and unlinks for a DB
1736  */
1737 void
ForgetDatabaseFsyncRequests(Oid dbid)1738 ForgetDatabaseFsyncRequests(Oid dbid)
1739 {
1740 	RelFileNode rnode;
1741 
1742 	rnode.dbNode = dbid;
1743 	rnode.spcNode = 0;
1744 	rnode.relNode = 0;
1745 
1746 	if (pendingOpsTable)
1747 	{
1748 		/* standalone backend or startup process: fsync state is local */
1749 		RememberFsyncRequest(rnode, InvalidForkNumber, FORGET_DATABASE_FSYNC);
1750 	}
1751 	else if (IsUnderPostmaster)
1752 	{
1753 		/* see notes in ForgetRelationFsyncRequests */
1754 		while (!ForwardFsyncRequest(rnode, InvalidForkNumber,
1755 									FORGET_DATABASE_FSYNC))
1756 			pg_usleep(10000L);	/* 10 msec seems a good number */
1757 	}
1758 }
1759 
1760 /*
1761  * DropRelationFiles -- drop files of all given relations
1762  */
1763 void
DropRelationFiles(RelFileNode * delrels,int ndelrels,bool isRedo)1764 DropRelationFiles(RelFileNode *delrels, int ndelrels, bool isRedo)
1765 {
1766 	SMgrRelation *srels;
1767 	int			i;
1768 
1769 	srels = palloc(sizeof(SMgrRelation) * ndelrels);
1770 	for (i = 0; i < ndelrels; i++)
1771 	{
1772 		SMgrRelation srel = smgropen(delrels[i], InvalidBackendId);
1773 
1774 		if (isRedo)
1775 		{
1776 			ForkNumber	fork;
1777 
1778 			for (fork = 0; fork <= MAX_FORKNUM; fork++)
1779 				XLogDropRelation(delrels[i], fork);
1780 		}
1781 		srels[i] = srel;
1782 	}
1783 
1784 	smgrdounlinkall(srels, ndelrels, isRedo);
1785 
1786 	for (i = 0; i < ndelrels; i++)
1787 		smgrclose(srels[i]);
1788 	pfree(srels);
1789 }
1790 
1791 
1792 /*
1793  *	_fdvec_alloc() -- Make a MdfdVec object.
1794  */
1795 static MdfdVec *
_fdvec_alloc(void)1796 _fdvec_alloc(void)
1797 {
1798 	return (MdfdVec *) MemoryContextAlloc(MdCxt, sizeof(MdfdVec));
1799 }
1800 
1801 /*
1802  * Return the filename for the specified segment of the relation. The
1803  * returned string is palloc'd.
1804  */
1805 static char *
_mdfd_segpath(SMgrRelation reln,ForkNumber forknum,BlockNumber segno)1806 _mdfd_segpath(SMgrRelation reln, ForkNumber forknum, BlockNumber segno)
1807 {
1808 	char	   *path,
1809 			   *fullpath;
1810 
1811 	path = relpath(reln->smgr_rnode, forknum);
1812 
1813 	if (segno > 0)
1814 	{
1815 		fullpath = psprintf("%s.%u", path, segno);
1816 		pfree(path);
1817 	}
1818 	else
1819 		fullpath = path;
1820 
1821 	return fullpath;
1822 }
1823 
1824 /*
1825  * Open the specified segment of the relation,
1826  * and make a MdfdVec object for it.  Returns NULL on failure.
1827  */
1828 static MdfdVec *
_mdfd_openseg(SMgrRelation reln,ForkNumber forknum,BlockNumber segno,int oflags)1829 _mdfd_openseg(SMgrRelation reln, ForkNumber forknum, BlockNumber segno,
1830 			  int oflags)
1831 {
1832 	MdfdVec    *v;
1833 	int			fd;
1834 	char	   *fullpath;
1835 
1836 	fullpath = _mdfd_segpath(reln, forknum, segno);
1837 
1838 	/* open the file */
1839 	fd = PathNameOpenFile(fullpath, O_RDWR | PG_BINARY | oflags, 0600);
1840 
1841 	pfree(fullpath);
1842 
1843 	if (fd < 0)
1844 		return NULL;
1845 
1846 	/* allocate an mdfdvec entry for it */
1847 	v = _fdvec_alloc();
1848 
1849 	/* fill the entry */
1850 	v->mdfd_vfd = fd;
1851 	v->mdfd_segno = segno;
1852 	v->mdfd_chain = NULL;
1853 	Assert(_mdnblocks(reln, forknum, v) <= ((BlockNumber) RELSEG_SIZE));
1854 
1855 	/* all done */
1856 	return v;
1857 }
1858 
1859 /*
1860  *	_mdfd_getseg() -- Find the segment of the relation holding the
1861  *		specified block.
1862  *
1863  * If the segment doesn't exist, we ereport, return NULL, or create the
1864  * segment, according to "behavior".  Note: skipFsync is only used in the
1865  * EXTENSION_CREATE case.
1866  */
1867 static MdfdVec *
_mdfd_getseg(SMgrRelation reln,ForkNumber forknum,BlockNumber blkno,bool skipFsync,int behavior)1868 _mdfd_getseg(SMgrRelation reln, ForkNumber forknum, BlockNumber blkno,
1869 			 bool skipFsync, int behavior)
1870 {
1871 	MdfdVec    *v = mdopen(reln, forknum, behavior);
1872 	BlockNumber targetseg;
1873 	BlockNumber nextsegno;
1874 
1875 	/* some way to handle non-existent segments needs to be specified */
1876 	Assert(behavior &
1877 		   (EXTENSION_FAIL | EXTENSION_CREATE | EXTENSION_RETURN_NULL));
1878 
1879 	if (!v)
1880 		return NULL;			/* if behavior & EXTENSION_RETURN_NULL */
1881 
1882 	targetseg = blkno / ((BlockNumber) RELSEG_SIZE);
1883 	for (nextsegno = 1; nextsegno <= targetseg; nextsegno++)
1884 	{
1885 		Assert(nextsegno == v->mdfd_segno + 1);
1886 
1887 		if (v->mdfd_chain == NULL)
1888 		{
1889 			BlockNumber nblocks = _mdnblocks(reln, forknum, v);
1890 			int			flags = 0;
1891 
1892 			if (nblocks > ((BlockNumber) RELSEG_SIZE))
1893 				elog(FATAL, "segment too big");
1894 
1895 			if ((behavior & EXTENSION_CREATE) ||
1896 				(InRecovery && (behavior & EXTENSION_CREATE_RECOVERY)))
1897 			{
1898 				/*
1899 				 * Normally we will create new segments only if authorized by
1900 				 * the caller (i.e., we are doing mdextend()).  But when doing
1901 				 * WAL recovery, create segments anyway; this allows cases
1902 				 * such as replaying WAL data that has a write into a
1903 				 * high-numbered segment of a relation that was later deleted.
1904 				 * We want to go ahead and create the segments so we can
1905 				 * finish out the replay.  However if the caller has specified
1906 				 * EXTENSION_REALLY_RETURN_NULL, then extension is not desired
1907 				 * even in recovery; we won't reach this point in that case.
1908 				 *
1909 				 * We have to maintain the invariant that segments before the
1910 				 * last active segment are of size RELSEG_SIZE; therefore, if
1911 				 * extending, pad them out with zeroes if needed.  (This only
1912 				 * matters if in recovery, or if the caller is extending the
1913 				 * relation discontiguously, but that can happen in hash
1914 				 * indexes.)
1915 				 */
1916 				if (nblocks < ((BlockNumber) RELSEG_SIZE))
1917 				{
1918 					char	   *zerobuf = palloc0(BLCKSZ);
1919 
1920 					mdextend(reln, forknum,
1921 							 nextsegno * ((BlockNumber) RELSEG_SIZE) - 1,
1922 							 zerobuf, skipFsync);
1923 					pfree(zerobuf);
1924 				}
1925 				flags = O_CREAT;
1926 			}
1927 			else if (!(behavior & EXTENSION_DONT_CHECK_SIZE) &&
1928 					 nblocks < ((BlockNumber) RELSEG_SIZE))
1929 			{
1930 				/*
1931 				 * When not extending (or explicitly including truncated
1932 				 * segments), only open the next segment if the current one is
1933 				 * exactly RELSEG_SIZE.  If not (this branch), either return
1934 				 * NULL or fail.
1935 				 */
1936 				if (behavior & EXTENSION_RETURN_NULL)
1937 				{
1938 					/*
1939 					 * Some callers discern between reasons for _mdfd_getseg()
1940 					 * returning NULL based on errno. As there's no failing
1941 					 * syscall involved in this case, explicitly set errno to
1942 					 * ENOENT, as that seems the closest interpretation.
1943 					 */
1944 					errno = ENOENT;
1945 					return NULL;
1946 				}
1947 
1948 				ereport(ERROR,
1949 						(errcode_for_file_access(),
1950 						 errmsg("could not open file \"%s\" (target block %u): previous segment is only %u blocks",
1951 								_mdfd_segpath(reln, forknum, nextsegno),
1952 								blkno, nblocks)));
1953 			}
1954 
1955 			v->mdfd_chain = _mdfd_openseg(reln, forknum, nextsegno, flags);
1956 
1957 			if (v->mdfd_chain == NULL)
1958 			{
1959 				if ((behavior & EXTENSION_RETURN_NULL) &&
1960 					FILE_POSSIBLY_DELETED(errno))
1961 					return NULL;
1962 				ereport(ERROR,
1963 						(errcode_for_file_access(),
1964 				   errmsg("could not open file \"%s\" (target block %u): %m",
1965 						  _mdfd_segpath(reln, forknum, nextsegno),
1966 						  blkno)));
1967 			}
1968 		}
1969 		v = v->mdfd_chain;
1970 	}
1971 	return v;
1972 }
1973 
1974 /*
1975  * Get number of blocks present in a single disk file
1976  */
1977 static BlockNumber
_mdnblocks(SMgrRelation reln,ForkNumber forknum,MdfdVec * seg)1978 _mdnblocks(SMgrRelation reln, ForkNumber forknum, MdfdVec *seg)
1979 {
1980 	off_t		len;
1981 
1982 	len = FileSeek(seg->mdfd_vfd, 0L, SEEK_END);
1983 	if (len < 0)
1984 		ereport(ERROR,
1985 				(errcode_for_file_access(),
1986 				 errmsg("could not seek to end of file \"%s\": %m",
1987 						FilePathName(seg->mdfd_vfd))));
1988 	/* note that this calculation will ignore any partial block at EOF */
1989 	return (BlockNumber) (len / BLCKSZ);
1990 }
1991