111#define BootstrapTimeLineID 1
140bool XLOG_DEBUG =
false;
150#define NUM_XLOGINSERT_LOCKS 8
173#ifdef HAVE_FSYNC_WRITETHROUGH
591#define INSERT_FREESPACE(endptr) \
592 (((endptr) % XLOG_BLCKSZ == 0) ? 0 : (XLOG_BLCKSZ - (endptr) % XLOG_BLCKSZ))
595#define NextBufIdx(idx) \
596 (((idx) == XLogCtl->XLogCacheBlck) ? 0 : ((idx) + 1))
602#define XLogRecPtrToBufIdx(recptr) \
603 (((recptr) / XLOG_BLCKSZ) % (XLogCtl->XLogCacheBlck + 1))
608#define UsableBytesInPage (XLOG_BLCKSZ - SizeOfXLogShortPHD)
614#define ConvertToXSegs(x, segsize) XLogMBVarToSegs((x), (segsize))
631#define RefreshXLogWriteResult(_target) \
633 _target.Flush = pg_atomic_read_u64(&XLogCtl->logFlushResult); \
635 _target.Write = pg_atomic_read_u64(&XLogCtl->logWriteResult); \
763 bool topxid_included)
790 elog(
ERROR,
"cannot make new WAL entries during recovery");
860 (!prevDoPageWrites ||
924 rdata_crc = rechdr->
xl_crc;
927 rechdr->
xl_crc = rdata_crc;
935 StartPos, EndPos, insertTLI);
977 if (StartPos / XLOG_BLCKSZ != EndPos / XLOG_BLCKSZ)
994 TRACE_POSTGRESQL_WAL_SWITCH();
1005 if (StartPos / XLOG_BLCKSZ != EndPos / XLOG_BLCKSZ)
1009 if (offset == EndPos % XLOG_BLCKSZ)
1025 char *errormsg = NULL;
1039 for (; rdata != NULL; rdata = rdata->
next)
1050 .segment_open = NULL,
1051 .segment_close = NULL),
1064 errormsg ? errormsg :
"no error message");
1070 debug_reader->
record = decoded;
1072 debug_reader->
record = NULL;
1144 startbytepos =
Insert->CurrBytePos;
1145 endbytepos = startbytepos + size;
1146 prevbytepos =
Insert->PrevBytePos;
1147 Insert->CurrBytePos = endbytepos;
1148 Insert->PrevBytePos = startbytepos;
1193 startbytepos =
Insert->CurrBytePos;
1199 *EndPos = *StartPos = ptr;
1203 endbytepos = startbytepos + size;
1204 prevbytepos =
Insert->PrevBytePos;
1216 Insert->CurrBytePos = endbytepos;
1217 Insert->PrevBytePos = startbytepos;
1261 while (rdata != NULL)
1263 const char *rdata_data = rdata->
data;
1264 int rdata_len = rdata->
len;
1266 while (rdata_len > freespace)
1272 memcpy(currpos, rdata_data, freespace);
1273 rdata_data += freespace;
1274 rdata_len -= freespace;
1275 written += freespace;
1276 CurrPos += freespace;
1307 memcpy(currpos, rdata_data, rdata_len);
1308 currpos += rdata_len;
1309 CurrPos += rdata_len;
1310 freespace -= rdata_len;
1311 written += rdata_len;
1313 rdata = rdata->
next;
1315 Assert(written == write_len);
1331 CurrPos += freespace;
1339 while (CurrPos < EndPos)
1363 CurrPos += XLOG_BLCKSZ;
1372 if (CurrPos != EndPos)
1375 errmsg_internal(
"space reserved for WAL record does not match what was written"));
1397 static int lockToTry = -1;
1399 if (lockToTry == -1)
1525 elog(
PANIC,
"cannot wait without a PGPROC structure");
1532 if (upto <= inserted)
1537 bytepos =
Insert->CurrBytePos;
1549 if (upto > reservedUpto)
1552 (
errmsg(
"request to flush past end of generated WAL; request %X/%X, current position %X/%X",
1554 upto = reservedUpto;
1566 finishedUpto = reservedUpto;
1598 insertingat, &insertingat))
1609 }
while (insertingat < upto);
1612 finishedUpto = insertingat;
1623 return finishedUpto;
1647 static uint64 cachedPage = 0;
1648 static char *cachedPos = NULL;
1655 if (ptr / XLOG_BLCKSZ == cachedPage)
1659 return cachedPos + ptr % XLOG_BLCKSZ;
1682 expectedEndPtr = ptr;
1683 expectedEndPtr += XLOG_BLCKSZ - ptr % XLOG_BLCKSZ;
1686 if (expectedEndPtr != endptr)
1711 initializedUpto = ptr;
1718 if (expectedEndPtr != endptr)
1719 elog(
PANIC,
"could not find WAL buffer for %X/%X",
1735 cachedPage = ptr / XLOG_BLCKSZ;
1741 return cachedPos + ptr % XLOG_BLCKSZ;
1762 char *pdst = dstbuf;
1765 Size nbytes = count;
1777 if (startptr + count > inserted)
1779 errmsg(
"cannot read past end of generated WAL: requested %X/%X, current position %X/%X",
1799 uint32 offset = recptr % XLOG_BLCKSZ;
1811 expectedEndPtr = recptr + (XLOG_BLCKSZ - offset);
1818 if (expectedEndPtr != endptr)
1827 psrc = page + offset;
1828 npagebytes =
Min(nbytes, XLOG_BLCKSZ - offset);
1837 memcpy(pdst, psrc, npagebytes);
1850 if (expectedEndPtr != endptr)
1854 recptr += npagebytes;
1855 nbytes -= npagebytes;
1858 Assert(pdst - dstbuf <= count);
1860 return pdst - dstbuf;
1888 seg_offset = XLOG_BLCKSZ;
1931 seg_offset = XLOG_BLCKSZ;
1938 seg_offset += fullpages * XLOG_BLCKSZ + bytesleft;
1962 offset = ptr % XLOG_BLCKSZ;
2030 while (upto >= ReservedPtr || opportunistic)
2032 Assert(ReservedPtr % XLOG_BLCKSZ == 0);
2052 upto = ReservedPtr - 1;
2062 ReservedPtr + XLOG_BLCKSZ))
2105 TRACE_POSTGRESQL_WAL_BUFFER_WRITE_DIRTY_START();
2106 WriteRqst.
Write = OldPageRqstPtr;
2107 WriteRqst.
Flush = 0;
2111 TRACE_POSTGRESQL_WAL_BUFFER_WRITE_DIRTY_DONE();
2120 NewPageBeginPtr = ReservedPtr;
2121 NewPageEndPtr = NewPageBeginPtr + XLOG_BLCKSZ;
2137 MemSet(NewPage, 0, XLOG_BLCKSZ);
2163 if (
Insert->runningBackups == 0)
2247 NewPageBeginPtr = NewPageEndPtr;
2248 NewPageEndPtr = NewPageBeginPtr + XLOG_BLCKSZ;
2282 if (XLOG_DEBUG && npages > 0)
2284 elog(
DEBUG1,
"initialized %d pages, up to %X/%X",
2342 GUC_check_errdetail(
"The WAL segment size must be a power of two between 1 MB and 1 GB.");
2361 "max_slot_wal_keep_size");
2402 recycleSegNo = (
XLogSegNo) ceil(((
double) lastredoptr + distance) /
2405 if (recycleSegNo < minSegNo)
2406 recycleSegNo = minSegNo;
2407 if (recycleSegNo > maxSegNo)
2408 recycleSegNo = maxSegNo;
2410 return recycleSegNo;
2450 bool last_iteration;
2495 elog(
PANIC,
"xlog write request %X/%X is past end of log %X/%X",
2550 finishing_seg = !ispartialpage &&
2553 if (last_iteration ||
2565 nbytes = npages * (
Size) XLOG_BLCKSZ;
2597 errmsg(
"could not write to log file \"%s\" at offset %u, length %zu: %m",
2598 xlogfname, startoffset, nleft)));
2602 startoffset += written;
2603 }
while (nleft > 0);
2660 if (flexible && npages == 0)
2725#ifdef USE_ASSERT_CHECKING
2770 if (asyncXactLSN <= prevAsyncXactLSN)
2893 if (!force && newMinRecoveryPoint < lsn)
2895 "xlog min recovery request %X/%X is past current point %X/%X",
2908 (
errmsg_internal(
"updated min recovery point to %X/%X on timeline %u",
2910 newMinRecoveryPointTLI)));
2948 elog(
LOG,
"xlog flush request %X/%X; write %X/%X; flush %X/%X",
2965 WriteRqstPtr = record;
2985 if (WriteRqstPtr < XLogCtl->LogwrtRqst.Write)
3043 WriteRqst.
Write = insertpos;
3044 WriteRqst.
Flush = insertpos;
3081 "xlog flush request %X/%X is not satisfied --- flushed only to %X/%X",
3114 bool flexible =
true;
3136 WriteRqst.
Write -= WriteRqst.
Write % XLOG_BLCKSZ;
3203 WriteRqst.
Flush = 0;
3208 elog(
LOG,
"xlog bg flush request write %X/%X; flush: %X/%X, current is write %X/%X; flush %X/%X",
3224 XLogWrite(WriteRqst, insertTLI, flexible);
3332 bool *added,
char *path)
3339 int open_flags = O_RDWR | O_CREAT | O_EXCL |
PG_BINARY;
3354 if (errno != ENOENT)
3357 errmsg(
"could not open file \"%s\": %m", path)));
3368 elog(
DEBUG2,
"creating and filling new WAL file");
3382 errmsg(
"could not create file \"%s\": %m", tmppath)));
3417 save_errno = errno ? errno : ENOSPC;
3443 errmsg(
"could not write to file \"%s\": %m", tmppath)));
3457 errmsg(
"could not fsync file \"%s\": %m", tmppath)));
3467 errmsg(
"could not close file \"%s\": %m", tmppath)));
3474 installed_segno = logsegno;
3490 elog(
DEBUG2,
"done creating and filling new WAL file");
3537 errmsg(
"could not open file \"%s\": %m", path)));
3576 errmsg(
"could not open file \"%s\": %m", path)));
3590 errmsg(
"could not create file \"%s\": %m", tmppath)));
3599 nread = upto - nbytes;
3605 if (nread <
sizeof(buffer))
3606 memset(buffer.
data, 0,
sizeof(buffer));
3612 if (nread >
sizeof(buffer))
3613 nread =
sizeof(buffer);
3615 r =
read(srcfd, buffer.
data, nread);
3621 errmsg(
"could not read file \"%s\": %m",
3626 errmsg(
"could not read file \"%s\": read %d of %zu",
3627 path, r, (
Size) nread)));
3633 if ((
int)
write(
fd, buffer.
data,
sizeof(buffer)) != (
int)
sizeof(buffer))
3635 int save_errno = errno;
3642 errno = save_errno ? save_errno : ENOSPC;
3646 errmsg(
"could not write to file \"%s\": %m", tmppath)));
3655 errmsg(
"could not fsync file \"%s\": %m", tmppath)));
3661 errmsg(
"could not close file \"%s\": %m", tmppath)));
3666 errmsg(
"could not close file \"%s\": %m", path)));
3672 elog(
ERROR,
"InstallXLogFileSegment should not have failed");
3706 struct stat stat_buf;
3727 while (
stat(path, &stat_buf) == 0)
3729 if ((*segno) >= max_segno)
3769 errmsg(
"could not open file \"%s\": %m", path)));
3788#if defined(USE_POSIX_FADVISE) && defined(POSIX_FADV_DONTNEED)
3790 (void) posix_fadvise(
openLogFile, 0, 0, POSIX_FADV_DONTNEED);
3796 int save_errno = errno;
3802 errmsg(
"could not close file \"%s\": %m", xlogfname)));
3868 int save_errno = errno;
3875 if (segno <= lastRemovedSegNo)
3883 errmsg(
"requested WAL segment %s has already been removed",
3905 return lastRemovedSegNo;
3934 if (tli != file_tli)
3938 if (oldest_segno == 0 || file_segno < oldest_segno)
3939 oldest_segno = file_segno;
3943 return oldest_segno;
3976 elog(
DEBUG2,
"removing all temporary WAL segments");
3983 if (strncmp(xlde->
d_name,
"xlogtemp.", 9) != 0)
3988 elog(
DEBUG2,
"removed temporary WAL segment \"%s\"", path);
4024 elog(
DEBUG2,
"attempting to remove WAL segments older than log file %s",
4047 if (strcmp(xlde->
d_name + 8, lastoff + 8) <= 0)
4094 recycleSegNo = endLogSegNo + 10;
4101 elog(
DEBUG2,
"attempting to remove WAL segments newer than log file %s",
4117 if (strncmp(xlde->
d_name, switchseg, 8) < 0 &&
4118 strcmp(xlde->
d_name + 8, switchseg + 8) > 0)
4156 const char *segname = segment_de->
d_name;
4166 *endlogSegNo <= recycleSegNo &&
4170 true, recycleSegNo, insertTLI))
4201 if (rename(path, newpath) != 0)
4205 errmsg(
"could not rename file \"%s\": %m",
4241 struct stat stat_buf;
4248 errmsg(
"required WAL directory \"%s\" does not exist",
4253 if (
stat(path, &stat_buf) == 0)
4259 errmsg(
"required WAL directory \"%s\" does not exist",
4265 (
errmsg(
"creating missing WAL directory \"%s\"", path)));
4269 errmsg(
"could not create missing directory \"%s\": %m",
4275 if (
stat(path, &stat_buf) == 0)
4280 (
errmsg(
"required WAL directory \"%s\" does not exist",
4286 (
errmsg(
"creating missing WAL directory \"%s\"", path)));
4289 (
errmsg(
"could not create missing directory \"%s\": %m",
4314 elog(
DEBUG2,
"removing WAL backup history file \"%s\"",
4355 (
errcode(ERRCODE_INTERNAL_ERROR),
4356 errmsg(
"could not generate secret authorization token")));
4454 errmsg(
"could not create file \"%s\": %m",
4466 errmsg(
"could not write to file \"%s\": %m",
4475 errmsg(
"could not fsync file \"%s\": %m",
4482 errmsg(
"could not close file \"%s\": %m",
4491 char wal_segsz_str[20];
4502 errmsg(
"could not open file \"%s\": %m",
4512 errmsg(
"could not read file \"%s\": %m",
4517 errmsg(
"could not read file \"%s\": read %d of %zu",
4533 (
errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4534 errmsg(
"database files are incompatible with server"),
4535 errdetail(
"The database cluster was initialized with PG_CONTROL_VERSION %d (0x%08x),"
4536 " but the server was compiled with PG_CONTROL_VERSION %d (0x%08x).",
4539 errhint(
"This could be a problem of mismatched byte ordering. It looks like you need to initdb.")));
4543 (
errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4544 errmsg(
"database files are incompatible with server"),
4545 errdetail(
"The database cluster was initialized with PG_CONTROL_VERSION %d,"
4546 " but the server was compiled with PG_CONTROL_VERSION %d.",
4548 errhint(
"It looks like you need to initdb.")));
4559 (
errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4560 errmsg(
"incorrect checksum in control file")));
4569 (
errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4570 errmsg(
"database files are incompatible with server"),
4572 errdetail(
"The database cluster was initialized with %s %d,"
4573 " but the server was compiled with %s %d.",
4576 errhint(
"It looks like you need to initdb.")));
4579 (
errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4580 errmsg(
"database files are incompatible with server"),
4582 errdetail(
"The database cluster was initialized with %s %d,"
4583 " but the server was compiled with %s %d.",
4585 "MAXALIGN", MAXIMUM_ALIGNOF),
4586 errhint(
"It looks like you need to initdb.")));
4589 (
errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4590 errmsg(
"database files are incompatible with server"),
4591 errdetail(
"The database cluster appears to use a different floating-point number format than the server executable."),
4592 errhint(
"It looks like you need to initdb.")));
4595 (
errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4596 errmsg(
"database files are incompatible with server"),
4598 errdetail(
"The database cluster was initialized with %s %d,"
4599 " but the server was compiled with %s %d.",
4602 errhint(
"It looks like you need to recompile or initdb.")));
4605 (
errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4606 errmsg(
"database files are incompatible with server"),
4608 errdetail(
"The database cluster was initialized with %s %d,"
4609 " but the server was compiled with %s %d.",
4611 "RELSEG_SIZE", RELSEG_SIZE),
4612 errhint(
"It looks like you need to recompile or initdb.")));
4615 (
errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4616 errmsg(
"database files are incompatible with server"),
4618 errdetail(
"The database cluster was initialized with %s %d,"
4619 " but the server was compiled with %s %d.",
4621 "XLOG_BLCKSZ", XLOG_BLCKSZ),
4622 errhint(
"It looks like you need to recompile or initdb.")));
4625 (
errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4626 errmsg(
"database files are incompatible with server"),
4628 errdetail(
"The database cluster was initialized with %s %d,"
4629 " but the server was compiled with %s %d.",
4632 errhint(
"It looks like you need to recompile or initdb.")));
4635 (
errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4636 errmsg(
"database files are incompatible with server"),
4638 errdetail(
"The database cluster was initialized with %s %d,"
4639 " but the server was compiled with %s %d.",
4642 errhint(
"It looks like you need to recompile or initdb.")));
4645 (
errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4646 errmsg(
"database files are incompatible with server"),
4648 errdetail(
"The database cluster was initialized with %s %d,"
4649 " but the server was compiled with %s %d.",
4652 errhint(
"It looks like you need to recompile or initdb.")));
4655 (
errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4656 errmsg(
"database files are incompatible with server"),
4658 errdetail(
"The database cluster was initialized with %s %d,"
4659 " but the server was compiled with %s %d.",
4662 errhint(
"It looks like you need to recompile or initdb.")));
4664#ifdef USE_FLOAT8_BYVAL
4667 (
errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4668 errmsg(
"database files are incompatible with server"),
4669 errdetail(
"The database cluster was initialized without USE_FLOAT8_BYVAL"
4670 " but the server was compiled with USE_FLOAT8_BYVAL."),
4671 errhint(
"It looks like you need to recompile or initdb.")));
4675 (
errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4676 errmsg(
"database files are incompatible with server"),
4677 errdetail(
"The database cluster was initialized with USE_FLOAT8_BYVAL"
4678 " but the server was compiled without USE_FLOAT8_BYVAL."),
4679 errhint(
"It looks like you need to recompile or initdb.")));
4686 errmsg_plural(
"invalid WAL segment size in control file (%d byte)",
4687 "invalid WAL segment size in control file (%d bytes)",
4690 errdetail(
"The WAL segment size must be a power of two between 1 MB and 1 GB.")));
4700 errmsg(
"\"%s\" must be at least twice \"%s\"",
4701 "min_wal_size",
"wal_segment_size")));
4706 errmsg(
"\"%s\" must be at least twice \"%s\"",
4707 "max_wal_size",
"wal_segment_size")));
4874 foreach(l, elemlist)
4876 char *tok = (
char *)
lfirst(l);
4882 for (rmid = 0; rmid <=
RM_MAX_ID; rmid++)
4884 newwalconsistency[rmid] =
true;
4891 for (rmid = 0; rmid <=
RM_MAX_ID; rmid++)
4896 newwalconsistency[rmid] =
true;
4930 memcpy(*extra, newwalconsistency, (
RM_MAX_ID + 1) *
sizeof(
bool));
4996 return "(disabled)";
5114 if (walDebugCxt == NULL)
5131 if (foundCFile || foundXLog)
5134 Assert(foundCFile && foundXLog);
5139 if (localControlFile)
5140 pfree(localControlFile);
5149 if (localControlFile)
5152 pfree(localControlFile);
5188 allocptr = (
char *)
TYPEALIGN(XLOG_BLCKSZ, allocptr);
5246 sysidentifier = ((
uint64) tv.tv_sec) << 32;
5247 sysidentifier |= ((
uint64) tv.tv_usec) << 12;
5248 sysidentifier |= getpid() & 0xFFF;
5251 buffer = (
char *)
palloc(XLOG_BLCKSZ + XLOG_BLCKSZ);
5253 memset(page, 0, XLOG_BLCKSZ);
5311 *(recptr++) =
sizeof(checkPoint);
5312 memcpy(recptr, &checkPoint,
sizeof(checkPoint));
5313 recptr +=
sizeof(checkPoint);
5341 errmsg(
"could not write bootstrap write-ahead log file: %m")));
5349 errmsg(
"could not fsync bootstrap write-ahead log file: %m")));
5355 errmsg(
"could not close bootstrap write-ahead log file: %m")));
5389 "%Y-%m-%d %H:%M:%S %Z",
5406 Assert(endTLI != newTLI);
5428 if (endLogSegNo == startLogSegNo)
5452 int save_errno = errno;
5458 errmsg(
"could not close file \"%s\": %m", xlogfname)));
5482 "recovery_end_command",
5484 WAIT_EVENT_RECOVERY_END_COMMAND);
5579 (
errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
5580 errmsg(
"WAL was generated with \"wal_level=minimal\", cannot continue recovering"),
5581 errdetail(
"This happens if you temporarily set \"wal_level=minimal\" on the server."),
5582 errhint(
"Use a backup taken after setting \"wal_level\" to higher than \"minimal\".")));
5621 bool haveBackupLabel;
5625 bool performedWalRecovery;
5630 bool promoted =
false;
5647 errmsg(
"control file contains invalid checkpoint location")));
5658 (
errmsg(
"database system was shut down at %s",
5664 (
errmsg(
"database system was shut down in recovery at %s",
5670 (
errmsg(
"database system shutdown was interrupted; last known up at %s",
5676 (
errmsg(
"database system was interrupted while in recovery at %s",
5678 errhint(
"This probably means that some data is corrupted and"
5679 " you will have to use the last backup for recovery.")));
5684 (
errmsg(
"database system was interrupted while in recovery at log time %s",
5686 errhint(
"If this has occurred more than once some data might be corrupted"
5687 " and you might need to choose an earlier recovery target.")));
5692 (
errmsg(
"database system was interrupted; last known up at %s",
5699 errmsg(
"control file contains invalid database cluster state")));
5703#ifdef XLOG_REPLAY_DELAY
5753 &haveBackupLabel, &haveTblspcMap);
5906 if (haveBackupLabel)
6015 running.
xcnt = nxids;
6024 running.
xids = xids;
6034 performedWalRecovery =
true;
6037 performedWalRecovery =
false;
6043 EndOfLog = endOfRecoveryInfo->
endOfLog;
6086 (
errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6087 errmsg(
"WAL ends before end of online backup"),
6088 errhint(
"All WAL generated while online backup was taken must be available at recovery.")));
6091 (
errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
6092 errmsg(
"WAL ends before consistent recovery point")));
6138 (
errmsg(
"selected new timeline ID: %u", newTLI)));
6171 (
errmsg(
"archive recovery complete")));
6214 if (EndOfLog % XLOG_BLCKSZ != 0)
6227 memset(page +
len, 0, XLOG_BLCKSZ -
len);
6320 if (performedWalRecovery)
6474 bool promoted =
false;
6616 return oldXLogAllowed;
6762 if (res < last_important)
6763 res = last_important;
6803 (
errmsg(
"shutting down")));
6842 (
errmsg(
"restartpoint starting:%s%s%s%s%s%s%s%s",
6854 (
errmsg(
"checkpoint starting:%s%s%s%s%s%s%s%s",
6876 uint64 average_sync_time;
6906 average_sync_time = 0;
6910 average_msecs = (long) ((average_sync_time + 999) / 1000);
6919 (
errmsg(
"restartpoint complete: wrote %d buffers (%.1f%%), "
6920 "wrote %d SLRU buffers; %d WAL file(s) added, "
6921 "%d removed, %d recycled; write=%ld.%03d s, "
6922 "sync=%ld.%03d s, total=%ld.%03d s; sync files=%d, "
6923 "longest=%ld.%03d s, average=%ld.%03d s; distance=%d kB, "
6924 "estimate=%d kB; lsn=%X/%X, redo lsn=%X/%X",
6931 write_msecs / 1000, (
int) (write_msecs % 1000),
6932 sync_msecs / 1000, (
int) (sync_msecs % 1000),
6933 total_msecs / 1000, (
int) (total_msecs % 1000),
6935 longest_msecs / 1000, (
int) (longest_msecs % 1000),
6936 average_msecs / 1000, (
int) (average_msecs % 1000),
6943 (
errmsg(
"checkpoint complete: wrote %d buffers (%.1f%%), "
6944 "wrote %d SLRU buffers; %d WAL file(s) added, "
6945 "%d removed, %d recycled; write=%ld.%03d s, "
6946 "sync=%ld.%03d s, total=%ld.%03d s; sync files=%d, "
6947 "longest=%ld.%03d s, average=%ld.%03d s; distance=%d kB, "
6948 "estimate=%d kB; lsn=%X/%X, redo lsn=%X/%X",
6955 write_msecs / 1000, (
int) (write_msecs % 1000),
6956 sync_msecs / 1000, (
int) (sync_msecs % 1000),
6957 total_msecs / 1000, (
int) (total_msecs % 1000),
6959 longest_msecs / 1000, (
int) (longest_msecs % 1000),
6960 average_msecs / 1000, (
int) (average_msecs % 1000),
7028 char activitymsg[128];
7030 snprintf(activitymsg,
sizeof(activitymsg),
"performing %s%s%s",
7033 restartpoint ?
"restartpoint" :
"checkpoint");
7089 int oldXLogAllowed = 0;
7102 elog(
ERROR,
"can't create a checkpoint during recovery");
7136 MemSet(&checkPoint, 0,
sizeof(checkPoint));
7212 checkPoint.
redo = curInsert;
7275 TRACE_POSTGRESQL_CHECKPOINT_START(flags);
7429 (
errmsg(
"concurrent write-ahead log activity while database system is shutting down")));
7570 elog(
ERROR,
"can only be used to end recovery");
7638 elog(
ERROR,
"can only be used at end of recovery");
7639 if (pagePtr % XLOG_BLCKSZ != 0)
7640 elog(
ERROR,
"invalid position for missing continuation record %X/%X",
7650 if (recptr != startPos)
7651 elog(
ERROR,
"invalid WAL insert position %X/%X for OVERWRITE_CONTRECORD",
7681 elog(
ERROR,
"OVERWRITE_CONTRECORD was inserted to unexpected position %X/%X",
7707 TRACE_POSTGRESQL_BUFFER_CHECKPOINT_START(flags);
7717 TRACE_POSTGRESQL_BUFFER_CHECKPOINT_SYNC_START();
7721 TRACE_POSTGRESQL_BUFFER_CHECKPOINT_DONE();
7750 "could not record restart point at %X/%X because there "
7751 "are unresolved references to invalid pages",
7809 (
errmsg_internal(
"skipping restartpoint, recovery has already ended")));
7960 endptr = (receivePtr < replayPtr) ? replayPtr : receivePtr;
8016 (
errmsg(
"recovery restart point at %X/%X",
8018 xtime ?
errdetail(
"Last completed transaction was at log time %s.",
8026 "archive_cleanup_command",
8028 WAIT_EVENT_ARCHIVE_CLEANUP_COMMAND);
8093 if (currSeg > keepSegs)
8094 oldestSegMaxWalSize = currSeg - keepSegs;
8096 oldestSegMaxWalSize = 1;
8105 if (targetSeg >= oldestSlotSeg)
8108 if (targetSeg >= oldestSegMaxWalSize)
8116 if (targetSeg >= oldestSeg)
8167 if (currSegNo - segno > slot_keep_segs)
8168 segno = currSegNo - slot_keep_segs;
8182 if (unsummarized_segno < segno)
8183 segno = unsummarized_segno;
8192 if (currSegNo - segno < keep_segs)
8195 if (currSegNo <= keep_segs)
8198 segno = currSegNo - keep_segs;
8203 if (segno < *logSegNo)
8255 if (mark_unimportant)
8280 (
errmsg(
"restore point \"%s\" created at %X/%X",
8357 bool recoveryInProgress;
8388 Insert->fullPageWrites =
true;
8407 Insert->fullPageWrites =
false;
8487 (
errmsg(
"online backup was canceled, recovery cannot continue")));
8514 running.
xcnt = nxids;
8523 running.
xids = xids;
8545 (
errmsg(
"unexpected timeline ID %u (should be %u) in shutdown checkpoint record",
8603 (
errmsg(
"unexpected timeline ID %u (should be %u) in online checkpoint record",
8632 (
errmsg(
"unexpected timeline ID %u (should be %u) in end-of-recovery record",
8672 elog(
ERROR,
"XLOG_FPI record did not contain a full-page image");
8677 elog(
ERROR,
"unexpected XLogReadBufferForRedo result when restoring backup block");
8783 int o_direct_flag = 0;
8796 return o_direct_flag;
8809 return o_direct_flag;
8812 return O_SYNC | o_direct_flag;
8816 return O_DSYNC | o_direct_flag;
8820 elog(
ERROR,
"unrecognized \"wal_sync_method\": %d", method);
8853 errmsg(
"could not fsync file \"%s\": %m", xlogfname)));
8897 msg =
_(
"could not fsync file \"%s\": %m");
8899#ifdef HAVE_FSYNC_WRITETHROUGH
8902 msg =
_(
"could not fsync write-through file \"%s\": %m");
8907 msg =
_(
"could not fdatasync file \"%s\": %m");
8916 errcode(ERRCODE_INVALID_PARAMETER_VALUE),
8925 int save_errno = errno;
8931 errmsg(msg, xlogfname)));
8983 (
errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
8984 errmsg(
"WAL level not sufficient for making an online backup"),
8985 errhint(
"\"wal_level\" must be set to \"replica\" or \"logical\" at server start.")));
8989 (
errcode(ERRCODE_INVALID_PARAMETER_VALUE),
8990 errmsg(
"backup label too long (max %d bytes)",
9027 bool gotUniqueStartpoint =
false;
9108 if (!checkpointfpw ||
state->startpoint <= recptr)
9110 (
errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
9111 errmsg(
"WAL generated with \"full_page_writes=off\" was replayed "
9112 "since last restartpoint"),
9113 errhint(
"This means that the backup being taken on the standby "
9114 "is corrupt and should not be used. "
9115 "Enable \"full_page_writes\" and run CHECKPOINT on the primary, "
9116 "and then try an online backup again.")));
9125 gotUniqueStartpoint =
true;
9143 gotUniqueStartpoint =
true;
9146 }
while (!gotUniqueStartpoint);
9151 datadirpathlen = strlen(
DataDir);
9176 tsoid = strtoul(de->
d_name, &badp, 10);
9177 if (*badp !=
'\0' || errno == EINVAL || errno == ERANGE)
9189 rllen =
readlink(fullpath, linkpath,
sizeof(linkpath));
9193 (
errmsg(
"could not read symbolic link \"%s\": %m",
9197 else if (rllen >=
sizeof(linkpath))
9200 (
errmsg(
"symbolic link \"%s\" target is too long",
9204 linkpath[rllen] =
'\0';
9211 if (rllen > datadirpathlen &&
9212 strncmp(linkpath,
DataDir, datadirpathlen) == 0 &&
9221 for (s = linkpath; *s; s++)
9223 if (*s ==
'\n' || *s ==
'\r' || *s ==
'\\')
9241 snprintf(linkpath,
sizeof(linkpath),
"%s/%s",
9258 *tablespaces =
lappend(*tablespaces, ti);
9299 bool backup_stopped_in_recovery =
false;
9305 int seconds_before_warning;
9307 bool reported_waiting =
false;
9319 (
errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
9320 errmsg(
"WAL level not sufficient for making an online backup"),
9321 errhint(
"\"wal_level\" must be set to \"replica\" or \"logical\" at server start.")));
9356 if (
state->started_in_recovery && !backup_stopped_in_recovery)
9358 (
errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
9359 errmsg(
"the standby was promoted during online backup"),
9360 errhint(
"This means that the backup being taken is corrupt "
9361 "and should not be used. "
9362 "Try taking another online backup.")));
9392 if (backup_stopped_in_recovery)
9404 if (
state->startpoint <= recptr)
9406 (
errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
9407 errmsg(
"WAL generated with \"full_page_writes=off\" was replayed "
9408 "during online backup"),
9409 errhint(
"This means that the backup being taken on the standby "
9410 "is corrupt and should not be used. "
9411 "Enable \"full_page_writes\" and run CHECKPOINT on the primary, "
9412 "and then try an online backup again.")));
9429 sizeof(
state->startpoint));
9456 errmsg(
"could not create file \"%s\": %m",
9461 fprintf(fp,
"%s", history_file);
9462 pfree(history_file);
9464 if (fflush(fp) || ferror(fp) ||
FreeFile(fp))
9467 errmsg(
"could not write file \"%s\": %m",
9500 if (waitforarchive &&
9512 seconds_before_warning = 60;
9520 if (!reported_waiting && waits > 5)
9523 (
errmsg(
"base backup done, waiting for required WAL segments to be archived")));
9524 reported_waiting =
true;
9530 WAIT_EVENT_BACKUP_WAIT_WAL_ARCHIVE);
9533 if (++waits >= seconds_before_warning)
9535 seconds_before_warning *= 2;
9537 (
errmsg(
"still waiting for all required WAL segments to be archived (%d seconds elapsed)",
9539 errhint(
"Check that your \"archive_command\" is executing properly. "
9540 "You can safely cancel this backup, "
9541 "but the database backup will not be usable without all the WAL segments.")));
9546 (
errmsg(
"all required WAL segments have been archived")));
9548 else if (waitforarchive)
9550 (
errmsg(
"WAL archiving is not enabled; you must ensure that all required WAL segments are copied through other means to complete the backup")));
9587 if (!during_backup_start)
9589 errmsg(
"aborting backup due to backend exiting before pg_backup_stop was called"));
9600 static bool already_done =
false;
9605 already_done =
true;
9618 current_bytepos =
Insert->CurrBytePos;
Datum idx(PG_FUNCTION_ARGS)
static void pg_atomic_write_u64(volatile pg_atomic_uint64 *ptr, uint64 val)
#define pg_memory_barrier()
static bool pg_atomic_compare_exchange_u64(volatile pg_atomic_uint64 *ptr, uint64 *expected, uint64 newval)
#define pg_read_barrier()
static uint64 pg_atomic_read_membarrier_u64(volatile pg_atomic_uint64 *ptr)
#define pg_write_barrier()
static uint64 pg_atomic_monotonic_advance_u64(volatile pg_atomic_uint64 *ptr, uint64 target)
static uint64 pg_atomic_fetch_add_u64(volatile pg_atomic_uint64 *ptr, int64 add_)
static void pg_atomic_init_u64(volatile pg_atomic_uint64 *ptr, uint64 val)
static void pg_atomic_write_membarrier_u64(volatile pg_atomic_uint64 *ptr, uint64 val)
static uint64 pg_atomic_read_u64(volatile pg_atomic_uint64 *ptr)
TimeLineID findNewestTimeLine(TimeLineID startTLI)
void restoreTimeLineHistoryFiles(TimeLineID begin, TimeLineID end)
void writeTimeLineHistory(TimeLineID newTLI, TimeLineID parentTLI, XLogRecPtr switchpoint, char *reason)
void startup_progress_timeout_handler(void)
long TimestampDifferenceMilliseconds(TimestampTz start_time, TimestampTz stop_time)
bool TimestampDifferenceExceeds(TimestampTz start_time, TimestampTz stop_time, int msec)
TimestampTz GetCurrentTimestamp(void)
const char * timestamptz_to_str(TimestampTz t)
Datum now(PG_FUNCTION_ARGS)
static bool backup_started_in_recovery
void CheckPointBuffers(int flags)
void UnlockReleaseBuffer(Buffer buffer)
#define pg_attribute_unused()
#define TYPEALIGN(ALIGNVAL, LEN)
#define pg_attribute_always_inline
#define MemSet(start, val, len)
#define CATALOG_VERSION_NO
void AbsorbSyncRequests(void)
double CheckPointCompletionTarget
void RequestCheckpoint(int flags)
void CheckPointCLOG(void)
void StartupCommitTs(void)
void CommitTsParameterChange(bool newvalue, bool oldvalue)
bool track_commit_timestamp
void CompleteCommitTsInitialization(void)
void BootStrapCommitTs(void)
void SetCommitTsLimit(TransactionId oldestXact, TransactionId newestXact)
void CheckPointCommitTs(void)
bool ConditionVariableCancelSleep(void)
void ConditionVariableBroadcast(ConditionVariable *cv)
void ConditionVariableInit(ConditionVariable *cv)
void ConditionVariableSleep(ConditionVariable *cv, uint32 wait_event_info)
void update_controlfile(const char *DataDir, ControlFileData *ControlFile, bool do_sync)
#define fprintf(file, fmt, msg)
int errmsg_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
int errmsg_internal(const char *fmt,...)
int errcode_for_file_access(void)
int errdetail(const char *fmt,...)
int errhint(const char *fmt,...)
int errcode(int sqlerrcode)
int errmsg(const char *fmt,...)
#define ereport(elevel,...)
struct pg_atomic_uint64 pg_atomic_uint64
int MakePGDirectory(const char *directoryName)
int pg_fsync_no_writethrough(int fd)
int durable_rename(const char *oldfile, const char *newfile, int elevel)
int CloseTransientFile(int fd)
int BasicOpenFile(const char *fileName, int fileFlags)
int pg_fsync_writethrough(int fd)
void ReleaseExternalFD(void)
int data_sync_elevel(int elevel)
static void Insert(File file)
DIR * AllocateDir(const char *dirname)
int durable_unlink(const char *fname, int elevel)
void ReserveExternalFD(void)
struct dirent * ReadDir(DIR *dir, const char *dirname)
FILE * AllocateFile(const char *name, const char *mode)
int OpenTransientFile(const char *fileName, int fileFlags)
void SyncDataDirectory(void)
#define IO_DIRECT_WAL_INIT
ssize_t pg_pwrite_zeros(int fd, size_t size, off_t offset)
PGFileType get_dirent_type(const char *path, const struct dirent *de, bool look_through_symlinks, int elevel)
volatile uint32 CritSectionCount
bool IsPostmasterEnvironment
int set_config_option_ext(const char *name, const char *value, GucContext context, GucSource source, Oid srole, GucAction action, bool changeVal, int elevel, bool is_reload)
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
void * guc_malloc(int elevel, size_t size)
struct config_generic * find_option(const char *name, bool create_placeholders, bool skip_errors, int elevel)
#define GUC_check_errdetail
Assert(PointerIsAligned(start, uint64))
#define TOAST_MAX_CHUNK_SIZE
#define INJECTION_POINT(name)
void before_shmem_exit(pg_on_exit_callback function, Datum arg)
#define PG_ENSURE_ERROR_CLEANUP(cleanup_function, arg)
#define PG_END_ENSURE_ERROR_CLEANUP(cleanup_function, arg)
if(TABLE==NULL||TABLE_index==NULL)
void SetLatch(Latch *latch)
void ResetLatch(Latch *latch)
int WaitLatch(Latch *latch, int wakeEvents, long timeout, uint32 wait_event_info)
List * lappend(List *list, void *datum)
void list_free(List *list)
void LWLockUpdateVar(LWLock *lock, pg_atomic_uint64 *valptr, uint64 val)
void LWLockReleaseClearVar(LWLock *lock, pg_atomic_uint64 *valptr, uint64 val)
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
bool LWLockWaitForVar(LWLock *lock, pg_atomic_uint64 *valptr, uint64 oldval, uint64 *newval)
void LWLockRelease(LWLock *lock)
void LWLockInitialize(LWLock *lock, int tranche_id)
bool LWLockConditionalAcquire(LWLock *lock, LWLockMode mode)
bool LWLockAcquireOrWait(LWLock *lock, LWLockMode mode)
char * pstrdup(const char *in)
void pfree(void *pointer)
MemoryContext TopMemoryContext
void MemoryContextAllowInCriticalSection(MemoryContext context, bool allow)
#define AllocSetContextCreate
#define ALLOCSET_DEFAULT_SIZES
#define IsBootstrapProcessingMode()
#define START_CRIT_SECTION()
#define CHECK_FOR_INTERRUPTS()
#define END_CRIT_SECTION()
#define AmWalReceiverProcess()
bool process_shared_preload_libraries_done
BackendType MyBackendType
void MultiXactSetNextMXact(MultiXactId nextMulti, MultiXactOffset nextMultiOffset)
void MultiXactAdvanceOldest(MultiXactId oldestMulti, Oid oldestMultiDB)
void MultiXactGetCheckptMulti(bool is_shutdown, MultiXactId *nextMulti, MultiXactOffset *nextMultiOffset, MultiXactId *oldestMulti, Oid *oldestMultiDB)
void SetMultiXactIdLimit(MultiXactId oldest_datminmxid, Oid oldest_datoid, bool is_startup)
void CheckPointMultiXact(void)
void MultiXactAdvanceNextMXact(MultiXactId minMulti, MultiXactOffset minMultiOffset)
void BootStrapMultiXact(void)
void StartupMultiXact(void)
void StartupReplicationOrigin(void)
void CheckPointReplicationOrigin(void)
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
#define ERRCODE_DATA_CORRUPTED
#define DEFAULT_XLOG_SEG_SIZE
#define PG_CACHE_LINE_SIZE
#define FLOATFORMAT_VALUE
#define XLOG_RESTORE_POINT
#define XLOG_CHECKPOINT_REDO
#define PG_CONTROL_VERSION
#define XLOG_OVERWRITE_CONTRECORD
#define XLOG_FPI_FOR_HINT
#define MOCK_AUTH_NONCE_LEN
@ DB_SHUTDOWNED_IN_RECOVERY
#define XLOG_CHECKPOINT_SHUTDOWN
#define PG_CONTROL_FILE_SIZE
#define XLOG_PARAMETER_CHANGE
#define XLOG_CHECKPOINT_ONLINE
#define XLOG_END_OF_RECOVERY
#define COMP_CRC32C(crc, data, len)
#define EQ_CRC32C(c1, c2)
static rewind_source * source
void pgstat_restore_stats(void)
void pgstat_discard_stats(void)
PgStat_CheckpointerStats PendingCheckpointerStats
instr_time pgstat_prepare_io_time(bool track_io_guc)
void pgstat_count_io_op_time(IOObject io_object, IOContext io_context, IOOp io_op, instr_time start_time, uint32 cnt, uint64 bytes)
size_t pg_strftime(char *s, size_t maxsize, const char *format, const struct pg_tm *t)
struct pg_tm * pg_localtime(const pg_time_t *timep, const pg_tz *tz)
PGDLLIMPORT pg_tz * log_timezone
bool pg_strong_random(void *buf, size_t len)
int pg_strcasecmp(const char *s1, const char *s2)
size_t strlcpy(char *dst, const char *src, size_t siz)
static bool DatumGetBool(Datum X)
void CheckPointPredicate(void)
static int fd(const char *x, int i)
#define GetPGProcByNumber(n)
#define DELAY_CHKPT_START
#define DELAY_CHKPT_COMPLETE
bool MinimumActiveBackends(int min)
TransactionId GetOldestActiveTransactionId(void)
TransactionId GetOldestTransactionIdConsideredRunning(void)
bool HaveVirtualXIDsDelayingChkpt(VirtualTransactionId *vxids, int nvxids, int type)
void ProcArrayApplyRecoveryInfo(RunningTransactions running)
void ProcArrayInitRecovery(TransactionId initializedUptoXID)
VirtualTransactionId * GetVirtualXIDsDelayingChkpt(int *nvxids, int type)
#define INVALID_PROC_NUMBER
static void set_ps_display(const char *activity)
void ResetUnloggedRelations(int op)
#define UNLOGGED_RELATION_INIT
#define UNLOGGED_RELATION_CLEANUP
void RelationCacheInitFileRemove(void)
void CheckPointRelationMap(void)
#define relpath(rlocator, forknum)
void StartupReorderBuffer(void)
ResourceOwner CurrentResourceOwner
ResourceOwner AuxProcessResourceOwner
void CheckPointLogicalRewriteHeap(void)
Size add_size(Size s1, Size s2)
Size mul_size(Size s1, Size s2)
void * ShmemInitStruct(const char *name, Size size, bool *foundPtr)
void pg_usleep(long microsec)
void CheckPointReplicationSlots(bool is_shutdown)
void StartupReplicationSlots(void)
bool InvalidateObsoleteReplicationSlots(uint32 possible_causes, XLogSegNo oldestSegno, Oid dboid, TransactionId snapshotConflictHorizon)
void CheckPointSnapBuild(void)
void DeleteAllExportedSnapshotFiles(void)
#define SpinLockInit(lock)
#define SpinLockRelease(lock)
#define SpinLockAcquire(lock)
XLogRecPtr LogStandbySnapshot(void)
void InitRecoveryTransactionEnvironment(void)
void ShutdownRecoveryTransactionEnvironment(void)
void appendStringInfo(StringInfo str, const char *fmt,...)
void appendBinaryStringInfo(StringInfo str, const void *data, int datalen)
void appendStringInfoString(StringInfo str, const char *s)
void appendStringInfoChar(StringInfo str, char ch)
void initStringInfo(StringInfo str)
MultiXactOffset nextMultiOffset
TransactionId newestCommitTsXid
TimeLineID PrevTimeLineID
TimeLineID ThisTimeLineID
TransactionId oldestActiveXid
FullTransactionId nextXid
TransactionId oldestCommitTsXid
uint64 ckpt_agg_sync_time
TimestampTz ckpt_sync_end_t
char mock_authentication_nonce[MOCK_AUTH_NONCE_LEN]
uint32 pg_control_version
XLogRecPtr backupStartPoint
bool track_commit_timestamp
CheckPoint checkPointCopy
XLogRecPtr backupEndPoint
XLogRecPtr minRecoveryPoint
uint32 data_checksum_version
bool default_char_signedness
uint32 catalog_version_no
TimeLineID minRecoveryPointTLI
uint32 toast_max_chunk_size
bool standby_signal_file_found
XLogRecPtr lastPageBeginPtr
char * recoveryStopReason
XLogRecPtr missingContrecPtr
bool recovery_signal_file_found
PgStat_Counter write_time
void(* rm_mask)(char *pagedata, BlockNumber blkno)
TransactionId oldestRunningXid
TransactionId latestCompletedXid
subxids_array_status subxid_status
TransactionId oldestCommitTsXid
TransactionId newestCommitTsXid
FullTransactionId latestCompletedXid
FullTransactionId nextXid
pg_atomic_uint64 insertingAt
XLogRecPtr lastImportantAt
CheckPoint lastCheckPoint
FullTransactionId ckptFullXid
pg_time_t lastSegSwitchTime
pg_atomic_uint64 InitializeReserved
pg_atomic_uint64 InitializedUpTo
XLogRecPtr replicationSlotMinLSN
RecoveryState SharedRecoveryState
TimeLineID InsertTimeLineID
ConditionVariable InitializedUpToCondVar
XLogRecPtr lastSegSwitchLSN
XLogSegNo lastRemovedSegNo
pg_atomic_uint64 * xlblocks
pg_atomic_uint64 logWriteResult
XLogRecPtr lastCheckPointRecPtr
XLogRecPtr lastFpwDisableRecPtr
bool InstallXLogFileSegmentActive
XLogRecPtr lastCheckPointEndPtr
pg_atomic_uint64 logFlushResult
pg_atomic_uint64 logInsertResult
XLogRecPtr InitializedFrom
TimeLineID PrevTimeLineID
pg_atomic_uint64 unloggedLSN
WALInsertLockPadded * WALInsertLocks
char pad[PG_CACHE_LINE_SIZE]
XLogRecPtr lastBackupStart
DecodedXLogRecord * record
struct XLogRecData * next
TimeLineID PrevTimeLineID
TimeLineID ThisTimeLineID
TimestampTz overwrite_time
XLogRecPtr overwritten_lsn
bool track_commit_timestamp
char rp_name[MAXFNAMELEN]
void StartupSUBTRANS(TransactionId oldestActiveXID)
void CheckPointSUBTRANS(void)
void BootStrapSUBTRANS(void)
void TruncateSUBTRANS(TransactionId oldestXact)
void ProcessSyncRequests(void)
void SyncPreCheckpoint(void)
void SyncPostCheckpoint(void)
TimeoutId RegisterTimeout(TimeoutId id, timeout_handler_proc handler)
@ STARTUP_PROGRESS_TIMEOUT
bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
#define TransactionIdRetreat(dest)
#define InvalidTransactionId
static void FullTransactionIdRetreat(FullTransactionId *dest)
#define XidFromFullTransactionId(x)
#define FirstGenbkiObjectId
#define FirstNormalTransactionId
#define TransactionIdIsValid(xid)
static FullTransactionId FullTransactionIdFromEpochAndXid(uint32 epoch, TransactionId xid)
#define TransactionIdIsNormal(xid)
#define FullTransactionIdPrecedes(a, b)
void RecoverPreparedTransactions(void)
void restoreTwoPhaseData(void)
TransactionId PrescanPreparedTransactions(TransactionId **xids_p, int *nxids_p)
void StandbyRecoverPreparedTransactions(void)
void CheckPointTwoPhase(XLogRecPtr redo_horizon)
char pad[PG_CACHE_LINE_SIZE]
bool SplitIdentifierString(char *rawstring, char separator, List **namelist)
void SetTransactionIdLimit(TransactionId oldest_datfrozenxid, Oid oldest_datoid)
void AdvanceOldestClogXid(TransactionId oldest_datfrozenxid)
TransamVariablesData * TransamVariables
static void pgstat_report_wait_start(uint32 wait_event_info)
static void pgstat_report_wait_end(void)
#define WL_EXIT_ON_PM_DEATH
static TimestampTz wakeup[NUM_WALRCV_WAKEUPS]
XLogRecPtr GetWalRcvFlushRecPtr(XLogRecPtr *latestChunkStart, TimeLineID *receiveTLI)
void ShutdownWalRcv(void)
void WalSndWakeup(bool physical, bool logical)
void WalSndInitStopping(void)
void WalSndWaitStopping(void)
static void WalSndWakeupProcessRequests(bool physical, bool logical)
#define WalSndWakeupRequest()
void WaitForWalSummarization(XLogRecPtr lsn)
void WakeupWalSummarizer(void)
XLogRecPtr GetOldestUnsummarizedLSN(TimeLineID *tli, bool *lsn_is_exact)
#define readlink(path, buf, size)
int gettimeofday(struct timeval *tp, void *tzp)
void MarkSubxactTopXidLogged(void)
void MarkCurrentTransactionIdLoggedIfAny(void)
int XLogFileInit(XLogSegNo logsegno, TimeLineID logtli)
void assign_wal_sync_method(int new_wal_sync_method, void *extra)
static void CreateEndOfRecoveryRecord(void)
uint64 GetSystemIdentifier(void)
int wal_decode_buffer_size
XLogRecPtr ProcLastRecPtr
static XLogCtlData * XLogCtl
void UpdateFullPageWrites(void)
bool RecoveryInProgress(void)
static void CleanupBackupHistory(void)
void GetFullPageWriteInfo(XLogRecPtr *RedoRecPtr_p, bool *doPageWrites_p)
TimeLineID GetWALInsertionTimeLine(void)
bool check_max_slot_wal_keep_size(int *newval, void **extra, GucSource source)
XLogRecPtr RequestXLogSwitch(bool mark_unimportant)
void do_pg_abort_backup(int code, Datum arg)
XLogSegNo XLogGetLastRemovedSegno(void)
static char * str_time(pg_time_t tnow)
char * XLogArchiveCommand
struct XLogCtlInsert XLogCtlInsert
Size WALReadFromBuffers(char *dstbuf, XLogRecPtr startptr, Size count, TimeLineID tli)
static XLogRecPtr WaitXLogInsertionsToFinish(XLogRecPtr upto)
static void WALInsertLockRelease(void)
static XLogRecPtr XLogBytePosToRecPtr(uint64 bytepos)
static void WALInsertLockUpdateInsertingAt(XLogRecPtr insertingAt)
XLogRecPtr GetRedoRecPtr(void)
void assign_wal_consistency_checking(const char *newval, void *extra)
static void InitControlFile(uint64 sysidentifier, uint32 data_checksum_version)
void SetInstallXLogFileSegmentActive(void)
static void AdvanceXLInsertBuffer(XLogRecPtr upto, TimeLineID tli, bool opportunistic)
static void WALInsertLockAcquireExclusive(void)
static void UpdateControlFile(void)
bool IsInstallXLogFileSegmentActive(void)
void BootStrapXLOG(uint32 data_checksum_version)
XLogRecPtr XactLastRecEnd
bool CreateRestartPoint(int flags)
static void ValidateXLOGDirectoryStructure(void)
static void RemoveOldXlogFiles(XLogSegNo segno, XLogRecPtr lastredoptr, XLogRecPtr endptr, TimeLineID insertTLI)
static XLogRecPtr CreateOverwriteContrecordRecord(XLogRecPtr aborted_lsn, XLogRecPtr pagePtr, TimeLineID newTLI)
XLogRecPtr GetInsertRecPtr(void)
static void CalculateCheckpointSegments(void)
SessionBackupState get_backup_status(void)
static void XLogReportParameters(void)
#define RefreshXLogWriteResult(_target)
void CheckXLogRemoved(XLogSegNo segno, TimeLineID tli)
static void LogCheckpointStart(int flags, bool restartpoint)
static XLogRecPtr RedoRecPtr
void assign_checkpoint_completion_target(double newval, void *extra)
static XLogRecPtr XLogGetReplicationSlotMinimumLSN(void)
XLogRecPtr XLogInsertRecord(XLogRecData *rdata, XLogRecPtr fpw_lsn, uint8 flags, int num_fpi, bool topxid_included)
static bool InstallXLogFileSegment(XLogSegNo *segno, char *tmppath, bool find_free, XLogSegNo max_segno, TimeLineID tli)
static void WriteControlFile(void)
struct XLogwrtResult XLogwrtResult
WALAvailability GetWALAvailability(XLogRecPtr targetLSN)
const char * show_archive_command(void)
#define UsableBytesInPage
void ShutdownXLOG(int code, Datum arg)
bool DataChecksumsEnabled(void)
static bool PerformRecoveryXLogAction(void)
RecoveryState GetRecoveryState(void)
static void CleanupAfterArchiveRecovery(TimeLineID EndOfLogTLI, XLogRecPtr EndOfLog, TimeLineID newTLI)
#define ConvertToXSegs(x, segsize)
static void RemoveXlogFile(const struct dirent *segment_de, XLogSegNo recycleSegNo, XLogSegNo *endlogSegNo, TimeLineID insertTLI)
pg_time_t GetLastSegSwitchData(XLogRecPtr *lastSwitchLSN)
static int XLOGChooseNumBuffers(void)
static XLogRecPtr XLogBytePosToEndRecPtr(uint64 bytepos)
static int get_sync_bit(int method)
static XLogwrtResult LogwrtResult
void XLogSetReplicationSlotMinimumLSN(XLogRecPtr lsn)
static void LogCheckpointEnd(bool restartpoint)
union WALInsertLockPadded WALInsertLockPadded
void SwitchIntoArchiveRecovery(XLogRecPtr EndRecPtr, TimeLineID replayTLI)
static bool lastFullPageWrites
char * wal_consistency_checking_string
static void WALInsertLockAcquire(void)
static void CopyXLogRecordToWAL(int write_len, bool isLogSwitch, XLogRecData *rdata, XLogRecPtr StartPos, XLogRecPtr EndPos, TimeLineID tli)
bool GetDefaultCharSignedness(void)
static double CheckPointDistanceEstimate
static uint64 XLogRecPtrToBytePos(XLogRecPtr ptr)
const char * show_in_hot_standby(void)
XLogRecPtr GetXLogInsertRecPtr(void)
void SetWalWriterSleeping(bool sleeping)
static void XLogInitNewTimeline(TimeLineID endTLI, XLogRecPtr endOfLog, TimeLineID newTLI)
static void CheckRequiredParameterValues(void)
#define XLogRecPtrToBufIdx(recptr)
int XLogFileOpen(XLogSegNo segno, TimeLineID tli)
int max_slot_wal_keep_size_mb
XLogRecPtr GetFlushRecPtr(TimeLineID *insertTLI)
static void PreallocXlogFiles(XLogRecPtr endptr, TimeLineID tli)
static bool holdingAllLocks
static TimeLineID openLogTLI
XLogRecPtr XactLastCommitEnd
WalLevel GetActiveWalLevelOnStandby(void)
static void KeepLogSeg(XLogRecPtr recptr, XLogSegNo *logSegNo)
static void XLogWrite(XLogwrtRqst WriteRqst, TimeLineID tli, bool flexible)
void InitializeWalConsistencyChecking(void)
static void UpdateMinRecoveryPoint(XLogRecPtr lsn, bool force)
static int LocalSetXLogInsertAllowed(void)
void assign_max_wal_size(int newval, void *extra)
void RemoveNonParentXlogFiles(XLogRecPtr switchpoint, TimeLineID newTLI)
XLogRecPtr GetLastImportantRecPtr(void)
void xlog_redo(XLogReaderState *record)
static void RecoveryRestartPoint(const CheckPoint *checkPoint, XLogReaderState *record)
bool XLogNeedsFlush(XLogRecPtr record)
void register_persistent_abort_backup_handler(void)
static double PrevCheckPointDistance
void ReachedEndOfBackup(XLogRecPtr EndRecPtr, TimeLineID tli)
void LocalProcessControlFile(bool reset)
static void XLogFileClose(void)
static void UpdateCheckPointDistanceEstimate(uint64 nbytes)
static bool LocalRecoveryInProgress
XLogSegNo XLogGetOldestSegno(TimeLineID tli)
XLogRecPtr GetXLogWriteRecPtr(void)
static WALInsertLockPadded * WALInsertLocks
static XLogSegNo openLogSegNo
#define INSERT_FREESPACE(endptr)
int wal_retrieve_retry_interval
bool XLogBackgroundFlush(void)
const struct config_enum_entry archive_mode_options[]
void GetOldestRestartPoint(XLogRecPtr *oldrecptr, TimeLineID *oldtli)
char * GetMockAuthenticationNonce(void)
static XLogSegNo XLOGfileslop(XLogRecPtr lastredoptr)
static int UsableBytesInSegment
static char * GetXLogBuffer(XLogRecPtr ptr, TimeLineID tli)
@ WALINSERT_SPECIAL_SWITCH
@ WALINSERT_SPECIAL_CHECKPOINT
bool XLogInsertAllowed(void)
void do_pg_backup_start(const char *backupidstr, bool fast, List **tablespaces, BackupState *state, StringInfo tblspcmapfile)
static ControlFileData * ControlFile
bool check_wal_segment_size(int *newval, void **extra, GucSource source)
static void XLogFileCopy(TimeLineID destTLI, XLogSegNo destsegno, TimeLineID srcTLI, XLogSegNo srcsegno, int upto)
static int LocalXLogInsertAllowed
static void RemoveTempXlogFiles(void)
XLogRecPtr XLogRestorePoint(const char *rpName)
static XLogRecPtr LocalMinRecoveryPoint
#define NUM_XLOGINSERT_LOCKS
struct XLogwrtRqst XLogwrtRqst
TimeLineID GetWALInsertionTimeLineIfSet(void)
void do_pg_backup_stop(BackupState *state, bool waitforarchive)
bool check_wal_consistency_checking(char **newval, void **extra, GucSource source)
const struct config_enum_entry wal_sync_method_options[]
bool CreateCheckPoint(int flags)
#define BootstrapTimeLineID
CheckpointStatsData CheckpointStats
bool check_wal_buffers(int *newval, void **extra, GucSource source)
XLogRecPtr GetFakeLSNForUnloggedRel(void)
void XLogPutNextOid(Oid nextOid)
void XLogFlush(XLogRecPtr record)
static void ReadControlFile(void)
static SessionBackupState sessionBackupState
static void CheckPointGuts(XLogRecPtr checkPointRedo, int flags)
static bool updateMinRecoveryPoint
static bool check_wal_consistency_checking_deferred
static void ReserveXLogInsertLocation(int size, XLogRecPtr *StartPos, XLogRecPtr *EndPos, XLogRecPtr *PrevPtr)
void XLogShutdownWalRcv(void)
static void UpdateLastRemovedPtr(char *filename)
static TimeLineID LocalMinRecoveryPointTLI
void issue_xlog_fsync(int fd, XLogSegNo segno, TimeLineID tli)
struct XLogCtlData XLogCtlData
static bool ReserveXLogSwitch(XLogRecPtr *StartPos, XLogRecPtr *EndPos, XLogRecPtr *PrevPtr)
void XLogSetAsyncXactLSN(XLogRecPtr asyncXactLSN)
bool XLogCheckpointNeeded(XLogSegNo new_segno)
bool * wal_consistency_checking
static int XLogFileInitInternal(XLogSegNo logsegno, TimeLineID logtli, bool *added, char *path)
static void update_checkpoint_display(int flags, bool restartpoint, bool reset)
#define XLogArchivingActive()
#define TABLESPACE_MAP_OLD
#define XLOG_MARK_UNIMPORTANT
#define STANDBY_SIGNAL_FILE
#define CHECKPOINT_CAUSE_XLOG
#define CHECKPOINT_END_OF_RECOVERY
#define CHECKPOINT_FLUSH_ALL
#define BACKUP_LABEL_FILE
#define CHECKPOINT_CAUSE_TIME
#define RECOVERY_SIGNAL_FILE
#define CHECKPOINT_IS_SHUTDOWN
#define XLogArchivingAlways()
#define CHECKPOINT_IMMEDIATE
@ WAL_SYNC_METHOD_FDATASYNC
@ WAL_SYNC_METHOD_FSYNC_WRITETHROUGH
@ WAL_SYNC_METHOD_OPEN_DSYNC
#define XLogStandbyInfoActive()
#define XLP_FIRST_IS_CONTRECORD
static RmgrData GetRmgr(RmgrId rmid)
#define IsValidWalSegSize(size)
XLogLongPageHeaderData * XLogLongPageHeader
#define XLP_FIRST_IS_OVERWRITE_CONTRECORD
#define XLOG_CONTROL_FILE
#define XLogSegmentOffset(xlogptr, wal_segsz_bytes)
static bool IsXLogFileName(const char *fname)
static void XLogFromFileName(const char *fname, TimeLineID *tli, XLogSegNo *logSegNo, int wal_segsz_bytes)
#define XLByteToPrevSeg(xlrp, logSegNo, wal_segsz_bytes)
#define XLogSegNoOffsetToRecPtr(segno, offset, wal_segsz_bytes, dest)
XLogPageHeaderData * XLogPageHeader
static bool IsBackupHistoryFileName(const char *fname)
#define XLP_BKP_REMOVABLE
#define XLByteToSeg(xlrp, logSegNo, wal_segsz_bytes)
static void BackupHistoryFileName(char *fname, TimeLineID tli, XLogSegNo logSegNo, XLogRecPtr startpoint, int wal_segsz_bytes)
static void XLogFilePath(char *path, TimeLineID tli, XLogSegNo logSegNo, int wal_segsz_bytes)
#define XRecOffIsValid(xlrp)
#define SizeOfXLogShortPHD
#define SizeOfXLogLongPHD
static void XLogFileName(char *fname, TimeLineID tli, XLogSegNo logSegNo, int wal_segsz_bytes)
static void BackupHistoryFilePath(char *path, TimeLineID tli, XLogSegNo logSegNo, XLogRecPtr startpoint, int wal_segsz_bytes)
static bool RmgrIdExists(RmgrId rmid)
#define XLByteInPrevSeg(xlrp, logSegNo, wal_segsz_bytes)
static bool IsPartialXLogFileName(const char *fname)
bool XLogArchiveIsReadyOrDone(const char *xlog)
bool XLogArchiveIsBusy(const char *xlog)
bool XLogArchiveIsReady(const char *xlog)
void XLogArchiveNotifySeg(XLogSegNo segno, TimeLineID tli)
void ExecuteRecoveryCommand(const char *command, const char *commandName, bool failOnSignal, uint32 wait_event_info)
bool XLogArchiveCheckDone(const char *xlog)
void XLogArchiveNotify(const char *xlog)
void XLogArchiveCleanup(const char *xlog)
char * build_backup_content(BackupState *state, bool ishistoryfile)
#define LSN_FORMAT_ARGS(lsn)
#define FirstNormalUnloggedLSN
#define XLogRecPtrIsInvalid(r)
#define InvalidXLogRecPtr
#define DEFAULT_WAL_SYNC_METHOD
XLogRecPtr XLogInsert(RmgrId rmid, uint8 info)
void XLogRegisterData(const void *data, uint32 len)
void XLogSetRecordFlags(uint8 flags)
void XLogBeginInsert(void)
XLogReaderState * XLogReaderAllocate(int wal_segment_size, const char *waldir, XLogReaderRoutine *routine, void *private_data)
bool DecodeXLogRecord(XLogReaderState *state, DecodedXLogRecord *decoded, XLogRecord *record, XLogRecPtr lsn, char **errormsg)
size_t DecodeXLogRecordRequiredSpace(size_t xl_tot_len)
#define XLogRecGetInfo(decoder)
#define XLogRecGetData(decoder)
#define XLogRecMaxBlockId(decoder)
#define XLogRecHasBlockImage(decoder, block_id)
#define XLogRecHasAnyBlockRefs(decoder)
#define SizeOfXLogRecordDataHeaderShort
#define XLR_BLOCK_ID_DATA_SHORT
void ShutdownWalRecovery(void)
bool ArchiveRecoveryRequested
void RecoveryRequiresIntParameter(const char *param_name, int currValue, int minValue)
void PerformWalRecovery(void)
char * archiveCleanupCommand
XLogRecPtr GetCurrentReplayRecPtr(TimeLineID *replayEndTLI)
void xlog_outdesc(StringInfo buf, XLogReaderState *record)
bool PromoteIsTriggered(void)
static XLogRecPtr missingContrecPtr
XLogRecPtr GetXLogReplayRecPtr(TimeLineID *replayTLI)
static XLogRecPtr abortedRecPtr
EndOfWalRecoveryInfo * FinishWalRecovery(void)
void InitWalRecovery(ControlFileData *ControlFile, bool *wasShutdown_ptr, bool *haveBackupLabel_ptr, bool *haveTblspcMap_ptr)
char * recoveryEndCommand
TimeLineID recoveryTargetTLI
TimestampTz GetLatestXTime(void)
bool XLogHaveInvalidPages(void)
XLogRedoAction XLogReadBufferForRedo(XLogReaderState *record, uint8 block_id, Buffer *buf)
HotStandbyState standbyState