InstallXLogFileSegment(XLogSegNo *segno, char *tmppath,
					   bool find_free, int *max_advance,
					   bool use_lock)
{
	char		path[MAXPGPATH];
	struct stat stat_buf;

	XLogFilePath(path, ThisTimeLineID, *segno);

	/*
	 * We want to be sure that only one process does this at a time.
	 */
	if (use_lock)
		LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);

	if (!find_free)
	{
		/* Force installation: get rid of any pre-existing segment file */
		unlink(path);
	}
	else
	{
		/* Find a free slot to put it in */
		while (stat(path, &stat_buf) == 0)
		{
			if (*max_advance <= 0)
			{
				/* Failed to find a free slot within specified range */
				if (use_lock)
					LWLockRelease(ControlFileLock);
				return false;
			}
			(*segno)++;
			(*max_advance)--;
			XLogFilePath(path, ThisTimeLineID, *segno);
		}
	}

	/*
	 * Prefer link() to rename() here just to be really sure that we don't
	 * overwrite an existing logfile.  However, there shouldn't be one, so
	 * rename() is an acceptable substitute except for the truly paranoid.
	 */
#if HAVE_WORKING_LINK
	if (link(tmppath, path) < 0)
	{
		if (use_lock)
			LWLockRelease(ControlFileLock);
		ereport(LOG,
				(errcode_for_file_access(),
				 errmsg("could not link file \"%s\" to \"%s\" (initialization of log file): %m",
						tmppath, path)));
		return false;
	}
	unlink(tmppath);
#else
	if (rename(tmppath, path) < 0)
	{
		if (use_lock)
			LWLockRelease(ControlFileLock);
		ereport(LOG,
				(errcode_for_file_access(),
				 errmsg("could not rename file \"%s\" to \"%s\" (initialization of log file): %m",
						tmppath, path)));
		return false;
	}
#endif

	if (use_lock)
		LWLockRelease(ControlFileLock);

	return true;
}
InstallXLogFileSegment(XLogSegNo *segno, char *tmppath,
					   bool find_free, int *max_advance,
					   bool use_lock)
{
	char		path[MAXPGPATH];
	struct stat stat_buf;

	XLogFilePath(path, ThisTimeLineID, *segno);

	 
	if (use_lock)
		LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);

	if (!find_free)
	{
		 
		unlink(path);
	}
	else
	{
		 
		while (stat(path, &stat_buf) == 0)
		{
			if (*max_advance <= 0)
			{
				 
				if (use_lock)
					LWLockRelease(ControlFileLock);
				return false;
			}
			(*segno)++;
			(*max_advance)--;
			XLogFilePath(path, ThisTimeLineID, *segno);
		}
	}

	 
#if HAVE_WORKING_LINK
	if (link(tmppath, path) < 0)
	{
		if (use_lock)
			LWLockRelease(ControlFileLock);
		ereport(LOG,
				(errcode_for_file_access(),
				 errmsg("could not link file \"%s\" to \"%s\" (initialization of log file): %m",
						tmppath, path)));
		return false;
	}
	unlink(tmppath);
#else
	if (rename(tmppath, path) < 0)
	{
		if (use_lock)
			LWLockRelease(ControlFileLock);
		ereport(LOG,
				(errcode_for_file_access(),
				 errmsg("could not rename file \"%s\" to \"%s\" (initialization of log file): %m",
						tmppath, path)));
		return false;
	}
#endif

	if (use_lock)
		LWLockRelease(ControlFileLock);

	return true;
}