-
-
Notifications
You must be signed in to change notification settings - Fork 234
/
Copy pathtpc.cpp
1236 lines (986 loc) · 37.1 KB
/
tpc.cpp
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
/*
* PROGRAM: JRD Access Method
* MODULE: tpc.cpp
* DESCRIPTION: TIP Cache for Database
*
* The contents of this file are subject to the Interbase Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy
* of the License at http://www.Inprise.com/IPL.html
*
* Software distributed under the License is distributed on an
* "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express
* or implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code was created by Inprise Corporation
* and its predecessors. Portions created by Inprise Corporation are
* Copyright (C) Inprise Corporation.
*
* All Rights Reserved.
* Contributor(s): ______________________________________.
*/
#include "firebird.h"
#include "../jrd/jrd.h"
#include "../jrd/ods.h"
#include "../jrd/tra.h"
#include "../jrd/pag.h"
#include "../jrd/cch_proto.h"
#include "../jrd/lck_proto.h"
#include "../jrd/ods_proto.h"
#include "../jrd/tpc_proto.h"
#include "../jrd/tra_proto.h"
#include "../jrd/replication/Publisher.h"
#include "../common/isc_proto.h"
#include <sys/stat.h>
using namespace Firebird;
namespace Jrd {
void TipCache::MemoryInitializer::mutexBug(int osErrorCode, const char* text)
{
string msg;
msg.printf("TPC: mutex %s error, status = %d", text, osErrorCode);
fb_utils::logAndDie(msg.c_str());
}
bool TipCache::GlobalTpcInitializer::initialize(SharedMemoryBase* sm, bool initFlag)
{
GlobalTpcHeader* header = static_cast<GlobalTpcHeader*>(sm->sh_mem_header);
if (!initFlag)
{
if (!checkHeader(header, false))
return false;
m_cache->initTransactionsPerBlock(header->tpc_block_size);
m_cache->mapInventoryPages(header);
return true;
}
thread_db* tdbb = JRD_get_thread_data();
Database* dbb = tdbb->getDatabase();
// Initialize the shared data header
initHeader(header);
header->latest_commit_number.store(CN_PREHISTORIC, std::memory_order_relaxed);
header->latest_statement_id.store(0, std::memory_order_relaxed);
header->monitor_generation.store(0, std::memory_order_relaxed);
header->tpc_block_size = dbb->dbb_config->getTipCacheBlockSize();
m_cache->initTransactionsPerBlock(header->tpc_block_size);
m_cache->loadInventoryPages(tdbb, header);
return true;
}
bool TipCache::SnapshotsInitializer::initialize(SharedMemoryBase* sm, bool initFlag)
{
if (!initFlag)
return true;
SnapshotList* header = static_cast<SnapshotList*>(sm->sh_mem_header);
// Initialize the shared data header
initHeader(header);
header->slots_used.store(0, std::memory_order_relaxed);
header->min_free_slot = 0;
const ULONG dataSize = sm->sh_mem_length_mapped - offsetof(SnapshotList, slots[0]);
header->slots_allocated.store(dataSize / sizeof(SnapshotData), std::memory_order_relaxed);
return true;
}
bool TipCache::MemBlockInitializer::initialize(SharedMemoryBase* sm, bool initFlag)
{
if (!initFlag)
return true;
TransactionStatusBlock* header = static_cast<TransactionStatusBlock*>(sm->sh_mem_header);
// Initialize the shared data header
initHeader(header);
memset(header->data, 0, sm->sh_mem_length_mapped - offsetof(TransactionStatusBlock, data[0]));
fb_assert(header->data->is_lock_free());
return true;
}
TipCache::TipCache(Database* dbb)
: m_tpcHeader(NULL), m_snapshots(NULL), m_transactionsPerBlock(0), m_lock(nullptr),
globalTpcInitializer(this), snapshotsInitializer(this), memBlockInitializer(this),
m_blocks_memory(*dbb->dbb_permanent)
{
}
TipCache::~TipCache()
{
// Make sure that object is finalized before being deleted
fb_assert(!m_blocks_memory.getFirst());
fb_assert(!m_snapshots);
fb_assert(!m_tpcHeader);
fb_assert(m_transactionsPerBlock == 0);
fb_assert((!m_lock.hasData()) || m_lock->lck_logical == LCK_none);
// Avoid worse case
if (m_lock.hasData() && (m_lock->lck_logical != LCK_none))
LCK_release(JRD_get_thread_data(), m_lock);
}
void TipCache::finalizeTpc(thread_db* tdbb)
{
// check for finalizeTpc() called more than once
if (!m_lock.hasData())
return;
// To avoid race conditions, this function might only
// be called during database shutdown when AST delivery is already disabled
// wait for all initializing processes (PR)
if (!LCK_convert(tdbb, m_lock, LCK_SW, LCK_WAIT))
ERR_bugcheck_msg("Unable to convert TPC lock (SW)");
// Release locks and deallocate all shared memory structures
if (m_blocks_memory.getFirst())
{
do
{
StatusBlockData* cur = m_blocks_memory.current();
delete cur;
} while (m_blocks_memory.getNext());
}
PathName nmSnap, nmHdr;
if (m_snapshots)
{
nmSnap = m_snapshots->getMapFileName();
delete m_snapshots;
m_snapshots = NULL;
}
if (m_tpcHeader)
{
nmHdr = m_tpcHeader->getMapFileName();
delete m_tpcHeader;
m_tpcHeader = NULL;
}
m_blocks_memory.clear();
m_transactionsPerBlock = 0;
if (nmSnap.hasData() || nmHdr.hasData())
{
if (LCK_lock(tdbb, m_lock, LCK_EX, LCK_NO_WAIT))
{
if (nmSnap.hasData())
SharedMemoryBase::unlinkFile(nmSnap.c_str());
if (nmHdr.hasData())
SharedMemoryBase::unlinkFile(nmHdr.c_str());
LCK_release(tdbb, m_lock);
}
else
tdbb->tdbb_status_vector->init();
}
else
LCK_release(tdbb, m_lock);
m_lock.reset();
}
CommitNumber TipCache::cacheState(TraNumber number)
{
fb_assert(m_tpcHeader);
GlobalTpcHeader* header = m_tpcHeader->getHeader();
TraNumber oldest = header->oldest_transaction.load(std::memory_order_relaxed);
if (number < oldest)
return CN_PREHISTORIC;
// It is possible to amortize barrier in getTransactionStatusBlock
// over large number of operations, if our callers are made aware of
// TransactionStatusBlock granularity and iterate over transactions
// directly. But since this function is not really called too frequently,
// it should not matter and we leave interface "as is" for now.
TpcBlockNumber blockNumber = number / m_transactionsPerBlock;
ULONG offset = number % m_transactionsPerBlock;
TransactionStatusBlock* block = getTransactionStatusBlock(header, blockNumber);
// This should not really happen ever
fb_assert(block);
if (!block)
return CN_PREHISTORIC;
// Barrier is not needed here when we are reading state from cache
// because all callers of this function are prepared to handle
// slightly out-dated information and will take slow path if necessary
CommitNumber state = block->data[offset];
return state;
}
void TipCache::initializeTpc(thread_db *tdbb)
{
Database* dbb = tdbb->getDatabase();
// Initialization can only be called on a TipCache that is not initialized
fb_assert(!m_transactionsPerBlock);
m_lock = FB_NEW_RPT(*dbb->dbb_permanent, 0) Lock(tdbb, 0, LCK_tpc_init);
// wait for finalizers (SW) locks
if (!LCK_lock(tdbb, m_lock, LCK_PR, LCK_WAIT))
ERR_bugcheck_msg("Unable to obtain TPC lock (PR)");
string fileName;
fileName.printf(TPC_HDR_FILE, dbb->getUniqueFileId().c_str());
try
{
m_tpcHeader = FB_NEW_POOL(*dbb->dbb_permanent) SharedMemory<GlobalTpcHeader>(
fileName.c_str(), sizeof(GlobalTpcHeader), &globalTpcInitializer);
const auto* header = m_tpcHeader->getHeader();
globalTpcInitializer.checkHeader(header);
}
catch (const Exception& ex)
{
iscLogException("TPC: Cannot initialize the shared memory region (header)", ex);
LCK_convert(tdbb, m_lock, LCK_SR, LCK_WAIT); // never fails
finalizeTpc(tdbb);
throw;
}
try
{
fileName.printf(SNAPSHOTS_FILE, dbb->getUniqueFileId().c_str());
m_snapshots = FB_NEW_POOL(*dbb->dbb_permanent) SharedMemory<SnapshotList>(
fileName.c_str(), dbb->dbb_config->getSnapshotsMemSize(), &snapshotsInitializer);
const auto* header = m_snapshots->getHeader();
snapshotsInitializer.checkHeader(header);
}
catch (const Exception& ex)
{
iscLogException("TPC: Cannot initialize the shared memory region (snapshots)", ex);
LCK_convert(tdbb, m_lock, LCK_SR, LCK_WAIT); // never fails
finalizeTpc(tdbb);
throw;
}
fb_assert(m_snapshots->getHeader()->mhb_version == TPC_VERSION);
LCK_convert(tdbb, m_lock, LCK_SR, LCK_WAIT); // never fails
}
void TipCache::initTransactionsPerBlock(ULONG blockSize)
{
if (m_transactionsPerBlock)
return;
const ULONG dataOffset = static_cast<ULONG>(offsetof(TransactionStatusBlock, data[0]));
m_transactionsPerBlock = (blockSize - dataOffset) / sizeof(CommitNumber);
}
void TipCache::loadInventoryPages(thread_db* tdbb, GlobalTpcHeader* header)
{
// check the header page for the oldest and newest transaction numbers
#ifdef SUPERSERVER_V2
Database* dbb = tdbb->getDatabase();
const TraNumber top = dbb->dbb_next_transaction;
const TraNumber hdr_oldest = dbb->dbb_oldest_transaction;
#else
WIN window(HEADER_PAGE_NUMBER);
const auto header_page = (Ods::header_page*) CCH_FETCH(tdbb, &window, LCK_read, pag_header);
const TraNumber hdr_next_transaction = header_page->hdr_next_transaction;
const TraNumber hdr_oldest_transaction = header_page->hdr_oldest_transaction;
const AttNumber hdr_attachment_id = header_page->hdr_attachment_id;
CCH_RELEASE(tdbb, &window);
#endif
header->latest_transaction_id.store(hdr_next_transaction, std::memory_order_relaxed);
header->oldest_transaction.store(hdr_oldest_transaction, std::memory_order_relaxed);
header->latest_attachment_id.store(hdr_attachment_id, std::memory_order_relaxed);
// Round down the oldest to a multiple of four, which puts the
// transaction in temporary buffer on a byte boundary
TraNumber base = hdr_oldest_transaction & ~TRA_MASK;
const FB_SIZE_T buffer_length = (hdr_next_transaction + 1 - base + TRA_MASK) / 4;
Array<UCHAR> transactions(buffer_length);
UCHAR* buffer = transactions.begin();
TRA_get_inventory(tdbb, buffer, base, hdr_next_transaction);
static const CommitNumber init_state_mapping[4] = {CN_ACTIVE, CN_LIMBO, CN_DEAD, CN_PREHISTORIC};
TpcBlockNumber blockNumber = hdr_oldest_transaction / m_transactionsPerBlock;
ULONG transOffset = hdr_oldest_transaction % m_transactionsPerBlock;
TransactionStatusBlock* statusBlock = getTransactionStatusBlock(header, blockNumber);
for (TraNumber t = hdr_oldest_transaction; ; )
{
int state = TRA_state(buffer, base, t);
CommitNumber cn = init_state_mapping[state];
// Barrier is not needed as our thread is the only one here.
// At the same time, simple write to a volatile variable is not good
// as it is not deterministic. Some compilers generate barriers and some do not.
(statusBlock->data + transOffset)->store(cn, std::memory_order_relaxed);
if (++t > hdr_next_transaction)
break;
if (++transOffset == m_transactionsPerBlock)
{
blockNumber++;
transOffset = 0;
statusBlock = getTransactionStatusBlock(header, blockNumber);
}
}
}
void TipCache::mapInventoryPages(GlobalTpcHeader* header)
{
TpcBlockNumber blockNumber = header->oldest_transaction / m_transactionsPerBlock;
const TpcBlockNumber lastNumber = header->latest_transaction_id / m_transactionsPerBlock;
for (; blockNumber <= lastNumber; blockNumber++)
getTransactionStatusBlock(header, blockNumber);
}
TipCache::StatusBlockData::StatusBlockData(thread_db* tdbb, TipCache* tipCache, ULONG blockSize, TpcBlockNumber blkNumber)
: blockNumber(blkNumber),
memory(NULL),
existenceLock(tdbb, sizeof(TpcBlockNumber), LCK_tpc_block, this, tpc_block_blocking_ast),
cache(tipCache),
acceptAst(false)
{
Database* dbb = tdbb->getDatabase();
existenceLock.setKey(blockNumber);
if (!LCK_lock(tdbb, &existenceLock, LCK_PR, LCK_WAIT))
ERR_bugcheck_msg("Unable to obtain memory block lock");
PathName fileName = makeSharedMemoryFileName(dbb, blockNumber, false);
try
{
// Here SharedMemory constructor is called with skipLock parameter set to true.
// Appropriate locking is performed by existenceLock using LM.
// This should be in sync with SharedMemoryBase::unlinkFile() call
// in TipCache::StatusBlockData::clear().
memory = FB_NEW_POOL(*dbb->dbb_permanent) SharedMemory<TransactionStatusBlock>(
fileName.c_str(), blockSize,
&cache->memBlockInitializer, true);
const auto* header = memory->getHeader();
cache->memBlockInitializer.checkHeader(header);
LCK_convert(tdbb, &existenceLock, LCK_SR, LCK_WAIT); // never fails
acceptAst = true;
}
catch (const Exception& ex)
{
iscLogException("TPC: Cannot initialize the shared memory region (transactions status block)", ex);
LCK_release(tdbb, &existenceLock);
throw;
}
fb_assert(memory->getHeader()->mhb_version == TPC_VERSION);
}
PathName TipCache::StatusBlockData::makeSharedMemoryFileName(Database* dbb, TpcBlockNumber n, bool fullPath)
{
PathName fileName;
fileName.printf(TPC_BLOCK_FILE, dbb->getUniqueFileId().c_str(), n);
if (!fullPath)
return fileName;
TEXT expanded_filename[MAXPATHLEN];
iscPrefixLock(expanded_filename, fileName.c_str(), false);
return PathName(expanded_filename);
}
TipCache::StatusBlockData::~StatusBlockData()
{
thread_db* tdbb = JRD_get_thread_data();
clear(tdbb);
}
void TipCache::StatusBlockData::clear(thread_db* tdbb)
{
// memory could be already released at tpc_block_blocking_ast
PathName fName;
if (memory)
{
// wait for all initializing processes (PR)
acceptAst = false;
TraNumber oldest;
if (cache->m_tpcHeader)
oldest = cache->m_tpcHeader->getHeader()->oldest_transaction.load(std::memory_order_relaxed);
else
{
Database* dbb = tdbb->getDatabase();
if (dbb->dbb_flags & DBB_shared)
oldest = dbb->dbb_oldest_transaction;
else
{
WIN window(HEADER_PAGE_NUMBER);
const auto header_page = (Ods::header_page*) CCH_FETCH(tdbb, &window, LCK_read, pag_header);
oldest = header_page->hdr_oldest_transaction;
CCH_RELEASE(tdbb, &window);
}
}
if (blockNumber < oldest / cache->m_transactionsPerBlock && // old block => send AST
!LCK_convert(tdbb, &existenceLock, LCK_SW, LCK_WAIT))
{
ERR_bugcheck_msg("Unable to convert TPC lock (SW)");
}
fName = memory->getMapFileName();
delete memory;
memory = NULL;
}
if (fName.hasData())
{
// Here file is removed from SharedMemory created with skipLock parameter
// set to true. That means internal file lock is turned off.
// Appropriate locking is performed by existenceLock using LM.
// This should be in sync with SharedMemory constructor called
// in TipCache::StatusBlockData constructor.
if (LCK_lock(tdbb, &existenceLock, LCK_EX, LCK_NO_WAIT))
SharedMemoryBase::unlinkFile(fName.c_str());
else
{
tdbb->tdbb_status_vector->init();
return;
}
}
LCK_release(tdbb, &existenceLock);
}
TipCache::TransactionStatusBlock* TipCache::createTransactionStatusBlock(ULONG blockSize, TpcBlockNumber blockNumber)
{
fb_assert(m_sync_status.ourExclusiveLock());
thread_db* tdbb = JRD_get_thread_data();
Database* dbb = tdbb->getDatabase();
StatusBlockData* blockData = FB_NEW_POOL(*dbb->dbb_permanent)
StatusBlockData(tdbb, this, blockSize, blockNumber);
m_blocks_memory.add(blockData);
return blockData->memory->getHeader();
}
TipCache::TransactionStatusBlock* TipCache::getTransactionStatusBlock(GlobalTpcHeader* header, TpcBlockNumber blockNumber)
{
// This is a double-checked locking pattern. SyncLockGuard uses atomic ops internally and should be cheap
TransactionStatusBlock* block = NULL;
{
SyncLockGuard sync(&m_sync_status, SYNC_SHARED, "TipCache::getTransactionStatusBlock");
BlocksMemoryMap::ConstAccessor acc(&m_blocks_memory);
if (acc.locate(blockNumber))
block = acc.current()->memory->getHeader();
}
if (!block)
{
SyncLockGuard sync(&m_sync_status, SYNC_EXCLUSIVE, "TipCache::getTransactionStatusBlock");
BlocksMemoryMap::ConstAccessor acc(&m_blocks_memory);
if (acc.locate(blockNumber))
block = acc.current()->memory->getHeader();
else
{
// Check if block might be too old to be created.
TraNumber oldest = header->oldest_transaction.load(std::memory_order_relaxed);
if (blockNumber >= oldest / m_transactionsPerBlock)
block = createTransactionStatusBlock(header->tpc_block_size, blockNumber);
}
}
return block;
}
TraNumber TipCache::findStates(TraNumber minNumber, TraNumber maxNumber, ULONG mask, int& state)
{
// Can only be called on initialized TipCache
fb_assert(m_tpcHeader);
GlobalTpcHeader* header = m_tpcHeader->getHeader();
TransactionStatusBlock* statusBlock;
TpcBlockNumber blockNumber;
ULONG transOffset;
do
{
TraNumber oldest = header->oldest_transaction.load(std::memory_order_relaxed);
if (minNumber < oldest)
minNumber = oldest;
blockNumber = minNumber / m_transactionsPerBlock;
transOffset = minNumber % m_transactionsPerBlock;
statusBlock = getTransactionStatusBlock(header, blockNumber);
} while (!statusBlock);
for (TraNumber t = minNumber; ; )
{
// Barrier is not needed here. Slightly out-dated information shall be ok here.
// Such transaction shall already be considered active by our caller.
// TODO: check if this assumption is indeed correct.
CommitNumber cn = (statusBlock->data + transOffset)->load(std::memory_order_relaxed);
switch (cn)
{
case CN_ACTIVE:
state = tra_active;
break;
case CN_LIMBO:
state = tra_limbo;
break;
case CN_DEAD:
state = tra_dead;
break;
case CN_MAX_NUMBER:
fb_assert(false); // fall thru
default:
state = tra_committed;
break;
}
if (((1 << state) & mask) != 0)
return t;
if (++t >= maxNumber)
break;
if (++transOffset == m_transactionsPerBlock)
{
blockNumber++;
transOffset = 0;
statusBlock = getTransactionStatusBlock(header, blockNumber);
}
}
return 0;
}
CommitNumber TipCache::setState(TraNumber number, int state)
{
// Can only be called on initialized TipCache
fb_assert(m_tpcHeader);
GlobalTpcHeader* header = m_tpcHeader->getHeader();
// over large number of operations, if our callers are made aware of
// TransactionStatusBlock granularity and iterate over transactions
// directly. But since this function is not really called too frequently,
// it should not matter and we leave interface "as is" for now.
TpcBlockNumber blockNumber = number / m_transactionsPerBlock;
ULONG offset = number % m_transactionsPerBlock;
TransactionStatusBlock* block = getTransactionStatusBlock(header, blockNumber);
// This should not really happen
if (!block)
ERR_bugcheck_msg("TPC: Attempt to change state of old transaction");
std::atomic<CommitNumber>* statePtr = block->data + offset;
CommitNumber oldStateCn = statePtr->load(std::memory_order_relaxed);
switch (state)
{
case tra_committed:
{
if (oldStateCn == CN_DEAD)
ERR_bugcheck_msg("TPC: Attempt to commit dead transaction");
// If transaction is already committed - do nothing
if (oldStateCn >= CN_PREHISTORIC && oldStateCn <= CN_MAX_NUMBER)
return oldStateCn;
// We verified for all other cases, transaction must either be Active or in Limbo
fb_assert(oldStateCn == CN_ACTIVE || oldStateCn == CN_LIMBO);
// Generate new commit number
CommitNumber newCommitNumber = header->latest_commit_number++ + 1;
statePtr->store(newCommitNumber, std::memory_order_relaxed);
return newCommitNumber;
}
case tra_limbo:
if (oldStateCn == CN_LIMBO)
return CN_LIMBO;
if (oldStateCn != CN_ACTIVE)
ERR_bugcheck_msg("TPC: Attempt to mark inactive transaction to be in limbo");
statePtr->store(CN_LIMBO, std::memory_order_relaxed);
return CN_LIMBO;
case tra_dead:
if (oldStateCn == CN_DEAD)
return CN_DEAD;
if (oldStateCn != CN_ACTIVE && oldStateCn != CN_LIMBO)
ERR_bugcheck_msg("TPC: Attempt to mark inactive transaction to be dead");
statePtr->store(CN_DEAD, std::memory_order_relaxed);
return CN_DEAD;
default:
ERR_bugcheck_msg("TPC: Attempt to mark invalid transaction state");
return CN_ACTIVE; // silence the compiler
}
}
CommitNumber TipCache::snapshotState(thread_db* tdbb, TraNumber number)
{
// Can only be called on initialized TipCache
fb_assert(m_tpcHeader);
// Get data from cache
CommitNumber stateCn = cacheState(number);
// Transaction is committed or dead?
if (stateCn == CN_DEAD || (stateCn >= CN_PREHISTORIC && stateCn <= CN_MAX_NUMBER))
return stateCn;
// We excluded all other cases above
fb_assert(stateCn == CN_ACTIVE || stateCn == CN_LIMBO);
// Query lock data for a transaction; if we can then we know it is still active.
//
// This logic differs from original TPC implementation as follows:
// 1. We use read_data instead of taking a lock, to avoid possible race conditions
// (they were probably not causing much harm, but consistency is a good thing)
// 2. Old TPC returned tra_active for transactions in limbo, which was not correct
//
// hvlad: tra_active is correct here as it allows caller to wait for prepared but
// still active transaction
Lock temp_lock(tdbb, sizeof(TraNumber), LCK_tra);
temp_lock.setKey(number);
if (LCK_read_data(tdbb, &temp_lock))
return CN_ACTIVE;
// Go to disk, and obtain state of our transaction from TIP
int state = TRA_fetch_state(tdbb, number);
// We already know for sure that this transaction cannot be active, so mark it dead now
// to avoid more work in the future
if (state == tra_active)
{
REPL_trans_cleanup(tdbb, number);
TRA_set_state(tdbb, 0, number, tra_dead); // This will update TIP cache
return CN_DEAD;
}
// Update cache and return new state
stateCn = setState(number, state);
return stateCn;
}
void TipCache::updateOldestTransaction(thread_db *tdbb, TraNumber oldest, TraNumber oldestSnapshot)
{
// Can only be called on initialized TipCache
fb_assert(m_tpcHeader);
GlobalTpcHeader* header = m_tpcHeader->getHeader();
TraNumber oldestNew = MIN(oldest, oldestSnapshot);
TraNumber oldestNow = header->oldest_transaction.load(std::memory_order_relaxed);
if (oldestNew > oldestNow)
{
header->oldest_transaction.store(oldestNew, std::memory_order_relaxed);
releaseSharedMemory(tdbb, oldestNow, oldestNew);
}
}
int TipCache::tpc_block_blocking_ast(void* arg)
{
StatusBlockData* data = static_cast<StatusBlockData*>(arg);
try
{
Database* dbb = data->existenceLock.lck_dbb;
AsyncContextHolder tdbb(dbb, FB_FUNCTION);
// Should we try to process AST?
if (!data->acceptAst)
return 0;
TipCache* cache = data->cache;
TraNumber oldest =
cache->m_tpcHeader->getHeader()->oldest_transaction.load(std::memory_order_relaxed);
// Is data block really old?
if (data->blockNumber >= oldest / cache->m_transactionsPerBlock)
return 0;
// Release shared memory
if (data->memory)
{
delete data->memory;
data->memory = NULL;
}
LCK_release(tdbb, &data->existenceLock);
}
catch (const Exception&)
{ }
return 0;
}
void TipCache::releaseSharedMemory(thread_db* tdbb, TraNumber oldest_old, TraNumber oldest_new)
{
Database* dbb = tdbb->getDatabase();
TpcBlockNumber lastInterestingBlockNumber = oldest_new / m_transactionsPerBlock;
// If we didn't cross block boundary - there is nothing to do.
// Note that due to the fuzziness of our caller's memory access to variables
// there is an unlikely possibility that we might lose one such event.
// This is not too bad, and next such event will clean things up.
if (oldest_old / m_transactionsPerBlock == lastInterestingBlockNumber)
return;
// Populate array of blocks that might be unmapped and deleted.
// We scan for blocks to clean up in descending order, but delete them in
// ascending order to ensure for robust operation.
PathName fileName;
HalfStaticArray<TpcBlockNumber, 16> blocksToCleanup;
for (TpcBlockNumber cleanupCounter = lastInterestingBlockNumber - SAFETY_GAP_BLOCKS;
cleanupCounter; cleanupCounter--)
{
TpcBlockNumber blockNumber = cleanupCounter - 1;
PathName fileName = StatusBlockData::makeSharedMemoryFileName(dbb, blockNumber, true);
struct stat st;
// If file is not found -- look no further
if (stat(fileName.c_str(), &st) != 0)
break;
blocksToCleanup.add(blockNumber);
}
if (blocksToCleanup.isEmpty())
return;
SyncLockGuard sync(&m_sync_status, SYNC_EXCLUSIVE, "TipCache::releaseSharedMemory");
while (blocksToCleanup.hasData())
{
TpcBlockNumber blockNumber = blocksToCleanup.pop();
if (m_blocks_memory.locate(blockNumber))
{
StatusBlockData* block = m_blocks_memory.current();
m_blocks_memory.fastRemove();
delete block;
}
// Signal other processes to release resources
Lock temp(tdbb, sizeof(TpcBlockNumber), LCK_tpc_block);
temp.setKey(blockNumber);
if (!LCK_lock(tdbb, &temp, LCK_EX, LCK_WAIT))
{
gds__log("TPC BUG: Unable to obtain cleanup lock for block %" UQUADFORMAT, blockNumber);
fb_assert(false);
break;
}
// Always delete file when EX lock is taken
PathName fileName = StatusBlockData::makeSharedMemoryFileName(dbb, blockNumber, true);
unlink(fileName.c_str());
LCK_release(tdbb, &temp);
}
}
SnapshotHandle TipCache::allocateSnapshotSlot()
{
// Try finding available slot
SnapshotList* snapshots = m_snapshots->getHeader();
// Scan previously used slots first
SnapshotHandle slotNumber;
ULONG slots_used = snapshots->slots_used.load(std::memory_order_relaxed);
for (slotNumber = snapshots->min_free_slot; slotNumber < slots_used; slotNumber++)
{
if (!snapshots->slots[slotNumber].attachment_id.load(std::memory_order_relaxed))
return slotNumber;
}
// See if we have some space left in the snapshots block
if (slotNumber < snapshots->slots_allocated.load(std::memory_order_relaxed))
{
snapshots->slots_used.store(slotNumber + 1, std::memory_order_release);
return slotNumber;
}
#ifdef HAVE_OBJECT_MAP
LocalStatus ls;
CheckStatusWrapper localStatus(&ls);
if (!m_snapshots->remapFile(&localStatus, m_snapshots->sh_mem_length_mapped * 2, true))
{
status_exception::raise(&localStatus);
}
snapshots = m_snapshots->getHeader();
snapshots->slots_allocated.store(
static_cast<ULONG>((m_snapshots->sh_mem_length_mapped - offsetof(SnapshotList, slots[0])) / sizeof(SnapshotData)),
std::memory_order_release);
#else
// NS: I do not intend to assign a code to this condition, because I think that we do not
// support platforms without HAVE_OBJECT_MAP capability, and the code below needs to be cleaned out
// sooner or later. And even if need to support such a platform suddenly appears we shall make it
// fail in remapFile code and not here.
(Arg::Gds(isc_random) <<
"Snapshots shared memory block is full on a platform that does not support shared memory remapping").raise();
#endif
fb_assert(slotNumber < snapshots->slots_allocated.load(std::memory_order_relaxed));
snapshots->slots_used.store(slotNumber + 1, std::memory_order_release);
return slotNumber;
}
void TipCache::remapSnapshots(bool sync)
{
// Can only be called on initialized TipCache
fb_assert(m_tpcHeader);
SnapshotList* snapshots = m_snapshots->getHeader();
if (snapshots->slots_allocated.load(std::memory_order_acquire) !=
(m_snapshots->sh_mem_length_mapped - offsetof(SnapshotList, slots[0])) / sizeof(SnapshotData))
{
SharedMutexGuard guard(m_snapshots, false);
if (sync)
guard.lock();
LocalStatus ls;
CheckStatusWrapper localStatus(&ls);
if (!m_snapshots->remapFile(&localStatus,
static_cast<ULONG>(
snapshots->slots_allocated.load(std::memory_order_relaxed) * sizeof(SnapshotData) +
offsetof(SnapshotList, slots[0])), false))
{
status_exception::raise(&localStatus);
}
}
}
SnapshotHandle TipCache::beginSnapshot(thread_db* tdbb, AttNumber attachmentId, CommitNumber& commitNumber)
{
// Can only be called on initialized TipCache
fb_assert(m_tpcHeader);
GlobalTpcHeader* header = m_tpcHeader->getHeader();
fb_assert(attachmentId);
// Lock mutex
SharedMutexGuard guard(m_snapshots);
// Remap snapshot list if it has been grown by someone else
remapSnapshots(false);
SnapshotList* snapshots = m_snapshots->getHeader();
if (commitNumber != 0)
{
ULONG slotsUsed = snapshots->slots_used.load(std::memory_order_relaxed);
bool found = false;
for (SnapshotHandle slotNumber = 0; slotNumber < slotsUsed; ++slotNumber)
{
if (snapshots->slots[slotNumber].attachment_id.load(std::memory_order_relaxed) != 0 &&
snapshots->slots[slotNumber].snapshot.load(std::memory_order_relaxed) == commitNumber)
{
found = true;
break;
}
}
if (!found)
ERR_post(Arg::Gds(isc_tra_snapshot_does_not_exist));
}
SnapshotHandle slotNumber = allocateSnapshotSlot();
// Note, that allocateSnapshotSlot might remap memory and thus invalidate pointers
snapshots = m_snapshots->getHeader();
// Store snapshot commit number and return handle
SnapshotData* slot = snapshots->slots + slotNumber;
if (commitNumber == 0)
commitNumber = header->latest_commit_number.load(std::memory_order_acquire);
slot->snapshot.store(commitNumber, std::memory_order_release);
// Only assign attachment_id after we completed all other work
slot->attachment_id.store(attachmentId, std::memory_order_release);
// And now move allocator watermark position after we used slot for sure
snapshots->min_free_slot = slotNumber + 1;
return slotNumber;
}
void TipCache::deallocateSnapshotSlot(SnapshotHandle slotNumber)
{
// Note: callers of this function assume that it cannot remap
// shared memory (as they keep shared memory pointers).
SnapshotList* snapshots = m_snapshots->getHeader();
// At first, make slot available for allocator (this is always safe)
if (snapshots->min_free_slot > slotNumber)
snapshots->min_free_slot = slotNumber;
SnapshotData* slot = snapshots->slots + slotNumber;
slot->snapshot.store(0, std::memory_order_release);
slot->attachment_id.store(0, std::memory_order_release);
// After we completed deallocation, update used slots count, if necessary
if (slotNumber == snapshots->slots_used.load(std::memory_order_relaxed) - 1)
{
do {
slot--;
} while (slot >= snapshots->slots && slot->attachment_id.load(std::memory_order_relaxed) == 0);
snapshots->slots_used.store(static_cast<ULONG>(slot - snapshots->slots + 1), std::memory_order_release);
}
}
void TipCache::endSnapshot(thread_db* tdbb, SnapshotHandle handle, AttNumber attachmentId)
{
// Can only be called on initialized TipCache
fb_assert(m_tpcHeader);
GlobalTpcHeader* header = m_tpcHeader->getHeader();
// Lock mutex
SharedMutexGuard guard(m_snapshots);
// We don't care to perform remap here, because we release a slot that was
// allocated by this process and we do not access any data past it during
// deallocation.
// Perform some sanity checks on a handle
SnapshotList* snapshots = m_snapshots->getHeader();
SnapshotData* slot = snapshots->slots + handle;