-
-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathdb.c
More file actions
1518 lines (1293 loc) Β· 52.3 KB
/
db.c
File metadata and controls
1518 lines (1293 loc) Β· 52.3 KB
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
#include <stdlib.h>
#include <stdint.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stdio.h>
#include <assert.h>
#include <string.h>
#include <pthread.h>
#include <signal.h>
#include <stdatomic.h>
#if __has_include ("tracy/TracyC.h")
#include "tracy/TracyC.h"
#endif
#include "common.h"
#include "trie.h"
#include "epoch.h"
#include "sysmon.h"
#include "db.h"
#include "vendor/stb_ds.h"
typedef struct ListOfEdgeTo {
size_t capacityEdges;
size_t nEdges; // This is an upper bound.
uint64_t edges[];
} ListOfEdgeTo;
#define SIZEOF_LIST_OF_EDGE_TO(CAPACITY_EDGES) (sizeof(ListOfEdgeTo) + (CAPACITY_EDGES)*sizeof(uint64_t))
typedef bool (*ListEdgeCheckerFn)(void* arg, uint64_t edge);
typedef struct GenRc {
// How many acquired raw pointers to this object exist? The object
// cannot be freed/invalidated as long as rc > 0. You must
// increment rc before accessing any other field in the object.
int16_t rc;
int gen: 15;
// The object also cannot be freed/invalidated as long as alive is
// true; alive indicates that the object is alive in the database
// (has supporting parent).
bool alive: 1;
} GenRc;
bool genRcAcquire(_Atomic GenRc* genRcPtr, int32_t gen) {
GenRc oldGenRc;
GenRc newGenRc;
do {
oldGenRc = *genRcPtr;
if (oldGenRc.gen < 0 || oldGenRc.gen != gen) {
return false;
}
newGenRc = oldGenRc;
newGenRc.rc++;
} while (!atomic_compare_exchange_weak(genRcPtr, &oldGenRc, newGenRc));
return true;
}
bool genRcRelease(_Atomic GenRc* genRcPtr) {
GenRc oldGenRc;
GenRc newGenRc;
bool callerIsLastReleaser = false;
do {
oldGenRc = *genRcPtr;
newGenRc = oldGenRc;
--newGenRc.rc;
callerIsLastReleaser = !oldGenRc.alive && (newGenRc.rc == 0);
if (callerIsLastReleaser) {
newGenRc.gen++;
}
} while (!atomic_compare_exchange_weak(genRcPtr, &oldGenRc, newGenRc));
return callerIsLastReleaser;
}
void genRcMarkAsDead(_Atomic GenRc* genRcPtr) {
// ASSUMES that rc > 0 (because the caller must have acquired the
// rc before calling us), which means gen cannot change. We do the
// loop here in case the rc changes.
GenRc oldGenRc;
GenRc newGenRc;
do {
oldGenRc = *genRcPtr;
newGenRc = oldGenRc;
newGenRc.alive = false;
// TODO: Check that gen hasn't changed and that rc > 0.
} while (!atomic_compare_exchange_weak(genRcPtr, &oldGenRc, newGenRc));
}
// Destructor datatype:
typedef struct Destructor {
_Atomic int rc;
void (*fn)(void*);
void* arg;
} Destructor;
Destructor* destructorNew(void (*fn)(void*), void* arg) {
Destructor* ret = malloc(sizeof(Destructor));
ret->rc = 0;
ret->fn = fn;
ret->arg = arg;
return ret;
}
void destructorRun(Destructor* d) {
assert(d->fn != NULL);
d->fn(d->arg);
d->fn = NULL;
}
static void destructorRetain(Destructor* d) {
d->rc++;
}
static void destructorRelease(Destructor* d) {
if (--d->rc == 0) {
destructorRun(d);
free(d);
}
}
typedef struct DestructorSet {
Destructor** destructors;
int destructorsCapacity;
int destructorsCount;
pthread_mutex_t destructorsMutex;
} DestructorSet;
void destructorSetInit(DestructorSet* set) {
set->destructors = malloc(8 * sizeof(Destructor*));
set->destructorsCapacity = 8;
set->destructorsCount = 0;
}
static void destructorSetAddImpl(DestructorSet* set, Destructor* d) {
assert(set->destructors != NULL);
if (set->destructorsCount == set->destructorsCapacity) {
set->destructorsCapacity *= 2;
set->destructors = realloc(set->destructors, set->destructorsCapacity * sizeof(Destructor));
}
destructorRetain(d);
set->destructors[set->destructorsCount++] = d;
}
void destructorSetAdd(DestructorSet* set, Destructor* d) {
destructorSetAddImpl(set, d);
}
void destructorSetInherit(DestructorSet* to, DestructorSet* from) {
for (int i = 0; i < from->destructorsCount; i++) {
destructorSetAddImpl(to, from->destructors[i]);
}
}
void destructorSetReleaseAll(DestructorSet* set) {
for (int i = 0; i < set->destructorsCount; i++) {
if (set->destructors[i] != NULL) {
destructorRelease(set->destructors[i]);
}
set->destructors[i] = NULL;
}
free(set->destructors);
set->destructors = NULL;
}
// Statement datatype:
typedef struct Statement {
_Atomic GenRc genRc;
// Immutable statement properties:
// -----
// Owned by the DB. clause cannot be mutated or invalidated while
// rc > 0.
Clause* _Atomic clause;
// If the statement is removed, we wait keepMs milliseconds before
// removing its child matches.
_Atomic long keepMs;
// Will be NULL if not running in an Atomically
// convergence-tracking subgraph.
AtomicallyVersion* atomicallyVersion;
// Note that statement destructors are not mutable after statement
// creation, so they can be safely looked up and inherited, unlike
// match destructors.
DestructorSet destructorSet;
pthread_mutex_t destructorSetMutex;
// Used for debugging (and stack traces for When bodies).
char sourceFileName[100];
int sourceLineNumber;
// Mutable statement properties:
// -----
// How many living Matches (or Holds or Asserts) are supporting
// this statement? When parentCount hits 0, we deindex the
// statement.
_Atomic int parentCount;
// ListOfEdgeTo MatchRef. Used for removal.
ListOfEdgeTo* childMatches;
pthread_mutex_t childMatchesMutex;
// TODO: Cache of Jim-local clause objects?
} Statement;
// Match datatype:
typedef struct Match {
_Atomic GenRc genRc;
// Immutable match properties:
// -----
int workerThreadIndex;
// Mutable match properties:
// -----
// Will be NULL if not running in an Atomically
// convergence-tracking subgraph.
AtomicallyVersion* _Atomic atomicallyVersion;
// Set to true if ANY parent statement was removed but we kept the
// Match alive.
_Atomic bool parentWasRemoved;
// isCompleted is set to true once the Tcl evaluation that builds
// the match is completed. As long as isCompleted is false,
// workerThread is subject to termination signal (SIGUSR1) if the
// match is removed.
_Atomic bool isCompleted;
DestructorSet destructorSet;
pthread_mutex_t destructorSetMutex;
// ListOfEdgeTo StatementRef. Used for removal.
ListOfEdgeTo* childStatements;
pthread_mutex_t childStatementsMutex;
} Match;
// Database datatypes:
typedef struct Hold {
// If key == NULL, then this Hold is an empty slot that can be
// used for a new hold key.
const char* key; // Owned by the DB.
double version;
StatementRef statement;
} Hold;
typedef struct AtomicallyVersion {
int number;
// Used to find older version to reap.
struct Atomically* atomically;
// When this is >0, there are still operations in flight within
// this AtomicallyVersion arena. When this is 0, this
// AtomicallyVersion is 'fully converged'. This should never be
// negative.
int _Atomic inflightCount;
// When you do When -atomically, every time its body executes, it
// produces a Match and a fresh AtomicallyVersion. That Match is
// the rootMatch of the AtomicallyVersion. The rootMatch (and
// therefore all descendant statements) is artificially kept alive
// as long as the AtomicallyVersion hasn't been
// invalidated. (matchRemoveSelf won't go through if
// match->atomicallyVersion->rootMatch is match.)
//
// Invalidation: When a newer version converges (or when the
// Atomically times out), we walk all older versions' rootMatches
// and NULL them out.
Match* _Atomic rootMatch;
} AtomicallyVersion;
typedef struct AtomicallyVersionList {
AtomicallyVersion* version;
struct AtomicallyVersionList* next;
} AtomicallyVersionList;
typedef struct Atomically {
// If key == NULL, then this Atomically is an empty slot that can
// be used for a new key.
const char* _Atomic key; // Owned by the DB.
int _Atomic nextNumber;
// This is used by a newly converged version to reap older
// versions.
AtomicallyVersionList* _Atomic allVersions;
AtomicallyVersion* _Atomic latestConvergedVersion;
// Records the last time that a version of this Atomically
// converged. The sysmon will check this every 50ms or so and
// reap any Atomicallys that haven't converged in a while.
int64_t latestConvergedTime;
int64_t timeout;
} Atomically;
typedef struct Db {
// Memory pool used to allocate statements.
Statement statementPool[65536]; // slot 0 is reserved.
_Atomic uint16_t statementPoolNextIdx;
// Memory pool used to allocate matches.
Match matchPool[65536]; // slot 0 is reserved.
_Atomic uint16_t matchPoolNextIdx;
// Primary trie (index) used for queries.
const Trie* _Atomic clauseToStatementRef;
// One for each Hold key, which always stores the highest-version
// held statement for that key. We keep this map so that we can
// overwrite out-of-date Holds for a key as soon as a newer one
// comes in, without having to actually emit and react to the
// statement.
Hold* holds; // stb_ds string hash map (keyed by Hold.key)
Mutex holdsMutex;
// One for each `atomically` key.
Atomically atomicallys[256];
// This Mutex guards the list but not the individual Atomically
// structs.
Mutex atomicallysMutex;
} Db;
////////////////////////////////////////////////////////////
// EdgeTo and ListOfEdgeTo:
////////////////////////////////////////////////////////////
ListOfEdgeTo* listOfEdgeToNew(size_t capacityEdges) {
ListOfEdgeTo* ret = calloc(SIZEOF_LIST_OF_EDGE_TO(capacityEdges), 1);
ret->capacityEdges = capacityEdges;
ret->nEdges = 0;
return ret;
}
static void listOfEdgeToDefragment(ListEdgeCheckerFn checker, void* checkerArg,
ListOfEdgeTo** listPtr);
// Takes a double pointer to list because it may move the list to grow
// it (requiring replacement of the original pointer). checker is used
// to discard any edges that have been invalidated if we defragment
// (to prevent unlimited growth of the edge list).
void listOfEdgeToAdd(ListEdgeCheckerFn checker, void* checkerArg,
ListOfEdgeTo** listPtr, uint64_t to) {
if ((*listPtr)->nEdges == (*listPtr)->capacityEdges) {
// We've run out of edge slots at the end of the
// list. Try defragmenting the list.
listOfEdgeToDefragment(checker, checkerArg, listPtr);
if ((*listPtr)->nEdges == (*listPtr)->capacityEdges) {
// Still no slots? Grow the statement to
// accommodate.
(*listPtr)->capacityEdges = (*listPtr)->capacityEdges * 2;
*listPtr = realloc(*listPtr, SIZEOF_LIST_OF_EDGE_TO((*listPtr)->capacityEdges));
}
}
assert((*listPtr)->nEdges < (*listPtr)->capacityEdges);
// There's a free slot at the end of the edgelist in
// the statement. Use it.
(*listPtr)->edges[(*listPtr)->nEdges++] = to;
}
void listOfEdgeToRemove(ListOfEdgeTo* list, uint64_t to) {
assert(list != NULL);
for (size_t i = 0; i < list->nEdges; i++) {
if (list->edges[i] == to) {
list->edges[i] = to;
}
}
}
// Given listPtr, moves all non-EMPTY edges to the front, then updates
// nEdges accordingly. Discards any edges for which checker(edge) is
// false.
//
// Defragmentation is necessary to prevent continual growth of
// the statement edgelist if you keep adding and removing
// edges on the same statement.
static void listOfEdgeToDefragment(ListEdgeCheckerFn checker, void* checkerArg,
ListOfEdgeTo** listPtr) {
// Copy all non-EMPTY edges into a new edgelist.
ListOfEdgeTo* list = calloc(SIZEOF_LIST_OF_EDGE_TO((*listPtr)->capacityEdges), 1);
size_t nEdges = 0;
for (size_t i = 0; i < (*listPtr)->nEdges; i++) {
uint64_t edge = (*listPtr)->edges[i];
// Also validate edge (is it a valid match / statement?)
if (edge != 0 && checker(checkerArg, edge)) {
list->edges[nEdges++] = edge;
}
}
list->nEdges = nEdges;
list->capacityEdges = (*listPtr)->capacityEdges;
free(*listPtr);
*listPtr = list;
}
////////////////////////////////////////////////////////////
// Statement:
////////////////////////////////////////////////////////////
Statement* statementAcquire(Db* db, StatementRef ref) {
if (ref.idx == 0) { return NULL; }
Statement* s = &db->statementPool[ref.idx];
if (genRcAcquire(&s->genRc, ref.gen)) {
return s;
}
return NULL;
}
Statement* statementUnsafeGet(Db* db, StatementRef ref) {
if (ref.idx == 0) { return NULL; }
return &db->statementPool[ref.idx];
}
static void statementDestroy(Statement* stmt);
void statementRelease(Db* db, Statement* stmt) {
if (genRcRelease(&stmt->genRc)) {
statementDestroy(stmt);
}
}
bool statementCheck(Db* db, StatementRef ref) {
Statement* s = &db->statementPool[ref.idx];
GenRc genRc = s->genRc;
return ref.gen >= 0 && ref.gen == genRc.gen;
}
StatementRef statementRef(Db* db, Statement* stmt) {
GenRc genRc = stmt->genRc;
return (StatementRef) {
.gen = genRc.gen,
.idx = stmt - &db->statementPool[0]
};
}
// Creates a new statement. Internal helper for the DB, not callable
// from the outside (they need to insert into the DB as a complete
// operation). Note: clause ownership transfers to the DB, which then
// becomes responsible for freeing it.
static StatementRef statementNew(Db* db, Clause* clause,
long keepMs, AtomicallyVersion* atomicallyVersion,
const char* sourceFileName,
int sourceLineNumber) {
StatementRef ret;
Statement* stmt = NULL;
// Look for a free statement slot to use:
while (1) {
int32_t idx = db->statementPoolNextIdx++;
if (idx == 0) { continue; } // skip null statement
stmt = &db->statementPool[idx];
GenRc oldGenRc = stmt->genRc;
if (oldGenRc.rc == 0 && !oldGenRc.alive && stmt->clause == NULL) {
GenRc newGenRc = oldGenRc;
newGenRc.alive = true;
if (atomic_compare_exchange_weak(&stmt->genRc, &oldGenRc, newGenRc)) {
ret = (StatementRef) { .gen = newGenRc.gen, .idx = idx };
break;
}
}
}
// We should now have exclusive access to stmt, as its rc
// is 0 and we were the ones who made it alive.
atomic_store(&stmt->clause, clause);
stmt->keepMs = keepMs;
// inflightCount must start incremented so that this
// atomicallyVersion never reports convergence (inflightCount = 0)
// before the first reaction is dispatched.
if (atomicallyVersion != NULL) {
atomicallyVersion->inflightCount++;
stmt->atomicallyVersion = atomicallyVersion;
} else {
stmt->atomicallyVersion = NULL;
}
stmt->parentCount = 1;
destructorSetInit(&stmt->destructorSet);
pthread_mutex_init(&stmt->destructorSetMutex, NULL);
stmt->childMatches = listOfEdgeToNew(8);
pthread_mutexattr_t mta;
pthread_mutexattr_init(&mta);
pthread_mutexattr_settype(&mta, PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init(&stmt->childMatchesMutex, &mta);
pthread_mutexattr_destroy(&mta);
snprintf(stmt->sourceFileName, sizeof(stmt->sourceFileName),
"%s", sourceFileName);
stmt->sourceLineNumber = sourceLineNumber;
return ret;
}
static void statementDestroy(Statement* stmt) {
stmt->parentCount = 0;
// They should have removed the children first.
assert(stmt->childMatches == NULL);
pthread_mutex_lock(&stmt->destructorSetMutex);
destructorSetReleaseAll(&stmt->destructorSet);
pthread_mutex_unlock(&stmt->destructorSetMutex);
Clause* stmtClause = statementClause(stmt);
// Marks this statement slot as being fully free and ready for
// reuse.
stmt->clause = NULL;
/* TracyCFreeS(stmt, 4); */
clauseFree(stmtClause);
}
Clause* statementClause(Statement* stmt) { return stmt->clause; }
AtomicallyVersion* statementAtomicallyVersion(Statement* stmt) {
return stmt->atomicallyVersion;
}
int statementParentCount(Statement* stmt) {
return stmt->parentCount;
}
char* statementSourceFileName(Statement* stmt) {
return stmt->sourceFileName;
}
int statementSourceLineNumber(Statement* stmt) {
return stmt->sourceLineNumber;
}
int statementIncompleteChildMatchesCount(Db* db, Statement* stmt) {
int count = 0;
pthread_mutex_lock(&stmt->childMatchesMutex);
if (stmt->childMatches == NULL) { goto done; }
for (size_t i = 0; i < stmt->childMatches->nEdges; i++) {
MatchRef childRef = { .val = stmt->childMatches->edges[i] };
Match* child = matchAcquire(db, childRef);
if (child != NULL) {
if (!child->isCompleted) { count++; }
matchRelease(db, child);
}
}
done:
pthread_mutex_unlock(&stmt->childMatchesMutex);
return count;
}
static bool matchChecker(void* db, uint64_t ref) {
return matchCheck((Db*) db, (MatchRef) { .val = ref });
}
// You must call this with the childMatchesMutex held.
static void statementAddChildMatch(Db* db, Statement* stmt, MatchRef child) {
listOfEdgeToAdd(&matchChecker, db,
&stmt->childMatches, child.val);
}
void statementAddDestructor(Statement* stmt, Destructor* d) {
pthread_mutex_lock(&stmt->destructorSetMutex);
destructorSetAdd(&stmt->destructorSet, d);
pthread_mutex_unlock(&stmt->destructorSetMutex);
}
void statementInheritDestructors(Statement* stmt, Statement* fromStmt) {
pthread_mutex_lock(&fromStmt->destructorSetMutex);
pthread_mutex_lock(&stmt->destructorSetMutex);
destructorSetInherit(&stmt->destructorSet,
&fromStmt->destructorSet);
pthread_mutex_unlock(&stmt->destructorSetMutex);
pthread_mutex_unlock(&fromStmt->destructorSetMutex);
}
// Fails to increment parentCount & returns false if parentCount is 0,
// meaning that the statement is in the process of being destroyed by
// someone else and you should back off.
bool statementTryIncrParentCount(Statement* stmt) {
int oldParentCount;
int newParentCount;
do {
oldParentCount = stmt->parentCount;
if (oldParentCount == 0) {
return false;
}
newParentCount = oldParentCount + 1;
} while (!atomic_compare_exchange_weak(&stmt->parentCount, &oldParentCount,
newParentCount));
return true;
}
void statementDecrParentCountAndMaybeRemoveSelf(Db* db, Statement* stmt) {
if (stmt->keepMs > 0) {
if (--stmt->parentCount == 0) {
// Note that we should have exclusive access to stmt at
// this point.
// Prevent future removers now that we've already
// scheduled removal.
long keepMs = stmt->keepMs;
stmt->keepMs = -keepMs;
// Tentatively trigger a removal in `keepMs` ms, but the
// statement is still able to be revived in the
// intervening time.
sysmonScheduleRemoveAfter(statementRef(db, stmt), keepMs);
stmt->parentCount++;
}
} else if (stmt->keepMs < 0) {
// We're carrying out a previously-scheduled removal.
if (--stmt->parentCount == 0) {
// Note that we should have exclusive access to stmt at
// this point.
statementRemoveSelf(db, stmt, true);
} else {
// The statement's been revived; restore keepMs.
// TODO: there's a race here if parentCount gets zeroed
// without ever getting scheduled for removal.
stmt->keepMs = -stmt->keepMs;
}
} else if (stmt->keepMs == 0) {
if (--stmt->parentCount == 0) {
// Note that we should have exclusive access to stmt at
// this point.
statementRemoveSelf(db, stmt, true);
}
}
}
// Call statementRemoveSelf when ALL of the statement's parents
// (matches or other) are removed (parentCount has hit 0).
void statementRemoveSelf(Db* db, Statement* stmt, bool doDeindex) {
assert(stmt->parentCount == 0);
if (doDeindex) {
uint64_t results[100]; int resultsCount;
epochBegin();
const Trie* oldClauseToStatementRef;
const Trie* newClauseToStatementRef;
do {
epochReset();
oldClauseToStatementRef = db->clauseToStatementRef;
newClauseToStatementRef =
trieRemove(db->clauseToStatementRef,
epochAlloc, epochFree,
stmt->clause,
(uint64_t*) results, sizeof(results)/sizeof(results[0]),
&resultsCount);
if (newClauseToStatementRef == oldClauseToStatementRef) {
break;
}
} while (!atomic_compare_exchange_weak(&db->clauseToStatementRef,
&oldClauseToStatementRef,
newClauseToStatementRef));
epochEnd();
}
/* printf("reactToRemovedStatement: s%d:%d (%s)\n", stmt - &db->statementPool[0], stmt->gen, */
/* clauseToString(stmt->clause)); */
pthread_mutex_lock(&stmt->childMatchesMutex);
ListOfEdgeTo* childMatches = stmt->childMatches;
assert(childMatches != NULL);
// Guarantees that no further matches can be added (we would be
// unable to remove those).
stmt->childMatches = NULL;
genRcMarkAsDead(&stmt->genRc);
pthread_mutex_unlock(&stmt->childMatchesMutex);
for (size_t i = 0; i < childMatches->nEdges; i++) {
MatchRef childRef = { .val = childMatches->edges[i] };
Match* child = matchAcquire(db, childRef);
if (child != NULL) {
// The removal of _any_ of a Match's statement parents
// means the removal of that Match.
matchRemoveSelf(db, child);
matchRelease(db, child);
}
}
free(childMatches);
}
////////////////////////////////////////////////////////////
// Match:
////////////////////////////////////////////////////////////
Match* matchAcquire(Db* db, MatchRef ref) {
if (ref.idx == 0) { return NULL; }
Match* m = &db->matchPool[ref.idx];
if (genRcAcquire(&m->genRc, ref.gen)) {
return m;
} else {
return NULL;
}
}
static void matchDestroy(Match* match);
void matchRelease(Db* db, Match* match) {
if (genRcRelease(&match->genRc)) {
matchDestroy(match);
}
}
bool matchCheck(Db* db, MatchRef ref) {
Match* m = &db->matchPool[ref.idx];
GenRc genRc = m->genRc;
return ref.gen >= 0 && ref.gen == genRc.gen;
}
MatchRef matchRef(Db* db, Match* match) {
GenRc genRc = match->genRc;
return (MatchRef) {
.gen = genRc.gen,
.idx = match - &db->matchPool[0]
};
}
static MatchRef matchNew(Db* db,
AtomicallyVersion* atomicallyVersion,
int workerThreadIndex) {
MatchRef ret;
Match* match = NULL;
// Look for a free match slot to use:
while (1) {
int32_t idx = db->matchPoolNextIdx++;
if (idx == 0) { continue; } // skip null match
match = &db->matchPool[idx];
GenRc oldGenRc = match->genRc;
if (oldGenRc.rc == 0 && !oldGenRc.alive && match->childStatements == NULL) {
GenRc newGenRc = oldGenRc;
newGenRc.alive = true;
if (atomic_compare_exchange_weak(&match->genRc, &oldGenRc, newGenRc)) {
ret = (MatchRef) { .gen = newGenRc.gen, .idx = idx };
break;
}
}
}
// We should have exclusive access to match right now.
match->childStatements = listOfEdgeToNew(8);
match->parentWasRemoved = false;
pthread_mutexattr_t mta;
pthread_mutexattr_init(&mta);
pthread_mutexattr_settype(&mta, PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init(&match->childStatementsMutex, &mta);
pthread_mutexattr_destroy(&mta);
match->atomicallyVersion = atomicallyVersion;
match->workerThreadIndex = workerThreadIndex;
match->isCompleted = false;
destructorSetInit(&match->destructorSet);
pthread_mutex_init(&match->destructorSetMutex, NULL);
return ret;
}
static void matchDestroy(Match* match) {
assert(match->childStatements == NULL);
// Fire any destructors.
pthread_mutex_lock(&match->destructorSetMutex);
destructorSetReleaseAll(&match->destructorSet);
pthread_mutex_unlock(&match->destructorSetMutex);
}
AtomicallyVersion* matchAtomicallyVersion(Match* m) {
return m->atomicallyVersion;
}
void matchSetAtomicallyVersion(Match* m, AtomicallyVersion* a) {
m->atomicallyVersion = a;
}
static bool statementChecker(void* db, uint64_t ref) {
return statementCheck((Db*) db, (StatementRef) { .val = ref });
}
// You must call this with the childStatementsMutex held.
static void matchAddChildStatement(Db* db, Match* match, StatementRef child) {
listOfEdgeToAdd(statementChecker, db,
&match->childStatements, child.val);
}
void matchAddDestructor(Match* m, Destructor* d) {
pthread_mutex_lock(&m->destructorSetMutex);
destructorSetAdd(&m->destructorSet, d);
pthread_mutex_unlock(&m->destructorSetMutex);
}
void matchCompleted(Match* match) {
match->isCompleted = true;
}
// Call matchRemoveSelf when ANY of the match's parent statements is
// removed.
//
// FIXME: Make this thread-safe (if called by multiple removers at the
// same time, it shouldn't double-free).
extern ThreadControlBlock threads[];
extern void traceItem(char* buf, size_t bufsz, WorkQueueItem item);
void matchRemoveSelf(Db* db, Match* match) {
/* assert(match > &db->matchPool[0] && match < &db->matchPool[65536]); */
if (match->atomicallyVersion != NULL &&
match->atomicallyVersion->rootMatch == match &&
((match->atomicallyVersion->atomically->latestConvergedVersion == NULL) ||
match->atomicallyVersion->number >=
match->atomicallyVersion->atomically->latestConvergedVersion->number)) {
// Skip this removal; this is a root match owned by an
// AtomicallyVersion; leave it to the atomically reaper.
match->parentWasRemoved = true;
return;
}
// Walk through each child statement and remove this match as a
// parent of that statement.
pthread_mutex_lock(&match->childStatementsMutex);
ListOfEdgeTo* childStatements = match->childStatements;
if (childStatements == NULL) {
// Someone else has done / is doing removal. Abort.
pthread_mutex_unlock(&match->childStatementsMutex);
return;
}
// This blocks further child statements from being added to this
// match (if they were added, then we wouldn't be able to remove
// them).
match->childStatements = NULL;
genRcMarkAsDead(&match->genRc);
pthread_mutex_unlock(&match->childStatementsMutex);
for (size_t i = 0; i < childStatements->nEdges; i++) {
StatementRef childRef = { .val = childStatements->edges[i] };
Statement* child = statementAcquire(db, childRef);
if (child != NULL) {
statementDecrParentCountAndMaybeRemoveSelf(db, child);
statementRelease(db, child);
}
}
free(childStatements);
if (!match->isCompleted) {
// Signal the match worker thread to terminate the match
// execution.
ThreadControlBlock *workerThread = &threads[match->workerThreadIndex];
if (timestamp_get(workerThread->clockid) - workerThread->currentItemStartTimestamp > 100000000) {
char buf[10000]; traceItem(buf, sizeof(buf), workerThread->currentItem);
fprintf(stderr, "KILL (%.150s)\n", buf);
kill(workerThread->tid, SIGUSR1);
}
}
}
////////////////////////////////////////////////////////////
// Database:
////////////////////////////////////////////////////////////
Db* dbNew() {
Db* ret = calloc(sizeof(Db), 1);
ret->statementPool[0].genRc = (GenRc) { .gen = -1, .rc = 0 };
ret->statementPoolNextIdx = 1;
ret->matchPool[0].genRc = (GenRc) { .gen = -1, .rc = 0 };
ret->matchPoolNextIdx = 1;
ret->clauseToStatementRef = trieNew();
sh_new_arena(ret->holds);
mutexInit(&ret->holdsMutex);
mutexInit(&ret->atomicallysMutex);
return ret;
}
// Used by trie-graph.folk. Avoid if you can.
void dbLockClauseToStatementRef(Db* db) {
epochBegin();
}
const Trie* dbGetClauseToStatementRef(Db* db) {
return db->clauseToStatementRef;
}
void dbUnlockClauseToStatementRef(Db* db) {
epochEnd();
}
// Query
ResultSet* dbQuery(Db* db, Clause* pattern) {
ResultSet *resultSet;
size_t maxResults = 500;
do {
resultSet = malloc(SIZEOF_RESULTSET(maxResults));
epochBegin();
resultSet->nResults =
trieLookup(db->clauseToStatementRef, pattern,
(uint64_t*) resultSet->results, maxResults);
epochEnd();
if (resultSet->nResults < maxResults) {
break;
}
maxResults *= 2;
if (maxResults > 10 * 1000) {
fprintf(stderr, "dbQuery: Too many results for query (%s)\n",
clauseToString(pattern));
exit(1);
}
free(resultSet);
} while (true);
return resultSet;
}
AtomicallyVersion* dbFreshAtomicallyVersionOnKey(Db* db, const char* key,
MatchRef rootMatchRef) {
mutexLock(&db->atomicallysMutex);
Atomically* atomically = NULL;
for (unsigned long i = 0; i < sizeof(db->atomicallys)/sizeof(db->atomicallys[0]); i++) {
if (db->atomicallys[i].key != NULL &&
strcmp(db->atomicallys[i].key, key) == 0) {
atomically = &db->atomicallys[i];
break;
}
}
if (atomically == NULL) {
for (unsigned long i = 0; i < sizeof(db->atomicallys)/sizeof(db->atomicallys[0]); i++) {
if (db->atomicallys[i].key == NULL) {
atomically = &db->atomicallys[i];
atomically->key = strdup(key);
atomically->nextNumber = 0;
atomically->allVersions = NULL;
atomically->timeout = 100000000; // 100ms
atomically->latestConvergedTime = 0;
break;
}
}
}
if (atomically == NULL) {
fprintf(stderr, "dbGetOrCreateAtomicallyByKey: Ran out of Atomically slots\n");
exit(1);
}
mutexUnlock(&db->atomicallysMutex);
AtomicallyVersion* atomicallyVersion = malloc(sizeof(AtomicallyVersion));
atomicallyVersion->atomically = atomically;
// FIXME: assert old values are bad, do something with refcount
atomicallyVersion->number = atomically->nextNumber++;
// An AtomicallyVersion should start unconverged, assuming that it
// always gets set into a currently running (incomplete) match
// that can mark it as converged when done.
atomicallyVersion->inflightCount = 1;
atomicallyVersion->rootMatch = matchAcquire(db, rootMatchRef);
assert(atomicallyVersion->rootMatch != NULL);
// Add this version to atomically->allVersions list
AtomicallyVersionList* newNode = malloc(sizeof(AtomicallyVersionList));
newNode->version = atomicallyVersion;
AtomicallyVersionList* oldList;
do {
oldList = atomically->allVersions;
newNode->next = oldList;
} while (!atomic_compare_exchange_weak(&atomically->allVersions,
&oldList,
newNode));
return atomicallyVersion;
}
static void dbAtomicallyReapAllVersions(Db* db, Atomically* atomically,
AtomicallyVersion* newlyConvergedVersion,
bool onlyReapConvergedVersions) {