-
Notifications
You must be signed in to change notification settings - Fork 151
/
db.cpp
2930 lines (2624 loc) · 117 KB
/
db.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
/*************************************************************************
*
* Copyright 2016 Realm Inc.
*
* Licensed under the Apache License, Version 2.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.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**************************************************************************/
#include <realm/transaction.hpp>
#include <algorithm>
#include <atomic>
#include <cerrno>
#include <fcntl.h>
#include <iostream>
#include <mutex>
#include <sstream>
#include <type_traits>
#include <random>
#include <deque>
#include <thread>
#include <chrono>
#include <condition_variable>
#include <realm/disable_sync_to_disk.hpp>
#include <realm/group_writer.hpp>
#include <realm/impl/simulated_failure.hpp>
#include <realm/replication.hpp>
#include <realm/util/errno.hpp>
#include <realm/util/features.h>
#include <realm/util/file_mapper.hpp>
#include <realm/util/safe_int_ops.hpp>
#include <realm/util/scope_exit.hpp>
#include <realm/util/thread.hpp>
#include <realm/util/to_string.hpp>
#ifndef _WIN32
#include <sys/wait.h>
#include <sys/time.h>
#include <unistd.h>
#else
#include <windows.h>
#include <process.h>
#endif
// #define REALM_ENABLE_LOGFILE
using namespace realm;
using namespace realm::util;
using Durability = DBOptions::Durability;
namespace {
// value change
// --------------------
// 4 Unknown
// 5 Introduction of SharedInfo::file_format_version and
// SharedInfo::history_type.
// 6 Using new robust mutex emulation where applicable
// 7 Introducing `commit_in_critical_phase` and `sync_agent_present`, and
// changing `daemon_started` and `daemon_ready` from 1-bit to 8-bit
// fields.
// 8 Placing the commitlog history inside the Realm file.
// 9 Fair write transactions requires an additional condition variable,
// `write_fairness`
// 10 Introducing SharedInfo::history_schema_version.
// 11 New impl of InterprocessCondVar on windows.
// 12 Change `number_of_versions` to an atomic rather than guarding it
// with a lock.
// 13 New impl of VersionList and added mutex for it (former RingBuffer)
// 14 Added field for tracking ongoing encrypted writes
const uint_fast16_t g_shared_info_version = 14;
struct VersionList {
// the VersionList is an array of ReadCount structures.
// it is placed in the "lock-file" and accessed via memory mapping
struct ReadCount {
uint64_t version;
uint64_t filesize;
uint64_t current_top;
uint32_t count_live;
uint32_t count_frozen;
uint32_t count_full;
bool is_active()
{
return version != 0;
}
void deactivate()
{
version = 0;
count_live = count_frozen = count_full = 0;
}
void activate(uint64_t v)
{
version = v;
}
};
void reserve(uint32_t size) noexcept
{
for (auto i = entries; i < size; ++i)
data()[i].deactivate();
if (size > entries) {
// Fence preventing downward motion of above writes
std::atomic_signal_fence(std::memory_order_release);
entries = size;
}
}
VersionList() noexcept
{
newest = nil; // empty
entries = 0;
reserve(init_readers_size);
}
static size_t compute_required_space(uint_fast32_t num_entries) noexcept
{
// get space required for given number of entries beyond the initial count.
// NB: this not the size of the VersionList, it is the size minus whatever was
// the initial size.
return sizeof(ReadCount) * (num_entries - init_readers_size);
}
unsigned int capacity() const noexcept
{
return entries;
}
ReadCount& get(uint_fast32_t idx) noexcept
{
return data()[idx];
}
ReadCount& get_newest() noexcept
{
return get(newest);
}
// returns nullptr if all entries are in use
ReadCount* try_allocate_entry(uint64_t top, uint64_t size, uint64_t version)
{
auto i = allocating.load();
if (i == newest.load()) {
// if newest != allocating we are recovering from a crash and MUST complete the earlier allocation
// but if not, find lowest free entry by linear search.
uint32_t k = 0;
while (k < entries && data()[k].is_active()) {
++k;
}
if (k == entries)
return nullptr; // no free entries
allocating.exchange(k); // barrier: prevent upward movement of instructions below
i = k;
}
auto& rc = data()[i];
REALM_ASSERT(rc.count_frozen == 0);
REALM_ASSERT(rc.count_live == 0);
REALM_ASSERT(rc.count_full == 0);
rc.current_top = top;
rc.filesize = size;
rc.activate(version);
newest.store(i); // barrier: prevent downward movement of instructions above
return &rc;
}
uint32_t index_of(const ReadCount& rc) noexcept
{
return (uint32_t)(&rc - data());
}
void free_entry(ReadCount* rc) noexcept
{
rc->current_top = rc->filesize = -1ULL; // easy to recognize in debugger
rc->deactivate();
}
// This method resets the version list to an empty state, then allocates an entry.
// Precondition: This should *only* be done if the caller has established that she
// is the only thread/process that has access to the VersionList. It is currently
// called from init_versioning(), which is called by DB::open() under the
// condition that it is the session initiator and under guard by the control mutex,
// thus ensuring the precondition. It is also called from compact() in a similar situation.
// It is most likely not suited for any other use.
ReadCount& init_versioning(uint64_t top, uint64_t filesize, uint64_t version) noexcept
{
newest = nil;
allocating = 0;
auto t_free = entries;
entries = 0;
reserve(t_free);
return *try_allocate_entry(top, filesize, version);
}
void purge_versions(uint64_t& oldest_live_v, TopRefMap& top_refs, bool& any_new_unreachables)
{
oldest_live_v = std::numeric_limits<uint64_t>::max();
auto oldest_full_v = std::numeric_limits<uint64_t>::max();
any_new_unreachables = false;
// correct case where an earlier crash may have left the entry at 'allocating' partially initialized:
const auto index_of_newest = newest.load();
if (auto a = allocating.load(); a != index_of_newest) {
data()[a].deactivate();
}
// determine fully locked versions - after one of those all versions are considered live.
for (auto* rc = data(); rc < data() + entries; ++rc) {
if (!rc->is_active())
continue;
if (rc->count_full) {
if (rc->version < oldest_full_v)
oldest_full_v = rc->version;
}
}
// collect reachable versions and determine oldest live reachable version
// (oldest reachable version is the first entry in the top_refs map, so no need to find it explicitly)
for (auto* rc = data(); rc < data() + entries; ++rc) {
if (!rc->is_active())
continue;
if (rc->count_frozen || rc->count_live || rc->version >= oldest_full_v) {
// entry is still reachable
top_refs.emplace(rc->version, VersionInfo{to_ref(rc->current_top), to_ref(rc->filesize)});
}
if (rc->count_live || rc->version >= oldest_full_v) {
if (rc->version < oldest_live_v)
oldest_live_v = rc->version;
}
}
// we must have found at least one reachable version
REALM_ASSERT(top_refs.size());
// free unreachable entries and determine if we want to trigger backdating
uint64_t oldest_v = top_refs.begin()->first;
for (auto* rc = data(); rc < data() + entries; ++rc) {
if (!rc->is_active())
continue;
if (rc->count_frozen == 0 && rc->count_live == 0 && rc->version < oldest_full_v) {
// entry is becoming unreachable.
// if it is also younger than a reachable version, then set 'any_new_unreachables' to trigger
// backdating
if (rc->version > oldest_v) {
any_new_unreachables = true;
}
REALM_ASSERT(index_of(*rc) != index_of_newest);
free_entry(rc);
}
}
REALM_ASSERT(oldest_v != std::numeric_limits<uint64_t>::max());
REALM_ASSERT(oldest_live_v != std::numeric_limits<uint64_t>::max());
}
#if REALM_DEBUG
void dump()
{
util::format(std::cout, "VersionList has %1 entries: \n", entries);
for (auto* rc = data(); rc < data() + entries; ++rc) {
util::format(std::cout, "[%1]: version %2, live: %3, full: %4, frozen: %5\n", index_of(*rc), rc->version,
rc->count_live, rc->count_full, rc->count_frozen);
}
}
#endif // REALM_DEBUG
constexpr static uint32_t nil = (uint32_t)-1;
const static int init_readers_size = 32;
uint32_t entries;
std::atomic<uint32_t> allocating; // atomic for crash safety, not threading
std::atomic<uint32_t> newest; // atomic for crash safety, not threading
// IMPORTANT: The actual data comprising the version list MUST BE PLACED LAST in
// the VersionList structure, as the data area is extended at run time.
// Similarly, the VersionList must be the final element of the SharedInfo structure.
// IMPORTANT II:
// To ensure proper alignment across all platforms, the SharedInfo structure
// should NOT have a stricter alignment requirement than the ReadCount structure.
ReadCount m_data[init_readers_size];
// Silence UBSan errors about out-of-bounds reads on m_data by casting to a pointer
ReadCount* data() noexcept
{
return m_data;
}
const ReadCount* data() const noexcept
{
return m_data;
}
};
// Using lambda rather than function so that shared_ptr shared state doesn't need to hold a function pointer.
constexpr auto TransactionDeleter = [](Transaction* t) {
t->close();
delete t;
};
template <typename... Args>
TransactionRef make_transaction_ref(Args&&... args)
{
return TransactionRef(new Transaction(std::forward<Args>(args)...), TransactionDeleter);
}
} // anonymous namespace
namespace realm {
/// The structure of the contents of the per session `.lock` file. Note that
/// this file is transient in that it is recreated/reinitialized at the
/// beginning of every session. A session is any sequence of temporally
/// overlapping openings of a particular Realm file via DB objects. For
/// example, if there are two DB objects, A and B, and the file is
/// first opened via A, then opened via B, then closed via A, and finally closed
/// via B, then the session streaches from the opening via A to the closing via
/// B.
///
/// IMPORTANT: Remember to bump `g_shared_info_version` if anything is changed
/// in the memory layout of this class, or if the meaning of any of the stored
/// values change.
///
/// Members `init_complete`, `shared_info_version`, `size_of_mutex`, and
/// `size_of_condvar` may only be modified only while holding an exclusive lock
/// on the file, and may be read only while holding a shared (or exclusive) lock
/// on the file. All other members (except for the VersionList which has its own mutex)
/// may be accessed only while holding a lock on `controlmutex`.
///
/// SharedInfo must be 8-byte aligned. On 32-bit Apple platforms, mutexes store their
/// alignment as part of the mutex state. We're copying the SharedInfo (including
/// embedded but alway unlocked mutexes) and it must retain the same alignment
/// throughout.
struct alignas(8) DB::SharedInfo {
/// Indicates that initialization of the lock file was completed
/// sucessfully.
///
/// CAUTION: This member must never move or change type, as that would
/// compromize safety of the the session initiation process.
std::atomic<uint8_t> init_complete; // Offset 0
/// The size in bytes of a mutex member of SharedInfo. This allows all
/// session participants to be in agreement. Obviously, a size match is not
/// enough to guarantee identical layout internally in the mutex object, but
/// it is hoped that it will catch some (if not most) of the cases where
/// there is a layout discrepancy internally in the mutex object.
uint8_t size_of_mutex; // Offset 1
/// Like size_of_mutex, but for condition variable members of SharedInfo.
uint8_t size_of_condvar; // Offset 2
/// Set during the critical phase of a commit, when the logs, the VersionList
/// and the database may be out of sync with respect to each other. If a
/// writer crashes during this phase, there is no safe way of continuing
/// with further write transactions. When beginning a write transaction,
/// this must be checked and an exception thrown if set.
///
/// Note that std::atomic<uint8_t> is guaranteed to have standard layout.
std::atomic<uint8_t> commit_in_critical_phase = {0}; // Offset 3
/// The target Realm file format version for the current session. This
/// allows all session participants to be in agreement. It can only differ
/// from what is returned by Group::get_file_format_version() temporarily,
/// and only during the Realm file opening process. If it differs, it means
/// that the file format needs to be upgraded from its current format
/// (Group::get_file_format_version()), the format specified by this member
/// of SharedInfo.
uint8_t file_format_version; // Offset 4
/// Stores a value of type Replication::HistoryType. Must match across all
/// session participants.
int8_t history_type; // Offset 5
/// The SharedInfo layout version. This allows all session participants to
/// be in agreement. Must be bumped if the layout of the SharedInfo
/// structure is changed. Note, however, that only the part that lies beyond
/// SharedInfoUnchangingLayout can have its layout changed.
///
/// CAUTION: This member must never move or change type, as that would
/// compromize version agreement checking.
uint16_t shared_info_version = g_shared_info_version; // Offset 6
uint16_t durability; // Offset 8
uint16_t free_write_slots = 0; // Offset 10
/// Number of participating shared groups
uint32_t num_participants = 0; // Offset 12
/// Latest version number. Guarded by the controlmutex (for lock-free
/// access, use get_version_of_latest_snapshot() instead)
uint64_t latest_version_number; // Offset 16
/// Pid of process initiating the session, but only if that process runs
/// with encryption enabled, zero otherwise. This was used to prevent
/// multiprocess encryption until support for that was added.
uint64_t session_initiator_pid = 0; // Offset 24
std::atomic<uint64_t> number_of_versions; // Offset 32
/// True (1) if there is a sync agent present (a session participant acting
/// as sync client). It is an error to have a session with more than one
/// sync agent. The purpose of this flag is to prevent that from ever
/// happening. If the sync agent crashes and leaves the flag set, the
/// session will need to be restarted (lock file reinitialized) before a new
/// sync agent can be started.
uint8_t sync_agent_present = 0; // Offset 40
/// Set when a participant decides to start the daemon, cleared by the
/// daemon when it decides to exit. Participants check during open() and
/// start the daemon if running in async mode.
uint8_t daemon_started = 0; // Offset 41
/// Set by the daemon when it is ready to handle commits. Participants must
/// wait during open() on 'daemon_becomes_ready' for this to become true.
/// Cleared by the daemon when it decides to exit.
uint8_t daemon_ready = 0; // Offset 42
uint8_t filler_1; // Offset 43
/// Stores a history schema version (as returned by
/// Replication::get_history_schema_version()). Must match across all
/// session participants.
uint16_t history_schema_version; // Offset 44
uint16_t filler_2; // Offset 46
InterprocessMutex::SharedPart shared_writemutex; // Offset 48
InterprocessMutex::SharedPart shared_controlmutex;
InterprocessMutex::SharedPart shared_versionlist_mutex;
InterprocessCondVar::SharedPart room_to_write;
InterprocessCondVar::SharedPart work_to_do;
InterprocessCondVar::SharedPart daemon_becomes_ready;
InterprocessCondVar::SharedPart new_commit_available;
InterprocessCondVar::SharedPart pick_next_writer;
std::atomic<uint32_t> next_ticket;
std::atomic<uint32_t> next_served = 0;
std::atomic<uint64_t> writing_page_offset;
std::atomic<uint64_t> write_counter;
// IMPORTANT: The VersionList MUST be the last field in SharedInfo - see above.
VersionList readers;
SharedInfo(Durability, Replication::HistoryType, int history_schema_version);
~SharedInfo() noexcept {}
void init_versioning(ref_type top_ref, size_t file_size, uint64_t initial_version)
{
// Create our first versioning entry:
readers.init_versioning(top_ref, file_size, initial_version);
}
};
DB::SharedInfo::SharedInfo(Durability dura, Replication::HistoryType ht, int hsv)
: size_of_mutex(sizeof(shared_writemutex))
, size_of_condvar(sizeof(room_to_write))
, shared_writemutex() // Throws
, shared_controlmutex() // Throws
{
durability = static_cast<uint16_t>(dura); // durability level is fixed from creation
REALM_ASSERT(!util::int_cast_has_overflow<decltype(history_type)>(ht + 0));
REALM_ASSERT(!util::int_cast_has_overflow<decltype(history_schema_version)>(hsv));
history_type = ht;
history_schema_version = static_cast<uint16_t>(hsv);
InterprocessCondVar::init_shared_part(new_commit_available); // Throws
InterprocessCondVar::init_shared_part(pick_next_writer); // Throws
next_ticket = 0;
// IMPORTANT: The offsets, types (, and meanings) of these members must
// never change, not even when the SharedInfo layout version is bumped. The
// eternal constancy of this part of the layout is what ensures that a
// joining session participant can reliably verify that the actual format is
// as expected.
#ifndef _WIN32
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Winvalid-offsetof"
#endif
static_assert(offsetof(SharedInfo, init_complete) == 0 && ATOMIC_BOOL_LOCK_FREE == 2 &&
std::is_same<decltype(init_complete), std::atomic<uint8_t>>::value &&
offsetof(SharedInfo, shared_info_version) == 6 &&
std::is_same<decltype(shared_info_version), uint16_t>::value,
"Forbidden change in SharedInfo layout");
// Try to catch some of the memory layout changes that requires bumping of
// the SharedInfo file format version (shared_info_version).
static_assert(
offsetof(SharedInfo, size_of_mutex) == 1 && std::is_same<decltype(size_of_mutex), uint8_t>::value &&
offsetof(SharedInfo, size_of_condvar) == 2 && std::is_same<decltype(size_of_condvar), uint8_t>::value &&
offsetof(SharedInfo, commit_in_critical_phase) == 3 &&
std::is_same<decltype(commit_in_critical_phase), std::atomic<uint8_t>>::value &&
offsetof(SharedInfo, file_format_version) == 4 &&
std::is_same<decltype(file_format_version), uint8_t>::value && offsetof(SharedInfo, history_type) == 5 &&
std::is_same<decltype(history_type), int8_t>::value && offsetof(SharedInfo, durability) == 8 &&
std::is_same<decltype(durability), uint16_t>::value && offsetof(SharedInfo, free_write_slots) == 10 &&
std::is_same<decltype(free_write_slots), uint16_t>::value &&
offsetof(SharedInfo, num_participants) == 12 &&
std::is_same<decltype(num_participants), uint32_t>::value &&
offsetof(SharedInfo, latest_version_number) == 16 &&
std::is_same<decltype(latest_version_number), uint64_t>::value &&
offsetof(SharedInfo, session_initiator_pid) == 24 &&
std::is_same<decltype(session_initiator_pid), uint64_t>::value &&
offsetof(SharedInfo, number_of_versions) == 32 &&
std::is_same<decltype(number_of_versions), std::atomic<uint64_t>>::value &&
offsetof(SharedInfo, sync_agent_present) == 40 &&
std::is_same<decltype(sync_agent_present), uint8_t>::value &&
offsetof(SharedInfo, daemon_started) == 41 && std::is_same<decltype(daemon_started), uint8_t>::value &&
offsetof(SharedInfo, daemon_ready) == 42 && std::is_same<decltype(daemon_ready), uint8_t>::value &&
offsetof(SharedInfo, filler_1) == 43 && std::is_same<decltype(filler_1), uint8_t>::value &&
offsetof(SharedInfo, history_schema_version) == 44 &&
std::is_same<decltype(history_schema_version), uint16_t>::value && offsetof(SharedInfo, filler_2) == 46 &&
std::is_same<decltype(filler_2), uint16_t>::value && offsetof(SharedInfo, shared_writemutex) == 48 &&
std::is_same<decltype(shared_writemutex), InterprocessMutex::SharedPart>::value,
"Caught layout change requiring SharedInfo file format bumping");
static_assert(std::atomic<uint64_t>::is_always_lock_free);
#ifndef _WIN32
#pragma GCC diagnostic pop
#endif
}
class DB::VersionManager {
public:
VersionManager(util::InterprocessMutex& mutex)
: m_mutex(mutex)
{
}
virtual ~VersionManager() {}
void cleanup_versions(uint64_t& oldest_live_version, TopRefMap& top_refs, bool& any_new_unreachables)
REQUIRES(!m_info_mutex)
{
std::lock_guard lock(m_mutex);
util::CheckedLockGuard info_lock(m_info_mutex);
ensure_reader_mapping();
m_info->readers.purge_versions(oldest_live_version, top_refs, any_new_unreachables);
}
version_type get_newest_version() REQUIRES(!m_local_readers_mutex, !m_info_mutex)
{
return get_version_id_of_latest_snapshot().version;
}
VersionID get_version_id_of_latest_snapshot() REQUIRES(!m_local_readers_mutex, !m_info_mutex)
{
{
// First check the local cache. This is an unlocked read, so it may
// race with adding a new version. If this happens we'll either see
// a stale value (acceptable for a racing write on one thread and
// a read on another), or a new value which is guaranteed to not
// be an active index in the local cache.
util::CheckedLockGuard lock(m_local_readers_mutex);
util::CheckedLockGuard info_lock(m_info_mutex);
auto index = m_info->readers.newest.load();
if (index < m_local_readers.size()) {
auto& r = m_local_readers[index];
if (r.is_active()) {
return {r.version, index};
}
}
}
std::lock_guard lock(m_mutex);
util::CheckedLockGuard info_lock(m_info_mutex);
auto index = m_info->readers.newest.load();
ensure_reader_mapping(index);
return {m_info->readers.get(index).version, index};
}
void release_read_lock(const ReadLockInfo& read_lock) REQUIRES(!m_local_readers_mutex, !m_info_mutex)
{
{
util::CheckedLockGuard lock(m_local_readers_mutex);
REALM_ASSERT(read_lock.m_reader_idx < m_local_readers.size());
auto& r = m_local_readers[read_lock.m_reader_idx];
auto& f = field_for_type(r, read_lock.m_type);
REALM_ASSERT(f > 0);
if (--f > 0)
return;
if (r.count_live == 0 && r.count_full == 0 && r.count_frozen == 0)
r.version = 0;
}
std::lock_guard lock(m_mutex);
util::CheckedLockGuard info_lock(m_info_mutex);
// we should not need to call ensure_full_reader_mapping,
// since releasing a read lock means it has been grabbed
// earlier - and hence must reside in mapped memory:
REALM_ASSERT(read_lock.m_reader_idx < m_local_max_entry);
auto& r = m_info->readers.get(read_lock.m_reader_idx);
REALM_ASSERT(read_lock.m_version == r.version);
--field_for_type(r, read_lock.m_type);
}
ReadLockInfo grab_read_lock(ReadLockInfo::Type type, VersionID version_id = {})
REQUIRES(!m_local_readers_mutex, !m_info_mutex)
{
ReadLockInfo read_lock;
if (try_grab_local_read_lock(read_lock, type, version_id))
return read_lock;
{
const bool pick_specific = version_id.version != VersionID().version;
std::lock_guard lock(m_mutex);
util::CheckedLockGuard info_lock(m_info_mutex);
auto newest = m_info->readers.newest.load();
REALM_ASSERT(newest != VersionList::nil);
read_lock.m_reader_idx = pick_specific ? version_id.index : newest;
ensure_reader_mapping((unsigned int)read_lock.m_reader_idx);
bool picked_newest = read_lock.m_reader_idx == (unsigned)newest;
auto& r = m_info->readers.get(read_lock.m_reader_idx);
if (pick_specific && version_id.version != r.version)
throw BadVersion(version_id.version);
if (!picked_newest) {
if (type == ReadLockInfo::Frozen && r.count_frozen == 0 && r.count_live == 0)
throw BadVersion(version_id.version);
if (type != ReadLockInfo::Frozen && r.count_live == 0)
throw BadVersion(version_id.version);
}
populate_read_lock(read_lock, r, type);
}
{
util::CheckedLockGuard local_lock(m_local_readers_mutex);
grow_local_cache(read_lock.m_reader_idx + 1);
auto& r2 = m_local_readers[read_lock.m_reader_idx];
if (!r2.is_active()) {
r2.version = read_lock.m_version;
r2.filesize = read_lock.m_file_size;
r2.current_top = read_lock.m_top_ref;
r2.count_full = r2.count_live = r2.count_frozen = 0;
}
REALM_ASSERT_EX(field_for_type(r2, type) == 0, type, r2.count_full, r2.count_live, r2.count_frozen);
field_for_type(r2, type) = 1;
}
return read_lock;
}
void init_versioning(ref_type top_ref, size_t file_size, uint64_t initial_version) REQUIRES(!m_info_mutex)
{
std::lock_guard lock(m_mutex);
util::CheckedLockGuard info_lock(m_info_mutex);
m_info->init_versioning(top_ref, file_size, initial_version);
}
void add_version(ref_type new_top_ref, size_t new_file_size, uint64_t new_version) REQUIRES(!m_info_mutex)
{
std::lock_guard lock(m_mutex);
util::CheckedLockGuard info_lock(m_info_mutex);
ensure_reader_mapping();
if (m_info->readers.try_allocate_entry(new_top_ref, new_file_size, new_version)) {
return;
}
// allocation failed, expand VersionList (and lockfile) and retry
auto entries = m_info->readers.capacity();
auto new_entries = entries + 32;
expand_version_list(new_entries);
m_local_max_entry = new_entries;
m_info->readers.reserve(new_entries);
auto success = m_info->readers.try_allocate_entry(new_top_ref, new_file_size, new_version);
REALM_ASSERT_EX(success, new_entries, new_version);
}
private:
void grow_local_cache(size_t new_size) REQUIRES(m_local_readers_mutex)
{
if (new_size > m_local_readers.size())
m_local_readers.resize(new_size, VersionList::ReadCount{});
}
void populate_read_lock(ReadLockInfo& read_lock, VersionList::ReadCount& r, ReadLockInfo::Type type)
{
++field_for_type(r, type);
read_lock.m_type = type;
read_lock.m_version = r.version;
read_lock.m_top_ref = static_cast<ref_type>(r.current_top);
read_lock.m_file_size = static_cast<size_t>(r.filesize);
}
bool try_grab_local_read_lock(ReadLockInfo& read_lock, ReadLockInfo::Type type, VersionID version_id)
REQUIRES(!m_local_readers_mutex, !m_info_mutex)
{
const bool pick_specific = version_id.version != VersionID().version;
auto index = version_id.index;
if (!pick_specific) {
util::CheckedLockGuard lock(m_info_mutex);
index = m_info->readers.newest.load();
}
util::CheckedLockGuard local_lock(m_local_readers_mutex);
if (index >= m_local_readers.size())
return false;
auto& r = m_local_readers[index];
if (!r.is_active())
return false;
if (pick_specific && r.version != version_id.version)
return false;
if (field_for_type(r, type) == 0)
return false;
read_lock.m_reader_idx = index;
populate_read_lock(read_lock, r, type);
return true;
}
static uint32_t& field_for_type(VersionList::ReadCount& r, ReadLockInfo::Type type)
{
switch (type) {
case ReadLockInfo::Frozen:
return r.count_frozen;
case ReadLockInfo::Live:
return r.count_live;
case ReadLockInfo::Full:
return r.count_full;
default:
REALM_UNREACHABLE(); // silence a warning
}
}
void mark_page_for_writing(uint64_t page_offset) REQUIRES(!m_info_mutex)
{
util::CheckedLockGuard info_lock(m_info_mutex);
m_info->writing_page_offset = page_offset + 1;
m_info->write_counter++;
}
void clear_writing_marker() REQUIRES(!m_info_mutex)
{
util::CheckedLockGuard info_lock(m_info_mutex);
m_info->write_counter++;
m_info->writing_page_offset = 0;
}
// returns false if no page is marked.
// if a page is marked, returns true and optionally the offset of the page marked for writing
// in all cases returns optionally the write counter
bool observe_writer(uint64_t* page_offset, uint64_t* write_counter) REQUIRES(!m_info_mutex)
{
util::CheckedLockGuard info_lock(m_info_mutex);
if (write_counter) {
*write_counter = m_info->write_counter;
}
uint64_t marked = m_info->writing_page_offset;
if (marked && page_offset) {
*page_offset = marked - 1;
}
return marked != 0;
}
protected:
util::InterprocessMutex& m_mutex;
util::CheckedMutex m_local_readers_mutex;
std::vector<VersionList::ReadCount> m_local_readers GUARDED_BY(m_local_readers_mutex);
util::CheckedMutex m_info_mutex;
unsigned int m_local_max_entry GUARDED_BY(m_info_mutex) = 0;
SharedInfo* m_info GUARDED_BY(m_info_mutex) = nullptr;
virtual void ensure_reader_mapping(unsigned int required = -1) REQUIRES(m_info_mutex) = 0;
virtual void expand_version_list(unsigned new_entries) REQUIRES(m_info_mutex) = 0;
friend class DB::EncryptionMarkerObserver;
};
class DB::FileVersionManager final : public DB::VersionManager {
public:
FileVersionManager(File& file, util::InterprocessMutex& mutex)
: VersionManager(mutex)
, m_file(file)
{
size_t size = 0, required_size = sizeof(SharedInfo);
while (size < required_size) {
// Map the file without the lock held. This could result in the
// mapping being too small and having to remap if the file is grown
// concurrently, but if this is the case we should always see a bigger
// size the next time.
auto new_size = static_cast<size_t>(m_file.get_size());
REALM_ASSERT(new_size > size);
size = new_size;
m_reader_map.remap(m_file, File::access_ReadWrite, size);
m_info = m_reader_map.get_addr();
std::lock_guard lock(m_mutex);
m_local_max_entry = m_info->readers.capacity();
required_size = sizeof(SharedInfo) + m_info->readers.compute_required_space(m_local_max_entry);
REALM_ASSERT(required_size >= size);
}
}
void expand_version_list(unsigned new_entries) override REQUIRES(m_info_mutex)
{
size_t new_info_size = sizeof(SharedInfo) + m_info->readers.compute_required_space(new_entries);
m_file.prealloc(new_info_size); // Throws
m_reader_map.remap(m_file, util::File::access_ReadWrite, new_info_size); // Throws
m_info = m_reader_map.get_addr();
}
private:
void ensure_reader_mapping(unsigned int required = -1) override REQUIRES(m_info_mutex)
{
using _impl::SimulatedFailure;
SimulatedFailure::trigger(SimulatedFailure::shared_group__grow_reader_mapping); // Throws
if (required < m_local_max_entry)
return;
auto new_max_entry = m_info->readers.capacity();
if (new_max_entry > m_local_max_entry) {
// handle mapping expansion if required
size_t info_size = sizeof(DB::SharedInfo) + m_info->readers.compute_required_space(new_max_entry);
m_reader_map.remap(m_file, util::File::access_ReadWrite, info_size); // Throws
m_local_max_entry = new_max_entry;
m_info = m_reader_map.get_addr();
}
}
File& m_file;
File::Map<DB::SharedInfo> m_reader_map;
friend class DB::EncryptionMarkerObserver;
};
// adapter class for marking/observing encrypted writes
class DB::EncryptionMarkerObserver final : public util::WriteMarker, public util::WriteObserver {
public:
EncryptionMarkerObserver(DB::VersionManager& vm)
: vm(vm)
{
}
bool no_concurrent_writer_seen() override
{
uint64_t tmp_write_count;
auto page_may_have_been_written = vm.observe_writer(nullptr, &tmp_write_count);
if (tmp_write_count != last_seen_count) {
page_may_have_been_written = true;
last_seen_count = tmp_write_count;
}
if (page_may_have_been_written) {
calls_since_last_writer_observed = 0;
return false;
}
++calls_since_last_writer_observed;
constexpr size_t max_calls = 5; // an arbitrary handful, > 1
return calls_since_last_writer_observed >= max_calls;
}
void mark(uint64_t pos) override
{
vm.mark_page_for_writing(pos);
}
void unmark() override
{
vm.clear_writing_marker();
}
private:
DB::VersionManager& vm;
uint64_t last_seen_count = 0;
size_t calls_since_last_writer_observed = 0;
};
class DB::InMemoryVersionManager final : public DB::VersionManager {
public:
InMemoryVersionManager(SharedInfo* info, util::InterprocessMutex& mutex)
: VersionManager(mutex)
{
m_info = info;
m_local_max_entry = m_info->readers.capacity();
}
void expand_version_list(unsigned) override
{
REALM_ASSERT(false);
}
private:
void ensure_reader_mapping(unsigned int) override {}
};
#if REALM_HAVE_STD_FILESYSTEM
std::string DBOptions::sys_tmp_dir = std::filesystem::temp_directory_path().string();
#else
std::string DBOptions::sys_tmp_dir = getenv("TMPDIR") ? getenv("TMPDIR") : "";
#endif
// NOTES ON CREATION AND DESTRUCTION OF SHARED MUTEXES:
//
// According to the 'process-sharing example' in the POSIX man page
// for pthread_mutexattr_init() other processes may continue to use a
// process-shared mutex after exit of the process that initialized
// it. Also, the example does not contain any call to
// pthread_mutex_destroy(), so apparently a process-shared mutex need
// not be destroyed at all, nor can it be that a process-shared mutex
// is associated with any resources that are local to the initializing
// process, because that would imply a leak.
//
// While it is not explicitly guaranteed in the man page, we shall
// assume that is is valid to initialize a process-shared mutex twice
// without an intervening call to pthread_mutex_destroy(). We need to
// be able to reinitialize a process-shared mutex if the first
// initializing process crashes and leaves the shared memory in an
// undefined state.
void DB::open(const std::string& path, const DBOptions& options)
{
// Exception safety: Since do_open() is called from constructors, if it
// throws, it must leave the file closed.
using util::format;
REALM_ASSERT(!is_attached());
REALM_ASSERT(path.size());
m_db_path = path;
set_logger(options.logger);
if (m_replication) {
m_replication->set_logger(m_logger.get());
}
if (m_logger) {
m_logger->log(util::Logger::Level::detail, "Open file: %1", path);
}
SlabAlloc& alloc = m_alloc;
ref_type top_ref = 0;
if (options.is_immutable) {
SlabAlloc::Config cfg;
cfg.read_only = true;
cfg.no_create = true;
cfg.encryption_key = options.encryption_key;
top_ref = alloc.attach_file(path, cfg);
SlabAlloc::DetachGuard dg(alloc);
Group::read_only_version_check(alloc, top_ref, path);
m_fake_read_lock_if_immutable = ReadLockInfo::make_fake(top_ref, m_alloc.get_baseline());
dg.release();
return;
}
std::string lockfile_path = get_core_file(path, CoreFileType::Lock);
std::string coordination_dir = get_core_file(path, CoreFileType::Management);
std::string lockfile_prefix = coordination_dir + "/access_control";
m_alloc.set_read_only(false);
Replication::HistoryType openers_hist_type = Replication::hist_None;
int openers_hist_schema_version = 0;
if (Replication* repl = get_replication()) {
openers_hist_type = repl->get_history_type();
openers_hist_schema_version = repl->get_history_schema_version();
}
int current_file_format_version;
int target_file_format_version;
int stored_hist_schema_version = -1; // Signals undetermined
int retries_left = 10; // number of times to retry before throwing exceptions
// in case there is something wrong with the .lock file... the retries allows
// us to pick a new lockfile initializer in case the first one crashes without
// completing the initialization
std::default_random_engine random_gen;
for (;;) {
// if we're retrying, we first wait a random time
if (retries_left < 10) {
if (retries_left == 9) { // we seed it from a true random source if possible
std::random_device r;
random_gen.seed(r());
}
int max_delay = (10 - retries_left) * 10;
int msecs = random_gen() % max_delay;
millisleep(msecs);
}
m_file.open(lockfile_path, File::access_ReadWrite, File::create_Auto, 0); // Throws
File::CloseGuard fcg(m_file);
m_file.set_fifo_path(coordination_dir, "lock.fifo");
if (m_file.try_rw_lock_exclusive()) { // Throws
File::UnlockGuard ulg(m_file);
// We're alone in the world, and it is Ok to initialize the
// file. Start by truncating the file to zero to ensure that
// the following resize will generate a file filled with zeroes.
//
// This will in particular set m_init_complete to 0.
m_file.resize(0);
m_file.prealloc(sizeof(SharedInfo));
// We can crash anytime during this process. A crash prior to
// the first resize could allow another thread which could not
// get the exclusive lock because we hold it, and hence were
// waiting for the shared lock instead, to observe and use an
// old lock file.
m_file_map.map(m_file, File::access_ReadWrite, sizeof(SharedInfo)); // Throws
File::UnmapGuard fug(m_file_map);
SharedInfo* info = m_file_map.get_addr();
new (info) SharedInfo{options.durability, openers_hist_type, openers_hist_schema_version}; // Throws
// Because init_complete is an std::atomic, it's guaranteed not to be observable by others
// as being 1 before the entire SharedInfo header has been written.
info->init_complete = 1;
}
// We hold the shared lock from here until we close the file!
#if REALM_PLATFORM_APPLE