/*-------------------------------------------------------------------------
 *
 * pg_stat_statements.c
 *
 *-------------------------------------------------------------------------
 */
#include "postgres.h"

#include <unistd.h>

#include "access/hash.h"
#include "funcapi.h"
#include "mb/pg_wchar.h"
#include "miscadmin.h"
#include "portability/instr_time.h"
#include "storage/ipc.h"
#include "storage/spin.h"
#include "utils/builtins.h"
#include "utils/guc_tables.h"
#include "utils/memutils.h"
#include "tcop/pquery.h"

#ifdef HAVE_SYS_RESOURCE_H
#include <sys/time.h>
#include <sys/resource.h>
#endif
#ifndef HAVE_GETRUSAGE
#include "rusagestub.h"
#endif

extern PGDLLIMPORT bool	log_executor_stats;
extern PGDLLIMPORT bool	log_statement_stats;
extern PGDLLIMPORT int	pgstat_track_activity_query_size;
extern PGDLLIMPORT long int ReadBufferCount;
extern PGDLLIMPORT long int ReadLocalBufferCount;
extern PGDLLIMPORT long int BufferHitCount;
extern PGDLLIMPORT long int LocalBufferHitCount;
extern PGDLLIMPORT long int BufferFlushCount;
extern PGDLLIMPORT long int LocalBufferFlushCount;
extern PGDLLIMPORT long BufFileReadCount;
extern PGDLLIMPORT long BufFileWriteCount;

/* #define PGSS_DEBUG */

PG_MODULE_MAGIC;

#define GUCNAME(name)		("statistics." name)

#define MAX_STATEMENTS_DEFAULT	1000
#define CHUNK_SIZE				MAXALIGN(pgstat_track_activity_query_size)

/* XXX: Should USAGE_EXEC reflect execution time and/or buffer usage? */
#define USAGE_EXEC(duration)	(1.0)
#define USAGE_INIT				(1.0)	/* including initial planning */
#define USAGE_DECREASE_FACTOR	(0.99)	/* decreased every entry_dealloc */
#define USAGE_DEALLOC_PERCENT	5		/* free this % of entries at once */

#define timeval_diff_in_usec(end, beg) \
	( (int64) ((end).tv_sec - (beg).tv_sec) * 1000000 \
	+ ((end).tv_usec - (beg).tv_usec))

#define current_gets()		(ReadBufferCount + ReadLocalBufferCount)
#define current_hits()		(BufferHitCount + LocalBufferHitCount)
#define current_writes()	(BufferFlushCount + LocalBufferFlushCount)
#define current_lreads()	(BufFileReadCount)
#define current_lwrites()	(BufFileWriteCount)

/*
 * Chunk buffer for query text.
 */
typedef union Chunk Chunk;
union Chunk
{
	char	query[1];	/* query text. true size is [CHUNK_SIZE] */
	Chunk  *next;		/* next free chunk */
};

/*
 * Statistics per statement
 */
typedef struct Entry
{
	uint32		tag;		/* hash value of query */
	Oid			userid;		/* user oid */
	Oid			dbid;		/* database oid */
	int64		calls;		/* # of executed */
	instr_time	total_time;	/* total execution time */
	int64		cpu_user;	/* user cpu time in usec */
	int64		cpu_sys;	/* sys cpu time in usec */
	int64		gets;		/* # of buffer gets during execution */
	int64		reads;		/* # of buffer reads during execution */
	int64		writes;		/* # of buffer writes during execution */
	int64		lreads;		/* # of buffile reads during execution */
	int64		lwrites;	/* # of buffile writes during execution */
	int64		rows;		/* # of retrieved or affected rows */
	double		usage;		/* usage factor */
	Chunk	   *chunk;		/* query text */
	slock_t		mutex;		/* protect above fields */
} Entry;

/*
 * Global shared state
 */
typedef struct pgStatStmt
{
	LWLockId	lock;				/* protect fields and hash */
	int			num_statements;		/* # of entries in hash */
	int			chunk_size;			/* max query length in bytes */
	Chunk	   *free_chunks;		/* single linked list of free chunks */
	Chunk		chunks[1];			/* chunk buffers */
} pgStatStmt;

/*---- Local variables ----*/

static ExecutorRun_hook_type	prev_ExecutorRun;
static startup_hook_type		prev_startup_hook;
static shutdown_hook_type		prev_shutdown_hook;
static pgStatStmt			   *pgss;
static HTAB					   *pgss_hash;
static bool						pgss_reset_requested = false;

/*---- Function declarations ----*/

void	_PG_init(void);
void	_PG_fini(void);
Datum	pg_stat_statements_reset(PG_FUNCTION_ARGS);
Datum	pg_stat_statements(PG_FUNCTION_ARGS);

PG_FUNCTION_INFO_V1(pg_stat_statements_reset);
PG_FUNCTION_INFO_V1(pg_stat_statements);

static uint32 pgss_tag(Oid userid, Oid dbid, const char *query);
static TupleTableSlot *pgss_ExecutorRun(QueryDesc *queryDesc,
                                        ScanDirection direction,
                                        long count);
static void pgss_executed(const char *query,
		instr_time duration, int64 cpu_user, int64 cpu_sys,
		long gets, long reads, long writes,
		long lreads, long lwrites, uint32 rows);

static Size	pgss_memsize(void);
static void pgss_init(void);
static volatile Entry *entry_alloc(uint32 tag, Oid userid, Oid dbid,
							const char *query);
static void entry_dealloc(void);
static void entry_reset(void);
static Chunk *chunk_alloc(void);
static void chunk_free(Chunk *chunk);
static void chunk_reset(void);

static bool assign_max_statements(int newval, bool doit, GucSource source);
static bool assign_track_statements(bool newval, bool doit, GucSource source);
static const char *assign_saved_file(const char *newval, bool doit, GucSource source);

/*---- GUC variables ----*/

static bool		track_statements = true;
static int		max_statements = 0;
static char	   *saved_file = NULL;

static struct config_int def_max_statements =
{
	{
		GUCNAME("max_statements"),
		PGC_USERSET,
		STATS_COLLECTOR,
		"Sets the maximum number of statements tracked by pg_stat_statements."
	},
	&max_statements,
	1000, 100, INT_MAX, assign_max_statements, NULL
};

static struct config_bool def_track_statements =
{
	{
		GUCNAME("track_statements"),
		PGC_USERSET,
		STATS_COLLECTOR,
		"Collects information about executed statements."
	},
	&track_statements,
	true, assign_track_statements, NULL
};

static struct config_string def_saved_file =
{
	{
		GUCNAME("saved_file"),
		PGC_USERSET,
		STATS_COLLECTOR,
		"Writes statistic files to the specified path.",
		NULL,
		GUC_SUPERUSER_ONLY
	},
	&saved_file,
	"global/pg_stat_statements.dump", assign_saved_file, NULL
};

const uint32 PGSS_FILE_HEADER = 0x20081027;

/*
 * pgss_shutdown - Dump statistics into file.
 */
static void
pgss_shutdown(void)
{
	FILE			   *file;
	HASH_SEQ_STATUS		hash_seq;
	Entry			   *entry;
	int					save_errno;

	if (prev_shutdown_hook)
		prev_shutdown_hook();

	if (saved_file == NULL || saved_file[0] == '\0')
		return;

	if (!pgss)
		pgss_init();

	file = fopen(saved_file, PG_BINARY_W);
	if (file == NULL ||
		fwrite(&PGSS_FILE_HEADER, sizeof(uint32), 1, file) != 1 ||
		fwrite(&pgss->num_statements, sizeof(int32), 1, file) != 1)
		goto error;

	hash_seq_init(&hash_seq, pgss_hash);
	while ((entry = hash_seq_search(&hash_seq)) != NULL)
	{
		int32	len = (int32) strlen(entry->chunk->query);

		if (fwrite(entry, offsetof(Entry, chunk), 1, file) != 1 ||
			fwrite(&len, sizeof(int32), 1, file) != 1 ||
			fwrite(entry->chunk->query, 1, len, file) != len)
			goto error;
	}

	fclose(file);
	return;

error:
	save_errno = errno;

	if (file)
		fclose(file);
	unlink(saved_file);

	errno = save_errno;
	ereport(LOG,
		(errcode_for_file_access(),
		 errmsg("could not write pg_stat_statement file \"%s\": %m",
				saved_file)));
}

/*
 * pgss_shutdown - Load statistics from file.
 */
static void
pgss_startup(void)
{
	FILE	   *file;
	uint32		header;
	int32		num;
	int32		i;
	char	   *buffer = NULL;
	int			save_errno;

	if (prev_startup_hook)
		prev_startup_hook();

	if (saved_file == NULL || saved_file[0] == '\0')
		return;

	file = fopen(saved_file, PG_BINARY_R);
	if (file == NULL)
	{
		if (errno == ENOENT)
			return;	/* ignore not found error */
		goto error;
	}

	if (!pgss)
		pgss_init();

	buffer = palloc(CHUNK_SIZE);

	if (fread(&header, sizeof(uint32), 1, file) != 1 ||
		header != PGSS_FILE_HEADER ||
		fread(&num, sizeof(int32), 1, file) != 1)
		goto error;

	for (i = 0; i < num; i++)
	{
		Entry		temp;
		Entry	   *entry;
		int32		templen;
		int32		len;

		if (fread(&temp, offsetof(Entry, chunk), 1, file) != 1 ||
			fread(&templen, sizeof(int32), 1, file) != 1)
			goto error;

		/*
		 * We might not have enough buffer to read query text
		 * when pgstat_track_activity_query_size is set smaller.
		 */
		if (templen < CHUNK_SIZE)
			len = templen;
		else
			len = CHUNK_SIZE - 1;

		if (fread(buffer, 1, len, file) != len)
			goto error;
		buffer[len] = '\0';
		entry = (Entry *) entry_alloc(
			temp.tag, temp.userid, temp.dbid, buffer);
		memcpy(entry, &temp, offsetof(Entry, chunk));

		/* Discard the tail of query text. */
		if (templen > len)
			fseek(file, templen - len, SEEK_CUR);
	}

	pfree(buffer);
	fclose(file);
	return;

error:
	save_errno = errno;

	if (file)
		fclose(file);
	unlink(saved_file);
	if (buffer)
		pfree(buffer);

	errno = save_errno;
	ereport(LOG,
		(errcode_for_file_access(),
		 errmsg("could not read pg_stat_statement file \"%s\": %m",
				saved_file)));
}

void
_PG_init(void)
{
	/* Define custom guc variables. */
	DefineCustomVariable(PGC_INT, &def_max_statements);
	DefineCustomVariable(PGC_BOOL, &def_track_statements);
	DefineCustomVariable(PGC_STRING, &def_saved_file);

	/* Request additonal shared resources. */
	RequestAddinShmemSpace(pgss_memsize());
	RequestAddinLWLocks(1);

	/* Install hooks. */
	prev_startup_hook = startup_hook;
	startup_hook = pgss_startup;
	prev_shutdown_hook = shutdown_hook;
	shutdown_hook = pgss_shutdown;
	prev_ExecutorRun = ExecutorRun_hook;
	ExecutorRun_hook = pgss_ExecutorRun;
}

void
_PG_fini(void)
{
	/* Uninstall hooks. */
	ExecutorRun_hook = prev_ExecutorRun;
	shutdown_hook = prev_shutdown_hook;
	startup_hook = prev_startup_hook;
}

static uint32
pgss_tag(Oid userid, Oid dbid, const char *query)
{
	return oid_hash(&userid, sizeof(Oid)) ^
		   oid_hash(&dbid, sizeof(Oid)) ^
		   DatumGetUInt32(hash_any((const unsigned char *) query,
								   (int) strlen(query)));
}

static void
pgss_executed(const char *query, instr_time duration,
			  int64 cpu_user, int64 cpu_sys,
			  long gets, long reads, long writes,
			  long lreads, long lwrites, uint32 rows)
{
	volatile Entry *entry;
	Oid				userid;
	Oid				dbid;
	uint32			tag;

	Assert(query != NULL);

	if (!track_statements)
		return;
	if (!pgss)
		pgss_init();

	userid = GetUserId();
	dbid = MyDatabaseId;
	tag = pgss_tag(userid, dbid, query);

	LWLockAcquire(pgss->lock, LW_SHARED);

	entry = hash_search(pgss_hash, &tag, HASH_FIND, NULL);
	if (!entry)
	{
		/* Re-acquire exclusive lock to add a new entry. */
		LWLockRelease(pgss->lock);
		LWLockAcquire(pgss->lock, LW_EXCLUSIVE);
		entry = entry_alloc(tag, userid, dbid, query);
	}

	SpinLockAcquire(&entry->mutex);
	INSTR_TIME_ADD(entry->total_time, duration);
	entry->calls += 1;
	entry->cpu_user += cpu_user;
	entry->cpu_sys += cpu_sys;
	entry->gets += gets;
	entry->reads += reads;
	entry->writes += writes;
	entry->lreads += lreads;
	entry->lwrites += lwrites;
	entry->rows += rows;
	entry->usage += USAGE_EXEC(duration);
	SpinLockRelease(&entry->mutex);

	LWLockRelease(pgss->lock);
}

typedef struct EStack EStack;
struct EStack
{
	long			gets;
	long			hits;
	long			writes;
	long			lreads;
	long			lwrites;
	struct rusage	ru;
	instr_time		starttime;
	EStack		   *next;
};

static EStack *stack = NULL;

static void
stack_push(void)
{
	EStack *s = MemoryContextAlloc(TopMemoryContext, sizeof(EStack));
	s->gets = current_gets();
	s->hits = current_hits();
	s->writes = current_writes();
	s->lreads = current_lreads();
	s->lwrites = current_lwrites();
	getrusage(RUSAGE_SELF, &s->ru);
	INSTR_TIME_SET_CURRENT(s->starttime);

	s->next = stack;
	stack = s;
}

static void
stack_pop(void)
{
	EStack *temp = stack;
	stack = stack->next;
	pfree(temp);
}

TupleTableSlot *
pgss_ExecutorRun(QueryDesc *queryDesc, ScanDirection direction, long count)
{
	TupleTableSlot *result;
	const char	   *query;

	Assert(ActivePortal != NULL);
	Assert(ActivePortal->sourceText != NULL);

	query = queryDesc->sourceText;

	if (track_statements && query)
	{
#ifdef PGSS_DEBUG
		elog(NOTICE, "EXEC: %s", query);
#endif

		stack_push();

		/* Disable our hooks temporarily during the top-level query. */
		PG_TRY();
		{
			if (prev_ExecutorRun)
				result = prev_ExecutorRun(queryDesc, direction, count);
			else
				result = standard_ExecutorRun(queryDesc, direction, count);

			if (pgss_reset_requested)
			{
				entry_reset();
				pgss_reset_requested = false;
			}
			else
			{
				long			gets;
				long			hits;
				long			writes;
				long			lreads;
				long			lwrites;
				struct rusage	ru;
				instr_time		duration;

				INSTR_TIME_SET_CURRENT(duration);
				INSTR_TIME_SUBTRACT(duration, stack->starttime);
				getrusage(RUSAGE_SELF, &ru);

				gets = current_gets() - stack->gets;
				hits = current_hits() - stack->hits;
				writes = current_writes() - stack->writes;
				lreads = current_lreads() - stack->lreads;
				lwrites = current_lwrites() - stack->lwrites;

				pgss_executed(query, duration,
					timeval_diff_in_usec(ru.ru_utime, stack->ru.ru_utime),
					timeval_diff_in_usec(ru.ru_stime, stack->ru.ru_stime),
					gets, gets - hits, writes, lreads, lwrites,
					queryDesc->estate->es_processed);
			}
			stack_pop();
		}
		PG_CATCH();
		{
			stack_pop();
			PG_RE_THROW();
		}
		PG_END_TRY();
	}
	else
	{
#ifdef PGSS_DEBUG
		elog(NOTICE, "EXEC(ignore): %s", query ? query : "(NULL)");
#endif
		/* ignore recursive executions, that are typically function calls */
		if (prev_ExecutorRun)
			result = prev_ExecutorRun(queryDesc, direction, count);
		else
			result = standard_ExecutorRun(queryDesc, direction, count);
	}

	return result;
}

Datum
pg_stat_statements_reset(PG_FUNCTION_ARGS)
{
	if (!pgss)
		pgss_init();
	pgss_reset_requested = true;
	PG_RETURN_BOOL(true);
}

#define pg_stat_statements_cols		13

Datum
pg_stat_statements(PG_FUNCTION_ARGS)
{
	ReturnSetInfo	   *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
	TupleDesc			tupdesc;
	Tuplestorestate    *tupstore;
	MemoryContext		per_query_ctx;
	MemoryContext		oldcontext;
	Oid					userid = GetUserId();
	bool				is_superuser = superuser();
	HASH_SEQ_STATUS		hash_seq;
	Entry			   *entry;

	if (!pgss)
		pgss_init();

	/* check to see if caller supports us returning a tuplestore */
	if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
		ereport(ERROR,
				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
				 errmsg("set-valued function called in context that cannot accept a set")));
	if (!(rsinfo->allowedModes & SFRM_Materialize))
		ereport(ERROR,
				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
				 errmsg("materialize mode required, but it is not " \
						"allowed in this context")));

	per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
	oldcontext = MemoryContextSwitchTo(per_query_ctx);

	tupdesc = CreateTupleDescCopy(rsinfo->expectedDesc);
	tupstore = tuplestore_begin_heap(true, false, work_mem);
	rsinfo->returnMode = SFRM_Materialize;
	rsinfo->setResult = tupstore;
	rsinfo->setDesc = tupdesc;

	LWLockAcquire(pgss->lock, LW_SHARED);

	hash_seq_init(&hash_seq, pgss_hash);
	while ((entry = hash_seq_search(&hash_seq)) != NULL)
	{
		Datum	values[pg_stat_statements_cols];
		bool	nulls[pg_stat_statements_cols] = { 0 };
		int		i = 0;

		/* generate junk in short-term context */
		MemoryContextSwitchTo(oldcontext);

		values[i++] = ObjectIdGetDatum(entry->userid);
		values[i++] = ObjectIdGetDatum(entry->dbid);

		if (is_superuser || entry->userid == userid)
			values[i++] = CStringGetTextDatum(entry->chunk->query);
		else
			values[i++] = CStringGetTextDatum("<insufficient privilege>");

		SpinLockAcquire(&entry->mutex);
		values[i++] = Int64GetDatumFast(entry->calls);
		values[i++] = Int64GetDatum(INSTR_TIME_GET_MICROSEC(entry->total_time));
		values[i++] = Int64GetDatumFast(entry->cpu_user);
		values[i++] = Int64GetDatumFast(entry->cpu_sys);
		values[i++] = Int64GetDatumFast(entry->gets);
		values[i++] = Int64GetDatumFast(entry->reads);
		values[i++] = Int64GetDatumFast(entry->writes);
		values[i++] = Int64GetDatumFast(entry->lreads);
		values[i++] = Int64GetDatumFast(entry->lwrites);
		values[i++] = Int64GetDatumFast(entry->rows);
		SpinLockRelease(&entry->mutex);
		Assert(i == pg_stat_statements_cols);

		/* switch to appropriate context while storing the tuple */
		MemoryContextSwitchTo(per_query_ctx);
		tuplestore_putvalues(tupstore, tupdesc, values, nulls);
	}

	LWLockRelease(pgss->lock);

	/* clean up and return the tuplestore */
	tuplestore_donestoring(tupstore);

	MemoryContextSwitchTo(oldcontext);

	return (Datum) 0;
}

static Size
pgss_memsize(void)
{
	Size	size;

	size = offsetof(pgStatStmt, chunks);
	size = add_size(size, mul_size(max_statements, CHUNK_SIZE));
	size = add_size(size, hash_estimate_size(max_statements, sizeof(Entry)));

	return size;
}

static void
pgss_init(void)
{
    bool		found;
	Size		size;
	HASHCTL		info = { 0 };

	Assert(pgss == NULL);

	size = pgss_memsize();

	LWLockAcquire(AddinShmemInitLock, LW_EXCLUSIVE);

	pgss = ShmemInitStruct("pg_stat_statements", size, &found);
	if (!pgss)
		elog(ERROR, "out of shared memory");

	if (!found)
    {
		pgss->lock = LWLockAssign();
		pgss->num_statements = 0;
		pgss->chunk_size = CHUNK_SIZE;
		chunk_reset();
	}

	info.keysize = sizeof(uint32);
	info.entrysize = sizeof(Entry);
	info.hash = oid_hash;
	pgss_hash = ShmemInitHash("pg_stat_statements hash",
							  max_statements, max_statements,
							  &info,
							  HASH_ELEM | HASH_FUNCTION);
	if (!pgss_hash)
		elog(ERROR, "out of shared memory");

	LWLockRelease(AddinShmemInitLock);
}

/*
 * caller must be hold an exclusive lock on pgStateStmt->lock
 */
static volatile Entry *
entry_alloc(uint32 tag, Oid userid, Oid dbid, const char *query)
{
	bool	found;
	Entry  *entry;

	Assert(query != NULL);

	while (pgss->num_statements >= max_statements)
		entry_dealloc();

	entry = hash_search(pgss_hash, &tag, HASH_ENTER, &found);

	if (!found)
	{
		Size	len;

		pgss->num_statements++;

		entry->userid = userid;
		entry->dbid = dbid;

		entry->chunk = chunk_alloc();
		len = strlen(query);
		len = pg_mbcliplen(query, len, pgss->chunk_size - 1);
		memcpy(entry->chunk->query, query, len);
		entry->chunk->query[len] = '\0';

		entry->calls = 0;
		INSTR_TIME_SET_ZERO(entry->total_time);
		entry->cpu_user = 0;
		entry->cpu_sys = 0;
		entry->gets = 0;
		entry->reads = 0;
		entry->writes = 0;
		entry->lreads = 0;
		entry->lwrites = 0;
		entry->rows = 0;
		entry->usage = USAGE_INIT;
		INSTR_TIME_SET_ZERO(entry->total_time);
		SpinLockInit(&entry->mutex);
	}

	return entry;
}

/*
 * Free least recently used entries.
 * Caller must be hold an exclusive lock on pgStateStmt->lock.
 */
static int
entry_cmp(const void *lhs, const void *rhs)
{
	double	l_usage = (*(const Entry **)lhs)->usage;
	double	r_usage = (*(const Entry **)rhs)->usage;

	if (l_usage < r_usage)
		return -1;
	else if (l_usage > r_usage)
		return +1;
	else
		return 0;
}

/*
 * Deallocate least used entries.
 */
static void
entry_dealloc(void)
{
	HASH_SEQ_STATUS		hash_seq;
	Entry			  **entries;
	Entry			   *entry;
	int					nvictims;
	int					i;

	/* Sort entries by usage and deallocate USAGE_DEALLOC_PERCENT of them. */

	entries = palloc(pgss->num_statements * sizeof(Entry *));

	i = 0;
	hash_seq_init(&hash_seq, pgss_hash);
	while ((entry = hash_seq_search(&hash_seq)) != NULL)
	{
		entries[i++] = entry;
		entry->usage *= USAGE_DECREASE_FACTOR;
	}

	qsort(entries, i, sizeof(Entry *), entry_cmp);
	nvictims = Max(10, i * USAGE_DEALLOC_PERCENT / 100);

	for (i = 0; i < nvictims; i++)
	{
		chunk_free(entries[i]->chunk);
		(void) SpinLockFree(&entries[i]->mutex);
		hash_search(pgss_hash, &entries[i]->tag, HASH_REMOVE, NULL);
		pgss->num_statements--;
	}

	pfree(entries);
}

static void
entry_reset(void)
{
	HASH_SEQ_STATUS		hash_seq;
	Entry			   *entry;

	LWLockAcquire(pgss->lock, LW_EXCLUSIVE);

	hash_seq_init(&hash_seq, pgss_hash);
	while ((entry = hash_seq_search(&hash_seq)) != NULL)
	{
		(void) SpinLockFree(&entry->mutex);
		hash_search(pgss_hash, &entry->tag, HASH_REMOVE, NULL);
	}

	pgss->num_statements = 0;
	chunk_reset();

	LWLockRelease(pgss->lock);
}

static Chunk *
chunk_alloc(void)
{
	Chunk *chunk;

	Assert(pgss->free_chunks != NULL);

	chunk = pgss->free_chunks;
	pgss->free_chunks = pgss->free_chunks->next;
	return chunk;
}

static void
chunk_free(Chunk *chunk)
{
	Assert(chunk != NULL);

	chunk->next = pgss->free_chunks;
	pgss->free_chunks = chunk;
}

static void
chunk_reset(void)
{
	Chunk  *chunk;
	Chunk  *next;
	int				i;

	chunk = pgss->free_chunks = pgss->chunks;
	for (i = 0; i < max_statements - 1; i++)
	{
		next = (Chunk *) ((char *)chunk + pgss->chunk_size);
		chunk->next = next;
		chunk = next;
	}
	chunk->next = NULL;
}

static bool
assign_max_statements(int newval, bool doit, GucSource source)
{
	if (!doit)
		return true;

	/* Emulate PGC_POSTMASTER; can be set only once. */
	if (max_statements == 0)
		return true;
	if (max_statements != newval)
	{
		ereport(GUC_complaint_elevel(source),
				(errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM),
				 errmsg("parameter \"%s\" cannot be changed after server start",
						GUCNAME("max_statements"))));
		return false;
	}
	return true;
}

static bool
assign_track_statements(bool newval, bool doit, GucSource source)
{
	/* Emulate PGC_SUSET */
	if (source >= PGC_S_CLIENT && !superuser())
	{
		ereport(GUC_complaint_elevel(source),
				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
				 errmsg("permission denied to set parameter \"%s\"",
						GUCNAME("track_statements"))));
		return false;
	}

	return true;
}

static const char *
assign_saved_file(const char *newval, bool doit, GucSource source)
{
	/* Emulate PGC_SIGHUP */
	if (saved_file != NULL && source >= PGC_S_DATABASE)
	{
		ereport(GUC_complaint_elevel(source),
				(errcode(ERRCODE_CANT_CHANGE_RUNTIME_PARAM),
				 errmsg("parameter \"%s\" cannot be changed now",
						GUCNAME("saved_file"))));
		return false;
	}

	if (doit)
	{
		char *canon_val = strdup(newval);
		if (canon_val == NULL)
			ereport(ERROR,
					(errcode(ERRCODE_OUT_OF_MEMORY),
					 errmsg("out of memory")));
		canonicalize_path(canon_val);
		return canon_val;
	}
	else
		return newval;
}