File: dblock.c

package info (click to toggle)
whitedb 0.7.2-1
  • links: PTS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 2,452 kB
  • ctags: 2,681
  • sloc: ansic: 31,714; python: 790; lex: 359; java: 277; makefile: 172; yacc: 138; sh: 87; sed: 36
file content (1424 lines) | stat: -rw-r--r-- 33,510 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
/*
* $Id:  $
* $Version: $
*
* Copyright (c) Priit Jrv 2009, 2010, 2011, 2013
*
* This file is part of WhiteDB
*
* WhiteDB is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* WhiteDB is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with WhiteDB.  If not, see <http://www.gnu.org/licenses/>.
*
*/

 /** @file dblock.c
 *  Concurrent access support for WhiteDB memory database
 *
 *  Note: this file contains compiler and target-specific code.
 *  For compiling on plaforms that do not have support for
 *  specific opcodes needed for atomic operations and spinlocks,
 *  locking may be disabled by ./configure --disable-locking
 *  or by editing the appropriate config-xxx.h file. This will
 *  allow the code to compile, but concurrent access will NOT
 *  work.
 */

/* ====== Includes =============== */

#include <stdio.h>
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#else
#include <time.h>
#include <limits.h>
#endif

#ifdef __cplusplus
extern "C" {
#endif

#ifdef _WIN32
#include "../config-w32.h"
#else
#include "../config.h"
#endif
#include "dballoc.h"
#include "dblock.h"

#if (LOCK_PROTO==TFQUEUE)
#ifdef __linux__
#include <linux/futex.h>
#include <unistd.h>
#include <sys/syscall.h>
#include <sys/errno.h>
#endif
#endif

/* ====== Private headers and defs ======== */

#define compare_and_swap wg_compare_and_swap // wg_ prefix used in dblock.h, non-wg below

#ifndef LOCK_PROTO
#define DUMMY_ATOMIC_OPS /* allow compilation on unsupported platforms */
#endif

#if (LOCK_PROTO==RPSPIN) || (LOCK_PROTO==WPSPIN)
#define WAFLAG 0x1  /* writer active flag */
#define RC_INCR 0x2  /* increment step for reader count */
#else
/* classes of locks. */
#define LOCKQ_READ 0x02
#define LOCKQ_WRITE 0x04
#endif

/* Macro to emit Pentium 4 "pause" instruction. */
#if !defined(LOCK_PROTO)
#define MM_PAUSE
#elif defined(__GNUC__)
#if defined(__i686__) || defined(__amd64__)  /* assume SSE2 support */
#define MM_PAUSE {\
  __asm__ __volatile__("pause;\n");\
}
#else
#define MM_PAUSE
#endif
#elif defined(_WIN32)
#include <emmintrin.h>
#define MM_PAUSE { _mm_pause(); }
#endif

/* Helper function for implementing atomic operations
 * with gcc 4.3 / ARM EABI by Julian Brown.
 * This works on Linux ONLY.
 */
#if defined(__ARM_EABI__) && defined(__linux__)
typedef int (kernel_cmpxchg_t) (int oldval, int newval, int *ptr);
#define kernel_cmpxchg (*(kernel_cmpxchg_t *) 0xffff0fc0)
#endif

/* For easier testing of GCC version */
#ifdef __GNUC__
#define GCC_VERSION (__GNUC__ * 10000 \
                   + __GNUC_MINOR__ * 100 \
                   + __GNUC_PATCHLEVEL__)
#endif

/* Spinlock timings
 * SPIN_COUNT: how many cycles until CPU is yielded
 * SLEEP_MSEC and SLEEP_NSEC: increment of wait time after each cycle
 */
#ifdef _WIN32
#define SPIN_COUNT 100000 /* Windows scheduling seems to force this */
#define SLEEP_MSEC 1 /* minimum resolution is 1 millisecond */
#else
#define SPIN_COUNT 500 /* shorter spins perform better with Linux */
#define SLEEP_NSEC 500000 /* 500 microseconds */
#endif

#ifdef _WIN32
/* XXX: quick hack for MSVC. Should probably find a cleaner solution */
#define inline __inline
#endif

#ifdef _WIN32
#define INIT_SPIN_TIMEOUT(t)
#else /* timings are in nsec */
#define INIT_SPIN_TIMEOUT(t) \
  if(t > INT_MAX/1000000) /* hack: primitive overflow protection */ \
    t = INT_MAX; \
  else \
    t *= 1000000;
#endif

#ifdef _WIN32
#define UPDATE_SPIN_TIMEOUT(t, ts) t -= ts;
#else
#define UPDATE_SPIN_TIMEOUT(t, ts) t -= ts.tv_nsec;
#endif

#define INIT_QLOCK_TIMEOUT(t, ts) \
  ts.tv_sec = t / 1000; \
  ts.tv_nsec = t % 1000;

#define ALLOC_LOCK(d, l) \
  l = alloc_lock(d); \
  if(!l) { \
    unlock_queue(d); \
    show_lock_error(d, "Failed to allocate lock"); \
    return 0; \
  }

#define DEQUEUE_LOCK(d, dbh, l, lp) \
  if(lp->prev) { \
    lock_queue_node *pp = offsettoptr(d, lp->prev); \
    pp->next = lp->next; \
  } \
  if(lp->next) { \
    lock_queue_node *np = offsettoptr(d, lp->next); \
    np->prev = lp->prev; \
  } else if(dbh->locks.tail == l) { \
    dbh->locks.tail = lp->prev; \
  }

/* ======= Private protos ================ */


static inline void atomic_increment(volatile gint *ptr, gint incr);
static inline void atomic_and(volatile gint *ptr, gint val);
static inline gint fetch_and_add(volatile gint *ptr, gint incr);
static inline gint fetch_and_store(volatile gint *ptr, gint val);
// static inline gint compare_and_swap(volatile gint *ptr, gint oldv, gint newv);

#if (LOCK_PROTO==TFQUEUE)
static inline gint alloc_lock(void * db);
static inline void free_lock(void * db, gint node);
/*static gint deref_link(void *db, volatile gint *link);*/
#ifdef __linux__
static inline void futex_wait(volatile gint *addr1, int val1);
static inline int futex_trywait(volatile gint *addr1, int val1,
  struct timespec *timeout);
static inline void futex_wake(volatile gint *addr1, int val1);
#endif
#endif

static gint show_lock_error(void *db, char *errmsg);


/* ====== Functions ============== */


/* -------------- helper functions -------------- */

/*
 * System- and platform-dependent atomic operations
 */

/** Atomic increment. On x86 platform, this is internally
 *  the same as fetch_and_add().
 */

static inline void atomic_increment(volatile gint *ptr, gint incr) {
#if defined(DUMMY_ATOMIC_OPS)
  *ptr += incr;
#elif defined(__GNUC__)
#if defined(_MIPS_ARCH)
  gint tmp1, tmp2;  /* XXX: any way to get rid of these? */
  __asm__ __volatile__(
    ".set	noreorder\n\t"
    "1: ll	%0,%4\n\t"    /* load old */
    "add	%1,%0,%3\n\t" /* compute tmp2=tmp1+incr */
    "sc		%1,%2\n\t"    /* store new */
    "beqz	%1,1b\n\t"    /* SC failed, retry */
    "sync\n\t"
    ".set	reorder\n\t"
    : "=&r" (tmp1), "=&r" (tmp2), "=m" (*ptr)
    : "r" (incr), "m" (*ptr)
    : "memory");
#elif (GCC_VERSION < 40400) && defined(__ARM_EABI__) && defined(__linux__)
  gint failure, tmp;
  do {
    tmp = *ptr;
    failure = kernel_cmpxchg(tmp, tmp + incr, (int *) ptr);
  } while (failure != 0);
#else /* try gcc intrinsic */
  __sync_fetch_and_add(ptr, incr);
#endif
#elif defined(_WIN32)
  _InterlockedExchangeAdd(ptr, incr);
#else
#error Atomic operations not implemented for this compiler
#endif
}

/** Atomic AND operation.
 */

static inline void atomic_and(volatile gint *ptr, gint val) {
#if defined(DUMMY_ATOMIC_OPS)
  *ptr &= val;
#elif defined(__GNUC__)
#if defined(_MIPS_ARCH)
  gint tmp1, tmp2;
  __asm__ __volatile__(
    ".set	noreorder\n\t"
    "1: ll	%0,%4\n\t"      /* load old */
    "and	%1,%0,%3\n\t"   /* compute tmp2=tmp1 & val; */
    "sc		%1,%2\n\t"      /* store new */
    "beqz	%1,1b\n\t"      /* SC failed, retry */
    "sync\n\t"
    ".set	reorder\n\t"
    : "=&r" (tmp1), "=&r" (tmp2), "=m" (*ptr)
    : "r" (val), "m" (*ptr)
    : "memory");
#elif (GCC_VERSION < 40400) && defined(__ARM_EABI__) && defined(__linux__)
  gint failure, tmp;
  do {
    tmp = *ptr;
    failure = kernel_cmpxchg(tmp, tmp & val, (int *) ptr);
  } while (failure != 0);
#else /* try gcc intrinsic */
  __sync_fetch_and_and(ptr, val);
#endif
#elif defined(_WIN32)
  _InterlockedAnd(ptr, val);
#else
#error Atomic operations not implemented for this compiler
#endif
}

/** Atomic OR operation.
 */

static inline void atomic_or(volatile gint *ptr, gint val) {
#if defined(DUMMY_ATOMIC_OPS)
  *ptr |= val;
#elif defined(__GNUC__)
#if defined(_MIPS_ARCH)
  gint tmp1, tmp2;
  __asm__ __volatile__(
    ".set	noreorder\n\t"
    "1: ll	%0,%4\n\t"      /* load old */
    "or		%1,%0,%3\n\t"   /* compute tmp2=tmp1 | val; */
    "sc		%1,%2\n\t"      /* store new */
    "beqz	%1,1b\n\t"      /* SC failed, retry */
    "sync\n\t"
    ".set	reorder\n\t"
    : "=&r" (tmp1), "=&r" (tmp2), "=m" (*ptr)
    : "r" (val), "m" (*ptr)
    : "memory");
#elif (GCC_VERSION < 40400) && defined(__ARM_EABI__) && defined(__linux__)
  gint failure, tmp;
  do {
    tmp = *ptr;
    failure = kernel_cmpxchg(tmp, tmp | val, (int *) ptr);
  } while (failure != 0);
#else /* try gcc intrinsic */
  __sync_fetch_and_or(ptr, val);
#endif
#elif defined(_WIN32)
  _InterlockedOr(ptr, val);
#else
#error Atomic operations not implemented for this compiler
#endif
}

/** Fetch and (dec|inc)rement. Returns value before modification.
 */

static inline gint fetch_and_add(volatile gint *ptr, gint incr) {
#if defined(DUMMY_ATOMIC_OPS)
  gint tmp = *ptr;
  *ptr += incr;
  return tmp;
#elif defined(__GNUC__)
#if defined(_MIPS_ARCH)
  gint ret, tmp;
  __asm__ __volatile__(
    ".set	noreorder\n\t"
    "1: ll	%0,%4\n\t"      /* load old */
    "add	%1,%0,%3\n\t"   /* compute tmp=ret+incr */
    "sc		%1,%2\n\t"      /* store new */
    "beqz	%1,1b\n\t"      /* SC failed, retry */
    "sync\n\t"
    ".set	reorder\n\t"
    : "=&r" (ret), "=&r" (tmp), "=m" (*ptr)
    : "r" (incr), "m" (*ptr)
    : "memory");
  return ret;
#elif (GCC_VERSION < 40400) && defined(__ARM_EABI__) && defined(__linux__)
  gint failure, tmp;
  do {
    tmp = *ptr;
    failure = kernel_cmpxchg(tmp, tmp + incr, (int *) ptr);
  } while (failure != 0);
  return tmp;
#else /* try gcc intrinsic */
  return __sync_fetch_and_add(ptr, incr);
#endif
#elif defined(_WIN32)
  return _InterlockedExchangeAdd(ptr, incr);
#else
#error Atomic operations not implemented for this compiler
#endif
}

/** Atomic fetch and store. Swaps two values.
 */

static inline gint fetch_and_store(volatile gint *ptr, gint val) {
  /* Despite the name, the GCC builtin should just
   * issue XCHG operation. There is no testing of
   * anything, just lock the bus and swap the values,
   * as per Intel's opcode reference.
   *
   * XXX: not available on all compiler targets :-(
   */
#if defined(DUMMY_ATOMIC_OPS)
  gint tmp = *ptr;
  *ptr = val;
  return tmp;
#elif defined(__GNUC__)
#if defined(_MIPS_ARCH)
  gint ret, tmp;
  __asm__ __volatile__(
    ".set	noreorder\n\t"
    "1: ll	%0,%4\n\t"  /* load old */
    "move	%1,%3\n\t"
    "sc		%1,%2\n\t"  /* store new */
    "beqz	%1,1b\n\t"  /* SC failed, retry */
    "sync\n\t"
    ".set	reorder\n\t"
    : "=&r" (ret), "=&r" (tmp), "=m" (*ptr)
    : "r" (val), "m" (*ptr)
    : "memory");
  return ret;
#elif (GCC_VERSION < 40400) && defined(__ARM_EABI__) && defined(__linux__)
  gint failure, oldval;
  do {
    oldval = *ptr;
    failure = kernel_cmpxchg(oldval, val, (int *) ptr);
  } while (failure != 0);
  return oldval;
#else /* try gcc intrinsic */
  return __sync_lock_test_and_set(ptr, val);
#endif
#elif defined(_WIN32)
  return _InterlockedExchange(ptr, val);
#else
#error Atomic operations not implemented for this compiler
#endif
}

/** Compare and swap. If value at ptr equals old, set it to
 *  new and return 1. Otherwise the function returns 0.
 */

inline gint wg_compare_and_swap(volatile gint *ptr, gint oldv, gint newv) {
#if defined(DUMMY_ATOMIC_OPS)
  if(*ptr == oldv) {
    *ptr = newv;
    return 1;
  }
  return 0;
#elif defined(__GNUC__)
#if defined(_MIPS_ARCH)
  gint ret;
  __asm__ __volatile__(
    ".set	noreorder\n\t"
    "1: ll	%0,%4\n\t"
    "bne	%0,%2,2f\n\t"   /* *ptr!=oldv, return *ptr */
    "move	%0,%3\n\t"
    "sc		%0,%1\n\t"
    "beqz	%0,1b\n\t"      /* SC failed, retry */
    "move	%0,%2\n\t"      /* return oldv (*ptr==newv now) */
    "2: sync\n\t"
    ".set	reorder\n\t"
    : "=&r" (ret), "=m" (*ptr)
    : "r" (oldv), "r" (newv), "m" (*ptr)
    : "memory");
  return ret == oldv;
#elif (GCC_VERSION < 40400) && defined(__ARM_EABI__) && defined(__linux__)
  gint failure = kernel_cmpxchg(oldv, newv, (int *) ptr);
  return (failure == 0);
#else /* try gcc intrinsic */
  return __sync_bool_compare_and_swap(ptr, oldv, newv);
#endif
#elif defined(_WIN32)
  return (_InterlockedCompareExchange(ptr, newv, oldv) == oldv);
#else
#error Atomic operations not implemented for this compiler
#endif
}

/* ----------- read and write transaction support ----------- */

/*
 * Read and write transactions are currently realized using database
 * level locking. The rest of the db API is implemented independently -
 * therefore use of the locking routines does not automatically guarantee
 * isolation, rather, all of the concurrently accessing clients are expected
 * to follow the same protocol.
 */

/** Start write transaction
 *   Current implementation: acquire database level exclusive lock
 */

gint wg_start_write(void * db) {
  return db_wlock(db, DEFAULT_LOCK_TIMEOUT);
}

/** End write transaction
 *   Current implementation: release database level exclusive lock
 */

gint wg_end_write(void * db, gint lock) {
  return db_wulock(db, lock);
}

/** Start read transaction
 *   Current implementation: acquire database level shared lock
 */

gint wg_start_read(void * db) {
  return db_rlock(db, DEFAULT_LOCK_TIMEOUT);
}

/** End read transaction
 *   Current implementation: release database level shared lock
 */

gint wg_end_read(void * db, gint lock) {
  return db_rulock(db, lock);
}

/*
 * The following functions implement a giant shared/exclusive
 * lock on the database.
 *
 * Algorithms used for locking:
 *
 * 1. Simple reader-preference lock using a single global sync
 *    variable (described by Mellor-Crummey & Scott '92).
 * 2. A writer-preference spinlock based on the above.
 * 3. A task-fair lock implemented using a queue. Similar to
 *    the queue-based MCS rwlock, but uses futexes to synchronize
 *    the waiting processes.
 */

#if (LOCK_PROTO==RPSPIN)

/** Acquire database level exclusive lock (reader-preference spinlock)
 *   Blocks until lock is acquired.
 *   If USE_LOCK_TIMEOUT is defined, may return without locking
 */

#ifdef USE_LOCK_TIMEOUT
gint db_rpspin_wlock(void * db, gint timeout) {
#else
gint db_rpspin_wlock(void * db) {
#endif
  int i;
#ifdef _WIN32
  int ts;
#else
  struct timespec ts;
#endif
  volatile gint *gl;

#ifdef CHECK
  if (!dbcheck(db)) {
    show_lock_error(db, "Invalid database pointer in db_wlock");
    return 0;
  }
#endif

  gl = (gint *) offsettoptr(db, dbmemsegh(db)->locks.global_lock);

  /* First attempt at getting the lock without spinning */
  if(compare_and_swap(gl, 0, WAFLAG))
    return 1;

#ifdef _WIN32
  ts = SLEEP_MSEC;
#else
  ts.tv_sec = 0;
  ts.tv_nsec = SLEEP_NSEC;
#endif

#ifdef USE_LOCK_TIMEOUT
  INIT_SPIN_TIMEOUT(timeout)
#endif

  /* Spin loop */
  for(;;) {
    for(i=0; i<SPIN_COUNT; i++) {
      MM_PAUSE
      if(!(*gl) && compare_and_swap(gl, 0, WAFLAG))
        return 1;
    }

    /* Check if we would time out during next sleep. Note that
     * this is not a real time measurement.
     */
#ifdef USE_LOCK_TIMEOUT
    UPDATE_SPIN_TIMEOUT(timeout, ts)
    if(timeout < 0)
      return 0;
#endif

    /* Give up the CPU so the lock holder(s) can continue */
#ifdef _WIN32
    Sleep(ts);
    ts += SLEEP_MSEC;
#else
    nanosleep(&ts, NULL);
    ts.tv_nsec += SLEEP_NSEC;
#endif
  }

  return 0; /* dummy */
}

/** Release database level exclusive lock (reader-preference spinlock)
 */

gint db_rpspin_wulock(void * db) {

  volatile gint *gl;

#ifdef CHECK
  if (!dbcheck(db)) {
    show_lock_error(db, "Invalid database pointer in db_wulock");
    return 0;
  }
#endif

  gl = (gint *) offsettoptr(db, dbmemsegh(db)->locks.global_lock);

  /* Clear the writer active flag */
  atomic_and(gl, ~(WAFLAG));

  return 1;
}

/** Acquire database level shared lock (reader-preference spinlock)
 *   Increments reader count, blocks until there are no active
 *   writers.
 *   If USE_LOCK_TIMEOUT is defined, may return without locking.
 */

#ifdef USE_LOCK_TIMEOUT
gint db_rpspin_rlock(void * db, gint timeout) {
#else
gint db_rpspin_rlock(void * db) {
#endif
  int i;
#ifdef _WIN32
  int ts;
#else
  struct timespec ts;
#endif
  volatile gint *gl;

#ifdef CHECK
  if (!dbcheck(db)) {
    show_lock_error(db, "Invalid database pointer in db_rlock");
    return 0;
  }
#endif

  gl = (gint *) offsettoptr(db, dbmemsegh(db)->locks.global_lock);

  /* Increment reader count atomically */
  fetch_and_add(gl, RC_INCR);

  /* Try getting the lock without pause */
  if(!((*gl) & WAFLAG)) return 1;

#ifdef _WIN32
  ts = SLEEP_MSEC;
#else
  ts.tv_sec = 0;
  ts.tv_nsec = SLEEP_NSEC;
#endif

#ifdef USE_LOCK_TIMEOUT
  INIT_SPIN_TIMEOUT(timeout)
#endif

  /* Spin loop */
  for(;;) {
    for(i=0; i<SPIN_COUNT; i++) {
      MM_PAUSE
      if(!((*gl) & WAFLAG)) return 1;
    }

    /* Check for timeout. */
#ifdef USE_LOCK_TIMEOUT
    UPDATE_SPIN_TIMEOUT(timeout, ts)
    if(timeout < 0) {
      /* We're no longer waiting, restore the counter */
      fetch_and_add(gl, -RC_INCR);
      return 0;
    }
#endif

#ifdef _WIN32
    Sleep(ts);
    ts += SLEEP_MSEC;
#else
    nanosleep(&ts, NULL);
    ts.tv_nsec += SLEEP_NSEC;
#endif
  }

  return 0; /* dummy */
}

/** Release database level shared lock (reader-preference spinlock)
 */

gint db_rpspin_rulock(void * db) {

  volatile gint *gl;

#ifdef CHECK
  if (!dbcheck(db)) {
    show_lock_error(db, "Invalid database pointer in db_rulock");
    return 0;
  }
#endif

  gl = (gint *) offsettoptr(db, dbmemsegh(db)->locks.global_lock);

  /* Decrement reader count */
  fetch_and_add(gl, -RC_INCR);

  return 1;
}

#elif (LOCK_PROTO==WPSPIN)

/** Acquire database level exclusive lock (writer-preference spinlock)
 *   Blocks until lock is acquired.
 */

#ifdef USE_LOCK_TIMEOUT
gint db_wpspin_wlock(void * db, gint timeout) {
#else
gint db_wpspin_wlock(void * db) {
#endif
  int i;
#ifdef _WIN32
  int ts;
#else
  struct timespec ts;
#endif
  volatile gint *gl, *w;

#ifdef CHECK
  if (!dbcheck(db)) {
    show_lock_error(db, "Invalid database pointer in db_wlock");
    return 0;
  }
#endif

  gl = (gint *) offsettoptr(db, dbmemsegh(db)->locks.global_lock);
  w = (gint *) offsettoptr(db, dbmemsegh(db)->locks.writers);

  /* Let the readers know a writer is present */
  atomic_increment(w, 1);

  /* First attempt at getting the lock without spinning */
  if(compare_and_swap(gl, 0, WAFLAG))
    return 1;

#ifdef _WIN32
  ts = SLEEP_MSEC;
#else
  ts.tv_sec = 0;
  ts.tv_nsec = SLEEP_NSEC;
#endif

#ifdef USE_LOCK_TIMEOUT
  INIT_SPIN_TIMEOUT(timeout)
#endif

  /* Spin loop */
  for(;;) {
    for(i=0; i<SPIN_COUNT; i++) {
      MM_PAUSE
      if(!(*gl) && compare_and_swap(gl, 0, WAFLAG))
        return 1;
    }

    /* Check for timeout. */
#ifdef USE_LOCK_TIMEOUT
    UPDATE_SPIN_TIMEOUT(timeout, ts)
    if(timeout < 0) {
      /* Restore the previous writer count */
      atomic_increment(w, -1);
      return 0;
    }
#endif

    /* Give up the CPU so the lock holder(s) can continue */
#ifdef _WIN32
    Sleep(ts);
    ts += SLEEP_MSEC;
#else
    nanosleep(&ts, NULL);
    ts.tv_nsec += SLEEP_NSEC;
#endif
  }

  return 0; /* dummy */
}

/** Release database level exclusive lock (writer-preference spinlock)
 */

gint db_wpspin_wulock(void * db) {

  volatile gint *gl, *w;

#ifdef CHECK
  if (!dbcheck(db)) {
    show_lock_error(db, "Invalid database pointer in db_wulock");
    return 0;
  }
#endif

  gl = (gint *) offsettoptr(db, dbmemsegh(db)->locks.global_lock);
  w = (gint *) offsettoptr(db, dbmemsegh(db)->locks.writers);

  /* Clear the writer active flag */
  atomic_and(gl, ~(WAFLAG));

  /* writers-- */
  atomic_increment(w, -1);

  return 1;
}

/** Acquire database level shared lock (writer-preference spinlock)
 *   Blocks until there are no active or waiting writers, then increments
 *   reader count atomically.
 */

#ifdef USE_LOCK_TIMEOUT
gint db_wpspin_rlock(void * db, gint timeout) {
#else
gint db_wpspin_rlock(void * db) {
#endif
  int i;
#ifdef _WIN32
  int ts;
#else
  struct timespec ts;
#endif
  volatile gint *gl, *w;

#ifdef CHECK
  if (!dbcheck(db)) {
    show_lock_error(db, "Invalid database pointer in db_rlock");
    return 0;
  }
#endif

  gl = (gint *) offsettoptr(db, dbmemsegh(db)->locks.global_lock);
  w = (gint *) offsettoptr(db, dbmemsegh(db)->locks.writers);

  /* Try locking without spinning */
  if(!(*w)) {
    gint readers = (*gl) & ~WAFLAG;
    if(compare_and_swap(gl, readers, readers + RC_INCR))
      return 1;
  }

#ifdef USE_LOCK_TIMEOUT
  INIT_SPIN_TIMEOUT(timeout)
#endif

  for(;;) {
#ifdef _WIN32
    ts = SLEEP_MSEC;
#else
    ts.tv_sec = 0;
    ts.tv_nsec = SLEEP_NSEC;
#endif

    /* Spin-wait until writers disappear */
    while(*w) {
      for(i=0; i<SPIN_COUNT; i++) {
        MM_PAUSE
        if(!(*w)) goto no_writers;
      }

#ifdef USE_LOCK_TIMEOUT
      UPDATE_SPIN_TIMEOUT(timeout, ts)
      if(timeout < 0)
        return 0;
#endif

#ifdef _WIN32
      Sleep(ts);
      ts += SLEEP_MSEC;
#else
      nanosleep(&ts, NULL);
      ts.tv_nsec += SLEEP_NSEC;
#endif
    }
no_writers:

    do {
      gint readers = (*gl) & ~WAFLAG;
      /* Atomically increment the reader count. If a writer has activated,
       * this fails and the do loop will also exit. If another reader modifies
       * the value, we retry.
       *
       * XXX: maybe MM_PAUSE and non-atomic checking can affect the
       * performance here, like in spin loops (this is more like a
       * retry loop though, not clear how many times it will typically
       * repeat).
       */
      if(compare_and_swap(gl, readers, readers + RC_INCR))
        return 1;
    } while(!(*w));
  }

  return 0; /* dummy */
}

/** Release database level shared lock (writer-preference spinlock)
 */

gint db_wpspin_rulock(void * db) {

  volatile gint *gl;

#ifdef CHECK
  if (!dbcheck(db)) {
    show_lock_error(db, "Invalid database pointer in db_rulock");
    return 0;
  }
#endif

  gl = (gint *) offsettoptr(db, dbmemsegh(db)->locks.global_lock);

  /* Decrement reader count */
  atomic_increment(gl, -RC_INCR);

  return 1;
}

#elif (LOCK_PROTO==TFQUEUE)

/** Acquire the queue mutex.
 */
static void lock_queue(void * db) {
  int i;
#ifdef _WIN32
  int ts;
#else
  struct timespec ts;
#endif
  volatile gint *gl;

  /* skip the database pointer check, this function is not called directly */
  gl = (gint *) offsettoptr(db, dbmemsegh(db)->locks.queue_lock);

  /* First attempt at getting the lock without spinning */
  if(compare_and_swap(gl, 0, 1))
    return;

#ifdef _WIN32
  ts = SLEEP_MSEC;
#else
  ts.tv_sec = 0;
  ts.tv_nsec = SLEEP_NSEC;
#endif

  /* Spin loop */
  for(;;) {
    for(i=0; i<SPIN_COUNT; i++) {
      MM_PAUSE
      if(!(*gl) && compare_and_swap(gl, 0, 1))
        return;
    }

    /* Backoff */
#ifdef _WIN32
    Sleep(ts);
    ts += SLEEP_MSEC;
#else
    nanosleep(&ts, NULL);
    ts.tv_nsec += SLEEP_NSEC;
#endif
  }
}

/** Release the queue mutex
 */
static void unlock_queue(void * db) {
  volatile gint *gl;

  gl = (gint *) offsettoptr(db, dbmemsegh(db)->locks.queue_lock);

  *gl = 0;
}

/** Acquire database level exclusive lock (task-fair queued lock)
 *   Blocks until lock is acquired.
 *   If USE_LOCK_TIMEOUT is defined, may return without locking
 */

#ifdef USE_LOCK_TIMEOUT
gint db_tfqueue_wlock(void * db, gint timeout) {
#else
gint db_tfqueue_wlock(void * db) {
#endif
#ifdef _WIN32
  int ts;
#else
  struct timespec ts;
#endif
  gint lock, prev;
  lock_queue_node *lockp;
  db_memsegment_header* dbh;

#ifdef CHECK
  if (!dbcheck(db)) {
    show_lock_error(db, "Invalid database pointer in db_wlock");
    return 0;
  }
#endif

  dbh = dbmemsegh(db);

  lock_queue(db);
  ALLOC_LOCK(db, lock)

  prev = dbh->locks.tail;
  dbh->locks.tail = lock;

  lockp = (lock_queue_node *) offsettoptr(db, lock);
  lockp->class = LOCKQ_WRITE;
  lockp->prev = prev;
  lockp->next = 0;

  if(prev) {
    lock_queue_node *prevp = offsettoptr(db, prev);
    prevp->next = lock;
    lockp->waiting = 1;
  } else {
    lockp->waiting = 0;
  }

  unlock_queue(db);

  if(lockp->waiting) {
#ifdef __linux__
#ifdef USE_LOCK_TIMEOUT
    INIT_QLOCK_TIMEOUT(timeout, ts)
    if(futex_trywait(&lockp->waiting, 1, &ts) == ETIMEDOUT) {
      lock_queue(db);
      DEQUEUE_LOCK(db, dbh, lock, lockp)
      free_lock(db, lock);
      unlock_queue(db);
      return 0;
    }
#else
    futex_wait(&lockp->waiting, 1);
#endif
#else
/* XXX: add support for other platforms */
#error This code needs Linux SYS_futex service to function
#endif
  }

  return lock;
}

/** Release database level exclusive lock (task-fair queued lock)
 */

gint db_tfqueue_wulock(void * db, gint lock) {
  lock_queue_node *lockp;
  db_memsegment_header* dbh;
  volatile gint *syn_addr = NULL;

#ifdef CHECK
  if (!dbcheck(db)) {
    show_lock_error(db, "Invalid database pointer in db_wulock");
    return 0;
  }
#endif

  dbh = dbmemsegh(db);
  lockp = (lock_queue_node *) offsettoptr(db, lock);

  lock_queue(db);
  if(lockp->next) {
    lock_queue_node *nextp = offsettoptr(db, lockp->next);
    nextp->waiting = 0;
    nextp->prev = 0; /* we're a writer lock, head of the queue */
    syn_addr = &nextp->waiting;
  } else if(dbh->locks.tail == lock) {
    dbh->locks.tail = 0;
  }
  free_lock(db, lock);
  unlock_queue(db);
  if(syn_addr) {
#ifdef __linux__
    futex_wake(syn_addr, 1);
#else
/* XXX: add support for other platforms */
#error This code needs Linux SYS_futex service to function
#endif
  }

  return 1;
}

/** Acquire database level shared lock (task-fair queued lock)
 *   If USE_LOCK_TIMEOUT is defined, may return without locking.
 */

#ifdef USE_LOCK_TIMEOUT
gint db_tfqueue_rlock(void * db, gint timeout) {
#else
gint db_tfqueue_rlock(void * db) {
#endif
#ifdef _WIN32
  int ts;
#else
  struct timespec ts;
#endif
  gint lock, prev;
  lock_queue_node *lockp;
  db_memsegment_header* dbh;

#ifdef CHECK
  if (!dbcheck(db)) {
    show_lock_error(db, "Invalid database pointer in db_rlock");
    return 0;
  }
#endif

  dbh = dbmemsegh(db);

  lock_queue(db);
  ALLOC_LOCK(db, lock)

  prev = dbh->locks.tail;
  dbh->locks.tail = lock;

  lockp = (lock_queue_node *) offsettoptr(db, lock);
  lockp->class = LOCKQ_READ;
  lockp->prev = prev;
  lockp->next = 0;

  if(prev) {
    lock_queue_node *prevp = (lock_queue_node *) offsettoptr(db, prev);
    prevp->next = lock;

    if(prevp->class == LOCKQ_READ && prevp->waiting == 0) {
      lockp->waiting = 0;
    } else {
      lockp->waiting = 1;
    }
  } else {
    lockp->waiting = 0;
  }
  unlock_queue(db);

  if(lockp->waiting) {
    volatile gint *syn_addr = NULL;
#ifdef __linux__
#ifdef USE_LOCK_TIMEOUT
    INIT_QLOCK_TIMEOUT(timeout, ts)
    if(futex_trywait(&lockp->waiting, 1, &ts) == ETIMEDOUT) {
      lock_queue(db);
      DEQUEUE_LOCK(db, dbh, lock, lockp)
      free_lock(db, lock);
      unlock_queue(db);
      return 0;
    }
#else
    futex_wait(&lockp->waiting, 1);
#endif
#else
/* XXX: add support for other platforms */
#error This code needs Linux SYS_futex service to function
#endif
    lock_queue(db);
    if(lockp->next) {
      lock_queue_node *nextp = offsettoptr(db, lockp->next);
      if(nextp->class == LOCKQ_READ && nextp->waiting) {
        nextp->waiting = 0;
        syn_addr = &nextp->waiting;
      }
    }
    unlock_queue(db);
    if(syn_addr) {
#ifdef __linux__
      futex_wake(syn_addr, 1);
#else
/* XXX: add support for other platforms */
#error This code needs Linux SYS_futex service to function
#endif
    }
  }

  return lock;
}

/** Release database level shared lock (task-fair queued lock)
 */

gint db_tfqueue_rulock(void * db, gint lock) {
  lock_queue_node *lockp;
  db_memsegment_header* dbh;
  volatile gint *syn_addr = NULL;

#ifdef CHECK
  if (!dbcheck(db)) {
    show_lock_error(db, "Invalid database pointer in db_rulock");
    return 0;
  }
#endif

  dbh = dbmemsegh(db);
  lockp = (lock_queue_node *) offsettoptr(db, lock);

  lock_queue(db);
  if(lockp->prev) {
    lock_queue_node *prevp = offsettoptr(db, lockp->prev);
    prevp->next = lockp->next;
  }
  if(lockp->next) {
    lock_queue_node *nextp = offsettoptr(db, lockp->next);
    nextp->prev = lockp->prev;
    if(nextp->waiting && (!lockp->prev || nextp->class == LOCKQ_READ)) {
      nextp->waiting = 0;
      syn_addr = &nextp->waiting;
    }
  } else if(dbh->locks.tail == lock) {
    dbh->locks.tail = lockp->prev;
  }
  free_lock(db, lock);
  unlock_queue(db);
  if(syn_addr) {
#ifdef __linux__
    futex_wake(syn_addr, 1);
#else
/* XXX: add support for other platforms */
#error This code needs Linux SYS_futex service to function
#endif
  }

  return 1;
}

#endif /* LOCK_PROTO */

/** Initialize locking subsystem.
 *   Not parallel-safe, so should be run during database init.
 *
 * Note that this function is called even if locking is disabled.
 */
gint wg_init_locks(void * db) {
#if (LOCK_PROTO==TFQUEUE)
  gint i, chunk_wall;
  lock_queue_node *tmp = NULL;
#endif
  db_memsegment_header* dbh;

#ifdef CHECK
  if (!dbcheck(db) && !dbcheckinit(db)) {
    show_lock_error(db, "Invalid database pointer in wg_init_locks");
    return -1;
  }
#endif
  dbh = dbmemsegh(db);

#if (LOCK_PROTO==TFQUEUE)
  chunk_wall = dbh->locks.storage + dbh->locks.max_nodes*SYN_VAR_PADDING;

  for(i=dbh->locks.storage; i<chunk_wall; ) {
    tmp = (lock_queue_node *) offsettoptr(db, i);
    i+=SYN_VAR_PADDING;
    tmp->next_cell = i; /* offset of next cell */
  }
  tmp->next_cell=0; /* last node */

  /* top of the stack points to first cell in chunk */
  dbh->locks.freelist = dbh->locks.storage;

  /* reset the state */
  dbh->locks.tail = 0; /* 0 is considered invalid offset==>no value */
  dbstore(db, dbh->locks.queue_lock, 0);
#else
  dbstore(db, dbh->locks.global_lock, 0);
  dbstore(db, dbh->locks.writers, 0);
#endif
  return 0;
}

#if (LOCK_PROTO==TFQUEUE)

/* ---------- memory management for queued locks ---------- */

/*
 * Queued locks algorithm assumes allocating memory cells
 * for each lock. These cells need to be memory-aligned to
 * allow spinlocks run locally, but more importantly, allocation
 * and freeing of the cells has to be implemented in a lock-free
 * manner.
 *
 * The method used in the initial implementation is freelist
 * with reference counts (generally described by Valois '95,
 * actual code is based on examples from
 * http://www.non-blocking.com/Eng/services-technologies_non-blocking-lock-free.htm)
 *
 * XXX: code untested currently
 * XXX: Mellor-Crummey & Scott algorithm possibly does not need
 *      refcounts. If so, they should be #ifdef-ed out, but
 *      kept for possible future expansion.
 */

/** Allocate memory cell for a lock.
 *   Used internally only, so we assume the passed db pointer
 *   is already validated.
 *
 *   Returns offset to allocated cell.
 */

#if 0
static inline gint alloc_lock(void * db) {
  db_memsegment_header* dbh = dbmemsegh(db);
  lock_queue_node *tmp;

  for(;;) {
    gint t = dbh->locks.freelist;
    if(!t)
      return 0; /* end of chain :-( */
    tmp = (lock_queue_node *) offsettoptr(db, t);

    fetch_and_add(&(tmp->refcount), 2);

    if(compare_and_swap(&(dbh->locks.freelist), t, tmp->next_cell)) {
      fetch_and_add(&(tmp->refcount), -1); /* clear lsb */
      return t;
    }

    free_lock(db, t);
  }

  return 0; /* dummy */
}

/** Release memory cell for a lock.
 *   Used internally only.
 */

static inline void free_lock(void * db, gint node) {
  db_memsegment_header* dbh = dbmemsegh(db);
  lock_queue_node *tmp;
  volatile gint t;

  tmp = (lock_queue_node *) offsettoptr(db, node);

  /* Clear reference */
  fetch_and_add(&(tmp->refcount), -2);

  /* Try to set lsb */
  if(compare_and_swap(&(tmp->refcount), 0, 1)) {

/* XXX:
    if(tmp->next_cell) free_lock(db, tmp->next_cell);
*/
    do {
      t = dbh->locks.freelist;
      tmp->next_cell = t;
    } while (!compare_and_swap(&(dbh->locks.freelist), t, node));
  }
}

/** De-reference (release pointer to) a link.
 *   Used internally only.
 */

static inline gint deref_link(void *db, volatile gint *link) {
  lock_queue_node *tmp;
  volatile gint t;

  for(;;) {
    t = *link;
    if(t == 0) return 0;

    tmp = (lock_queue_node *) offsettoptr(db, t);

    fetch_and_add(&(tmp->refcount), 2);
    if(t == *link) return t;
    free_lock(db, t);
  }
}

#else
/* Simple lock memory allocation (non lock-free) */

static inline gint alloc_lock(void * db) {
  db_memsegment_header* dbh = dbmemsegh(db);
  gint t = dbh->locks.freelist;
  lock_queue_node *tmp;

  if(!t)
    return 0; /* end of chain :-( */
  tmp = (lock_queue_node *) offsettoptr(db, t);

  dbh->locks.freelist = tmp->next_cell;
  return t;
}

static inline void free_lock(void * db, gint node) {
  db_memsegment_header* dbh = dbmemsegh(db);
  lock_queue_node *tmp = (lock_queue_node *) offsettoptr(db, node);
  tmp->next_cell = dbh->locks.freelist;
  dbh->locks.freelist = node;
}

#endif

#ifdef __linux__
/* Futex operations */

static inline void futex_wait(volatile gint *addr1, int val1)
{
  syscall(SYS_futex, (void *) addr1, FUTEX_WAIT, val1, NULL);
}

static inline int futex_trywait(volatile gint *addr1, int val1,
  struct timespec *timeout)
{
  if(syscall(SYS_futex, (void *) addr1, FUTEX_WAIT, val1, timeout) == -1)
    return errno; /* On Linux, this is thread-safe. Caution needed however */
  else
    return 0;
}

static inline void futex_wake(volatile gint *addr1, int val1)
{
  syscall(SYS_futex, (void *) addr1, FUTEX_WAKE, val1);
}
#endif

#endif /* LOCK_PROTO==TFQUEUE */


/* ------------ error handling ---------------- */

static gint show_lock_error(void *db, char *errmsg) {
#ifdef WG_NO_ERRPRINT
#else
  fprintf(stderr,"wg locking error: %s.\n", errmsg);
#endif
  return -1;
}

#ifdef __cplusplus
}
#endif