summaryrefslogtreecommitdiff
path: root/src/key-value-store/database/kissdb.c
blob: 6a4d11938bffd79a4f0843a4623a7b2a21c8ad92 (plain)
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
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
/******************************************************************************
* Project         Persistency
* (c) copyright   2014
* Company         XS Embedded GmbH
*****************************************************************************/
/* (Keep It) Simple Stupid Database
*
* Written by Adam Ierymenko <adam.ierymenko@zerotier.com>
* Modified by Simon Disch <simon.disch@xse.de>
*
* KISSDB is in the public domain and is distributed with NO WARRANTY.
*
* http://creativecommons.org/publicdomain/zero/1.0/ */

/* Compile with KISSDB_TEST to build as a test program. */

/* Note: big-endian systems will need changes to implement byte swapping
* on hash table file I/O. Or you could just use it as-is if you don't care
* that your database files will be unreadable on little-endian systems. */
#define _FILE_OFFSET_BITS 64
#define KISSDB_HEADER_SIZE sizeof(Header_s)

#include "./kissdb.h"
#include "../crc32.h"
#include <string.h>
#include <stdlib.h>
#include <inttypes.h>
#include <stdint.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/mman.h>
#include <unistd.h>
#include <ctype.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <semaphore.h>
#include <dlt.h>
#include "persComErrors.h"

//
//#ifdef COND_GCOV
//extern void __gcov_flush(void);
//#endif

//#define PFS_TEST
//extern DltContext persComLldbDLTCtx;
DLT_IMPORT_CONTEXT (persComLldbDLTCtx)

#ifdef __showTimeMeasurements
inline long long getNsDuration(struct timespec* start, struct timespec* end)
{
   return ((end->tv_sec * SECONDS2NANO) + end->tv_nsec) - ((start->tv_sec * SECONDS2NANO) + start->tv_nsec);
}
#endif

/* djb2 hash function */
static uint64_t KISSDB_hash(const void* b, unsigned long len)
{
   unsigned long i;
   uint64_t hash = 5381;
   for (i = 0; i < len; ++i)
   {
      hash = ((hash << 5) + hash) + (uint64_t) (((const uint8_t*) b)[i]);
   }
   return hash;
}

#if 1
//returns a name for shared memory objects beginning with a slash followed by "path" (non alphanumeric chars are replaced with '_')  appended with "tailing"
char* kdbGetShmName(const char* tailing, const char* path)
{
   int pathLen = strlen(path);
   int tailLen = strlen(tailing);
   char* result = (char*) malloc(1 + pathLen + tailLen + 1);   //free happens at lifecycle shutdown
   int i =0;
   int x = 1;

   if (result != NULL)
   {
      result[0] = '/';
      for (i = 0; i < pathLen; i++)
      {
         if (!isalnum(path[i]))
         {
            result[i + 1] = '_';
         }
         else
         {
            result[i + 1] = path[i];
         }
      }
      for (x = 0; x < tailLen; x++)
      {
         result[i + x + 1] = tailing[x];
      }
      result[i + x + 1] = '\0';
   }
   else
   {
      result = NULL;
   }
   return result;
}
#endif



//returns -1 on error and positive value for success
int kdbShmemOpen(const char* name, size_t length, Kdb_bool* shmCreator)
{
   int result;
   result = shm_open(name, O_CREAT | O_EXCL | O_RDWR, S_IRUSR | S_IWUSR);
   if (result < 0)
   {
      if (errno == EEXIST)
      {
         *shmCreator = Kdb_false;
         result = shm_open(name, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
         if (result < 0)
         {
            return -1;
         }
      }
   }
   else
   {
      *shmCreator = Kdb_true;
      if (ftruncate(result, length) < 0)
      {
         return -1;
      }
   }
   return result;
}

void Kdb_wrlock(pthread_rwlock_t* wrlock)
{
   pthread_rwlock_wrlock(wrlock);
}

//void Kdb_rdlock(pthread_rwlock_t* rdlock)
//{
//   pthread_rwlock_rdlock(rdlock);
//}

void Kdb_unlock(pthread_rwlock_t* lock)
{
   pthread_rwlock_unlock(lock);
}

Kdb_bool kdbShmemClose(int shmem, const char* shmName)
{
   if( close(shmem) == -1)
   {
      return Kdb_false;
   }
   if( shm_unlink(shmName) < 0)
   {
      return Kdb_false;
   }
   return Kdb_true;
}

void* getKdbShmemPtr(int shmem, size_t length)
{
   void* result = mmap(NULL, length, PROT_READ | PROT_WRITE, MAP_SHARED, shmem, 0);
   if (result == MAP_FAILED)
   {
      return ((void*) -1);
   }
   return result;
}


Kdb_bool freeKdbShmemPtr(void* shmem_ptr, size_t length)
{
   if(munmap(shmem_ptr, length) == 0)
   {
      return Kdb_true;
   }
   else
   {
      return Kdb_false;
   }
}

Kdb_bool resizeKdbShmem(int shmem, Hashtable_s** shmem_ptr, size_t oldLength, size_t newLength)
{
   //unmap shm with old size
   if( freeKdbShmemPtr(*shmem_ptr, oldLength) == Kdb_false)
   {
      return Kdb_false;
   }

   if (ftruncate(shmem, newLength) < 0)
   {
      return Kdb_false;
   }

   //get pointer to resized shm with new Length
   *shmem_ptr = getKdbShmemPtr(shmem, newLength);
   if(*shmem_ptr == ((void*) -1))
   {
      return Kdb_false;
   }
   return Kdb_true;
}


Kdb_bool remapSharedHashtable(int shmem, Hashtable_s** shmem_ptr, size_t oldLength, size_t newLength )
{
   //unmap hashtable with old size
   if( freeKdbShmemPtr(*shmem_ptr, oldLength) == Kdb_false)
   {
      return Kdb_false;
   }
   //get pointer to resized shm with new Length
   *shmem_ptr = getKdbShmemPtr(shmem, newLength);
   if(*shmem_ptr == ((void*) -1))
   {
      return Kdb_false;
   }
   return Kdb_true;
}

#if 0
void printKdb(KISSDB* db)
{
   printf("START ############################### \n");
   printf("db->htSize:  %d \n", db->htSize);
   printf("db->cacheReferenced: %d \n", db->cacheReferenced);
   printf("db->keySize:  %" PRId64 " \n", db->keySize);
   printf("db->valSize:  %" PRId64 " \n", db->valSize);
   printf("db->htSizeBytes:  %" PRId64 " \n", db->htSizeBytes);
   printf("db->htMappedSize:  %" PRId64 " \n", db->htMappedSize);
   printf("db->dbMappedSize:  %" PRId64 " \n", db->dbMappedSize);
   printf("db->shmCreator:  %d \n", db->shmCreator);
   printf("db->alreadyOpen:  %d \n", db->alreadyOpen);
   printf("db->hashTables:  %p \n", db->hashTables);
   printf("db->mappedDb:  %p \n", db->mappedDb);
   printf("db->sharedCache:  %p \n", db->sharedCache);
   printf("db->sharedFd:  %d \n", db->sharedFd);
   printf("db->htFd:  %d \n", db->htFd);
   printf("db->sharedCacheFd:  %d \n", db->sharedCacheFd);
   printf("db->semName:  %s \n", db->semName);
   printf("db->sharedName:  %s \n", db->sharedName);
   printf("db->cacheName:  %s \n", db->cacheName);
   printf("db->htName:  %s \n", db->htName);
   printf("db->shared:  %p \n", db->shared);
   printf("db->tbl:  %p \n", db->tbl[0]);
   printf("db->kdbSem:  %p \n", db->kdbSem);
   printf("db->fd:  %d \n", db->fd);
   printf("END ############################### \n");
}
#endif


int KISSDB_open(KISSDB* db, const char* path, int openMode, int writeMode, uint16_t hash_table_size, uint64_t key_size, uint64_t value_size)
{
   Hashtable_s* htptr;
   int ret = 0;
   Kdb_bool htFound;
   Kdb_bool tmpCreator;
   off_t offset = 0;
   size_t firstMappSize;
   struct stat sb;

   if (db->alreadyOpen == Kdb_false) //check if this instance has already opened the db before
   {
      db->sharedName = kdbGetShmName("-shm-info", path);
      if (db->sharedName == NULL)
      {
         return KISSDB_ERROR_MALLOC;
      }
      db->sharedFd = kdbShmemOpen(db->sharedName, sizeof(Shared_Data_s), &db->shmCreator);
      if (db->sharedFd < 0)
      {
         return KISSDB_ERROR_OPEN_SHM;
      }
      db->shared = (Shared_Data_s*) getKdbShmemPtr(db->sharedFd, sizeof(Shared_Data_s));
      if (db->shared == ((void*) -1))
      {
         return KISSDB_ERROR_MAP_SHM;
      }

      db->sharedCacheFd = -1;
      db->mappedDb = NULL;

      if (db->shmCreator == Kdb_true)
      {
         //[Initialize rwlock attributes]
         pthread_rwlockattr_t rwlattr;
         pthread_rwlockattr_init(&rwlattr);
         pthread_rwlockattr_setpshared(&rwlattr, PTHREAD_PROCESS_SHARED);
         pthread_rwlock_init(&db->shared->rwlock, &rwlattr);

         Kdb_wrlock(&db->shared->rwlock);

         //init cache filedescriptor, reference counter and hashtable number
         db->sharedCacheFd = -1;
         db->shared->refCount = 0;
         db->shared->htNum = 0;
         db->shared->mappedDbSize = 0;
         db->shared->writeMode = writeMode;
         db->shared->openMode = openMode;
      }
      else
      {
         Kdb_wrlock(&db->shared->rwlock);
      }
   }
   else
   {
      Kdb_wrlock(&db->shared->rwlock);
   }

   switch (db->shared->openMode)
   {
      case KISSDB_OPEN_MODE_RWCREAT:
      {
         //create database
         db->fd = open(path, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
         break;
      }
      case KISSDB_OPEN_MODE_RDWR:
      {
         //read / write mode
         db->fd = open(path, O_RDWR, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
         break;
      }
      case KISSDB_OPEN_MODE_RDONLY:
      {
         db->fd = open(path, O_RDONLY);
         break;
      }
      default:
      {
         break;
      }
   }
   if(db->fd == -1)
   {
      DLT_LOG(persComLldbDLTCtx, DLT_LOG_ERROR, DLT_STRING(__FUNCTION__); DLT_STRING(": Opening database file: <"); DLT_STRING(path); DLT_STRING("> failed: "); DLT_STRING(strerror(errno)));
      return KISSDB_ERROR_IO;
   }

   if( 0 != fstat(db->fd, &sb))
   {
      return KISSDB_ERROR_IO;
   }


   /* mmap whole database file if it already exists (else the file is mapped in writeheader()) */
   if (sb.st_size > 0)
   {
      if(db->shared->openMode != KISSDB_OPEN_MODE_RDONLY )
      {
         db->mappedDb = (void*) mmap(NULL, sb.st_size, PROT_WRITE | PROT_READ, MAP_SHARED, db->fd, 0);
      }
      else
      {
         db->mappedDb = (void*) mmap(NULL, sb.st_size, PROT_READ, MAP_SHARED, db->fd, 0);
      }
      if (db->mappedDb == MAP_FAILED)
      {
         return KISSDB_ERROR_IO;
      }
      else
      {
         //update mapped size
         db->shared->mappedDbSize = (uint64_t)sb.st_size;
         db->dbMappedSize = db->shared->mappedDbSize;
      }
   }

   offset = sb.st_size;
   if (offset == -1)
   {
      return KISSDB_ERROR_IO;
   }
   if ( offset < KISSDB_HEADER_SIZE)
   {
      /* write header if not already present */
      if ((hash_table_size) && (key_size) && (value_size))
      {
         ret = writeHeader(db, &hash_table_size, &key_size, &value_size);
         if(0 != ret)
         {
            return ret;
         }
      }
      else
      {
         return KISSDB_ERROR_INVALID_PARAMETERS;
      }
   }
   else
   {
      /* read existing header to verify database version */
      ret = readHeader(db, &hash_table_size, &key_size, &value_size);
      if( 0 != ret)
      {
         return ret;
      }
   }
   //store non shared db information
   db->htSize = hash_table_size;
   db->keySize = key_size;
   db->valSize = value_size;
   db->htSizeBytes = sizeof(Hashtable_s);

   if (db->alreadyOpen == Kdb_false) //check if this instance has already opened the db before
   {
      db->cacheName = kdbGetShmName("-cache", path);
      if(db->cacheName == NULL)
      {
         return KISSDB_ERROR_MALLOC;
      }
      //check if more than one hashtable is already in shared memory
      if(db->shared->htShmSize > db->htSizeBytes )
      {
         firstMappSize = db->shared->htShmSize;
      }
      else
      {
         firstMappSize = db->htSizeBytes;
      }

      //open / create shared memory for first hashtable
      db->htName = kdbGetShmName("-ht", path);
      if(db->htName == NULL)
      {
         return KISSDB_ERROR_MALLOC;
      }
      db->htFd = kdbShmemOpen(db->htName,  firstMappSize, &tmpCreator);
      if(db->htFd < 0)
      {
         return KISSDB_ERROR_OPEN_SHM;
      }
      db->hashTables = (Hashtable_s*) getKdbShmemPtr(db->htFd, firstMappSize);
      if(db->hashTables == ((void*) -1))
      {
         return KISSDB_ERROR_MAP_SHM;
      }
      db->htMappedSize = firstMappSize;
      db->alreadyOpen = Kdb_true;
   }

   /*
    *  Read hashtables from file into memory ONLY for first caller of KISSDB_open
    *  Determine number of existing hashtables (db->shared->htNum)    *
    */
   if (db->shmCreator == Kdb_true )
   {
      uint64_t offset = KISSDB_HEADER_SIZE;
      //only read hashtables from file if file is larger than header + hashtable size
      if(db->shared->mappedDbSize >= ( KISSDB_HEADER_SIZE + db->htSizeBytes) )
      {
         htptr = (Hashtable_s*) ( db->mappedDb + KISSDB_HEADER_SIZE);
         htFound = Kdb_true;
         while (htFound && offset < db->dbMappedSize )
         {
            //check for existing start OR end delimiter of hashtable
            if (htptr->delimStart == HASHTABLE_START_DELIMITER || htptr->delimEnd == HASHTABLE_END_DELIMITER)
            {
               //if new size would exceed old shared memory size-> allocate additional memory page to shared memory
               Kdb_bool result = Kdb_false;
               if ( (db->htSizeBytes * (db->shared->htNum + 1)) > db->htMappedSize)
               {
                  Kdb_bool temp;
                  if (db->htFd <= 0)
                  {
                     db->htFd = kdbShmemOpen(db->htName,  db->htMappedSize, &temp);
                     if(db->htFd < 0)
                     {
                        return KISSDB_ERROR_OPEN_SHM;
                     }
                  }
                  result = resizeKdbShmem(db->htFd, &db->hashTables, db->htMappedSize, db->htMappedSize + db->htSizeBytes);
                  if (result == Kdb_false)
                  {
                     return KISSDB_ERROR_RESIZE_SHM;
                  }
                  else
                  {
                     db->shared->htShmSize = db->htMappedSize + db->htSizeBytes;
                     db->htMappedSize = db->shared->htShmSize;
                  }
               }
               // copy the current hashtable read from file to (htadress + (htsize  * htcount)) in memory
               memcpy(((uint8_t*) db->hashTables) + (db->htSizeBytes * db->shared->htNum), htptr, db->htSizeBytes);
               ++db->shared->htNum;

               //read until all linked hashtables have been read
               if (htptr->slots[db->htSize].offsetA ) //if a offset to a further hashtable exists
               {
                  htptr = (Hashtable_s*) (db->mappedDb + htptr->slots[db->htSize].offsetA); //follow link to next hashtable
                  offset = htptr->slots[db->htSize].offsetA;
               }
               else //no link to next hashtable or link is invalid
               {
                  htFound = Kdb_false;
               }
            }
            else //delimiters of first hashtable or linked hashtable are invalid
            {
               DLT_LOG(persComLldbDLTCtx, DLT_LOG_ERROR, DLT_STRING(__FUNCTION__); DLT_STRING(": hashtable delimiters are invalid -> rebuild not possible!"));
               htFound = Kdb_false;
            }
         }
      }
      /*
       *  CHECK POWERLOSS FLAGS AND REBUILD DATABASE IF NECESSARY
       */
      if (db->shared->openMode != KISSDB_OPEN_MODE_RDONLY)
      {
         if (checkErrorFlags(db) != 0)
         {
            DLT_LOG(persComLldbDLTCtx, DLT_LOG_WARN, DLT_STRING(__FUNCTION__); DLT_STRING(": database was not closed correctly in last lifecycle!"));
            if (verifyHashtableCS(db) != 0)
            {
               DLT_LOG(persComLldbDLTCtx, DLT_LOG_WARN, DLT_STRING(__FUNCTION__); DLT_STRING(": A hashtable is invalid -> Start rebuild of hashtables!"));
               if (rebuildHashtables(db) != 0) //hashtables are corrupt, walk through the database and search for data blocks -> then rebuild the hashtables
               {
                  DLT_LOG(persComLldbDLTCtx, DLT_LOG_ERROR, DLT_STRING(__FUNCTION__); DLT_STRING(": hashtable rebuild failed!"));
               }
               else
               {
                  DLT_LOG(persComLldbDLTCtx, DLT_LOG_DEBUG, DLT_STRING(__FUNCTION__); DLT_STRING(": hashtable rebuild successful!"));
               }
               DLT_LOG(persComLldbDLTCtx, DLT_LOG_WARN, DLT_STRING(__FUNCTION__); DLT_STRING(":Start datablock check / recovery!"));
               recoverDataBlocks(db);
               DLT_LOG(persComLldbDLTCtx, DLT_LOG_WARN, DLT_STRING(__FUNCTION__); DLT_STRING(":End datablock check / recovery!"));
            }
            else
            {
               DLT_LOG(persComLldbDLTCtx, DLT_LOG_WARN, DLT_STRING(__FUNCTION__); DLT_STRING(":Start datablock check / recovery!"));
               recoverDataBlocks(db);
               DLT_LOG(persComLldbDLTCtx, DLT_LOG_WARN, DLT_STRING(__FUNCTION__); DLT_STRING(":End datablock check / recovery!"));
            }
         }
      }
   }
   Kdb_unlock(&db->shared->rwlock);
   return 0;
}


int KISSDB_close(KISSDB* db)
{
#ifdef PFS_TEST
   printf("  START: KISSDB_CLOSE \n");
#endif

   Hashtable_s* htptr = NULL;
   Header_s* ptr = 0;
   uint64_t  crc = 0;

   Kdb_wrlock(&db->shared->rwlock);

   //if no other instance has opened the database
   if( db->shared->refCount == 0)
   {
      if (db->shared->openMode != KISSDB_OPEN_MODE_RDONLY)
      {
         if(db->htMappedSize < db->shared->htShmSize)
         {
            if ( Kdb_false == remapSharedHashtable(db->htFd, &db->hashTables, db->htMappedSize, db->shared->htShmSize))
            {
               return KISSDB_ERROR_RESIZE_SHM;
            }
            else
            {
               db->htMappedSize = db->shared->htShmSize;
            }
         }
         //remap database file if in the meanwhile another process added new data (key value pairs / hashtables) to the file (only happens if writethrough is used)
         if (db->dbMappedSize < db->shared->mappedDbSize)
         {
            db->mappedDb = mremap(db->mappedDb, db->dbMappedSize, db->shared->mappedDbSize, MREMAP_MAYMOVE);
            if (db->mappedDb == MAP_FAILED)
            {
               DLT_LOG(persComLldbDLTCtx, DLT_LOG_WARN, DLT_STRING(__FUNCTION__); DLT_STRING(":mremap error: !"), DLT_STRING(strerror(errno)));
               return KISSDB_ERROR_IO;
            }
            else
            {
               db->dbMappedSize = db->shared->mappedDbSize;
            }
         }

         // generate checksum for every hashtable and write crc to file
         if (db->fd)
         {
            int i = 0;
            int offset = sizeof(Header_s); //offset in file to first hashtable
            if (db->shared->htNum > 0) //if hashtables exist
            {
               //write hashtables and crc to file
               for (i = 0; i < db->shared->htNum; i++)
               {
                  crc = 0;
                  crc = (uint64_t) pcoCrc32(crc, (unsigned char*) db->hashTables[i].slots, sizeof(db->hashTables[i].slots));
                  db->hashTables[i].crc = crc;
                  htptr = (Hashtable_s*) (db->mappedDb +  offset);
                  //copy hashtable and generated crc from shared memory to mapped hashtable in file
                  memcpy(htptr, &db->hashTables[i], db->htSizeBytes);
                  offset = db->hashTables[i].slots[db->htSize].offsetA;
               }
            }
         }
         //update header (close flags)
         ptr = (Header_s*) db->mappedDb;
         ptr->closeFailed = 0x00; //remove closeFailed flag
         ptr->closeOk = 0x01;     //set closeOk flag
         msync(db->mappedDb, KISSDB_HEADER_SIZE, MS_SYNC);
      }

      //unmap whole database file
      munmap(db->mappedDb, db->dbMappedSize);
      db->mappedDb = NULL;

      //unmap shared hashtables
      munmap(db->hashTables, db->htMappedSize);
      db->hashTables = NULL;
      //close shared memory for hashtables
      if( kdbShmemClose(db->htFd, db->htName) == Kdb_false)
      {
         close(db->fd);
         Kdb_unlock(&db->shared->rwlock);
         return KISSDB_ERROR_CLOSE_SHM;
      }
      db->htFd = 0;

      if(db->htName != NULL)
      {
         free(db->htName);
         db->htName = NULL;
      }

      //free rwlocks
      Kdb_unlock(&db->shared->rwlock);
      pthread_rwlock_destroy(&db->shared->rwlock);

      // unmap shared information
      munmap(db->shared, sizeof(Shared_Data_s));
      db->shared = NULL;

      if (kdbShmemClose(db->sharedFd, db->sharedName) == Kdb_false)
      {
         close(db->fd);
         return KISSDB_ERROR_CLOSE_SHM;
      }
      db->sharedFd =0;
      if(db->sharedName != NULL)
      {
         free(db->sharedName);
         db->sharedName = NULL;
      }
      if(db->cacheName != NULL)
      {
        free(db->cacheName); //free memory for name  obtained by kdbGetShmName() function
        db->cacheName = NULL;
      }
      if( db->fd)
      {
         close(db->fd);
         db->fd = 0;
      }

      db->alreadyOpen = Kdb_false;
      db->htSize = 0;
      //db->cacheReferenced = 0;
      db->keySize = 0;
      db->valSize = 0;
      db->htSizeBytes = 0;
      db->htMappedSize = 0;
      db->dbMappedSize = 0;
      db->shmCreator = 0;
      db->alreadyOpen = 0;

      //destroy named semaphore
      if (-1 == sem_post(db->kdbSem)) //release semaphore
      {
         DLT_LOG(persComLldbDLTCtx, DLT_LOG_ERROR,
                 DLT_STRING(__FUNCTION__); DLT_STRING(": sem_post() failed: "),
                 DLT_STRING(strerror(errno)));
      }
      if (-1 == sem_close(db->kdbSem))
      {
         DLT_LOG(persComLldbDLTCtx, DLT_LOG_ERROR,
                 DLT_STRING(__FUNCTION__); DLT_STRING(": sem_close() failed: "),
                 DLT_STRING(strerror(errno)));
      }
      if (-1 == sem_unlink(db->semName))
      {
         DLT_LOG(persComLldbDLTCtx, DLT_LOG_ERROR,
                 DLT_STRING(__FUNCTION__); DLT_STRING(": sem_unlink() failed: "),
                 DLT_STRING(strerror(errno)));
      }
      db->kdbSem = NULL;
      if(db->semName != NULL)
      {
         free(db->semName);
         db->semName = NULL;
      }

   }
   else
   {
      //if caller of close is not the last instance using the database
      //unmap whole database file
      munmap(db->mappedDb, db->dbMappedSize);
      db->mappedDb = NULL;

      //unmap shared hashtables
      munmap(db->hashTables, db->htMappedSize);
      db->hashTables = NULL;

      if( db->fd)
      {
         close(db->fd);
         db->fd = 0;
      }
      if(db->htFd)
      {
         close(db->htFd);
         db->htFd = 0;
      }

      db->alreadyOpen = Kdb_false;
      db->htSize = 0;
      //db->cacheReferenced = 0;
      db->keySize = 0;
      db->valSize = 0;
      db->htSizeBytes = 0;
      db->htMappedSize = 0;
      db->dbMappedSize = 0;
      db->shmCreator = 0;
      db->alreadyOpen = 0;

      Kdb_unlock(&db->shared->rwlock);

      // unmap shared information
      munmap(db->shared, sizeof(Shared_Data_s));
      db->shared = NULL;

      if(db->sharedFd)
      {
         close(db->sharedFd);
         db->sharedFd = 0;
      }
      if(db->htName != NULL)
      {
         free(db->htName);
         db->htName = NULL;
      }
      if(db->sharedName != NULL)
      {
         free(db->sharedName);
         db->sharedName = NULL;
      }
      if(db->cacheName != NULL)
      {
        free(db->cacheName); //free memory for name  obtained by kdbGetShmName() function
        db->cacheName = NULL;
      }
      //clean struct
      if (-1 == sem_post(db->kdbSem))
      {
         DLT_LOG(persComLldbDLTCtx, DLT_LOG_ERROR,
                 DLT_STRING(__FUNCTION__); DLT_STRING(": sem_post() in close failed: "),
                 DLT_STRING(strerror(errno)));
      }
      if (-1 == sem_close(db->kdbSem))
      {
         DLT_LOG(persComLldbDLTCtx, DLT_LOG_ERROR,
                 DLT_STRING(__FUNCTION__); DLT_STRING(": sem_close() in close failed: "),
                 DLT_STRING(strerror(errno)));
      }
      db->kdbSem = NULL;
      if(db->semName != NULL)
      {
         free(db->semName);
         db->semName = NULL;
      }
   }
#ifdef PFS_TEST
   printf("  END: KISSDB_CLOSE \n");
#endif
   return 0;
}


int KISSDB_get(KISSDB* db, const void* key, void* vbuf, uint32_t bufsize, uint32_t* vsize)
{
   const uint8_t* kptr;
   DataBlock_s* block;
   Hashtable_slot_s* hashTable;
   int64_t offset;
   Kdb_bool bCanContinue = Kdb_true;
   Kdb_bool bKeyFound = Kdb_false;
   uint64_t hash = 0;
   unsigned long klen, i;

   klen = strlen(key);
   hash = KISSDB_hash(key, klen) % (uint64_t) db->htSize;

   if(db->htMappedSize < db->shared->htShmSize)
   {
      if ( Kdb_false == remapSharedHashtable(db->htFd, &db->hashTables, db->htMappedSize, db->shared->htShmSize))
      {
         return KISSDB_ERROR_RESIZE_SHM;
      }
      else
      {
         db->htMappedSize = db->shared->htShmSize;
      }
   }

   hashTable = db->hashTables[0].slots; //pointer to first hashtable in memory at first slot

   if (db->dbMappedSize < db->shared->mappedDbSize)
   {
      db->mappedDb = mremap(db->mappedDb, db->dbMappedSize, db->shared->mappedDbSize, MREMAP_MAYMOVE);
      if (db->mappedDb == MAP_FAILED)
      {
         DLT_LOG(persComLldbDLTCtx, DLT_LOG_WARN, DLT_STRING(__FUNCTION__); DLT_STRING(":mremap error: !"), DLT_STRING(strerror(errno)));
         return KISSDB_ERROR_IO;
      }
      else
      {
         db->dbMappedSize = db->shared->mappedDbSize;
      }
   }


   for (i = 0; i < db->shared->htNum; ++i)
   {
      //get information about current valid offset to latest written data
      offset = (hashTable[hash].current == 0x00) ? hashTable[hash].offsetA : hashTable[hash].offsetB; // if 0x00 -> offsetA is latest else offsetB is latest
      if(offset < 0) //deleted or invalidated data but search in next hashtable
      {
         bCanContinue = Kdb_false; //deleted datablock -> do not compare the key
      }
      else
      {
         bCanContinue = Kdb_true; //possible match -> compare the key
      }

      if(Kdb_true == bCanContinue)
      {
         if( abs(offset) > db->dbMappedSize )
         {
            return KISSDB_ERROR_IO;
         }
         if (offset >= KISSDB_HEADER_SIZE) //if a valid offset is available in the slot
         {
            block = (DataBlock_s*) (db->mappedDb +  offset);
            kptr = (const uint8_t*) key;
            if (klen > 0)
            {
               if (memcmp(kptr, block->key, klen)
                     || strlen(block->key) != klen) //if search key does not match with key in file
               {
                  bKeyFound = Kdb_false;
               }
               else
               {
                  bKeyFound = Kdb_true;
               }
            }
            if(Kdb_true == bKeyFound)
            {
               //copy found value if buffer is big enough
               if(bufsize >= block->valSize)
               {
                  memcpy(vbuf, block->value, block->valSize);
               }
               *(vsize) = block->valSize;
               return 0; /* success */
            }
         }
         else
         {
            return 1; /* not found */
         }
      }
      hashTable = (Hashtable_slot_s*) ((char*) hashTable + sizeof(Hashtable_s));  //pointer to the next memory-hashtable
   }
   return 1; /* not found */
}


int KISSDB_delete(KISSDB* db, const void* key, int32_t* bytesDeleted)
{
   const uint8_t* kptr;
   DataBlock_s* backupBlock;
   DataBlock_s* block;
   Hashtable_slot_s* hashTable;
   int64_t backupOffset = 0;
   int64_t offset = 0;
   Kdb_bool bCanContinue = Kdb_true;
   Kdb_bool bKeyFound = Kdb_false;
   uint64_t hash = 0;
   uint64_t crc = 0x00;
   unsigned long klen, i;

   klen = strlen(key);
   hash = KISSDB_hash(key, klen) % (uint64_t) db->htSize;
   *(bytesDeleted) = PERS_COM_ERR_NOT_FOUND;

   if(db->htMappedSize < db->shared->htShmSize)
   {
      if ( Kdb_false == remapSharedHashtable(db->htFd, &db->hashTables, db->htMappedSize, db->shared->htShmSize))
      {
         return KISSDB_ERROR_RESIZE_SHM;
      }
      else
      {
         db->htMappedSize = db->shared->htShmSize;
      }
   }

   hashTable = db->hashTables->slots; //pointer to current hashtable in memory

   //remap database file if in the meanwhile another process added new data (key value pairs / hashtables) to the file
   if (db->dbMappedSize < db->shared->mappedDbSize)
   {
      db->mappedDb = mremap(db->mappedDb, db->dbMappedSize, db->shared->mappedDbSize, MREMAP_MAYMOVE);
      if (db->mappedDb == MAP_FAILED)
      {
         DLT_LOG(persComLldbDLTCtx, DLT_LOG_WARN, DLT_STRING(__FUNCTION__); DLT_STRING(":mremap error: !"), DLT_STRING(strerror(errno)));
         return KISSDB_ERROR_IO;
      }
      db->dbMappedSize = db->shared->mappedDbSize;
   }

   for (i = 0; i < db->shared->htNum; ++i)
   {
      //get information about current valid offset to latest written data
      if (hashTable[hash].current == 0x00) //valid is offsetA
      {
         offset = hashTable[hash].offsetA;
         backupOffset = hashTable[hash].offsetB;
      }
      else
      {
         offset = hashTable[hash].offsetB;
         backupOffset = hashTable[hash].offsetA;
      }
      if (offset < 0) //deleted or invalidated data but search in next hashtable
      {
         bCanContinue = Kdb_false;
      }
      else
      {
         bCanContinue = Kdb_true;
      }
      if (Kdb_true == bCanContinue)
      {
         if (offset >= KISSDB_HEADER_SIZE)
         {
            if( abs(offset) > db->dbMappedSize || abs(backupOffset) >  db->dbMappedSize)
            {
               return KISSDB_ERROR_IO;
            }

            block = (DataBlock_s*) (db->mappedDb +  offset);
            kptr = (const uint8_t*) key;  //pointer to search key
            if (klen > 0)
            {
               if (memcmp(kptr, block->key, klen) || strlen(block->key) != klen) //if search key does not match with key in file
               {
                  bKeyFound = Kdb_false;
               }
               else
               {
                  bKeyFound = Kdb_true;
               }
            }
            /* data to be deleted was found
             write "deleted block delimiters" for both blocks and delete key / value */
            if (Kdb_true == bKeyFound)
            {
               block->delimStart = (offset < backupOffset) ? DATA_BLOCK_A_DELETED_START_DELIMITER : DATA_BLOCK_B_DELETED_START_DELIMITER;
               //memset(block->key,   0, db->keySize); //do not delete key -> used in hashtable rebuild
               memset(block->value, 0, db->valSize);
               block->valSize = 0;
               crc = 0x00;
               crc = (uint32_t) pcoCrc32(crc, (unsigned char*)block->key, db->keySize + sizeof(uint32_t) + db->valSize + sizeof(uint64_t) );
               block->crc = crc;
               block->delimEnd = (offset < backupOffset) ? DATA_BLOCK_A_DELETED_END_DELIMITER : DATA_BLOCK_B_DELETED_END_DELIMITER;

               backupBlock = (DataBlock_s*) (db->mappedDb +  backupOffset);  //map data and backup block

               backupBlock->delimStart = (backupOffset < offset) ? DATA_BLOCK_A_DELETED_START_DELIMITER : DATA_BLOCK_B_DELETED_START_DELIMITER;
               //memset(backupBlock->key,   0, db->keySize);
               memset(backupBlock->value, 0, db->valSize);
               backupBlock->valSize = 0;
               crc = 0x00;
               crc = (uint32_t) pcoCrc32(crc, (unsigned char*)backupBlock->key, db->keySize + sizeof(uint32_t) + db->valSize + sizeof(uint64_t) );
               backupBlock->crc = crc;
               backupBlock->delimEnd = (backupOffset < offset) ? DATA_BLOCK_A_DELETED_END_DELIMITER : DATA_BLOCK_B_DELETED_END_DELIMITER;


               //negate offsetB, delete checksums and current flag in memory
               hashTable[hash].offsetA = -hashTable[hash].offsetA; //negate offset in hashtable that points to the data
               hashTable[hash].offsetB = -hashTable[hash].offsetB;
               hashTable[hash].current = 0x00;

               *(bytesDeleted) = block->valSize;
               return 0; /* success */
            }
         }
         else
         {
            return 1; /* not found */ //if no offset is found at hashed position in slots
         }
      }
      hashTable = (Hashtable_slot_s*) ((char*) hashTable + sizeof(Hashtable_s));  //pointer to the next memory-hashtable
   }
   return 1; /* not found */
}

// To improve write amplifiction: sort the keys at writeback for sequential write
//return offset where key would be written if Kissdb_put with same key is called
//int determineKeyOffset(KISSDB* db, const void* key)
//{
//   /*
//    * - hash the key,
//    * - go through hashtables and get corresponding offset to hash
//    * - if offset is negative return the inverse offset
//    * - if key matches at file offset return this offset
//    */
//   return 0;
//}




int KISSDB_put(KISSDB* db, const void* key, const void* value, int valueSize, int32_t* bytesWritten)
{
   const uint8_t* kptr;
   DataBlock_s* backupBlock;
   DataBlock_s* block;
   Hashtable_s* hashtable;
   Hashtable_s* htptr;
   Hashtable_slot_s* hashTable;
   int64_t offset, backupOffset, endoffset;
   Kdb_bool bKeyFound = Kdb_false;
   Kdb_bool result = Kdb_false;
   Kdb_bool temp = Kdb_false;
   uint64_t crc = 0x00;
   uint64_t hash = 0;
   unsigned long klen, i;

   klen = strlen(key);
   hash = KISSDB_hash(key, klen) % (uint64_t) db->htSize;
   *(bytesWritten) = 0;

   if(db->htMappedSize < db->shared->htShmSize)
   {
      if ( Kdb_false == remapSharedHashtable(db->htFd, &db->hashTables, db->htMappedSize, db->shared->htShmSize))
      {
         return KISSDB_ERROR_RESIZE_SHM;
      }
      else
      {
         db->htMappedSize = db->shared->htShmSize;
      }
   }

   hashTable = db->hashTables->slots; //pointer to current hashtable in memory

   //remap database file (only necessary here in writethrough mode) if in the meanwhile another process added new data (key value pairs / hashtables) to the file
   if (db->dbMappedSize < db->shared->mappedDbSize)
   {
      db->mappedDb = mremap(db->mappedDb, db->dbMappedSize, db->shared->mappedDbSize, MREMAP_MAYMOVE);
      if (db->mappedDb == MAP_FAILED)
      {
         DLT_LOG(persComLldbDLTCtx, DLT_LOG_WARN, DLT_STRING(__FUNCTION__); DLT_STRING(":mremap error: !"), DLT_STRING(strerror(errno)));
         return KISSDB_ERROR_IO;
      }
      db->dbMappedSize = db->shared->mappedDbSize;
   }


   for (i = 0; i < db->shared->htNum; ++i)
   {
      offset = hashTable[hash].offsetA;   //fileoffset to data in file
      if (offset >= KISSDB_HEADER_SIZE || offset < 0) //if a key with same hash is already in this slot or the same key must be overwritten
      {
         if( abs(offset) > db->dbMappedSize )
         {
            return KISSDB_ERROR_IO;
         }

         // if slot is marked as deleted, use this slot and negate the offset in order to reuse the existing data block
         if(offset < 0)
         {
            offset = -offset; //get original offset where data was deleted
            //printf("Overwriting slot for key: [%s] which was deleted before, offsetA: %d \n",key, offset);
            writeDualDataBlock(db, offset, i, key, klen, value, valueSize);
            hashTable[hash].offsetA = offset; //write the offset to the data in the memory-hashtable slot
            offset += sizeof(DataBlock_s);
            hashTable[hash].offsetB = offset; //write the offset to the second databloxk in the memory-hashtable slot
            hashTable[hash].current = 0x00;
            *(bytesWritten) = valueSize;

            return 0; /* success */
         }
         //overwrite existing if key matches
         offset = (hashTable[hash].current == 0x00) ? hashTable[hash].offsetA : hashTable[hash].offsetB; // if 0x00 -> offsetA is latest else offsetB is latest
         block = (DataBlock_s*) (db->mappedDb +  offset);
         kptr = (const uint8_t*) key;  //pointer to search key
         if (klen > 0)
         {
            if (memcmp(kptr, block->key, klen)
                  || strlen(block->key) != klen) //if search key does not match with key in file
            {
               //if key does not match -> search in next hashtable
               bKeyFound = Kdb_false;
            }
            else
            {
               bKeyFound = Kdb_true;
            }
         }
         if(Kdb_true == bKeyFound)
         {
            backupOffset = (hashTable[hash].current == 0x00) ? hashTable[hash].offsetB : hashTable[hash].offsetA; // if 0x00 -> offsetB is latest backup  else offsetA is latest

            //ALSO OVERWRITE LATEST VALID BLOCK to improve write amplification factor
            block->delimStart = (offset < backupOffset) ? DATA_BLOCK_A_START_DELIMITER : DATA_BLOCK_B_START_DELIMITER;
            block->valSize = valueSize;
            memcpy(block->value,value, block->valSize);
            block->htNum = i;
            crc = 0x00;
            crc = (uint32_t) pcoCrc32(crc, (unsigned char*)block->key, db->keySize + sizeof(uint32_t) + db->valSize + sizeof(uint64_t) );
            block->crc = crc;
            block->delimEnd = (offset < backupOffset) ? DATA_BLOCK_A_END_DELIMITER : DATA_BLOCK_B_END_DELIMITER;

            //if key matches -> seek to currently non valid data block for this key
            backupOffset = (hashTable[hash].current == 0x00) ? hashTable[hash].offsetB : hashTable[hash].offsetA; // if 0x00 -> offsetB is latest backup  else offsetA is latest
            backupBlock = (DataBlock_s*) (db->mappedDb +  backupOffset);
            //backupBlock->delimStart = DATA_BLOCK_START_DELIMITER;
            backupBlock->delimStart = (backupOffset < offset) ? DATA_BLOCK_A_START_DELIMITER : DATA_BLOCK_B_START_DELIMITER;
            backupBlock->valSize = valueSize;
            memcpy(backupBlock->value,value, backupBlock->valSize);
            backupBlock->htNum = i;
            crc = 0x00;
            crc = (uint32_t) pcoCrc32(crc, (unsigned char*)backupBlock->key, db->keySize + sizeof(uint32_t) + db->valSize + sizeof(uint64_t) );
            backupBlock->crc = crc;
            //backupBlock->delimEnd = DATA_BLOCK_END_DELIMITER;
            backupBlock->delimEnd = (backupOffset < offset) ? DATA_BLOCK_A_END_DELIMITER : DATA_BLOCK_B_END_DELIMITER;
            // check current flag and decide what parts of hashtable slot in file must be updated
            hashTable[hash].current = (hashTable[hash].current == 0x00) ? 0x01 : 0x00; // if 0x00 -> offsetA is latest -> set to 0x01 else /offsetB is latest -> modify settings of A set 0x00
            *(bytesWritten) = valueSize;

            return 0; //success
         }
      }
      else //if key is not already inserted
      {
         /* add new data if an empty hash table slot is discovered */
         endoffset = db->shared->mappedDbSize;
         if ( -1 == endoffset) //filepointer to the end of the file
         {
            return KISSDB_ERROR_IO;
         }

         //truncate file -> data + backup block
         if( ftruncate(db->fd, endoffset + ( sizeof(DataBlock_s) * 2) ) < 0)
         {
            return KISSDB_ERROR_IO;
         }

         db->mappedDb = mremap(db->mappedDb, db->dbMappedSize, db->shared->mappedDbSize + (sizeof(DataBlock_s) * 2), MREMAP_MAYMOVE);
         if (db->mappedDb == MAP_FAILED)
         {
            DLT_LOG(persComLldbDLTCtx, DLT_LOG_WARN, DLT_STRING(__FUNCTION__); DLT_STRING(":mremap error: !"),DLT_STRING(strerror(errno)));
            return KISSDB_ERROR_IO;
         }

         db->shared->mappedDbSize = db->shared->mappedDbSize + (sizeof(DataBlock_s) * 2); //shared info about database file size
         db->dbMappedSize = db->shared->mappedDbSize; //local info about mapped size of file

         writeDualDataBlock(db, endoffset, i, key, klen, value, valueSize);

         //update hashtable entry
         offset = endoffset + sizeof(DataBlock_s);
         hashTable[hash].offsetA = endoffset; //write the offsetA to the data in the memory-hashtable slot
         hashTable[hash].offsetB = offset;    //write the offset to the data in the memory-hashtable slot
         hashTable[hash].current = 0x00;

         *(bytesWritten) = valueSize;
         return 0; /* success */
      }
      hashTable = (Hashtable_slot_s*) ((char*) hashTable + sizeof(Hashtable_s));  //pointer to the next memory-hashtable
   }

   //if new size would exceed old shared memory size for hashtables-> allocate additional memory to shared memory (+ db->htSizeBytes)
   if( (db->htSizeBytes * (db->shared->htNum + 1)) > db->shared->htShmSize)
   {
      //munlockall();
      if (db->htFd <= 0)
      {
         db->htFd = kdbShmemOpen(db->htName,  db->htMappedSize, &temp);
         if(db->htFd < 0)
         {
            return KISSDB_ERROR_OPEN_SHM;
         }
      }
      result = resizeKdbShmem(db->htFd, &db->hashTables, db->htMappedSize, db->htMappedSize + db->htSizeBytes);
      if (result == Kdb_false)
      {
         return KISSDB_ERROR_RESIZE_SHM;
      }
      else
      {
         db->shared->htShmSize = db->htMappedSize + db->htSizeBytes;
         db->htMappedSize = db->shared->htShmSize;
      }
      //mlockall(MCL_FUTURE);
   }

   /* if no existing slots, add a new page of hash table entries */
   endoffset = db->shared->mappedDbSize;
   if ( -1 == endoffset) //filepointer to the end of the file
   {
      return KISSDB_ERROR_IO;
   }
   //truncate file in order to save new hashtable + two Datablocks (this does not modify filedescriptor)
   if (ftruncate(db->fd, endoffset + db->htSizeBytes + (sizeof(DataBlock_s) * 2)) < 0)
   {
      return KISSDB_ERROR_IO;
   }

   db->mappedDb = mremap(db->mappedDb, db->dbMappedSize, db->shared->mappedDbSize + (db->htSizeBytes + (sizeof(DataBlock_s) * 2)), MREMAP_MAYMOVE);
   if (db->mappedDb == MAP_FAILED)
   {
      DLT_LOG(persComLldbDLTCtx, DLT_LOG_WARN, DLT_STRING(__FUNCTION__); DLT_STRING(":mremap error: !"),DLT_STRING(strerror(errno)));
      return KISSDB_ERROR_IO;
   }
   db->shared->mappedDbSize = db->shared->mappedDbSize + (db->htSizeBytes + (sizeof(DataBlock_s) * 2));
   db->dbMappedSize = db->shared->mappedDbSize;

   //prepare new hashtable in shared memory
   hashtable = &(db->hashTables[db->shared->htNum]);
   memset(hashtable, 0, db->htSizeBytes); //hashtable init
   hashtable->delimStart = HASHTABLE_START_DELIMITER;
   hashtable->delimEnd = HASHTABLE_END_DELIMITER;
   hashtable->crc = 0x00;
   hashTable = hashtable->slots; //pointer to the next memory-hashtable
   hashTable[hash].offsetA = endoffset + db->htSizeBytes; /* where new entry will go (behind the new Ht that gets written)*/
   hashTable[hash].offsetB = hashTable[hash].offsetA + sizeof(DataBlock_s);//write the offset to the data in the memory-hashtable slot
   hashTable[hash].current = 0x00;

   htptr = (Hashtable_s*) (db->mappedDb + endoffset);
   //copy hashtable in shared memory to mapped hashtable in file
   memcpy(htptr, hashtable, db->htSizeBytes);
   //write data behind new hashtable
   writeDualDataBlock(db, endoffset + db->htSizeBytes, db->shared->htNum, key, klen, value, valueSize);
   //if a hashtable exists, update link to new hashtable in previous hashtable
   if (db->shared->htNum)
   {
      db->hashTables[db->shared->htNum -1].slots[HASHTABLE_SLOT_COUNT].offsetA = endoffset; //update link to new hashtable in previous hashtable
   }
   ++db->shared->htNum;

   *(bytesWritten) = valueSize;

   return 0; /* success */
}



#if 0
/*
 * prints the offsets stored in the shared Hashtable
 */
void printSharedHashtable(KISSDB* db)
{
   unsigned long k=0;
   int i = 0;

   for(i =0 ; i< db->shared->htNum; i++)
   {
      for (k = 0; k <= db->htSize; k++)
      {
         printf("ht[%d] offsetA  [%lu]: %" PRId64 " \n",i, k, db->hashTables[i].slots[k].offsetA);
         printf("ht[%d] offsetB  [%lu]: %" PRId64 " \n",i, k, db->hashTables[i].slots[k].offsetB);
         printf("ht[%d] current  [%lu]: %" PRIu64 " \n",i, k, db->hashTables[i].slots[k].current);
      }
   }
}
#endif


void KISSDB_Iterator_init(KISSDB* db, KISSDB_Iterator* dbi)
{
   dbi->db = db;
   dbi->h_no = 0;  // number of read hashtables
   dbi->h_idx = 0; // index in current hashtable
}


int KISSDB_Iterator_next(KISSDB_Iterator* dbi, void* kbuf, void* vbuf)
{
   DataBlock_s* block;
   Hashtable_slot_s* ht;
   int64_t offset;

   if(dbi->db->htMappedSize < dbi->db->shared->htShmSize)
   {
      if ( Kdb_false == remapSharedHashtable(dbi->db->htFd, &dbi->db->hashTables, dbi->db->htMappedSize, dbi->db->shared->htShmSize))
      {
         return KISSDB_ERROR_RESIZE_SHM;
      }
      else
      {
         dbi->db->htMappedSize = dbi->db->shared->htShmSize;
      }
   }

   //remap database file if in the meanwhile another process added new data (key value pairs / hashtables) to the file
   if (dbi->db->dbMappedSize < dbi->db->shared->mappedDbSize)
   {
      dbi->db->mappedDb = mremap(dbi->db->mappedDb, dbi->db->dbMappedSize, dbi->db->shared->mappedDbSize, MREMAP_MAYMOVE);
      if (dbi->db->mappedDb == MAP_FAILED)
      {
         DLT_LOG(persComLldbDLTCtx, DLT_LOG_WARN, DLT_STRING(__FUNCTION__); DLT_STRING(":mremap error: !"), DLT_STRING(strerror(errno)));
         return KISSDB_ERROR_IO;
      }
      dbi->db->dbMappedSize = dbi->db->shared->mappedDbSize;
   }

   if ((dbi->h_no < (dbi->db->shared->htNum)) && (dbi->h_idx < dbi->db->htSize))
   {
      ht = dbi->db->hashTables[dbi->h_no].slots; //pointer to first hashtable

      while ( !(ht[dbi->h_idx].offsetA || ht[dbi->h_idx].offsetB) ) //until a offset was found
      {
         if (++dbi->h_idx >= dbi->db->htSize)
         {
            dbi->h_idx = 0;
            if (++dbi->h_no >= (dbi->db->shared->htNum))
            {
               return 0;
            }
            else
            {
               ht = dbi->db->hashTables[dbi->h_no].slots;   //next hashtable
            }
         }
      }
      if(ht[dbi->h_idx].current == 0x00)
      {
         offset = ht[dbi->h_idx].offsetA;
      }
      else
      {
         offset = ht[dbi->h_idx].offsetB;
      }

      if( abs(offset) > dbi->db->dbMappedSize )
      {
         return KISSDB_ERROR_IO;
      }

      block = (DataBlock_s*) (dbi->db->mappedDb + offset);
      memcpy(kbuf,block->key, dbi->db->keySize);
      if (vbuf != NULL)
      {
         memcpy(vbuf, block->value, dbi->db->valSize);
      }
      if (++dbi->h_idx >= dbi->db->htSize)
      {
         dbi->h_idx = 0;
         ++dbi->h_no;
      }
      return 1;
   }
   return 0;
}




int readHeader(KISSDB* db, uint16_t* htSize, uint64_t* keySize, uint64_t* valSize)
{
   Header_s* ptr = 0;
   ptr = (Header_s*) db->mappedDb;

   if ((ptr->KdbV[0] != 'K') || (ptr->KdbV[1] != 'd') || (ptr->KdbV[2] != 'B') )
   {
      return KISSDB_ERROR_CORRUPT_DBFILE;
   }
   if( (ptr->KdbV[3] != KISSDB_MAJOR_VERSION) || (ptr->KdbV[4] != '.') || (ptr->KdbV[5] != KISSDB_MINOR_VERSION))
   {
      return KISSDB_ERROR_WRONG_DATABASE_VERSION;
   }
   if (!ptr->htSize)
   {
      return KISSDB_ERROR_CORRUPT_DBFILE;
   }
   (*htSize) = (uint16_t) ptr->htSize;
   if (!ptr->keySize)
   {
      return KISSDB_ERROR_CORRUPT_DBFILE;
   }
   (*keySize) = (uint64_t) ptr->keySize;

   if (!ptr->valSize)
   {
      return KISSDB_ERROR_CORRUPT_DBFILE;
   }
   (*valSize) = (uint64_t) ptr->valSize;
   return 0;
}




int writeHeader(KISSDB* db, uint16_t* htSize, uint64_t* keySize, uint64_t* valSize)
{
   Header_s* ptr = 0;
   int ret= 0;

   //truncate file to needed size for header
   ret = ftruncate(db->fd, KISSDB_HEADER_SIZE);
   if (ret < 0)
   {
      return KISSDB_ERROR_IO;
   }
   //mmap whole file for the first time
   db->mappedDb = (void*) mmap(NULL, KISSDB_HEADER_SIZE, PROT_WRITE | PROT_READ, MAP_SHARED, db->fd, 0);
   if (db->mappedDb == MAP_FAILED)
   {
      return KISSDB_ERROR_IO;
   }
   db->shared->mappedDbSize = KISSDB_HEADER_SIZE;
   db->dbMappedSize = KISSDB_HEADER_SIZE;

   ptr = (Header_s*) db->mappedDb;
   ptr->KdbV[0] = 'K';
   ptr->KdbV[1] = 'd';
   ptr->KdbV[2] = 'B';
   ptr->KdbV[3] = KISSDB_MAJOR_VERSION;
   ptr->KdbV[4] = '.';
   ptr->KdbV[5] = KISSDB_MINOR_VERSION;
   ptr->KdbV[6] = '0';
   ptr->KdbV[7] = '0';
   ptr->checksum = 0x00;
   ptr->closeFailed = 0x00; //remove closeFailed flag
   ptr->closeOk = 0x01;     //set closeOk flag
   ptr->htSize = (uint64_t)(*htSize);
   ptr->keySize = (uint64_t)(*keySize);
   ptr->valSize = (uint64_t)(*valSize);
   msync(db->mappedDb, KISSDB_HEADER_SIZE, MS_SYNC);

   return 0;
}


int checkErrorFlags(KISSDB* db)
{
   Header_s* ptr;
   ptr = (Header_s*) db->mappedDb;

   //check if closeFailed flag is set or closeOk is not set
   if(ptr->closeFailed == 0x01 || ptr->closeOk == 0x00 )
   {
#ifdef PFS_TEST
      printf("CHECK ERROR FLAGS: CLOSE FAILED!\n");
#endif
      ptr->closeFailed = 0x01; //create close failed flags
      ptr->closeOk = 0x00;
      return KISSDB_ERROR_CORRUPT_DBFILE;
   }
   else
   {
#ifdef PFS_TEST
      printf("CHECK ERROR FLAGS: CLOSE OK!\n");
#endif
      ptr->closeFailed = 0x01; //NO: create close failed flag
      ptr->closeOk = 0x00;
   }
   msync(db->mappedDb, KISSDB_HEADER_SIZE, MS_SYNC);

   return 0;
}


int verifyHashtableCS(KISSDB* db)
{
   char* ptr;
   Hashtable_s* hashtable;
   int i = 0;
   int ptrOffset=1;
   int64_t offset = 0;
   struct stat statBuf;
   uint64_t crc = 0;
   void* memory;

   if (db->fd)
   {
      //map entire file into memory
      fstat(db->fd, &statBuf);
      memory = (void*) mmap(NULL, statBuf.st_size, PROT_WRITE | PROT_READ, MAP_SHARED, db->fd, 0);
      if (memory == MAP_FAILED)
      {
         return KISSDB_ERROR_IO;
      }
      ptr = (char*) memory;
      db->shared->htNum = 0;
      //unmap previously allocated and maybe corrupted hashtables
      munmap(db->hashTables, db->htMappedSize);
      db->hashTables = (Hashtable_s*) getKdbShmemPtr(db->htFd, db->htSizeBytes);
      if(db->hashTables == ((void*) -1))
      {
         return KISSDB_ERROR_MAP_SHM;
      }
      db->htMappedSize = db->htSizeBytes; //size for first hashtable

      //determine greatest common factor of hashtable and datablock used for pointer incrementation
      ptrOffset = greatestCommonFactor(sizeof(DataBlock_s), sizeof(Hashtable_s) );

      //offsets in mapped area to first hashtable
      offset = sizeof(Header_s);
      ptr += offset;

      //get number of hashtables in file (search for hashtable delimiters) and copy the hashtables to memory
      while (offset <= (statBuf.st_size - db->htSizeBytes)) //begin with offset for first hashtable
      {
         hashtable = (Hashtable_s*) ptr;
         //if at least one of two hashtable delimiters are found
         if (hashtable->delimStart == HASHTABLE_START_DELIMITER
               || hashtable->delimEnd == HASHTABLE_END_DELIMITER)
         {
               //next hashtable to use
               //rewrite delimiters to make sure that both exist
               hashtable->delimStart = HASHTABLE_START_DELIMITER;
               hashtable->delimEnd   = HASHTABLE_END_DELIMITER;
               Kdb_bool result = Kdb_false;
               //if new size would exceed old shared memory size-> allocate additional memory page to shared memory
               if (db->htSizeBytes * (db->shared->htNum + 1) > db->htMappedSize)
               {
                  result = resizeKdbShmem(db->htFd, &db->hashTables, db->htMappedSize, db->htMappedSize + db->htSizeBytes);
                  if (result == Kdb_false)
                  {
                     return KISSDB_ERROR_RESIZE_SHM;
                  }
                  else
                  {
                     db->shared->htShmSize = db->htMappedSize + db->htSizeBytes;
                     db->htMappedSize = db->shared->htShmSize;
                  }
               }
               // copy the current hashtable read from file to (htadress + (htsize  * htcount)) in memory
               memcpy(((uint8_t*) db->hashTables) + (db->htSizeBytes * db->shared->htNum), ptr, db->htSizeBytes);
               ++db->shared->htNum;

               //jump to next data block after hashtable
               offset += sizeof(Hashtable_s);
               ptr += sizeof(Hashtable_s);
         }
         else
         {
            offset += ptrOffset;
            ptr += ptrOffset;
         }
      }
      munmap(memory, statBuf.st_size);

      //check CRC of all found hashtables
      if (db->shared->htNum > 0)
      {
         for (i = 0; i < db->shared->htNum; i++)
         {
            crc = 0;
            crc = (uint64_t) pcoCrc32(crc, (unsigned char*) db->hashTables[i].slots, sizeof(db->hashTables[i].slots));
            if (db->hashTables[i].crc != crc)
            {
               DLT_LOG(persComLldbDLTCtx, DLT_LOG_WARN, DLT_STRING(__FUNCTION__); DLT_STRING(": Checksum of hashtable number: <"); DLT_INT(i); DLT_STRING("> is invalid"));
#ifdef PFS_TEST
               printf("VERIFY HASHTABLE: hashtable #%d: CHECKSUM INVALID! \n",i);
#endif
               return -1; //start rebuild of hashtables
            }
            else
            {
               DLT_LOG(persComLldbDLTCtx, DLT_LOG_DEBUG, DLT_STRING(__FUNCTION__); DLT_STRING(": Checksum of hashtable number: <"); DLT_INT(i); DLT_STRING("> is OK"));

#ifdef PFS_TEST
               printf("VERIFY HASHTABLE: hashtable #%d: CHECKSUM OK! \n",i);
#endif
            }
         }
      }
   }
   return 0;
}

int rebuildHashtables(KISSDB* db)
{
   char* ptr;
   DataBlock_s* data;
   DataBlock_s* dataA;
   DataBlock_s* dataB;
   Hashtable_s* hashtable;
   int current = 0;
   int ptrOffset = 1;
   int64_t offset=0;
   int64_t offsetA = 0;
   struct stat statBuf;
   uint64_t crc = 0;
   uint64_t calcCrcA, calcCrcB, readCrcA, readCrcB;
   void* memory;

   fstat(db->fd, &statBuf);
   memory = (char*) mmap(NULL, statBuf.st_size, PROT_WRITE | PROT_READ, MAP_SHARED, db->fd, 0);
   if (memory == MAP_FAILED)
   {
      return KISSDB_ERROR_IO;
   }
   ptr = (char*) memory;

   //recover all hashtables of database
   if (db->shared->htNum > 0) //htNum was determined in verifyhashtables() -> no reallocation is needed
   {
      ptr = (void*) memory;
      memset(db->hashTables, 0, db->shared->htNum * sizeof(Hashtable_s));
      db->hashTables[0].delimStart = HASHTABLE_START_DELIMITER;
      db->hashTables[0].delimEnd = HASHTABLE_END_DELIMITER;

      ptrOffset = greatestCommonFactor(sizeof(DataBlock_s), sizeof(Hashtable_s) );

      //begin searching after first hashtable
      offset = sizeof(Header_s) + sizeof(Hashtable_s);
      ptr += offset;

      //go through  database file until offset + Datablock size reaches end of file mapping
      while (offset <= (statBuf.st_size - sizeof(DataBlock_s)))
      {
         data = (DataBlock_s*) ptr;

         //if block A start or end delimiters were found
         if (data->delimStart == DATA_BLOCK_A_START_DELIMITER
               || data->delimEnd == DATA_BLOCK_A_END_DELIMITER)
         {
            //calculate checksum of Block A
            calcCrcA = 0;
            calcCrcA = (uint64_t) pcoCrc32(calcCrcA, (unsigned char*) data->key, db->keySize + sizeof(uint32_t) + db->valSize + sizeof(uint64_t));
            readCrcA = data->crc;

            //search for block B start delimiter
            offset += sizeof(DataBlock_s);
            ptr += sizeof(DataBlock_s);
            dataB = (DataBlock_s*) ptr;
            if (dataB->delimStart == DATA_BLOCK_B_START_DELIMITER
                  || dataB->delimEnd == DATA_BLOCK_B_END_DELIMITER)
            {
               //verify checksum of Block B
               calcCrcB = 0;
               calcCrcB = (uint64_t) pcoCrc32(calcCrcB, (unsigned char*) dataB->key, db->keySize + sizeof(uint32_t) + db->valSize + sizeof(uint64_t));
               readCrcB = dataB->crc;
               if (readCrcB == calcCrcB) //checksum of block B matches
               {
                  if (readCrcA == calcCrcA) //checksum of block A matches
                  {
                     if (1) //decide which datablock has latest written data - still statically using Block B for recovery because both blocks are written in kissdb_put
                     {
                        offsetA = offset - sizeof(DataBlock_s);
                        rebuildWithBlockB(dataB, db, offsetA, offset);
                     }
                     else
                     {
                        // use block A for rebuild
                        //write offsets for block a and block B
                        offsetA = offset - sizeof(DataBlock_s);
                        rebuildWithBlockA(data, db, offsetA, offset);
                     }
                  }
                  else //checksum of block A does not match, but checksum of block B was valid
                  {
                     // use block B for rebuild
                     offsetA = offset - sizeof(DataBlock_s);
                     rebuildWithBlockB(dataB, db, offsetA, offset);
                  }
               }
               else
               {
                  if (readCrcA == calcCrcA)
                  {
                     // use block A for rebuild
                     //write offsets for block a and block B
                     offsetA = offset - sizeof(DataBlock_s);
                     rebuildWithBlockA(data, db, offsetA, offset);
                  }
                  else //checksum of block A and of Block B do not match ---> worst case scenario
                  {
                     invalidateBlocks(data, dataB, db);
                  }
               }
            }
            else
            {
               //if checksum A matches and block B was not found
               if (readCrcA == calcCrcA)
               {
                  // use block A for rebuild
                  //write offsets for block a and block B
                  offsetA = offset - sizeof(DataBlock_s);
                  rebuildWithBlockA(data, db, offsetA, offset);
               }
               else //checksum of block A does not match and block B was not found
               {
                  invalidateBlocks(data, dataB, db);
               }
            }
            //jump behind datablock B
            offset += sizeof(DataBlock_s);
            ptr += sizeof(DataBlock_s);
         }
         //If a Bock B start or end delimiters were found: this only can happen if previous Block A was not found
         else if (data->delimStart == DATA_BLOCK_B_START_DELIMITER
                    || data->delimEnd == DATA_BLOCK_B_END_DELIMITER)
         {
            dataA = (DataBlock_s*) (ptr - sizeof(DataBlock_s)) ;
            //verify checksum of Block B
            crc = 0;
            crc = (uint64_t) pcoCrc32(crc, (unsigned char*) data->key, db->keySize + sizeof(uint32_t) + db->valSize + sizeof(uint64_t));
            if (data->crc == crc)
            {
               //use block B for rebuild
               //write offsets for block A and block B
               offsetA = offset - sizeof(DataBlock_s);
               rebuildWithBlockB(data, db, offsetA, offset);
            }
            else
            {
               invalidateBlocks(dataA, data, db);
            }
            //jump behind datablock B
            offset += sizeof(DataBlock_s);
            ptr += sizeof(DataBlock_s);
         }
         else if (data->delimStart == DATA_BLOCK_A_DELETED_START_DELIMITER
                    || data->delimEnd == DATA_BLOCK_A_DELETED_END_DELIMITER)
         {
            //calculate checksum of Block A
            calcCrcA = 0;
            calcCrcA = (uint64_t) pcoCrc32(calcCrcA, (unsigned char*) data->key, db->keySize + sizeof(uint32_t) + db->valSize + sizeof(uint64_t));
            readCrcA = data->crc;

            //search for block B start delimiter
            offset += sizeof(DataBlock_s);
            ptr += sizeof(DataBlock_s);
            dataB = (DataBlock_s*) ptr;

            if (dataB->delimStart == DATA_BLOCK_B_DELETED_START_DELIMITER
                  || dataB->delimEnd == DATA_BLOCK_B_DELETED_END_DELIMITER)
            {
               //calculate checksum of Block B
               calcCrcB = 0;
               calcCrcB = (uint64_t) pcoCrc32(calcCrcB, (unsigned char*) dataB->key, db->keySize + sizeof(uint32_t) + db->valSize + sizeof(uint64_t));
               readCrcB = dataB->crc;
               if (readCrcB == calcCrcB) //checksum of block B matches
               {
                  offsetA = offset - sizeof(DataBlock_s);
                  invertBlockOffsets(data, db, offsetA, offset);
               }
               else
               {
                  if (readCrcA == calcCrcA)
                  {
                     offsetA = offset - sizeof(DataBlock_s);
                     invertBlockOffsets(data, db, offsetA, offset);
                  }
                  else
                  {
                     invalidateBlocks(data, dataB, db);
                  }
               }
            }
            else //NO BLOCK B Found
            {
               if (readCrcA == calcCrcA)
               {

                  offsetA = offset - sizeof(DataBlock_s);
                  invertBlockOffsets(data, db, offsetA, offset);
               }
               else
               {
                  invalidateBlocks(data, dataB, db);
               }
            }
            //jump behind datablock B
            offset += sizeof(DataBlock_s);
            ptr += sizeof(DataBlock_s);
         }
         else if (data->delimStart == DATA_BLOCK_B_DELETED_START_DELIMITER
                    || data->delimEnd == DATA_BLOCK_B_DELETED_END_DELIMITER)
         {
            crc = 0;
            crc = (uint64_t) pcoCrc32(crc, (unsigned char*) data->key, db->keySize + sizeof(uint32_t) + db->valSize + sizeof(uint64_t));
            if (crc == data->crc)
            {
               offsetA = offset - sizeof(DataBlock_s);
               invertBlockOffsets(data, db, offsetA, offset);
            }
            else
            {
               dataA = (DataBlock_s*) (ptr - sizeof(DataBlock_s)) ;
               invalidateBlocks(dataA, data, db);
            }
            //jump behind datablock B
            offset += sizeof(DataBlock_s);
            ptr += sizeof(DataBlock_s);
         }
         else if( offset <= (statBuf.st_size - sizeof(Hashtable_s)) ) //check if ptr range for hashtable is within mapping of file
         {
            hashtable = (Hashtable_s*) ptr;

            if (hashtable->delimStart == HASHTABLE_START_DELIMITER
                  || hashtable->delimEnd == HASHTABLE_END_DELIMITER)
            {
               //next hashtable to use
               db->hashTables[current].slots[db->htSize].offsetA = offset; //update link to next hashtable in current hashtable
               current++;
               if (current < db->shared->htNum)
               {
                  db->hashTables[current].delimStart = HASHTABLE_START_DELIMITER;
                  db->hashTables[current].delimEnd   = HASHTABLE_END_DELIMITER;
               }
               else
               {
                  return -1;
               }
               offset += sizeof(Hashtable_s);
               ptr += sizeof(Hashtable_s);
            }
            else //if no hashtable is found
            {
               offset += ptrOffset;
               ptr += ptrOffset;
            }
         }
         else //if nothing is found for offsets in -> (filesize - hashtablesize)   area
         {
            DLT_LOG(persComLldbDLTCtx, DLT_LOG_WARN, DLT_STRING(__FUNCTION__); DLT_STRING(": No Datablock or hashtable area found!"));
            //increment pointer by greatest common factor of hashtable size and datablock size
            offset += ptrOffset;
            ptr += ptrOffset;
         }
      }
   }
   msync(memory, statBuf.st_size, MS_SYNC | MS_INVALIDATE);
   munmap(memory, statBuf.st_size);
   return 0;
}


//invalidate block content for A and B
//this block can never be found / overwritten again
//new insertions can reuse hashtable entry but block is added at EOF
void invalidateBlocks(DataBlock_s* dataA, DataBlock_s* dataB, KISSDB* db)
{
   DLT_LOG(persComLldbDLTCtx, DLT_LOG_ERROR, DLT_STRING(__FUNCTION__); DLT_STRING(": Datablock recovery for key: <"); DLT_STRING(dataA->key); DLT_STRING("> impossible: both datablocks are invalid!"));

   memset(dataA->key, 0, db->keySize);
   memset(dataA->value, 0, db->valSize);
   dataA->crc=0;
   dataA->htNum = 0;
   dataA->valSize = 0;

   memset(dataB->key, 0, db->keySize);
   memset(dataB->value, 0, db->valSize);
   dataB->crc=0;
   dataB->htNum = 0;
   dataB->valSize = 0;
}


void invertBlockOffsets(DataBlock_s* data, KISSDB* db, int64_t offsetA, int64_t offsetB)
{
   uint64_t hash = 0;
   hash = KISSDB_hash(data->key, strlen(data->key)) % (uint64_t) db->htSize;
   //invert offsets for deleted block A
   db->hashTables[data->htNum].slots[hash].offsetA = - offsetA;
   //invert offsets for deleted block B
   db->hashTables[data->htNum].slots[hash].offsetB = - offsetB;
   //reset current flag
   db->hashTables[data->htNum].slots[hash].current = 0x00;
}


void rebuildWithBlockB(DataBlock_s* data, KISSDB* db, int64_t offsetA, int64_t offsetB)
{
   uint64_t hash = KISSDB_hash(data->key, strlen(data->key)) % (uint64_t) db->htSize;
   //write offsets for block A and block B
   db->hashTables[data->htNum].slots[hash].offsetA = offsetA;
   db->hashTables[data->htNum].slots[hash].offsetB = offsetB;
   //set block B as current
   db->hashTables[data->htNum].slots[hash].current = 0x01;

   /*
   DLT_LOG(persComLldbDLTCtx, DLT_LOG_DEBUG, DLT_STRING(__FUNCTION__); DLT_STRING(": Rebuild in hashtable No. <"); DLT_INT(data->htNum);
         DLT_STRING("> with Datablock B for key: <"); DLT_STRING(data->key); DLT_STRING("- hash: <"); DLT_INT(hash); DLT_STRING("> - OffsetA: <"); DLT_INT(offsetA);
         DLT_STRING("> - OffsetB: <"); DLT_INT(offsetB));
   */
}


void rebuildWithBlockA(DataBlock_s* data, KISSDB* db, int64_t offsetA, int64_t offsetB)
{
   uint64_t hash = KISSDB_hash(data->key, strlen(data->key)) % (uint64_t) db->htSize;
   //write offsets for block A and block B
   db->hashTables[data->htNum].slots[hash].offsetA = offsetA;
   db->hashTables[data->htNum].slots[hash].offsetB = offsetB;
   //set block B as current
   db->hashTables[data->htNum].slots[hash].current = 0x00;

   /*
   DLT_LOG(persComLldbDLTCtx, DLT_LOG_DEBUG, DLT_STRING(__FUNCTION__); DLT_STRING(": Rebuild in hashtable No. <"); DLT_INT(data->htNum);
         DLT_STRING("> with Datablock A for key: <"); DLT_STRING(data->key); DLT_STRING("- hash: <"); DLT_INT(hash); DLT_STRING("> - OffsetA: <"); DLT_INT(offsetA);
         DLT_STRING("> - OffsetB: <"); DLT_INT(offsetB));
   */
}




int recoverDataBlocks(KISSDB* db)
{

#ifdef PFS_TEST
                  printf("DATABLOCK RECOVERY: START! \n");
#endif

   char* ptr;
   DataBlock_s* data;
   int i = 0;
   int k = 0;
   int64_t offset = 0;
   struct stat statBuf;
   uint64_t crc = 0;
   void* memory;

   fstat(db->fd, &statBuf);
   memory = (char*) mmap(NULL, statBuf.st_size, PROT_WRITE | PROT_READ, MAP_SHARED, db->fd, 0);
   if (memory == MAP_FAILED)
   {
      return KISSDB_ERROR_IO;
   }
   ptr = (char*) memory;

   //go through all hashtables and jump to data blocks for crc validation
   if (db->shared->htNum > 0)
   {
      ptr = (void*) memory;
      for (i = 0; i < db->shared->htNum; i++)
      {
         for (k = 0; k < HASHTABLE_SLOT_COUNT; k++)
         {
            if (db->hashTables[i].slots[k].offsetA > 0) //ignore deleted or unused slots
            {
               ptr = (void*) memory;  //reset pointer
               //current valid data is offset A or offset B?
               offset = (db->hashTables[i].slots[k].current == 0x00) ? db->hashTables[i].slots[k].offsetA : db->hashTables[i].slots[k].offsetB;
               ptr += offset; //set pointer to current valid datablock
               data = (DataBlock_s*) ptr;
               //check crc of data block marked as current in hashtable
               crc = 0;
               crc = (uint64_t) pcoCrc32(crc, (unsigned char*) data->key, db->keySize + sizeof(uint32_t) + db->valSize + sizeof(uint64_t));
               if (data->crc != crc)
               {
                  DLT_LOG(persComLldbDLTCtx, DLT_LOG_WARN, DLT_STRING(__FUNCTION__); DLT_STRING(": Invalid datablock found at file offset: "); DLT_INT(offset));
#ifdef PFS_TEST
                  printf("DATABLOCK RECOVERY: INVALID CRC FOR CURRENT DATABLOCK DETECTED! \n");
#endif
                  ptr = (void*) memory;
                  //get offset to other data block and check crc
                  offset = (db->hashTables[i].slots[k].current == 0x00) ? db->hashTables[i].slots[k].offsetB : db->hashTables[i].slots[k].offsetA;
                  ptr += offset;
                  data = (DataBlock_s*) ptr;
                  crc = 0;
                  crc = (uint64_t) pcoCrc32(crc, (unsigned char*) data->key, db->keySize + sizeof(uint32_t) + db->valSize + sizeof(uint64_t));
                  if (data->crc == crc)
                  {
                     //switch current flag if valid backup is available
                     db->hashTables[i].slots[k].current = (db->hashTables[i].slots[k].current == 0x00) ? 0x01 : 0x00;
#ifdef PFS_TEST
                     printf("DATABLOCK RECOVERY: REPAIR OF INVALID DATA SUCCESSFUL! \n");
#endif
                     DLT_LOG(persComLldbDLTCtx, DLT_LOG_DEBUG, DLT_STRING(__FUNCTION__); DLT_STRING(": Invalid datablock for key: <"); DLT_STRING(data->key); DLT_STRING("> successfully recovered!"));
                  }
                  else
                  {
                     //invalidate data blocks if recovery fails
                     db->hashTables[i].slots[k].offsetA = - db->hashTables[i].slots[k].offsetA;
                     db->hashTables[i].slots[k].offsetB = - db->hashTables[i].slots[k].offsetB;
                     db->hashTables[i].slots[k].current = 0x00;
                     DLT_LOG(persComLldbDLTCtx, DLT_LOG_ERROR, DLT_STRING(__FUNCTION__); DLT_STRING(": Datablock recovery for key: <"); DLT_STRING(data->key); DLT_STRING("> impossible: both datablocks are invalid!"));
#ifdef PFS_TEST
                     printf("DATABLOCK RECOVERY: ERROR -> BOTH BLOCKS ARE INVALID! \n");
#endif
                  }
               }
            }
         }
      }
   }
   msync(memory, statBuf.st_size, MS_SYNC | MS_INVALIDATE);
   munmap(memory, statBuf.st_size);

#ifdef PFS_TEST
                  printf("DATABLOCK RECOVERY: END! \n");
#endif

   return 0;
}


int checkIsLink(const char* path, char* linkBuffer)
{
   char fileName[64] = { 0 };
   char truncPath[128] = { 0 };
   int isLink = 0;
   int len = 0;
   size_t strLen = 0;
   struct stat statBuf;
   uint16_t i = 0;

   memset(&statBuf, 0, sizeof(statBuf));
   strLen = strlen(path);
   for (i = 0; i < strLen; i++)
   {
      if (path[i] == '/')
      {
         len = i; // remember the position of the last '/'
      }
   }
   strncpy(truncPath, path, len);
   truncPath[len + 1] = '\0'; // set end of string
   strncpy(fileName, (const char*) path + len, 64);

   if (lstat(truncPath, &statBuf) != -1)
   {
      if (S_ISLNK(statBuf.st_mode))
      {
         if (readlink(truncPath, linkBuffer, 256) != -1)
         {
            strncat(linkBuffer, fileName, 256);
            isLink = 1;
         }
         else
         {
            DLT_LOG(persComLldbDLTCtx, DLT_LOG_DEBUG,
                    DLT_STRING(__FUNCTION__); DLT_STRING(": readlink failed: "); DLT_STRING(strerror(errno)));
            isLink = -1;
         }
      }
      else
      {
         isLink = -1;
      }
   }
   else
   {
      DLT_LOG(persComLldbDLTCtx, DLT_LOG_WARN,
              DLT_STRING(__FUNCTION__); DLT_STRING(": lstat failed: "); DLT_STRING(strerror(errno)));
      isLink = -1;
   }
   return isLink;
}



void cleanKdbStruct(KISSDB* db)
{
   if (db->shared != NULL)
   {
      //Clean for every instance
      if (db->mappedDb != NULL)
      {
         munmap(db->mappedDb, db->dbMappedSize);
         db->mappedDb = NULL;
      }
      if (db->hashTables != NULL)
      {
         munmap(db->hashTables, db->htMappedSize);
         db->hashTables = NULL;
      }
      if(db->cacheName != NULL)
      {
         free(db->cacheName);
         db->cacheName = NULL;
      }
      if (db->fd)
      {
         close(db->fd);
         db->fd = 0;
      }
      if(db->sharedCacheFd)
      {
         close(db->sharedCacheFd);
         db->sharedCacheFd = -1;
      }
      db->alreadyOpen = Kdb_false;
      db->htSize = 0;
      //db->cacheReferenced = 0;
      db->keySize = 0;
      db->valSize = 0;
      db->htSizeBytes = 0;
      db->htMappedSize = 0;
      db->dbMappedSize = 0;
      db->shmCreator = 0;

      Kdb_unlock(&db->shared->rwlock);

      //Clean up for last instance referencing the database
      if (db->shared->refCount == 0)
      {
         //close shared hashtable memory
         if (db->htFd)
         {
            kdbShmemClose(db->htFd, db->htName);
            db->htFd = 0;
         }
         if(db->htName != NULL)
         {
            free(db->htName);
            db->htName = NULL;
         }
         //free rwlocks
         pthread_rwlock_destroy(&db->shared->rwlock);
         if (db->shared != NULL)
         {
            munmap(db->shared, sizeof(Shared_Data_s));
            db->shared = NULL;
         }
         if (db->sharedFd)
         {
            kdbShmemClose(db->sharedFd, db->sharedName);
            db->sharedFd = 0;
         }
         if(db->sharedName != NULL)
         {
            free(db->sharedName);
            db->sharedName = NULL;
         }

         //destroy and unlock named semaphore only if ref counter is zero
         if (-1 == sem_post(db->kdbSem)) //release semaphore
         {
            DLT_LOG(persComLldbDLTCtx, DLT_LOG_ERROR, DLT_STRING(__FUNCTION__); DLT_STRING(": sem_post() in cleanup failed: "),
                  DLT_STRING(strerror(errno)));
         }
         if (-1 == sem_close(db->kdbSem))
         {
            DLT_LOG(persComLldbDLTCtx, DLT_LOG_ERROR, DLT_STRING(__FUNCTION__); DLT_STRING(": sem_close() in cleanup failed: "),
                  DLT_STRING(strerror(errno)));
         }
         if (-1 == sem_unlink(db->semName))
         {
            DLT_LOG(persComLldbDLTCtx, DLT_LOG_ERROR, DLT_STRING(__FUNCTION__); DLT_STRING(": sem_unlink() in cleanup failed: "),
                  DLT_STRING(strerror(errno)));
         }
         db->kdbSem = NULL;
      }
      else  //Clean up if other instances have reference to the database
      {
         if (db->sharedFd)
         {
            close(db->sharedFd);
            db->sharedFd = 0;
         }
         if (db->htFd)
         {
            close(db->htFd);
            db->htFd = 0;
         }
         if (db->shared != NULL)
         {
            munmap(db->shared, sizeof(Shared_Data_s));
            db->shared = NULL;
         }
         if(db->htName != NULL)
         {
            free(db->htName);
            db->htName = NULL;
         }
         if (-1 == sem_post(db->kdbSem))
         {
            DLT_LOG(persComLldbDLTCtx, DLT_LOG_ERROR, DLT_STRING(__FUNCTION__); DLT_STRING(": sem_post() in cleanup with refcounter > 0 failed: "),
                  DLT_STRING(strerror(errno)));
         }
         if (-1 == sem_close(db->kdbSem))
         {
            DLT_LOG(persComLldbDLTCtx, DLT_LOG_ERROR, DLT_STRING(__FUNCTION__); DLT_STRING(": sem_close() in cleanup with refcounter > 0 failed: "),
                    DLT_STRING(strerror(errno)));
         }
         db->kdbSem = NULL;
      }
   }
}


int writeDualDataBlock(KISSDB* db, int64_t offset, int htNumber, const void* key, unsigned long klen, const void* value, int valueSize)
{
   DataBlock_s* backupBlock;
   DataBlock_s* block;
   uint64_t crc = 0x00;

   block = (DataBlock_s*) (db->mappedDb + offset);
   block->delimStart = DATA_BLOCK_A_START_DELIMITER;
   memcpy(block->key,key, klen);
   block->valSize = valueSize;
   memcpy(block->value,value, block->valSize);
   block->htNum = htNumber;
   crc = 0x00;
   crc = (uint32_t) pcoCrc32(crc, (unsigned char*)block->key, db->keySize + sizeof(uint32_t) + db->valSize + sizeof(uint64_t)); //crc over key, datasize, data and htnum
   block->crc = crc;
   block->delimEnd = DATA_BLOCK_A_END_DELIMITER;

   // write same key and value again
   backupBlock = (DataBlock_s*) ((char*) block + sizeof(DataBlock_s));
   backupBlock->delimStart = DATA_BLOCK_B_START_DELIMITER;
   backupBlock->crc = crc;
   memcpy(backupBlock->key,key, klen);
   backupBlock->valSize = valueSize;
   memcpy(backupBlock->value,value, backupBlock->valSize);
   backupBlock->htNum = htNumber;
   backupBlock->delimEnd = DATA_BLOCK_B_END_DELIMITER;

   return 0;
}


int greatestCommonFactor(int x, int y)
{
   while (y != 0)
   {
      if (x > y)
      {
         x = x - y;
      }
      else
      {
         y = y - x;
      }
   }
   return x;
}