forked from brong/cyrus-imapd-legacy
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcyrusdb_skiplist.c
2427 lines (2041 loc) · 60 KB
/
cyrusdb_skiplist.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_skiplist.c -- cyrusdb skiplist implementation
*
* 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.
*
* $Id: cyrusdb_skiplist.c,v 1.71 2010/01/06 17:01:45 murch Exp $
*/
/* xxx check retry_xxx for failure */
/* xxx all offsets should be uint32_ts i think */
#include <config.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <errno.h>
#include <syslog.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <netinet/in.h>
#include "assert.h"
#include "bsearch.h"
#include "cyrusdb.h"
#include "libcyr_cfg.h"
#include "cyr_lock.h"
#include "map.h"
#include "retry.h"
#include "util.h"
#include "xmalloc.h"
#include "xstrlcpy.h"
#include "xstrlcat.h"
#define PROB (0.5)
/*
*
* disk format; all numbers in network byte order
*
* there's the data file, consisting of the
* multiple records of "key", "data", and "skip pointers", where skip
* pointers are the record number of the data pointer.
*
* on startup, recovery is performed. the last known good data file
* is taken and the intent log is replayed on it. the index file is
* regenerated from scratch.
*
* during operation ckecpoints will compress the data. the data file
* is locked. then a checkpoint rewrites the data file in order,
* removing any unused records. this is written and fsync'd to
* dfile.NEW and stored for use during recovery.
*/
/*
header "skiplist file\0\0\0"
version (4 bytes)
version_minor (4 bytes)
maxlevel (4 bytes)
curlevel (4 bytes)
listsize (4 bytes)
in active items
log start (4 bytes)
offset where log records start, used mainly to tell when to compress
last recovery (4 bytes)
seconds since unix epoch
1 or more skipnodes, one of:
record type (4 bytes) [DUMMY, INORDER, ADD]
key size (4 bytes)
key string (bit string, rounded to up to 4 byte multiples w/ 0s)
data size (4 bytes)
data string (bit string, rounded to up to 4 byte multiples w/ 0s)
skip pointers (4 bytes each)
least to most
padding (4 bytes, must be -1)
record type (4 bytes) [DELETE]
record ptr (4 bytes; record to be deleted)
record type (4 bytes) [COMMIT]
record type is either
DUMMY (first node is of this type)
INORDER
ADD
DELETE
COMMIT (commit the previous records)
*/
enum {
INORDER = 1,
ADD = 2,
DELETE = 4,
COMMIT = 255,
DUMMY = 257
};
enum {
UNLOCKED = 0,
READLOCKED = 1,
WRITELOCKED = 2,
};
struct txn {
int syncfd;
/* logstart is where we start changes from on commit, where we truncate
to on abort */
unsigned logstart;
unsigned logend; /* where to write to continue this txn */
};
struct dbengine {
/* file data */
char *fname;
int fd;
const char *map_base;
size_t map_len; /* mapped size */
size_t map_size; /* actual size */
ino_t map_ino;
/* header info */
uint32_t version;
uint32_t version_minor;
uint32_t maxlevel;
uint32_t curlevel;
uint32_t listsize;
uint32_t logstart; /* where the log starts from last chkpnt */
time_t last_recovery;
/* tracking info */
int lock_status;
int is_open;
struct txn *current_txn;
struct timeval starttime;
/* comparator function to use for sorting */
int (*compar) (const char *s1, int l1, const char *s2, int l2);
};
struct db_list {
struct dbengine *db;
struct db_list *next;
int refcount;
};
static time_t global_recovery = 0;
static struct db_list *open_db = NULL;
/* Perform an FSYNC/FDATASYNC if we are *not* operating in UNSAFE mode */
#define DO_FSYNC (!libcyrus_config_getswitch(CYRUSOPT_SKIPLIST_UNSAFE))
enum {
be_paranoid = 0,
use_osync = 0
};
static void getsyncfd(struct dbengine *db, struct txn *t)
{
if (!use_osync) {
t->syncfd = db->fd;
} else if (t->syncfd == -1) {
t->syncfd = open(db->fname, O_RDWR | O_DSYNC, 0666);
assert(t->syncfd != -1); /* xxx do better error recovery */
}
}
static void closesyncfd(struct dbengine *db __attribute__((unused)),
struct txn *t)
{
/* if we're using fsync, then we don't want to close the file */
if (use_osync && (t->syncfd != -1)) {
close(t->syncfd);
}
t->syncfd = -1;
}
static int myinit(const char *dbdir, int myflags)
{
char sfile[1024];
int fd, r = 0;
uint32_t net32_time;
snprintf(sfile, sizeof(sfile), "%s/skipstamp", dbdir);
if (myflags & CYRUSDB_RECOVER) {
struct stat sbuf;
char cleanfile[1024];
snprintf(cleanfile, sizeof(cleanfile), "%s/skipcleanshutdown", dbdir);
/* if we had a clean shutdown, we don't need to run recovery on
* everything */
if (stat(cleanfile, &sbuf) == 0) {
syslog(LOG_NOTICE, "skiplist: clean shutdown detected, starting normally");
unlink(cleanfile);
goto normal;
}
syslog(LOG_NOTICE, "skiplist: clean shutdown file missing, updating recovery stamp");
/* set the recovery timestamp; all databases earlier than this
time need recovery run when opened */
global_recovery = time(NULL);
fd = open(sfile, O_RDWR | O_CREAT, 0644);
if (fd == -1) r = -1;
if (r != -1) r = ftruncate(fd, 0);
net32_time = htonl(global_recovery);
if (r != -1) r = write(fd, &net32_time, 4);
if (r != -1) r = close(fd);
if (r == -1) {
syslog(LOG_ERR, "DBERROR: writing %s: %m", sfile);
if (fd != -1) close(fd);
return CYRUSDB_IOERROR;
}
} else {
normal:
/* read the global recovery timestamp */
fd = open(sfile, O_RDONLY, 0644);
if (fd == -1) r = -1;
if (r != -1) r = read(fd, &net32_time, 4);
if (r != -1) r = close(fd);
if (r == -1) {
syslog(LOG_ERR, "DBERROR: reading %s, assuming the worst: %m",
sfile);
global_recovery = 0;
} else {
global_recovery = ntohl(net32_time);
}
}
srand(time(NULL) * getpid());
open_db = NULL;
return 0;
}
enum {
SKIPLIST_VERSION = 1,
SKIPLIST_VERSION_MINOR = 2,
SKIPLIST_MAXLEVEL = 20,
SKIPLIST_MINREWRITE = 16834 /* don't rewrite logs smaller than this */
};
#define HEADER_MAGIC ("\241\002\213\015skiplist file\0\0\0")
#define HEADER_MAGIC_SIZE (20)
/* offsets of header files */
enum {
OFFSET_HEADER = 0,
OFFSET_VERSION = 20,
OFFSET_VERSION_MINOR = 24,
OFFSET_MAXLEVEL = 28,
OFFSET_CURLEVEL = 32,
OFFSET_LISTSIZE = 36,
OFFSET_LOGSTART = 40,
OFFSET_LASTRECOVERY = 44
};
enum {
HEADER_SIZE = OFFSET_LASTRECOVERY + 4
};
static int mycommit(struct dbengine *db, struct txn *tid);
static int myabort(struct dbengine *db, struct txn *tid);
static int mycheckpoint(struct dbengine *db, int locked);
static int myconsistent(struct dbengine *db, struct txn *tid, int locked);
static int recovery(struct dbengine *db, int flags);
enum {
/* Force recovery regardless of timestamp on database */
RECOVERY_FORCE = 1,
/* Caller already has a write lock on the database. In the case
* of successful recovery, the database will still be locked on return.
*
* If the recovery fails, then the database will be unlocked an an
* error will be returned */
RECOVERY_CALLER_LOCKED = 2
};
/* file looks like:
struct header {
...
}
struct dummy {
uint32_t t = htonl(DUMMY);
uint32_t ks = 0;
uint32_t ds = 0;
uint32_t forward[db->maxlevel];
uint32_t pad = -1;
} */
#define DUMMY_OFFSET(db) (HEADER_SIZE)
#define DUMMY_PTR(db) ((db)->map_base + HEADER_SIZE)
#define DUMMY_SIZE(db) (4 * (3 + db->maxlevel + 1))
/* bump to the next multiple of 4 bytes */
#define ROUNDUP(num) (((num) + 3) & 0xFFFFFFFC)
#define TYPE(ptr) (ntohl(*((uint32_t *)(ptr))))
#define KEY(ptr) ((ptr) + 8)
#define KEYLEN(ptr) (ntohl(*((uint32_t *)((ptr) + 4))))
#define DATA(ptr) ((ptr) + 8 + ROUNDUP(KEYLEN(ptr)) + 4)
#define DATALEN(ptr) (ntohl(*((uint32_t *)((ptr) + 8 + ROUNDUP(KEYLEN(ptr))))))
#define FIRSTPTR(ptr) ((ptr) + 8 + ROUNDUP(KEYLEN(ptr)) + 4 + ROUNDUP(DATALEN(ptr)))
/* return a pointer to the pointer */
#define PTR(ptr, x) (FIRSTPTR(ptr) + 4 * (x))
/* FORWARD(ptr, x)
* given a pointer to the start of the record, return the offset
* corresponding to the xth pointer
*/
#define FORWARD(ptr, x) (ntohl(*((uint32_t *)(FIRSTPTR(ptr) + 4 * (x)))))
/* how many levels does this record have? */
static unsigned LEVEL(const char *ptr)
{
const uint32_t *p, *q;
assert(TYPE(ptr) == DUMMY || TYPE(ptr) == INORDER || TYPE(ptr) == ADD);
p = q = (uint32_t *) FIRSTPTR(ptr);
while (*p != (uint32_t)-1) p++;
return (p - q);
}
/* how big is this record? */
static unsigned RECSIZE(const char *ptr)
{
int ret = 0;
switch (TYPE(ptr)) {
case DUMMY:
case INORDER:
case ADD:
ret += 4; /* tag */
ret += 4; /* keylen */
ret += ROUNDUP(KEYLEN(ptr)); /* key */
ret += 4; /* datalen */
ret += ROUNDUP(DATALEN(ptr)); /* data */
ret += 4 * LEVEL(ptr); /* pointers */
ret += 4; /* padding */
break;
case DELETE:
ret += 8;
break;
case COMMIT:
ret += 4;
break;
}
return ret;
}
/* Determine if it is safe to append to this skiplist database.
* e.g. does it end in 4 bytes of -1 followed by a commit record?
* *or* does it end with 'DELETE' + 4 bytes + a commit record?
* *or* is this the beginning of the log, in which case we only need
* the padding from the last INORDER (or DUMMY) record
*/
static int SAFE_TO_APPEND(struct dbengine *db)
{
/* check it's a multiple of 4 */
if (db->map_size % 4) return 1;
/* is it the beginning of the log? */
if (db->map_size == db->logstart) {
if (*((uint32_t *)(db->map_base + db->map_size - 4)) != htonl(-1)) {
return 1;
}
}
/* in the middle of the log somewhere */
else {
if (*((uint32_t *)(db->map_base + db->map_size - 4)) != htonl(COMMIT)) {
return 1;
}
/* if it's not an end of a record or a delete */
if (!((*((uint32_t *)(db->map_base + db->map_size - 8)) == htonl(-1)) ||
(*((uint32_t *)(db->map_base + db->map_size -12)) == htonl(DELETE)))) {
return 1;
}
}
return 0;
}
static int newtxn(struct dbengine *db, struct txn **tidptr)
{
struct txn *tid;
/* is this file safe to append to?
*
* If it isn't, we need to run recovery. */
if (SAFE_TO_APPEND(db)) {
int r = recovery(db, RECOVERY_FORCE | RECOVERY_CALLER_LOCKED);
if (r) return r;
}
/* create the transaction */
tid = xmalloc(sizeof(struct txn));
tid->syncfd = -1;
tid->logstart = db->map_size;
/* assert(t->logstart != -1);*/
tid->logend = tid->logstart;
db->current_txn = tid;
/* pass it back out */
*tidptr = tid;
return 0;
}
#define PADDING(ptr) (ntohl(*((uint32_t *)((ptr) + RECSIZE(ptr) - 4))))
/* given an open, mapped db, read in the header information */
static int read_header(struct dbengine *db)
{
const char *dptr;
int r;
assert(db && db->map_len && db->fname && db->map_base
&& db->is_open && db->lock_status);
if (db->map_len < HEADER_SIZE) {
syslog(LOG_ERR,
"skiplist: file not large enough for header: %s", db->fname);
}
if (memcmp(db->map_base, HEADER_MAGIC, HEADER_MAGIC_SIZE)) {
syslog(LOG_ERR, "skiplist: invalid magic header: %s", db->fname);
return CYRUSDB_IOERROR;
}
db->version = ntohl(*((uint32_t *)(db->map_base + OFFSET_VERSION)));
db->version_minor =
ntohl(*((uint32_t *)(db->map_base + OFFSET_VERSION_MINOR)));
if (db->version != SKIPLIST_VERSION) {
syslog(LOG_ERR, "skiplist: version mismatch: %s has version %d.%d",
db->fname, db->version, db->version_minor);
return CYRUSDB_IOERROR;
}
db->maxlevel = ntohl(*((uint32_t *)(db->map_base + OFFSET_MAXLEVEL)));
if (db->maxlevel > SKIPLIST_MAXLEVEL) {
syslog(LOG_ERR,
"skiplist %s: MAXLEVEL %d in database beyond maximum %d\n",
db->fname, db->maxlevel, SKIPLIST_MAXLEVEL);
return CYRUSDB_IOERROR;
}
db->curlevel = ntohl(*((uint32_t *)(db->map_base + OFFSET_CURLEVEL)));
if (db->curlevel > db->maxlevel) {
syslog(LOG_ERR,
"skiplist %s: CURLEVEL %d in database beyond maximum %d\n",
db->fname, db->curlevel, db->maxlevel);
return CYRUSDB_IOERROR;
}
db->listsize = ntohl(*((uint32_t *)(db->map_base + OFFSET_LISTSIZE)));
db->logstart = ntohl(*((uint32_t *)(db->map_base + OFFSET_LOGSTART)));
db->last_recovery =
ntohl(*((uint32_t *)(db->map_base + OFFSET_LASTRECOVERY)));
/* verify dummy node */
dptr = DUMMY_PTR(db);
r = 0;
if (!r && TYPE(dptr) != DUMMY) {
syslog(LOG_ERR, "DBERROR: %s: first node not type DUMMY",
db->fname);
r = CYRUSDB_IOERROR;
}
if (!r && KEYLEN(dptr) != 0) {
syslog(LOG_ERR, "DBERROR: %s: DUMMY has non-zero KEYLEN",
db->fname);
r = CYRUSDB_IOERROR;
}
if (!r && DATALEN(dptr) != 0) {
syslog(LOG_ERR, "DBERROR: %s: DUMMY has non-zero DATALEN",
db->fname);
r = CYRUSDB_IOERROR;
}
if (!r && LEVEL(dptr) != db->maxlevel) {
syslog(LOG_ERR, "DBERROR: %s: DUMMY level(%d) != db->maxlevel(%d)",
db->fname, LEVEL(dptr), db->maxlevel);
r = CYRUSDB_IOERROR;
}
return r;
}
/* given an open, mapped db, locked db,
write the header information */
static int write_header(struct dbengine *db)
{
char buf[HEADER_SIZE];
int n;
assert (db->lock_status == WRITELOCKED);
memcpy(buf + 0, HEADER_MAGIC, HEADER_MAGIC_SIZE);
*((uint32_t *)(buf + OFFSET_VERSION)) = htonl(db->version);
*((uint32_t *)(buf + OFFSET_VERSION_MINOR)) = htonl(db->version_minor);
*((uint32_t *)(buf + OFFSET_MAXLEVEL)) = htonl(db->maxlevel);
*((uint32_t *)(buf + OFFSET_CURLEVEL)) = htonl(db->curlevel);
*((uint32_t *)(buf + OFFSET_LISTSIZE)) = htonl(db->listsize);
*((uint32_t *)(buf + OFFSET_LOGSTART)) = htonl(db->logstart);
*((uint32_t *)(buf + OFFSET_LASTRECOVERY)) = htonl(db->last_recovery);
/* write it out */
lseek(db->fd, 0, SEEK_SET);
n = retry_write(db->fd, buf, HEADER_SIZE);
if (n != HEADER_SIZE) {
syslog(LOG_ERR, "DBERROR: writing skiplist header for %s: %m",
db->fname);
return CYRUSDB_IOERROR;
}
return 0;
}
/* make sure our mmap() is big enough */
static int update_lock(struct dbengine *db, struct txn *txn)
{
/* txn->logend is the current size of the file */
assert (db->is_open && db->lock_status == WRITELOCKED);
map_refresh(db->fd, 0, &db->map_base, &db->map_len, txn->logend,
db->fname, 0);
db->map_size = txn->logend;
return 0;
}
static int write_lock(struct dbengine *db, const char *altname)
{
struct stat sbuf;
const char *lockfailaction;
const char *fname = altname ? altname : db->fname;
assert(db->lock_status == UNLOCKED);
if (lock_reopen(db->fd, fname, &sbuf, &lockfailaction) < 0) {
syslog(LOG_ERR, "IOERROR: %s %s: %m", lockfailaction, fname);
return CYRUSDB_IOERROR;
}
if (db->map_ino != sbuf.st_ino) {
map_free(&db->map_base, &db->map_len);
}
db->map_size = sbuf.st_size;
db->map_ino = sbuf.st_ino;
db->lock_status = WRITELOCKED;
gettimeofday(&db->starttime, 0);
map_refresh(db->fd, 0, &db->map_base, &db->map_len, sbuf.st_size,
fname, 0);
if (db->is_open) {
/* reread header */
read_header(db);
}
/* printf("%d: write lock: %d\n", getpid(), db->map_ino); */
return 0;
}
static int read_lock(struct dbengine *db)
{
struct stat sbuf, sbuffile;
int newfd = -1;
assert(db->lock_status == UNLOCKED);
for (;;) {
if (lock_shared(db->fd) < 0) {
syslog(LOG_ERR, "IOERROR: lock_shared %s: %m", db->fname);
return CYRUSDB_IOERROR;
}
if (fstat(db->fd, &sbuf) == -1) {
syslog(LOG_ERR, "IOERROR: fstat %s: %m", db->fname);
lock_unlock(db->fd);
return CYRUSDB_IOERROR;
}
if (stat(db->fname, &sbuffile) == -1) {
syslog(LOG_ERR, "IOERROR: stat %s: %m", db->fname);
lock_unlock(db->fd);
return CYRUSDB_IOERROR;
}
if (sbuf.st_ino == sbuffile.st_ino) break;
newfd = open(db->fname, O_RDWR, 0644);
if (newfd == -1) {
syslog(LOG_ERR, "IOERROR: open %s: %m", db->fname);
lock_unlock(db->fd);
return CYRUSDB_IOERROR;
}
dup2(newfd, db->fd);
close(newfd);
}
if (db->map_ino != sbuf.st_ino) {
map_free(&db->map_base, &db->map_len);
}
db->map_size = sbuf.st_size;
db->map_ino = sbuf.st_ino;
db->lock_status = READLOCKED;
gettimeofday(&db->starttime, 0);
/* printf("%d: read lock: %d\n", getpid(), db->map_ino); */
map_refresh(db->fd, 0, &db->map_base, &db->map_len, sbuf.st_size,
db->fname, 0);
if (db->is_open) {
/* reread header */
read_header(db);
}
return 0;
}
static int unlock(struct dbengine *db)
{
struct timeval endtime;
double timediff;
if (db->lock_status == UNLOCKED) {
syslog(LOG_NOTICE, "skiplist: unlock while not locked");
}
if (lock_unlock(db->fd) < 0) {
syslog(LOG_ERR, "IOERROR: lock_unlock %s: %m", db->fname);
return CYRUSDB_IOERROR;
}
db->lock_status = UNLOCKED;
gettimeofday(&endtime, 0);
timediff = timesub(&db->starttime, &endtime);
if (timediff > 1.0) {
syslog(LOG_NOTICE, "skiplist: longlock %s for %0.1f seconds",
db->fname, timediff);
}
/* printf("%d: unlock: %d\n", getpid(), db->map_ino); */
return 0;
}
static int lock_or_refresh(struct dbengine *db, struct txn **tidptr)
{
int r;
assert(db);
if (!tidptr) {
/* just grab a readlock */
r = read_lock(db);
if (r) return r;
/* start tracking the lock time */
gettimeofday(&db->starttime, 0);
return 0;
}
else if (*tidptr) {
/* check that the DB agrees that we're in this transaction */
assert(db->current_txn == *tidptr);
/* just update the active transaction */
return update_lock(db, *tidptr);
}
/* check that the DB isn't in a transaction */
assert(db->current_txn == NULL);
/* grab a r/w lock */
r = write_lock(db, NULL);
if (r) return r;
/* start the transaction */
r = newtxn(db, tidptr);
if (r) return r;
/* start tracking the lock time */
gettimeofday(&db->starttime, 0);
return 0;
}
static int dispose_db(struct dbengine *db)
{
if (!db) return 0;
if (db->lock_status) {
syslog(LOG_ERR, "skiplist: closed while still locked");
unlock(db);
}
if (db->fname) {
free(db->fname);
}
if (db->map_base) {
map_free(&db->map_base, &db->map_len);
}
if (db->fd != -1) {
close(db->fd);
}
free(db);
return 0;
}
/* NOTE: this function compares with the SIGNED CHAR value of
* the individual characters. This is a pretty bogus sort order,
* but for backwards compatibility reasons we're stuck with it
* for skiplist files at least */
static int compare_signed(const char *s1, int l1, const char *s2, int l2)
{
int min = l1 < l2 ? l1 : l2;
int cmp;
while (min-- > 0 && (cmp = *s1 - *s2) == 0) {
s1++;
s2++;
}
if (min >= 0) {
return cmp;
} else {
if (l1 > l2) return 1;
else if (l2 > l1) return -1;
else return 0;
}
}
static int myopen(const char *fname, int flags, struct dbengine **ret)
{
struct dbengine *db;
struct db_list *list_ent = open_db;
int r;
while (list_ent && strcmp(list_ent->db->fname, fname)) {
list_ent = list_ent->next;
}
if (list_ent) {
/* we already have this DB open! */
syslog(LOG_NOTICE, "skiplist: %s is already open %d time%s, returning object",
fname, list_ent->refcount, list_ent->refcount == 1 ? "" : "s");
*ret = list_ent->db;
++list_ent->refcount;
return 0;
}
db = (struct dbengine *) xzmalloc(sizeof(struct dbengine));
db->fd = -1;
db->fname = xstrdup(fname);
db->compar = (flags & CYRUSDB_MBOXSORT) ? bsearch_ncompare_mbox : compare_signed;
db->fd = open(fname, O_RDWR, 0644);
if (db->fd == -1 && errno == ENOENT) {
if (!(flags & CYRUSDB_CREATE)) {
dispose_db(db);
return CYRUSDB_NOTFOUND;
}
if (cyrus_mkdir(fname, 0755) == -1) {
dispose_db(db);
return CYRUSDB_IOERROR;
}
db->fd = open(fname, O_RDWR | O_CREAT, 0644);
}
if (db->fd == -1) {
syslog(LOG_ERR, "IOERROR: opening %s: %m", fname);
dispose_db(db);
return CYRUSDB_IOERROR;
}
db->curlevel = 0;
db->is_open = 0;
db->lock_status = UNLOCKED;
/* grab a read lock, only reading the header */
r = read_lock(db);
if (r < 0) {
dispose_db(db);
return r;
}
/* if the file is empty, then the header needs to be created first */
if (db->map_size == 0) {
unlock(db);
r = write_lock(db, NULL);
if (r < 0) {
dispose_db(db);
return r;
}
}
/* race condition. Another process may have already got the write
* lock and created the header. Only go ahead if the map_size is
* still zero (read/write_lock updates map_size). */
if (db->map_size == 0) {
/* initialize in memory structure */
db->version = SKIPLIST_VERSION;
db->version_minor = SKIPLIST_VERSION_MINOR;
db->maxlevel = SKIPLIST_MAXLEVEL;
db->curlevel = 1;
db->listsize = 0;
/* where do we start writing new entries? */
db->logstart = DUMMY_OFFSET(db) + DUMMY_SIZE(db);
db->last_recovery = time(NULL);
/* create the header */
r = write_header(db);
if (!r) {
int n;
int dsize = DUMMY_SIZE(db);
uint32_t *buf = (uint32_t *) xzmalloc(dsize);
buf[0] = htonl(DUMMY);
buf[(dsize / 4) - 1] = htonl(-1);
lseek(db->fd, DUMMY_OFFSET(db), SEEK_SET);
n = retry_write(db->fd, (char *) buf, dsize);
if (n != dsize) {
syslog(LOG_ERR, "DBERROR: writing dummy node for %s: %m",
db->fname);
r = CYRUSDB_IOERROR;
}
free(buf);
}
/* sync the db */
if (!r && DO_FSYNC && (fsync(db->fd) < 0)) {
syslog(LOG_ERR, "DBERROR: fsync(%s): %m", db->fname);
r = CYRUSDB_IOERROR;
}
/* map the new file */
db->map_size = db->logstart;
map_refresh(db->fd, 0, &db->map_base, &db->map_len, db->logstart,
db->fname, 0);
}
db->is_open = 1;
r = read_header(db);
if (r) {
dispose_db(db);
return r;
}
/* unlock the db */
unlock(db);
if (!global_recovery || db->last_recovery < global_recovery) {
/* run recovery; we rebooted since the last time recovery
was run */
r = recovery(db, 0);
if (r) {
dispose_db(db);
return r;
}
}
*ret = db;
/* track this database in the open list */
list_ent = (struct db_list *) xzmalloc(sizeof(struct db_list));
list_ent->db = db;
list_ent->next = open_db;
list_ent->refcount = 1;
open_db = list_ent;
return 0;
}
static int myclose(struct dbengine *db)
{
struct db_list *list_ent = open_db;
struct db_list *prev = NULL;
/* remove this DB from the open list */
while (list_ent && list_ent->db != db) {
prev = list_ent;
list_ent = list_ent->next;
}
assert(list_ent);
if (--list_ent->refcount <= 0) {
if (prev) prev->next = list_ent->next;
else open_db = list_ent->next;
free(list_ent);
return dispose_db(db);
}
return 0;
}
/* returns the offset to the node asked for, or the node after it
if it doesn't exist.
if previous is set, finds the last node < key */
static const char *find_node(struct dbengine *db,
const char *key, size_t keylen,
unsigned *updateoffsets)
{
const char *ptr = db->map_base + DUMMY_OFFSET(db);
int i;
unsigned offset;
if (updateoffsets) {
for (i = 0; (unsigned) i < db->maxlevel; i++) {
updateoffsets[i] = DUMMY_OFFSET(db);
}
}
for (i = db->curlevel - 1; i >= 0; i--) {
while ((offset = FORWARD(ptr, i)) &&
db->compar(KEY(db->map_base + offset), KEYLEN(db->map_base + offset),
key, keylen) < 0) {
/* move forward at level 'i' */
ptr = db->map_base + offset;
}
if (updateoffsets) updateoffsets[i] = ptr - db->map_base;
}
ptr = db->map_base + FORWARD(ptr, 0);
return ptr;
}
static int myfetch(struct dbengine *db,
const char *key, size_t keylen,
const char **data, size_t *datalen,
struct txn **tidptr)
{
const char *ptr;
int r = 0;
assert(db != NULL && key != NULL);
if (data) *data = NULL;
if (datalen) *datalen = 0;
/* Hacky workaround:
*
* If no transaction was passed, but we're in a transaction,
* then just do the read within that transaction.