xlog.c 60.6 KB
Newer Older
1
/*-------------------------------------------------------------------------
2 3 4 5
 *
 * xlog.c
 *
 *
B
Add:  
Bruce Momjian 已提交
6 7
 * Portions Copyright (c) 1996-2000, PostgreSQL, Inc
 * Portions Copyright (c) 1994, Regents of the University of California
8
 *
9
 * $Header: /cvsroot/pgsql/src/backend/access/transam/xlog.c,v 1.50 2001/01/14 05:08:15 tgl Exp $
10 11 12
 *
 *-------------------------------------------------------------------------
 */
13

14 15
#include "postgres.h"

16 17 18 19
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <sys/stat.h>
V
Vadim B. Mikheev 已提交
20
#include <sys/time.h>
V
Vadim B. Mikheev 已提交
21 22
#include <sys/types.h>
#include <dirent.h>
23 24 25
#ifdef USE_LOCALE
#include <locale.h>
#endif
26

27
#include "access/transam.h"
28
#include "access/xact.h"
29
#include "catalog/catversion.h"
30 31 32 33
#include "storage/sinval.h"
#include "storage/proc.h"
#include "storage/spin.h"
#include "storage/s_lock.h"
34
#include "storage/bufpage.h"
V
Vadim B. Mikheev 已提交
35 36
#include "access/xlog.h"
#include "access/xlogutils.h"
37
#include "utils/builtins.h"
38
#include "utils/relcache.h"
39

V
WAL  
Vadim B. Mikheev 已提交
40 41
#include "miscadmin.h"

V
Vadim B. Mikheev 已提交
42
int			XLOGbuffers = 8;
43
int			XLOGfiles = 0;	/* how many files to pre-allocate */
44
XLogRecPtr	MyLastRecPtr = {0, 0};
45
bool		InRecovery = false;
V
WAL  
Vadim B. Mikheev 已提交
46
StartUpID	ThisStartUpID = 0;
47
XLogRecPtr	RedoRecPtr;
V
WAL  
Vadim B. Mikheev 已提交
48

V
Vadim B. Mikheev 已提交
49
int			XLOG_DEBUG = 0;
50

V
Vadim B. Mikheev 已提交
51
/* To read/update control file and create new log file */
52
SPINLOCK	ControlFileLockId;
V
Vadim B. Mikheev 已提交
53 54

/* To generate new xid */
55 56
SPINLOCK	XidGenLockId;

57 58 59
static char		XLogDir[MAXPGPATH];
static char		ControlFilePath[MAXPGPATH];

60
#define MinXLOGbuffers	4
61 62 63

typedef struct XLgwrRqst
{
64 65
	XLogRecPtr	Write;			/* byte (1-based) to write out */
	XLogRecPtr	Flush;			/* byte (1-based) to flush */
66 67 68 69
} XLgwrRqst;

typedef struct XLgwrResult
{
70 71
	XLogRecPtr	Write;			/* bytes written out */
	XLogRecPtr	Flush;			/* bytes flushed */
72 73 74 75
} XLgwrResult;

typedef struct XLogCtlInsert
{
76 77 78 79 80 81
	XLgwrResult		LgwrResult;
	XLogRecPtr		PrevRecord;
	uint16			curridx;		/* current block index in cache */
	XLogPageHeader	currpage;
	char		   *currpos;
	XLogRecPtr		RedoRecPtr;
82 83 84 85
} XLogCtlInsert;

typedef struct XLogCtlWrite
{
86 87
	XLgwrResult LgwrResult;
	uint16		curridx;		/* index of next block to write */
88 89
} XLogCtlWrite;

90

91 92
typedef struct XLogCtlData
{
V
Vadim B. Mikheev 已提交
93 94 95 96 97 98 99 100 101
	XLogCtlInsert	Insert;
	XLgwrRqst		LgwrRqst;
	XLgwrResult		LgwrResult;
	XLogCtlWrite	Write;
	char		   *pages;
	XLogRecPtr	   *xlblocks;		/* 1st byte ptr-s + BLCKSZ */
	uint32			XLogCacheByte;
	uint32			XLogCacheBlck;
	StartUpID		ThisStartUpID;
102
	XLogRecPtr		RedoRecPtr;		/* for postmaster */
V
Vadim B. Mikheev 已提交
103 104 105 106
	slock_t			insert_lck;
	slock_t			info_lck;
	slock_t			lgwr_lck;
	slock_t			chkp_lck;		/* checkpoint lock */
107 108
} XLogCtlData;

109
static XLogCtlData *XLogCtl = NULL;
110

111 112 113 114
/*
 * Contents of pg_control
 */

115 116
typedef enum DBState
{
117 118
	DB_STARTUP = 0,
	DB_SHUTDOWNED,
119 120 121 122 123
	DB_SHUTDOWNING,
	DB_IN_RECOVERY,
	DB_IN_PRODUCTION
} DBState;

124 125
#define LOCALE_NAME_BUFLEN  128

126 127
typedef struct ControlFileData
{
128
	crc64		crc;
129 130 131 132
	uint32		logId;			/* current log file id */
	uint32		logSeg;			/* current log file segment (1-based) */
	XLogRecPtr	checkPoint;		/* last check point record ptr */
	time_t		time;			/* time stamp of last modification */
133
	DBState		state;			/* see enum above */
134 135

	/*
136
	 * this data is used to make sure that configuration of this DB is
137
	 * compatible with the backend executable
138
	 */
139 140 141
	uint32		blcksz;			/* block size for this DB */
	uint32		relseg_size;	/* blocks per segment of large relation */
	uint32		catalog_version_no;		/* internal version number */
142 143 144
	/* active locales --- "C" if compiled without USE_LOCALE: */
	char		lc_collate[LOCALE_NAME_BUFLEN];
	char		lc_ctype[LOCALE_NAME_BUFLEN];
145 146

	/*
147
	 * important directory locations
148
	 */
149
	char		archdir[MAXPGPATH];		/* where to move offline log files */
150 151
} ControlFileData;

152
static ControlFileData *ControlFile = NULL;
153 154 155

typedef struct CheckPoint
{
V
WAL  
Vadim B. Mikheev 已提交
156 157 158 159 160 161 162 163 164 165
	XLogRecPtr		redo;		/* next RecPtr available when we */
								/* began to create CheckPoint */
								/* (i.e. REDO start point) */
	XLogRecPtr		undo;		/* first record of oldest in-progress */
								/* transaction when we started */
								/* (i.e. UNDO end point) */
	StartUpID		ThisStartUpID;
	TransactionId	nextXid;
	Oid				nextOid;
	bool			Shutdown;
166 167
} CheckPoint;

V
WAL  
Vadim B. Mikheev 已提交
168
#define XLOG_CHECKPOINT		0x00
169
#define XLOG_NEXTOID		0x10
V
WAL  
Vadim B. Mikheev 已提交
170

171 172 173 174 175 176 177
typedef struct BkpBlock
{
	crc64			crc;
	RelFileNode		node;
	BlockNumber		block;
} BkpBlock;

178 179
/*
 * We break each log file in 16Mb segments
180
 */
181
#define XLogSegSize		(16*1024*1024)
182 183
#define XLogLastSeg		(0xffffffff / XLogSegSize)
#define XLogFileSize	(XLogLastSeg * XLogSegSize)
184

185 186 187 188 189 190 191 192 193 194 195 196
#define NextLogSeg(_logId, _logSeg)		\
{\
	if (_logSeg >= XLogLastSeg)\
	{\
		_logId++;\
		_logSeg = 0;\
	}\
	else\
		_logSeg++;\
}


197
#define XLogFileName(path, log, seg)	\
198 199
			snprintf(path, MAXPGPATH, "%s%c%08X%08X",	\
					 XLogDir, SEP_CHAR, log, seg)
200

V
Vadim B. Mikheev 已提交
201 202 203 204
#define XLogTempFileName(path, log, seg)	\
			snprintf(path, MAXPGPATH, "%s%cT%08X%08X",	\
					 XLogDir, SEP_CHAR, log, seg)

205
#define PrevBufIdx(curridx)		\
206 207
		((curridx == 0) ? XLogCtl->XLogCacheBlck : (curridx - 1))

208
#define NextBufIdx(curridx)		\
209 210
		((curridx == XLogCtl->XLogCacheBlck) ? 0 : (curridx + 1))

211
#define InitXLBuffer(curridx)	(\
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
				XLogCtl->xlblocks[curridx].xrecoff = \
				(XLogCtl->xlblocks[Insert->curridx].xrecoff == XLogFileSize) ? \
				BLCKSZ : (XLogCtl->xlblocks[Insert->curridx].xrecoff + BLCKSZ), \
				XLogCtl->xlblocks[curridx].xlogid = \
				(XLogCtl->xlblocks[Insert->curridx].xrecoff == XLogFileSize) ? \
				(XLogCtl->xlblocks[Insert->curridx].xlogid + 1) : \
				XLogCtl->xlblocks[Insert->curridx].xlogid, \
				Insert->curridx = curridx, \
				Insert->currpage = (XLogPageHeader) (XLogCtl->pages + curridx * BLCKSZ), \
				Insert->currpos = \
					((char*) Insert->currpage) + SizeOfXLogPHD, \
				Insert->currpage->xlp_magic = XLOG_PAGE_MAGIC, \
				Insert->currpage->xlp_info = 0 \
				)

227
#define XRecOffIsValid(xrecoff) \
228 229 230
		(xrecoff % BLCKSZ >= SizeOfXLogPHD && \
		(BLCKSZ - xrecoff % BLCKSZ) >= SizeOfXLogRecord)

231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
#define _INTL_MAXLOGRECSZ	(3 * MAXLOGRECSZ)

extern uint32	crc_table[];
#define INIT_CRC64(crc)		(crc.crc1 = 0xffffffff, crc.crc2 = 0xffffffff)
#define FIN_CRC64(crc)		(crc.crc1 ^= 0xffffffff, crc.crc2 ^= 0xffffffff)
#define COMP_CRC64(crc, data, len)	\
{\
	uint32		__c1 = crc.crc1;\
	uint32		__c2 = crc.crc2;\
	char	   *__data = data;\
	uint32		__len = len;\
\
	while (__len >= 2)\
	{\
		__c1 = crc_table[(__c1 ^ *__data++) & 0xff] ^ (__c1 >> 8);\
		__c2 = crc_table[(__c2 ^ *__data++) & 0xff] ^ (__c2 >> 8);\
		__len -= 2;\
	}\
	if (__len > 0)\
		__c1 = crc_table[(__c1 ^ *__data++) & 0xff] ^ (__c1 >> 8);\
	crc.crc1 = __c1;\
	crc.crc2 = __c2;\
}

void SetRedoRecPtr(void);
void GetRedoRecPtr(void);

258 259
static void GetFreeXLBuffer(void);
static void XLogWrite(char *buffer);
V
Vadim B. Mikheev 已提交
260
static int	XLogFileInit(uint32 log, uint32 seg, bool *usexistent);
261 262
static int	XLogFileOpen(uint32 log, uint32 seg, bool econt);
static XLogRecord *ReadRecord(XLogRecPtr *RecPtr, char *buffer);
263 264
static void WriteControlFile(void);
static void ReadControlFile(void);
265
static char *str_time(time_t tnow);
V
WAL  
Vadim B. Mikheev 已提交
266
static void xlog_outrec(char *buf, XLogRecord *record);
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283

static XLgwrResult LgwrResult = {{0, 0}, {0, 0}};
static XLgwrRqst LgwrRqst = {{0, 0}, {0, 0}};

static int	logFile = -1;
static uint32 logId = 0;
static uint32 logSeg = 0;
static uint32 logOff = 0;

static XLogRecPtr ReadRecPtr;
static XLogRecPtr EndRecPtr;
static int	readFile = -1;
static uint32 readId = 0;
static uint32 readSeg = 0;
static uint32 readOff = 0;
static char readBuf[BLCKSZ];
static XLogRecord *nextRecord = NULL;
284

V
WAL  
Vadim B. Mikheev 已提交
285 286
static bool InRedo = false;

287
XLogRecPtr
288
XLogInsert(RmgrId rmid, uint8 info, XLogRecData *rdata)
289
{
V
Vadim B. Mikheev 已提交
290 291 292 293
	XLogCtlInsert  *Insert = &XLogCtl->Insert;
	XLogRecord	   *record;
	XLogSubRecord  *subrecord;
	XLogRecPtr		RecPtr;
294
	uint32			freespace;
V
Vadim B. Mikheev 已提交
295
	uint16			curridx;
296 297 298 299 300 301 302 303 304 305
	XLogRecData	   *rdt;
	Buffer			dtbuf[2] = {InvalidBuffer, InvalidBuffer};
	bool			dtbuf_bkp[2] = {false, false};
	XLogRecData		dtbuf_rdt[4];
	BkpBlock		dtbuf_xlg[2];
	XLogRecPtr		dtbuf_lsn[2];
	crc64			dtbuf_crc[2],
					rdata_crc;
	uint32			len;
	unsigned		i;
V
Vadim B. Mikheev 已提交
306
	bool			updrqst = false;
307
	bool			repeat = false;
V
Vadim B. Mikheev 已提交
308 309 310 311 312 313 314 315 316 317 318
	bool			no_tran = (rmid == RM_XLOG_ID) ? true : false;

	if (info & XLR_INFO_MASK)
	{
		if ((info & XLR_INFO_MASK) != XLOG_NO_TRAN)
			elog(STOP, "XLogInsert: invalid info mask %02X", 
				(info & XLR_INFO_MASK));
		no_tran = true;
		info &= ~XLR_INFO_MASK;
	}

V
Vadim B. Mikheev 已提交
319
	if (IsBootstrapProcessingMode() && rmid != RM_XLOG_ID)
V
WAL  
Vadim B. Mikheev 已提交
320 321 322 323 324 325
	{
		RecPtr.xlogid = 0;
		RecPtr.xrecoff = SizeOfXLogPHD;	/* start of 1st checkpoint record */
		return (RecPtr);
	}

326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
begin:;
	INIT_CRC64(rdata_crc);
	for (len = 0, rdt = rdata; ; )
	{
		if (rdt->buffer == InvalidBuffer)
		{
			len += rdt->len;
			COMP_CRC64(rdata_crc, rdt->data, rdt->len);
			if (rdt->next == NULL)
				break;
			rdt = rdt->next;
			continue;
		}
		for (i = 0; i < 2; i++)
		{
			if (rdt->buffer == dtbuf[i])
			{
				if (dtbuf_bkp[i])
					rdt->data = NULL;
				else if (rdt->data)
				{
					len += rdt->len;
					COMP_CRC64(rdata_crc, rdt->data, rdt->len);
				}
				break;
			}
			if (dtbuf[i] == InvalidBuffer)
			{
				dtbuf[i] = rdt->buffer;
				dtbuf_lsn[i] = *((XLogRecPtr*)(BufferGetBlock(rdt->buffer)));
				if (XLByteLE(dtbuf_lsn[i], RedoRecPtr))
				{
					crc64	crc;

					dtbuf_bkp[i] = true;
					rdt->data = NULL;
					INIT_CRC64(crc);
					COMP_CRC64(crc, ((char*)BufferGetBlock(dtbuf[i])), BLCKSZ);
					dtbuf_crc[i] = crc;
				}
				else if (rdt->data)
				{
					len += rdt->len;
					COMP_CRC64(rdata_crc, rdt->data, rdt->len);
				}
				break;
			}
		}
		if (i >= 2)
			elog(STOP, "XLogInsert: can backup 2 blocks at most");
		if (rdt->next == NULL)
			break;
		rdt = rdt->next;
	}

	if (len == 0 || len > MAXLOGRECSZ)
		elog(STOP, "XLogInsert: invalid record len %u", len);

384
	START_CRIT_SECTION();
385

386 387 388 389 390
	/* obtain xlog insert lock */
	if (TAS(&(XLogCtl->insert_lck)))	/* busy */
	{
		bool		do_lgwr = true;

391
		for (i = 0;;)
392 393 394 395 396 397 398
		{
			/* try to read LgwrResult while waiting for insert lock */
			if (!TAS(&(XLogCtl->info_lck)))
			{
				LgwrRqst = XLogCtl->LgwrRqst;
				LgwrResult = XLogCtl->LgwrResult;
				S_UNLOCK(&(XLogCtl->info_lck));
399

400 401 402 403
				/*
				 * If cache is half filled then try to acquire lgwr lock
				 * and do LGWR work, but only once.
				 */
404 405 406 407
				if (do_lgwr &&
					(LgwrRqst.Write.xlogid != LgwrResult.Write.xlogid ||
					 (LgwrRqst.Write.xrecoff - LgwrResult.Write.xrecoff >=
					  XLogCtl->XLogCacheByte / 2)))
408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425
				{
					if (!TAS(&(XLogCtl->lgwr_lck)))
					{
						LgwrResult = XLogCtl->Write.LgwrResult;
						if (!TAS(&(XLogCtl->info_lck)))
						{
							LgwrRqst = XLogCtl->LgwrRqst;
							S_UNLOCK(&(XLogCtl->info_lck));
						}
						if (XLByteLT(LgwrResult.Write, LgwrRqst.Write))
						{
							XLogWrite(NULL);
							do_lgwr = false;
						}
						S_UNLOCK(&(XLogCtl->lgwr_lck));
					}
				}
			}
426
			S_LOCK_SLEEP(&(XLogCtl->insert_lck), i++);
427 428 429 430 431
			if (!TAS(&(XLogCtl->insert_lck)))
				break;
		}
	}

432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448
	/* Race condition: RedoRecPtr was changed */
	RedoRecPtr = Insert->RedoRecPtr;
	repeat = false;
	for (i = 0; i < 2; i++)
	{
		if (dtbuf[i] == InvalidBuffer)
			continue;
		if (dtbuf_bkp[i] == false &&
			XLByteLE(dtbuf_lsn[i], RedoRecPtr))
		{
			dtbuf[i] = InvalidBuffer;
			repeat = true;
		}
	}
	if (repeat)
	{
		S_UNLOCK(&(XLogCtl->insert_lck));
449
		END_CRIT_SECTION();
450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484
		goto begin;
	}

	/* Attach backup blocks to record data */
	for (i = 0; i < 2; i++)
	{
		if (dtbuf[i] == InvalidBuffer || !(dtbuf_bkp[i]))
			continue;

		info |= (XLR_SET_BKP_BLOCK(i));

		dtbuf_xlg[i].node = BufferGetFileNode(dtbuf[i]);
		dtbuf_xlg[i].block = BufferGetBlockNumber(dtbuf[i]);
		COMP_CRC64(dtbuf_crc[i], 
			((char*)&(dtbuf_xlg[i]) + offsetof(BkpBlock, node)),
			(sizeof(BkpBlock) - offsetof(BkpBlock, node)));
		FIN_CRC64(dtbuf_crc[i]);
		dtbuf_xlg[i].crc = dtbuf_crc[i];

		rdt->next = &(dtbuf_rdt[2 * i]);

		dtbuf_rdt[2 * i].data = (char*)&(dtbuf_xlg[i]);
		dtbuf_rdt[2 * i].len = sizeof(BkpBlock);
		len += sizeof(BkpBlock);

		rdt = dtbuf_rdt[2 * i].next = &(dtbuf_rdt[2 * i + 1]);

		dtbuf_rdt[2 * i + 1].data = (char*)(BufferGetBlock(dtbuf[i]));
		dtbuf_rdt[2 * i + 1].len = BLCKSZ;
		len += BLCKSZ;
		dtbuf_rdt[2 * i + 1].next = NULL;
	}

	/* Insert record */

485
	freespace = ((char *) Insert->currpage) + BLCKSZ - Insert->currpos;
486 487 488 489 490
	if (freespace < SizeOfXLogRecord)
	{
		curridx = NextBufIdx(Insert->curridx);
		if (XLByteLE(XLogCtl->xlblocks[curridx], LgwrResult.Write))
			InitXLBuffer(curridx);
491
		else
492 493 494 495 496 497 498
			GetFreeXLBuffer();
		freespace = BLCKSZ - SizeOfXLogPHD;
	}
	else
		curridx = Insert->curridx;

	freespace -= SizeOfXLogRecord;
499
	record = (XLogRecord *) Insert->currpos;
500
	record->xl_prev = Insert->PrevRecord;
V
Vadim B. Mikheev 已提交
501
	if (no_tran)
502 503 504 505
	{
		record->xl_xact_prev.xlogid = 0;
		record->xl_xact_prev.xrecoff = 0;
	}
V
Vadim B. Mikheev 已提交
506 507 508
	else
		record->xl_xact_prev = MyLastRecPtr;

509
	record->xl_xid = GetCurrentTransactionId();
510 511
	record->xl_len = len;
	record->xl_info = info;
512
	record->xl_rmid = rmid;
513 514 515 516 517 518

	COMP_CRC64(rdata_crc, ((char*)record + offsetof(XLogRecord, xl_prev)), 
				(SizeOfXLogRecord - offsetof(XLogRecord, xl_prev)));
	FIN_CRC64(rdata_crc);
	record->xl_crc = rdata_crc;

519
	RecPtr.xlogid = XLogCtl->xlblocks[curridx].xlogid;
520 521 522
	RecPtr.xrecoff =
		XLogCtl->xlblocks[curridx].xrecoff - BLCKSZ +
		Insert->currpos - ((char *) Insert->currpage);
V
Vadim B. Mikheev 已提交
523
	if (MyLastRecPtr.xrecoff == 0 && !no_tran)
524 525 526 527 528
	{
		SpinAcquire(SInvalLock);
		MyProc->logRec = RecPtr;
		SpinRelease(SInvalLock);
	}
V
WAL  
Vadim B. Mikheev 已提交
529 530 531 532 533 534 535 536
	Insert->PrevRecord = RecPtr;

	if (XLOG_DEBUG)
	{
		char	buf[8192];

		sprintf(buf, "INSERT @ %u/%u: ", RecPtr.xlogid, RecPtr.xrecoff);
		xlog_outrec(buf, record);
537
		if (rdata->data != NULL)
V
WAL  
Vadim B. Mikheev 已提交
538 539
		{
			strcat(buf, " - ");
540
			RmgrTable[record->xl_rmid].rm_desc(buf, record->xl_info, rdata->data);
V
WAL  
Vadim B. Mikheev 已提交
541 542 543 544 545
		}
		strcat(buf, "\n");
		write(2, buf, strlen(buf));
	}

V
Vadim B. Mikheev 已提交
546
	MyLastRecPtr = RecPtr;	/* begin of record */
547
	Insert->currpos += SizeOfXLogRecord;
548 549

	while (len)
550
	{
551 552 553 554
		while (rdata->data == NULL)
			rdata = rdata->next;

		if (freespace > 0)
555
		{
556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571
			if (rdata->len > freespace)
			{
				memcpy(Insert->currpos, rdata->data, freespace);
				rdata->data += freespace;
				rdata->len -= freespace;
				len -= freespace;
			}
			else
			{
				memcpy(Insert->currpos, rdata->data, rdata->len);
				freespace -= rdata->len;
				len -= rdata->len;
				Insert->currpos += rdata->len;
				rdata = rdata->next;
				continue;
			}
572 573
		}

574
		/* Use next buffer */
575 576 577 578 579 580 581 582 583 584
		curridx = NextBufIdx(curridx);
		if (XLByteLE(XLogCtl->xlblocks[curridx], LgwrResult.Write))
		{
			InitXLBuffer(curridx);
			updrqst = true;
		}
		else
			GetFreeXLBuffer();
		freespace = BLCKSZ - SizeOfXLogPHD - SizeOfXLogSubRecord;
		Insert->currpage->xlp_info |= XLP_FIRST_IS_SUBRECORD;
585
		subrecord = (XLogSubRecord *) Insert->currpos;
586
		subrecord->xl_len = len;
587 588
		Insert->currpos += SizeOfXLogSubRecord;
	}
589 590 591

	Insert->currpos = ((char *) Insert->currpage) +
			MAXALIGN(Insert->currpos - ((char *) Insert->currpage));
592 593
	freespace = ((char *) Insert->currpage) + BLCKSZ - Insert->currpos;

V
Vadim B. Mikheev 已提交
594 595 596 597 598 599 600 601 602
	/*
	 * Begin of the next record will be stored as LSN for
	 * changed data page...
	 */
	RecPtr.xlogid = XLogCtl->xlblocks[curridx].xlogid;
	RecPtr.xrecoff =
		XLogCtl->xlblocks[curridx].xrecoff - BLCKSZ +
		Insert->currpos - ((char *) Insert->currpage);

603
	/* Need to update global LgwrRqst if some block was filled up */
604
	if (freespace < SizeOfXLogRecord)
605
		updrqst = true;	/* curridx is filled and available for writing out */
606 607 608 609 610 611 612 613
	else
		curridx = PrevBufIdx(curridx);
	LgwrRqst.Write = XLogCtl->xlblocks[curridx];

	S_UNLOCK(&(XLogCtl->insert_lck));

	if (updrqst)
	{
614 615 616 617
		S_LOCK(&(XLogCtl->info_lck));
		if (XLByteLT(XLogCtl->LgwrRqst.Write, LgwrRqst.Write))
			XLogCtl->LgwrRqst.Write = LgwrRqst.Write;
		S_UNLOCK(&(XLogCtl->info_lck));
618 619
	}

620
	END_CRIT_SECTION();
621
	return (RecPtr);
622
}
623 624 625 626

void
XLogFlush(XLogRecPtr record)
{
627 628 629
	XLogRecPtr	WriteRqst;
	char		buffer[BLCKSZ];
	char	   *usebuf = NULL;
630
	unsigned	spins = 0;
631
	bool		force_lgwr = false;
632

V
WAL  
Vadim B. Mikheev 已提交
633 634 635 636 637 638 639 640 641 642 643
	if (XLOG_DEBUG)
	{
		fprintf(stderr, "XLogFlush%s%s: rqst %u/%u; wrt %u/%u; flsh %u/%u\n",
			(IsBootstrapProcessingMode()) ? "(bootstrap)" : "",
			(InRedo) ? "(redo)" : "",
			record.xlogid, record.xrecoff,
			LgwrResult.Write.xlogid, LgwrResult.Write.xrecoff,
			LgwrResult.Flush.xlogid, LgwrResult.Flush.xrecoff);
		fflush(stderr);
	}

V
Vadim B. Mikheev 已提交
644
	if (InRedo)
V
WAL  
Vadim B. Mikheev 已提交
645
		return;
646 647
	if (XLByteLE(record, LgwrResult.Flush))
		return;
648

649
	START_CRIT_SECTION();
650

651
	WriteRqst = LgwrRqst.Write;
652
	for (;;)
653 654 655 656 657 658 659 660
	{
		/* try to read LgwrResult */
		if (!TAS(&(XLogCtl->info_lck)))
		{
			LgwrResult = XLogCtl->LgwrResult;
			if (XLByteLE(record, LgwrResult.Flush))
			{
				S_UNLOCK(&(XLogCtl->info_lck));
661
				END_CRIT_SECTION();
662 663 664 665 666 667 668 669 670 671 672 673 674 675
				return;
			}
			if (XLByteLT(XLogCtl->LgwrRqst.Flush, record))
				XLogCtl->LgwrRqst.Flush = record;
			if (XLByteLT(WriteRqst, XLogCtl->LgwrRqst.Write))
			{
				WriteRqst = XLogCtl->LgwrRqst.Write;
				usebuf = NULL;
			}
			S_UNLOCK(&(XLogCtl->info_lck));
		}
		/* if something was added to log cache then try to flush this too */
		if (!TAS(&(XLogCtl->insert_lck)))
		{
676 677 678
			XLogCtlInsert *Insert = &XLogCtl->Insert;
			uint32		freespace =
			((char *) Insert->currpage) + BLCKSZ - Insert->currpos;
679 680 681 682 683 684 685 686 687 688 689 690

			if (freespace < SizeOfXLogRecord)	/* buffer is full */
			{
				usebuf = NULL;
				LgwrRqst.Write = WriteRqst = XLogCtl->xlblocks[Insert->curridx];
			}
			else
			{
				usebuf = buffer;
				memcpy(usebuf, Insert->currpage, BLCKSZ - freespace);
				memset(usebuf + BLCKSZ - freespace, 0, freespace);
				WriteRqst = XLogCtl->xlblocks[Insert->curridx];
691 692
				WriteRqst.xrecoff = WriteRqst.xrecoff - BLCKSZ +
					Insert->currpos - ((char *) Insert->currpage);
693 694 695 696
			}
			S_UNLOCK(&(XLogCtl->insert_lck));
			force_lgwr = true;
		}
697 698
		if (force_lgwr || WriteRqst.xlogid > record.xlogid ||
			(WriteRqst.xlogid == record.xlogid &&
699 700 701 702 703 704 705 706
			 WriteRqst.xrecoff >= record.xrecoff + BLCKSZ))
		{
			if (!TAS(&(XLogCtl->lgwr_lck)))
			{
				LgwrResult = XLogCtl->Write.LgwrResult;
				if (XLByteLE(record, LgwrResult.Flush))
				{
					S_UNLOCK(&(XLogCtl->lgwr_lck));
707
					END_CRIT_SECTION();
708 709 710 711 712 713 714 715
					return;
				}
				if (XLByteLT(LgwrResult.Write, WriteRqst))
				{
					LgwrRqst.Flush = LgwrRqst.Write = WriteRqst;
					XLogWrite(usebuf);
					S_UNLOCK(&(XLogCtl->lgwr_lck));
					if (XLByteLT(LgwrResult.Flush, record))
716
						elog(STOP, "XLogFlush: request is not satisfied");
717
					END_CRIT_SECTION();
718 719 720 721 722
					return;
				}
				break;
			}
		}
723
		S_LOCK_SLEEP(&(XLogCtl->lgwr_lck), spins++);
724 725
	}

726 727
	if (logFile >= 0 && (LgwrResult.Write.xlogid != logId ||
				 (LgwrResult.Write.xrecoff - 1) / XLogSegSize != logSeg))
728 729
	{
		if (close(logFile) != 0)
730 731
			elog(STOP, "close(logfile %u seg %u) failed: %m",
				 logId, logSeg);
732 733 734 735 736 737 738
		logFile = -1;
	}

	if (logFile < 0)
	{
		logId = LgwrResult.Write.xlogid;
		logSeg = (LgwrResult.Write.xrecoff - 1) / XLogSegSize;
739
		logOff = 0;
740 741 742
		logFile = XLogFileOpen(logId, logSeg, false);
	}

743
	if (pg_fsync(logFile) != 0)
744 745
		elog(STOP, "fsync(logfile %u seg %u) failed: %m",
			 logId, logSeg);
746 747
	LgwrResult.Flush = LgwrResult.Write;

748 749 750 751 752 753
	S_LOCK(&(XLogCtl->info_lck));
	XLogCtl->LgwrResult = LgwrResult;
	if (XLByteLT(XLogCtl->LgwrRqst.Write, LgwrResult.Write))
		XLogCtl->LgwrRqst.Write = LgwrResult.Write;
	S_UNLOCK(&(XLogCtl->info_lck));

754 755 756
	XLogCtl->Write.LgwrResult = LgwrResult;

	S_UNLOCK(&(XLogCtl->lgwr_lck));
757

758
	END_CRIT_SECTION();
759 760 761 762 763 764 765
	return;

}

static void
GetFreeXLBuffer()
{
766 767 768
	XLogCtlInsert *Insert = &XLogCtl->Insert;
	XLogCtlWrite *Write = &XLogCtl->Write;
	uint16		curridx = NextBufIdx(Insert->curridx);
769
	unsigned	spins = 0;
770 771

	LgwrRqst.Write = XLogCtl->xlblocks[Insert->curridx];
772
	for (;;)
773 774 775 776 777 778 779 780 781 782 783 784 785
	{
		if (!TAS(&(XLogCtl->info_lck)))
		{
			LgwrResult = XLogCtl->LgwrResult;
			XLogCtl->LgwrRqst.Write = LgwrRqst.Write;
			S_UNLOCK(&(XLogCtl->info_lck));
			if (XLByteLE(XLogCtl->xlblocks[curridx], LgwrResult.Write))
			{
				Insert->LgwrResult = LgwrResult;
				InitXLBuffer(curridx);
				return;
			}
		}
786

787 788 789 790 791 792 793 794 795 796 797 798 799 800
		/*
		 * LgwrResult lock is busy or un-updated. Try to acquire lgwr lock
		 * and write full blocks.
		 */
		if (!TAS(&(XLogCtl->lgwr_lck)))
		{
			LgwrResult = Write->LgwrResult;
			if (XLByteLE(XLogCtl->xlblocks[curridx], LgwrResult.Write))
			{
				S_UNLOCK(&(XLogCtl->lgwr_lck));
				Insert->LgwrResult = LgwrResult;
				InitXLBuffer(curridx);
				return;
			}
801 802 803 804

			/*
			 * Have to write buffers while holding insert lock - not
			 * good...
805 806 807 808 809 810 811
			 */
			XLogWrite(NULL);
			S_UNLOCK(&(XLogCtl->lgwr_lck));
			Insert->LgwrResult = LgwrResult;
			InitXLBuffer(curridx);
			return;
		}
812
		S_LOCK_SLEEP(&(XLogCtl->lgwr_lck), spins++);
813 814 815 816 817 818
	}
}

static void
XLogWrite(char *buffer)
{
819 820 821
	XLogCtlWrite *Write = &XLogCtl->Write;
	char	   *from;
	uint32		wcnt = 0;
V
Vadim B. Mikheev 已提交
822
	bool		usexistent;
823

824
	for (; XLByteLT(LgwrResult.Write, LgwrRqst.Write);)
825 826
	{
		LgwrResult.Write = XLogCtl->xlblocks[Write->curridx];
827
		if (LgwrResult.Write.xlogid != logId ||
828 829 830 831
			(LgwrResult.Write.xrecoff - 1) / XLogSegSize != logSeg)
		{
			if (wcnt > 0)
			{
832
				if (pg_fsync(logFile) != 0)
833 834
					elog(STOP, "fsync(logfile %u seg %u) failed: %m",
						 logId, logSeg);
835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853
				if (LgwrResult.Write.xlogid != logId)
					LgwrResult.Flush.xrecoff = XLogFileSize;
				else
					LgwrResult.Flush.xrecoff = LgwrResult.Write.xrecoff - BLCKSZ;
				LgwrResult.Flush.xlogid = logId;
				if (!TAS(&(XLogCtl->info_lck)))
				{
					XLogCtl->LgwrResult.Flush = LgwrResult.Flush;
					XLogCtl->LgwrResult.Write = LgwrResult.Flush;
					if (XLByteLT(XLogCtl->LgwrRqst.Write, LgwrResult.Flush))
						XLogCtl->LgwrRqst.Write = LgwrResult.Flush;
					if (XLByteLT(XLogCtl->LgwrRqst.Flush, LgwrResult.Flush))
						XLogCtl->LgwrRqst.Flush = LgwrResult.Flush;
					S_UNLOCK(&(XLogCtl->info_lck));
				}
			}
			if (logFile >= 0)
			{
				if (close(logFile) != 0)
854 855
					elog(STOP, "close(logfile %u seg %u) failed: %m",
						 logId, logSeg);
856 857 858 859
				logFile = -1;
			}
			logId = LgwrResult.Write.xlogid;
			logSeg = (LgwrResult.Write.xrecoff - 1) / XLogSegSize;
860
			logOff = 0;
861
			SpinAcquire(ControlFileLockId);
V
Vadim B. Mikheev 已提交
862 863 864
			/* create/use new log file */
			usexistent = true;
			logFile = XLogFileInit(logId, logSeg, &usexistent);
865 866 867 868 869
			ControlFile->logId = logId;
			ControlFile->logSeg = logSeg + 1;
			ControlFile->time = time(NULL);
			UpdateControlFile();
			SpinRelease(ControlFileLockId);
V
Vadim B. Mikheev 已提交
870
			if (!usexistent)	/* there was no file */
871 872
				elog(LOG, "XLogWrite: new log file created - "
					"try to increase WAL_FILES");
873 874 875 876 877 878
		}

		if (logFile < 0)
		{
			logId = LgwrResult.Write.xlogid;
			logSeg = (LgwrResult.Write.xrecoff - 1) / XLogSegSize;
879
			logOff = 0;
880 881 882 883 884 885
			logFile = XLogFileOpen(logId, logSeg, false);
		}

		if (logOff != (LgwrResult.Write.xrecoff - BLCKSZ) % XLogSegSize)
		{
			logOff = (LgwrResult.Write.xrecoff - BLCKSZ) % XLogSegSize;
886
			if (lseek(logFile, (off_t) logOff, SEEK_SET) < 0)
887 888
				elog(STOP, "lseek(logfile %u seg %u off %u) failed: %m",
					 logId, logSeg, logOff);
889 890 891 892 893 894 895 896
		}

		if (buffer != NULL && XLByteLT(LgwrRqst.Write, LgwrResult.Write))
			from = buffer;
		else
			from = XLogCtl->pages + Write->curridx * BLCKSZ;

		if (write(logFile, from, BLCKSZ) != BLCKSZ)
897 898
			elog(STOP, "write(logfile %u seg %u off %u) failed: %m",
				 logId, logSeg, logOff);
899 900 901 902 903 904 905 906 907 908 909 910

		wcnt++;
		logOff += BLCKSZ;

		if (from != buffer)
			Write->curridx = NextBufIdx(Write->curridx);
		else
			LgwrResult.Write = LgwrRqst.Write;
	}
	if (wcnt == 0)
		elog(STOP, "XLogWrite: nothing written");

911
	if (XLByteLT(LgwrResult.Flush, LgwrRqst.Flush) &&
912 913
		XLByteLE(LgwrRqst.Flush, LgwrResult.Write))
	{
914
		if (pg_fsync(logFile) != 0)
915 916
			elog(STOP, "fsync(logfile %u seg %u) failed: %m",
				 logId, logSeg);
917 918 919
		LgwrResult.Flush = LgwrResult.Write;
	}

920 921 922 923 924 925
	S_LOCK(&(XLogCtl->info_lck));
	XLogCtl->LgwrResult = LgwrResult;
	if (XLByteLT(XLogCtl->LgwrRqst.Write, LgwrResult.Write))
		XLogCtl->LgwrRqst.Write = LgwrResult.Write;
	S_UNLOCK(&(XLogCtl->info_lck));

926 927 928 929
	Write->LgwrResult = LgwrResult;
}

static int
V
Vadim B. Mikheev 已提交
930
XLogFileInit(uint32 log, uint32 seg, bool *usexistent)
931
{
932
	char		path[MAXPGPATH];
V
Vadim B. Mikheev 已提交
933
	char		tpath[MAXPGPATH];
934
	int			fd;
935 936

	XLogFileName(path, log, seg);
V
Vadim B. Mikheev 已提交
937 938 939 940 941 942 943 944 945 946 947

	/*
	 * Try to use existent file (checkpoint maker
	 * creates it sometime).
	 */
	if (*usexistent)
	{
		fd = BasicOpenFile(path, O_RDWR | PG_BINARY, S_IRUSR | S_IWUSR);
		if (fd < 0)
		{
			if (errno != ENOENT)
948 949
				elog(STOP, "InitOpen(logfile %u seg %u) failed: %m",
					logId, logSeg);
V
Vadim B. Mikheev 已提交
950 951 952 953 954 955 956 957
		}
		else
			return(fd);
		*usexistent = false;
	}

	XLogTempFileName(tpath, log, seg);
	unlink(tpath);
958 959
	unlink(path);

V
Vadim B. Mikheev 已提交
960
	fd = BasicOpenFile(tpath, O_RDWR | O_CREAT | O_EXCL | PG_BINARY, S_IRUSR | S_IWUSR);
961
	if (fd < 0)
962 963
		elog(STOP, "InitCreate(logfile %u seg %u) failed: %m",
			 logId, logSeg);
964 965

	if (lseek(fd, XLogSegSize - 1, SEEK_SET) != (off_t) (XLogSegSize - 1))
966 967
		elog(STOP, "lseek(logfile %u seg %u) failed: %m",
			 logId, logSeg);
968 969

	if (write(fd, "", 1) != 1)
970 971
		elog(STOP, "write(logfile %u seg %u) failed: %m",
			 logId, logSeg);
972

973
	if (pg_fsync(fd) != 0)
974 975
		elog(STOP, "fsync(logfile %u seg %u) failed: %m",
			 logId, logSeg);
976

977
	if (lseek(fd, 0, SEEK_SET) < 0)
978 979
		elog(STOP, "lseek(logfile %u seg %u off %u) failed: %m",
			 log, seg, 0);
980

V
Vadim B. Mikheev 已提交
981
	close(fd);
T
Tom Lane 已提交
982

983
#ifndef __BEOS__
T
Tom Lane 已提交
984
	if (link(tpath, path) < 0)
985 986 987
#else
	if (rename(tpath, path) < 0)
#endif
T
Tom Lane 已提交
988 989 990
		elog(STOP, "InitRelink(logfile %u seg %u) failed: %m",
			 logId, logSeg);

V
Vadim B. Mikheev 已提交
991 992 993 994
	unlink(tpath);

	fd = BasicOpenFile(path, O_RDWR | PG_BINARY, S_IRUSR | S_IWUSR);
	if (fd < 0)
995 996
		elog(STOP, "InitReopen(logfile %u seg %u) failed: %m",
			 logId, logSeg);
V
Vadim B. Mikheev 已提交
997

998
	return (fd);
999 1000 1001 1002 1003
}

static int
XLogFileOpen(uint32 log, uint32 seg, bool econt)
{
1004 1005
	char		path[MAXPGPATH];
	int			fd;
1006 1007 1008

	XLogFileName(path, log, seg);

1009
	fd = BasicOpenFile(path, O_RDWR | PG_BINARY, S_IRUSR | S_IWUSR);
1010 1011 1012 1013
	if (fd < 0)
	{
		if (econt && errno == ENOENT)
		{
1014
			elog(LOG, "open(logfile %u seg %u) failed: %m",
1015
				 logId, logSeg);
1016 1017
			return (fd);
		}
V
WAL  
Vadim B. Mikheev 已提交
1018
		abort();
1019 1020
		elog(STOP, "open(logfile %u seg %u) failed: %m",
			 logId, logSeg);
1021 1022
	}

1023
	return (fd);
1024 1025
}

V
Vadim B. Mikheev 已提交
1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040
/*
 * (Re)move offline log files older or equal to passwd one
 */
static void
MoveOfflineLogs(char *archdir, uint32 _logId, uint32 _logSeg)
{
	DIR			   *xldir;
	struct dirent  *xlde;
	char			lastoff[32];
	char			path[MAXPGPATH];

	Assert(archdir[0] == 0);	/* ! implemented yet */

	xldir = opendir(XLogDir);
	if (xldir == NULL)
1041
		elog(STOP, "MoveOfflineLogs: cannot open xlog dir: %m");
V
Vadim B. Mikheev 已提交
1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058

	sprintf(lastoff, "%08X%08X", _logId, _logSeg);

	errno = 0;
	while ((xlde = readdir(xldir)) != NULL)
	{
		if (strlen(xlde->d_name) != 16 || 
			strspn(xlde->d_name, "0123456789ABCDEF") != 16)
			continue;
		if (strcmp(xlde->d_name, lastoff) > 0)
		{
			errno = 0;
			continue;
		}
		elog(LOG, "MoveOfflineLogs: %s %s", (archdir[0]) ? 
			"archive" : "remove", xlde->d_name);
		sprintf(path, "%s%c%s",	XLogDir, SEP_CHAR, xlde->d_name);
V
Vadim B. Mikheev 已提交
1059
		if (archdir[0] == 0)
V
Vadim B. Mikheev 已提交
1060 1061 1062 1063
			unlink(path);
		errno = 0;
	}
	if (errno)
1064
		elog(STOP, "MoveOfflineLogs: cannot read xlog dir: %m");
V
Vadim B. Mikheev 已提交
1065 1066 1067
	closedir(xldir);
}

1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172
static void
RestoreBkpBlocks(XLogRecord *record, XLogRecPtr lsn)
{
	Relation	reln;
	Buffer		buffer;
	Page		page;
	BkpBlock	bkpb;
	char	   *blk;
	int			i;

	for (i = 0, blk = (char*)XLogRecGetData(record) + record->xl_len; i < 2; i++)
	{
		if (!(record->xl_info & (XLR_SET_BKP_BLOCK(i))))
			continue;

		memcpy((char*)&bkpb, blk, sizeof(BkpBlock));
		blk += sizeof(BkpBlock);

		reln = XLogOpenRelation(true, record->xl_rmid, bkpb.node);

		if (reln)
		{
			buffer = XLogReadBuffer(true, reln, bkpb.block);
			if (BufferIsValid(buffer))
			{
				page = (Page) BufferGetPage(buffer);
				memcpy((char*)page, blk, BLCKSZ);
				PageSetLSN(page, lsn);
				PageSetSUI(page, ThisStartUpID);
				UnlockAndWriteBuffer(buffer);
			}
		}

		blk += BLCKSZ;
	}
}

static bool
RecordIsValid(XLogRecord *record, XLogRecPtr recptr, int emode)
{
	crc64		crc;
	crc64		cbuf;
	int			i;
	uint32		len = record->xl_len;
	char	   *blk;

	for (i = 0; i < 2; i++)
	{
		if (!(record->xl_info & (XLR_SET_BKP_BLOCK(i))))
			continue;

		if (len <= (sizeof(BkpBlock) + BLCKSZ))
		{
			elog(emode, "ReadRecord: record at %u/%u is too short to keep bkp block",
				recptr.xlogid, recptr.xrecoff);
			return(false);
		}
		len -= sizeof(BkpBlock);
		len -= BLCKSZ;
	}

	/* CRC of rmgr data */
	INIT_CRC64(crc);
	COMP_CRC64(crc, ((char*)XLogRecGetData(record)), len);
	COMP_CRC64(crc, ((char*)record + offsetof(XLogRecord, xl_prev)), 
				(SizeOfXLogRecord - offsetof(XLogRecord, xl_prev)));
	FIN_CRC64(crc);

	if (record->xl_crc.crc1 != crc.crc1 || record->xl_crc.crc2 != crc.crc2)
	{
		elog(emode, "ReadRecord: bad rmgr data CRC in record at %u/%u",
			recptr.xlogid, recptr.xrecoff);
		return(false);
	}

	if (record->xl_len == len)
		return(true);

	for (i = 0, blk = (char*)XLogRecGetData(record) + len; i < 2; i++)
	{
		if (!(record->xl_info & (XLR_SET_BKP_BLOCK(i))))
			continue;

		INIT_CRC64(crc);
		COMP_CRC64(crc, (blk + sizeof(BkpBlock)), BLCKSZ);
		COMP_CRC64(crc, (blk + offsetof(BkpBlock, node)),
			(sizeof(BkpBlock) - offsetof(BkpBlock, node)));
		FIN_CRC64(crc);
		memcpy((char*)&cbuf, blk, sizeof(crc64));

		if (cbuf.crc1 != crc.crc1 || cbuf.crc2 != crc.crc2)
		{
			elog(emode, "ReadRecord: bad bkp block %d CRC in record at %u/%u",
				i + 1, recptr.xlogid, recptr.xrecoff);
			return(false);
		}
		blk += sizeof(BkpBlock);
		blk += BLCKSZ;
	}

	record->xl_len = len;	/* !!! */

	return(true);
}

1173
static XLogRecord *
1174
ReadRecord(XLogRecPtr *RecPtr, char *buffer)
1175
{
1176 1177
	XLogRecord *record;
	XLogRecPtr	tmpRecPtr = EndRecPtr;
1178
	uint32		len;
1179 1180 1181
	bool		nextmode = (RecPtr == NULL);
	int			emode = (nextmode) ? LOG : STOP;
	bool		noBlck = false;
1182

1183
	if (nextmode)
1184
	{
1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198
		RecPtr = &tmpRecPtr;
		if (nextRecord != NULL)
		{
			record = nextRecord;
			goto got_record;
		}
		if (tmpRecPtr.xrecoff % BLCKSZ != 0)
			tmpRecPtr.xrecoff += (BLCKSZ - tmpRecPtr.xrecoff % BLCKSZ);
		if (tmpRecPtr.xrecoff >= XLogFileSize)
		{
			(tmpRecPtr.xlogid)++;
			tmpRecPtr.xrecoff = 0;
		}
		tmpRecPtr.xrecoff += SizeOfXLogPHD;
1199
	}
1200
	else if (!XRecOffIsValid(RecPtr->xrecoff))
1201
		elog(STOP, "ReadRecord: invalid record offset at (%u, %u)",
1202
			 RecPtr->xlogid, RecPtr->xrecoff);
1203

1204 1205
	if (readFile >= 0 && (RecPtr->xlogid != readId ||
						  RecPtr->xrecoff / XLogSegSize != readSeg))
1206
	{
1207 1208
		close(readFile);
		readFile = -1;
1209
	}
1210 1211 1212
	readId = RecPtr->xlogid;
	readSeg = RecPtr->xrecoff / XLogSegSize;
	if (readFile < 0)
1213
	{
1214 1215 1216 1217
		noBlck = true;
		readFile = XLogFileOpen(readId, readSeg, nextmode);
		if (readFile < 0)
			goto next_record_is_invalid;
1218 1219
	}

1220
	if (noBlck || readOff != (RecPtr->xrecoff % XLogSegSize) / BLCKSZ)
1221 1222
	{
		readOff = (RecPtr->xrecoff % XLogSegSize) / BLCKSZ;
1223
		if (lseek(readFile, (off_t) (readOff * BLCKSZ), SEEK_SET) < 0)
1224 1225
			elog(STOP, "ReadRecord: lseek(logfile %u seg %u off %u) failed: %m",
				 readId, readSeg, readOff);
1226
		if (read(readFile, readBuf, BLCKSZ) != BLCKSZ)
1227 1228
			elog(STOP, "ReadRecord: read(logfile %u seg %u off %u) failed: %m",
				 readId, readSeg, readOff);
1229
		if (((XLogPageHeader) readBuf)->xlp_magic != XLOG_PAGE_MAGIC)
1230 1231
		{
			elog(emode, "ReadRecord: invalid magic number %u in logfile %u seg %u off %u",
1232 1233
				 ((XLogPageHeader) readBuf)->xlp_magic,
				 readId, readSeg, readOff);
1234 1235 1236
			goto next_record_is_invalid;
		}
	}
1237
	if ((((XLogPageHeader) readBuf)->xlp_info & XLP_FIRST_IS_SUBRECORD) &&
1238 1239 1240
		RecPtr->xrecoff % BLCKSZ == SizeOfXLogPHD)
	{
		elog(emode, "ReadRecord: subrecord is requested by (%u, %u)",
1241
			 RecPtr->xlogid, RecPtr->xrecoff);
1242 1243
		goto next_record_is_invalid;
	}
1244
	record = (XLogRecord *) ((char *) readBuf + RecPtr->xrecoff % BLCKSZ);
1245 1246

got_record:;
1247 1248 1249 1250 1251 1252
	if (record->xl_len == 0)
	{
		elog(emode, "ReadRecord: record with zero len at (%u, %u)",
			RecPtr->xlogid, RecPtr->xrecoff);
		goto next_record_is_invalid;
	}
1253
	if (record->xl_len > _INTL_MAXLOGRECSZ)
1254
	{
1255
		elog(emode, "ReadRecord: too long record len %u at (%u, %u)",
1256
			record->xl_len, RecPtr->xlogid, RecPtr->xrecoff);
1257 1258 1259 1260
		goto next_record_is_invalid;
	}
	if (record->xl_rmid > RM_MAX_ID)
	{
1261
		elog(emode, "ReadRecord: invalid resource managed id %u at (%u, %u)",
1262
			 record->xl_rmid, RecPtr->xlogid, RecPtr->xrecoff);
1263 1264 1265
		goto next_record_is_invalid;
	}
	nextRecord = NULL;
1266 1267
	len = BLCKSZ - RecPtr->xrecoff % BLCKSZ - SizeOfXLogRecord;
	if (record->xl_len > len)
1268
	{
1269 1270
		XLogSubRecord  *subrecord;
		uint32			gotlen = len;
1271

1272
		memcpy(buffer, record, len + SizeOfXLogRecord);
1273
		record = (XLogRecord *) buffer;
1274
		buffer += len + SizeOfXLogRecord;
1275
		for (;;)
1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286
		{
			readOff++;
			if (readOff == XLogSegSize / BLCKSZ)
			{
				readSeg++;
				if (readSeg == XLogLastSeg)
				{
					readSeg = 0;
					readId++;
				}
				close(readFile);
1287
				readOff = 0;
1288 1289 1290 1291 1292
				readFile = XLogFileOpen(readId, readSeg, nextmode);
				if (readFile < 0)
					goto next_record_is_invalid;
			}
			if (read(readFile, readBuf, BLCKSZ) != BLCKSZ)
1293 1294
				elog(STOP, "ReadRecord: read(logfile %u seg %u off %u) failed: %m",
					 readId, readSeg, readOff);
1295
			if (((XLogPageHeader) readBuf)->xlp_magic != XLOG_PAGE_MAGIC)
1296 1297
			{
				elog(emode, "ReadRecord: invalid magic number %u in logfile %u seg %u off %u",
1298 1299
					 ((XLogPageHeader) readBuf)->xlp_magic,
					 readId, readSeg, readOff);
1300 1301
				goto next_record_is_invalid;
			}
1302
			if (!(((XLogPageHeader) readBuf)->xlp_info & XLP_FIRST_IS_SUBRECORD))
1303 1304
			{
				elog(emode, "ReadRecord: there is no subrecord flag in logfile %u seg %u off %u",
1305
					 readId, readSeg, readOff);
1306 1307
				goto next_record_is_invalid;
			}
1308
			subrecord = (XLogSubRecord *) ((char *) readBuf + SizeOfXLogPHD);
1309 1310
			if (subrecord->xl_len == 0 || 
				record->xl_len < (subrecord->xl_len + gotlen))
1311 1312
			{
				elog(emode, "ReadRecord: invalid subrecord len %u in logfile %u seg %u off %u",
1313
					 subrecord->xl_len, readId, readSeg, readOff);
1314 1315
				goto next_record_is_invalid;
			}
1316 1317 1318
			len = BLCKSZ - SizeOfXLogPHD - SizeOfXLogSubRecord;

			if (subrecord->xl_len > len)
1319
			{
1320 1321 1322 1323
				memcpy(buffer, (char *) subrecord + SizeOfXLogSubRecord, len);
				gotlen += len;
				buffer += len;
				continue;
1324
			}
1325
			if (record->xl_len != (subrecord->xl_len + gotlen))
1326
			{
1327 1328 1329
				elog(emode, "ReadRecord: invalid len %u of constracted record in logfile %u seg %u off %u",
					 subrecord->xl_len + gotlen, readId, readSeg, readOff);
				goto next_record_is_invalid;
1330
			}
1331
			memcpy(buffer, (char *) subrecord + SizeOfXLogSubRecord, subrecord->xl_len);
1332 1333
			break;
		}
1334 1335
		if (!RecordIsValid(record, *RecPtr, emode))
			goto next_record_is_invalid;
V
WAL  
Vadim B. Mikheev 已提交
1336
		if (BLCKSZ - SizeOfXLogRecord >= MAXALIGN(subrecord->xl_len) + 
V
Vadim B. Mikheev 已提交
1337
			SizeOfXLogPHD + SizeOfXLogSubRecord)
1338
		{
V
Vadim B. Mikheev 已提交
1339
			nextRecord = (XLogRecord *) ((char *) subrecord + 
V
WAL  
Vadim B. Mikheev 已提交
1340
				MAXALIGN(subrecord->xl_len) + SizeOfXLogSubRecord);
1341 1342
		}
		EndRecPtr.xlogid = readId;
1343
		EndRecPtr.xrecoff = readSeg * XLogSegSize + readOff * BLCKSZ +
V
Vadim B. Mikheev 已提交
1344
			SizeOfXLogPHD + SizeOfXLogSubRecord + 
V
WAL  
Vadim B. Mikheev 已提交
1345
			MAXALIGN(subrecord->xl_len);
1346
		ReadRecPtr = *RecPtr;
1347
		return (record);
1348
	}
1349 1350
	if (!RecordIsValid(record, *RecPtr, emode))
		goto next_record_is_invalid;
V
WAL  
Vadim B. Mikheev 已提交
1351
	if (BLCKSZ - SizeOfXLogRecord >= MAXALIGN(record->xl_len) + 
V
Vadim B. Mikheev 已提交
1352 1353
		RecPtr->xrecoff % BLCKSZ + SizeOfXLogRecord)
		nextRecord = (XLogRecord *) ((char *) record + 
V
WAL  
Vadim B. Mikheev 已提交
1354
			MAXALIGN(record->xl_len) + SizeOfXLogRecord);
1355
	EndRecPtr.xlogid = RecPtr->xlogid;
V
Vadim B. Mikheev 已提交
1356
	EndRecPtr.xrecoff = RecPtr->xrecoff + 
V
WAL  
Vadim B. Mikheev 已提交
1357
		MAXALIGN(record->xl_len) + SizeOfXLogRecord;
1358 1359
	ReadRecPtr = *RecPtr;

1360
	return (record);
1361 1362 1363 1364 1365 1366

next_record_is_invalid:;
	close(readFile);
	readFile = -1;
	nextRecord = NULL;
	memset(buffer, 0, SizeOfXLogRecord);
1367 1368
	record = (XLogRecord *) buffer;

1369 1370 1371 1372 1373 1374
	/*
	 * If we assumed that next record began on the same page where
	 * previous one ended - zero end of page.
	 */
	if (XLByteEQ(tmpRecPtr, EndRecPtr))
	{
1375 1376
		Assert(EndRecPtr.xrecoff % BLCKSZ > (SizeOfXLogPHD + SizeOfXLogSubRecord) &&
			   BLCKSZ - EndRecPtr.xrecoff % BLCKSZ >= SizeOfXLogRecord);
1377 1378 1379
		readId = EndRecPtr.xlogid;
		readSeg = EndRecPtr.xrecoff / XLogSegSize;
		readOff = (EndRecPtr.xrecoff % XLogSegSize) / BLCKSZ;
1380
		elog(LOG, "Formatting logfile %u seg %u block %u at offset %u",
1381
			 readId, readSeg, readOff, EndRecPtr.xrecoff % BLCKSZ);
1382
		readFile = XLogFileOpen(readId, readSeg, false);
1383
		if (lseek(readFile, (off_t) (readOff * BLCKSZ), SEEK_SET) < 0)
1384 1385
			elog(STOP, "ReadRecord: lseek(logfile %u seg %u off %u) failed: %m",
				 readId, readSeg, readOff);
1386
		if (read(readFile, readBuf, BLCKSZ) != BLCKSZ)
1387 1388
			elog(STOP, "ReadRecord: read(logfile %u seg %u off %u) failed: %m",
				 readId, readSeg, readOff);
1389 1390 1391
		memset(readBuf + EndRecPtr.xrecoff % BLCKSZ, 0,
			   BLCKSZ - EndRecPtr.xrecoff % BLCKSZ);
		if (lseek(readFile, (off_t) (readOff * BLCKSZ), SEEK_SET) < 0)
1392 1393
			elog(STOP, "ReadRecord: lseek(logfile %u seg %u off %u) failed: %m",
				 readId, readSeg, readOff);
1394
		if (write(readFile, readBuf, BLCKSZ) != BLCKSZ)
1395 1396
			elog(STOP, "ReadRecord: write(logfile %u seg %u off %u) failed: %m",
				 readId, readSeg, readOff);
1397 1398 1399 1400
		readOff++;
	}
	else
	{
1401 1402
		Assert(EndRecPtr.xrecoff % BLCKSZ == 0 ||
			   BLCKSZ - EndRecPtr.xrecoff % BLCKSZ < SizeOfXLogRecord);
1403 1404 1405
		readId = tmpRecPtr.xlogid;
		readSeg = tmpRecPtr.xrecoff / XLogSegSize;
		readOff = (tmpRecPtr.xrecoff % XLogSegSize) / BLCKSZ;
1406
		Assert(readOff > 0);
1407 1408 1409
	}
	if (readOff > 0)
	{
1410
		if (!XLByteEQ(tmpRecPtr, EndRecPtr))
1411
			elog(LOG, "Formatting logfile %u seg %u block %u at offset 0",
1412
				 readId, readSeg, readOff);
1413 1414 1415
		readOff *= BLCKSZ;
		memset(readBuf, 0, BLCKSZ);
		readFile = XLogFileOpen(readId, readSeg, false);
1416
		if (lseek(readFile, (off_t) readOff, SEEK_SET) < 0)
1417 1418
			elog(STOP, "ReadRecord: lseek(logfile %u seg %u off %u) failed: %m",
				 readId, readSeg, readOff);
1419 1420 1421
		while (readOff < XLogSegSize)
		{
			if (write(readFile, readBuf, BLCKSZ) != BLCKSZ)
1422 1423
				elog(STOP, "ReadRecord: write(logfile %u seg %u off %u) failed: %m",
					 readId, readSeg, readOff);
1424 1425 1426 1427 1428
			readOff += BLCKSZ;
		}
	}
	if (readFile >= 0)
	{
1429
		if (pg_fsync(readFile) < 0)
1430 1431
			elog(STOP, "ReadRecord: fsync(logfile %u seg %u) failed: %m",
				 readId, readSeg);
1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452
		close(readFile);
		readFile = -1;
	}

	readId = EndRecPtr.xlogid;
	readSeg = (EndRecPtr.xrecoff - 1) / XLogSegSize + 1;
	elog(LOG, "The last logId/logSeg is (%u, %u)", readId, readSeg - 1);
	if (ControlFile->logId != readId || ControlFile->logSeg != readSeg)
	{
		elog(LOG, "Set logId/logSeg in control file");
		ControlFile->logId = readId;
		ControlFile->logSeg = readSeg;
		ControlFile->time = time(NULL);
		UpdateControlFile();
	}
	if (readSeg == XLogLastSeg)
	{
		readSeg = 0;
		readId++;
	}
	{
1453
		char		path[MAXPGPATH];
1454 1455 1456 1457 1458

		XLogFileName(path, readId, readSeg);
		unlink(path);
	}

1459
	return (record);
1460 1461
}

1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534
/*
 * I/O routines for pg_control
 *
 * *ControlFile is a buffer in shared memory that holds an image of the
 * contents of pg_control.  WriteControlFile() initializes pg_control
 * given a preloaded buffer, ReadControlFile() loads the buffer from
 * the pg_control file (during postmaster or standalone-backend startup),
 * and UpdateControlFile() rewrites pg_control after we modify xlog state.
 *
 * For simplicity, WriteControlFile() initializes the fields of pg_control
 * that are related to checking backend/database compatibility, and
 * ReadControlFile() verifies they are correct.  We could split out the
 * I/O and compatibility-check functions, but there seems no need currently.
 */

void
XLOGPathInit(void)
{
	/* Init XLOG file paths */
	snprintf(XLogDir, MAXPGPATH, "%s/pg_xlog", DataDir);
	snprintf(ControlFilePath, MAXPGPATH, "%s/global/pg_control", DataDir);
}

static void
WriteControlFile(void)
{
	int			fd;
	char		buffer[BLCKSZ];
#ifdef USE_LOCALE
	char	   *localeptr;
#endif

	/*
	 * Initialize compatibility-check fields
	 */
	ControlFile->blcksz = BLCKSZ;
	ControlFile->relseg_size = RELSEG_SIZE;
	ControlFile->catalog_version_no = CATALOG_VERSION_NO;
#ifdef USE_LOCALE
	localeptr = setlocale(LC_COLLATE, NULL);
	if (!localeptr)
		elog(STOP, "Invalid LC_COLLATE setting");
	StrNCpy(ControlFile->lc_collate, localeptr, LOCALE_NAME_BUFLEN);
	localeptr = setlocale(LC_CTYPE, NULL);
	if (!localeptr)
		elog(STOP, "Invalid LC_CTYPE setting");
	StrNCpy(ControlFile->lc_ctype, localeptr, LOCALE_NAME_BUFLEN);
	/*
	 * Issue warning notice if initdb'ing in a locale that will not permit
	 * LIKE index optimization.  This is not a clean place to do it, but
	 * I don't see a better place either...
	 */
	if (!locale_is_like_safe())
		elog(NOTICE, "Initializing database with %s collation order."
			 "\n\tThis locale setting will prevent use of index optimization for"
			 "\n\tLIKE and regexp searches.  If you are concerned about speed of"
			 "\n\tsuch queries, you may wish to set LC_COLLATE to \"C\" and"
			 "\n\tre-initdb.  For more information see the Administrator's Guide.",
			 ControlFile->lc_collate);
#else
	strcpy(ControlFile->lc_collate, "C");
	strcpy(ControlFile->lc_ctype, "C");
#endif

	/*
	 * We write out BLCKSZ bytes into pg_control, zero-padding the
	 * excess over sizeof(ControlFileData).  This reduces the odds
	 * of premature-EOF errors when reading pg_control.  We'll still
	 * fail when we check the contents of the file, but hopefully with
	 * a more specific error than "couldn't read pg_control".
	 */
	if (sizeof(ControlFileData) > BLCKSZ)
		elog(STOP, "sizeof(ControlFileData) is too large ... fix xlog.c");
1535 1536 1537 1538 1539 1540 1541

	INIT_CRC64(ControlFile->crc);
	COMP_CRC64(ControlFile->crc, 
		((char*)ControlFile + offsetof(ControlFileData, logId)), 
		(sizeof(ControlFileData) - offsetof(ControlFileData, logId)));
	FIN_CRC64(ControlFile->crc);

1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552
	memset(buffer, 0, BLCKSZ);
	memcpy(buffer, ControlFile, sizeof(ControlFileData));

	fd = BasicOpenFile(ControlFilePath, O_RDWR | O_CREAT | O_EXCL | PG_BINARY, S_IRUSR | S_IWUSR);
	if (fd < 0)
		elog(STOP, "WriteControlFile failed to create control file (%s): %m",
			 ControlFilePath);

	if (write(fd, buffer, BLCKSZ) != BLCKSZ)
		elog(STOP, "WriteControlFile failed to write control file: %m");

1553
	if (pg_fsync(fd) != 0)
1554 1555 1556 1557 1558 1559 1560 1561
		elog(STOP, "WriteControlFile failed to fsync control file: %m");

	close(fd);
}

static void
ReadControlFile(void)
{
1562
	crc64		crc;
1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576
	int			fd;

	/*
	 * Read data...
	 */
	fd = BasicOpenFile(ControlFilePath, O_RDWR | PG_BINARY, S_IRUSR | S_IWUSR);
	if (fd < 0)
		elog(STOP, "open(\"%s\") failed: %m", ControlFilePath);

	if (read(fd, ControlFile, sizeof(ControlFileData)) != sizeof(ControlFileData))
		elog(STOP, "read(\"%s\") failed: %m", ControlFilePath);

	close(fd);

1577 1578 1579 1580 1581 1582 1583 1584 1585
	INIT_CRC64(crc);
	COMP_CRC64(crc, 
		((char*)ControlFile + offsetof(ControlFileData, logId)), 
		(sizeof(ControlFileData) - offsetof(ControlFileData, logId)));
	FIN_CRC64(crc);

	if (crc.crc1 != ControlFile->crc.crc1 || crc.crc2 != ControlFile->crc.crc2)
		elog(STOP, "Invalid CRC in control file");

1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620
	/*
	 * Do compatibility checking immediately.  We do this here for 2 reasons:
	 *
	 * (1) if the database isn't compatible with the backend executable,
	 * we want to abort before we can possibly do any damage;
	 *
	 * (2) this code is executed in the postmaster, so the setlocale() will
	 * propagate to forked backends, which aren't going to read this file
	 * for themselves.  (These locale settings are considered critical
	 * compatibility items because they can affect sort order of indexes.)
	 */
	if (ControlFile->blcksz != BLCKSZ)
		elog(STOP, "database was initialized with BLCKSZ %d,\n\tbut the backend was compiled with BLCKSZ %d.\n\tlooks like you need to initdb.",
			 ControlFile->blcksz, BLCKSZ);
	if (ControlFile->relseg_size != RELSEG_SIZE)
		elog(STOP, "database was initialized with RELSEG_SIZE %d,\n\tbut the backend was compiled with RELSEG_SIZE %d.\n\tlooks like you need to initdb.",
			 ControlFile->relseg_size, RELSEG_SIZE);
	if (ControlFile->catalog_version_no != CATALOG_VERSION_NO)
		elog(STOP, "database was initialized with CATALOG_VERSION_NO %d,\n\tbut the backend was compiled with CATALOG_VERSION_NO %d.\n\tlooks like you need to initdb.",
			 ControlFile->catalog_version_no, CATALOG_VERSION_NO);
#ifdef USE_LOCALE
	if (setlocale(LC_COLLATE, ControlFile->lc_collate) == NULL)
		elog(STOP, "database was initialized with LC_COLLATE '%s',\n\twhich is not recognized by setlocale().\n\tlooks like you need to initdb.",
			 ControlFile->lc_collate);
	if (setlocale(LC_CTYPE, ControlFile->lc_ctype) == NULL)
		elog(STOP, "database was initialized with LC_CTYPE '%s',\n\twhich is not recognized by setlocale().\n\tlooks like you need to initdb.",
			 ControlFile->lc_ctype);
#else
	if (strcmp(ControlFile->lc_collate, "C") != 0 ||
		strcmp(ControlFile->lc_ctype, "C") != 0)
		elog(STOP, "database was initialized with LC_COLLATE '%s' and LC_CTYPE '%s',\n\tbut the backend was compiled without locale support.\n\tlooks like you need to initdb or recompile.",
			 ControlFile->lc_collate, ControlFile->lc_ctype);
#endif
}

1621
void
1622
UpdateControlFile(void)
1623
{
1624
	int			fd;
1625

1626 1627 1628 1629 1630 1631
	INIT_CRC64(ControlFile->crc);
	COMP_CRC64(ControlFile->crc, 
		((char*)ControlFile + offsetof(ControlFileData, logId)), 
		(sizeof(ControlFileData) - offsetof(ControlFileData, logId)));
	FIN_CRC64(ControlFile->crc);

1632
	fd = BasicOpenFile(ControlFilePath, O_RDWR | PG_BINARY, S_IRUSR | S_IWUSR);
1633
	if (fd < 0)
1634
		elog(STOP, "open(\"%s\") failed: %m", ControlFilePath);
1635

1636
	if (write(fd, ControlFile, sizeof(ControlFileData)) != sizeof(ControlFileData))
1637
		elog(STOP, "write(cntlfile) failed: %m");
1638

1639
	if (pg_fsync(fd) != 0)
1640
		elog(STOP, "fsync(cntlfile) failed: %m");
1641 1642 1643 1644

	close(fd);
}

1645 1646 1647 1648
/*
 * Management of shared memory for XLOG
 */

1649
int
1650
XLOGShmemSize(void)
1651 1652 1653 1654
{
	if (XLOGbuffers < MinXLOGbuffers)
		XLOGbuffers = MinXLOGbuffers;

1655
	return (sizeof(XLogCtlData) + BLCKSZ * XLOGbuffers +
1656 1657
			sizeof(XLogRecPtr) * XLOGbuffers +
			sizeof(ControlFileData));
1658 1659 1660 1661 1662
}

void
XLOGShmemInit(void)
{
1663
	bool		found;
1664

1665
	/* this must agree with space requested by XLOGShmemSize() */
1666 1667 1668
	if (XLOGbuffers < MinXLOGbuffers)
		XLOGbuffers = MinXLOGbuffers;

1669 1670
	XLogCtl = (XLogCtlData *)
		ShmemInitStruct("XLOG Ctl", sizeof(XLogCtlData) + BLCKSZ * XLOGbuffers +
1671 1672
						sizeof(XLogRecPtr) * XLOGbuffers, &found);
	Assert(!found);
1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683
	ControlFile = (ControlFileData *)
		ShmemInitStruct("Control File", sizeof(ControlFileData), &found);
	Assert(!found);

	/*
	 * If we are not in bootstrap mode, pg_control should already exist.
	 * Read and validate it immediately (see comments in ReadControlFile()
	 * for the reasons why).
	 */
	if (!IsBootstrapProcessingMode())
		ReadControlFile();
1684 1685 1686 1687 1688 1689 1690 1691
}

/*
 * This func must be called ONCE on system install
 */
void
BootStrapXLOG()
{
1692
	CheckPoint	checkPoint;
1693
	char		buffer[BLCKSZ];
1694
	bool        usexistent = false;
1695 1696
	XLogPageHeader page = (XLogPageHeader) buffer;
	XLogRecord *record;
1697
	crc64		crc;
1698 1699 1700 1701 1702

	checkPoint.redo.xlogid = 0;
	checkPoint.redo.xrecoff = SizeOfXLogPHD;
	checkPoint.undo = checkPoint.redo;
	checkPoint.nextXid = FirstTransactionId;
1703
	checkPoint.nextOid = BootstrapObjectIdData;
V
WAL  
Vadim B. Mikheev 已提交
1704
	checkPoint.ThisStartUpID = 0;
V
misc  
Vadim B. Mikheev 已提交
1705
	checkPoint.Shutdown = true;
1706

1707 1708 1709 1710
	ShmemVariableCache->nextXid = checkPoint.nextXid;
	ShmemVariableCache->nextOid = checkPoint.nextOid;
	ShmemVariableCache->oidCount = 0;

1711 1712 1713
	memset(buffer, 0, BLCKSZ);
	page->xlp_magic = XLOG_PAGE_MAGIC;
	page->xlp_info = 0;
1714 1715 1716
	record = (XLogRecord *) ((char *) page + SizeOfXLogPHD);
	record->xl_prev.xlogid = 0;
	record->xl_prev.xrecoff = 0;
1717 1718 1719 1720 1721
	record->xl_xact_prev = record->xl_prev;
	record->xl_xid = InvalidTransactionId;
	record->xl_len = sizeof(checkPoint);
	record->xl_info = 0;
	record->xl_rmid = RM_XLOG_ID;
1722
	memcpy((char *) record + SizeOfXLogRecord, &checkPoint, sizeof(checkPoint));
1723

1724 1725 1726 1727 1728 1729 1730
	INIT_CRC64(crc);
	COMP_CRC64(crc, ((char*)&checkPoint), sizeof(checkPoint));
	COMP_CRC64(crc, ((char*)record + offsetof(XLogRecord, xl_prev)), 
				(SizeOfXLogRecord - offsetof(XLogRecord, xl_prev)));
	FIN_CRC64(crc);
	record->xl_crc = crc;

V
Vadim B. Mikheev 已提交
1731
	logFile = XLogFileInit(0, 0, &usexistent);
1732

1733
	if (write(logFile, buffer, BLCKSZ) != BLCKSZ)
1734
		elog(STOP, "BootStrapXLOG failed to write logfile: %m");
1735

1736
	if (pg_fsync(logFile) != 0)
1737
		elog(STOP, "BootStrapXLOG failed to fsync logfile: %m");
1738 1739 1740 1741

	close(logFile);
	logFile = -1;

1742
	memset(ControlFile, 0, sizeof(ControlFileData));
1743 1744 1745 1746 1747
	ControlFile->logId = 0;
	ControlFile->logSeg = 1;
	ControlFile->checkPoint = checkPoint.redo;
	ControlFile->time = time(NULL);
	ControlFile->state = DB_SHUTDOWNED;
1748
	/* some additional ControlFile fields are set in WriteControlFile() */
1749

1750
	WriteControlFile();
1751 1752
}

1753
static char *
1754 1755
str_time(time_t tnow)
{
1756
	static char buf[20];
1757

1758 1759 1760
	strftime(buf, sizeof(buf),
			 "%Y-%m-%d %H:%M:%S",
			 localtime(&tnow));
1761

1762
	return buf;
1763 1764 1765 1766 1767 1768 1769 1770
}

/*
 * This func must be called ONCE on system startup
 */
void
StartupXLOG()
{
1771 1772 1773 1774 1775
	XLogCtlInsert *Insert;
	CheckPoint	checkPoint;
	XLogRecPtr	RecPtr,
				LastRec;
	XLogRecord *record;
1776
	char		buffer[_INTL_MAXLOGRECSZ + SizeOfXLogRecord];
1777

1778
	elog(LOG, "starting up");
1779
	CritSectionCount++;
1780

1781 1782
	XLogCtl->xlblocks = (XLogRecPtr *) (((char *) XLogCtl) + sizeof(XLogCtlData));
	XLogCtl->pages = ((char *) XLogCtl->xlblocks + sizeof(XLogRecPtr) * XLOGbuffers);
1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795
	XLogCtl->XLogCacheByte = BLCKSZ * XLOGbuffers;
	XLogCtl->XLogCacheBlck = XLOGbuffers - 1;
	memset(XLogCtl->xlblocks, 0, sizeof(XLogRecPtr) * XLOGbuffers);
	XLogCtl->LgwrRqst = LgwrRqst;
	XLogCtl->LgwrResult = LgwrResult;
	XLogCtl->Insert.LgwrResult = LgwrResult;
	XLogCtl->Insert.curridx = 0;
	XLogCtl->Insert.currpage = (XLogPageHeader) (XLogCtl->pages);
	XLogCtl->Write.LgwrResult = LgwrResult;
	XLogCtl->Write.curridx = 0;
	S_INIT_LOCK(&(XLogCtl->insert_lck));
	S_INIT_LOCK(&(XLogCtl->info_lck));
	S_INIT_LOCK(&(XLogCtl->lgwr_lck));
V
Vadim B. Mikheev 已提交
1796
	S_INIT_LOCK(&(XLogCtl->chkp_lck));
1797 1798

	/*
1799 1800 1801 1802
	 * Read control file and check XLOG status looks valid.
	 *
	 * Note: in most control paths, *ControlFile is already valid and we
	 * need not do ReadControlFile() here, but might as well do it to be sure.
1803
	 */
1804
	ReadControlFile();
1805

1806 1807 1808 1809
	if (ControlFile->logSeg == 0 ||
		ControlFile->time <= 0 ||
		ControlFile->state < DB_SHUTDOWNED ||
		ControlFile->state > DB_IN_PRODUCTION ||
1810
		!XRecOffIsValid(ControlFile->checkPoint.xrecoff))
1811
		elog(STOP, "control file context is broken");
1812 1813

	if (ControlFile->state == DB_SHUTDOWNED)
1814
		elog(LOG, "database system was shut down at %s",
1815
			 str_time(ControlFile->time));
1816
	else if (ControlFile->state == DB_SHUTDOWNING)
1817
		elog(LOG, "database system shutdown was interrupted at %s",
1818
			 str_time(ControlFile->time));
1819
	else if (ControlFile->state == DB_IN_RECOVERY)
1820
		elog(LOG, "database system was interrupted being in recovery at %s\n"
1821
			 "\tThis propably means that some data blocks are corrupted\n"
1822
			 "\tand you will have to use last backup for recovery.",
1823
			 str_time(ControlFile->time));
1824
	else if (ControlFile->state == DB_IN_PRODUCTION)
1825
		elog(LOG, "database system was interrupted at %s",
1826
			 str_time(ControlFile->time));
1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837

	LastRec = RecPtr = ControlFile->checkPoint;
	if (!XRecOffIsValid(RecPtr.xrecoff))
		elog(STOP, "Invalid checkPoint in control file");
	elog(LOG, "CheckPoint record at (%u, %u)", RecPtr.xlogid, RecPtr.xrecoff);

	record = ReadRecord(&RecPtr, buffer);
	if (record->xl_rmid != RM_XLOG_ID)
		elog(STOP, "Invalid RMID in checkPoint record");
	if (record->xl_len != sizeof(checkPoint))
		elog(STOP, "Invalid length of checkPoint record");
1838
	checkPoint = *((CheckPoint *) ((char *) record + SizeOfXLogRecord));
1839

V
Vadim B. Mikheev 已提交
1840
	elog(LOG, "Redo record at (%u, %u); Undo record at (%u, %u); Shutdown %s",
1841
		 checkPoint.redo.xlogid, checkPoint.redo.xrecoff,
V
Vadim B. Mikheev 已提交
1842 1843
		 checkPoint.undo.xlogid, checkPoint.undo.xrecoff,
		 (checkPoint.Shutdown) ? "TRUE" : "FALSE");
1844
	elog(LOG, "NextTransactionId: %u; NextOid: %u",
1845 1846
		 checkPoint.nextXid, checkPoint.nextOid);
	if (checkPoint.nextXid < FirstTransactionId ||
1847 1848 1849 1850 1851
		checkPoint.nextOid < BootstrapObjectIdData)
		elog(STOP, "Invalid NextTransactionId/NextOid");

	ShmemVariableCache->nextXid = checkPoint.nextXid;
	ShmemVariableCache->nextOid = checkPoint.nextOid;
1852
	ShmemVariableCache->oidCount = 0;
1853

V
WAL  
Vadim B. Mikheev 已提交
1854
	ThisStartUpID = checkPoint.ThisStartUpID;
1855 1856
	RedoRecPtr = XLogCtl->Insert.RedoRecPtr = 
		XLogCtl->RedoRecPtr = checkPoint.redo;
V
WAL  
Vadim B. Mikheev 已提交
1857

1858 1859 1860 1861 1862
	if (XLByteLT(RecPtr, checkPoint.redo))
		elog(STOP, "Invalid redo in checkPoint record");
	if (checkPoint.undo.xrecoff == 0)
		checkPoint.undo = RecPtr;

V
Vadim B. Mikheev 已提交
1863 1864
	if (XLByteLT(checkPoint.undo, RecPtr) || 
		XLByteLT(checkPoint.redo, RecPtr))
1865
	{
V
Vadim B. Mikheev 已提交
1866 1867
		if (checkPoint.Shutdown)
			elog(STOP, "Invalid Redo/Undo record in shutdown checkpoint");
1868
		if (ControlFile->state == DB_SHUTDOWNED)
1869
			elog(STOP, "Invalid Redo/Undo record in shut down state");
V
WAL  
Vadim B. Mikheev 已提交
1870
		InRecovery = true;
1871 1872
	}
	else if (ControlFile->state != DB_SHUTDOWNED)
V
Vadim B. Mikheev 已提交
1873
	{
V
WAL  
Vadim B. Mikheev 已提交
1874
		InRecovery = true;
V
Vadim B. Mikheev 已提交
1875
	}
1876

V
WAL  
Vadim B. Mikheev 已提交
1877 1878
	/* REDO */
	if (InRecovery)
1879
	{
1880 1881
		elog(LOG, "database system was not properly shut down; "
			 "automatic recovery in progress...");
1882 1883 1884 1885
		ControlFile->state = DB_IN_RECOVERY;
		ControlFile->time = time(NULL);
		UpdateControlFile();

V
Vadim B. Mikheev 已提交
1886
		XLogOpenLogRelation();	/* open pg_log */
V
WAL  
Vadim B. Mikheev 已提交
1887
		XLogInitRelationCache();
V
Vadim B. Mikheev 已提交
1888

1889 1890 1891
		/* Is REDO required ? */
		if (XLByteLT(checkPoint.redo, RecPtr))
			record = ReadRecord(&(checkPoint.redo), buffer);
1892
		else	/* read past CheckPoint record */
1893 1894 1895 1896
			record = ReadRecord(NULL, buffer);

		if (record->xl_len != 0)
		{
V
WAL  
Vadim B. Mikheev 已提交
1897
			InRedo = true;
1898
			elog(LOG, "redo starts at (%u, %u)",
1899
				 ReadRecPtr.xlogid, ReadRecPtr.xrecoff);
1900 1901 1902 1903
			do
			{
				if (record->xl_xid >= ShmemVariableCache->nextXid)
					ShmemVariableCache->nextXid = record->xl_xid + 1;
V
WAL  
Vadim B. Mikheev 已提交
1904 1905 1906 1907
				if (XLOG_DEBUG)
				{
					char	buf[8192];

1908 1909 1910
					sprintf(buf, "REDO @ %u/%u; LSN %u/%u: ", 
						ReadRecPtr.xlogid, ReadRecPtr.xrecoff,
						EndRecPtr.xlogid, EndRecPtr.xrecoff);
V
WAL  
Vadim B. Mikheev 已提交
1911 1912 1913 1914 1915 1916 1917 1918
					xlog_outrec(buf, record);
					strcat(buf, " - ");
					RmgrTable[record->xl_rmid].rm_desc(buf, 
						record->xl_info, XLogRecGetData(record));
					strcat(buf, "\n");
					write(2, buf, strlen(buf));
				}

1919 1920 1921
				if (record->xl_info & (XLR_BKP_BLOCK_1|XLR_BKP_BLOCK_2))
					RestoreBkpBlocks(record, EndRecPtr);

1922 1923 1924
				RmgrTable[record->xl_rmid].rm_redo(EndRecPtr, record);
				record = ReadRecord(NULL, buffer);
			} while (record->xl_len != 0);
1925
			elog(LOG, "redo done at (%u, %u)",
1926
				 ReadRecPtr.xlogid, ReadRecPtr.xrecoff);
1927
			LastRec = ReadRecPtr;
V
WAL  
Vadim B. Mikheev 已提交
1928
			InRedo = false;
1929 1930
		}
		else
1931
			elog(LOG, "redo is not required");
V
WAL  
Vadim B. Mikheev 已提交
1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956
	}

	/* Init xlog buffer cache */
	record = ReadRecord(&LastRec, buffer);
	logId = EndRecPtr.xlogid;
	logSeg = (EndRecPtr.xrecoff - 1) / XLogSegSize;
	logOff = 0;
	logFile = XLogFileOpen(logId, logSeg, false);
	XLogCtl->xlblocks[0].xlogid = logId;
	XLogCtl->xlblocks[0].xrecoff =
		((EndRecPtr.xrecoff - 1) / BLCKSZ + 1) * BLCKSZ;
	Insert = &XLogCtl->Insert;
	memcpy((char *) (Insert->currpage), readBuf, BLCKSZ);
	Insert->currpos = ((char *) Insert->currpage) +
		(EndRecPtr.xrecoff + BLCKSZ - XLogCtl->xlblocks[0].xrecoff);
	Insert->PrevRecord = LastRec;

	LgwrRqst.Write = LgwrRqst.Flush =
	LgwrResult.Write = LgwrResult.Flush = EndRecPtr;

	XLogCtl->Write.LgwrResult = LgwrResult;
	Insert->LgwrResult = LgwrResult;

	XLogCtl->LgwrRqst = LgwrRqst;
	XLogCtl->LgwrResult = LgwrResult;
1957

V
Vadim B. Mikheev 已提交
1958
#ifdef NOT_USED
V
WAL  
Vadim B. Mikheev 已提交
1959 1960 1961
	/* UNDO */
	if (InRecovery)
	{
1962 1963 1964
		RecPtr = ReadRecPtr;
		if (XLByteLT(checkPoint.undo, RecPtr))
		{
1965
			elog(LOG, "undo starts at (%u, %u)",
1966
				 RecPtr.xlogid, RecPtr.xrecoff);
1967 1968 1969
			do
			{
				record = ReadRecord(&RecPtr, buffer);
1970
				if (TransactionIdIsValid(record->xl_xid) &&
1971
					!TransactionIdDidCommit(record->xl_xid))
V
misc  
Vadim B. Mikheev 已提交
1972
					RmgrTable[record->xl_rmid].rm_undo(EndRecPtr, record);
1973 1974
				RecPtr = record->xl_prev;
			} while (XLByteLE(checkPoint.undo, RecPtr));
1975
			elog(LOG, "undo done at (%u, %u)",
1976
				 ReadRecPtr.xlogid, ReadRecPtr.xrecoff);
1977 1978
		}
		else
1979
			elog(LOG, "undo is not required");
1980
	}
V
WAL  
Vadim B. Mikheev 已提交
1981
#endif
1982

V
WAL  
Vadim B. Mikheev 已提交
1983
	if (InRecovery)
1984 1985
	{
		CreateCheckPoint(true);
V
WAL  
Vadim B. Mikheev 已提交
1986
		XLogCloseRelationCache();
1987
	}
1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004

	if (XLOGfiles > 0)		/* pre-allocate log files */
	{
		uint32	_logId = logId,
				_logSeg = logSeg;
		int		lf, i;
		bool	usexistent;

		for (i = 1; i <= XLOGfiles; i++)
		{
			NextLogSeg(_logId, _logSeg);
			usexistent = false;
			lf = XLogFileInit(_logId, _logSeg, &usexistent);
			close(lf);
		}
	}

V
WAL  
Vadim B. Mikheev 已提交
2005
	InRecovery = false;
2006 2007 2008 2009 2010

	ControlFile->state = DB_IN_PRODUCTION;
	ControlFile->time = time(NULL);
	UpdateControlFile();

V
WAL  
Vadim B. Mikheev 已提交
2011 2012 2013
	ThisStartUpID++;
	XLogCtl->ThisStartUpID = ThisStartUpID;

2014
	elog(LOG, "database system is in production state");
2015
	CritSectionCount--;
2016 2017 2018 2019

	return;
}

V
WAL  
Vadim B. Mikheev 已提交
2020
/*
2021 2022
 * Postmaster uses it to set ThisStartUpID & RedoRecPtr from
 * XLogCtlData located in shmem after successful startup.
V
WAL  
Vadim B. Mikheev 已提交
2023 2024 2025 2026 2027
 */
void
SetThisStartUpID(void)
{
	ThisStartUpID = XLogCtl->ThisStartUpID;
2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045
	RedoRecPtr = XLogCtl->RedoRecPtr;
}

/*
 * CheckPoint-er called by postmaster creates copy of RedoRecPtr
 * for postmaster in shmem. Postmaster uses GetRedoRecPtr after
 * that to update its own copy of RedoRecPtr.
 */
void
SetRedoRecPtr(void)
{
	XLogCtl->RedoRecPtr = RedoRecPtr;
}

void
GetRedoRecPtr(void)
{
	RedoRecPtr = XLogCtl->RedoRecPtr;
V
WAL  
Vadim B. Mikheev 已提交
2046 2047
}

2048 2049 2050 2051 2052 2053
/*
 * This func must be called ONCE on system shutdown
 */
void
ShutdownXLOG()
{
2054
	elog(LOG, "shutting down");
2055

2056
	CritSectionCount++;
V
Vadim B. Mikheev 已提交
2057
	CreateDummyCaches();
2058
	CreateCheckPoint(true);
2059
	CritSectionCount--;
2060

2061
	elog(LOG, "database system is shut down");
2062 2063
}

V
Vadim B. Mikheev 已提交
2064 2065
extern XLogRecPtr	GetUndoRecPtr(void);

2066 2067 2068
void
CreateCheckPoint(bool shutdown)
{
2069 2070 2071
	CheckPoint	checkPoint;
	XLogRecPtr	recptr;
	XLogCtlInsert *Insert = &XLogCtl->Insert;
2072
	XLogRecData	rdata;
2073 2074
	uint32		freespace;
	uint16		curridx;
V
Vadim B. Mikheev 已提交
2075 2076 2077
	uint32		_logId;
	uint32		_logSeg;
	char		archdir[MAXPGPATH];
2078
	unsigned	spins = 0;
V
Vadim B. Mikheev 已提交
2079 2080 2081 2082

	if (MyLastRecPtr.xrecoff != 0)
		elog(ERROR, "CreateCheckPoint: cannot be called inside transaction block");
 
2083
	START_CRIT_SECTION();
2084 2085

	/* Grab lock, using larger than normal sleep between tries (1 sec) */
V
Vadim B. Mikheev 已提交
2086 2087
	while (TAS(&(XLogCtl->chkp_lck)))
	{
2088
		S_LOCK_SLEEP_INTERVAL(&(XLogCtl->chkp_lck), spins++, 1000000);
V
Vadim B. Mikheev 已提交
2089
	}
2090 2091 2092 2093 2094 2095 2096 2097

	memset(&checkPoint, 0, sizeof(checkPoint));
	if (shutdown)
	{
		ControlFile->state = DB_SHUTDOWNING;
		ControlFile->time = time(NULL);
		UpdateControlFile();
	}
V
WAL  
Vadim B. Mikheev 已提交
2098 2099
	checkPoint.ThisStartUpID = ThisStartUpID;
	checkPoint.Shutdown = shutdown;
2100 2101

	/* Get REDO record ptr */
2102
	S_LOCK(&(XLogCtl->insert_lck));
2103
	freespace = ((char *) Insert->currpage) + BLCKSZ - Insert->currpos;
2104 2105 2106 2107 2108
	if (freespace < SizeOfXLogRecord)
	{
		curridx = NextBufIdx(Insert->curridx);
		if (XLByteLE(XLogCtl->xlblocks[curridx], LgwrResult.Write))
			InitXLBuffer(curridx);
2109
		else
2110 2111 2112 2113 2114 2115
			GetFreeXLBuffer();
		freespace = BLCKSZ - SizeOfXLogPHD;
	}
	else
		curridx = Insert->curridx;
	checkPoint.redo.xlogid = XLogCtl->xlblocks[curridx].xlogid;
2116 2117
	checkPoint.redo.xrecoff = XLogCtl->xlblocks[curridx].xrecoff - BLCKSZ +
		Insert->currpos - ((char *) Insert->currpage);
2118
	RedoRecPtr = XLogCtl->Insert.RedoRecPtr = checkPoint.redo;
2119 2120 2121 2122 2123 2124 2125
	S_UNLOCK(&(XLogCtl->insert_lck));

	SpinAcquire(XidGenLockId);
	checkPoint.nextXid = ShmemVariableCache->nextXid;
	SpinRelease(XidGenLockId);
	SpinAcquire(OidGenLockId);
	checkPoint.nextOid = ShmemVariableCache->nextOid;
2126 2127 2128
	if (!shutdown)
		checkPoint.nextOid += ShmemVariableCache->oidCount;

2129 2130
	SpinRelease(OidGenLockId);

V
Vadim B. Mikheev 已提交
2131
	FlushBufferPool();
2132

V
Vadim B. Mikheev 已提交
2133
	/* Get UNDO record ptr - should use oldest of PROC->logRec */
V
Vadim B. Mikheev 已提交
2134
	checkPoint.undo = GetUndoRecPtr();
2135 2136 2137 2138

	if (shutdown && checkPoint.undo.xrecoff != 0)
		elog(STOP, "Active transaction while data base is shutting down");

2139 2140 2141 2142 2143 2144
	rdata.buffer = InvalidBuffer;
	rdata.data = (char *)(&checkPoint);
	rdata.len = sizeof(checkPoint);
	rdata.next = NULL;

	recptr = XLogInsert(RM_XLOG_ID, XLOG_CHECKPOINT, &rdata);
2145 2146 2147 2148 2149 2150 2151 2152

	if (shutdown && !XLByteEQ(checkPoint.redo, MyLastRecPtr))
		elog(STOP, "XLog concurrent activity while data base is shutting down");

	XLogFlush(recptr);

	SpinAcquire(ControlFileLockId);
	if (shutdown)
2153 2154
	{
		/* probably should delete extra log files */
2155
		ControlFile->state = DB_SHUTDOWNED;
2156 2157
	}
	else	/* create new log file(s) */
V
Vadim B. Mikheev 已提交
2158
	{
2159 2160 2161 2162 2163 2164
		int		lf;
		bool	usexistent = true;

		_logId = recptr.xlogid;
		_logSeg = (recptr.xrecoff - 1) / XLogSegSize;
		if (XLOGfiles > 0)
V
Vadim B. Mikheev 已提交
2165
		{
2166 2167
			struct timeval	delay;
			int				i;
V
Vadim B. Mikheev 已提交
2168

2169
			for (i = 1; i <= XLOGfiles; i++)
V
Vadim B. Mikheev 已提交
2170
			{
2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183
				usexistent = true;
				NextLogSeg(_logId, _logSeg);
				lf = XLogFileInit(_logId, _logSeg, &usexistent);
				close(lf);
				/*
				 * Give up ControlFileLockId for 1/50 sec to let other
				 * backends switch to new log file in XLogWrite()
				 */
				SpinRelease(ControlFileLockId);
				delay.tv_sec = 0;
				delay.tv_usec = 20000;
				(void) select(0, NULL, NULL, NULL, &delay);
				SpinAcquire(ControlFileLockId);
V
Vadim B. Mikheev 已提交
2184
			}
2185 2186 2187 2188 2189
		}
		else if ((recptr.xrecoff - 1) % XLogSegSize >= 
			(uint32) (0.75 * XLogSegSize))
		{
			NextLogSeg(_logId, _logSeg);
V
Vadim B. Mikheev 已提交
2190 2191 2192 2193 2194
			lf = XLogFileInit(_logId, _logSeg, &usexistent);
			close(lf);
		}
	}

2195
	ControlFile->checkPoint = MyLastRecPtr;
V
Vadim B. Mikheev 已提交
2196
	strcpy(archdir, ControlFile->archdir);
2197 2198 2199 2200
	ControlFile->time = time(NULL);
	UpdateControlFile();
	SpinRelease(ControlFileLockId);

V
Vadim B. Mikheev 已提交
2201 2202
	/*
	 * Delete offline log files. Get oldest online
2203 2204
	 * log file from redo or undo record, whatever
	 * is older.
V
Vadim B. Mikheev 已提交
2205
	 */
2206 2207
	if (checkPoint.undo.xrecoff != 0 && 
		XLByteLT(checkPoint.undo, checkPoint.redo))
V
Vadim B. Mikheev 已提交
2208 2209 2210 2211
	{
		_logId = checkPoint.undo.xlogid;
		_logSeg = checkPoint.undo.xrecoff / XLogSegSize;
	}
2212 2213 2214 2215 2216
	else
	{
		_logId = checkPoint.redo.xlogid;
		_logSeg = checkPoint.redo.xrecoff / XLogSegSize;
	}
V
Vadim B. Mikheev 已提交
2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231
	if (_logId || _logSeg)
	{
		if (_logSeg)
			_logSeg--;
		else
		{
			_logId--;
			_logSeg = 0;
		}
		MoveOfflineLogs(archdir, _logId, _logSeg);
	}

	S_UNLOCK(&(XLogCtl->chkp_lck));

	MyLastRecPtr.xrecoff = 0;	/* to avoid commit record */
2232
	END_CRIT_SECTION();
V
Vadim B. Mikheev 已提交
2233

2234 2235
	return;
}
V
WAL  
Vadim B. Mikheev 已提交
2236

2237 2238 2239 2240 2241
void XLogPutNextOid(Oid nextOid);

void
XLogPutNextOid(Oid nextOid)
{
2242
	XLogRecData		rdata;
2243

2244 2245 2246 2247 2248 2249
	rdata.buffer = InvalidBuffer;
	rdata.data = (char *)(&nextOid);
	rdata.len = sizeof(Oid);
	rdata.next = NULL;
	(void) XLogInsert(RM_XLOG_ID, XLOG_NEXTOID, &rdata);
}
V
WAL  
Vadim B. Mikheev 已提交
2250 2251 2252 2253

void
xlog_redo(XLogRecPtr lsn, XLogRecord *record)
{
2254 2255 2256 2257 2258 2259 2260 2261 2262 2263
	uint8	info = record->xl_info & ~XLR_INFO_MASK;

	if (info == XLOG_NEXTOID)
	{
		Oid		nextOid;

		memcpy(&nextOid, XLogRecGetData(record), sizeof(Oid));
		if (ShmemVariableCache->nextOid < nextOid)
			ShmemVariableCache->nextOid = nextOid;
	}
V
WAL  
Vadim B. Mikheev 已提交
2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286
}
 
void
xlog_undo(XLogRecPtr lsn, XLogRecord *record)
{
}
 
void
xlog_desc(char *buf, uint8 xl_info, char* rec)
{
	uint8	info = xl_info & ~XLR_INFO_MASK;

	if (info == XLOG_CHECKPOINT)
	{
		CheckPoint	*checkpoint = (CheckPoint*) rec;
		sprintf(buf + strlen(buf), "checkpoint: redo %u/%u; undo %u/%u; "
		"sui %u; xid %u; oid %u; %s",
			checkpoint->redo.xlogid, checkpoint->redo.xrecoff,
			checkpoint->undo.xlogid, checkpoint->undo.xrecoff,
			checkpoint->ThisStartUpID, checkpoint->nextXid, 
			checkpoint->nextOid,
			(checkpoint->Shutdown) ? "shutdown" : "online");
	}
2287 2288 2289 2290 2291 2292 2293
	else if (info == XLOG_NEXTOID)
	{
		Oid		nextOid;

		memcpy(&nextOid, rec, sizeof(Oid));
		sprintf(buf + strlen(buf), "nextOid: %u", nextOid);
	}
V
WAL  
Vadim B. Mikheev 已提交
2294 2295 2296 2297 2298 2299 2300
	else
		strcat(buf, "UNKNOWN");
}

static void
xlog_outrec(char *buf, XLogRecord *record)
{
2301 2302 2303 2304
	int		bkpb;
	int		i;

	sprintf(buf + strlen(buf), "prev %u/%u; xprev %u/%u; xid %u",
V
WAL  
Vadim B. Mikheev 已提交
2305 2306
		record->xl_prev.xlogid, record->xl_prev.xrecoff,
		record->xl_xact_prev.xlogid, record->xl_xact_prev.xrecoff,
2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319
		record->xl_xid);

	for (i = 0, bkpb = 0; i < 2; i++)
	{
		if (!(record->xl_info & (XLR_SET_BKP_BLOCK(i))))
			continue;
		bkpb++;
	}

	if (bkpb)
		sprintf(buf + strlen(buf), "; bkpb %d", bkpb);

	sprintf(buf + strlen(buf), ": %s",
V
WAL  
Vadim B. Mikheev 已提交
2320 2321
		RmgrTable[record->xl_rmid].rm_name);
}