summaryrefslogtreecommitdiff
path: root/src/gtm/main/gtm_seq.c
blob: 2265c037ace89bbaab91598f3d1355cb93399f0a (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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
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
1332
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
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
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
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
/*-------------------------------------------------------------------------
 *
 * gtm_seq.c
 *	Sequence handling on GTM
 *
 * Portions Copyright (c) 2012-2014, TransLattice, Inc.
 * Portions Copyright (c) 1996-2009, PostgreSQL Global Development Group
 * Portions Copyright (c) 1994, Regents of the University of California
 * Portions Copyright (c) 2010-2012 Postgres-XC Development Group
 *
 *
 * IDENTIFICATION
 *	  $PostgreSQL$
 *
 *-------------------------------------------------------------------------
 */
#include <unistd.h>

#include "gtm/assert.h"
#include "gtm/elog.h"
#include "gtm/gtm.h"
#include "gtm/gtm_client.h"
#include "gtm/gtm_seq.h"
#include "gtm/gtm_serialize.h"
#include "gtm/gtm_standby.h"
#include "gtm/standby_utils.h"
#include "gtm/libpq.h"
#include "gtm/libpq-int.h"
#include "gtm/pqformat.h"
#include "gtm/gtm_backup.h"

extern bool Backup_synchronously;

typedef struct GTM_SeqInfoHashBucket
{
	gtm_List   *shb_list;
	GTM_RWLock	shb_lock;
} GTM_SeqInfoHashBucket;

typedef struct GTM_SeqAlteredInfo
{
	GTM_SequenceKey	curr_key;
	GTM_SequenceKey	prev_key;
} GTM_SeqAlteredInfo;
 
#define SEQ_HASH_TABLE_SIZE		1024
static GTM_SeqInfoHashBucket GTMSequences[SEQ_HASH_TABLE_SIZE];

static uint32 seq_gethash(GTM_SequenceKey key);
static bool seq_keys_equal(GTM_SequenceKey key1, GTM_SequenceKey key2);
static bool seq_key_dbname_equal(GTM_SequenceKey nsp, GTM_SequenceKey seq);
static GTM_SeqInfo *seq_find_seqinfo(GTM_SequenceKey seqkey);
static int seq_release_seqinfo(GTM_SeqInfo *seqinfo);
static int seq_add_seqinfo(GTM_SeqInfo *seqinfo);
static int seq_remove_seqinfo(GTM_SeqInfo *seqinfo);
static int seq_rename_seqinfo(GTM_SeqInfo *seqinfo, GTM_SequenceKey newkey);
static GTM_SequenceKey seq_copy_key_context(GTM_SequenceKey key,
		MemoryContext context);
static GTM_SequenceKey seq_copy_key(GTM_SequenceKey key);
static int seq_drop_with_dbkey(GTM_SequenceKey nsp);
static bool GTM_NeedSeqRestoreUpdateInternal(GTM_SeqInfo *seqinfo);

static GTM_Sequence get_rangemax(GTM_SeqInfo *seqinfo, GTM_Sequence range);

/*
 * Get the hash value given the sequence key
 *
 * XXX This should probably be replaced by a better hash function.
 */
static uint32
seq_gethash(GTM_SequenceKey key)
{
	uint32 total = 0;
	int ii;

	for (ii = 0; ii < key->gsk_keylen; ii++)
		total += key->gsk_key[ii];
	return (total % SEQ_HASH_TABLE_SIZE);
}

/*
 * Return true if both keys are equal, else return false
 */
static bool
seq_keys_equal(GTM_SequenceKey key1, GTM_SequenceKey key2)
{
	Assert(key1);
	Assert(key2);

	if (key1->gsk_keylen != key2->gsk_keylen) return false;

	return (memcmp(key1->gsk_key, key2->gsk_key,
				  Min(key1->gsk_keylen, key2->gsk_keylen)) == 0);
}

/*
 * Find the seqinfo structure for the given key. The reference count is
 * incremented before structure is returned. The caller must release the
 * reference to the structure when done with it
 */
static GTM_SeqInfo *
seq_find_seqinfo(GTM_SequenceKey seqkey)
{
	uint32 hash = seq_gethash(seqkey);
	GTM_SeqInfoHashBucket *bucket;
	gtm_ListCell *elem;
	GTM_SeqInfo *curr_seqinfo = NULL;

	bucket = &GTMSequences[hash];

	GTM_RWLockAcquire(&bucket->shb_lock, GTM_LOCKMODE_READ);

	gtm_foreach(elem, bucket->shb_list)
	{
		curr_seqinfo = (GTM_SeqInfo *) gtm_lfirst(elem);
		if (seq_keys_equal(curr_seqinfo->gs_key, seqkey))
			break;
		curr_seqinfo = NULL;
	}

	if (curr_seqinfo != NULL)
	{
		GTM_RWLockAcquire(&curr_seqinfo->gs_lock, GTM_LOCKMODE_WRITE);
		if (curr_seqinfo->gs_state != SEQ_STATE_ACTIVE)
		{
			elog(LOG, "Sequence not active");
			GTM_RWLockRelease(&curr_seqinfo->gs_lock);
			GTM_RWLockRelease(&bucket->shb_lock);
			return NULL;
		}
		Assert(curr_seqinfo->gs_ref_count != SEQ_MAX_REFCOUNT);
		curr_seqinfo->gs_ref_count++;
		GTM_RWLockRelease(&curr_seqinfo->gs_lock);
	}
	GTM_RWLockRelease(&bucket->shb_lock);

	return curr_seqinfo;
}

/*
 * Release previously grabbed reference to the structure. If the structure is
 * marked for deletion, it will be removed from the global array and released
 */
static int
seq_release_seqinfo(GTM_SeqInfo *seqinfo)
{
	bool remove = false;

	GTM_RWLockAcquire(&seqinfo->gs_lock, GTM_LOCKMODE_WRITE);
	Assert(seqinfo->gs_ref_count > 0);
	seqinfo->gs_ref_count--;

	if ((seqinfo->gs_state == SEQ_STATE_DELETED) &&
		(seqinfo->gs_ref_count == 0))
		remove = true;

	GTM_RWLockRelease(&seqinfo->gs_lock);
	/*
	 * Remove the structure from the global hash table
	 */
	if (remove) seq_remove_seqinfo(seqinfo);
	return 0;
}

/*
 * Add a seqinfo structure to the global hash table.
 */
static int
seq_add_seqinfo(GTM_SeqInfo *seqinfo)
{
	uint32 hash = seq_gethash(seqinfo->gs_key);
	GTM_SeqInfoHashBucket	*bucket;
	gtm_ListCell *elem;

	bucket = &GTMSequences[hash];

	GTM_RWLockAcquire(&bucket->shb_lock, GTM_LOCKMODE_WRITE);

	gtm_foreach(elem, bucket->shb_list)
	{
		GTM_SeqInfo *curr_seqinfo = NULL;
		curr_seqinfo = (GTM_SeqInfo *) gtm_lfirst(elem);

		if (seq_keys_equal(curr_seqinfo->gs_key, seqinfo->gs_key))
		{
			GTM_RWLockRelease(&bucket->shb_lock);
			ereport(LOG,
					(EEXIST,
					 errmsg("Sequence with the given key already exists")));
			return EEXIST;
		}
	}

	/*
	 * Safe to add the structure to the list
	 */
	bucket->shb_list = gtm_lappend(bucket->shb_list, seqinfo);
	GTM_RWLockRelease(&bucket->shb_lock);

	return 0;
}

/*
 * Remove the seqinfo structure from the global hash table. If the structure is
 * currently referenced by some other thread, just mark the structure for
 * deletion and it will be deleted by the final reference is released.
 */
static int
seq_remove_seqinfo(GTM_SeqInfo *seqinfo)
{
	uint32 hash = seq_gethash(seqinfo->gs_key);
	GTM_SeqInfoHashBucket	*bucket;

	bucket = &GTMSequences[hash];

	GTM_RWLockAcquire(&bucket->shb_lock, GTM_LOCKMODE_WRITE);
	GTM_RWLockAcquire(&seqinfo->gs_lock, GTM_LOCKMODE_WRITE);

	if (seqinfo->gs_ref_count > 1)
	{
		seqinfo->gs_state = SEQ_STATE_DELETED;
		GTM_RWLockRelease(&seqinfo->gs_lock);
		GTM_RWLockRelease(&bucket->shb_lock);
		return EBUSY;
	}

	bucket->shb_list = gtm_list_delete(bucket->shb_list, seqinfo);
	GTM_RWLockRelease(&seqinfo->gs_lock);
	GTM_RWLockRelease(&bucket->shb_lock);

	return 0;
}

/*
 * Rename sequence managed by seqinfo to "newkey".
 *
 * The sequence is moved to the new bucket and rest of the fields remain
 * unchanged.
 */
static int
seq_rename_seqinfo(GTM_SeqInfo *seqinfo, GTM_SequenceKey newkey)
{
	uint32 oldhash = seq_gethash(seqinfo->gs_key);
	uint32 newhash = seq_gethash(newkey);
	GTM_SeqInfoHashBucket	*oldbucket;
	GTM_SeqInfoHashBucket	*newbucket;
	gtm_ListCell *elem;
	MemoryContext oldContext;

	oldbucket = &GTMSequences[oldhash];
	newbucket = &GTMSequences[newhash];

	/*
	 * We must lock both old and new hash buckets. To avoid deadlock, we must
	 * ensure that we don't try to lock the same bucket twice (in case old and
	 * new keys are mapped to the same bucket) and also lock them in the same
	 * order.
	 */
	if (oldhash < newhash)
	{
		GTM_RWLockAcquire(&oldbucket->shb_lock, GTM_LOCKMODE_WRITE);
		GTM_RWLockAcquire(&newbucket->shb_lock, GTM_LOCKMODE_WRITE);
	}
	else if (oldhash > newhash)
	{
		GTM_RWLockAcquire(&newbucket->shb_lock, GTM_LOCKMODE_WRITE);
		GTM_RWLockAcquire(&oldbucket->shb_lock, GTM_LOCKMODE_WRITE);
	}
	else
		/* old and new buckets are just the same */
		GTM_RWLockAcquire(&newbucket->shb_lock, GTM_LOCKMODE_WRITE);

	GTM_RWLockAcquire(&seqinfo->gs_lock, GTM_LOCKMODE_WRITE);

	gtm_foreach(elem, newbucket->shb_list)
	{
		GTM_SeqInfo *curr_seqinfo = NULL;
		curr_seqinfo = (GTM_SeqInfo *) gtm_lfirst(elem);

		if (seq_keys_equal(curr_seqinfo->gs_key, newkey))
		{
			GTM_RWLockRelease(&seqinfo->gs_lock);
			GTM_RWLockRelease(&newbucket->shb_lock);
			/*
			 * Release oldbucket lock but only if its not same as the new
			 * bucket
			 * */
			if (oldhash != newhash)
				GTM_RWLockRelease(&oldbucket->shb_lock);
			ereport(LOG,
					(EEXIST,
					 errmsg("Sequence with the given key already exists")));
			return EEXIST;
		}
	}
	
	/*
	 * Must use TopMostMemoryContext since the hash bucket links can survive
	 * forever
	 */
	oldContext = MemoryContextSwitchTo(TopMostMemoryContext);
	seqinfo->gs_key = seq_copy_key(newkey);
	oldbucket->shb_list = gtm_list_delete(oldbucket->shb_list, seqinfo);
	newbucket->shb_list = gtm_lappend(newbucket->shb_list, seqinfo);
	MemoryContextSwitchTo(oldContext);

	GTM_RWLockRelease(&seqinfo->gs_lock);
	GTM_RWLockRelease(&newbucket->shb_lock);
	/* Release oldbucket lock but only if its not same as the new bucket */
	if (oldhash != newhash)
		GTM_RWLockRelease(&oldbucket->shb_lock);

	return 0;

}

/*
 * Same as seq_copy_key but use specified MemoryContext
 */
static GTM_SequenceKey
seq_copy_key_context(GTM_SequenceKey key, MemoryContext context)
{
	MemoryContext	oldContext;
	GTM_SequenceKey	newkey;

	oldContext = MemoryContextSwitchTo(TopMostMemoryContext);
	newkey = seq_copy_key(key);
	MemoryContextSwitchTo(oldContext);
	return newkey;
}

/*
 * Copy sequence key in the CurrentMemoryContext
 */
static GTM_SequenceKey
seq_copy_key(GTM_SequenceKey key)
{
	GTM_SequenceKey retkey = NULL;

	/*
	 * We must use the TopMostMemoryContext because the sequence information is
	 * not bound to a thread and can outlive any of the thread specific
	 * contextes.
	 */
	retkey = (GTM_SequenceKey) MemoryContextAlloc(TopMostMemoryContext,
												  sizeof(GTM_SequenceKeyData) +
														key->gsk_keylen);

	if (retkey == NULL)
		ereport(ERROR, (ENOMEM, errmsg("Out of memory")));

	retkey->gsk_keylen = key->gsk_keylen;
	retkey->gsk_key = (char *)((char *)retkey + sizeof (GTM_SequenceKeyData));

	memcpy(retkey->gsk_key, key->gsk_key, key->gsk_keylen);
	return retkey;
}

/*
 * Initialize a new sequence. Optionally set the initial value of the sequence.
 */
static int
GTM_SeqOpen(GTM_SequenceKey seqkey,
			GTM_Sequence increment_by,
			GTM_Sequence minval,
			GTM_Sequence maxval,
			GTM_Sequence startval,
			bool cycle,
			GlobalTransactionId gxid)
{
	GTM_SeqInfo *seqinfo = NULL;
	int errcode = 0;
	seqinfo = (GTM_SeqInfo *) palloc(sizeof (GTM_SeqInfo));

	if (seqinfo == NULL)
		ereport(ERROR, (ENOMEM, errmsg("Out of memory")));

	GTM_RWLockInit(&seqinfo->gs_lock);

	seqinfo->gs_ref_count = 0;
	seqinfo->gs_key = seq_copy_key(seqkey);
	seqinfo->gs_state = SEQ_STATE_ACTIVE;
	seqinfo->gs_called = false;
	seqinfo->gs_created_gxid = gxid;

	/*
	 * Set the increment. Default is 1
	 */
	if (SEQVAL_IS_VALID(increment_by))
		seqinfo->gs_increment_by = increment_by;
	else
		seqinfo->gs_increment_by = 1;

	/*
	 * If minval is specified, set the minvalue to the given minval,
	 * otherwise set to the defaults
	 */
	if (SEQVAL_IS_VALID(minval))
		seqinfo->gs_min_value = minval;
	else if (SEQ_IS_ASCENDING(seqinfo))
		seqinfo->gs_min_value = SEQ_DEF_MIN_SEQVAL_ASCEND;
	else
		seqinfo->gs_min_value = SEQ_DEF_MIN_SEQVAL_DESCEND;

	/*
	 * If maxval is specfied, set the maxvalue to the given maxval, otherwise
	 * set to the defaults depending on whether the seqeunce is ascending or
	 * descending. Also do some basic contraint checks
	 */
	if (SEQVAL_IS_VALID(maxval))
	{
		if (maxval < seqinfo->gs_min_value)
			ereport(ERROR,
					(ERANGE,
					 errmsg("Max value must be greater than min value")));
		seqinfo->gs_max_value = maxval;
	}
	else if (SEQ_IS_ASCENDING(seqinfo))
		seqinfo->gs_max_value = SEQ_DEF_MAX_SEQVAL_ASCEND;
	else
		seqinfo->gs_max_value = SEQ_DEF_MAX_SEQVAL_DESCEND;


	/*
	 * Set the startval if specified. Do some basic checks like startval must
	 * be in-between min and max values
	 */
	if (SEQVAL_IS_VALID(startval))
	{
		if (startval < seqinfo->gs_min_value)
			ereport(ERROR,
					(ERANGE,
					 errmsg("Start value must be greater than or equal to the min value")));

		if (startval > seqinfo->gs_max_value)
			ereport(ERROR,
					(ERANGE,
					 errmsg("Start value must be less than or equal to the max value")));

		seqinfo->gs_init_value = seqinfo->gs_value = startval;
	}
	else if (SEQ_IS_ASCENDING(seqinfo))
		seqinfo->gs_init_value = seqinfo->gs_value = SEQ_DEF_MIN_SEQVAL_ASCEND;
	else
		seqinfo->gs_init_value = seqinfo->gs_value = SEQ_DEF_MIN_SEQVAL_DESCEND;

	/*
	 * Should we wrap around ?
	 */
	seqinfo->gs_cycle = cycle;

	seqinfo->gs_max_lastvals = 0;
	seqinfo->gs_lastval_count = 0;
	seqinfo->gs_last_values = NULL;

	seqinfo->gs_backedUpValue = seqinfo->gs_value;

	if ((errcode = seq_add_seqinfo(seqinfo)))
	{
		GTM_RWLockDestroy(&seqinfo->gs_lock);
		pfree(seqinfo->gs_key);
		pfree(seqinfo);
	}
	else
	{
		seqinfo = seq_find_seqinfo(seqinfo->gs_key);
		GTM_RememberCreatedSequence(gxid, seq_copy_key_context(seqinfo->gs_key,
					TopMostMemoryContext));
	}

	GTM_SetNeedBackup();

	return errcode;
}

/*
 * Alter a sequence
 *
 * We don't track altered sequences because changes to sequence values are not
 * transactional and must not be rolled back if the transaction aborts.
 */
static int
GTM_SeqAlter(GTM_SequenceKey seqkey,
			 GTM_Sequence increment_by,
			 GTM_Sequence minval,
			 GTM_Sequence maxval,
			 GTM_Sequence startval,
			 GTM_Sequence lastval,
			 bool cycle,
			 bool is_restart)
{
	GTM_SeqInfo *seqinfo = seq_find_seqinfo(seqkey);

	if (seqinfo == NULL)
	{
		ereport(LOG,
				(EINVAL,
				 errmsg("The sequence with the given key does not exist")));
		return EINVAL;
	}

	GTM_RWLockAcquire(&seqinfo->gs_lock, GTM_LOCKMODE_WRITE);

	/* Modify the data if necessary */
	if (seqinfo->gs_cycle != cycle)
		seqinfo->gs_cycle = cycle;
	if (seqinfo->gs_min_value != minval)
		seqinfo->gs_min_value = minval;
	if (seqinfo->gs_max_value != maxval)
		seqinfo->gs_max_value = maxval;
	if (seqinfo->gs_increment_by != increment_by)
		seqinfo->gs_increment_by = increment_by;

	/*
	 * Check start/restart processes.
	 * Check first if restart is necessary and reset sequence in that case.
	 * If not, check if a simple start is necessary and update sequence.
	 */
	if (is_restart)
	{
		/* Restart command has been used, reset the sequence */
		seqinfo->gs_called = false;
		seqinfo->gs_value = lastval;
	}
	if (seqinfo->gs_init_value != startval)
		seqinfo->gs_init_value = startval;

	/* Remove the old key with the old name */
	GTM_RWLockRelease(&seqinfo->gs_lock);
	seq_release_seqinfo(seqinfo);
	return 0;
}

/*
 * Restore a sequence.
 */
int
GTM_SeqRestore(GTM_SequenceKey seqkey,
			   GTM_Sequence increment_by,
			   GTM_Sequence minval,
			   GTM_Sequence maxval,
			   GTM_Sequence startval,
			   GTM_Sequence curval,
			   int32 state,
			   bool cycle,
			   bool called)
{
	GTM_SeqInfo *seqinfo = NULL;
	int errcode = 0;
	seqinfo = (GTM_SeqInfo *) palloc(sizeof (GTM_SeqInfo));

	if (seqinfo == NULL)
		ereport(ERROR, (ENOMEM, errmsg("Out of memory")));

	GTM_RWLockInit(&seqinfo->gs_lock);

	seqinfo->gs_ref_count = 0;
	seqinfo->gs_key = seq_copy_key(seqkey);
	seqinfo->gs_state = state;
	seqinfo->gs_called = called;

	seqinfo->gs_increment_by = increment_by;
	seqinfo->gs_min_value = minval;
	seqinfo->gs_max_value = maxval;

	seqinfo->gs_init_value = startval;
	seqinfo->gs_max_lastvals = 0;
	seqinfo->gs_lastval_count = 0;
	seqinfo->gs_last_values = NULL;
	seqinfo->gs_value = curval;
	seqinfo->gs_backedUpValue = seqinfo->gs_value;

	/*
	 * Should we wrap around ?
	 */
	seqinfo->gs_cycle = cycle;

	if ((errcode = seq_add_seqinfo(seqinfo)))
	{
	 	GTM_RWLockDestroy(&seqinfo->gs_lock);
		pfree(seqinfo->gs_key);
		pfree(seqinfo);
	}
	return errcode;
}

/*
 * Destroy the given sequence depending on type of given key
 */
static int
GTM_SeqClose(GTM_SequenceKey seqkey, GlobalTransactionId gxid)
{
	int res;

	switch(seqkey->gsk_type)
	{
		case GTM_SEQ_FULL_NAME:
		{
			GTM_SeqInfo *seqinfo = seq_find_seqinfo(seqkey);
			/*
			 * If the sequence by created by the same transaction, then just
			 * drop it completely
			 */
			res = 0;
			if ((seqinfo != NULL) && (!GlobalTransactionIdIsValid(gxid) ||
				(seqinfo->gs_created_gxid == gxid)))
			{
				GTM_ForgetCreatedSequence(gxid, seqinfo);
				seq_release_seqinfo(seqinfo);
				if (!seq_remove_seqinfo(seqinfo))
				{
					pfree(seqinfo->gs_key);
					pfree(seqinfo);
				}
			}
			/*
			 * Otherwise we rename it to a special value so that it can be
			 * restored back if the transaction fails
			 */
			else if (seqinfo != NULL)
			{
				GTM_SequenceKeyData newkey;
				MemoryContext oldContext;

				newkey.gsk_key = (char *) palloc0(seqinfo->gs_key->gsk_keylen +
						strlen("__dropped_") + 11);
				sprintf(newkey.gsk_key, "%s_dropped_%d", seqinfo->gs_key->gsk_key,
						gxid);
				newkey.gsk_key[strlen(newkey.gsk_key)] = '\0';
				newkey.gsk_keylen = strlen(newkey.gsk_key) + 1;
				oldContext = MemoryContextSwitchTo(TopMostMemoryContext);
				seqinfo->gs_oldkey = seq_copy_key(seqinfo->gs_key);
				if ((res = seq_rename_seqinfo(seqinfo, &newkey)) == 0)
					GTM_RememberDroppedSequence(gxid,
							seq_copy_key_context(seqinfo->gs_key, TopMostMemoryContext));
				MemoryContextSwitchTo(oldContext);
				seq_release_seqinfo(seqinfo);
			}
			else if (seqinfo == NULL)
				res = EINVAL;

			break;
		}
		case GTM_SEQ_DB_NAME:
			res = seq_drop_with_dbkey(seqkey);
			break;

		default:
			res = EINVAL;
			break;
	}

	return res;
}

/* Check if sequence key contains only Database name */
static bool
seq_key_dbname_equal(GTM_SequenceKey nsp, GTM_SequenceKey seq)
{
	Assert(nsp);
	Assert(seq);

	/*
	 * Sequence key of GTM_SEQ_DB_NAME type has to be shorter
	 * than given sequence key.
	 */
	if(nsp->gsk_keylen >= seq->gsk_keylen)
		return false;

	/*
	 * Check also if first part of sequence key name has a dot at the right place.
	 * This accelerates process instead of making numerous memcmp.
	 */
	if (seq->gsk_key[nsp->gsk_keylen - 1] != '.')
		return false;

	/* Then Check the strings */
	return (memcmp(nsp->gsk_key, seq->gsk_key, nsp->gsk_keylen - 1) == 0);
}

/*
 * Remove all sequences with given key depending on its type.
 */
static int
seq_drop_with_dbkey(GTM_SequenceKey nsp)
{
	int ii = 0;
	GTM_SeqInfoHashBucket *bucket;
	gtm_ListCell *cell, *prev;
	GTM_SeqInfo *curr_seqinfo = NULL;
	int res = 0;
	bool deleted;

	for(ii = 0; ii < SEQ_HASH_TABLE_SIZE; ii++)
	{
		bucket = &GTMSequences[ii];

		GTM_RWLockAcquire(&bucket->shb_lock, GTM_LOCKMODE_READ);

		prev = NULL;
		cell = gtm_list_head(bucket->shb_list);
		while (cell != NULL)
		{
			curr_seqinfo = (GTM_SeqInfo *) gtm_lfirst(cell);
			deleted = false;

			if (seq_key_dbname_equal(nsp, curr_seqinfo->gs_key))
			{
				GTM_RWLockAcquire(&curr_seqinfo->gs_lock, GTM_LOCKMODE_WRITE);

				if (curr_seqinfo->gs_ref_count > 1)
				{
					curr_seqinfo->gs_state = SEQ_STATE_DELETED;

					/* can not happen, be checked before called */
					elog(LOG,"Sequence %s is in use, mark for deletion only",
							 curr_seqinfo->gs_key->gsk_key);

					/*
					 * Continue to delete other sequences linked to this dbname,
					 * sequences in use are deleted later.
					 */
					res = EBUSY;
				}
				else
				{
					/* Sequence is not is busy state, it can be deleted safely */

					bucket->shb_list = gtm_list_delete_cell(bucket->shb_list, cell, prev);
					elog(DEBUG1, "Sequence %s was deleted from GTM",
							  curr_seqinfo->gs_key->gsk_key);

					deleted = true;
				}
				GTM_RWLockRelease(&curr_seqinfo->gs_lock);
			}
			if (deleted)
			{
				if (prev)
					cell = gtm_lnext(prev);
				else
					cell = gtm_list_head(bucket->shb_list);
			}
			else
			{
				prev = cell;
				cell = gtm_lnext(cell);
			}
		}
		GTM_RWLockRelease(&bucket->shb_lock);
	}

	return res;
}
/*
 * Rename an existing sequence with a new name
 */
static int
GTM_SeqRename(GTM_SequenceKey seqkey, GTM_SequenceKey newseqkey,
		GlobalTransactionId gxid)
{
	GTM_SeqInfo *seqinfo = seq_find_seqinfo(seqkey);
	int errcode = 0;
	MemoryContext oldContext;
	GTM_SeqAlteredInfo *alterinfo;

	/* replace old key by new key */
	if (seqinfo == NULL)
	{
		ereport(LOG,
				(EINVAL,
				 errmsg("The sequence with the given key does not exist")));
		return EINVAL;
	}

	oldContext = MemoryContextSwitchTo(TopMostMemoryContext);
	alterinfo = (GTM_SeqAlteredInfo *) palloc0(sizeof (GTM_SeqAlteredInfo));

	alterinfo->curr_key = seq_copy_key(newseqkey);
	alterinfo->prev_key = seq_copy_key(seqinfo->gs_key);
	MemoryContextSwitchTo(oldContext);

	errcode = seq_rename_seqinfo(seqinfo, newseqkey);
	if (!errcode)
		GTM_RememberAlteredSequence(gxid, alterinfo);
	seq_release_seqinfo(seqinfo);
	return errcode;
}

/*
 * Get current value for the sequence without incrementing it
 */
static void
GTM_SeqGetCurrent(GTM_SequenceKey seqkey, char *coord_name,
				  int coord_procid, GTM_Sequence *result)
{
	GTM_SeqInfo *seqinfo = seq_find_seqinfo(seqkey);
	int			i;
	bool		found = false;

	elog(DEBUG1, "Look up last value of Sequence %s in session %s:%d",
			seqkey->gsk_key, coord_name, coord_procid);

	if (seqinfo == NULL)
	{
		ereport(ERROR,
				(EINVAL,
				 errmsg("sequence \"%s\" does not exist", seqkey->gsk_key)));
		return;
	}

	GTM_RWLockAcquire(&seqinfo->gs_lock, GTM_LOCKMODE_READ);

	for (i = 0; i < seqinfo->gs_lastval_count; i++)
	{
		if (strcmp(seqinfo->gs_last_values[i].gs_coord_name, coord_name) == 0 &&
				seqinfo->gs_last_values[i].gs_coord_procid == coord_procid)
		{
			*result = seqinfo->gs_last_values[i].gs_last_value;
			found = true;
			break;
		}
	}

	GTM_RWLockRelease(&seqinfo->gs_lock);
	seq_release_seqinfo(seqinfo);
	if (!found)
		ereport(ERROR,
				(ERANGE,
				 errmsg("currval of sequence \"%s\" is not yet defined in this session",
						seqkey->gsk_key)));

}


/*
 * Store the sequence value as last for the specified distributed session
 */
static void
seq_set_lastval(GTM_SeqInfo *seqinfo, char *coord_name,
				int coord_procid, GTM_Sequence newval)
{
	GTM_SeqLastVal *lastval;
	int			i;

	/* Can not assign value to not defined value */
	if (coord_name == NULL || coord_procid == 0)
		return;

	elog(DEBUG1, "Remember last value of Sequence %s in session %s:%d",
			seqinfo->gs_key->gsk_key, coord_name, coord_procid);

	/*
	 * If last value is already defined for the session update it
	 */
	for (i = 0; i < seqinfo->gs_lastval_count; i++)
	{
		if (strcmp(seqinfo->gs_last_values[i].gs_coord_name, coord_name) == 0 &&
				seqinfo->gs_last_values[i].gs_coord_procid == coord_procid)
		{
			seqinfo->gs_last_values[i].gs_last_value = newval;
			return;
		}
	}

	/* Not found, add new entry for the distributed session */
	if (seqinfo->gs_lastval_count == seqinfo->gs_max_lastvals)
	{
		/* Need more room */
#define INIT_LASTVALS 16

		if (seqinfo->gs_max_lastvals == 0)
		{
			/* No values at all, palloc memory block */
			MemoryContext oldContext;
			oldContext = MemoryContextSwitchTo(TopMostMemoryContext);
			seqinfo->gs_last_values = (GTM_SeqLastVal *)
					palloc(INIT_LASTVALS * sizeof(GTM_SeqLastVal));
			seqinfo->gs_max_lastvals = INIT_LASTVALS;
			MemoryContextSwitchTo(oldContext);
		}
		else
		{
			/* Increase existing array */
			int newsize = seqinfo->gs_max_lastvals * 2;
			seqinfo->gs_last_values = (GTM_SeqLastVal *)
					repalloc(seqinfo->gs_last_values,
							 newsize * sizeof(GTM_SeqLastVal));
			seqinfo->gs_max_lastvals = newsize;
		}
	}

	/* Populate new entry */
	lastval = &seqinfo->gs_last_values[seqinfo->gs_lastval_count++];
	memcpy(lastval->gs_coord_name, coord_name, strlen(coord_name) + 1);
	lastval->gs_coord_procid = coord_procid;
	lastval->gs_last_value = newval;
}


/*
 * Set values for the sequence
 */
static int
GTM_SeqSetVal(GTM_SequenceKey seqkey, char *coord_name,
			  int coord_procid, GTM_Sequence nextval, bool iscalled)
{
	GTM_SeqInfo *seqinfo = seq_find_seqinfo(seqkey);

	if (seqinfo == NULL)
	{
		ereport(LOG,
				(EINVAL,
				 errmsg("The sequence with the given key does not exist")));

		return EINVAL;
	}

	GTM_RWLockAcquire(&seqinfo->gs_lock, GTM_LOCKMODE_WRITE);

	seqinfo->gs_value = nextval;
	seqinfo->gs_called = iscalled;

	/* If sequence is not called, update last value for the session */
	if (!iscalled)
		seq_set_lastval(seqinfo, coord_name, coord_procid, nextval);

	/* Remove the old key with the old name */
	GTM_RWLockRelease(&seqinfo->gs_lock);
	seq_release_seqinfo(seqinfo);

	return 0;
}

/*
 * Get next value for the sequence
 */
static int
GTM_SeqGetNext(GTM_SequenceKey seqkey, char *coord_name,
			   int coord_procid, GTM_Sequence range,
			   GTM_Sequence *result, GTM_Sequence *rangemax)
{
	GTM_SeqInfo *seqinfo = seq_find_seqinfo(seqkey);

	if (seqinfo == NULL)
	{
		ereport(LOG,
				(EINVAL,
				 errmsg("The sequence with the given key does not exist")));
		return EINVAL;
	}

	GTM_RWLockAcquire(&seqinfo->gs_lock, GTM_LOCKMODE_WRITE);

	/*
	 * If the sequence is called for the first time return the current value.
	 * It should be already initialized.
	 */
	if (!SEQ_IS_CALLED(seqinfo))
	{
		*result = seqinfo->gs_value;
		seqinfo->gs_called = true;
	}
	else
	{
		if (SEQ_IS_ASCENDING(seqinfo))
		{
			/*
			 * Check if the sequence is about to wrap-around. If the sequence
			 * does not support wrap-around, throw an error.
			 * Beware overflow!
			 */
			if (seqinfo->gs_max_value - seqinfo->gs_increment_by
					>= seqinfo->gs_value)
			{
				GTM_Sequence newval = seqinfo->gs_value + seqinfo->gs_increment_by;
				*result = seqinfo->gs_value = newval;
			}
			else if (SEQ_IS_CYCLE(seqinfo))
				*result = seqinfo->gs_value = seqinfo->gs_min_value;
			else
			{
				GTM_RWLockRelease(&seqinfo->gs_lock);
				seq_release_seqinfo(seqinfo);
				ereport(LOG,
						(ERANGE,
						 errmsg("Sequence reached maximum value")));
				return ERANGE;
			}
		}
		else
		{
			/*
			 * Check if the sequence is about to wrap-around. If the sequence
			 * does not support wrap-around, throw an error.
			 * Beware overflow!
			 *
			 * Note: The gs_increment_by is a signed integer and is negative for
			 * descending sequences. So we don't need special handling below
			 */
			if (seqinfo->gs_min_value - seqinfo->gs_increment_by
					<= seqinfo->gs_value)
			{
				GTM_Sequence newval = seqinfo->gs_value + seqinfo->gs_increment_by;
				*result = seqinfo->gs_value = newval;
			}
			else if (SEQ_IS_CYCLE(seqinfo))
				*result = seqinfo->gs_value = seqinfo->gs_max_value;
			else
			{
				GTM_RWLockRelease(&seqinfo->gs_lock);
				seq_release_seqinfo(seqinfo);
				ereport(LOG,
						(ERANGE,
						 errmsg("Sequence reached maximum value")));
				return ERANGE;
			}
		}
	}
	/* if range is specified calculate valid max value for this range */
	if (range > 1)
		*rangemax = get_rangemax(seqinfo, range);
	else
		*rangemax = *result;
	/*
	 * lastval has to be set to rangemax obtained above because
	 * values upto it will be consumed by this nextval caller and
	 * the next caller should get values starting above this
	 * lastval. Same reasoning for gs_value, but we still return
	 * result as the first calculated gs_value above to form the
	 * local starting seed at the caller. This will go upto the
	 * rangemax value before contacting GTM again..
	 */
	seq_set_lastval(seqinfo, coord_name, coord_procid, *rangemax);
	seqinfo->gs_value = *rangemax;
	GTM_RWLockRelease(&seqinfo->gs_lock);
	seq_release_seqinfo(seqinfo);
	return 0;
}

/*
 * Given a sequence and the requested range for its values, calculate
 * the legitimate maximum permissible value for this range. In
 * particular we need to be careful about overflow and underflow for
 * mix and max types of sequences..
 */
static GTM_Sequence
get_rangemax(GTM_SeqInfo *seqinfo, GTM_Sequence range)
{
	GTM_Sequence rangemax = seqinfo->gs_value;

	/*
	 * Deduct 1 from range because the currval has been accounted
	 * for already before this call has been made
	 */
	range--;
	if (SEQ_IS_ASCENDING(seqinfo))
	{
		/*
		 * Check if the sequence will overflow because of the range
		 * request. If yes, cap it at close to or equal to max value
		 */
		while (range != 0 &&
				(seqinfo->gs_max_value - seqinfo->gs_increment_by >=
				  rangemax))
		{
			rangemax += seqinfo->gs_increment_by;
			range--;
		}
	}
	else
	{
		/*
		 * Check if the sequence will underflow because of the range
		 * request. If yes, cap it at close to or equal to min value
		 *
		 * Note: The gs_increment_by is a signed integer and is negative for
		 * descending sequences. So we don't need special handling below
		 */
		while (range != 0 &&
				(seqinfo->gs_min_value - seqinfo->gs_increment_by <=
				 rangemax))
		{
			rangemax += seqinfo->gs_increment_by;
			range--;
		}
	}
	return rangemax;
}

/*
 * Reset the sequence
 */
static int
GTM_SeqReset(GTM_SequenceKey seqkey)
{
	GTM_SeqInfo *seqinfo = seq_find_seqinfo(seqkey);

	if (seqinfo == NULL)
	{
		ereport(LOG,
				(EINVAL,
				 errmsg("The sequence with the given key does not exist")));
		return EINVAL;
	}

	GTM_RWLockAcquire(&seqinfo->gs_lock, GTM_LOCKMODE_WRITE);
	seqinfo->gs_value = seqinfo->gs_backedUpValue = seqinfo->gs_init_value;

	GTM_RWLockRelease(&gtm_bkup_lock);

	GTM_SetNeedBackup();
	seq_release_seqinfo(seqinfo);
	return 0;
}

void
GTM_InitSeqManager(void)
{
	int ii;

	for (ii = 0; ii < SEQ_HASH_TABLE_SIZE; ii++)
	{
		GTMSequences[ii].shb_list = gtm_NIL;
		GTM_RWLockInit(&GTMSequences[ii].shb_lock);
	}
}

/*
 * Process MSG_SEQUENCE_INIT/MSG_BKUP_SEQUENCE_INIT message
 *
 * is_backup indicates the message is MSG_BKUP_SEQUENCE_INIT
 */
void
ProcessSequenceInitCommand(Port *myport, StringInfo message, bool is_backup)
{
	GTM_SequenceKeyData seqkey;
	GTM_Sequence increment, minval, maxval, startval;
	bool cycle;
	StringInfoData buf;
	int errcode;
	MemoryContext oldContext;
    const char *data;
	GlobalTransactionId gxid;

	/*
	 * Get the sequence key
	 */
	seqkey.gsk_keylen = pq_getmsgint(message, sizeof (seqkey.gsk_keylen));
	seqkey.gsk_key = (char *)pq_getmsgbytes(message, seqkey.gsk_keylen);

	/*
	 * Read various sequence parameters
	 */
	memcpy(&increment, pq_getmsgbytes(message, sizeof (GTM_Sequence)),
		   sizeof (GTM_Sequence));
	memcpy(&minval, pq_getmsgbytes(message, sizeof (GTM_Sequence)),
		   sizeof (GTM_Sequence));
	memcpy(&maxval, pq_getmsgbytes(message, sizeof (GTM_Sequence)),
		   sizeof (GTM_Sequence));
	memcpy(&startval, pq_getmsgbytes(message, sizeof (GTM_Sequence)),
		   sizeof (GTM_Sequence));

	cycle = pq_getmsgbyte(message);

	data = pq_getmsgbytes(message, sizeof (gxid));
	if (data == NULL)
		ereport(ERROR,
				(EPROTO,
				 errmsg("Message does not contain valid GXID")));
	memcpy(&gxid, data, sizeof (gxid));


	/*
	 * We must use the TopMostMemoryContext because the sequence information is
	 * not bound to a thread and can outlive any of the thread specific
	 * contextes.
	 */
	oldContext = MemoryContextSwitchTo(TopMostMemoryContext);

	if ((errcode = GTM_SeqOpen(&seqkey, increment, minval, maxval, startval,
					cycle, gxid)))
		ereport(ERROR,
				(errcode,
				 errmsg("Failed to open a new sequence")));

	MemoryContextSwitchTo(oldContext);

	elog(DEBUG1, "Opening sequence %s", seqkey.gsk_key);

	pq_getmsgend(message);

	if (!is_backup)
	{
		/* Backup first */
		if (GetMyThreadInfo->thr_conn->standby)
		{
			int rc;
			GTM_Conn *oldconn = GetMyThreadInfo->thr_conn->standby;
			int count = 0;

			elog(DEBUG1, "calling open_sequence() for standby GTM %p.", GetMyThreadInfo->thr_conn->standby);

		retry:
			rc = bkup_open_sequence(GetMyThreadInfo->thr_conn->standby,
									&seqkey,
									increment,
									minval,
									maxval,
									startval,
									cycle,
									gxid);

			if (gtm_standby_check_communication_error(&count, oldconn))
				goto retry;

			/* Sync */
			if (Backup_synchronously && (myport->remote_type != GTM_NODE_GTM_PROXY))
				gtm_sync_standby(GetMyThreadInfo->thr_conn->standby);

			elog(DEBUG1, "open_sequence() returns rc %d.", rc);
		}
		/* Save control file with new seq info */
        SaveControlInfo();
		/*
		 * Send a SUCCESS message back to the client
		 */
		pq_beginmessage(&buf, 'S');
		pq_sendint(&buf, SEQUENCE_INIT_RESULT, 4);
		if (myport->remote_type == GTM_NODE_GTM_PROXY)
		{
			GTM_ProxyMsgHeader proxyhdr;
			proxyhdr.ph_conid = myport->conn_id;
			pq_sendbytes(&buf, (char *)&proxyhdr, sizeof (GTM_ProxyMsgHeader));
		}
		pq_sendint(&buf, seqkey.gsk_keylen, 4);
		pq_sendbytes(&buf, seqkey.gsk_key, seqkey.gsk_keylen);
		pq_endmessage(myport, &buf);

		if (myport->remote_type != GTM_NODE_GTM_PROXY)
		{
			/* Flush standby first */
			if (GetMyThreadInfo->thr_conn->standby)
				gtmpqFlush(GetMyThreadInfo->thr_conn->standby);
			pq_flush(myport);
		}
	}
	/* FIXME: need to check errors */
}


/*
 * Process MSG_SEQUENCE_ALTER/MSG_BKUP_SEQUENCE_ALTER message
 *
 * is_backup indicates the message is MSG_BKUP_SEQUENCE_ALTER
 */
void
ProcessSequenceAlterCommand(Port *myport, StringInfo message, bool is_backup)
{
	GTM_SequenceKeyData seqkey;
	GTM_Sequence increment, minval, maxval, startval, lastval;
	bool cycle, is_restart;
	StringInfoData buf;
	int errcode;
	MemoryContext oldContext;

	/*
	 * Get the sequence key
	 */
	seqkey.gsk_keylen = pq_getmsgint(message, sizeof (seqkey.gsk_keylen));
	seqkey.gsk_key = (char *)pq_getmsgbytes(message, seqkey.gsk_keylen);

	/*
	 * Read various sequence parameters
	 */
	memcpy(&increment, pq_getmsgbytes(message, sizeof (GTM_Sequence)),
		sizeof (GTM_Sequence));
	memcpy(&minval, pq_getmsgbytes(message, sizeof (GTM_Sequence)),
		sizeof (GTM_Sequence));
	memcpy(&maxval, pq_getmsgbytes(message, sizeof (GTM_Sequence)),
		sizeof (GTM_Sequence));
	memcpy(&startval, pq_getmsgbytes(message, sizeof (GTM_Sequence)),
		sizeof (GTM_Sequence));
	memcpy(&lastval, pq_getmsgbytes(message, sizeof (GTM_Sequence)),
		sizeof (GTM_Sequence));

	cycle = pq_getmsgbyte(message);
	is_restart = pq_getmsgbyte(message);

	/*
	 * We must use the TopMostMemoryContext because the sequence information is
	 * not bound to a thread and can outlive any of the thread specific
	 * contextes.
	 */
	oldContext = MemoryContextSwitchTo(TopMostMemoryContext);

	elog(DEBUG1, "Altering sequence key %s", seqkey.gsk_key);

	if ((errcode = GTM_SeqAlter(&seqkey, increment, minval, maxval, startval,
					lastval, cycle, is_restart)))
		ereport(ERROR,
				(errcode,
				 errmsg("Failed to open a new sequence")));

	MemoryContextSwitchTo(oldContext);

	pq_getmsgend(message);

	if (!is_backup)
	{
		/* Backup first */
		if ( GetMyThreadInfo->thr_conn->standby )
		{
			int rc;
			GTM_Conn *oldconn = GetMyThreadInfo->thr_conn->standby;
			int count = 0;

			elog(DEBUG1, "calling alter_sequence() for standby GTM %p.", GetMyThreadInfo->thr_conn->standby);

		retry:
			rc = bkup_alter_sequence(GetMyThreadInfo->thr_conn->standby,
									 &seqkey,
									 increment,
									 minval,
									 maxval,
									 startval,
									 lastval,
									 cycle,
									 is_restart);

			if (gtm_standby_check_communication_error(&count, oldconn))
				goto retry;

			/* Sync */
			if (Backup_synchronously && (myport->remote_type != GTM_NODE_GTM_PROXY))
				gtm_sync_standby(GetMyThreadInfo->thr_conn->standby);

			elog(DEBUG1, "alter_sequence() returns rc %d.", rc);
		}
		/* Save control file info */
        SaveControlInfo();

		pq_beginmessage(&buf, 'S');
		pq_sendint(&buf, SEQUENCE_ALTER_RESULT, 4);
		if (myport->remote_type == GTM_NODE_GTM_PROXY)
		{
			GTM_ProxyMsgHeader proxyhdr;
			proxyhdr.ph_conid = myport->conn_id;
			pq_sendbytes(&buf, (char *)&proxyhdr, sizeof (GTM_ProxyMsgHeader));
		}
		pq_sendint(&buf, seqkey.gsk_keylen, 4);
		pq_sendbytes(&buf, seqkey.gsk_key, seqkey.gsk_keylen);
		pq_endmessage(myport, &buf);

		if (myport->remote_type != GTM_NODE_GTM_PROXY)
		{
			if (GetMyThreadInfo->thr_conn->standby)
				gtmpqFlush(GetMyThreadInfo->thr_conn->standby);
			pq_flush(myport);
		}

		/* FIXME: need to check errors */
	}
}


/*
 * Process MSG_SEQUENCE_LIST message
 */
void
ProcessSequenceListCommand(Port *myport, StringInfo message)
{
	StringInfoData buf;
	int seq_count;
	int seq_maxcount;
	GTM_SeqInfo **seq_list;
	int i;

	if (Recovery_IsStandby())
		ereport(ERROR,
			(EPERM,
			 errmsg("Operation not permitted under the standby mode.")));

	seq_count = 0;
	seq_maxcount = 1024;
	seq_list = (GTM_SeqInfo **) palloc(seq_maxcount * sizeof(GTM_SeqInfo *));;

	/*
	 * Store pointers to all GTM_SeqInfo in the hash buckets into an array.
	 */
	for (i = 0 ; i < SEQ_HASH_TABLE_SIZE ; i++)
	{
		GTM_SeqInfoHashBucket *b;
		gtm_ListCell *elem;

		b = &GTMSequences[i];

		GTM_RWLockAcquire(&b->shb_lock, GTM_LOCKMODE_READ);

		gtm_foreach(elem, b->shb_list)
		{
			/* Allocate larger array if required */
			if (seq_count == seq_maxcount)
			{
				int 			newcount;
				GTM_SeqInfo   **newlist;

				newcount = 2 * seq_maxcount;
				newlist = (GTM_SeqInfo **) repalloc(seq_list, newcount * sizeof(GTM_SeqInfo *));
				/*
				 * If failed try to get less. It is unlikely to happen, but
				 * let's be safe.
				 */
				while (newlist == NULL)
				{
					newcount = seq_maxcount + (newcount - seq_maxcount) / 2 - 1;
					if (newcount <= seq_maxcount)
					{
						/* give up */
						GTM_RWLockRelease(&b->shb_lock);
						ereport(ERROR,
								(ERANGE,
								 errmsg("Can not list all the sequences")));
					}
					newlist = (GTM_SeqInfo **) repalloc(seq_list, newcount * sizeof(GTM_SeqInfo *));
				}
				seq_maxcount = newcount;
				seq_list = newlist;
			}
			seq_list[seq_count] = (GTM_SeqInfo *) gtm_lfirst(elem);
			seq_count++;
		}

		GTM_RWLockRelease(&b->shb_lock);
	}

	pq_getmsgend(message);

	pq_beginmessage(&buf, 'S');
	pq_sendint(&buf, SEQUENCE_LIST_RESULT, 4);

	if (myport->remote_type == GTM_NODE_GTM_PROXY)
	{
		GTM_ProxyMsgHeader proxyhdr;
		proxyhdr.ph_conid = myport->conn_id;
		pq_sendbytes(&buf, (char *)&proxyhdr, sizeof (GTM_ProxyMsgHeader));
	}

	/* Send a number of sequences */
	pq_sendint(&buf, seq_count, 4);

	/*
	 * Send sequences from the array
	 */
	{
		/*
		 * TODO set initial size big enough to fit any sequence, and avoid
		 * reallocations.
		 */
		size_t seq_maxlen = 256;
		char *seq_buf = (char *) palloc(seq_maxlen);

		for (i = 0 ; i < seq_count ; i++)
		{
			size_t seq_buflen = gtm_get_sequence_size(seq_list[i]);
			if (seq_buflen > seq_maxlen)
			{
				seq_maxlen = seq_buflen;
				seq_buf = (char *)repalloc(seq_buf, seq_maxlen);
			}

			gtm_serialize_sequence(seq_list[i], seq_buf, seq_buflen);

			elog(DEBUG1, "seq_buflen = %ld", seq_buflen);

			pq_sendint(&buf, seq_buflen, 4);
			pq_sendbytes(&buf, seq_buf, seq_buflen);
		}
	}

	pq_endmessage(myport, &buf);

	elog(DEBUG1, "ProcessSequenceListCommand() done.");

	if (myport->remote_type != GTM_NODE_GTM_PROXY)
		/* Don't flush to the backup because this does not change the internal status */
		pq_flush(myport);
}


/*
 * Process MSG_SEQUENCE_GET_CURRENT message
 */
void
ProcessSequenceGetCurrentCommand(Port *myport, StringInfo message)
{
	GTM_SequenceKeyData seqkey;
	StringInfoData buf;
	GTM_Sequence seqval;
	uint32 coord_namelen;
	char  *coord_name;
	uint32 coord_procid;

	seqkey.gsk_keylen = pq_getmsgint(message, sizeof (seqkey.gsk_keylen));
	seqkey.gsk_key = (char *)pq_getmsgbytes(message, seqkey.gsk_keylen);

	coord_namelen = pq_getmsgint(message, sizeof(coord_namelen));
	if (coord_namelen > 0)
		coord_name = (char *)pq_getmsgbytes(message, coord_namelen);
	else
		coord_name = NULL;
	coord_procid = pq_getmsgint(message, sizeof(coord_procid));

	GTM_SeqGetCurrent(&seqkey, coord_name, coord_procid, &seqval);

	elog(DEBUG1, "Getting current value %ld for sequence %s", seqval, seqkey.gsk_key);

	pq_beginmessage(&buf, 'S');
	pq_sendint(&buf, SEQUENCE_GET_CURRENT_RESULT, 4);
	if (myport->remote_type == GTM_NODE_GTM_PROXY)
	{
		GTM_ProxyMsgHeader proxyhdr;
		proxyhdr.ph_conid = myport->conn_id;
		pq_sendbytes(&buf, (char *)&proxyhdr, sizeof (GTM_ProxyMsgHeader));
	}
	pq_sendint(&buf, seqkey.gsk_keylen, 4);
	pq_sendbytes(&buf, seqkey.gsk_key, seqkey.gsk_keylen);
	pq_sendbytes(&buf, (char *)&seqval, sizeof (GTM_Sequence));
	pq_endmessage(myport, &buf);

	if (myport->remote_type != GTM_NODE_GTM_PROXY)
		/* Don't flush to the standby because this does not change the status */
		pq_flush(myport);

	/*
	 * I don't think backup is needed here. It does not change internal state.
	 * 27th Dec., 2011, K.Suzuki
	 */
#if 0
	if (GetMyThreadInfo->thr_conn->standby)
	{
		GTM_Sequence loc_seq;
		GTM_Conn *oldconn = GetMyThreadInfo->thr_conn->standby;
		int count = 0;

		elog(DEBUG1, "calling get_current() for standby GTM %p.", GetMyThreadInfo->thr_conn->standby);

retry:
		loc_seq = get_current(GetMyThreadInfo->thr_conn->standby, &seqkey);

		if (gtm_standby_check_communication_error(&count, oldconn))
			goto retry;

		elog(DEBUG1, "get_current() returns GTM_Sequence %ld.", loc_seq);
	}
#endif

	/* FIXME: need to check errors */
}

/*
 * Process MSG_SEQUENCE_GET_NEXT/MSG_BKUP_SEQUENCE_GET_NEXT message
 *
 * is_backup indicates the message is MSG_BKUP_SEQUENCE_GET_NEXT
 */
void
ProcessSequenceGetNextCommand(Port *myport, StringInfo message, bool is_backup)
{
	GTM_SequenceKeyData seqkey;
	StringInfoData buf;
	GTM_Sequence seqval;
	GTM_Sequence range;
	GTM_Sequence rangemax;
	uint32 coord_namelen;
	char  *coord_name;
	uint32 coord_procid;

	seqkey.gsk_keylen = pq_getmsgint(message, sizeof (seqkey.gsk_keylen));
	seqkey.gsk_key = (char *)pq_getmsgbytes(message, seqkey.gsk_keylen);

	coord_namelen = pq_getmsgint(message, sizeof(coord_namelen));
	if (coord_namelen > 0)
		coord_name = (char *)pq_getmsgbytes(message, coord_namelen);
	else
		coord_name = NULL;
	coord_procid = pq_getmsgint(message, sizeof(coord_procid));
	memcpy(&range, pq_getmsgbytes(message, sizeof (GTM_Sequence)),
		   sizeof (GTM_Sequence));

	if (GTM_SeqGetNext(&seqkey, coord_name, coord_procid, range,
					&seqval, &rangemax))
		ereport(ERROR,
				(ERANGE,
				 errmsg("Can not get current value of the sequence")));

	elog(DEBUG1, "Getting next value %ld for sequence %s", seqval, seqkey.gsk_key);

	if (!is_backup)
	{
		/* Backup first */
		if (GetMyThreadInfo->thr_conn->standby)
		{
			GTM_Sequence loc_seq;
			GTM_Conn *oldconn = GetMyThreadInfo->thr_conn->standby;
			int count = 0;

			elog(DEBUG1, "calling get_next() for standby GTM %p.", GetMyThreadInfo->thr_conn->standby);

		retry:
			bkup_get_next(GetMyThreadInfo->thr_conn->standby, &seqkey,
						  coord_name, coord_procid,
						  range, &loc_seq, &rangemax);

			if (gtm_standby_check_communication_error(&count, oldconn))
				goto retry;

			/* Sync */
			if (Backup_synchronously &&(myport->remote_type != GTM_NODE_GTM_PROXY))
				gtm_sync_standby(GetMyThreadInfo->thr_conn->standby);

			elog(DEBUG1, "get_next() returns GTM_Sequence %ld.", loc_seq);
		}
		/* Save control file info */
        SaveControlInfo();

		/* Respond to the client */
		pq_beginmessage(&buf, 'S');
		pq_sendint(&buf, SEQUENCE_GET_NEXT_RESULT, 4);
		if (myport->remote_type == GTM_NODE_GTM_PROXY)
		{
			GTM_ProxyMsgHeader proxyhdr;
			proxyhdr.ph_conid = myport->conn_id;
			pq_sendbytes(&buf, (char *)&proxyhdr, sizeof (GTM_ProxyMsgHeader));
		}
		pq_sendint(&buf, seqkey.gsk_keylen, 4);
		pq_sendbytes(&buf, seqkey.gsk_key, seqkey.gsk_keylen);
		pq_sendbytes(&buf, (char *)&seqval, sizeof (GTM_Sequence));
		pq_sendbytes(&buf, (char *)&rangemax, sizeof (GTM_Sequence));
		pq_endmessage(myport, &buf);

		if (myport->remote_type != GTM_NODE_GTM_PROXY)
		{
			/* Flush to the standby first */
			if (GetMyThreadInfo->thr_conn->standby)
				gtmpqFlush(GetMyThreadInfo->thr_conn->standby);
			pq_flush(myport);
		}

		/* FIXME: need to check errors */
	}
}

/*
 * Process MSG_SEQUENCE_SET_VAL/MSG_BKUP_SEQUENCE_SET_VAL message
 *
 * is_backup indicates the message is MSG_BKUP_SEQUENCE_SET_VAL
 */
void
ProcessSequenceSetValCommand(Port *myport, StringInfo message, bool is_backup)
{
	GTM_SequenceKeyData seqkey;
	GTM_Sequence nextval;
	MemoryContext oldContext;
	StringInfoData buf;
	bool iscalled;
	int errcode;
	uint32 coord_namelen;
	char  *coord_name;
	uint32 coord_procid;

	/*
	 * Get the sequence key
	 */
	seqkey.gsk_keylen = pq_getmsgint(message, sizeof (seqkey.gsk_keylen));
	seqkey.gsk_key = (char *)pq_getmsgbytes(message, seqkey.gsk_keylen);

	coord_namelen = pq_getmsgint(message, sizeof(coord_namelen));
	if (coord_namelen > 0)
		coord_name = (char *)pq_getmsgbytes(message, coord_namelen);
	else
		coord_name = NULL;
	coord_procid = pq_getmsgint(message, sizeof(coord_procid));

	/* Read parameters to be set */
	memcpy(&nextval, pq_getmsgbytes(message, sizeof (GTM_Sequence)),
		   sizeof (GTM_Sequence));

	iscalled = pq_getmsgbyte(message);

	/*
	 * We must use the TopMostMemoryContext because the sequence information is
	 * not bound to a thread and can outlive any of the thread specific
	 * contextes.
	 */
	oldContext = MemoryContextSwitchTo(TopMostMemoryContext);

	elog(DEBUG1, "Setting new value %ld for sequence %s", nextval, seqkey.gsk_key);

	if ((errcode = GTM_SeqSetVal(&seqkey, coord_name, coord_procid, nextval, iscalled)))
		ereport(ERROR,
				(errcode,
				 errmsg("Failed to set values of sequence")));

	MemoryContextSwitchTo(oldContext);

	pq_getmsgend(message);

	if (!is_backup)
	{
		/* Backup first */
		if (GetMyThreadInfo->thr_conn->standby)
		{
			int rc;
			GTM_Conn *oldconn = GetMyThreadInfo->thr_conn->standby;
			int count = 0;

			elog(DEBUG1, "calling set_val() for standby GTM %p.", GetMyThreadInfo->thr_conn->standby);

		retry:
			rc = bkup_set_val(GetMyThreadInfo->thr_conn->standby,
							  &seqkey,
							  coord_name,
							  coord_procid,
							  nextval,
							  iscalled);

			if (gtm_standby_check_communication_error(&count, oldconn))
				goto retry;

			/* Sync */
			if (Backup_synchronously && (myport->remote_type != GTM_NODE_GTM_PROXY))
				gtm_sync_standby(GetMyThreadInfo->thr_conn->standby);

			elog(DEBUG1, "set_val() returns rc %d.", rc);
		}
		/* Save control file info */
        SaveControlInfo();

		/* Respond to the client */
		pq_beginmessage(&buf, 'S');
		pq_sendint(&buf, SEQUENCE_SET_VAL_RESULT, 4);
		if (myport->remote_type == GTM_NODE_GTM_PROXY)
		{
			GTM_ProxyMsgHeader proxyhdr;
			proxyhdr.ph_conid = myport->conn_id;
			pq_sendbytes(&buf, (char *)&proxyhdr, sizeof (GTM_ProxyMsgHeader));
		}
		pq_sendint(&buf, seqkey.gsk_keylen, 4);
		pq_sendbytes(&buf, seqkey.gsk_key, seqkey.gsk_keylen);
		pq_endmessage(myport, &buf);

		if (myport->remote_type != GTM_NODE_GTM_PROXY)
		{
			/* Flush the standby first */
			if (GetMyThreadInfo->thr_conn->standby)
				gtmpqFlush(GetMyThreadInfo->thr_conn->standby);
			pq_flush(myport);
		}

	}
	/* FIXME: need to check errors */
}

/*
 * Process MSG_SEQUENCE_RESET/MSG_BKUP_SEQUENCE_RESET message
 *
 * is_backup indicates the cmessage is MSG_BKUP_SEQUENCE_RESULT
 */
void
ProcessSequenceResetCommand(Port *myport, StringInfo message, bool is_backup)
{
	GTM_SequenceKeyData seqkey;
	StringInfoData buf;
	int errcode;

	seqkey.gsk_keylen = pq_getmsgint(message, sizeof (seqkey.gsk_keylen));
	seqkey.gsk_key = (char *)pq_getmsgbytes(message, seqkey.gsk_keylen);

	elog(DEBUG1, "Resetting sequence %s", seqkey.gsk_key);

	if ((errcode = GTM_SeqReset(&seqkey)))
		ereport(ERROR,
				(errcode,
				 errmsg("Can not reset the sequence")));

	if (!is_backup)
	{
		/* Backup first */
		if (GetMyThreadInfo->thr_conn->standby)
		{
			int rc;
			GTM_Conn *oldconn = GetMyThreadInfo->thr_conn->standby;
			int count = 0;

			elog(DEBUG1, "calling reset_sequence() for standby GTM %p.", GetMyThreadInfo->thr_conn->standby);

		retry:
			rc = bkup_reset_sequence(GetMyThreadInfo->thr_conn->standby, &seqkey);

			if (gtm_standby_check_communication_error(&count, oldconn))
				goto retry;

			/* Sync */
			if (Backup_synchronously && (myport->remote_type != GTM_NODE_GTM_PROXY))
				gtm_sync_standby(GetMyThreadInfo->thr_conn->standby);

			elog(DEBUG1, "reset_sequence() returns rc %d.", rc);
		}
		/* Save control file info */
        SaveControlInfo();

		/* Respond to the client */
		pq_beginmessage(&buf, 'S');
		pq_sendint(&buf, SEQUENCE_RESET_RESULT, 4);
		if (myport->remote_type == GTM_NODE_GTM_PROXY)
		{
			GTM_ProxyMsgHeader proxyhdr;
			proxyhdr.ph_conid = myport->conn_id;
			pq_sendbytes(&buf, (char *)&proxyhdr, sizeof (GTM_ProxyMsgHeader));
		}
		pq_sendint(&buf, seqkey.gsk_keylen, 4);
		pq_sendbytes(&buf, seqkey.gsk_key, seqkey.gsk_keylen);
		pq_endmessage(myport, &buf);

		if (myport->remote_type != GTM_NODE_GTM_PROXY)
		{
			/* Flush the standby first */
			if (GetMyThreadInfo->thr_conn->standby)
				gtmpqFlush(GetMyThreadInfo->thr_conn->standby);
			pq_flush(myport);
		}

	}
	/* FIXME: need to check errors */
}

/*
 * Process MSG_SEQUENCE_CLOSE/MSG_BKUP_SEQUENCE_CLOSE message
 *
 * is_backup indicates the message is MSG_BKUP_SEQUENCE_CLOSE
 */
void
ProcessSequenceCloseCommand(Port *myport, StringInfo message, bool is_backup)
{
	GTM_SequenceKeyData seqkey;
	StringInfoData buf;
	int errcode;
	GlobalTransactionId gxid;
	const char *data;

	seqkey.gsk_keylen = pq_getmsgint(message, sizeof (seqkey.gsk_keylen));
	seqkey.gsk_key = (char *)pq_getmsgbytes(message, seqkey.gsk_keylen);
	memcpy(&seqkey.gsk_type, pq_getmsgbytes(message, sizeof (GTM_SequenceKeyType)),
		   sizeof (GTM_SequenceKeyType));

    data = pq_getmsgbytes(message, sizeof (gxid));
    if (data == NULL)
        ereport(ERROR,
                (EPROTO,
                 errmsg("Message does not contain valid GXID")));
    memcpy(&gxid, data, sizeof (gxid));

	elog(DEBUG1, "Closing sequence %s", seqkey.gsk_key);

	if ((errcode = GTM_SeqClose(&seqkey, gxid)))
		ereport(ERROR,
				(errcode,
				 errmsg("Can not close the sequence")));

	if (!is_backup)
	{
		/* Backup first */
		if (GetMyThreadInfo->thr_conn->standby)
		{
			int rc;
			GTM_Conn *oldconn = GetMyThreadInfo->thr_conn->standby;
			int count = 0;

			elog(DEBUG1, "calling close_sequence() for standby GTM %p.", GetMyThreadInfo->thr_conn->standby);

		retry:
			rc = bkup_close_sequence(GetMyThreadInfo->thr_conn->standby,
					&seqkey, gxid);

			if (gtm_standby_check_communication_error(&count, oldconn))
				goto retry;

			/* Sync */
			if (Backup_synchronously && (myport->remote_type != GTM_NODE_GTM_PROXY))
				gtm_sync_standby(GetMyThreadInfo->thr_conn->standby);

			elog(DEBUG1, "close_sequence() returns rc %d.", rc);
		}
		/* Save control file info */
        SaveControlInfo();

		/* Respond to the client */
		pq_beginmessage(&buf, 'S');
		pq_sendint(&buf, SEQUENCE_CLOSE_RESULT, 4);
		if (myport->remote_type == GTM_NODE_GTM_PROXY)
		{
			GTM_ProxyMsgHeader proxyhdr;
			proxyhdr.ph_conid = myport->conn_id;
			pq_sendbytes(&buf, (char *)&proxyhdr, sizeof (GTM_ProxyMsgHeader));
		}
		pq_sendint(&buf, seqkey.gsk_keylen, 4);
		pq_sendbytes(&buf, seqkey.gsk_key, seqkey.gsk_keylen);
		pq_endmessage(myport, &buf);

		if (myport->remote_type != GTM_NODE_GTM_PROXY)
		{
			/* Flush the standby first */
			if (GetMyThreadInfo->thr_conn->standby)
				gtmpqFlush(GetMyThreadInfo->thr_conn->standby);
			pq_flush(myport);
		}

		/* FIXME: need to check errors */
	}
}

/*
 * Process MSG_SEQUENCE_RENAME/MSG_BKUP_SEQUENCE_RENAME message
 *
 * is_backup indicates the message is MSG_BKUP_SEQUENCE_RENAME
 */
void
ProcessSequenceRenameCommand(Port *myport, StringInfo message, bool is_backup)
{
	GTM_SequenceKeyData seqkey, newseqkey;
	StringInfoData buf;
	int errcode;
	MemoryContext oldContext;
    const char *data;
	GlobalTransactionId gxid;

	/* get the message from backend */
	seqkey.gsk_keylen = pq_getmsgint(message, sizeof (seqkey.gsk_keylen));
	seqkey.gsk_key = (char *)pq_getmsgbytes(message, seqkey.gsk_keylen);

	/* Get the rest of the message, new name length and string with new name */
	newseqkey.gsk_keylen = pq_getmsgint(message, sizeof (newseqkey.gsk_keylen));
	newseqkey.gsk_key = (char *)pq_getmsgbytes(message, newseqkey.gsk_keylen);

    data = pq_getmsgbytes(message, sizeof (gxid));
    if (data == NULL)
        ereport(ERROR,
                (EPROTO,
                 errmsg("Message does not contain valid GXID")));
    memcpy(&gxid, data, sizeof (gxid));


	/*
	 * As when creating a sequence, we must use the TopMostMemoryContext
	 * because the sequence information is not bound to a thread and
	 * can outlive any of the thread specific contextes.
	 */
	oldContext = MemoryContextSwitchTo(TopMostMemoryContext);

	elog(DEBUG1, "Renaming sequence %s to %s", seqkey.gsk_key, newseqkey.gsk_key);

	if ((errcode = GTM_SeqRename(&seqkey, &newseqkey, gxid)))
		ereport(ERROR,
				(errcode,
				 errmsg("Can not rename the sequence")));

	MemoryContextSwitchTo(oldContext);

	pq_getmsgend(message);

	if (!is_backup)
	{
		/* Backup first */
		if (GetMyThreadInfo->thr_conn->standby)
		{
			int rc;
			GTM_Conn *oldconn = GetMyThreadInfo->thr_conn->standby;
			int count = 0;

			elog(DEBUG1, "calling rename_sequence() for standby GTM %p.", GetMyThreadInfo->thr_conn->standby);

		retry:
			rc = bkup_rename_sequence(GetMyThreadInfo->thr_conn->standby,
					&seqkey, &newseqkey, gxid);

			if (gtm_standby_check_communication_error(&count, oldconn))
				goto retry;

			/* Sync */
			if (Backup_synchronously && (myport->remote_type != GTM_NODE_GTM_PROXY))
				gtm_sync_standby(GetMyThreadInfo->thr_conn->standby);

			elog(DEBUG1, "rename_sequence() returns rc %d.", rc);
		}
		/* Save control file info */
        SaveControlInfo();

		/* Send a SUCCESS message back to the client */
		pq_beginmessage(&buf, 'S');
		pq_sendint(&buf, SEQUENCE_RENAME_RESULT, 4);
		if (myport->remote_type == GTM_NODE_GTM_PROXY)
		{
			GTM_ProxyMsgHeader proxyhdr;
			proxyhdr.ph_conid = myport->conn_id;
			pq_sendbytes(&buf, (char *)&proxyhdr, sizeof (GTM_ProxyMsgHeader));
		}
		pq_sendint(&buf, newseqkey.gsk_keylen, 4);
		pq_sendbytes(&buf, newseqkey.gsk_key, newseqkey.gsk_keylen);
		pq_endmessage(myport, &buf);

		if (myport->remote_type != GTM_NODE_GTM_PROXY)
		{
			/* Flush the standby first */
			if (GetMyThreadInfo->thr_conn->standby)
				gtmpqFlush(GetMyThreadInfo->thr_conn->standby);
			pq_flush(myport);
		}

	}
	/* FIXME: need to check errors */
}



/*
 * Escape whitespace and non-printable characters in the sequence name to
 * store it to the control file.
 */
static void
encode_seq_key(GTM_SequenceKey seqkey, char *buffer)
{
	int 	i;
	char	c;
	char   *out;

	out = buffer;
	for (i = 0; i < seqkey->gsk_keylen; i++)
	{
		c = seqkey->gsk_key[i];

		if (c == '\\') /* double backslach */
		{
			*out++ = '\\';
			*out++ = '\\';
		}
		else if (c > ' ') /* no need to escape */
		{
			*out++ = c;
		}
		else if (c == '\n') /* below some known non-printable chars */
		{
			*out++ = '\\';
			*out++ = 'n';
		}
		else if (c == '\r')
		{
			*out++ = '\\';
			*out++ = 'r';
		}
		else if (c == '\t')
		{
			*out++ = '\\';
			*out++ = 't';
		}
		else /* other non-printable chars */
		{
			*out++ = '\\';
			if ((int) c < 10)
			{
				*out++ = '0';
				*out++ = (char) ((int) '0' + (int) c);
			}
			else
			{
				*out++ = (char) ((int) '0' + ((int) c) / 10);
				*out++ = (char) ((int) '0' + ((int) c) % 10);
			}
		}
	}
	/* Add NULL terminator */
	*out++ = '\0';
}


/*
 * Decode the string encoded by the encode_seq_key function
 */
void
decode_seq_key(char* value, GTM_SequenceKey seqkey)
{
	char   *in;
	char 	out[1024];
	int		len = 0;

	in = value;
	while (*in != '\0')
	{
		if (*in == '\\') /* get escaped character */
		{
			in++; /* next value */
			if (*in == '\\')
				out[len++] = *in++;
			else if (*in == 'n')
			{
				out[len++] = '\n';
				in++;
			}
			else if (*in == 'r')
			{
				out[len++] = '\r';
				in++;
			}
			else if (*in == 't')
			{
				out[len++] = '\t';
				in++;
			}
			else /* \nn format */
			{
				int val;
				val = ((int) *in++ - (int) '0');
				val *= 10;
				val += ((int) *in++ - (int) '0');
				out[len++] = (char) val;
			}
		}
		else /* get plain character */
		{
			out[len++] = *in++;
		}
	}
	/* copy result to palloc'ed memory */
	seqkey->gsk_keylen = len;
	seqkey->gsk_key = (char *) palloc(len);
	memcpy(seqkey->gsk_key, out, len);
}

static GTM_Sequence distanceToBackedUpSeqValue(GTM_SeqInfo *seqinfo)
{
	if (!SEQ_IS_CALLED(seqinfo))
		return (GTM_Sequence)0;
	if (SEQ_IS_ASCENDING(seqinfo))
	{
		if ((seqinfo->gs_backedUpValue - seqinfo->gs_value) >= 0)
			return (seqinfo->gs_backedUpValue - seqinfo->gs_value);
		if (SEQ_IS_CYCLE(seqinfo))
			return((seqinfo->gs_max_value - seqinfo->gs_value) + (seqinfo->gs_backedUpValue - seqinfo->gs_min_value));
		else
			return(seqinfo->gs_backedUpValue - seqinfo->gs_value);
	}
	else
	{
		if ((seqinfo->gs_value - seqinfo->gs_backedUpValue) >= 0)
			return(seqinfo->gs_backedUpValue - seqinfo->gs_value);
		if (SEQ_IS_CYCLE(seqinfo))
			return((seqinfo->gs_max_value - seqinfo->gs_backedUpValue) + (seqinfo->gs_value - seqinfo->gs_min_value));
		else
			return(seqinfo->gs_backedUpValue - seqinfo->gs_value);
	}
	return 0;
}

bool GTM_NeedSeqRestoreUpdate(GTM_SequenceKey seqkey)
{
	GTM_SeqInfo *seqinfo = seq_find_seqinfo(seqkey);
	if (!seqinfo)
		return FALSE;
	return GTM_NeedSeqRestoreUpdateInternal(seqinfo);
}

static bool GTM_NeedSeqRestoreUpdateInternal(GTM_SeqInfo *seqinfo)
{
	GTM_Sequence distance;

	if (!SEQ_IS_CALLED(seqinfo))
		/* The first call.  Must backup */
		return TRUE;
	distance = distanceToBackedUpSeqValue(seqinfo);
	if (SEQ_IS_ASCENDING(seqinfo))
		return(distance >= seqinfo->gs_increment_by);
	else
		return(distance <= seqinfo->gs_increment_by);
}



static void
GTM_SaveSeqInfo2(FILE *ctlf, bool isBackup)
{
	GTM_SeqInfoHashBucket *bucket;
	gtm_ListCell *elem;
	GTM_SeqInfo *seqinfo = NULL;
	int hash;
	char buffer[1024];

	for (hash = 0; hash < SEQ_HASH_TABLE_SIZE; hash++)
	{
		bucket = &GTMSequences[hash];

		GTM_RWLockAcquire(&bucket->shb_lock, GTM_LOCKMODE_READ);

		gtm_foreach(elem, bucket->shb_list)
		{
			seqinfo = (GTM_SeqInfo *) gtm_lfirst(elem);
			if (seqinfo == NULL)
				break;

			if (seqinfo->gs_state == SEQ_STATE_DELETED)
				continue;

			GTM_RWLockAcquire(&seqinfo->gs_lock, GTM_LOCKMODE_READ);

			encode_seq_key(seqinfo->gs_key, buffer);
			fprintf(ctlf, "%s\t%ld\t%ld\t%ld\t%ld\t%ld\t%c\t%c\t%x\n",
					buffer, isBackup ? seqinfo->gs_backedUpValue : seqinfo->gs_value,
					seqinfo->gs_init_value, seqinfo->gs_increment_by,
					seqinfo->gs_min_value, seqinfo->gs_max_value,
					(seqinfo->gs_cycle ? 't' : 'f'),
					(seqinfo->gs_called ? 't' : 'f'),
					seqinfo->gs_state);

			GTM_RWLockRelease(&seqinfo->gs_lock);
		}
		GTM_RWLockRelease(&bucket->shb_lock);
	}

}

void GTM_SaveSeqInfo(FILE *ctlf)
{
	GTM_SaveSeqInfo2(ctlf, FALSE);
}

static void advance_gs_value(GTM_SeqInfo *seqinfo)
{
	
	GTM_Sequence distance;

	distance = seqinfo->gs_increment_by * RestoreDuration;
	if (SEQ_IS_ASCENDING(seqinfo))
	{
		if ((seqinfo->gs_max_value - seqinfo->gs_value) >= distance)
			seqinfo->gs_backedUpValue = seqinfo->gs_value + distance;
		else
		{
			if (SEQ_IS_CYCLE(seqinfo))
				seqinfo->gs_backedUpValue = seqinfo->gs_min_value + (distance - (seqinfo->gs_max_value - seqinfo->gs_value));
			else
				seqinfo->gs_backedUpValue = seqinfo->gs_max_value;
		}
	}
	else
	{
		if ((seqinfo->gs_min_value - seqinfo->gs_value) >= distance)
			seqinfo->gs_backedUpValue = seqinfo->gs_value + distance;
		else
		{
			if (SEQ_IS_CYCLE(seqinfo))
				seqinfo->gs_backedUpValue = seqinfo->gs_max_value + (distance - (seqinfo->gs_min_value - seqinfo->gs_value));
			else
				seqinfo->gs_backedUpValue = seqinfo->gs_min_value;
		}
	}
}


static void
GTM_UpdateRestorePointSeq(void)
{
	GTM_SeqInfoHashBucket *bucket;
	gtm_ListCell *elem;
	GTM_SeqInfo *seqinfo = NULL;
	int hash;

	for (hash = 0; hash < SEQ_HASH_TABLE_SIZE; hash++)
	{
		bucket = &GTMSequences[hash];

		GTM_RWLockAcquire(&bucket->shb_lock, GTM_LOCKMODE_READ);

		gtm_foreach(elem, bucket->shb_list)
		{
			seqinfo = (GTM_SeqInfo *) gtm_lfirst(elem);
			if (seqinfo == NULL)
				break;

			if (seqinfo->gs_state == SEQ_STATE_DELETED)
				continue;

			GTM_RWLockAcquire(&seqinfo->gs_lock, GTM_LOCKMODE_READ);
			advance_gs_value(seqinfo);
			GTM_RWLockRelease(&seqinfo->gs_lock);
		}

		GTM_RWLockRelease(&bucket->shb_lock);
	}

}


void GTM_WriteRestorePointSeq(FILE *ctlf)
{
	GTM_UpdateRestorePointSeq();
	GTM_SaveSeqInfo2(ctlf, TRUE);
}

/*
 * Remove all current values allocated for the specified session from all
 * sequences.
 */
void
GTM_CleanupSeqSession(char *coord_name, int coord_procid)
{
	int i;

	elog(DEBUG1, "Clean up Sequences used in session %s:%d",
			coord_name, coord_procid);

	for (i = 0; i < SEQ_HASH_TABLE_SIZE; i++)
	{
		GTM_SeqInfoHashBucket *bucket = &GTMSequences[i];
		gtm_ListCell *elem;
		GTM_SeqInfo *curr_seqinfo;

		GTM_RWLockAcquire(&bucket->shb_lock, GTM_LOCKMODE_READ);

		gtm_foreach(elem, bucket->shb_list)
		{
			int j;
			curr_seqinfo = (GTM_SeqInfo *) gtm_lfirst(elem);
			GTM_RWLockAcquire(&curr_seqinfo->gs_lock, GTM_LOCKMODE_WRITE);
			if (curr_seqinfo->gs_state != SEQ_STATE_ACTIVE)
			{
				GTM_RWLockRelease(&curr_seqinfo->gs_lock);
				continue;
			}

			for (j = 0; j < curr_seqinfo->gs_lastval_count; j++)
			{
				GTM_SeqLastVal *lastval = &curr_seqinfo->gs_last_values[j];
				if (strcmp(lastval->gs_coord_name, coord_name) == 0 &&
						lastval->gs_coord_procid == coord_procid)
				{
					int newcount = --curr_seqinfo->gs_lastval_count;
					elog(DEBUG1, "remove value of Sequence %s acquired for session %s:%d",
						 curr_seqinfo->gs_key->gsk_key, lastval->gs_coord_name,
						 lastval->gs_coord_procid);
					if (j < newcount)
						memcpy(lastval, &curr_seqinfo->gs_last_values[newcount],
								sizeof(GTM_SeqLastVal));
					if (curr_seqinfo->gs_lastval_count == 0)
					{
						elog(DEBUG1, "Sequence %s is not used, free curr values memory",
							 curr_seqinfo->gs_key->gsk_key);
						curr_seqinfo->gs_max_lastvals = 0;
						pfree(curr_seqinfo->gs_last_values);
						curr_seqinfo->gs_last_values = NULL;
					}
					break;
				}
			}
			GTM_RWLockRelease(&curr_seqinfo->gs_lock);
		}
		GTM_RWLockRelease(&bucket->shb_lock);
	}
}

/*
 * Upon transaction abort, remove the sequence created in the transaction being
 * aborted.
 */
void
GTM_SeqRemoveCreated(void *ptr)
{
	GTM_SeqInfo *seqinfo = seq_find_seqinfo((GTM_SequenceKey) ptr);
	if (seqinfo)
	{
		seq_release_seqinfo(seqinfo);
		if (!seq_remove_seqinfo(seqinfo))
		{
			pfree(seqinfo->gs_key);
			pfree(seqinfo);
		}
	}
}

/*
 * Upon transaction abort, restore the sequence back to its state when it was
 * altered first time in the transaction.
 */
void
GTM_SeqRestoreAltered(void *ptr)
{
	GTM_SeqAlteredInfo *alterinfo = (GTM_SeqAlteredInfo *) ptr;
	GTM_SeqInfo *seqinfo = seq_find_seqinfo(alterinfo->curr_key);

	if (seqinfo)
	{
		if (!seq_keys_equal(seqinfo->gs_key, alterinfo->prev_key))
			seq_rename_seqinfo(seqinfo, alterinfo->prev_key);
		pfree(alterinfo->prev_key);
		pfree(alterinfo->curr_key);
		pfree(alterinfo);
		seq_release_seqinfo(seqinfo);
	}
}

/*
 * Upon transaction abort, rename the sequence back to its original value.
 */
void
GTM_SeqRestoreDropped(void *ptr)
{
	GTM_SeqInfo *seqinfo = seq_find_seqinfo((GTM_SequenceKey) ptr);
	if (seqinfo)
	{
		seq_rename_seqinfo(seqinfo, seqinfo->gs_oldkey);
		seq_release_seqinfo(seqinfo);
	}
	
}

/*
 * Upon transaction commit, forget the original sequence state. The current
 * state becomes the final state of the sequence.
 */
void
GTM_SeqRemoveAltered(void *ptr)
{
	GTM_SeqAlteredInfo *alterinfo = (GTM_SeqAlteredInfo *) ptr;
	if (alterinfo)
	{
		pfree(alterinfo->curr_key);
		pfree(alterinfo->prev_key);
		pfree(alterinfo);
	}
}

/*
 * Upon transaction commit, remove the temporarily renamed sequence forever
 * from the global structure.
 */
void
GTM_SeqRemoveDropped(void *ptr)
{
	GTM_SeqInfo *seqinfo = seq_find_seqinfo((GTM_SequenceKey) ptr);
	if (seqinfo)
	{
		seq_release_seqinfo(seqinfo);
		if (!seq_remove_seqinfo(seqinfo))
		{
			pfree(seqinfo->gs_key);
			pfree(seqinfo);
		}
	}
}