forked from brong/cyrus-imapd-legacy
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcyrusdb_twoskip.c
2321 lines (1916 loc) · 58.5 KB
/
cyrusdb_twoskip.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
/* cyrusdb_twoskip.c - brand new twoskip implementation, not backwards anything
*
* Copyright (c) 1994-2008 Carnegie Mellon University. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The name "Carnegie Mellon University" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For permission or any legal
* details, please contact
* Carnegie Mellon University
* Center for Technology Transfer and Enterprise Creation
* 4615 Forbes Avenue
* Suite 302
* Pittsburgh, PA 15213
* (412) 268-7393, fax: (412) 268-7395
*
* 4. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by Computing Services
* at Carnegie Mellon University (http://www.cmu.edu/computing/)."
*
* CARNEGIE MELLON UNIVERSITY DISCLAIMS ALL WARRANTIES WITH REGARD TO
* THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS, IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY BE LIABLE
* FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
* AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
* OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <config.h>
#include <errno.h>
#include <limits.h>
#include <stdlib.h>
#include <string.h>
#include <syslog.h>
#include <sys/types.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include "assert.h"
#include "bsearch.h"
#include "byteorder64.h"
#include "cyrusdb.h"
#include "crc32.h"
#include "libcyr_cfg.h"
#include "mappedfile.h"
#include "util.h"
#include "xmalloc.h"
#include "xstrlcpy.h"
/*
* twoskip disk format.
*
* GOALS:
* a) 64 bit through
* b) Fast recovery after crashes
* c) integrity checks throughout
* d) simple format
*
* ACHIEVED BY:
* a)
* - 64 bit offsets for all values
* - smaller initial keylen and vallen, but they can
* can be extended up to 64 bits as well.
* - no timestamps stored in the file.
* - XXX - may behave strangely with large files on
* 32 bit architectures, particularly if size_t is
* not 64 bit.
*
* b)
* - "dirty flag" is always set in the header and
* fsynced BEFORE writing anything else.
* - a header field for "current size", after which
* all changes are considered suspect until commit.
* - two "lowest level" offsets, used in alternating
* order, so the highest value less than "current_size"
* is always the correct pointer - this means we
* never lose linkage, so never need to rewrite more
* than the affected records during a recovery.
* - all data is fsynced BEFORE rewriting the header to
* remove the dirty flag.
* - As long as the first 64 bytes of the file are
* guaranteed to write all together or not at all,
* we're crash-safe.
*
* c)
* - every byte in the file is covered by one of the
* crc32 values stored throughout.
* - header CRC is checked on every header read (open/lock)
* - record head CRCs are checked on every record read,
* including skiplist traverse.
* - record tail CRCs (key/value) are check on every exact
* key match result, during traverse for read or write.
*
* d)
* - there are no special commit, inorder, etc records.
* just add records and ghost "delete" records to give
* somewhere to point to on deletes. These are only
* at the lowest level, so don't have a significant
* seek impact.
* - modular code makes the logic much clearer.
*/
/*
* FORMAT:
*
* HEADER: 64 bytes
* magic: 20 bytes: "4 bytes same as skiplist" "twoskip file\0\0\0\0"
* version: 4 bytes
* generation: 8 bytes
* num_records: 8 bytes
* repack_size: 8 bytes
* current_size: 8 bytes
* flags: 4 bytes
* crc32: 4 bytes
*
* RECORDS:
* type 1 byte
* level: 1 byte
* keylen: 2 bytes
* vallen: 4 bytes
* <optionally: 64 bit keylen if keylen == UINT16_MAX>
* <optionally: 64 bit vallen if vallen == UINT32_MAX>
* ptrs: 8 bytes * (level+1)
* crc32_head: 4 bytes
* crc32_tail: 4 bytes
* key: (keylen bytes)
* val: (vallen bytes)
* padding: enough zeros to round up to an 8 byte multiple
*
* defined types, in skiplist language are:
* '=' -> DUMMY
* '+' -> ADD/INORDER
* '-' -> DELETE (kind of)
* '$' -> COMMIT
* but note that delete records behave differently - they're
* part of the pointer hierarchy, so that back offsets will
* always point somewhere past the 'end' until commit.
*
* The DUMMY is always MAXLEVEL level, with zero keylen and vallen
* The DELETE is always zero level, with zero keylen and vallen
* crc32_head is calculated on all bytes before it in the record
* crc32_tail is calculated on all bytes after, INCLUDING padding
*
* The COMMIT is inserted at the end of each transaction, and its
* single pointer points back to the start of the transaction.
*/
/* OPERATION:
*
* Finding a record works very much like skiplist, but we have
* a datastructure, 'struct skiploc', to help find it. There
* is one of these embedded directly in the 'struct db', and
* it's the only one we ever use.
*
* skiploc contains two complete sets of offsets - at every
* level the offset of the previous record, and the offset of
* the next record, in relation to the requested key. If the
* key is an exact match, it also contains a copy of the
* struct skiprecord. If not, it contains the struct
* skiprecord for the previous record at level zero.
*
* It also contains a 'struct buf' with a copy of the requested
* key, which allows for efficient relocation of the position in
* the file when nothing is changed.
*
* So nothing is really changed with finding, except the special
* "level zero" alternative pointer. We'll see that in action
* later.
*
* TRANSACTIONS:
* 1) before writing anything else, the header is updated with the
* DIRTY flag set, and then fdatasync is run.
* 2) after all changes, fdatasync is run again.
* 3) finally, the header is updated with a new current_size and
* the DIRTY flag clear, then fdatasync is run for a third time.
*
* ADDING A NEW RECORD:
* a new record is created with forward locations pointing to the
* next pointers in the skiploc. This is appended to the file.
* This works for either a create OR replace, since in both cases
* the nextlocs are correct. Level zero is set to zero on a new
* record.
*
* If it's not a replace, a "random" level will be chosen for the
* record. All update operations below apply only up to this level,
* pointers above are unaffected - and continue over the location
* of this change.
*
* For each backloc, the record at that offset is read, and the
* forward pointers at each level are replaced with the offset
* of the new record. NOTE: see special level zero logic below.
*
* Again, if this was a replace, the backlocs don't point to the
* current record, so it just silently disappears from the lists.
*
* DELETING A RECORD:
* The logic is almost identical to adding, but a delete record
* always has a level of zero, with only a single pointer forward
* to the next record.
*
* Because of this, the updates are done up to the level of the
* old record instead.
*
* THE SPECIAL "level zero":
* To allow a "fast fsck" after an aborted transaction, rather
* than having only a single level 1 pointer, we have two. The
* following algorithm is used to select which one to change.
*
* The definition of "current_size" is the size of the database
* at last commit, it does not get updated during a transaction.
*
* So: when updating level 1 - if either level 1 or level 0 has
* a value >= current_size, then that value gets updated again.
* otherwise, the lowest value gets replaced with the new value.
*
* when reading, the highest value is used - except during
* recovery when it's the highest value less than current_size,
* since any "future" offsets are bogus.
*
* This means that there is always at least one offset which
* points to the "next" record as if the current transaction
* had never occured - allowing recovery to find all alive
* records without scanning and updating the rest of the file.
* This guarantee exists regardless of any ordering of writes
* within the transaction, any page could be inconsistent and
* the result is still a clean recovery.
*
* CHECKPOINT:
* Over time, a twoskip database accumulates cruft - replaced
* records and delete records. Records out of order, slowing
* down sequential access. When the calculated "repack size"
* is sufficiently smaller than the current size (see the
* TUNING constants below) then the file is checkpointed.
* A checkpoint is achieved by creating a new file, and
* copying all the current records, in order, into it, then
* renaming the new file over the old. The "generation"
* counter in the header is incremented to tell other users
* that offsets into the file are no longer valid. This is
* more reliable than just using the inode, because inodes
* can be reused.
*
* LOCATION OPTIMISATION:
* If the generation is unchanged AND the size of the file
* is unchanged, then all offsets stored in the skiploc are
* still valid. This is used to optimise finding the current
* key, advancing to the "next" key, and also to optimise
* regular fetches that happen to hit either the current key,
* the gap immediately after, or the next key. All other
* locations cause a full relocate.
*/
/********** TUNING *************/
/* don't bother rewriting if the database has less than this much "new" data */
#define MINREWRITE 16834
/* don't bother rewriting if less than this ratio is dirty (20%) */
#define REWRITE_RATIO 0.2
/* number of skiplist levels - 31 gives us binary search to 2^32 records.
* limited to 255 by file format, but skiplist had 20, and that was enough
* for most real uses. 31 is heaps. */
#define MAXLEVEL 31
/* should be 0.5 for binary search semantics */
#define PROB 0.5
/* format specifics */
#define VERSION 1
/* type aliases */
#define LLU long long unsigned int
#define LU long unsigned int
/* record types */
#define DUMMY '='
#define RECORD '+'
#define DELETE '-'
#define COMMIT '$'
/********** DATA STRUCTURES *************/
/* A single "record" in the twoskip file. This could be a
* DUMMY, a KEYRECORD, a VALRECORD or even a DELETE - they
* all read and write with the same functions */
struct skiprecord {
/* location on disk (not part of the on-disk format as such) */
size_t offset;
size_t len;
/* what are our header fields */
uint8_t type;
uint8_t level;
size_t keylen;
size_t vallen;
/* where to do we go from here? */
size_t nextloc[MAXLEVEL+1];
/* what do our integrity checks say? */
uint32_t crc32_head;
uint32_t crc32_tail;
/* our key and value */
size_t keyoffset;
size_t valoffset;
};
/* a location in the twoskip file. We always have:
* record: if "is_exactmatch" this points to the record
* with the matching key, otherwise it points to
* the 'compar' order previous record.
* backloc: the records that point TO this location
* at each level. If is_exactmatch, they
* point to the record, otherwise they are
* the record.
* forwardloc: the records pointed to by the record
* at 'backloc' at the same level. Kept
* here for efficiency
* keybuf: a copy of the requested key - we always keep
* this so we can re-seek after the file has been
* checkpointed under us (say a read-only foreach)
*
* generation and end can be used to see if anything in
* the file may have changed and needs re-reading.
*/
struct skiploc {
/* requested, may not match actual record */
struct buf keybuf;
int is_exactmatch;
/* current or next record */
struct skiprecord record;
/* we need both sets of offsets to cheaply insert */
size_t backloc[MAXLEVEL];
size_t forwardloc[MAXLEVEL];
/* need a generation so we know if the location is still valid */
uint64_t generation;
size_t end;
};
enum {
UNLOCKED = 0,
READLOCKED = 1,
WRITELOCKED = 2,
};
#define DIRTY (1<<0)
struct txn {
/* logstart is where we start changes from on commit, where we truncate
to on abort */
int num;
};
struct db_header {
/* header info */
uint32_t version;
uint32_t flags;
uint64_t generation;
uint64_t num_records;
size_t repack_size;
size_t current_size;
};
struct dbengine {
/* file data */
struct mappedfile *mf;
struct db_header header;
struct skiploc loc;
/* tracking info */
int is_open;
size_t end;
int txn_num;
struct txn *current_txn;
/* comparator function to use for sorting */
int open_flags;
int (*compar) (const char *s1, int l1, const char *s2, int l2);
};
struct db_list {
struct dbengine *db;
struct db_list *next;
int refcount;
};
#define HEADER_MAGIC ("\241\002\213\015twoskip file\0\0\0\0")
#define HEADER_MAGIC_SIZE (20)
/* offsets of header files */
enum {
OFFSET_HEADER = 0,
OFFSET_VERSION = 20,
OFFSET_GENERATION = 24,
OFFSET_NUM_RECORDS = 32,
OFFSET_REPACK_SIZE = 40,
OFFSET_CURRENT_SIZE = 48,
OFFSET_FLAGS = 56,
OFFSET_CRC32 = 60,
};
#define HEADER_SIZE 64
#define MAXRECORDHEAD ((MAXLEVEL + 5)*8)
/* mount a scratch monkey */
union skipwritebuf {
uint64_t align;
char s[MAXRECORDHEAD];
} scratchspace;
static struct db_list *open_twoskip = NULL;
static int mycommit(struct dbengine *db, struct txn *tid);
static int myabort(struct dbengine *db, struct txn *tid);
static int mycheckpoint(struct dbengine *db);
static int myconsistent(struct dbengine *db, struct txn *tid);
static int recovery(struct dbengine *db);
static int recovery1(struct dbengine *db, int *count);
static int recovery2(struct dbengine *db, int *count);
/************** HELPER FUNCTIONS ****************/
/* calculate padding size */
static size_t roundup(size_t record_size, int howfar)
{
if (record_size % howfar)
record_size += howfar - (record_size % howfar);
return record_size;
}
/* choose a level appropriately randomly */
static uint8_t randlvl(uint8_t lvl, uint8_t maxlvl)
{
while (((float) rand() / (float) (RAND_MAX)) < PROB) {
lvl++;
if (lvl == maxlvl) break;
}
return lvl;
}
static const char *_base(struct dbengine *db)
{
return mappedfile_base(db->mf);
}
static const char *_key(struct dbengine *db, struct skiprecord *rec)
{
return mappedfile_base(db->mf) + rec->keyoffset;
}
static const char *_val(struct dbengine *db, struct skiprecord *rec)
{
return mappedfile_base(db->mf) + rec->valoffset;
}
static size_t _size(struct dbengine *db)
{
return mappedfile_size(db->mf);
}
static const char *_fname(struct dbengine *db)
{
return mappedfile_fname(db->mf);
}
/************** HEADER ****************/
/* given an open, mapped db, read in the header information */
static int read_header(struct dbengine *db)
{
uint32_t crc;
assert(db && db->mf && db->is_open);
if (_size(db) < HEADER_SIZE) {
syslog(LOG_ERR,
"twoskip: file not large enough for header: %s", _fname(db));
return CYRUSDB_IOERROR;
}
if (memcmp(_base(db), HEADER_MAGIC, HEADER_MAGIC_SIZE)) {
syslog(LOG_ERR, "twoskip: invalid magic header: %s", _fname(db));
return CYRUSDB_IOERROR;
}
db->header.version
= ntohl(*((uint32_t *)(_base(db) + OFFSET_VERSION)));
if (db->header.version > VERSION) {
syslog(LOG_ERR, "twoskip: version mismatch: %s has version %d",
_fname(db), db->header.version);
return CYRUSDB_IOERROR;
}
db->header.generation
= ntohll(*((uint64_t *)(_base(db) + OFFSET_GENERATION)));
db->header.num_records
= ntohll(*((uint64_t *)(_base(db) + OFFSET_NUM_RECORDS)));
db->header.repack_size
= ntohll(*((uint64_t *)(_base(db) + OFFSET_REPACK_SIZE)));
db->header.current_size
= ntohll(*((uint64_t *)(_base(db) + OFFSET_CURRENT_SIZE)));
db->header.flags
= ntohl(*((uint32_t *)(_base(db) + OFFSET_FLAGS)));
crc = ntohl(*((uint32_t *)(_base(db) + OFFSET_CRC32)));
if (crc32_map(_base(db), OFFSET_CRC32) != crc) {
syslog(LOG_ERR, "DBERROR: %s: twoskip header CRC failure",
_fname(db));
return CYRUSDB_IOERROR;
}
db->end = db->header.current_size;
return 0;
}
/* given an open, mapped, locked db, write the header information */
static int write_header(struct dbengine *db)
{
char *buf = scratchspace.s;
int n;
/* format one buffer */
memcpy(buf, HEADER_MAGIC, HEADER_MAGIC_SIZE);
*((uint32_t *)(buf + OFFSET_VERSION)) = htonl(db->header.version);
*((uint64_t *)(buf + OFFSET_GENERATION)) = htonll(db->header.generation);
*((uint64_t *)(buf + OFFSET_NUM_RECORDS)) = htonll(db->header.num_records);
*((uint64_t *)(buf + OFFSET_REPACK_SIZE)) = htonll(db->header.repack_size);
*((uint64_t *)(buf + OFFSET_CURRENT_SIZE)) = htonll(db->header.current_size);
*((uint32_t *)(buf + OFFSET_FLAGS)) = htonl(db->header.flags);
*((uint32_t *)(buf + OFFSET_CRC32)) = htonl(crc32_map(buf, OFFSET_CRC32));
/* write it out */
n = mappedfile_pwrite(db->mf, buf, HEADER_SIZE, 0);
if (n < 0) return CYRUSDB_IOERROR;
return 0;
}
/* simple wrapper to write with an fsync */
static int commit_header(struct dbengine *db)
{
int r = write_header(db);
if (!r) r = mappedfile_commit(db->mf);
return r;
}
/******************** RECORD *********************/
static int check_tailcrc(struct dbengine *db, struct skiprecord *record)
{
uint32_t crc;
crc = crc32_map(_base(db) + record->keyoffset,
roundup(record->keylen + record->vallen, 8));
if (crc != record->crc32_tail) {
syslog(LOG_ERR, "DBERROR: invalid tail crc %s at %llX",
_fname(db), (LLU)record->offset);
return CYRUSDB_IOERROR;
}
return 0;
}
/* read a single skiprecord at the given offset */
static int read_record(struct dbengine *db, size_t offset,
struct skiprecord *record)
{
const char *base;
int i;
memset(record, 0, sizeof(struct skiprecord));
record->offset = offset;
record->len = 24; /* absolute minimum */
/* need space for at least the header plus some details */
if (record->offset + record->len > _size(db))
goto badsize;
base = _base(db) + offset;
/* read in the record header */
record->type = base[0];
record->level = base[1];
record->keylen = ntohs(*((uint16_t *)(base + 2)));
record->vallen = ntohl(*((uint32_t *)(base + 4)));
offset += 8;
/* make sure we fit */
assert(record->level <= MAXLEVEL);
/* long key */
if (record->keylen == UINT16_MAX) {
base = _base(db) + offset;
record->keylen = ntohll(*((uint64_t *)base));
offset += 8;
}
/* long value */
if (record->vallen == UINT32_MAX) {
base = _base(db) + offset;
record->vallen = ntohll(*((uint64_t *)base));
offset += 8;
}
/* we know the length now */
record->len = (offset - record->offset) /* header including lengths */
+ 8 * (1 + record->level) /* ptrs */
+ 8 /* crc32s */
+ roundup(record->keylen + record->vallen, 8); /* keyval */
if (record->offset + record->len > _size(db))
goto badsize;
for (i = 0; i <= record->level; i++) {
base = _base(db) + offset;
record->nextloc[i] = ntohll(*((uint64_t *)base));
offset += 8;
}
base = _base(db) + offset;
record->crc32_head = ntohl(*((uint32_t *)base));
if (crc32_map(_base(db) + record->offset, (offset - record->offset))
!= record->crc32_head)
return CYRUSDB_IOERROR;
record->crc32_tail = ntohl(*((uint32_t *)(base+4)));
record->keyoffset = offset + 8;
record->valoffset = record->keyoffset + record->keylen;
return 0;
badsize:
syslog(LOG_ERR, "twoskip: attempt to read past end of file %s: %08llX > %08llX",
_fname(db), (LLU)record->offset + record->len, (LLU)_size(db));
return CYRUSDB_IOERROR;
}
/* prepare the header part of the record (everything except the key, value
* and padding). Used for both writes and rewrites. */
static void prepare_record(struct skiprecord *record, char *buf, size_t *sizep)
{
int len = 8;
int i;
assert(record->level <= MAXLEVEL);
buf[0] = record->type;
buf[1] = record->level;
if (record->keylen < UINT16_MAX) {
*((uint16_t *)(buf+2)) = htons(record->keylen);
}
else {
*((uint16_t *)(buf+2)) = htons(UINT16_MAX);
*((uint64_t *)(buf+len)) = htonll(record->keylen);
len += 8;
}
if (record->vallen < UINT32_MAX) {
*((uint32_t *)(buf+4)) = htonl(record->vallen);
}
else {
*((uint32_t *)(buf+4)) = htonl(UINT32_MAX);
*((uint64_t *)(buf+len)) = htonll(record->vallen);
len += 8;
}
/* got pointers? */
for (i = 0; i <= record->level; i++) {
*((uint64_t *)(buf+len)) = htonll(record->nextloc[i]);
len += 8;
}
/* NOTE: crc32_tail does not change */
record->crc32_head = crc32_map(buf, len);
*((uint32_t *)(buf+len)) = htonl(record->crc32_head);
*((uint32_t *)(buf+len+4)) = htonl(record->crc32_tail);
len += 8;
*sizep = len;
}
/* only changing the record head, so only rewrite that much */
static int rewrite_record(struct dbengine *db, struct skiprecord *record)
{
char *buf = scratchspace.s;
size_t len;
int n;
/* we must already be in a transaction before updating records */
assert(db->header.flags & DIRTY);
assert(record->offset);
prepare_record(record, buf, &len);
n = mappedfile_pwrite(db->mf, buf, len, record->offset);
if (n < 0) return CYRUSDB_IOERROR;
return 0;
}
/* you can only write records at the end */
static int write_record(struct dbengine *db, struct skiprecord *record,
const char *key, const char *val)
{
char zeros[8] = {0, 0, 0, 0, 0, 0, 0, 0};
uint64_t len;
struct iovec io[4];
int n;
assert(!record->offset);
/* we'll put the HEAD on later */
io[0].iov_base = scratchspace.s;
io[0].iov_len = 0;
io[1].iov_base = (char *)key;
io[1].iov_len = record->keylen;
io[2].iov_base = (char *)val;
io[2].iov_len = record->vallen;
/* pad to 8 bytes */
len = record->vallen + record->keylen;
io[3].iov_base = zeros;
io[3].iov_len = roundup(len, 8) - len;
/* calculate the CRC32 of the tail first */
record->crc32_tail = crc32_iovec(io+1, 3);
/* prepare the record once we know the crc32 of the tail */
prepare_record(record, io[0].iov_base, &io[0].iov_len);
/* write to the mapped file, getting the offset updated */
n = mappedfile_pwritev(db->mf, io, 4, db->end);
if (n < 0) return CYRUSDB_IOERROR;
/* locate the record */
record->offset = db->end;
record->keyoffset = db->end + io[0].iov_len;
record->valoffset = record->keyoffset + record->keylen;
record->len = n;
/* and advance the known file size */
db->end += n;
return 0;
}
/* helper to append a record, starting the transaction by dirtying the
* header first if required */
static int append_record(struct dbengine *db, struct skiprecord *record,
const char *key, const char *val)
{
int r;
assert(db->current_txn);
/* dirty the header if not already dirty */
if (!(db->header.flags & DIRTY)) {
db->header.flags |= DIRTY;
r = commit_header(db);
if (r) return r;
}
return write_record(db, record, key, val);
}
/************************** LOCATION MANAGEMENT ***************************/
static size_t _getzero(struct dbengine *db, struct skiprecord *record)
{
/* if one is past, must be the other */
if (record->nextloc[0] >= db->end)
return record->nextloc[1];
else if (record->nextloc[1] >= db->end)
return record->nextloc[0];
/* highest remaining */
else if (record->nextloc[0] > record->nextloc[1])
return record->nextloc[0];
else
return record->nextloc[1];
}
/* find the next record at a given level, encapsulating the
* level 0 magic */
static int _getloc(struct dbengine *db, struct skiprecord *record,
uint8_t level, size_t *outloc)
{
struct skiprecord local;
size_t offset;
int r;
if (level) {
*outloc = record->nextloc[level + 1];
return 0;
}
offset = _getzero(db, record);
/* obviously not a delete! */
if (!offset) {
*outloc = offset;
return 0;
}
r = read_record(db, offset, &local);
if (r) return r;
if (local.type == '-')
*outloc = local.nextloc[0];
else
*outloc = offset;
return 0;
}
/* set the next record at a given level, encapsulating the
* level 0 magic */
static void _setloc(struct dbengine *db, struct skiprecord *record,
uint8_t level, size_t offset)
{
if (level) {
record->nextloc[level+1] = offset;
return;
}
/* level zero is special */
/* already this transaction, update this one */
if (record->nextloc[0] >= db->header.current_size)
record->nextloc[0] = offset;
else if (record->nextloc[1] >= db->header.current_size)
record->nextloc[1] = offset;
/* otherwise, update older one */
else if (record->nextloc[1] > record->nextloc[0])
record->nextloc[0] = offset;
else
record->nextloc[1] = offset;
}
/* finds a record, either an exact match or the record
* immediately before */
static int relocate(struct dbengine *db)
{
struct skiploc *loc = &db->loc;
struct skiprecord newrecord;
size_t offset;
uint8_t level;
uint8_t i;
int cmp = -1; /* never found a thing! */
int r;
/* pointer validity */
loc->generation = db->header.generation;
loc->end = db->end;
/* start with the dummy */
r = read_record(db, HEADER_SIZE, &loc->record);
loc->is_exactmatch = 0;
/* special case start pointer for efficiency */
if (!loc->keybuf.len) {
for (i = 0; i < loc->record.level; i++) {
loc->backloc[i] = loc->record.offset;
r = _getloc(db, &loc->record, i, &loc->forwardloc[i]);
if (r) return r;
}
return 0;
}
level = loc->record.level;
newrecord.offset = 0;
while (level) {
r = _getloc(db, &loc->record, level-1, &offset);
if (r) return r;
loc->backloc[level-1] = loc->record.offset;
loc->forwardloc[level-1] = offset;
if (offset && newrecord.offset != offset) {
r = read_record(db, offset, &newrecord);
if (r) return r;
cmp = db->compar(_key(db, &newrecord), newrecord.keylen,
loc->keybuf.s, loc->keybuf.len);
/* not there? stay at this level */
if (cmp < 0) {
/* move the offset range along */
loc->record = newrecord;
continue;
}
}
level--;
}
if (cmp == 0) { /* we found it exactly */
loc->is_exactmatch = 1;
loc->record = newrecord;
for (i = 0; i < loc->record.level; i++) {
r = _getloc(db, &loc->record, i, &loc->forwardloc[i]);
if (r) return r;
}
/* make sure this record is complete */
r = check_tailcrc(db, &loc->record);
if (r) return r;
}
return 0;
}
/* helper function to find a location, either by using the existing
* location if it's close enough, or using the full relocate above */
static int find_loc(struct dbengine *db, const char *key, size_t keylen)
{
struct skiprecord newrecord;
struct skiploc *loc = &db->loc;
int cmp, i, r;
buf_setmap(&loc->keybuf, key, keylen);
/* can we special case advance? */
if (keylen && loc->end == db->end
&& loc->generation == db->header.generation) {
cmp = db->compar(_key(db, &loc->record), loc->record.keylen,
loc->keybuf.s, loc->keybuf.len);
/* same place, and was exact. Otherwise we're going back,
* and the reverse pointers are no longer valid... */
if (db->loc.is_exactmatch && cmp == 0) {
return 0;
}
/* we're looking after this record */
if (cmp < 0) {
for (i = 0; i < db->loc.record.level; i++)
loc->backloc[i] = db->loc.record.offset;
/* nothing afterwards? */
if (!loc->forwardloc[0]) {
db->loc.is_exactmatch = 0;
return 0;
}
/* read the next record */
r = read_record(db, loc->forwardloc[0], &newrecord);
if (r) return r;
/* now where is THIS record? */
cmp = db->compar(_key(db, &newrecord), newrecord.keylen,
loc->keybuf.s, loc->keybuf.len);
/* exact match? */
if (cmp == 0) {
db->loc.is_exactmatch = 1;
db->loc.record = newrecord;
for (i = 0; i < newrecord.level; i++) {
r = _getloc(db, &newrecord, i, &loc->forwardloc[i]);
if (r) return r;
}
/* make sure this record is complete */
r = check_tailcrc(db, &loc->record);
if (r) return r;
return 0;
}
/* or in the gap */
if (cmp > 0) {
db->loc.is_exactmatch = 0;