xlog.c 53.2 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.42 2000/12/11 19:27:42 vadim 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"
V
Vadim B. Mikheev 已提交
34 35
#include "access/xlog.h"
#include "access/xlogutils.h"
36
#include "utils/builtins.h"
37
#include "utils/relcache.h"
38

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

V
Vadim B. Mikheev 已提交
41
int			XLOGbuffers = 8;
42
XLogRecPtr	MyLastRecPtr = {0, 0};
43
uint32		StopIfError = 0;
44
bool		InRecovery = false;
V
WAL  
Vadim B. Mikheev 已提交
45 46
StartUpID	ThisStartUpID = 0;

V
Vadim B. Mikheev 已提交
47
int			XLOG_DEBUG = 0;
48

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

/* To generate new xid */
53 54
SPINLOCK	XidGenLockId;

55 56 57
static char		XLogDir[MAXPGPATH];
static char		ControlFilePath[MAXPGPATH];

58
#define MinXLOGbuffers	4
59 60 61

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

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

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

typedef struct XLogCtlWrite
{
83 84
	XLgwrResult LgwrResult;
	uint16		curridx;		/* index of next block to write */
85 86
} XLogCtlWrite;

87

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

105
static XLogCtlData *XLogCtl = NULL;
106

107 108 109 110
/*
 * Contents of pg_control
 */

111 112
typedef enum DBState
{
113 114
	DB_STARTUP = 0,
	DB_SHUTDOWNED,
115 116 117 118 119
	DB_SHUTDOWNING,
	DB_IN_RECOVERY,
	DB_IN_PRODUCTION
} DBState;

120 121
#define LOCALE_NAME_BUFLEN  128

122 123
typedef struct ControlFileData
{
124 125 126
	/*
	 * XLOG state
	 */
127 128 129 130
	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 */
131
	DBState		state;			/* see enum above */
132 133

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

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

150
static ControlFileData *ControlFile = NULL;
151

152

153 154
typedef struct CheckPoint
{
V
WAL  
Vadim B. Mikheev 已提交
155 156 157 158 159 160 161 162 163 164
	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;
165 166
} CheckPoint;

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

170 171
/*
 * We break each log file in 16Mb segments
172
 */
173
#define XLogSegSize		(16*1024*1024)
174 175
#define XLogLastSeg		(0xffffffff / XLogSegSize)
#define XLogFileSize	(XLogLastSeg * XLogSegSize)
176

177
#define XLogFileName(path, log, seg)	\
178 179
			snprintf(path, MAXPGPATH, "%s%c%08X%08X",	\
					 XLogDir, SEP_CHAR, log, seg)
180

V
Vadim B. Mikheev 已提交
181 182 183 184
#define XLogTempFileName(path, log, seg)	\
			snprintf(path, MAXPGPATH, "%s%cT%08X%08X",	\
					 XLogDir, SEP_CHAR, log, seg)

185
#define PrevBufIdx(curridx)		\
186 187
		((curridx == 0) ? XLogCtl->XLogCacheBlck : (curridx - 1))

188
#define NextBufIdx(curridx)		\
189 190
		((curridx == XLogCtl->XLogCacheBlck) ? 0 : (curridx + 1))

191
#define InitXLBuffer(curridx)	(\
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
				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 \
				)

207
#define XRecOffIsValid(xrecoff) \
208 209 210
		(xrecoff % BLCKSZ >= SizeOfXLogPHD && \
		(BLCKSZ - xrecoff % BLCKSZ) >= SizeOfXLogRecord)

211 212
static void GetFreeXLBuffer(void);
static void XLogWrite(char *buffer);
V
Vadim B. Mikheev 已提交
213
static int	XLogFileInit(uint32 log, uint32 seg, bool *usexistent);
214 215
static int	XLogFileOpen(uint32 log, uint32 seg, bool econt);
static XLogRecord *ReadRecord(XLogRecPtr *RecPtr, char *buffer);
216 217
static void WriteControlFile(void);
static void ReadControlFile(void);
218
static char *str_time(time_t tnow);
V
WAL  
Vadim B. Mikheev 已提交
219
static void xlog_outrec(char *buf, XLogRecord *record);
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236

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;
237

V
WAL  
Vadim B. Mikheev 已提交
238 239
static bool InRedo = false;

240
XLogRecPtr
V
Vadim B. Mikheev 已提交
241
XLogInsert(RmgrId rmid, uint8 info, char *hdr, uint32 hdrlen, char *buf, uint32 buflen)
242
{
V
Vadim B. Mikheev 已提交
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
	XLogCtlInsert  *Insert = &XLogCtl->Insert;
	XLogRecord	   *record;
	XLogSubRecord  *subrecord;
	XLogRecPtr		RecPtr;
	uint32			len = hdrlen + buflen,
					freespace,
					wlen;
	uint16			curridx;
	bool			updrqst = false;
	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;
	}

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

V
Vadim B. Mikheev 已提交
266
	if (IsBootstrapProcessingMode() && rmid != RM_XLOG_ID)
V
WAL  
Vadim B. Mikheev 已提交
267 268 269 270 271 272
	{
		RecPtr.xlogid = 0;
		RecPtr.xrecoff = SizeOfXLogPHD;	/* start of 1st checkpoint record */
		return (RecPtr);
	}

273 274
	START_CRIT_CODE;

275 276 277 278 279 280
	/* obtain xlog insert lock */
	if (TAS(&(XLogCtl->insert_lck)))	/* busy */
	{
		bool		do_lgwr = true;
		unsigned	i = 0;

281
		for (;;)
282 283 284 285 286 287 288
		{
			/* 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));
289

290 291 292 293
				/*
				 * If cache is half filled then try to acquire lgwr lock
				 * and do LGWR work, but only once.
				 */
294 295 296 297
				if (do_lgwr &&
					(LgwrRqst.Write.xlogid != LgwrResult.Write.xlogid ||
					 (LgwrRqst.Write.xrecoff - LgwrResult.Write.xrecoff >=
					  XLogCtl->XLogCacheByte / 2)))
298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
				{
					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));
					}
				}
			}
			s_lock_sleep(i++);
			if (!TAS(&(XLogCtl->insert_lck)))
				break;
		}
	}

322
	freespace = ((char *) Insert->currpage) + BLCKSZ - Insert->currpos;
323 324 325 326 327
	if (freespace < SizeOfXLogRecord)
	{
		curridx = NextBufIdx(Insert->curridx);
		if (XLByteLE(XLogCtl->xlblocks[curridx], LgwrResult.Write))
			InitXLBuffer(curridx);
328
		else
329 330 331 332 333 334 335
			GetFreeXLBuffer();
		freespace = BLCKSZ - SizeOfXLogPHD;
	}
	else
		curridx = Insert->curridx;

	freespace -= SizeOfXLogRecord;
336
	record = (XLogRecord *) Insert->currpos;
337
	record->xl_prev = Insert->PrevRecord;
V
Vadim B. Mikheev 已提交
338
	if (no_tran)
339 340 341 342
	{
		record->xl_xact_prev.xlogid = 0;
		record->xl_xact_prev.xrecoff = 0;
	}
V
Vadim B. Mikheev 已提交
343 344 345
	else
		record->xl_xact_prev = MyLastRecPtr;

346 347
	record->xl_xid = GetCurrentTransactionId();
	record->xl_len = (len > freespace) ? freespace : len;
V
Vadim B. Mikheev 已提交
348 349
	record->xl_info = (len > freespace) ? 
		(info | XLR_TO_BE_CONTINUED) : info;
350 351
	record->xl_rmid = rmid;
	RecPtr.xlogid = XLogCtl->xlblocks[curridx].xlogid;
352 353 354
	RecPtr.xrecoff =
		XLogCtl->xlblocks[curridx].xrecoff - BLCKSZ +
		Insert->currpos - ((char *) Insert->currpage);
V
Vadim B. Mikheev 已提交
355
	if (MyLastRecPtr.xrecoff == 0 && !no_tran)
356 357 358 359 360
	{
		SpinAcquire(SInvalLock);
		MyProc->logRec = RecPtr;
		SpinRelease(SInvalLock);
	}
V
WAL  
Vadim B. Mikheev 已提交
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377
	Insert->PrevRecord = RecPtr;

	if (XLOG_DEBUG)
	{
		char	buf[8192];

		sprintf(buf, "INSERT @ %u/%u: ", RecPtr.xlogid, RecPtr.xrecoff);
		xlog_outrec(buf, record);
		if (hdr != NULL)
		{
			strcat(buf, " - ");
			RmgrTable[record->xl_rmid].rm_desc(buf, record->xl_info, hdr);
		}
		strcat(buf, "\n");
		write(2, buf, strlen(buf));
	}

V
Vadim B. Mikheev 已提交
378
	MyLastRecPtr = RecPtr;	/* begin of record */
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
	Insert->currpos += SizeOfXLogRecord;
	if (freespace > 0)
	{
		wlen = (hdrlen > freespace) ? freespace : hdrlen;
		memcpy(Insert->currpos, hdr, wlen);
		freespace -= wlen;
		hdrlen -= wlen;
		hdr += wlen;
		Insert->currpos += wlen;
		if (buflen > 0 && freespace > 0)
		{
			wlen = (buflen > freespace) ? freespace : buflen;
			memcpy(Insert->currpos, buf, wlen);
			freespace -= wlen;
			buflen -= wlen;
			buf += wlen;
			Insert->currpos += wlen;
		}
397
		Insert->currpos = ((char *) Insert->currpage) +
V
WAL  
Vadim B. Mikheev 已提交
398
			MAXALIGN(Insert->currpos - ((char *) Insert->currpage));
399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417
		len = hdrlen + buflen;
	}

	if (len != 0)
	{
nbuf:
		curridx = NextBufIdx(curridx);
		if (XLByteLE(XLogCtl->xlblocks[curridx], LgwrResult.Write))
		{
			InitXLBuffer(curridx);
			updrqst = true;
		}
		else
		{
			GetFreeXLBuffer();
			updrqst = false;
		}
		freespace = BLCKSZ - SizeOfXLogPHD - SizeOfXLogSubRecord;
		Insert->currpage->xlp_info |= XLP_FIRST_IS_SUBRECORD;
418
		subrecord = (XLogSubRecord *) Insert->currpos;
419 420 421 422
		Insert->currpos += SizeOfXLogSubRecord;
		if (hdrlen > freespace)
		{
			subrecord->xl_len = freespace;
V
Vadim B. Mikheev 已提交
423
			/* we don't store info in subrecord' xl_info */
424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
			subrecord->xl_info = XLR_TO_BE_CONTINUED;
			memcpy(Insert->currpos, hdr, freespace);
			hdrlen -= freespace;
			hdr += freespace;
			goto nbuf;
		}
		else if (hdrlen > 0)
		{
			subrecord->xl_len = hdrlen;
			memcpy(Insert->currpos, hdr, hdrlen);
			Insert->currpos += hdrlen;
			freespace -= hdrlen;
			hdrlen = 0;
		}
		else
			subrecord->xl_len = 0;
		if (buflen > freespace)
		{
			subrecord->xl_len += freespace;
V
Vadim B. Mikheev 已提交
443
			/* we don't store info in subrecord' xl_info */
444 445 446 447 448 449 450 451 452 453 454 455
			subrecord->xl_info = XLR_TO_BE_CONTINUED;
			memcpy(Insert->currpos, buf, freespace);
			buflen -= freespace;
			buf += freespace;
			goto nbuf;
		}
		else if (buflen > 0)
		{
			subrecord->xl_len += buflen;
			memcpy(Insert->currpos, buf, buflen);
			Insert->currpos += buflen;
		}
V
Vadim B. Mikheev 已提交
456
		/* we don't store info in subrecord' xl_info */
457
		subrecord->xl_info = 0;
458
		Insert->currpos = ((char *) Insert->currpage) +
V
WAL  
Vadim B. Mikheev 已提交
459
			MAXALIGN(Insert->currpos - ((char *) Insert->currpage));
460
	}
461 462
	freespace = ((char *) Insert->currpage) + BLCKSZ - Insert->currpos;

V
Vadim B. Mikheev 已提交
463 464 465 466 467 468 469 470 471
	/*
	 * 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);

472 473 474 475
	/*
	 * All done! Update global LgwrRqst if some block was filled up.
	 */
	if (freespace < SizeOfXLogRecord)
476 477
		updrqst = true;			/* curridx is filled and available for
								 * writing out */
478 479 480 481 482 483 484 485 486 487
	else
		curridx = PrevBufIdx(curridx);
	LgwrRqst.Write = XLogCtl->xlblocks[curridx];

	S_UNLOCK(&(XLogCtl->insert_lck));

	if (updrqst)
	{
		unsigned	i = 0;

488
		for (;;)
489 490 491 492 493 494 495 496 497 498 499 500
		{
			if (!TAS(&(XLogCtl->info_lck)))
			{
				if (XLByteLT(XLogCtl->LgwrRqst.Write, LgwrRqst.Write))
					XLogCtl->LgwrRqst.Write = LgwrRqst.Write;
				S_UNLOCK(&(XLogCtl->info_lck));
				break;
			}
			s_lock_sleep(i++);
		}
	}

501
	END_CRIT_CODE;
502
	return (RecPtr);
503
}
504 505 506 507

void
XLogFlush(XLogRecPtr record)
{
508 509 510 511 512
	XLogRecPtr	WriteRqst;
	char		buffer[BLCKSZ];
	char	   *usebuf = NULL;
	unsigned	i = 0;
	bool		force_lgwr = false;
513

V
WAL  
Vadim B. Mikheev 已提交
514 515 516 517 518 519 520 521 522 523 524
	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 已提交
525
	if (InRedo)
V
WAL  
Vadim B. Mikheev 已提交
526
		return;
527 528
	if (XLByteLE(record, LgwrResult.Flush))
		return;
529 530 531

	START_CRIT_CODE;

532
	WriteRqst = LgwrRqst.Write;
533
	for (;;)
534 535 536 537 538 539 540 541
	{
		/* try to read LgwrResult */
		if (!TAS(&(XLogCtl->info_lck)))
		{
			LgwrResult = XLogCtl->LgwrResult;
			if (XLByteLE(record, LgwrResult.Flush))
			{
				S_UNLOCK(&(XLogCtl->info_lck));
542
				END_CRIT_CODE;
543 544 545 546 547 548 549 550 551 552 553 554 555 556
				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)))
		{
557 558 559
			XLogCtlInsert *Insert = &XLogCtl->Insert;
			uint32		freespace =
			((char *) Insert->currpage) + BLCKSZ - Insert->currpos;
560 561 562 563 564 565 566 567 568 569 570 571

			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];
572 573
				WriteRqst.xrecoff = WriteRqst.xrecoff - BLCKSZ +
					Insert->currpos - ((char *) Insert->currpage);
574 575 576 577
			}
			S_UNLOCK(&(XLogCtl->insert_lck));
			force_lgwr = true;
		}
578 579
		if (force_lgwr || WriteRqst.xlogid > record.xlogid ||
			(WriteRqst.xlogid == record.xlogid &&
580 581 582 583 584 585 586 587
			 WriteRqst.xrecoff >= record.xrecoff + BLCKSZ))
		{
			if (!TAS(&(XLogCtl->lgwr_lck)))
			{
				LgwrResult = XLogCtl->Write.LgwrResult;
				if (XLByteLE(record, LgwrResult.Flush))
				{
					S_UNLOCK(&(XLogCtl->lgwr_lck));
588
					END_CRIT_CODE;
589 590 591 592 593 594 595 596
					return;
				}
				if (XLByteLT(LgwrResult.Write, WriteRqst))
				{
					LgwrRqst.Flush = LgwrRqst.Write = WriteRqst;
					XLogWrite(usebuf);
					S_UNLOCK(&(XLogCtl->lgwr_lck));
					if (XLByteLT(LgwrResult.Flush, record))
597
						elog(STOP, "XLogFlush: request is not satisfied");
598
					END_CRIT_CODE;
599 600 601 602 603 604 605 606
					return;
				}
				break;
			}
		}
		s_lock_sleep(i++);
	}

607 608
	if (logFile >= 0 && (LgwrResult.Write.xlogid != logId ||
				 (LgwrResult.Write.xrecoff - 1) / XLogSegSize != logSeg))
609 610
	{
		if (close(logFile) != 0)
611 612
			elog(STOP, "close(logfile %u seg %u) failed: %m",
				 logId, logSeg);
613 614 615 616 617 618 619
		logFile = -1;
	}

	if (logFile < 0)
	{
		logId = LgwrResult.Write.xlogid;
		logSeg = (LgwrResult.Write.xrecoff - 1) / XLogSegSize;
620
		logOff = 0;
621 622 623
		logFile = XLogFileOpen(logId, logSeg, false);
	}

624
	if (pg_fsync(logFile) != 0)
625 626
		elog(STOP, "fsync(logfile %u seg %u) failed: %m",
			 logId, logSeg);
627 628
	LgwrResult.Flush = LgwrResult.Write;

629
	for (i = 0;;)
630 631 632 633 634 635 636 637 638 639 640 641 642 643
	{
		if (!TAS(&(XLogCtl->info_lck)))
		{
			XLogCtl->LgwrResult = LgwrResult;
			if (XLByteLT(XLogCtl->LgwrRqst.Write, LgwrResult.Write))
				XLogCtl->LgwrRqst.Write = LgwrResult.Write;
			S_UNLOCK(&(XLogCtl->info_lck));
			break;
		}
		s_lock_sleep(i++);
	}
	XLogCtl->Write.LgwrResult = LgwrResult;

	S_UNLOCK(&(XLogCtl->lgwr_lck));
644 645

	END_CRIT_CODE;
646 647 648 649 650 651 652
	return;

}

static void
GetFreeXLBuffer()
{
653 654 655
	XLogCtlInsert *Insert = &XLogCtl->Insert;
	XLogCtlWrite *Write = &XLogCtl->Write;
	uint16		curridx = NextBufIdx(Insert->curridx);
656 657

	LgwrRqst.Write = XLogCtl->xlblocks[Insert->curridx];
658
	for (;;)
659 660 661 662 663 664 665 666 667 668 669 670 671
	{
		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;
			}
		}
672

673 674 675 676 677 678 679 680 681 682 683 684 685 686
		/*
		 * 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;
			}
687 688 689 690

			/*
			 * Have to write buffers while holding insert lock - not
			 * good...
691 692 693 694 695 696 697 698 699 700 701 702 703 704 705
			 */
			XLogWrite(NULL);
			S_UNLOCK(&(XLogCtl->lgwr_lck));
			Insert->LgwrResult = LgwrResult;
			InitXLBuffer(curridx);
			return;
		}
	}

	return;
}

static void
XLogWrite(char *buffer)
{
706 707 708 709
	XLogCtlWrite *Write = &XLogCtl->Write;
	char	   *from;
	uint32		wcnt = 0;
	int			i = 0;
V
Vadim B. Mikheev 已提交
710
	bool		usexistent;
711

712
	for (; XLByteLT(LgwrResult.Write, LgwrRqst.Write);)
713 714
	{
		LgwrResult.Write = XLogCtl->xlblocks[Write->curridx];
715
		if (LgwrResult.Write.xlogid != logId ||
716 717 718 719
			(LgwrResult.Write.xrecoff - 1) / XLogSegSize != logSeg)
		{
			if (wcnt > 0)
			{
720
				if (pg_fsync(logFile) != 0)
721 722
					elog(STOP, "fsync(logfile %u seg %u) failed: %m",
						 logId, logSeg);
723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741
				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)
742 743
					elog(STOP, "close(logfile %u seg %u) failed: %m",
						 logId, logSeg);
744 745 746 747
				logFile = -1;
			}
			logId = LgwrResult.Write.xlogid;
			logSeg = (LgwrResult.Write.xrecoff - 1) / XLogSegSize;
748
			logOff = 0;
749
			SpinAcquire(ControlFileLockId);
V
Vadim B. Mikheev 已提交
750 751 752
			/* create/use new log file */
			usexistent = true;
			logFile = XLogFileInit(logId, logSeg, &usexistent);
753 754 755 756 757
			ControlFile->logId = logId;
			ControlFile->logSeg = logSeg + 1;
			ControlFile->time = time(NULL);
			UpdateControlFile();
			SpinRelease(ControlFileLockId);
V
Vadim B. Mikheev 已提交
758 759 760
			if (!usexistent)	/* there was no file */
				elog(LOG, "XLogWrite: had to create new log file - "
					"you probably should do checkpoints more often");
761 762 763 764 765 766
		}

		if (logFile < 0)
		{
			logId = LgwrResult.Write.xlogid;
			logSeg = (LgwrResult.Write.xrecoff - 1) / XLogSegSize;
767
			logOff = 0;
768 769 770 771 772 773
			logFile = XLogFileOpen(logId, logSeg, false);
		}

		if (logOff != (LgwrResult.Write.xrecoff - BLCKSZ) % XLogSegSize)
		{
			logOff = (LgwrResult.Write.xrecoff - BLCKSZ) % XLogSegSize;
774
			if (lseek(logFile, (off_t) logOff, SEEK_SET) < 0)
775 776
				elog(STOP, "lseek(logfile %u seg %u off %u) failed: %m",
					 logId, logSeg, logOff);
777 778 779 780 781 782 783 784
		}

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

		if (write(logFile, from, BLCKSZ) != BLCKSZ)
785 786
			elog(STOP, "write(logfile %u seg %u off %u) failed: %m",
				 logId, logSeg, logOff);
787 788 789 790 791 792 793 794 795 796 797 798

		wcnt++;
		logOff += BLCKSZ;

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

799
	if (XLByteLT(LgwrResult.Flush, LgwrRqst.Flush) &&
800 801
		XLByteLE(LgwrRqst.Flush, LgwrResult.Write))
	{
802
		if (pg_fsync(logFile) != 0)
803 804
			elog(STOP, "fsync(logfile %u seg %u) failed: %m",
				 logId, logSeg);
805 806 807
		LgwrResult.Flush = LgwrResult.Write;
	}

808
	for (;;)
809 810 811 812 813 814 815 816 817 818 819 820 821 822 823
	{
		if (!TAS(&(XLogCtl->info_lck)))
		{
			XLogCtl->LgwrResult = LgwrResult;
			if (XLByteLT(XLogCtl->LgwrRqst.Write, LgwrResult.Write))
				XLogCtl->LgwrRqst.Write = LgwrResult.Write;
			S_UNLOCK(&(XLogCtl->info_lck));
			break;
		}
		s_lock_sleep(i++);
	}
	Write->LgwrResult = LgwrResult;
}

static int
V
Vadim B. Mikheev 已提交
824
XLogFileInit(uint32 log, uint32 seg, bool *usexistent)
825
{
826
	char		path[MAXPGPATH];
V
Vadim B. Mikheev 已提交
827
	char		tpath[MAXPGPATH];
828
	int			fd;
829 830

	XLogFileName(path, log, seg);
V
Vadim B. Mikheev 已提交
831 832 833 834 835 836 837 838 839 840 841

	/*
	 * 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)
842 843
				elog(STOP, "InitOpen(logfile %u seg %u) failed: %m",
					logId, logSeg);
V
Vadim B. Mikheev 已提交
844 845 846 847 848 849 850 851
		}
		else
			return(fd);
		*usexistent = false;
	}

	XLogTempFileName(tpath, log, seg);
	unlink(tpath);
852 853
	unlink(path);

V
Vadim B. Mikheev 已提交
854
	fd = BasicOpenFile(tpath, O_RDWR | O_CREAT | O_EXCL | PG_BINARY, S_IRUSR | S_IWUSR);
855
	if (fd < 0)
856 857
		elog(STOP, "InitCreate(logfile %u seg %u) failed: %m",
			 logId, logSeg);
858 859

	if (lseek(fd, XLogSegSize - 1, SEEK_SET) != (off_t) (XLogSegSize - 1))
860 861
		elog(STOP, "lseek(logfile %u seg %u) failed: %m",
			 logId, logSeg);
862 863

	if (write(fd, "", 1) != 1)
864 865
		elog(STOP, "write(logfile %u seg %u) failed: %m",
			 logId, logSeg);
866

867
	if (pg_fsync(fd) != 0)
868 869
		elog(STOP, "fsync(logfile %u seg %u) failed: %m",
			 logId, logSeg);
870

871
	if (lseek(fd, 0, SEEK_SET) < 0)
872 873
		elog(STOP, "lseek(logfile %u seg %u off %u) failed: %m",
			 log, seg, 0);
874

V
Vadim B. Mikheev 已提交
875
	close(fd);
T
Tom Lane 已提交
876 877 878 879 880

	if (link(tpath, path) < 0)
		elog(STOP, "InitRelink(logfile %u seg %u) failed: %m",
			 logId, logSeg);

V
Vadim B. Mikheev 已提交
881 882 883 884
	unlink(tpath);

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

888
	return (fd);
889 890 891 892 893
}

static int
XLogFileOpen(uint32 log, uint32 seg, bool econt)
{
894 895
	char		path[MAXPGPATH];
	int			fd;
896 897 898

	XLogFileName(path, log, seg);

899
	fd = BasicOpenFile(path, O_RDWR | PG_BINARY, S_IRUSR | S_IWUSR);
900 901 902 903
	if (fd < 0)
	{
		if (econt && errno == ENOENT)
		{
904
			elog(LOG, "open(logfile %u seg %u) failed: %m",
905
				 logId, logSeg);
906 907
			return (fd);
		}
V
WAL  
Vadim B. Mikheev 已提交
908
		abort();
909 910
		elog(STOP, "open(logfile %u seg %u) failed: %m",
			 logId, logSeg);
911 912
	}

913
	return (fd);
914 915
}

V
Vadim B. Mikheev 已提交
916 917 918 919 920 921 922 923 924 925 926 927 928 929 930
/*
 * (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)
931
		elog(STOP, "MoveOfflineLogs: cannot open xlog dir: %m");
V
Vadim B. Mikheev 已提交
932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948

	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 已提交
949
		if (archdir[0] == 0)
V
Vadim B. Mikheev 已提交
950 951 952 953
			unlink(path);
		errno = 0;
	}
	if (errno)
954
		elog(STOP, "MoveOfflineLogs: cannot read xlog dir: %m");
V
Vadim B. Mikheev 已提交
955 956 957
	closedir(xldir);
}

958
static XLogRecord *
959
ReadRecord(XLogRecPtr *RecPtr, char *buffer)
960
{
961 962 963 964 965
	XLogRecord *record;
	XLogRecPtr	tmpRecPtr = EndRecPtr;
	bool		nextmode = (RecPtr == NULL);
	int			emode = (nextmode) ? LOG : STOP;
	bool		noBlck = false;
966

967
	if (nextmode)
968
	{
969 970 971 972 973 974 975 976 977 978 979 980 981 982
		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;
983
	}
984 985
	else if (!XRecOffIsValid(RecPtr->xrecoff))
		elog(STOP, "ReadRecord: invalid record offset in (%u, %u)",
986
			 RecPtr->xlogid, RecPtr->xrecoff);
987

988 989
	if (readFile >= 0 && (RecPtr->xlogid != readId ||
						  RecPtr->xrecoff / XLogSegSize != readSeg))
990
	{
991 992
		close(readFile);
		readFile = -1;
993
	}
994 995 996
	readId = RecPtr->xlogid;
	readSeg = RecPtr->xrecoff / XLogSegSize;
	if (readFile < 0)
997
	{
998 999 1000 1001
		noBlck = true;
		readFile = XLogFileOpen(readId, readSeg, nextmode);
		if (readFile < 0)
			goto next_record_is_invalid;
1002 1003
	}

1004
	if (noBlck || readOff != (RecPtr->xrecoff % XLogSegSize) / BLCKSZ)
1005 1006
	{
		readOff = (RecPtr->xrecoff % XLogSegSize) / BLCKSZ;
1007
		if (lseek(readFile, (off_t) (readOff * BLCKSZ), SEEK_SET) < 0)
1008 1009
			elog(STOP, "ReadRecord: lseek(logfile %u seg %u off %u) failed: %m",
				 readId, readSeg, readOff);
1010
		if (read(readFile, readBuf, BLCKSZ) != BLCKSZ)
1011 1012
			elog(STOP, "ReadRecord: read(logfile %u seg %u off %u) failed: %m",
				 readId, readSeg, readOff);
1013
		if (((XLogPageHeader) readBuf)->xlp_magic != XLOG_PAGE_MAGIC)
1014 1015
		{
			elog(emode, "ReadRecord: invalid magic number %u in logfile %u seg %u off %u",
1016 1017
				 ((XLogPageHeader) readBuf)->xlp_magic,
				 readId, readSeg, readOff);
1018 1019 1020
			goto next_record_is_invalid;
		}
	}
1021
	if ((((XLogPageHeader) readBuf)->xlp_info & XLP_FIRST_IS_SUBRECORD) &&
1022 1023 1024
		RecPtr->xrecoff % BLCKSZ == SizeOfXLogPHD)
	{
		elog(emode, "ReadRecord: subrecord is requested by (%u, %u)",
1025
			 RecPtr->xlogid, RecPtr->xrecoff);
1026 1027
		goto next_record_is_invalid;
	}
1028
	record = (XLogRecord *) ((char *) readBuf + RecPtr->xrecoff % BLCKSZ);
1029 1030

got_record:;
V
WAL  
Vadim B. Mikheev 已提交
1031
	if (record->xl_len >
1032 1033 1034
		(BLCKSZ - RecPtr->xrecoff % BLCKSZ - SizeOfXLogRecord))
	{
		elog(emode, "ReadRecord: invalid record len %u in (%u, %u)",
1035
			 record->xl_len, RecPtr->xlogid, RecPtr->xrecoff);
1036 1037 1038 1039 1040
		goto next_record_is_invalid;
	}
	if (record->xl_rmid > RM_MAX_ID)
	{
		elog(emode, "ReadRecord: invalid resource managed id %u in (%u, %u)",
1041
			 record->xl_rmid, RecPtr->xlogid, RecPtr->xrecoff);
1042 1043 1044 1045 1046
		goto next_record_is_invalid;
	}
	nextRecord = NULL;
	if (record->xl_info & XLR_TO_BE_CONTINUED)
	{
1047 1048
		XLogSubRecord *subrecord;
		uint32		len = record->xl_len;
1049

V
WAL  
Vadim B. Mikheev 已提交
1050
		if (MAXALIGN(record->xl_len) + RecPtr->xrecoff % BLCKSZ + 
V
Vadim B. Mikheev 已提交
1051
			SizeOfXLogRecord != BLCKSZ)
1052 1053
		{
			elog(emode, "ReadRecord: invalid fragmented record len %u in (%u, %u)",
1054
				 record->xl_len, RecPtr->xlogid, RecPtr->xrecoff);
1055 1056 1057
			goto next_record_is_invalid;
		}
		memcpy(buffer, record, record->xl_len + SizeOfXLogRecord);
1058
		record = (XLogRecord *) buffer;
1059
		buffer += record->xl_len + SizeOfXLogRecord;
1060
		for (;;)
1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
		{
			readOff++;
			if (readOff == XLogSegSize / BLCKSZ)
			{
				readSeg++;
				if (readSeg == XLogLastSeg)
				{
					readSeg = 0;
					readId++;
				}
				close(readFile);
1072
				readOff = 0;
1073 1074 1075 1076 1077
				readFile = XLogFileOpen(readId, readSeg, nextmode);
				if (readFile < 0)
					goto next_record_is_invalid;
			}
			if (read(readFile, readBuf, BLCKSZ) != BLCKSZ)
1078 1079
				elog(STOP, "ReadRecord: read(logfile %u seg %u off %u) failed: %m",
					 readId, readSeg, readOff);
1080
			if (((XLogPageHeader) readBuf)->xlp_magic != XLOG_PAGE_MAGIC)
1081 1082
			{
				elog(emode, "ReadRecord: invalid magic number %u in logfile %u seg %u off %u",
1083 1084
					 ((XLogPageHeader) readBuf)->xlp_magic,
					 readId, readSeg, readOff);
1085 1086
				goto next_record_is_invalid;
			}
1087
			if (!(((XLogPageHeader) readBuf)->xlp_info & XLP_FIRST_IS_SUBRECORD))
1088 1089
			{
				elog(emode, "ReadRecord: there is no subrecord flag in logfile %u seg %u off %u",
1090
					 readId, readSeg, readOff);
1091 1092
				goto next_record_is_invalid;
			}
1093 1094
			subrecord = (XLogSubRecord *) ((char *) readBuf + SizeOfXLogPHD);
			if (subrecord->xl_len == 0 || subrecord->xl_len >
1095 1096 1097
				(BLCKSZ - SizeOfXLogPHD - SizeOfXLogSubRecord))
			{
				elog(emode, "ReadRecord: invalid subrecord len %u in logfile %u seg %u off %u",
1098
					 subrecord->xl_len, readId, readSeg, readOff);
1099 1100 1101 1102 1103 1104
				goto next_record_is_invalid;
			}
			len += subrecord->xl_len;
			if (len > MAXLOGRECSZ)
			{
				elog(emode, "ReadRecord: too long record len %u in (%u, %u)",
1105
					 len, RecPtr->xlogid, RecPtr->xrecoff);
1106 1107
				goto next_record_is_invalid;
			}
1108
			memcpy(buffer, (char *) subrecord + SizeOfXLogSubRecord, subrecord->xl_len);
1109 1110 1111
			buffer += subrecord->xl_len;
			if (subrecord->xl_info & XLR_TO_BE_CONTINUED)
			{
V
WAL  
Vadim B. Mikheev 已提交
1112
				if (MAXALIGN(subrecord->xl_len) +
1113 1114 1115
					SizeOfXLogPHD + SizeOfXLogSubRecord != BLCKSZ)
				{
					elog(emode, "ReadRecord: invalid fragmented subrecord len %u in logfile %u seg %u off %u",
1116
						 subrecord->xl_len, readId, readSeg, readOff);
1117 1118 1119 1120 1121 1122
					goto next_record_is_invalid;
				}
				continue;
			}
			break;
		}
V
WAL  
Vadim B. Mikheev 已提交
1123
		if (BLCKSZ - SizeOfXLogRecord >= MAXALIGN(subrecord->xl_len) + 
V
Vadim B. Mikheev 已提交
1124
			SizeOfXLogPHD + SizeOfXLogSubRecord)
1125
		{
V
Vadim B. Mikheev 已提交
1126
			nextRecord = (XLogRecord *) ((char *) subrecord + 
V
WAL  
Vadim B. Mikheev 已提交
1127
				MAXALIGN(subrecord->xl_len) + SizeOfXLogSubRecord);
1128
		}
1129
		record->xl_len = len;
1130
		EndRecPtr.xlogid = readId;
1131
		EndRecPtr.xrecoff = readSeg * XLogSegSize + readOff * BLCKSZ +
V
Vadim B. Mikheev 已提交
1132
			SizeOfXLogPHD + SizeOfXLogSubRecord + 
V
WAL  
Vadim B. Mikheev 已提交
1133
			MAXALIGN(subrecord->xl_len);
1134
		ReadRecPtr = *RecPtr;
1135
		return (record);
1136
	}
V
WAL  
Vadim B. Mikheev 已提交
1137
	if (BLCKSZ - SizeOfXLogRecord >= MAXALIGN(record->xl_len) + 
V
Vadim B. Mikheev 已提交
1138 1139
		RecPtr->xrecoff % BLCKSZ + SizeOfXLogRecord)
		nextRecord = (XLogRecord *) ((char *) record + 
V
WAL  
Vadim B. Mikheev 已提交
1140
			MAXALIGN(record->xl_len) + SizeOfXLogRecord);
1141
	EndRecPtr.xlogid = RecPtr->xlogid;
V
Vadim B. Mikheev 已提交
1142
	EndRecPtr.xrecoff = RecPtr->xrecoff + 
V
WAL  
Vadim B. Mikheev 已提交
1143
		MAXALIGN(record->xl_len) + SizeOfXLogRecord;
1144 1145
	ReadRecPtr = *RecPtr;

1146
	return (record);
1147 1148 1149 1150 1151 1152

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

1155 1156 1157 1158 1159 1160
	/*
	 * If we assumed that next record began on the same page where
	 * previous one ended - zero end of page.
	 */
	if (XLByteEQ(tmpRecPtr, EndRecPtr))
	{
1161 1162
		Assert(EndRecPtr.xrecoff % BLCKSZ > (SizeOfXLogPHD + SizeOfXLogSubRecord) &&
			   BLCKSZ - EndRecPtr.xrecoff % BLCKSZ >= SizeOfXLogRecord);
1163 1164 1165
		readId = EndRecPtr.xlogid;
		readSeg = EndRecPtr.xrecoff / XLogSegSize;
		readOff = (EndRecPtr.xrecoff % XLogSegSize) / BLCKSZ;
1166
		elog(LOG, "Formatting logfile %u seg %u block %u at offset %u",
1167
			 readId, readSeg, readOff, EndRecPtr.xrecoff % BLCKSZ);
1168
		readFile = XLogFileOpen(readId, readSeg, false);
1169
		if (lseek(readFile, (off_t) (readOff * BLCKSZ), SEEK_SET) < 0)
1170 1171
			elog(STOP, "ReadRecord: lseek(logfile %u seg %u off %u) failed: %m",
				 readId, readSeg, readOff);
1172
		if (read(readFile, readBuf, BLCKSZ) != BLCKSZ)
1173 1174
			elog(STOP, "ReadRecord: read(logfile %u seg %u off %u) failed: %m",
				 readId, readSeg, readOff);
1175 1176 1177
		memset(readBuf + EndRecPtr.xrecoff % BLCKSZ, 0,
			   BLCKSZ - EndRecPtr.xrecoff % BLCKSZ);
		if (lseek(readFile, (off_t) (readOff * BLCKSZ), SEEK_SET) < 0)
1178 1179
			elog(STOP, "ReadRecord: lseek(logfile %u seg %u off %u) failed: %m",
				 readId, readSeg, readOff);
1180
		if (write(readFile, readBuf, BLCKSZ) != BLCKSZ)
1181 1182
			elog(STOP, "ReadRecord: write(logfile %u seg %u off %u) failed: %m",
				 readId, readSeg, readOff);
1183 1184 1185 1186
		readOff++;
	}
	else
	{
1187 1188
		Assert(EndRecPtr.xrecoff % BLCKSZ == 0 ||
			   BLCKSZ - EndRecPtr.xrecoff % BLCKSZ < SizeOfXLogRecord);
1189 1190 1191
		readId = tmpRecPtr.xlogid;
		readSeg = tmpRecPtr.xrecoff / XLogSegSize;
		readOff = (tmpRecPtr.xrecoff % XLogSegSize) / BLCKSZ;
1192
		Assert(readOff > 0);
1193 1194 1195
	}
	if (readOff > 0)
	{
1196
		if (!XLByteEQ(tmpRecPtr, EndRecPtr))
1197
			elog(LOG, "Formatting logfile %u seg %u block %u at offset 0",
1198
				 readId, readSeg, readOff);
1199 1200 1201
		readOff *= BLCKSZ;
		memset(readBuf, 0, BLCKSZ);
		readFile = XLogFileOpen(readId, readSeg, false);
1202
		if (lseek(readFile, (off_t) readOff, SEEK_SET) < 0)
1203 1204
			elog(STOP, "ReadRecord: lseek(logfile %u seg %u off %u) failed: %m",
				 readId, readSeg, readOff);
1205 1206 1207
		while (readOff < XLogSegSize)
		{
			if (write(readFile, readBuf, BLCKSZ) != BLCKSZ)
1208 1209
				elog(STOP, "ReadRecord: write(logfile %u seg %u off %u) failed: %m",
					 readId, readSeg, readOff);
1210 1211 1212 1213 1214
			readOff += BLCKSZ;
		}
	}
	if (readFile >= 0)
	{
1215
		if (pg_fsync(readFile) < 0)
1216 1217
			elog(STOP, "ReadRecord: fsync(logfile %u seg %u) failed: %m",
				 readId, readSeg);
1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238
		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++;
	}
	{
1239
		char		path[MAXPGPATH];
1240 1241 1242 1243 1244

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

1245
	return (record);
1246 1247
}

1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331
/*
 * 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");
	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");

1332
	if (pg_fsync(fd) != 0)
1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389
		elog(STOP, "WriteControlFile failed to fsync control file: %m");

	close(fd);
}

static void
ReadControlFile(void)
{
	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);

	/*
	 * 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
}

1390
void
1391
UpdateControlFile(void)
1392
{
1393
	int			fd;
1394

1395
	fd = BasicOpenFile(ControlFilePath, O_RDWR | PG_BINARY, S_IRUSR | S_IWUSR);
1396
	if (fd < 0)
1397
		elog(STOP, "open(\"%s\") failed: %m", ControlFilePath);
1398

1399
	if (write(fd, ControlFile, sizeof(ControlFileData)) != sizeof(ControlFileData))
1400
		elog(STOP, "write(cntlfile) failed: %m");
1401

1402
	if (pg_fsync(fd) != 0)
1403
		elog(STOP, "fsync(cntlfile) failed: %m");
1404 1405 1406 1407

	close(fd);
}

1408 1409 1410 1411
/*
 * Management of shared memory for XLOG
 */

1412
int
1413
XLOGShmemSize(void)
1414 1415 1416 1417
{
	if (XLOGbuffers < MinXLOGbuffers)
		XLOGbuffers = MinXLOGbuffers;

1418
	return (sizeof(XLogCtlData) + BLCKSZ * XLOGbuffers +
1419 1420
			sizeof(XLogRecPtr) * XLOGbuffers +
			sizeof(ControlFileData));
1421 1422 1423 1424 1425
}

void
XLOGShmemInit(void)
{
1426
	bool		found;
1427

1428
	/* this must agree with space requested by XLOGShmemSize() */
1429 1430 1431
	if (XLOGbuffers < MinXLOGbuffers)
		XLOGbuffers = MinXLOGbuffers;

1432 1433
	XLogCtl = (XLogCtlData *)
		ShmemInitStruct("XLOG Ctl", sizeof(XLogCtlData) + BLCKSZ * XLOGbuffers +
1434 1435
						sizeof(XLogRecPtr) * XLOGbuffers, &found);
	Assert(!found);
1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446
	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();
1447 1448 1449 1450 1451 1452 1453 1454
}

/*
 * This func must be called ONCE on system install
 */
void
BootStrapXLOG()
{
1455
	CheckPoint	checkPoint;
1456
	char		buffer[BLCKSZ];
1457
	bool        usexistent = false;
1458 1459
	XLogPageHeader page = (XLogPageHeader) buffer;
	XLogRecord *record;
1460 1461 1462 1463 1464

	checkPoint.redo.xlogid = 0;
	checkPoint.redo.xrecoff = SizeOfXLogPHD;
	checkPoint.undo = checkPoint.redo;
	checkPoint.nextXid = FirstTransactionId;
1465
	checkPoint.nextOid = BootstrapObjectIdData;
V
WAL  
Vadim B. Mikheev 已提交
1466
	checkPoint.ThisStartUpID = 0;
V
misc  
Vadim B. Mikheev 已提交
1467
	checkPoint.Shutdown = true;
1468

1469 1470 1471 1472
	ShmemVariableCache->nextXid = checkPoint.nextXid;
	ShmemVariableCache->nextOid = checkPoint.nextOid;
	ShmemVariableCache->oidCount = 0;

1473 1474 1475
	memset(buffer, 0, BLCKSZ);
	page->xlp_magic = XLOG_PAGE_MAGIC;
	page->xlp_info = 0;
1476 1477 1478
	record = (XLogRecord *) ((char *) page + SizeOfXLogPHD);
	record->xl_prev.xlogid = 0;
	record->xl_prev.xrecoff = 0;
1479 1480 1481 1482 1483
	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;
1484
	memcpy((char *) record + SizeOfXLogRecord, &checkPoint, sizeof(checkPoint));
1485

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

1488
	if (write(logFile, buffer, BLCKSZ) != BLCKSZ)
1489
		elog(STOP, "BootStrapXLOG failed to write logfile: %m");
1490

1491
	if (pg_fsync(logFile) != 0)
1492
		elog(STOP, "BootStrapXLOG failed to fsync logfile: %m");
1493 1494 1495 1496

	close(logFile);
	logFile = -1;

1497
	memset(ControlFile, 0, sizeof(ControlFileData));
1498 1499 1500 1501 1502
	ControlFile->logId = 0;
	ControlFile->logSeg = 1;
	ControlFile->checkPoint = checkPoint.redo;
	ControlFile->time = time(NULL);
	ControlFile->state = DB_SHUTDOWNED;
1503
	/* some additional ControlFile fields are set in WriteControlFile() */
1504

1505
	WriteControlFile();
1506 1507
}

1508
static char *
1509 1510
str_time(time_t tnow)
{
1511
	static char buf[20];
1512

1513 1514 1515
	strftime(buf, sizeof(buf),
			 "%Y-%m-%d %H:%M:%S",
			 localtime(&tnow));
1516

1517
	return buf;
1518 1519 1520 1521 1522 1523 1524 1525
}

/*
 * This func must be called ONCE on system startup
 */
void
StartupXLOG()
{
1526 1527 1528 1529 1530 1531 1532
	XLogCtlInsert *Insert;
	CheckPoint	checkPoint;
	XLogRecPtr	RecPtr,
				LastRec;
	XLogRecord *record;
	char		buffer[MAXLOGRECSZ + SizeOfXLogRecord];

1533
	elog(LOG, "starting up");
1534
	StopIfError++;
1535

1536 1537
	XLogCtl->xlblocks = (XLogRecPtr *) (((char *) XLogCtl) + sizeof(XLogCtlData));
	XLogCtl->pages = ((char *) XLogCtl->xlblocks + sizeof(XLogRecPtr) * XLOGbuffers);
1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550
	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 已提交
1551
	S_INIT_LOCK(&(XLogCtl->chkp_lck));
1552 1553

	/*
1554 1555 1556 1557
	 * 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.
1558
	 */
1559
	ReadControlFile();
1560

1561 1562 1563 1564
	if (ControlFile->logSeg == 0 ||
		ControlFile->time <= 0 ||
		ControlFile->state < DB_SHUTDOWNED ||
		ControlFile->state > DB_IN_PRODUCTION ||
1565
		!XRecOffIsValid(ControlFile->checkPoint.xrecoff))
1566
		elog(STOP, "control file context is broken");
1567 1568

	if (ControlFile->state == DB_SHUTDOWNED)
1569
		elog(LOG, "database system was shut down at %s",
1570
			 str_time(ControlFile->time));
1571
	else if (ControlFile->state == DB_SHUTDOWNING)
1572
		elog(LOG, "database system shutdown was interrupted at %s",
1573
			 str_time(ControlFile->time));
1574
	else if (ControlFile->state == DB_IN_RECOVERY)
1575
		elog(LOG, "database system was interrupted being in recovery at %s\n"
1576
			 "\tThis propably means that some data blocks are corrupted\n"
1577
			 "\tand you will have to use last backup for recovery.",
1578
			 str_time(ControlFile->time));
1579
	else if (ControlFile->state == DB_IN_PRODUCTION)
1580
		elog(LOG, "database system was interrupted at %s",
1581
			 str_time(ControlFile->time));
1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592

	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");
1593
	checkPoint = *((CheckPoint *) ((char *) record + SizeOfXLogRecord));
1594

V
Vadim B. Mikheev 已提交
1595
	elog(LOG, "Redo record at (%u, %u); Undo record at (%u, %u); Shutdown %s",
1596
		 checkPoint.redo.xlogid, checkPoint.redo.xrecoff,
V
Vadim B. Mikheev 已提交
1597 1598
		 checkPoint.undo.xlogid, checkPoint.undo.xrecoff,
		 (checkPoint.Shutdown) ? "TRUE" : "FALSE");
1599
	elog(LOG, "NextTransactionId: %u; NextOid: %u",
1600 1601
		 checkPoint.nextXid, checkPoint.nextOid);
	if (checkPoint.nextXid < FirstTransactionId ||
1602 1603 1604 1605 1606
		checkPoint.nextOid < BootstrapObjectIdData)
		elog(STOP, "Invalid NextTransactionId/NextOid");

	ShmemVariableCache->nextXid = checkPoint.nextXid;
	ShmemVariableCache->nextOid = checkPoint.nextOid;
1607
	ShmemVariableCache->oidCount = 0;
1608

V
WAL  
Vadim B. Mikheev 已提交
1609 1610
	ThisStartUpID = checkPoint.ThisStartUpID;

1611 1612 1613 1614 1615 1616 1617
	if (XLByteLT(RecPtr, checkPoint.redo))
		elog(STOP, "Invalid redo in checkPoint record");
	if (checkPoint.undo.xrecoff == 0)
		checkPoint.undo = RecPtr;
	if (XLByteLT(RecPtr, checkPoint.undo))
		elog(STOP, "Invalid undo in checkPoint record");

V
Vadim B. Mikheev 已提交
1618 1619
	if (XLByteLT(checkPoint.undo, RecPtr) || 
		XLByteLT(checkPoint.redo, RecPtr))
1620
	{
V
Vadim B. Mikheev 已提交
1621 1622
		if (checkPoint.Shutdown)
			elog(STOP, "Invalid Redo/Undo record in shutdown checkpoint");
1623
		if (ControlFile->state == DB_SHUTDOWNED)
1624
			elog(STOP, "Invalid Redo/Undo record in shut down state");
V
WAL  
Vadim B. Mikheev 已提交
1625
		InRecovery = true;
1626 1627
	}
	else if (ControlFile->state != DB_SHUTDOWNED)
V
Vadim B. Mikheev 已提交
1628
	{
V
WAL  
Vadim B. Mikheev 已提交
1629
		InRecovery = true;
V
Vadim B. Mikheev 已提交
1630
	}
1631

V
WAL  
Vadim B. Mikheev 已提交
1632 1633
	/* REDO */
	if (InRecovery)
1634
	{
1635 1636
		elog(LOG, "database system was not properly shut down; "
			 "automatic recovery in progress...");
1637 1638 1639 1640
		ControlFile->state = DB_IN_RECOVERY;
		ControlFile->time = time(NULL);
		UpdateControlFile();

V
Vadim B. Mikheev 已提交
1641
		XLogOpenLogRelation();	/* open pg_log */
V
WAL  
Vadim B. Mikheev 已提交
1642
		XLogInitRelationCache();
V
Vadim B. Mikheev 已提交
1643

1644 1645 1646
		/* Is REDO required ? */
		if (XLByteLT(checkPoint.redo, RecPtr))
			record = ReadRecord(&(checkPoint.redo), buffer);
1647 1648
		else
/* read past CheckPoint record */
1649 1650 1651 1652
			record = ReadRecord(NULL, buffer);

		if (record->xl_len != 0)
		{
V
WAL  
Vadim B. Mikheev 已提交
1653
			InRedo = true;
1654
			elog(LOG, "redo starts at (%u, %u)",
1655
				 ReadRecPtr.xlogid, ReadRecPtr.xrecoff);
1656 1657 1658 1659
			do
			{
				if (record->xl_xid >= ShmemVariableCache->nextXid)
					ShmemVariableCache->nextXid = record->xl_xid + 1;
V
WAL  
Vadim B. Mikheev 已提交
1660 1661 1662 1663
				if (XLOG_DEBUG)
				{
					char	buf[8192];

1664 1665 1666
					sprintf(buf, "REDO @ %u/%u; LSN %u/%u: ", 
						ReadRecPtr.xlogid, ReadRecPtr.xrecoff,
						EndRecPtr.xlogid, EndRecPtr.xrecoff);
V
WAL  
Vadim B. Mikheev 已提交
1667 1668 1669 1670 1671 1672 1673 1674
					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));
				}

1675 1676 1677
				RmgrTable[record->xl_rmid].rm_redo(EndRecPtr, record);
				record = ReadRecord(NULL, buffer);
			} while (record->xl_len != 0);
1678
			elog(LOG, "redo done at (%u, %u)",
1679
				 ReadRecPtr.xlogid, ReadRecPtr.xrecoff);
1680
			LastRec = ReadRecPtr;
V
WAL  
Vadim B. Mikheev 已提交
1681
			InRedo = false;
1682 1683
		}
		else
1684
			elog(LOG, "redo is not required");
V
WAL  
Vadim B. Mikheev 已提交
1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709
	}

	/* 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;
1710

V
Vadim B. Mikheev 已提交
1711
#ifdef NOT_USED
V
WAL  
Vadim B. Mikheev 已提交
1712 1713 1714
	/* UNDO */
	if (InRecovery)
	{
1715 1716 1717
		RecPtr = ReadRecPtr;
		if (XLByteLT(checkPoint.undo, RecPtr))
		{
1718
			elog(LOG, "undo starts at (%u, %u)",
1719
				 RecPtr.xlogid, RecPtr.xrecoff);
1720 1721 1722
			do
			{
				record = ReadRecord(&RecPtr, buffer);
1723
				if (TransactionIdIsValid(record->xl_xid) &&
1724
					!TransactionIdDidCommit(record->xl_xid))
V
misc  
Vadim B. Mikheev 已提交
1725
					RmgrTable[record->xl_rmid].rm_undo(EndRecPtr, record);
1726 1727
				RecPtr = record->xl_prev;
			} while (XLByteLE(checkPoint.undo, RecPtr));
1728
			elog(LOG, "undo done at (%u, %u)",
1729
				 ReadRecPtr.xlogid, ReadRecPtr.xrecoff);
1730 1731
		}
		else
1732
			elog(LOG, "undo is not required");
1733
	}
V
WAL  
Vadim B. Mikheev 已提交
1734
#endif
1735

V
WAL  
Vadim B. Mikheev 已提交
1736
	if (InRecovery)
1737 1738
	{
		CreateCheckPoint(true);
V
WAL  
Vadim B. Mikheev 已提交
1739
		XLogCloseRelationCache();
1740
	}
V
WAL  
Vadim B. Mikheev 已提交
1741
	InRecovery = false;
1742 1743 1744 1745 1746

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

V
WAL  
Vadim B. Mikheev 已提交
1747 1748 1749
	ThisStartUpID++;
	XLogCtl->ThisStartUpID = ThisStartUpID;

1750
	elog(LOG, "database system is in production state");
1751
	StopIfError--;
1752 1753 1754 1755

	return;
}

V
WAL  
Vadim B. Mikheev 已提交
1756 1757 1758 1759 1760 1761 1762 1763 1764 1765
/*
 * Postmaster uses it to set ThisStartUpID from XLogCtlData
 * located in shmem after successful startup.
 */
void
SetThisStartUpID(void)
{
	ThisStartUpID = XLogCtl->ThisStartUpID;
}

1766 1767 1768 1769 1770 1771
/*
 * This func must be called ONCE on system shutdown
 */
void
ShutdownXLOG()
{
1772
	elog(LOG, "shutting down");
1773

1774
	StopIfError++;
V
Vadim B. Mikheev 已提交
1775
	CreateDummyCaches();
1776
	CreateCheckPoint(true);
1777
	StopIfError--;
1778

1779
	elog(LOG, "database system is shut down");
1780 1781
}

V
Vadim B. Mikheev 已提交
1782 1783
extern XLogRecPtr	GetUndoRecPtr(void);

1784 1785 1786
void
CreateCheckPoint(bool shutdown)
{
1787 1788 1789 1790 1791
	CheckPoint	checkPoint;
	XLogRecPtr	recptr;
	XLogCtlInsert *Insert = &XLogCtl->Insert;
	uint32		freespace;
	uint16		curridx;
V
Vadim B. Mikheev 已提交
1792 1793 1794 1795 1796 1797 1798
	uint32		_logId;
	uint32		_logSeg;
	char		archdir[MAXPGPATH];

	if (MyLastRecPtr.xrecoff != 0)
		elog(ERROR, "CreateCheckPoint: cannot be called inside transaction block");
 
1799
	START_CRIT_CODE;
V
Vadim B. Mikheev 已提交
1800 1801 1802 1803 1804 1805 1806 1807
	while (TAS(&(XLogCtl->chkp_lck)))
	{
		struct timeval delay = {2, 0};

		if (shutdown)
			elog(STOP, "Checkpoint lock is busy while data base is shutting down");
		(void) select(0, NULL, NULL, NULL, &delay);
	}
1808 1809 1810 1811 1812 1813 1814 1815

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

	/* Get REDO record ptr */
1820
	while (TAS(&(XLogCtl->insert_lck)))
1821
	{
V
Vadim B. Mikheev 已提交
1822
		struct timeval delay = {1, 0};
1823 1824 1825 1826 1827

		if (shutdown)
			elog(STOP, "XLog insert lock is busy while data base is shutting down");
		(void) select(0, NULL, NULL, NULL, &delay);
	}
1828
	freespace = ((char *) Insert->currpage) + BLCKSZ - Insert->currpos;
1829 1830 1831 1832 1833
	if (freespace < SizeOfXLogRecord)
	{
		curridx = NextBufIdx(Insert->curridx);
		if (XLByteLE(XLogCtl->xlblocks[curridx], LgwrResult.Write))
			InitXLBuffer(curridx);
1834
		else
1835 1836 1837 1838 1839 1840
			GetFreeXLBuffer();
		freespace = BLCKSZ - SizeOfXLogPHD;
	}
	else
		curridx = Insert->curridx;
	checkPoint.redo.xlogid = XLogCtl->xlblocks[curridx].xlogid;
1841 1842
	checkPoint.redo.xrecoff = XLogCtl->xlblocks[curridx].xrecoff - BLCKSZ +
		Insert->currpos - ((char *) Insert->currpage);
1843 1844 1845 1846 1847 1848 1849
	S_UNLOCK(&(XLogCtl->insert_lck));

	SpinAcquire(XidGenLockId);
	checkPoint.nextXid = ShmemVariableCache->nextXid;
	SpinRelease(XidGenLockId);
	SpinAcquire(OidGenLockId);
	checkPoint.nextOid = ShmemVariableCache->nextOid;
1850 1851 1852
	if (!shutdown)
		checkPoint.nextOid += ShmemVariableCache->oidCount;

1853 1854
	SpinRelease(OidGenLockId);

V
Vadim B. Mikheev 已提交
1855
	FlushBufferPool();
1856

V
Vadim B. Mikheev 已提交
1857
	/* Get UNDO record ptr - should use oldest of PROC->logRec */
V
Vadim B. Mikheev 已提交
1858
	checkPoint.undo = GetUndoRecPtr();
1859 1860 1861 1862

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

V
WAL  
Vadim B. Mikheev 已提交
1863 1864
	recptr = XLogInsert(RM_XLOG_ID, XLOG_CHECKPOINT, (char *) &checkPoint, 
			sizeof(checkPoint), NULL, 0);
1865 1866 1867 1868 1869 1870 1871 1872 1873

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

	XLogFlush(recptr);

	SpinAcquire(ControlFileLockId);
	if (shutdown)
		ControlFile->state = DB_SHUTDOWNED;
V
Vadim B. Mikheev 已提交
1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895
	else	/* create new log file */
	{
		if (recptr.xrecoff % XLogSegSize >= 
			(uint32) (0.75 * XLogSegSize))
		{
			int		lf;
			bool	usexistent = true;

			_logId = recptr.xlogid;
			_logSeg = recptr.xrecoff / XLogSegSize;
			if (_logSeg >= XLogLastSeg)
			{
				_logId++;
				_logSeg = 0;
			}
			else
				_logSeg++;
			lf = XLogFileInit(_logId, _logSeg, &usexistent);
			close(lf);
		}
	}

1896
	ControlFile->checkPoint = MyLastRecPtr;
V
Vadim B. Mikheev 已提交
1897 1898 1899 1900 1901

	_logId = ControlFile->logId;
	_logSeg = ControlFile->logSeg - 1;
	strcpy(archdir, ControlFile->archdir);

1902 1903 1904 1905
	ControlFile->time = time(NULL);
	UpdateControlFile();
	SpinRelease(ControlFileLockId);

V
Vadim B. Mikheev 已提交
1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929
	/*
	 * Delete offline log files. Get oldest online
	 * log file from undo rec if it's valid.
	 */
	if (checkPoint.undo.xrecoff != 0)
	{
		_logId = checkPoint.undo.xlogid;
		_logSeg = checkPoint.undo.xrecoff / XLogSegSize;
	}
	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 */
1930
	END_CRIT_CODE;
V
Vadim B. Mikheev 已提交
1931

1932 1933
	return;
}
V
WAL  
Vadim B. Mikheev 已提交
1934

1935 1936 1937 1938 1939 1940 1941 1942 1943
void XLogPutNextOid(Oid nextOid);

void
XLogPutNextOid(Oid nextOid)
{
	(void) XLogInsert(RM_XLOG_ID, XLOG_NEXTOID, 
					(char *) &nextOid, sizeof(Oid), NULL, 0);
}

V
WAL  
Vadim B. Mikheev 已提交
1944 1945 1946 1947

void
xlog_redo(XLogRecPtr lsn, XLogRecord *record)
{
1948 1949 1950 1951 1952 1953 1954 1955 1956 1957
	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 已提交
1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980
}
 
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");
	}
1981 1982 1983 1984 1985 1986 1987
	else if (info == XLOG_NEXTOID)
	{
		Oid		nextOid;

		memcpy(&nextOid, rec, sizeof(Oid));
		sprintf(buf + strlen(buf), "nextOid: %u", nextOid);
	}
V
WAL  
Vadim B. Mikheev 已提交
1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000
	else
		strcat(buf, "UNKNOWN");
}

static void
xlog_outrec(char *buf, XLogRecord *record)
{
	sprintf(buf + strlen(buf), "prev %u/%u; xprev %u/%u; xid %u: %s",
		record->xl_prev.xlogid, record->xl_prev.xrecoff,
		record->xl_xact_prev.xlogid, record->xl_xact_prev.xrecoff,
		record->xl_xid, 
		RmgrTable[record->xl_rmid].rm_name);
}