-
-
Notifications
You must be signed in to change notification settings - Fork 234
/
Copy pathnbak.cpp
1065 lines (881 loc) · 29.2 KB
/
nbak.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: nbak.cpp
* DESCRIPTION: Incremental backup technology
*
* The contents of this file are subject to the Initial
* Developer's 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.ibphoenix.com/main.nfs?a=ibphoenix&page=ibp_idpl.
*
* Software distributed under the License is distributed AS IS,
* 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 Nickolay Samofatov
* for the Firebird Open Source RDBMS project.
*
* Copyright (c) 2004 Nickolay Samofatov <[email protected]>
* and all contributors signed below.
*
* All Rights Reserved.
* Contributor(s):
*
* Roman Simakov <[email protected]>
* Khorsun Vladyslav <[email protected]>
*
*/
#include "firebird.h"
#include "jrd.h"
#include "nbak.h"
#include "ods.h"
#include "lck.h"
#include "cch.h"
#include "lck_proto.h"
#include "pag_proto.h"
#include "err_proto.h"
#include "cch_proto.h"
#include "../common/isc_proto.h"
#include "os/pio_proto.h"
#include "iberror.h"
#include "../yvalve/gds_proto.h"
#include "../common/os/guid.h"
#include "../common/os/isc_i_proto.h"
#include "../jrd/CryptoManager.h"
#include "../jrd/replication/Publisher.h"
#ifdef HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif
#ifdef HAVE_SYS_STAT_H
#include <sys/stat.h>
#endif
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef HAVE_ERRNO_H
#include <errno.h>
#endif
#ifdef NBAK_DEBUG
#include <stdarg.h>
IMPLEMENT_TRACE_ROUTINE(nbak_trace, "NBAK")
#endif
using namespace Jrd;
using namespace Firebird;
/******************************** NBackupStateLock ******************************/
NBackupStateLock::NBackupStateLock(thread_db* tdbb, MemoryPool& p, BackupManager* bakMan):
GlobalRWLock(tdbb, p, LCK_backup_database), backup_manager(bakMan)
{
}
bool NBackupStateLock::fetch(thread_db* tdbb)
{
backup_manager->endFlush();
NBAK_TRACE( ("backup_manager->endFlush()") );
if (!backup_manager->actualizeState(tdbb))
{
ERR_bugcheck_msg("Can't actualize backup state");
}
return true;
}
void NBackupStateLock::invalidate(thread_db* tdbb)
{
GlobalRWLock::invalidate(tdbb);
NBAK_TRACE( ("invalidate state stateLock(%p)", this) );
backup_manager->setState(Ods::hdr_nbak_unknown);
backup_manager->closeDelta(tdbb);
}
void NBackupStateLock::blockingAstHandler(thread_db* tdbb)
{
// master instance should not try to acquire localStateLock or enter "flush" mode
if (backup_manager->isMaster())
{
GlobalRWLock::blockingAstHandler(tdbb);
return;
}
// Ensure we have no dirty pages in local cache before releasing
// of state lock
if (!backup_manager->databaseFlushInProgress())
{
backup_manager->beginFlush();
NBAK_TRACE_AST( ("backup_manager->beginFlush()") );
Firebird::MutexUnlockGuard counterGuard(counterMutex, FB_FUNCTION);
CCH_flush_ast(tdbb);
NBAK_TRACE_AST(("database FLUSHED"));
}
{ // scope
Firebird::MutexUnlockGuard counterGuard(counterMutex, FB_FUNCTION);
backup_manager->stateBlocking = !backup_manager->localStateLock.tryBeginWrite(FB_FUNCTION);
if (backup_manager->stateBlocking)
return;
}
GlobalRWLock::blockingAstHandler(tdbb);
if (cachedLock->lck_physical == LCK_read)
backup_manager->endFlush();
backup_manager->localStateLock.endWrite();
}
/******************************** NBackupAllocLock ******************************/
NBackupAllocLock::NBackupAllocLock(thread_db* tdbb, MemoryPool& p, BackupManager* bakMan):
GlobalRWLock(tdbb, p, LCK_backup_alloc), backup_manager(bakMan)
{
}
bool NBackupAllocLock::fetch(thread_db* tdbb)
{
if (!backup_manager->actualizeAlloc(tdbb, true))
ERR_bugcheck_msg("Can't actualize alloc table");
return true;
}
void NBackupAllocLock::invalidate(thread_db* tdbb)
{
backup_manager->invalidateAlloc(tdbb);
GlobalRWLock::invalidate(tdbb);
NBAK_TRACE(("invalidate alloc table allocLock(%p)", this));
}
/******************************** BackupManager::StateWriteGuard ******************************/
BackupManager::StateWriteGuard::StateWriteGuard(thread_db* tdbb, Jrd::WIN* window)
: m_tdbb(tdbb), m_window(NULL), m_success(false)
{
Database* const dbb = tdbb->getDatabase();
Jrd::Attachment* const att = tdbb->getAttachment();
dbb->dbb_backup_manager->beginFlush();
CCH_flush(tdbb, FLUSH_ALL, 0); // Flush local cache to release all dirty pages
CCH_FETCH(tdbb, window, LCK_write, pag_header);
dbb->dbb_backup_manager->localStateLock.beginWrite(FB_FUNCTION);
if (!dbb->dbb_backup_manager->lockStateWrite(tdbb, LCK_WAIT))
{
dbb->dbb_backup_manager->localStateLock.endWrite();
ERR_bugcheck_msg("Can't lock state for write");
}
dbb->dbb_backup_manager->endFlush();
NBAK_TRACE(("backup state locked for write"));
m_window = window;
}
BackupManager::StateWriteGuard::~StateWriteGuard()
{
Database* const dbb = m_tdbb->getDatabase();
Jrd::Attachment* const att = m_tdbb->getAttachment();
// It is important to set state into nbak_state_unknown *before* release of state lock,
// otherwise someone could acquire state lock, fetch and modify some page before state will
// be set into unknown. But dirty page can't be written when backup state is unknown
// because write target (database or delta) is also unknown.
if (!m_success)
{
NBAK_TRACE( ("invalidate state") );
dbb->dbb_backup_manager->setState(Ods::hdr_nbak_unknown);
}
releaseHeader();
dbb->dbb_backup_manager->unlockStateWrite(m_tdbb);
dbb->dbb_backup_manager->localStateLock.endWrite();
}
void BackupManager::StateWriteGuard::releaseHeader()
{
if (m_window)
{
CCH_RELEASE(m_tdbb, m_window);
m_window = NULL;
}
}
/********************************** CORE LOGIC ********************************/
void BackupManager::generateFilename()
{
diff_name = database->dbb_filename + ".delta";
explicit_diff_name = false;
}
void BackupManager::openDelta(thread_db* tdbb)
{
fb_assert(!diff_file);
diff_file = PIO_open(tdbb, diff_name, diff_name);
if (database->dbb_flags & (DBB_force_write | DBB_no_fs_cache))
{
setForcedWrites(database->dbb_flags & DBB_force_write,
database->dbb_flags & DBB_no_fs_cache);
}
}
void BackupManager::closeDelta(thread_db* tdbb)
{
if (diff_file)
{
PIO_flush(tdbb, diff_file);
PIO_close(diff_file);
diff_file = NULL;
}
}
// Initialize and open difference file for writing
void BackupManager::beginBackup(thread_db* tdbb)
{
NBAK_TRACE(("beginBackup"));
SET_TDBB(tdbb);
// Check for raw device
if ((!explicit_diff_name) && database->onRawDevice()) {
ERR_post(Arg::Gds(isc_need_difference));
}
MasterGuard masterGuard(*this);
WIN window(HEADER_PAGE_NUMBER);
StateWriteGuard stateGuard(tdbb, &window);
Ods::header_page* header = (Ods::header_page*) window.win_buffer;
// Check state
if (backup_state != Ods::hdr_nbak_normal)
{
NBAK_TRACE(("begin backup - invalid state %d", backup_state));
stateGuard.setSuccess();
return;
}
// Check crypt state
if (header->hdr_flags & Ods::hdr_crypt_process)
{
NBAK_TRACE(("begin backup - crypt thread runs"));
stateGuard.setSuccess();
ERR_post(Arg::Gds(isc_wish_list) << Arg::Gds(isc_random) <<
"Cannot begin backup: please wait for crypt thread completion");
}
try
{
// Create file
NBAK_TRACE(("Creating difference file %s", diff_name.c_str()));
diff_file = PIO_create(tdbb, diff_name, true, false);
}
catch (const Firebird::Exception&)
{
// no reasons to set it to unknown if we just failed to create difference file
stateGuard.setSuccess();
backup_state = Ods::hdr_nbak_normal;
throw;
}
{ // logical scope
if (database->dbb_flags & (DBB_force_write | DBB_no_fs_cache))
{
setForcedWrites(database->dbb_flags & DBB_force_write,
database->dbb_flags & DBB_no_fs_cache);
}
#ifdef UNIX
// adjust difference file access rights to make it match main DB ones
if (diff_file && geteuid() == 0)
{
struct STAT st;
PageSpace* pageSpace = database->dbb_page_manager.findPageSpace(DB_PAGE_SPACE);
const char* func = NULL;
{
jrd_file* file = pageSpace->file;
ReadLockGuard readGuard(file->fil_desc_lock, FB_FUNCTION);
if (os_utils::fstat(file->fil_desc, &st) != 0)
{
func = "fstat";
}
}
while (!func && fchown(diff_file->fil_desc, st.st_uid, st.st_gid) != 0)
{
if (errno != EINTR)
func = "fchown";
}
while (!func && fchmod(diff_file->fil_desc, st.st_mode) != 0)
{
if (errno != EINTR)
func = "fchmod";
}
if (func)
{
stateGuard.setSuccess();
Firebird::system_call_failed::raise(func);
}
}
#endif
// Zero out first page (empty allocation table)
BufferDesc temp_bdb(database->dbb_bcb);
temp_bdb.bdb_page = 0;
temp_bdb.bdb_buffer = reinterpret_cast<Ods::pag*>(alloc_buffer);
memset(alloc_buffer, 0, database->dbb_page_size);
if (!PIO_write(tdbb, diff_file, &temp_bdb, temp_bdb.bdb_buffer, tdbb->tdbb_status_vector))
ERR_punt();
NBAK_TRACE(("Set backup state in header"));
Guid guid;
GenerateGuid(&guid);
// Set state in database header page. All changes are written to main database file yet.
CCH_MARK_MUST_WRITE(tdbb, &window);
const int newState = Ods::hdr_nbak_stalled; // Should be USHORT?
header->hdr_flags = (header->hdr_flags & ~Ods::hdr_backup_mask) | newState;
const ULONG adjusted_scn = ++header->hdr_header.pag_scn; // Generate new SCN
PAG_replace_entry_first(tdbb, header, Ods::HDR_backup_guid, sizeof(guid),
reinterpret_cast<const UCHAR*>(&guid));
REPL_journal_switch(tdbb);
stateGuard.releaseHeader();
stateGuard.setSuccess();
backup_state = newState;
current_scn = adjusted_scn;
// All changes go to the difference file now
}
}
// Determine actual DB size (raw devices support)
ULONG BackupManager::getPageCount(thread_db* tdbb)
{
if (backup_state != Ods::hdr_nbak_stalled)
{
// calculate pages only when database is locked for backup:
// other case such service is just dangerous
return 0;
}
return PAG_page_count(tdbb);
}
bool BackupManager::extendDatabase(thread_db* tdbb)
{
if (!alloc_table)
{
LocalAllocWriteGuard localAllocGuard(this);
actualizeAlloc(tdbb, false);
}
ULONG maxPage = 0;
{
LocalAllocReadGuard localAllocGuard(this);
AllocItemTree::Accessor all(alloc_table);
if (all.getFirst())
{
do
{
const ULONG pg = all.current().db_page;
if (maxPage < pg)
maxPage = pg;
} while (all.getNext());
}
}
PageSpace *pgSpace = database->dbb_page_manager.findPageSpace(DB_PAGE_SPACE);
ULONG maxAllocPage = pgSpace->maxAlloc();
if (maxAllocPage >= maxPage)
return true;
if (!pgSpace->extend(tdbb, maxPage, true))
return false;
maxAllocPage = pgSpace->maxAlloc();
while (maxAllocPage < maxPage)
{
const USHORT ret = PIO_init_data(tdbb, pgSpace->file, tdbb->tdbb_status_vector,
maxAllocPage, 256);
if (ret != 256)
return false;
maxAllocPage += ret;
}
return true;
}
// Merge difference file to main files (if needed) and unlink() difference
// file then. If merge is already in progress method silently returns and
// does nothing (so it can be used for recovery on database startup).
void BackupManager::endBackup(thread_db* tdbb, bool recover)
{
NBAK_TRACE(("end_backup, recover=%i", recover));
// Check for recover
GlobalRWLock endLock(tdbb, *database->dbb_permanent, LCK_backup_end, false);
if (!endLock.lockWrite(tdbb, LCK_NO_WAIT))
{
// Someboby holds write lock on LCK_backup_end. We need not to do end_backup
return;
}
MasterGuard masterGuard(*this);
// STEP 1. Change state in header to "merge"
WIN window(HEADER_PAGE_NUMBER);
Ods::header_page* header;
#ifdef NBAK_DEBUG
ULONG adjusted_scn; // We use this value to prevent race conditions.
// They are possible because we release state lock
// for some instants and anything is possible at
// that times.
#endif
try
{
// Check state under PR lock of backup state for speed
{ // scope
StateReadGuard stateGuard(tdbb);
// Nobody is doing end_backup but database isn't in merge state.
if ( (recover || backup_state != Ods::hdr_nbak_stalled) && (backup_state != Ods::hdr_nbak_merge ) )
{
NBAK_TRACE(("invalid state %d", backup_state));
endLock.unlockWrite(tdbb);
return;
}
if (backup_state == Ods::hdr_nbak_stalled && !extendDatabase(tdbb))
status_exception::raise(tdbb->tdbb_status_vector);
}
// Here backup state can be changed. Need to check it again after lock
StateWriteGuard stateGuard(tdbb, &window);
if ( (recover || backup_state != Ods::hdr_nbak_stalled) && (backup_state != Ods::hdr_nbak_merge ) )
{
stateGuard.setSuccess();
NBAK_TRACE(("invalid state %d", backup_state));
endLock.unlockWrite(tdbb);
return;
}
if (!extendDatabase(tdbb))
{
stateGuard.setSuccess();
status_exception::raise(tdbb->tdbb_status_vector);
}
header = (Ods::header_page*) window.win_buffer;
NBAK_TRACE(("difference file %s, current backup state is %d", diff_name.c_str(), backup_state));
// Set state in database header
backup_state = Ods::hdr_nbak_merge;
#ifdef NBAK_DEBUG
adjusted_scn =
#endif
++current_scn;
NBAK_TRACE(("New state is getting to become %d", backup_state));
CCH_MARK_MUST_WRITE(tdbb, &window);
// Generate new SCN
header->hdr_header.pag_scn = current_scn;
NBAK_TRACE(("new SCN=%d is getting written to header", header->hdr_header.pag_scn));
// Adjust state
header->hdr_flags = (header->hdr_flags & ~Ods::hdr_backup_mask) | backup_state;
NBAK_TRACE(("Setting state %d in header page is over", backup_state));
stateGuard.setSuccess();
}
catch (const Firebird::Exception&)
{
endLock.unlockWrite(tdbb);
throw;
}
// STEP 2. Merging database and delta
// Here comes the dirty work. We need to reapply all changes from difference file to database
// Release write state lock and get read lock.
// Merge process should not inhibit normal operations.
try
{
NBAK_TRACE(("database locked to merge"));
StateReadGuard stateGuard(tdbb);
NBAK_TRACE(("Merge. State=%d, current_scn=%d, adjusted_scn=%d",
backup_state, current_scn, adjusted_scn));
{ // scope
LocalAllocWriteGuard localAllocGuard(this);
// In merge mode allocation table can not be changed, so we don't
// need to acquire global allocLock.
actualizeAlloc(tdbb, true);
}
LocalAllocReadGuard localAllocGuard(this);
NBAK_TRACE(("Merge. Alloc table is actualized."));
AllocItemTree::Accessor all(alloc_table);
if (all.getFirst())
{
int n = 0;
do {
JRD_reschedule(tdbb);
WIN window2(DB_PAGE_SPACE, all.current().db_page);
NBAK_TRACE(("Merge page %d, diff=%d", all.current().db_page, all.current().diff_page));
Ods::pag* page = CCH_FETCH(tdbb, &window2, LCK_write, pag_undefined);
NBAK_TRACE(("Merge: page %d is fetched", all.current().db_page));
if (page->pag_scn != current_scn)
{
CCH_MARK_SYSTEM(tdbb, &window2);
NBAK_TRACE(("Merge: page %d is marked", all.current().db_page));
}
CCH_RELEASE(tdbb, &window2);
NBAK_TRACE(("Merge: page %d is released", all.current().db_page));
if (++n == 512)
{
CCH_flush(tdbb, FLUSH_SYSTEM, 0);
n = 0;
}
} while (all.getNext());
}
CCH_flush(tdbb, FLUSH_ALL, 0);
NBAK_TRACE(("Merging is over. Database unlocked"));
}
catch (const Firebird::Exception&)
{
endLock.unlockWrite(tdbb);
throw;
}
// STEP 3. Change state in header to "normal"
// We finished. We need to reflect it in our database header page
try {
window.win_page = HEADER_PAGE;
window.win_flags = 0;
StateWriteGuard stateGuard(tdbb, &window);
header = (Ods::header_page*) window.win_buffer;
// Set state in database header
backup_state = Ods::hdr_nbak_normal;
CCH_MARK_MUST_WRITE(tdbb, &window);
// Adjust state
header->hdr_flags = (header->hdr_flags & ~Ods::hdr_backup_mask) | backup_state;
NBAK_TRACE(("Set state %d in header page", backup_state));
// Generate new SCN
header->hdr_header.pag_scn = ++current_scn;
NBAK_TRACE(("new SCN=%d is getting written to header", header->hdr_header.pag_scn));
stateGuard.releaseHeader();
stateGuard.setSuccess();
// Page allocation table cache is no longer valid
NBAK_TRACE(("Dropping alloc table"));
{
LocalAllocWriteGuard localAllocGuard(this);
delete alloc_table;
alloc_table = NULL;
last_allocated_page = 0;
if (!allocLock->tryReleaseLock(tdbb))
ERR_bugcheck_msg("There are holders of alloc_lock after end_backup finish");
}
closeDelta(tdbb);
unlink(diff_name.c_str());
NBAK_TRACE(("backup is over"));
endLock.unlockWrite(tdbb);
}
catch (const Firebird::Exception&)
{
endLock.unlockWrite(tdbb);
throw;
}
return;
}
void BackupManager::initializeAlloc(thread_db* tdbb)
{
StateReadGuard stateGuard(tdbb);
if (getState() != Ods::hdr_nbak_normal)
actualizeAlloc(tdbb, false);
}
bool BackupManager::actualizeAlloc(thread_db* tdbb, bool haveGlobalLock)
{
// localAllocLock must be already locked for write here !
// Difference file pointer pages have one ULONG as number of pages allocated on the page and
// then go physical numbers of pages from main database file. Offsets of numbers correspond
// to difference file pages.
const size_t PAGES_PER_ALLOC_PAGE = database->dbb_page_size / sizeof(ULONG) - 1;
FbStatusVector *status_vector = tdbb->tdbb_status_vector;
try {
NBAK_TRACE(("actualize_alloc last_allocated_page=%d alloc_table=%p",
last_allocated_page, alloc_table));
// For SuperServer this routine is really executed only at database startup when
// it has exlock or when exclusive access to database is enabled
if (!alloc_table)
alloc_table = FB_NEW_POOL(*database->dbb_permanent) AllocItemTree(database->dbb_permanent);
while (true)
{
BufferDesc temp_bdb(database->dbb_bcb);
// Get offset of pointer page. We can do so because page sizes are powers of 2
temp_bdb.bdb_page = last_allocated_page & ~PAGES_PER_ALLOC_PAGE;
temp_bdb.bdb_buffer = reinterpret_cast<Ods::pag*>(alloc_buffer);
if (!PIO_read(tdbb, diff_file, &temp_bdb, temp_bdb.bdb_buffer, status_vector)) {
return false;
}
// If we have not acquired global allocLock, don't read last page of allocation
// table as it could be modified concurrently. Lets read it later when global
// alloc lock will be acquired.
if (!haveGlobalLock && (alloc_buffer[0] != PAGES_PER_ALLOC_PAGE))
break;
for (ULONG i = last_allocated_page - temp_bdb.bdb_page.getPageNum(); i < alloc_buffer[0]; i++)
{
NBAK_TRACE(("alloc item page=%d, diff=%d", alloc_buffer[i + 1], temp_bdb.bdb_page.getPageNum() + i + 1));
if (!alloc_table->add(AllocItem(alloc_buffer[i + 1], temp_bdb.bdb_page.getPageNum() + i + 1)))
{
database->dbb_flags |= DBB_bugcheck;
ERR_build_status(status_vector,
Arg::Gds(isc_bug_check) << Arg::Str("Duplicated item in allocation table detected"));
return false;
}
}
last_allocated_page = temp_bdb.bdb_page.getPageNum() + alloc_buffer[0];
if (alloc_buffer[0] == PAGES_PER_ALLOC_PAGE)
last_allocated_page++; // if page is full adjust position for next pointer page
else
break; // We finished reading allocation table
}
}
catch (const Firebird::Exception& ex)
{
// Handle out of memory error, etc
delete alloc_table;
ex.stuffException(status_vector);
alloc_table = NULL;
last_allocated_page = 0;
return false;
}
allocIsValid = haveGlobalLock;
return true;
}
ULONG BackupManager::findPageIndex(thread_db* tdbb, ULONG db_page)
{
// localAllocLock must be already locked here
NBAK_TRACE(("find_page_index"));
if (!alloc_table)
return 0;
AllocItemTree::Accessor a(alloc_table);
ULONG diff_page = a.locate(db_page) ? a.current().diff_page : 0;
return diff_page;
}
// Return page index in difference file that can be used in
// writeDifference call later.
ULONG BackupManager::getPageIndex(thread_db* tdbb, ULONG db_page)
{
NBAK_TRACE(("get_page_index"));
{
LocalAllocReadGuard localAllocGuard(this);
const ULONG diff_page = findPageIndex(tdbb, db_page);
if (diff_page || backup_state == Ods::hdr_nbak_merge && allocIsValid)
return diff_page;
}
LocalAllocWriteGuard localAllocGuard(this);
GlobalAllocReadGuard globalAllocGuard(tdbb, this);
return findPageIndex(tdbb, db_page);
}
// Mark next difference page as used by some database page
ULONG BackupManager::allocateDifferencePage(thread_db* tdbb, ULONG db_page)
{
LocalAllocWriteGuard localAllocGuard(this);
// This page may be allocated while we wait for a local lock above
if (ULONG diff_page = findPageIndex(tdbb, db_page)) {
return diff_page;
}
GlobalAllocWriteGuard globalAllocGuard(tdbb, this);
// This page may be allocated by other process
if (ULONG diff_page = findPageIndex(tdbb, db_page)) {
return diff_page;
}
NBAK_TRACE(("allocate_difference_page"));
fb_assert(last_allocated_page % (database->dbb_page_size / sizeof(ULONG)) == alloc_buffer[0]);
FbStatusVector* status_vector = tdbb->tdbb_status_vector;
// Grow file first. This is done in such order to keep difference
// file consistent in case of write error. We should always be able
// to read next alloc page when previous one is full.
BufferDesc temp_bdb(database->dbb_bcb);
temp_bdb.bdb_page = last_allocated_page + 1;
temp_bdb.bdb_buffer = reinterpret_cast<Ods::pag*>(empty_buffer);
if (!PIO_write(tdbb, diff_file, &temp_bdb, temp_bdb.bdb_buffer, status_vector))
return 0;
const bool alloc_page_full = alloc_buffer[0] == database->dbb_page_size / sizeof(ULONG) - 2;
if (alloc_page_full)
{
// Pointer page is full. Its time to create new one.
temp_bdb.bdb_page = last_allocated_page + 2;
temp_bdb.bdb_buffer = reinterpret_cast<Ods::pag*>(empty_buffer);
if (!PIO_write(tdbb, diff_file, &temp_bdb, temp_bdb.bdb_buffer, status_vector))
return 0;
}
// Write new item to the allocation table
temp_bdb.bdb_page = last_allocated_page & ~(database->dbb_page_size / sizeof(ULONG) - 1);
temp_bdb.bdb_buffer = reinterpret_cast<Ods::pag*>(alloc_buffer);
alloc_buffer[++alloc_buffer[0]] = db_page;
if (!PIO_write(tdbb, diff_file, &temp_bdb, temp_bdb.bdb_buffer, status_vector))
return 0;
last_allocated_page++;
// Register new page in the alloc table
try
{
alloc_table->add(AllocItem(db_page, last_allocated_page));
}
catch (const Firebird::Exception& ex)
{
// Handle out of memory error
delete alloc_table;
alloc_table = NULL;
last_allocated_page = 0;
ex.stuffException(status_vector);
return 0;
}
// Adjust buffer and counters if we allocated new alloc page earlier
if (alloc_page_full)
{
last_allocated_page++;
memset(alloc_buffer, 0, database->dbb_page_size);
return last_allocated_page - 1;
}
return last_allocated_page;
}
bool BackupManager::writeDifference(thread_db* tdbb, FbStatusVector* status, ULONG diff_page, Ods::pag* page)
{
if (!diff_page)
{
// We should never be here but if it happens let not overwrite first allocation
// page with garbage.
(Arg::Gds(isc_random) << "Can't allocate difference page").copyTo(status);
return false;
}
NBAK_TRACE(("write_diff page=%d, diff=%d", page->pag_pageno, diff_page));
BufferDesc temp_bdb(database->dbb_bcb);
temp_bdb.bdb_page = diff_page;
temp_bdb.bdb_buffer = page;
// Check that diff page is not allocation page
fb_assert(diff_page % (database->dbb_page_size / sizeof(ULONG)));
class Pio : public CryptoManager::IOCallback
{
public:
Pio(jrd_file* p_file, BufferDesc* p_bdb)
: file(p_file), bdb(p_bdb)
{ }
bool callback(thread_db* tdbb, FbStatusVector* sv, Ods::pag* page)
{
return PIO_write(tdbb, file, bdb, page, sv);
}
private:
jrd_file* file;
BufferDesc* bdb;
};
Pio io(diff_file, &temp_bdb);
if (!database->dbb_crypto_manager->write(tdbb, status, page, &io))
return false;
return true;
}
bool BackupManager::readDifference(thread_db* tdbb, ULONG diff_page, Ods::pag* page)
{
BufferDesc temp_bdb(database->dbb_bcb);
temp_bdb.bdb_page = diff_page;
temp_bdb.bdb_buffer = page;
class Pio : public CryptoManager::IOCallback
{
public:
Pio(jrd_file* p_file, BufferDesc* p_bdb)
: file(p_file), bdb(p_bdb)
{ }
bool callback(thread_db* tdbb, FbStatusVector* sv, Ods::pag* page)
{
return PIO_read(tdbb, file, bdb, page, sv);
}
private:
jrd_file* file;
BufferDesc* bdb;
};
Pio io(diff_file, &temp_bdb);
if (!database->dbb_crypto_manager->read(tdbb, tdbb->tdbb_status_vector, page, &io))
return false;
NBAK_TRACE(("read_diff page=%d, diff=%d", page->pag_pageno, diff_page));
return true;
}
void BackupManager::flushDifference(thread_db* tdbb)
{
PIO_flush(tdbb, diff_file);
}
void BackupManager::setForcedWrites(const bool forceWrite, const bool notUseFSCache)
{
if (diff_file)
PIO_force_write(diff_file, forceWrite, notUseFSCache);
}
BackupManager::BackupManager(thread_db* tdbb, Database* _database, int ini_state) :
dbCreating(false), database(_database), diff_file(NULL), alloc_table(NULL),
last_allocated_page(0), temp_buffers_space(*database->dbb_permanent),
current_scn(0), diff_name(*database->dbb_permanent),
explicit_diff_name(false), flushInProgress(false), shutDown(false), allocIsValid(false),
master(false), stateBlocking(false),
stateLock(FB_NEW_POOL(*database->dbb_permanent) NBackupStateLock(tdbb, *database->dbb_permanent, this)),
allocLock(FB_NEW_POOL(*database->dbb_permanent) NBackupAllocLock(tdbb, *database->dbb_permanent, this))
{
// Allocate various database page buffers needed for operation
// Align it at sector boundary for faster IO (also guarantees correct alignment for ULONG later)
UCHAR* temp_buffers = reinterpret_cast<UCHAR*>
(temp_buffers_space.getAlignedBuffer(database->dbb_page_size * 3, database->getIOBlockSize()));
backup_state = ini_state;
empty_buffer = reinterpret_cast<ULONG*>(temp_buffers);
spare_buffer = reinterpret_cast<ULONG*>(temp_buffers + database->dbb_page_size);
alloc_buffer = reinterpret_cast<ULONG*>(temp_buffers + database->dbb_page_size * 2);
NBAK_TRACE(("Create BackupManager, database=%s", database->dbb_filename.c_str()));
}
BackupManager::~BackupManager()
{
delete stateLock;
delete allocLock;
delete alloc_table;
}
void BackupManager::setDifference(thread_db* tdbb, const char* filename)
{
SET_TDBB(tdbb);
if (filename)
{
WIN window(HEADER_PAGE_NUMBER);
Ods::header_page* header =
(Ods::header_page*) CCH_FETCH(tdbb, &window, LCK_write, pag_header);
CCH_MARK_MUST_WRITE(tdbb, &window);
PAG_replace_entry_first(tdbb, header, Ods::HDR_difference_file,
static_cast<USHORT>(strlen(filename)), reinterpret_cast<const UCHAR*>(filename));
CCH_RELEASE(tdbb, &window);
diff_name = filename;
explicit_diff_name = true;
}
else
{
PAG_delete_clump_entry(tdbb, Ods::HDR_difference_file);
generateFilename();
}
}
bool BackupManager::actualizeState(thread_db* tdbb)
{
// State is unknown. We need to read it from the disk.
// We cannot use CCH for this because of likely recursion.
NBAK_TRACE(("actualizeState: current_state=%i", backup_state));
if (dbCreating)
{
backup_state = Ods::hdr_nbak_normal;
return true;
}
SET_TDBB(tdbb);
FbStatusVector* status = tdbb->tdbb_status_vector;
// Read original page from database file or shadows.
SSHORT retryCount = 0;
Ods::header_page* header = reinterpret_cast<Ods::header_page*>(spare_buffer);
BufferDesc temp_bdb(database->dbb_bcb);
temp_bdb.bdb_page = HEADER_PAGE_NUMBER;
temp_bdb.bdb_buffer = &header->hdr_header;
PageSpace* pageSpace = database->dbb_page_manager.findPageSpace(DB_PAGE_SPACE);
fb_assert(pageSpace);
jrd_file* file = pageSpace->file;
// It's header page, never encrypted
while (!PIO_read(tdbb, file, &temp_bdb, temp_bdb.bdb_buffer, status))
{
if (!CCH_rollover_to_shadow(tdbb, database, file, false))
{
NBAK_TRACE(("Shadow change error"));
return false;
}
if (file != pageSpace->file)
file = pageSpace->file;
else
{
if (retryCount++ == 3)
{
NBAK_TRACE(("IO error"));
return false;
}
}