summaryrefslogtreecommitdiff
path: root/sql/txid/epoch.c
blob: a2cc28cd8243f09c07df968c1e7de9b1aa70fdcb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
/*-------------------------------------------------------------------------
 * epoch.c
 *
 *	Detect current epoch.
 *-------------------------------------------------------------------------
 */

#include "postgres.h"

#include <limits.h>

#include "access/transam.h"
#include "executor/spi.h"
#include "miscadmin.h"
#include "catalog/pg_control.h"
#include "access/xlog.h"

#include "txid.h"

/*
 * do a TransactionId -> txid conversion
 */
txid txid_convert_xid(TransactionId xid, TxidEpoch *state)
{
	uint64 epoch;

	/* avoid issues with the the special meaning of 0 */
	if (xid == InvalidTransactionId)
		return MAX_INT64;

	/* return special xid's as-is */
	if (xid < FirstNormalTransactionId)
		return xid;

	/* xid can on both sides on wrap-around */
	epoch = state->epoch;
	if (TransactionIdPrecedes(xid, state->last_value)) {
		if (xid > state->last_value)
			epoch--;
	} else if (TransactionIdFollows(xid, state->last_value)) {
		if (xid < state->last_value)
			epoch++;
	}
	return (epoch << 32) | xid;
}

#if PG_CONTROL_VERSION >= 820

/*
 * PostgreSQl 8.2 keeps track of epoch internally.
 */

void txid_load_epoch(TxidEpoch *state, int try_write)
{
	TransactionId	xid;
	uint32			epoch;

	GetNextXidAndEpoch(&xid, &epoch);

	state->epoch = epoch;
	state->last_value = xid;
}

#else

/*
 * For older PostgreSQL keep epoch in table.
 */

/*
 * this caches the txid_epoch table.
 * The struct should be updated only together with the table.
 */
static TxidEpoch epoch_state = { 0, 0 };

/*
 * load values from txid_epoch table.
 */
static int load_epoch(void)
{
	HeapTuple row;
	TupleDesc rdesc;
	bool isnull = false;
	Datum tmp;
	int res;
	uint64 db_epoch, db_value;

	res = SPI_connect();
	if (res < 0)
		elog(ERROR, "cannot connect to SPI");

	res = SPI_execute("select epoch, last_value from txid.epoch", true, 0);
	if (res != SPI_OK_SELECT)
		elog(ERROR, "load_epoch: select failed?");
	if (SPI_processed != 1)
		elog(ERROR, "load_epoch: there must be exactly 1 row");

	row = SPI_tuptable->vals[0];
	rdesc = SPI_tuptable->tupdesc;

	tmp = SPI_getbinval(row, rdesc, 1, &isnull);
	if (isnull)
		elog(ERROR, "load_epoch: epoch is NULL");
	db_epoch = DatumGetInt64(tmp);

	tmp = SPI_getbinval(row, rdesc, 2, &isnull);
	if (isnull)
		elog(ERROR, "load_epoch: last_value is NULL");
	db_value = DatumGetInt64(tmp);
	
	SPI_finish();

	/*
	 * If the db has lesser values, then some updates were lost.
	 *
	 * Should that be special-cased?  ATM just use db values.
	 * Thus immidiate update.
	 */
	epoch_state.epoch = db_epoch;
	epoch_state.last_value = db_value;
	return 1;
}

/*
 * updates last_value and epoch, if needed
 */
static void save_epoch(void)
{
	int res;
	char qbuf[200];
	uint64 new_epoch, new_value;
	TransactionId xid = GetTopTransactionId();
	TransactionId old_value;

	/* store old state */
	MemoryContext oldcontext = CurrentMemoryContext;
	ResourceOwner oldowner = CurrentResourceOwner;

	/*
	 * avoid changing internal values.
	 */
	new_value = xid;
	new_epoch = epoch_state.epoch;
	old_value = (TransactionId)epoch_state.last_value;
	if (xid < old_value) {
		if (TransactionIdFollows(xid, old_value))
			new_epoch++;
		else
			return;
	}
	sprintf(qbuf, "update txid.epoch set epoch = %llu, last_value = %llu",
				(unsigned long long)new_epoch,
				(unsigned long long)new_value);

	/*
	 * The update may fail in case of SERIALIZABLE transaction.
	 * Try to catch the error and hide it.
	 */
	BeginInternalSubTransaction(NULL);
	PG_TRY();
	{
		/* do the update */
		res = SPI_connect();
		if (res < 0)
			elog(ERROR, "cannot connect to SPI");
		res = SPI_execute(qbuf, false, 0);
		SPI_finish();

		ReleaseCurrentSubTransaction();
	}
	PG_CATCH();
	{
		/* we expect rollback to clean up inner SPI call */
		RollbackAndReleaseCurrentSubTransaction();
		FlushErrorState();
		res = -1;  /* remember failure */
	}
	PG_END_TRY();

	/* restore old state */
	MemoryContextSwitchTo(oldcontext);
	CurrentResourceOwner = oldowner;

	if (res < 0)
		return;

	/*
	 * Seems the update was successful, update internal state too.
	 *
	 * There is a chance that the TX will be rollbacked, but then
	 * another backend will do the update, or this one at next
	 * checkpoint.
	 */
	epoch_state.epoch = new_epoch;
	epoch_state.last_value = new_value;
}

static void check_epoch(int update_prio)
{
	TransactionId xid = GetTopTransactionId();
	TransactionId recheck, tx_next;
	int ok = 1;

	/* should not happen, but just in case */
	if (xid == InvalidTransactionId)
		return;

	/* new backend */
	if (epoch_state.last_value == 0)
		load_epoch();
	
	/* try to avoid concurrent access */
	if (update_prio)
		recheck = 50000 + 100 * (MyProcPid & 0x1FF);
	else
		recheck = 300000 + 1000 * (MyProcPid & 0x1FF);

	/* read table */
	tx_next = (TransactionId)epoch_state.last_value + recheck;
	if (TransactionIdFollows(xid, tx_next))
		ok = load_epoch();

	/*
	 * check if save is needed.  last_value may be updated above.
	 */
	tx_next = (TransactionId)epoch_state.last_value + recheck;
	if (!ok || TransactionIdFollows(xid, tx_next))
		save_epoch();
}

void txid_load_epoch(TxidEpoch *state, int try_write)
{
	check_epoch(try_write);

	state->epoch = epoch_state.epoch;
	state->last_value = epoch_state.last_value;
}


#endif