PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
xlog.h
Go to the documentation of this file.
1 /*
2  * xlog.h
3  *
4  * PostgreSQL transaction log manager
5  *
6  * Portions Copyright (c) 1996-2014, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  * src/include/access/xlog.h
10  */
11 #ifndef XLOG_H
12 #define XLOG_H
13 
14 #include "access/rmgr.h"
15 #include "access/xlogdefs.h"
16 #include "datatype/timestamp.h"
17 #include "lib/stringinfo.h"
18 #include "storage/buf.h"
19 #include "utils/pg_crc.h"
20 
21 /*
22  * The overall layout of an XLOG record is:
23  * Fixed-size header (XLogRecord struct)
24  * rmgr-specific data
25  * BkpBlock
26  * backup block data
27  * BkpBlock
28  * backup block data
29  * ...
30  *
31  * where there can be zero to four backup blocks (as signaled by xl_info flag
32  * bits). XLogRecord structs always start on MAXALIGN boundaries in the WAL
33  * files, and we round up SizeOfXLogRecord so that the rmgr data is also
34  * guaranteed to begin on a MAXALIGN boundary. However, no padding is added
35  * to align BkpBlock structs or backup block data.
36  *
37  * NOTE: xl_len counts only the rmgr data, not the XLogRecord header,
38  * and also not any backup blocks. xl_tot_len counts everything. Neither
39  * length field is rounded up to an alignment boundary.
40  */
41 typedef struct XLogRecord
42 {
43  uint32 xl_tot_len; /* total len of entire record */
44  TransactionId xl_xid; /* xact id */
45  uint32 xl_len; /* total len of rmgr data */
46  uint8 xl_info; /* flag bits, see below */
47  RmgrId xl_rmid; /* resource manager for this record */
48  /* 2 bytes of padding here, initialize to zero */
49  XLogRecPtr xl_prev; /* ptr to previous record in log */
50  pg_crc32 xl_crc; /* CRC for this record */
51 
52  /* If MAXALIGN==8, there are 4 wasted bytes here */
53 
54  /* ACTUAL LOG DATA FOLLOWS AT END OF STRUCT */
55 
56 } XLogRecord;
57 
58 #define SizeOfXLogRecord MAXALIGN(sizeof(XLogRecord))
59 
60 #define XLogRecGetData(record) ((char*) (record) + SizeOfXLogRecord)
61 
62 /*
63  * XLOG uses only low 4 bits of xl_info. High 4 bits may be used by rmgr.
64  */
65 #define XLR_INFO_MASK 0x0F
66 
67 /*
68  * If we backed up any disk blocks with the XLOG record, we use flag bits in
69  * xl_info to signal it. We support backup of up to 4 disk blocks per XLOG
70  * record.
71  */
72 #define XLR_BKP_BLOCK_MASK 0x0F /* all info bits used for bkp blocks */
73 #define XLR_MAX_BKP_BLOCKS 4
74 #define XLR_BKP_BLOCK(iblk) (0x08 >> (iblk)) /* iblk in 0..3 */
75 
76 /* Sync methods */
77 #define SYNC_METHOD_FSYNC 0
78 #define SYNC_METHOD_FDATASYNC 1
79 #define SYNC_METHOD_OPEN 2 /* for O_SYNC */
80 #define SYNC_METHOD_FSYNC_WRITETHROUGH 3
81 #define SYNC_METHOD_OPEN_DSYNC 4 /* for O_DSYNC */
82 extern int sync_method;
83 
84 /*
85  * The rmgr data to be written by XLogInsert() is defined by a chain of
86  * one or more XLogRecData structs. (Multiple structs would be used when
87  * parts of the source data aren't physically adjacent in memory, or when
88  * multiple associated buffers need to be specified.)
89  *
90  * If buffer is valid then XLOG will check if buffer must be backed up
91  * (ie, whether this is first change of that page since last checkpoint).
92  * If so, the whole page contents are attached to the XLOG record, and XLOG
93  * sets XLR_BKP_BLOCK(N) bit in xl_info. Note that the buffer must be pinned
94  * and exclusive-locked by the caller, so that it won't change under us.
95  * NB: when the buffer is backed up, we DO NOT insert the data pointed to by
96  * this XLogRecData struct into the XLOG record, since we assume it's present
97  * in the buffer. Therefore, rmgr redo routines MUST pay attention to
98  * XLR_BKP_BLOCK(N) to know what is actually stored in the XLOG record.
99  * The N'th XLR_BKP_BLOCK bit corresponds to the N'th distinct buffer
100  * value (ignoring InvalidBuffer) appearing in the rdata chain.
101  *
102  * When buffer is valid, caller must set buffer_std to indicate whether the
103  * page uses standard pd_lower/pd_upper header fields. If this is true, then
104  * XLOG is allowed to omit the free space between pd_lower and pd_upper from
105  * the backed-up page image. Note that even when buffer_std is false, the
106  * page MUST have an LSN field as its first eight bytes!
107  *
108  * Note: data can be NULL to indicate no rmgr data associated with this chain
109  * entry. This can be sensible (ie, not a wasted entry) if buffer is valid.
110  * The implication is that the buffer has been changed by the operation being
111  * logged, and so may need to be backed up, but the change can be redone using
112  * only information already present elsewhere in the XLOG entry.
113  */
114 typedef struct XLogRecData
115 {
116  char *data; /* start of rmgr data to include */
117  uint32 len; /* length of rmgr data to include */
118  Buffer buffer; /* buffer associated with data, if any */
119  bool buffer_std; /* buffer has standard pd_lower/pd_upper */
120  struct XLogRecData *next; /* next struct in chain, or NULL */
121 } XLogRecData;
122 
123 extern PGDLLIMPORT TimeLineID ThisTimeLineID; /* current TLI */
124 
125 /*
126  * Prior to 8.4, all activity during recovery was carried out by the startup
127  * process. This local variable continues to be used in many parts of the
128  * code to indicate actions taken by RecoveryManagers. Other processes that
129  * potentially perform work during recovery should check RecoveryInProgress().
130  * See XLogCtl notes in xlog.c.
131  */
132 extern bool InRecovery;
133 
134 /*
135  * Like InRecovery, standbyState is only valid in the startup process.
136  * In all other processes it will have the value STANDBY_DISABLED (so
137  * InHotStandby will read as FALSE).
138  *
139  * In DISABLED state, we're performing crash recovery or hot standby was
140  * disabled in postgresql.conf.
141  *
142  * In INITIALIZED state, we've run InitRecoveryTransactionEnvironment, but
143  * we haven't yet processed a RUNNING_XACTS or shutdown-checkpoint WAL record
144  * to initialize our master-transaction tracking system.
145  *
146  * When the transaction tracking is initialized, we enter the SNAPSHOT_PENDING
147  * state. The tracked information might still be incomplete, so we can't allow
148  * connections yet, but redo functions must update the in-memory state when
149  * appropriate.
150  *
151  * In SNAPSHOT_READY mode, we have full knowledge of transactions that are
152  * (or were) running in the master at the current WAL location. Snapshots
153  * can be taken, and read-only queries can be run.
154  */
155 typedef enum
156 {
162 
164 
165 #define InHotStandby (standbyState >= STANDBY_SNAPSHOT_PENDING)
166 
167 /*
168  * Recovery target type.
169  * Only set during a Point in Time recovery, not when standby_mode = on
170  */
171 typedef enum
172 {
179 
181 
182 extern bool reachedConsistency;
183 
184 /* these variables are GUC parameters related to XLOG */
185 extern int CheckPointSegments;
186 extern int wal_keep_segments;
187 extern int XLOGbuffers;
188 extern int XLogArchiveTimeout;
189 extern bool XLogArchiveMode;
190 extern char *XLogArchiveCommand;
191 extern bool EnableHotStandby;
192 extern bool fullPageWrites;
193 extern bool wal_log_hints;
194 extern bool log_checkpoints;
195 extern int num_xloginsert_locks;
196 
197 /* WAL levels */
198 typedef enum WalLevel
199 {
204 } WalLevel;
205 extern int wal_level;
206 
207 #define XLogArchivingActive() (XLogArchiveMode && wal_level >= WAL_LEVEL_ARCHIVE)
208 #define XLogArchiveCommandSet() (XLogArchiveCommand[0] != '\0')
209 
210 /*
211  * Is WAL-logging necessary for archival or log-shipping, or can we skip
212  * WAL-logging if we fsync() the data before committing instead?
213  */
214 #define XLogIsNeeded() (wal_level >= WAL_LEVEL_ARCHIVE)
215 
216 /*
217  * Is a full-page image needed for hint bit updates?
218  *
219  * Normally, we don't WAL-log hint bit updates, but if checksums are enabled,
220  * we have to protect them against torn page writes. When you only set
221  * individual bits on a page, it's still consistent no matter what combination
222  * of the bits make it to disk, but the checksum wouldn't match. Also WAL-log
223  * them if forced by wal_log_hints=on.
224  */
225 #define XLogHintBitIsNeeded() (DataChecksumsEnabled() || wal_log_hints)
226 
227 /* Do we need to WAL-log information required only for Hot Standby and logical replication? */
228 #define XLogStandbyInfoActive() (wal_level >= WAL_LEVEL_HOT_STANDBY)
229 
230 /* Do we need to WAL-log information required only for logical replication? */
231 #define XLogLogicalInfoActive() (wal_level >= WAL_LEVEL_LOGICAL)
232 
233 #ifdef WAL_DEBUG
234 extern bool XLOG_DEBUG;
235 #endif
236 
237 /*
238  * OR-able request flag bits for checkpoints. The "cause" bits are used only
239  * for logging purposes. Note: the flags must be defined so that it's
240  * sensible to OR together request flags arising from different requestors.
241  */
242 
243 /* These directly affect the behavior of CreateCheckPoint and subsidiaries */
244 #define CHECKPOINT_IS_SHUTDOWN 0x0001 /* Checkpoint is for shutdown */
245 #define CHECKPOINT_END_OF_RECOVERY 0x0002 /* Like shutdown checkpoint,
246  * but issued at end of WAL
247  * recovery */
248 #define CHECKPOINT_IMMEDIATE 0x0004 /* Do it without delays */
249 #define CHECKPOINT_FORCE 0x0008 /* Force even if no activity */
250 /* These are important to RequestCheckpoint */
251 #define CHECKPOINT_WAIT 0x0010 /* Wait for completion */
252 /* These indicate the cause of a checkpoint request */
253 #define CHECKPOINT_CAUSE_XLOG 0x0020 /* XLOG consumption */
254 #define CHECKPOINT_CAUSE_TIME 0x0040 /* Elapsed time */
256 /* Checkpoint statistics */
257 typedef struct CheckpointStatsData
258 {
259  TimestampTz ckpt_start_t; /* start of checkpoint */
260  TimestampTz ckpt_write_t; /* start of flushing buffers */
261  TimestampTz ckpt_sync_t; /* start of fsyncs */
262  TimestampTz ckpt_sync_end_t; /* end of fsyncs */
263  TimestampTz ckpt_end_t; /* end of checkpoint */
264 
265  int ckpt_bufs_written; /* # of buffers written */
267  int ckpt_segs_added; /* # of new xlog segments created */
268  int ckpt_segs_removed; /* # of xlog segments deleted */
269  int ckpt_segs_recycled; /* # of xlog segments recycled */
271  int ckpt_sync_rels; /* # of relations synced */
272  uint64 ckpt_longest_sync; /* Longest sync for one relation */
273  uint64 ckpt_agg_sync_time; /* The sum of all the individual sync
274  * times, which is not necessarily the
275  * same as the total elapsed time for
276  * the entire sync phase. */
278 
280 
281 extern XLogRecPtr XLogInsert(RmgrId rmid, uint8 info, XLogRecData *rdata);
282 extern bool XLogCheckBufferNeedsBackup(Buffer buffer);
283 extern void XLogFlush(XLogRecPtr RecPtr);
284 extern bool XLogBackgroundFlush(void);
285 extern bool XLogNeedsFlush(XLogRecPtr RecPtr);
286 extern int XLogFileInit(XLogSegNo segno, bool *use_existent, bool use_lock);
287 extern int XLogFileOpen(XLogSegNo segno);
288 
289 extern XLogRecPtr XLogSaveBufferForHint(Buffer buffer, bool buffer_std);
290 
291 extern void CheckXLogRemoved(XLogSegNo segno, TimeLineID tli);
293 extern void XLogSetAsyncXactLSN(XLogRecPtr record);
295 
296 extern Buffer RestoreBackupBlock(XLogRecPtr lsn, XLogRecord *record,
297  int block_index,
298  bool get_cleanup_lock, bool keep_buffer);
299 
300 extern void xlog_redo(XLogRecPtr lsn, XLogRecord *record);
301 extern void xlog_desc(StringInfo buf, uint8 xl_info, char *rec);
302 
303 extern void issue_xlog_fsync(int fd, XLogSegNo segno);
304 
305 extern bool RecoveryInProgress(void);
306 extern bool HotStandbyActive(void);
307 extern bool HotStandbyActiveInReplay(void);
308 extern bool XLogInsertAllowed(void);
309 extern void GetXLogReceiptTime(TimestampTz *rtime, bool *fromStream);
310 extern XLogRecPtr GetXLogReplayRecPtr(TimeLineID *replayTLI);
311 extern XLogRecPtr GetXLogInsertRecPtr(void);
312 extern XLogRecPtr GetXLogWriteRecPtr(void);
313 extern bool RecoveryIsPaused(void);
314 extern void SetRecoveryPause(bool recoveryPause);
315 extern TimestampTz GetLatestXTime(void);
317 extern char *XLogFileNameP(TimeLineID tli, XLogSegNo segno);
318 
319 extern void UpdateControlFile(void);
320 extern uint64 GetSystemIdentifier(void);
321 extern bool DataChecksumsEnabled(void);
323 extern Size XLOGShmemSize(void);
324 extern void XLOGShmemInit(void);
325 extern void BootStrapXLOG(void);
326 extern void StartupXLOG(void);
327 extern void ShutdownXLOG(int code, Datum arg);
328 extern void InitXLOGAccess(void);
329 extern void CreateCheckPoint(int flags);
330 extern bool CreateRestartPoint(int flags);
331 extern void XLogPutNextOid(Oid nextOid);
332 extern XLogRecPtr XLogRestorePoint(const char *rpName);
333 extern void UpdateFullPageWrites(void);
334 extern XLogRecPtr GetRedoRecPtr(void);
335 extern XLogRecPtr GetInsertRecPtr(void);
336 extern XLogRecPtr GetFlushRecPtr(void);
337 extern void GetNextXidAndEpoch(TransactionId *xid, uint32 *epoch);
338 
339 extern bool CheckPromoteSignal(void);
340 extern void WakeupRecovery(void);
341 extern void SetWalWriterSleeping(bool sleeping);
342 
343 /*
344  * Starting/stopping a base backup
345  */
346 extern XLogRecPtr do_pg_start_backup(const char *backupidstr, bool fast,
347  TimeLineID *starttli_p, char **labelfile);
348 extern XLogRecPtr do_pg_stop_backup(char *labelfile, bool waitforarchive,
349  TimeLineID *stoptli_p);
350 extern void do_pg_abort_backup(void);
352 /* File path names (all relative to $PGDATA) */
353 #define BACKUP_LABEL_FILE "backup_label"
354 #define BACKUP_LABEL_OLD "backup_label.old"
355 
356 #endif /* XLOG_H */