-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathspace.c
3376 lines (2823 loc) · 101 KB
/
space.c
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
/*
//
//
// TRAVAUX EN COURS
// WORK IN PROGRESS
// nouvelle représentation sur 24 octets (22 effectif)
// nouvel atom : small
// nouvelle propriété faible: rootage faible, "weak" flag
// - n'empêche pas l'oubli (le GC) de ses bouts
// - est supprimée avec ses bouts
// Toute flèche dispose des flags suivants
// R: roots flag, indique que la flèche appartient au contexte globale
// W: weakness flag, liaison faible dans le contexte globale
// la flèche est oubliée quand ses 2 bouts sont déracinés
//
// A TERMINER / A ETUDIER
// Option: types de rootage faibles: par la queue, par la tete, doublement
// API: weak(arrow)
// exemple d'usage: root(A(weak(root(atom('hello'))), atom('world'))
// si 'hello' déracinée, 'hello'->'world' aussi
// weak(A) est immédiatement "loose" (sur le point d'être oubliée) si aucun des 2 bouts de A n'est enraciné
// B: Brotherhood flag, indique que la flèche sert à relier entre elles les composantes d'une collection des flèches enfants d'une autre flèche
// utiliser une indirection (Eve->bout) pour ignorer un rootage non désiré
// unroot regarde s'il y a des enfants faibles et les déracinent
// attention: préfèrer xls_weak_link(C,A,B) = weak((C,A)=>(C,B)) et utiliser par ex xls_partnersOf(C,A) pour faire un lien faible entre 2 objets
// xls_weak(c,a) devrait permettre d'enrichir un contexte sans le verouiller, cette flèche étant libérée quand plus aucune autre flèche non faible n'est vraie dans ce contexte
*/
#define _XOPEN_SOURCE 600
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include <printf.h>
#include <ctype.h>
#include <pthread.h>
#include "entrelacs/entrelacs.h"
#include "mem0.h"
#include "mem.h"
#include "sha1.h"
#define LOG_CURRENT LOG_SPACE
#include "log.h"
/** Memory corruption trigger */
#define MAX_CHILDCELLPROBE 32
/** statistic structure and variables
*/
static struct s_space_stats {
// operation and other events counters
int get; //< GET op counter
int root; //< root op counter
int unroot; //< unroot op counter
int new; //< new arrow event counter
int found; //< found arrow event counter
int connect; //< connect op counter
int disconnect; //< disconnect op counter
int atom; //< atom creation counter
int pair; //< pair cration counter
int forget; //< forget op counter
} space_stats_zero = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0
}, space_stats = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
/** Things to make the API parallelizable
*/
static pthread_mutexattr_t apiMutexAttr;
static pthread_mutex_t apiMutex = PTHREAD_MUTEX_INITIALIZER;
#define LOCK() pthread_mutex_lock(&apiMutex)
#define LOCK_END() pthread_mutex_unlock(&apiMutex)
#define LOCK_OUT(X) (pthread_mutex_unlock(&apiMutex), (Arrow)X)
#define LOCK_OUT64(X) (pthread_mutex_unlock(&apiMutex), (uint64_t))
#define LOCK_OUTSTR(X) (pthread_mutex_unlock(&apiMutex), (char*)X)
static pthread_cond_t apiNowDormant; // Signaled when all thread are ready to commit
static pthread_cond_t apiNowActive; // Signaled once a thread has finished commit
static int apiActivity = 0; // Activity counter; Incremented/Decremented by xl_begin/xl_over. Decremented when waiting for commit. Incremented again after.
static int spaceGCDone = 1; // 1->0 when a thread starts waiting in xl_commit()/xl_over(), 0->1 when all threads synced and GC is done
static int memCommitDone = 1; // 1->0 when a thread starts waiting in xl_commit(), 0->1 when all threads synced and mem_commit(); occurs only if !memCommitDone
static int memCloseDone = 1; // 1->0 when a xl_over thread starts waiting, 0->1 when all threads synced and a xl_commit() thread does commit (without actually mem_close)
#define ACTIVITY_BEGIN() (!apiActivity++ ? (void)pthread_cond_signal(&apiNowActive) : (void)0)
#define ACTIVITY_OVER() (apiActivity ? (--apiActivity ? (void)0 : (void)pthread_cond_signal(&apiNowDormant)) : (void)0)
#define WAIT_DORMANCY() (apiActivity > 0 ? (void)pthread_cond_wait(&apiNowDormant, &apiMutex) : (void)0)
/*
* Size limit from where data is stored as "blob" or "tag" or "small"
*/
#define TAG_MINSIZE 12
#define BLOB_MINSIZE 100
/*
* Eve
*/
#define EVE (0)
const Arrow Eve = EVE;
#define EVE_HASH (0x8421A593U)
/*
* Memory device
*
* -------+------+------+------+-------
* ... | cell | cell | cell | ...
* -------+------+------+------+-------
*
*/
/** Cell structure (24 bytes).
*
* +---------------------------------------+---+---+
* | data | T | P |
* +---------------------------------------+---+---+
* 22 1 1
*
* P: "Peeble" count aka "More" counter (8 bits)
* T: Cell type ID (8 bits)
* Data: Data (22 bytes)
*
*
*/
#pragma pack(push) /* push current alignment to stack */
#pragma pack(1) /* set alignment to 1 byte boundary */
typedef union u_cell {
/** opaque for mem1 */
CellBody u_body;
struct u_full {
char data[22];
unsigned char peeble;
unsigned char type;
} full;
#define PEEBLE_MAX 0xFFu
/*
* Cell content type
*/
#define CELLTYPE_EMPTY 0
#define CELLTYPE_PAIR 1
#define CELLTYPE_SMALL 2
#define CELLTYPE_TAG 3
#define CELLTYPE_BLOB 4
#define CELLTYPE_ARROWLIMIT CELLTYPE_BLOB
#define CELLTYPE_SLICE 5
#define CELLTYPE_LAST 6
#define CELLTYPE_SYNC 7
#define CELLTYPE_REATTACHMENT 7
#define CELLTYPE_CHILDREN 8
/*
* raw
*/
struct s_uint {
uint32_t data[6];
} uint;
/* T = 0: empty cell.
* +---------------------------------------------------+
* | junk |
* +---------------------------------------------------+
* 22 bytes
*/
/** T = 1, 2, 3, 4: arrow definition.
* +--------+----------------------+-----------+----------+----+----+
* | hash | full or partial def | RWC0dWnCn | Child0 | cr | dr |
* +--------+----------------------+-----------+----------+----+----+
* 4 8 4 4 1 1
* where RWC0dWnCn = R|W|C0d|Wn|Cn
*
* R = root flag (1 bit)
* W = weak flag (1 bit)
* C0d = child0 direction (1 bit)
* Wn = Weak children count (14 bits)
* Cn = Non-weak children count (15 bits)
*
* child0 = 1st child of this arrow
* cr = children revision
* dr = definition revision
*/
struct s_arrow {
uint32_t hash;
char def[8];
uint32_t RWWnCn;
uint32_t child0;
unsigned char cr;
unsigned char dr;
} arrow;
/** RWWnCn flags.
*/
#define FLAGS_ROOTED 0x80000000u
#define FLAGS_WEAK 0x40000000u
#define FLAGS_C0D 0x20000000u
#define FLAGS_WEAKCHILDRENMASK 0x1FFF8000u
#define MAX_WEAKREFCOUNT 0x1FFFu
#define FLAGS_CHILDRENMASK 0X00007FFFu
#define MAX_REFCOUNT 0x7FFFu
/* T = 1: regular pair.
* +--------+--------+--------+-----------+----------+----+----+
* | hash | tail | head | RWC0dWnCn | Child0 | cr | dr |
* +--------+--------+--------+-----------+----------+----+----+
* 4 4 4 4 4 1 1
*/
struct s_pair {
uint32_t hash;
uint32_t tail;
uint32_t head;
uint32_t RWWnCn;
uint32_t child0;
unsigned char cr;
unsigned char dr;
} pair;
/* T = 2: small.
* +---+-------+-------------------+-----------+----------+----+----+
* | s | hash3 | data | RWC0dWnCn | Child0 | cr | dr |
* +---+-------+-------------------+-----------+----------+----+----+
* 1 3 8
* <---hash--->
*
* s : small size (0 < s <= 11)
* hash3: (data 1st word ^ 2d word ^ 3d word) & 0xFFFFFFu
* ... if s > 8, one can get 3 additional bytes, by computing:(1st word ^ 2d word ^ hash) & 0xFFFFFFu
*/
struct s_small {
unsigned char s;
char hash3[3];
char data[8];
uint32_t RWWnCn;
uint32_t child0;
unsigned char cr;
unsigned char dr;
} small;
/* T = 3: tag or 4: blob footprint.
* +--------+------------+----+-----------+----------+----+----+
* | hash | slice0 | J0 | RWC0dWnCn | Child0 | cr | dr |
* +--------+------------+----+-----------+----------+----+----+
* 4 7 1
* J = first slice jump, h-sequence multiplier (1 byte)
*/
struct s_tagOrBlob {
uint32_t hash;
char slice0[7];
unsigned char jump0;
uint32_t RWWnCn;
uint32_t child0;
unsigned char cr;
unsigned char dr;
} tagOrBlob;
#define MAX_JUMP0 0xFFu
/* T = 5: slice of binary string (tag/blob)
* +-----------------------------------------+---+
* | data | J |
* +-----------------------------------------+---+
* 21 1
*/
struct s_slice {
char data[21];
unsigned char jump;
} slice;
#define MAX_JUMP 0xFFu
/* T = 6: last slice of binary string
* +-----------------------------------------+---+
* | data | s |
* +-----------------------------------------+---+
* 21 1
* s = slice size
*/
struct s_last {
char data[21];
unsigned char size;
} last;
/* T = 7: sequence reattachment
* +--------+--------+--------------+
* | from | to | ... |
* +--------+--------+--------------+
* 4 4
*/
struct s_reattachment {
uint32_t from;
uint32_t to;
char junk[14];
} reattachment;
/* T = 8: children cell
* +------+------+------+------+------+---+
* | C4 | C3 | C2 | C1 | C0 |td |
* +------+------+------+------+------+---+
* 4 4 4 4 4 2
* Ci : Child or list terminator
* (list terminator = parent address with flag)
* td: terminators (1 byte) . directions (1 byte, 1 outgoing)
* 5 significative bits per byte
*
*/
struct s_children {
uint32_t C[5];
uint16_t directions;
} children;
} Cell;
#pragma pack(pop) /* restore original alignment from stack */
// The loose log.
// This is a dynamic array containing all arrows in loose state.
// it grows geometrically.
static Arrow *looseLog = NULL;
static uint32_t looseLogMax = 0;
static uint32_t looseLogSize = 0;
// private functions
char* digestOf(Arrow a, Cell* cellp, uint32_t *l);
static void cell_getSmallPayload(Cell *cell, char* buffer) {
int bigSmall = cell->small.s > 8;
memcpy(buffer, cell->small.data, bigSmall ? 8 : cell->small.s);
if (bigSmall) {
buffer[8] = cell->small.hash3[0] ^ cell->small.data[1] ^ cell->small.data[5];
if (cell->small.s > 9) {
buffer[9] = cell->small.hash3[1] ^ cell->small.data[2] ^ cell->small.data[6];
if (cell->small.s > 10) {
buffer[10] = cell->small.hash3[2] ^ cell->small.data[3] ^ cell->small.data[7];
}
}
}
}
/** log cell access.
* operation = R/W
* address
* cell pointer
*/
static void logCell(int logLevel, int line, char operation, Address address, Cell* cell) {
static const char* cats[] = {
"EMPTY",
"PAIR",
"SMALL",
"TAG",
"BLOB",
"SLICE",
"LAST",
"REATTACHMENT",
"CHILDREN"
};
unsigned type = (unsigned)cell->full.type;
unsigned peeble = (unsigned)cell->full.peeble;
const char* cat = cats[type];
if (type == CELLTYPE_EMPTY) {
LOGPRINTF(logLevel, "%d %c %06x EMPTY (peeble=%02x)",
line, operation, address, peeble);
return;
}
if (type <= CELLTYPE_ARROWLIMIT) {
char flags[] = {
(cell->arrow.RWWnCn & FLAGS_ROOTED ? 'R' : '.'),
(cell->arrow.RWWnCn & FLAGS_WEAK ? 'W' : '.'),
(cell->arrow.child0 ? (cell->arrow.RWWnCn & FLAGS_C0D ? 'O' : 'I') : '.'),
'\0'
};
uint32_t hash = cell->arrow.hash;
int weakChildrenCount = (int)((cell->arrow.RWWnCn & FLAGS_WEAKCHILDRENMASK) >> 15);
int childrenCount = (int)(cell->arrow.RWWnCn & FLAGS_CHILDRENMASK);
int cr = (int)cell->arrow.cr;
int dr = (int)cell->arrow.dr;
if (type == CELLTYPE_PAIR) {
LOGPRINTF(logLevel, "%d %c %06x peeble=%02x type=%1x hash=%08x Flags=%s weakCount=%04x refCount=%04x child0=%06x cr=%02x dr=%02x %s tail=%06x head=%06x",
line, operation, address, peeble, type,
hash, flags, weakChildrenCount, childrenCount, cell->arrow.child0, cr, dr, cat,
cell->pair.tail,
cell->pair.head);
} else if (type == CELLTYPE_SMALL) {
int s = (int)cell->small.s;
char buffer[11];
cell_getSmallPayload(cell, buffer);
LOGPRINTF(logLevel, "%d %c %06x peeble=%02x type=%1x hash=%08x Flags=%s weakCount=%04x refCount=%04x child0=%06x cr=%02x dr=%02x %s size=%d data=%.*s",
line, operation, address, peeble, type,
hash, flags, weakChildrenCount, childrenCount, cell->arrow.child0, cr, dr, cat,
s, s, buffer);
} else if (type == CELLTYPE_BLOB || type == CELLTYPE_TAG) {
LOGPRINTF(logLevel, "%d %c %06x peeble=%02x type=%1x hash=%08x Flags=%s weakCount=%04x refCount=%04x child0=%06x cr=%02x dr=%02x %s jump0=%1x slice0=%.7s",
line, operation, address, peeble, type,
hash, flags, weakChildrenCount, childrenCount, cell->arrow.child0, cr, dr, cat,
(int)cell->tagOrBlob.jump0, cell->tagOrBlob.slice0);
}
} else if (type == CELLTYPE_SLICE) {
LOGPRINTF(logLevel, "%d %c %06x peeble=%02x type=%1x %s jump=%1x data=%.21s",
line, operation, address, peeble, type, cat,
(int)cell->slice.jump, cell->slice.data);
} else if (type == CELLTYPE_LAST) {
LOGPRINTF(logLevel, "%d %c %06x peeble=%02x type=%1x %s size=%d data=%.*s",
line, operation, address, peeble, type, cat,
(int)cell->last.size,
(int)cell->last.size,
cell->last.data);
} else if (type == CELLTYPE_CHILDREN) {
char directions[] = {
'[',
(cell->children.directions & 0x01 ? 'O' : '.'),
(cell->children.directions & 0x02 ? 'O' : '.'),
(cell->children.directions & 0x04 ? 'O' : '.'),
(cell->children.directions & 0x08 ? 'O' : '.'),
(cell->children.directions & 0x10 ? 'O' : '.'),
(cell->children.directions & 0x0100 ? 'T' : '.'),
(cell->children.directions & 0x0200 ? 'T' : '.'),
(cell->children.directions & 0x0400 ? 'T' : '.'),
(cell->children.directions & 0x0800 ? 'T' : '.'),
(cell->children.directions & 0x1000 ? 'T' : '.'),
']',
'\0'
};
LOGPRINTF(logLevel, "%d %c %06x peeble=%02x type=%1x %s C[]={%x %x %x %x %x} D=%s",
line, operation, address, peeble, type, cat,
cell->children.C[0],
cell->children.C[1],
cell->children.C[2],
cell->children.C[3],
cell->children.C[4],
directions);
} else if (type == CELLTYPE_REATTACHMENT) {
LOGPRINTF(logLevel, "%d %c %06x peeble=%02x type=%1x %s from=%x to=%x",
line, operation, address, peeble, type, cat,
(int)cell->reattachment.from, cell->reattachment.to);
} else {
LOGPRINTF(logLevel, "%d %c %06x peeble=%02x type=%1x ANOMALY",
line, operation, address, peeble, type);
assert(0 == 1);
}
}
#define LOGCELL(operation, address, cell) logCell(LOG_DEBUG, __LINE__, operation, address, cell)
static void showCell(Address a) {
Cell cell;
mem_get(a, &cell.u_body);
logCell(LOG_INFO, __LINE__, ' ', a, &cell);
}
static void looseLogAdd(Address a) {
geoalloc((char**) &looseLog, &looseLogMax, &looseLogSize, sizeof (Arrow), looseLogSize + 1);
looseLog[looseLogSize - 1] = a;
}
static void looseLogRemove(Address a) {
assert(looseLogSize);
// if the arrow is at the log end, then one reduces the log
if (looseLog[looseLogSize - 1] == a)
looseLogSize--;
// else ... nothing is done.
}
/* ________________________________________
* Hash functions
* One computes 3 kinds of hashcode.
* * hashAddress: default cell address of an arrow.
* hashAddress = hashArrow(tail, head) % PRIM0 for a regular arrow
* hashAddress = hashString(string) for a tag arrow
* * hashProbe: probing offset when looking for a free cell nearby a conflict.
* hProbe = hashArrow(tail, head) % PRIM1 for a regular pair
* * hashChain: offset to separate chained cells
* chained data slices (and tuple ends) are separated by JUMP * h3 cells
* * hashChild : offset to probe children cells
*/
/* hash function to get H1 from a regular pair definition */
uint64_t hashPair(uint64_t tail, uint64_t head) {
return PRIM1 + (tail << 20) + (head << 4) + tail + head; // (tail << 20) ^ (tail >> 4) ^ head;
}
/* hash function to get H1 from a tag arrow definition */
uint64_t hashStringAndGetSize(char *str, uint32_t* length) { // simple string hash
uint64_t hash = 5381;
char *s = str;
int c;
uint32_t l = 0;
while (c = *s++) { // for all bytes up to the null terminator
// 5 bits shift only because ASCII varies within 5 bits
hash = ((hash << 5) + hash) + c;
l++;
}
// // The null-terminator is counted and hashed for consistancy with hashRaw
// hash = ((hash << 5) + hash) + c;
// l++;
TRACEPRINTF("hashStringAndGetSize(\"%s\") = [ %016llx ; %d] ", str, hash, l);
*length = l;
return hash;
}
/* hash function to get H1 from a binary tag arrow definition */
uint64_t hashRaw(char *buffer, uint32_t length) { // simple string hash
uint64_t hash = 5381;
int c;
char *p = buffer;
uint32_t l = length;
while (l--) { // for all bytes (even last one)
c = *p++;
// 5 bits shift only because ASCII generally works within 5 bits
hash = ((hash << 5) + hash) + c;
}
hash = (hash ^ (hash >> 32) ^ (hash << 32));
TRACEPRINTF("hashRaw(%d, \"%.*s\") = %016llx", length, length, buffer, hash);
return hash;
}
/* hash function to get hashChain from a tag or blob containing cell */
uint32_t hashChain(Cell* cell) {
// This hash mixes the cell content
uint32_t inverted = cell->arrow.hash >> 16 & cell->arrow.hash << 16;
if (cell->full.type == CELLTYPE_BLOB || cell->full.type == CELLTYPE_TAG)
inverted = inverted ^ cell->uint.data[1] ^ cell->uint.data[2];
return inverted;
}
/* hash function to get hashChild from a cell caracteristics */
uint32_t hashChild(Cell* cell) {
return hashChain(cell) ^ 0xFFFFFFFFu;
}
/* ________________________________________
* The blob cryptographic hash computing fonction.
* This function returns a string used to define a tag arrow.
*
*/
#define CRYPTO_SIZE 40
char* crypto(uint32_t size, char* data, char output[CRYPTO_SIZE + 1]) {
char h[20];
sha1(data, size, h);
sprintf(output, "%08x%08x%08x%08x%08x", *(uint32_t *) h, *(uint32_t *) (h + 4), *(uint32_t *) (h + 8),
*(uint32_t *) (h + 12), *(uint32_t *) (h + 16));
return output;
}
/* MACROS
* ====== */
/* Address shifting */
#define SHIFT_LIMIT 20
#define PROBE_LIMIT 40
#define ADDRESS_SHIFT(ADDRESS, NEW, OFFSET) \
(NEW = (((ADDRESS) + ((OFFSET)++)) % (SPACE_SIZE)))
// FIXME ADDRESS_JUMP
#define ADDRESS_JUMP(ADDRESS, NEW, OFFSET, JUMP) \
(NEW = (((((ADDRESS) + ((JUMP) * (OFFSET))) % (SPACE_SIZE)) + ((JUMP) * ((JUMP) - 1) / 2)) % (SPACE_SIZE)))
/* Cell testing */
#define CELL_CONTAINS_ARROW(CELL) ((CELL).full.type != CELLTYPE_EMPTY && (CELL).full.type <= CELLTYPE_ARROWLIMIT)
#define CELL_CONTAINS_ATOM(CELL) ((CELL).full.type == CELLTYPE_BLOB || (CELL).full.type <= CELLTYPE_TAG)
/** function used to go to the first cell in a chain
*/
static Address jumpToFirst(Cell* cell, Address address, Address offset) {
Address next = address;
assert(CELL_CONTAINS_ATOM(*cell));
int jump = cell->tagOrBlob.jump0 + 1; // Note: jump=1 means 2 shifts
ADDRESS_JUMP(address, next, offset, jump);
if (jump == MAX_JUMP0 + 1) {
// one needs to look for a reattachment (sync) cell
offset += MAX_JUMP0 + 1;
Cell probed;
mem_get(next, &probed.u_body);
ONDEBUG((LOGCELL('R', next, &probed)));
int safeguard = PROBE_LIMIT;
while (--safeguard && !(
probed.full.type == CELLTYPE_REATTACHMENT
&& probed.reattachment.from == address)) {
ADDRESS_SHIFT(next, next, offset);
mem_get(next, &probed.u_body);
ONDEBUG((LOGCELL('R', next, &probed)));
}
assert(safeguard);
next = probed.reattachment.to;
}
return next;
}
static Address jumpToNext(Cell* cell, Address address, Address offset) {
Address next = address;
assert(cell->full.type == CELLTYPE_SLICE);
uint32_t jump = cell->slice.jump + 1; // Note: jump == 1 means 2 shifts
ADDRESS_JUMP(address, next, offset, jump);
if (jump == MAX_JUMP + 1) {
// one needs to look for a reattachment (sync) cell
Cell probed;
mem_get(next, &probed.u_body);
ONDEBUG((LOGCELL('R', next, &probed)));
offset += MAX_JUMP + 1;
int safeguard = PROBE_LIMIT;
while (--safeguard && !(
probed.full.type == CELLTYPE_REATTACHMENT
&& probed.reattachment.from == address)) {
ADDRESS_SHIFT(next, next, offset);
mem_get(next, &probed.u_body);
ONDEBUG((LOGCELL('R', next, &probed)));
}
assert(safeguard);
next = probed.reattachment.to;
}
return next;
}
/** return Eve */
Arrow xl_Eve() {
return EVE;
}
/** retrieve the arrow corresponding to data at $str with size $length and precomputed $hash.
* Will create the singleton if missing except if $ifExist is set.
* $str might be a blob signature or a tag content.
*/
Arrow payload(int cellType, int length, char* str, uint64_t payloadHash, int ifExist) {
Address hashAddress, hashProbe, hChain;
uint32_t l;
uint32_t hash;
Address probeAddress, firstFreeAddress, next;
Cell probed, sliceCell;
unsigned i, safeguard, jump;
char c, *p;
space_stats.atom++;
if (!length) {
return EVE;
}
hash = payloadHash & 0xFFFFFFFFU;
hashAddress = hash % PRIM0;
hashProbe = hash % PRIM1;
if (!hashProbe) hashProbe = 1; // offset can't be 0
// Search for an existing singleton
probeAddress = hashAddress;
firstFreeAddress = EVE;
while (1) {
mem_get(probeAddress, &probed.u_body);
ONDEBUG((LOGCELL('R', probeAddress, &probed)));
if (probed.full.type == CELLTYPE_EMPTY) {
firstFreeAddress = probeAddress;
} else if (probed.full.type == cellType
&& probed.tagOrBlob.hash == hash
&& !memcmp(probed.tagOrBlob.slice0, str, sizeof(probed.tagOrBlob.slice0))) {
// chance we found it
// now comparing the whole string
hChain = hashChain(&probed) % PRIM1;
if (!hChain) hChain = 1; // offset can't be 0
p = str + sizeof(probed.tagOrBlob.slice0);
l = length - sizeof(probed.tagOrBlob.slice0);
assert(l > 0);
i = 0;
next = jumpToFirst(&probed, probeAddress, hChain);
mem_get(next, &sliceCell.u_body);
ONDEBUG((LOGCELL('R', next, &sliceCell)));
while ((c = *p++) == sliceCell.slice.data[i++] && --l) { // cmp loop
if (i == sizeof(sliceCell.slice.data)) {
// one shifts to the next linked cell
if (sliceCell.full.type == CELLTYPE_LAST) {
break; // the chain is over
}
next = jumpToNext(&sliceCell, next, hChain);
mem_get(next, &sliceCell.u_body);
ONDEBUG((LOGCELL('R', next, &sliceCell)));
i = 0;
}
} // cmp loop
if (!l && sliceCell.full.type == CELLTYPE_LAST
&& sliceCell.last.size == i) {
// exact match
space_stats.found++;
return probeAddress; // found arrow
} // match
} // if candidate
// Not the singleton
if (!probed.full.peeble) { // nothing further
break; // Miss
}
ADDRESS_SHIFT(probeAddress, probeAddress, hashProbe);
}
if (ifExist) {
// if one only wants to check arrow existency, then a miss is a miss
return EVE;
}
// else ... one creates a corresponding arrow right now
space_stats.new++;
space_stats.atom++;
if (firstFreeAddress == EVE) {
Cell probed;
int safeguard = PROBE_LIMIT;
while (--safeguard) {
ADDRESS_SHIFT(probeAddress, probeAddress, hashProbe);
mem_get(probeAddress, &probed.u_body);
ONDEBUG((LOGCELL('R', probeAddress, &probed)));
if (probed.full.type == CELLTYPE_EMPTY) {
firstFreeAddress = probeAddress;
break;
}
}
assert(safeguard);
}
// Create an arrow representation
Address current, newArrow = firstFreeAddress;
Cell newCell, nextCell, currentCell;
mem_get(newArrow, &newCell.u_body);
ONDEBUG((LOGCELL('R', newArrow, &newCell)));
/* | hash | slice0 | J | R.W.Wn.Cn | Child0 | cr | dr |
* 4 7 1
*/
newCell.tagOrBlob.hash = hash;
memcpy(newCell.tagOrBlob.slice0, str, sizeof(newCell.tagOrBlob.slice0));
newCell.arrow.RWWnCn = 0;
newCell.arrow.child0 = 0;
newCell.full.type = cellType;
newCell.arrow.dr = space_stats.new & 0xFFu;
hChain = hashChain(&newCell) % PRIM1;
if (!hChain) hChain = 1; // offset can't be 0
Address offset = hChain;
ADDRESS_SHIFT(newArrow, next, offset);
mem_get(next, &nextCell.u_body);
ONDEBUG((LOGCELL('R', next, &nextCell)));
jump = 0;
safeguard = PROBE_LIMIT;
while (--safeguard && nextCell.full.type != CELLTYPE_EMPTY) {
jump++;
ADDRESS_SHIFT(next, next, offset);
mem_get(next, &nextCell.u_body);
ONDEBUG((LOGCELL('R', next, &nextCell)));
}
assert(safeguard);
if (jump >= MAX_JUMP) {
Address sync = next;
Cell syncCell = nextCell;
syncCell.full.type = CELLTYPE_REATTACHMENT;
syncCell.reattachment.from = newArrow;
syncCell.reattachment.to = newArrow; // will be overwritten as soon as possible
mem_set(sync, &syncCell.u_body);
ONDEBUG((LOGCELL('W', sync, &syncCell)));
offset = hChain;
ADDRESS_SHIFT(next, next, offset);
mem_get(next, &nextCell.u_body);
ONDEBUG((LOGCELL('R', next, &nextCell)));
safeguard = PROBE_LIMIT;
while (--safeguard && nextCell.full.type == CELLTYPE_EMPTY) {
ADDRESS_SHIFT(next, next, offset);
mem_get(next, &nextCell.u_body);
ONDEBUG((LOGCELL('R', next, &nextCell)));
}
assert(safeguard);
syncCell.reattachment.to = next;
mem_set(sync, &syncCell.u_body);
ONDEBUG((LOGCELL('W', sync, &syncCell)));
jump = MAX_JUMP;
}
newCell.tagOrBlob.jump0 = jump;
mem_set(newArrow, &newCell.u_body);
ONDEBUG((LOGCELL('W', newArrow, &newCell)));
current = next;
currentCell = nextCell;
p = str + sizeof(newCell.tagOrBlob.slice0);
l = length - sizeof(newCell.tagOrBlob.slice0);
i = 0;
c = 0;
assert(l);
while (1) {
c = *p++;
currentCell.slice.data[i] = c;
if (!--l) break;
if (++i == sizeof(currentCell.slice.data)) {
offset = hChain;
ADDRESS_SHIFT(current, next, offset);
mem_get(next, &nextCell.u_body);
ONDEBUG((LOGCELL('R', next, &nextCell)));
jump = 0;
int safeguard = PROBE_LIMIT;
while (nextCell.full.type != CELLTYPE_EMPTY && --safeguard) {
jump++;
ADDRESS_SHIFT(next, next, offset);
mem_get(next, &nextCell.u_body);
ONDEBUG((LOGCELL('R', next, &nextCell)));
}
assert(safeguard);
if (jump >= MAX_JUMP) {
Address sync = next;
Cell syncCell = nextCell;
syncCell.full.type = CELLTYPE_REATTACHMENT;
syncCell.reattachment.from = current;
syncCell.reattachment.to = current; // will be overwritten as soon as possible
mem_set(sync, &syncCell.u_body);
ONDEBUG((LOGCELL('W', sync, &syncCell)));
offset = hChain;
ADDRESS_SHIFT(next, next, offset);
mem_get(next, &nextCell.u_body);
ONDEBUG((LOGCELL('R', next, &nextCell)));
int safeguard = PROBE_LIMIT;
while (--safeguard && nextCell.full.type == CELLTYPE_EMPTY) {
ADDRESS_SHIFT(next, next, offset);
mem_get(next, &nextCell.u_body);
ONDEBUG((LOGCELL('R', next, &nextCell)));
}
assert(safeguard);
syncCell.reattachment.to = next;
mem_set(sync, &syncCell.u_body);
ONDEBUG((LOGCELL('W', sync, &syncCell)));
jump = MAX_JUMP;
}
currentCell.full.type = CELLTYPE_SLICE;
currentCell.slice.jump = jump;
mem_set(current, ¤tCell.u_body);
ONDEBUG((LOGCELL('W', current, ¤tCell)));
i = 0;
current = next;
mem_get(current, ¤tCell.u_body);
}
}
currentCell.full.type = CELLTYPE_LAST;
currentCell.last.size = 1 + i /* size */;
mem_set(current, ¤tCell.u_body);
ONDEBUG((LOGCELL('W', current, ¤tCell)));
// Now incremeting "peeble" counters in the probing path up to the new singleton
// important to reinitialize probing variables
probeAddress = /* hash % PRIM0 */ hashAddress;
hashProbe = hash % PRIM1;
if (!hashProbe)
hashProbe = 1;
while (probeAddress != newArrow) {
Cell probed;
mem_get(probeAddress, &probed.u_body);
ONDEBUG((LOGCELL('R', probeAddress, &probed)));
if (probed.full.peeble != PEEBLE_MAX)
probed.full.peeble++;
mem_set(probeAddress, &probed.u_body);
ONDEBUG((LOGCELL('W', probeAddress, &probed)));
ADDRESS_SHIFT(probeAddress, probeAddress, hashProbe);
}
// log loose arrow
looseLogAdd(newArrow);
return newArrow;
}
uint32_t hashOf(Arrow a) {
Cell cell;
if (a == XL_EVE)
return EVE_HASH; // Eve hash is not zero!
else if (a >= SPACE_SIZE)
return 0; // Out of space
else {
mem_get(a, &cell.u_body);
ONDEBUG((LOGCELL('R', a, &cell)));
if (cell.full.type == CELLTYPE_EMPTY
|| cell.full.type > CELLTYPE_ARROWLIMIT)
return 0; // Not an arrow
else
return cell.arrow.hash; // hash
}
}
uint32_t xl_hashOf(Arrow a) {
LOCK();
uint32_t cs = hashOf(a);
return LOCK_OUT(cs);
}
/** retrieve small
* by creating the singleton if not found.
* except if ifExist param is set.
*/
static Arrow small(int length, char* str, int ifExist) {
DEBUGPRINTF("small(%02x %.*s %1x) begin", length, length, str, ifExist);
uint32_t hash;
Address hashAddress, hashProbe;
Address probeAddress, firstFreeAddress;
uint32_t uint_buffer[3];
char* buffer = (char *)uint_buffer;
if (length == 0 || length > 11)
return NIL;
memcpy(buffer + 4, str, (length > 8 ? 8 : length));
if (length < 8) {
memset(buffer + 4 + length, (char)length, 8 - length);
}
if (length > 8) {
// trust me
memcpy(buffer, str + 7, length - 7);
*buffer = (char)length;
if (length < 11) {
memset(buffer + length - 7, (char)length, 11 - length);
}
} else {
memset(buffer, (char)length, 4);
}
/*| s | hash3 | data | R.W.Wn.Cn | Child0 | cr | dr |
* s : small size (0 < s <= 11)
* hash3: (data 1st word ^ 2d word ^ 3d word) with s completion
*/
buffer[1] = buffer[1] ^ buffer[5] ^ buffer[9];
buffer[2] = buffer[2] ^ buffer[6] ^ buffer[10];
buffer[3] = buffer[3] ^ buffer[7] ^ buffer[11];
space_stats.get++;