This repository has been archived by the owner on Oct 15, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 123
/
Copy pathmmapstorage.c
1564 lines (1392 loc) · 47.2 KB
/
mmapstorage.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @file
*
* @brief Source for mmapstorage plugin
*
* @copyright BSD License (see LICENSE.md or https://www.libelektra.org)
*
*/
#define _XOPEN_SOURCE 600
/* -- Imports --------------------------------------------------------------------------------------------------------------------------- */
#include "mmapstorage.h"
#include "dynarray.h"
#include "internal.h"
#include <kdbassert.h>
#include <kdberrors.h>
#include <kdbhelper.h>
#include <kdblogger.h>
#include <kdbprivate.h>
#ifdef HAVE_KDBCONFIG_H
#include "kdbconfig.h"
#endif
#include <errno.h>
#include <fcntl.h> // fcntl()
#include <limits.h> // SSIZE_MAX
#include <stdint.h> // uintN_t, uintptr_t
#include <stdio.h> // fopen(), fileno()
#include <stdlib.h> // strtol()
#include <string.h> // memcmp()
#include <sys/mman.h> // mmap()
#include <sys/stat.h> // stat(), fstat()
#include <sys/types.h> // ftruncate (), size_t
#include <unistd.h> // close(), ftruncate(), unlink(), read(), write()
#ifdef ELEKTRA_MMAP_CHECKSUM
#include <zlib.h> // crc32()
#endif
/* -- Global declarations---------------------------------------------------------------------------------------------------------------- */
#ifndef ELEKTRA_MMAP_MAGIC_NUMBER
#error ELEKTRA_MMAP_MAGIC_NUMBER should be defined by CMake
#endif
static const KeySet magicKeySet = (KeySet){
// FIXME: new magic data for COW
};
static const Key magicKey = (Key){
// FIXME: new magic data for COW
};
static const MmapMetaData magicMmapMetaData = (MmapMetaData){
.numKeySets = SIZE_MAX,
.ksAlloc = 0,
.numKeys = SIZE_MAX / 2,
};
#ifdef ELEKTRA_ENABLE_OPTIMIZATIONS
static const Opmphm magicOpmphm = (Opmphm){
.hashFunctionSeeds = (void *) ELEKTRA_MMAP_MAGIC_NUMBER,
.rUniPar = INT8_MAX,
.componentSize = SIZE_MAX / 2,
.graph = (void *) ~ELEKTRA_MMAP_MAGIC_NUMBER,
.size = SIZE_MAX,
};
static const OpmphmPredictor magicOpmphmPredictor = (OpmphmPredictor){
.history = UINT16_MAX,
.patternTable = (void *) ELEKTRA_MMAP_MAGIC_NUMBER,
.size = SIZE_MAX / 2,
.lookupCount = 0,
.ksSize = SIZE_MAX,
};
#endif
typedef enum
{
MODE_STORAGE = 1,
MODE_GLOBALCACHE = 1 << 1,
MODE_NONREGULAR_FILE = 1 << 2
} PluginMode;
/* -- File handling --------------------------------------------------------------------------------------------------------------------- */
/**
* @brief Wrapper for open().
*
* @param parentKey containing the filename
* @param flags file access mode
* @param openMode file mode bits when file is created
* @param mode the current plugin mode
*
* @return file descriptor
*/
static int openFile (Key * parentKey, int flag, mode_t openMode, PluginMode mode)
{
int fd;
ELEKTRA_LOG_DEBUG ("opening file %s", keyString (parentKey));
if ((fd = open (keyString (parentKey), flag, openMode)) == -1)
{
ELEKTRA_MMAP_LOG_WARNING ("error opening file %s", keyString (parentKey));
}
return fd;
}
/**
* @brief Wrapper for ftruncate().
*
* @param fd the file descriptor
* @param mmapsize size of the mapped region
* @param parentKey holding the filename, for debug purposes
* @param mode the current plugin mode
*
* @retval 1 on success
* @retval -1 if ftruncate() failed
*/
static int truncateFile (int fd, size_t mmapsize, Key * parentKey ELEKTRA_UNUSED, PluginMode mode)
{
ELEKTRA_LOG_DEBUG ("truncating file %s", keyString (parentKey));
if ((ftruncate (fd, mmapsize)) == -1)
{
ELEKTRA_MMAP_LOG_WARNING ("error truncating file %s", keyString (parentKey));
return -1;
}
return 1;
}
/**
* @brief Wrapper for fstat().
*
* @param fd the file descriptor
* @param sbuf the stat structure
* @param parentKey holding the filename
* @param mode the current plugin mode
*
* @retval 1 on success
* @retval -1 if fstat() failed
*/
static int fstatFile (int fd, struct stat * sbuf, Key * parentKey ELEKTRA_UNUSED, PluginMode mode)
{
ELEKTRA_LOG_DEBUG ("fstat() on file %s", keyString (parentKey));
memset (sbuf, 0, sizeof (struct stat));
if (fstat (fd, sbuf) == -1)
{
ELEKTRA_MMAP_LOG_WARNING ("error on fstat() for file %s", keyString (parentKey));
return -1;
}
return 1;
}
/**
* @brief Wrapper for mmap().
*
* @param addr address hint, where the mapping should start
* @param fd file descriptor of the file to be mapped
* @param mmapSize size of the mapped region
* @param mapOpts mmap flags (MAP_PRIVATE, MAP_FIXED, ...)
* @param parentKey holding the filename, for debug purposes
* @param mode the current plugin mode
*
* @return pointer to mapped region on success, MAP_FAILED on failure
*/
static char * mmapFile (void * addr, int fd, size_t mmapSize, int mapOpts, Key * parentKey ELEKTRA_UNUSED, PluginMode mode)
{
ELEKTRA_LOG_DEBUG ("mapping file %s", keyString (parentKey));
char * mappedRegion = MAP_FAILED;
if (test_bit (mode, MODE_NONREGULAR_FILE))
{
mappedRegion = elektraCalloc (mmapSize);
if (!mappedRegion)
{
ELEKTRA_MMAP_LOG_WARNING ("error allocating buffer for file %s\nmmapSize: %zu", keyString (parentKey), mmapSize);
return MAP_FAILED;
}
}
else
{
mappedRegion = mmap (addr, mmapSize, PROT_READ | PROT_WRITE, mapOpts, fd, 0);
if (mappedRegion == MAP_FAILED)
{
ELEKTRA_MMAP_LOG_WARNING ("error mapping file %s\nmmapSize: %zu", keyString (parentKey), mmapSize);
return MAP_FAILED;
}
}
return mappedRegion;
}
/**
* @brief Copy file
*
* @param sourceFd source file descriptor
* @param destFd destination file descriptor
*
* @retval 0 on success
* @retval -1 if any error occured
*/
static int copyFile (int sourceFd, int destFd)
{
ssize_t readBytes = 0;
char buf[ELEKTRA_MMAP_BUFSIZE];
while ((readBytes = read (sourceFd, buf, ELEKTRA_MMAP_BUFSIZE)) > 0)
{
if (readBytes <= 0)
{
if (errno == EINTR)
continue;
else
return -1;
}
ssize_t writtenBytes = 0;
while (readBytes > 0)
{
writtenBytes = write (destFd, buf, readBytes);
if (writtenBytes <= 0)
{
if (errno == EINTR)
continue;
else
return -1;
}
readBytes -= writtenBytes;
}
}
return 0;
}
/**
* @brief Copy file to anonymous temporary file
*
* This function is needed to make mmapstorage compatible
* with any file. The `mmap()` syscall only supports regular
* files.
*
* @param fd source file descriptor
* @param sbuf the stat structure
* @param parentKey holding the file name
* @param mode the current plugin mode
*
* @retval 0 on success
* @retval -1 if any error occured
*/
static int copyToAnonymousTempfile (int fd, struct stat * sbuf, Key * parentKey, PluginMode mode)
{
int tmpFd = 0;
char name[] = ELEKTRA_MMAP_TMP_NAME;
if ((tmpFd = mkstemp (name)) < 0)
{
return -1;
}
ELEKTRA_LOG_DEBUG ("using anon tmp file: %s", name);
keySetString (parentKey, name);
// use anonymous file
if (unlink (name) != 0)
{
ELEKTRA_MMAP_LOG_WARNING ("could not unlink");
return -1;
}
copyFile (fd, tmpFd);
if (close (fd) != 0)
{
ELEKTRA_MMAP_LOG_WARNING ("could not close");
return -1;
}
// replace old file
fd = tmpFd;
if (fstatFile (fd, sbuf, parentKey, mode) != 1)
{
return -1;
}
return fd;
}
/* -- Internal Functions --------------------------------------------------------------------------------------------------------------- */
/**
* @brief MmapHeader initializer.
*
* @param mmapHeader to initialize
*/
static void initHeader (MmapHeader * mmapHeader)
{
memset (mmapHeader, 0, SIZEOF_MMAPHEADER);
mmapHeader->mmapMagicNumber = ELEKTRA_MAGIC_MMAP_NUMBER;
mmapHeader->formatVersion = ELEKTRA_MMAP_FORMAT_VERSION;
#ifdef ELEKTRA_MMAP_CHECKSUM
set_bit (mmapHeader->formatFlags, MMAP_FLAG_CHECKSUM);
#endif
#ifdef ELEKTRA_ENABLE_OPTIMIZATIONS
set_bit (mmapHeader->formatFlags, MMAP_FLAG_OPMPHM);
#endif
}
/**
* @brief MmapMetaData initializer.
*
* @param mmapMetaData to initialize
*/
static void initMetaData (MmapMetaData * mmapMetaData)
{
memset (mmapMetaData, 0, SIZEOF_MMAPMETADATA);
}
/**
* @brief MmapFooter initializer.
*
* @param mmapFooter to initialize
*/
static void initFooter (MmapFooter * mmapFooter)
{
memset (mmapFooter, 0, SIZEOF_MMAPFOOTER);
mmapFooter->mmapMagicNumber = ELEKTRA_MAGIC_MMAP_NUMBER;
}
/**
* @brief Reads the MmapHeader and MmapMetaData from a file.
*
* @param fp file pointer to read the data from
* @param mmapHeader buffer where the MmapHeader is stored
* @param mmapMetaData buffer where the MmapMetaData is stored
*
* @retval -1 if magic number or format version was wrong
* @retval 0 if read succeeded, the magic number was read correctly and the format version matched
*/
static int readHeader (const char * mappedRegion, MmapHeader ** mmapHeader, MmapMetaData ** mmapMetaData)
{
*mmapHeader = (MmapHeader *) mappedRegion;
*mmapMetaData = (MmapMetaData *) (mappedRegion + OFFSET_MMAPMETADATA);
if ((*mmapHeader)->mmapMagicNumber == ELEKTRA_MAGIC_MMAP_NUMBER && (*mmapHeader)->formatVersion == ELEKTRA_MMAP_FORMAT_VERSION)
{
return 0;
}
return -1;
}
/**
* @brief Reads the MmapFooter from the end of the mapped region.
*
* @param mappedRegion pointer to the mapped region
* @param mmapHeader the MmapHeader containing the size of the allocation
*
* @retval -1 if the magic number did not match
* @retval 0 if the magic number matched
*/
static int readFooter (const char * mappedRegion, MmapHeader * mmapHeader)
{
MmapFooter * mmapFooter = (MmapFooter *) (mappedRegion + mmapHeader->allocSize - SIZEOF_MMAPFOOTER);
if (mmapFooter->mmapMagicNumber == ELEKTRA_MAGIC_MMAP_NUMBER)
{
return 0;
}
return -1;
}
/**
* @brief Writes the magic data for consistency checks.
*
* @param dest to write the data to.
*/
static void writeMagicData (const char * mappedRegion)
{
KeySet * destKeySet = (KeySet *) (mappedRegion + OFFSET_MAGIC_KEYSET);
Key * keyPtr = (Key *) (mappedRegion + OFFSET_MAGIC_KEY);
MmapMetaData * mmapMetaData = (MmapMetaData *) (mappedRegion + OFFSET_MAGIC_MMAPMETADATA);
memcpy (destKeySet, &magicKeySet, SIZEOF_KEYSET);
memcpy (keyPtr, &magicKey, SIZEOF_KEY);
memcpy (mmapMetaData, &magicMmapMetaData, SIZEOF_MMAPMETADATA);
#ifdef ELEKTRA_ENABLE_OPTIMIZATIONS
Opmphm * opmphm = (Opmphm *) (mappedRegion + OFFSET_MAGIC_OPMPHM);
OpmphmPredictor * opmphmPredictor = (OpmphmPredictor *) (mappedRegion + OFFSET_MAGIC_OPMPHMPREDICTOR);
memcpy (opmphm, &magicOpmphm, sizeof (Opmphm));
memcpy (opmphmPredictor, &magicOpmphmPredictor, sizeof (OpmphmPredictor));
#endif
}
/* -- Verification Functions ----------------------------------------------------------------------------------------------------------- */
/**
* @brief Verify the magic KeySet.
*
* @param ks keyset to verify
*
* @retval 0 if magic KeySet is consistent
* @retval -1 if magic KeySet is inconsistent
*/
static int verifyMagicKeySet (KeySet * ks)
{
if (!ks) return -1;
return memcmp (ks, &magicKeySet, SIZEOF_KEYSET);
}
/**
* @brief Verify the magic Key.
*
* @param key to verify
*
* @retval 0 if magic Key is consistent
* @retval -1 if magic Key is inconsistent
*/
static int verifyMagicKey (Key * key)
{
if (!key) return -1;
return memcmp (key, &magicKey, SIZEOF_KEY);
}
/**
* @brief Verify the magic MmapMetaData.
*
* @param mmapMetaData to verify
*
* @retval 0 if magic MmapMetaData is consistent
* @retval -1 if magic MmapMetaData is inconsistent
*/
static int verifyMagicMmapMetaData (MmapMetaData * mmapMetaData)
{
if (!mmapMetaData) return -1;
return memcmp (mmapMetaData, &magicMmapMetaData, SIZEOF_MMAPMETADATA);
}
#ifdef ELEKTRA_ENABLE_OPTIMIZATIONS
/**
* @brief Verify the magic Opmphm.
*
* @param opmphm to verify
*
* @retval 0 if magic Opmphm is consistent
* @retval -1 if magic Opmphm is inconsistent
*/
static int verifyMagicOpmphm (Opmphm * opmphm)
{
if (!opmphm) return -1;
return memcmp (opmphm, &magicOpmphm, sizeof (Opmphm));
}
/**
* @brief Verify the magic OpmphmPredictor.
*
* @param opmphmPredictor to verify
*
* @retval 0 if magic OpmphmPredictor is consistent
* @retval -1 if magic OpmphmPredictor is inconsistent
*/
static int verifyMagicOpmphmPredictor (OpmphmPredictor * opmphmPredictor)
{
if (!opmphmPredictor) return -1;
return memcmp (opmphmPredictor, &magicOpmphmPredictor, sizeof (OpmphmPredictor));
}
#endif
/**
* @brief Verify magic data in the mapped region.
*
* @param mappedRegion pointer to mapped region
*
* @retval 0 if magic data is consistent
* @retval -1 if magic data is inconsistent
*/
static int verifyMagicData (char * mappedRegion)
{
KeySet * destKeySet = (KeySet *) (mappedRegion + OFFSET_MAGIC_KEYSET);
Key * keyPtr = (Key *) (mappedRegion + OFFSET_MAGIC_KEY);
MmapMetaData * mmapMetaData = (MmapMetaData *) (mappedRegion + OFFSET_MAGIC_MMAPMETADATA);
if ((verifyMagicKey (keyPtr) != 0) || (verifyMagicKeySet (destKeySet) != 0) || (verifyMagicMmapMetaData (mmapMetaData) != 0))
{
return -1;
}
#ifdef ELEKTRA_ENABLE_OPTIMIZATIONS
Opmphm * opmphm = (Opmphm *) (mappedRegion + OFFSET_MAGIC_OPMPHM);
OpmphmPredictor * opmphmPredictor = (OpmphmPredictor *) (mappedRegion + OFFSET_MAGIC_OPMPHMPREDICTOR);
if ((verifyMagicOpmphm (opmphm) != 0) || (verifyMagicOpmphmPredictor (opmphmPredictor) != 0))
{
return -1;
}
#endif
return 0;
}
#ifdef ELEKTRA_MMAP_CHECKSUM
/**
* @brief Verify checksum of the critical mmap data.
*
* Verifies the CRC32 checksum of all KeySet and Key structs (including pointers/pointer arrays)
* as well as the MmapMetaData. Does not check Key name and value.
*
* @param mappedRegion pointer to mapped region
* @param mmapHeader containing the stored checksum and size of the checksum region
*
* @retval 0 if checksum was correct
* @retval -1 if there was a checksum mismatch
*/
static int verifyChecksum (char * mappedRegion, MmapHeader * mmapHeader, PluginMode mode)
{
// if file was written without checksum, we skip the check
if (!test_bit (mmapHeader->formatFlags, MMAP_FLAG_CHECKSUM)) return 0;
uint32_t checksum = crc32 (0L, Z_NULL, 0);
checksum = crc32 (checksum, (const unsigned char *) (mappedRegion + SIZEOF_MMAPHEADER), mmapHeader->cksumSize);
if (checksum != mmapHeader->checksum)
{
ELEKTRA_MMAP_LOG_WARNING ("old checksum: %ul", mmapHeader->checksum);
ELEKTRA_MMAP_LOG_WARNING ("new checksum: %ul", checksum);
return -1;
}
return 0;
}
#endif
/**
* Calculate the data block size of all keys within a key set.
* @param mmapMetaData the structure where to add the allocation size to
* @param keySet the key set which contains all the keys to use for calculation
* @param dynArray used for the `dynArrayFindOrInsert` function
* @return the sum of all the data block sizes
*/
static size_t calculateDataBlockSize (MmapMetaData * mmapMetaData, const KeySet * keySet, DynArray * dynArray)
{
Key * cur;
size_t dataBlocksSize = 0;
for (elektraCursor it = 0; it < ksGetSize (keySet); ++it)
{
cur = ksAtCursor (keySet, it);
dataBlocksSize += (cur->keySize + cur->keyUSize + cur->dataSize);
if (cur->meta && cur->meta->size > 0)
{
++mmapMetaData->numKeySets;
Key * curMeta;
for (elektraCursor itMeta = 0; itMeta < ksGetSize (cur->meta); ++itMeta)
{
curMeta = ksAtCursor (cur->meta, itMeta);
if (ELEKTRA_PLUGIN_FUNCTION (dynArrayFindOrInsert) (curMeta, dynArray) == 0)
{
// key was just inserted
dataBlocksSize += (curMeta->keySize + curMeta->keyUSize + curMeta->dataSize);
}
}
mmapMetaData->ksAlloc += (cur->meta->alloc);
}
}
return dataBlocksSize;
}
/**
* @brief Calculates the size, in bytes, needed to store the KeySet in a mmap region.
*
* Iterates over the KeySet and calculates the complete size in bytes, needed to store the KeySet
* within a mapped region. The size includes all mmap meta-information, magic KeySet and Key for
* consistency checks, KeySets, meta-KeySets, Keys, meta-Keys, Key names and values.
* Copied meta-Keys are counted once for deduplication. If needed, padding is added to align the
* MmapFooter properly at the end of the mapping. When the plugin is in a global position,
* acting as a cache, the calculated size includes the global KeySet.
*
* The complete size and some other meta-information are stored in the MmapHeader and MmapMetaData.
* The DynArray stores the unique meta-Key pointers needed for deduplication.
*
* @param mmapHeader to store the allocation size
* @param mmapMetaData to store the number of KeySets and Keys
* @param returned the KeySet that should be stored
* @param global the global KeySet
* @param dynArray to store meta-key pointers for deduplication
*/
static void calculateMmapDataSize (MmapHeader * mmapHeader, MmapMetaData * mmapMetaData, KeySet * returned, KeySet * global,
DynArray * dynArray)
{
size_t dataBlocksSize; // sum of keyName and keyValue sizes
mmapMetaData->numKeys = 0;
mmapMetaData->numKeySets = 3; // include the magic, global and main keyset
mmapMetaData->ksAlloc = returned->alloc; // sum of allocation sizes for all meta-keysets
dataBlocksSize = calculateDataBlockSize (mmapMetaData, returned, dynArray);
if (global)
{
ELEKTRA_LOG_DEBUG ("calculate global keyset into size");
mmapMetaData->ksAlloc += global->alloc;
mmapMetaData->numKeys += global->size;
dataBlocksSize += calculateDataBlockSize (mmapMetaData, global, dynArray);
}
mmapMetaData->numKeys += returned->size + dynArray->size + 1; // +1 for magic Key
size_t opmphmSize = 0;
#ifdef ELEKTRA_ENABLE_OPTIMIZATIONS
// the OPMPHM structs are included regardless of existece in KeySet
// s.t. the format stays the same for all KeySets
opmphmSize = (sizeof (Opmphm) * 2) + (sizeof (OpmphmPredictor) * 2); // *2 for magic opmphm data
Opmphm * opmphm = returned->opmphm;
if (opmphm)
{
if (opmphm->rUniPar) dataBlocksSize += opmphm->rUniPar * sizeof (int32_t);
dataBlocksSize += opmphm->size;
}
OpmphmPredictor * opmphmPredictor = returned->opmphmPredictor;
if (opmphmPredictor)
{
dataBlocksSize += opmphmPredictor->size * sizeof (uint8_t);
}
ELEKTRA_LOG_DEBUG ("OPMPHM enabled, size: %zu", opmphmSize);
#endif
size_t keyArraySize = mmapMetaData->numKeys * SIZEOF_KEY;
mmapHeader->allocSize = (SIZEOF_MMAPMETADATA * 2) + opmphmSize + (SIZEOF_KEYSET * mmapMetaData->numKeySets) + keyArraySize +
dataBlocksSize + (mmapMetaData->ksAlloc * SIZEOF_KEY_PTR);
mmapHeader->cksumSize = mmapHeader->allocSize; // cksumSize now contains size of all critical data
size_t padding = sizeof (uint64_t) - (mmapHeader->allocSize % sizeof (uint64_t)); // alignment for MMAP Footer at end of mapping
mmapHeader->allocSize += SIZEOF_MMAPHEADER + padding + SIZEOF_MMAPFOOTER;
mmapMetaData->numKeys--; // don't include magic Key
mmapMetaData->numKeySets--; // don't include magic KeySet
}
/**
* @brief Write meta-keys to the mapped region.
*
* This function only writes all meta-keys to the mapped region.
* The meta-keys are later referenced in the meta-keysets.
*
* @param mmapAddr struct containing pointers to the mapped region
* @param dynArray containing deduplicated meta-keys
*/
static void writeMetaKeys (MmapAddr * mmapAddr, DynArray * dynArray)
{
if (dynArray->size == 0)
{
return;
}
// allocate space in DynArray to remember the addresses of mapped meta-keys
dynArray->mappedKeyArray = elektraCalloc (dynArray->size * sizeof (Key *));
// write the meta keys into place
for (size_t i = 0; i < dynArray->size; ++i)
{
Key * curMeta = dynArray->keyArray[i]; // old key location
Key * mmapMetaKey = (Key *) mmapAddr->keyPtr; // new key location
*mmapMetaKey = *curMeta;
mmapAddr->keyPtr += SIZEOF_KEY;
// move Key name
if (curMeta->key)
{
memcpy (mmapAddr->dataPtr, curMeta->key, curMeta->keySize);
mmapMetaKey->key = mmapAddr->dataPtr - mmapAddr->mmapAddrInt;
mmapAddr->dataPtr += curMeta->keySize;
mmapMetaKey->flags |= KEY_FLAG_MMAP_KEY;
}
// move Key unescaped name
if (curMeta->ukey)
{
memcpy (mmapAddr->dataPtr, curMeta->ukey, curMeta->keyUSize);
mmapMetaKey->ukey = mmapAddr->dataPtr - mmapAddr->mmapAddrInt;
mmapAddr->dataPtr += curMeta->keyUSize;
mmapMetaKey->flags |= KEY_FLAG_MMAP_KEY;
}
// move Key value
if (curMeta->data.v)
{
memcpy (mmapAddr->dataPtr, curMeta->data.v, curMeta->dataSize);
mmapMetaKey->data.v = mmapAddr->dataPtr - mmapAddr->mmapAddrInt;
mmapAddr->dataPtr += curMeta->dataSize;
mmapMetaKey->flags |= KEY_FLAG_MMAP_DATA;
}
// move Key itself
mmapMetaKey->flags |= KEY_FLAG_MMAP_STRUCT;
mmapMetaKey->meta = 0;
mmapMetaKey->refs = 0;
dynArray->mappedKeyArray[i] = mmapMetaKey;
}
}
/**
* @brief Writes a meta keyset of a key to the mapped region.
*
* @param key holding the meta-keyset
* @param mmapAddr structure holding pointers to the mapped region
* @param dynArray holding deduplicated references to meta-keys
*
* @return pointer to the new meta keyset
*/
static KeySet * writeMetaKeySet (Key * key, MmapAddr * mmapAddr, DynArray * dynArray)
{
// write the meta KeySet
if (!key->meta || !(key->meta->size > 0)) return 0;
KeySet * newMeta = (KeySet *) mmapAddr->metaKsPtr;
mmapAddr->metaKsPtr += SIZEOF_KEYSET;
newMeta->flags = key->meta->flags | KS_FLAG_MMAP_STRUCT | KS_FLAG_MMAP_ARRAY;
newMeta->array = (Key **) mmapAddr->metaKsArrayPtr;
mmapAddr->metaKsArrayPtr += SIZEOF_KEY_PTR * key->meta->alloc;
size_t metaKeyIndex = 0;
Key * mappedMetaKey = 0;
const Key * metaKey;
KeySet * metaKeys = keyMeta (key);
for (elektraCursor it = 0; it < ksGetSize (metaKeys); ++it)
{
metaKey = ksAtCursor (metaKeys, it);
// get address of mapped key and store it in the new array
mappedMetaKey = dynArray->mappedKeyArray[ELEKTRA_PLUGIN_FUNCTION (dynArrayFind) ((Key *) metaKey, dynArray)];
newMeta->array[metaKeyIndex] = (Key *) ((char *) mappedMetaKey - mmapAddr->mmapAddrInt);
if (mappedMetaKey->refs < UINT16_MAX - 1)
{
++(mappedMetaKey->refs);
}
++metaKeyIndex;
}
newMeta->array[key->meta->size] = 0;
newMeta->array = (Key **) ((char *) newMeta->array - mmapAddr->mmapAddrInt);
newMeta->alloc = key->meta->alloc;
newMeta->size = key->meta->size;
newMeta = (KeySet *) ((char *) newMeta - mmapAddr->mmapAddrInt);
return newMeta;
}
/**
* @brief Writes the keys of the keyset to the mapped region.
*
* For each key, the corresponding meta keyset is also written
* to the mapped region.
*
* @param keySet holding the keys to be written to the mapped region
* @param mmapAddr structure holding pointers to the mapped region
* @param dynArray holding deduplicated meta-key pointers
*/
static void writeKeys (KeySet * keySet, MmapAddr * mmapAddr, DynArray * dynArray, PluginMode mode)
{
Key * cur;
size_t keyIndex = 0;
Key ** ksArray = 0;
if (test_bit (mode, MODE_STORAGE))
{
ksArray = (Key **) mmapAddr->ksArrayPtr;
}
else
{
ksArray = (Key **) mmapAddr->globalKsArrayPtr;
}
for (elektraCursor it = 0; it < ksGetSize (keySet); ++it)
{
cur = ksAtCursor (keySet, it);
Key * mmapKey = (Key *) mmapAddr->keyPtr; // new key location
mmapAddr->keyPtr += SIZEOF_KEY;
*mmapKey = *cur;
// move Key name
if (cur->key)
{
memcpy (mmapAddr->dataPtr, cur->key, cur->keySize);
mmapKey->key = mmapAddr->dataPtr - mmapAddr->mmapAddrInt;
mmapAddr->dataPtr += cur->keySize;
mmapKey->flags |= KEY_FLAG_MMAP_KEY;
}
// move Key unescaped name
if (cur->ukey)
{
memcpy (mmapAddr->dataPtr, cur->ukey, cur->keyUSize);
mmapKey->ukey = mmapAddr->dataPtr - mmapAddr->mmapAddrInt;
mmapAddr->dataPtr += cur->keyUSize;
mmapKey->flags |= KEY_FLAG_MMAP_KEY;
}
// move Key value
if (cur->data.v)
{
memcpy (mmapAddr->dataPtr, cur->data.v, cur->dataSize);
mmapKey->data.v = mmapAddr->dataPtr - mmapAddr->mmapAddrInt;
mmapAddr->dataPtr += cur->dataSize;
mmapKey->flags |= KEY_FLAG_MMAP_DATA;
}
else
{
mmapKey->data.v = 0;
mmapKey->dataSize = 0;
}
// write the meta KeySet
mmapKey->meta = writeMetaKeySet (cur, mmapAddr, dynArray);
// move Key itself
mmapKey->flags |= KEY_FLAG_MMAP_STRUCT;
mmapKey->refs = 1;
// write the relative Key pointer into the KeySet array
ksArray[keyIndex] = (Key *) ((char *) mmapKey - mmapAddr->mmapAddrInt);
++keyIndex;
}
}
static void printMmapAddr (MmapAddr * mmapAddr ELEKTRA_UNUSED)
{
ELEKTRA_LOG_DEBUG ("globalKsPtr: \t\t %p", (void *) mmapAddr->globalKsPtr);
ELEKTRA_LOG_DEBUG ("ksPtr: \t\t %p", (void *) mmapAddr->ksPtr);
ELEKTRA_LOG_DEBUG ("metaKsPtr: \t\t %p", (void *) mmapAddr->metaKsPtr);
ELEKTRA_LOG_DEBUG ("globalKsArrayPtr: \t %p", (void *) mmapAddr->globalKsArrayPtr);
ELEKTRA_LOG_DEBUG ("ksArrayPtr: \t\t %p", (void *) mmapAddr->ksArrayPtr);
ELEKTRA_LOG_DEBUG ("metaKsArrayPtr: \t %p", (void *) mmapAddr->metaKsArrayPtr);
ELEKTRA_LOG_DEBUG ("keyPtr: \t\t %p", (void *) mmapAddr->keyPtr);
ELEKTRA_LOG_DEBUG ("dataPtr: \t\t %p", (void *) mmapAddr->dataPtr);
ELEKTRA_LOG_DEBUG ("mmapAddrInt: \t\t %lu", mmapAddr->mmapAddrInt);
}
static void printMmapMetaData (MmapMetaData * mmapMetaData ELEKTRA_UNUSED)
{
ELEKTRA_LOG_DEBUG ("numKeySets: \t %lu", mmapMetaData->numKeySets);
ELEKTRA_LOG_DEBUG ("ksAlloc: \t %lu", mmapMetaData->ksAlloc);
ELEKTRA_LOG_DEBUG ("numKeys: \t %lu", mmapMetaData->numKeys);
}
/**
* @brief Copies a keyset to a mapped region.
*
* Writes a keyset with all needed information to the mapped region and calculates
* the checksum. Everything is written to the mapped region, including keyset, keys,
* meta-information and data for consistency checks.
*
* @param dest address of the mapped region
* @param keySet to copy to the mapped region
* @param global global keyset
* @param mmapHeader containing the size and checksum of the mapped region
* @param mmapMetaData containing meta-information of the mapped region
* @param mmapFooter containing a magic number for consistency checks
* @param dynArray containing deduplicated pointers to meta-keys
* @param mode the current plugin mode
*
* @retval 0 on success
* @retval -1 if msync() failed
*/
static int copyKeySetToMmap (char * const dest, KeySet * keySet, KeySet * global, MmapHeader * mmapHeader, MmapMetaData * mmapMetaData,
MmapFooter * mmapFooter, DynArray * dynArray, PluginMode mode)
{
writeMagicData (dest);
size_t globalAlloc = 0;
if (global) globalAlloc = global->alloc;
MmapAddr mmapAddr = { .globalKsPtr = (KeySet *) (dest + OFFSET_GLOBAL_KEYSET),
.ksPtr = (KeySet *) (dest + OFFSET_KEYSET),
.metaKsPtr = (char *) mmapAddr.ksPtr + SIZEOF_KEYSET,
.globalKsArrayPtr = (dest + OFFSET_GLOBAL_KEYSET) + (SIZEOF_KEYSET * mmapMetaData->numKeySets),
.ksArrayPtr = mmapAddr.globalKsArrayPtr + (SIZEOF_KEY_PTR * globalAlloc),
.metaKsArrayPtr = mmapAddr.ksArrayPtr + (SIZEOF_KEY_PTR * keySet->alloc),
.keyPtr = mmapAddr.globalKsArrayPtr + (SIZEOF_KEY_PTR * mmapMetaData->ksAlloc),
.dataPtr = mmapAddr.keyPtr + (SIZEOF_KEY * mmapMetaData->numKeys),
.mmapAddrInt = (uintptr_t) dest };
printMmapAddr (&mmapAddr);
printMmapMetaData (mmapMetaData);
#ifdef ELEKTRA_ENABLE_OPTIMIZATIONS
// We FIRST write the opmphm data. If this is changed, you'll run into alignment problems.
// set OPMPHM flag, so file is not readable by builds without OPMPHM
set_bit (mmapHeader->formatFlags, MMAP_FLAG_OPMPHM);
if (keySet->opmphm)
{
mmapAddr.ksPtr->opmphm = (Opmphm *) (dest + OFFSET_OPMPHM);
memcpy (mmapAddr.ksPtr->opmphm, keySet->opmphm, sizeof (Opmphm));
mmapAddr.ksPtr->opmphm->flags = OPMPHM_FLAG_MMAP_STRUCT;
if (keySet->opmphm->rUniPar)
{
mmapAddr.ksPtr->opmphm->hashFunctionSeeds = (int32_t *) mmapAddr.dataPtr;
memcpy (mmapAddr.ksPtr->opmphm->hashFunctionSeeds, keySet->opmphm->hashFunctionSeeds,
keySet->opmphm->rUniPar * sizeof (int32_t));
set_bit (mmapAddr.ksPtr->opmphm->flags, OPMPHM_FLAG_MMAP_HASHFUNCTIONSEEDS);
mmapAddr.dataPtr += keySet->opmphm->rUniPar * sizeof (int32_t);
mmapAddr.ksPtr->opmphm->hashFunctionSeeds =
(int32_t *) (((char *) mmapAddr.ksPtr->opmphm->hashFunctionSeeds) - mmapAddr.mmapAddrInt);
}
if (keySet->opmphm->size)
{
mmapAddr.ksPtr->opmphm->graph = (uint32_t *) mmapAddr.dataPtr;
memcpy (mmapAddr.ksPtr->opmphm->graph, keySet->opmphm->graph, keySet->opmphm->size);
set_bit (mmapAddr.ksPtr->opmphm->flags, OPMPHM_FLAG_MMAP_GRAPH);
mmapAddr.dataPtr += keySet->opmphm->size;
mmapAddr.ksPtr->opmphm->graph = (uint32_t *) (((char *) mmapAddr.ksPtr->opmphm->graph) - mmapAddr.mmapAddrInt);
}
mmapAddr.ksPtr->opmphm = (Opmphm *) (((char *) mmapAddr.ksPtr->opmphm) - mmapAddr.mmapAddrInt);
}
if (keySet->opmphmPredictor)
{
ELEKTRA_LOG_DEBUG ("OPMPHM: will store predictor");
mmapAddr.ksPtr->opmphmPredictor = (OpmphmPredictor *) (dest + OFFSET_OPMPHMPREDICTOR);
memcpy (mmapAddr.ksPtr->opmphmPredictor, keySet->opmphmPredictor, sizeof (OpmphmPredictor));
mmapAddr.ksPtr->opmphmPredictor->patternTable = (uint8_t *) mmapAddr.dataPtr;
memcpy (mmapAddr.ksPtr->opmphmPredictor->patternTable, keySet->opmphmPredictor->patternTable,
keySet->opmphmPredictor->size * sizeof (uint8_t));
mmapAddr.ksPtr->opmphmPredictor->flags = OPMPHM_PREDICTOR_FLAG_MMAP_STRUCT | OPMPHM_PREDICTOR_FLAG_MMAP_PATTERNTABLE;
mmapAddr.dataPtr += keySet->opmphmPredictor->size * sizeof (uint8_t);
mmapAddr.ksPtr->opmphmPredictor->patternTable =
(uint8_t *) (((char *) mmapAddr.ksPtr->opmphmPredictor->patternTable) - mmapAddr.mmapAddrInt);
mmapAddr.ksPtr->opmphmPredictor = (OpmphmPredictor *) (((char *) mmapAddr.ksPtr->opmphmPredictor) - mmapAddr.mmapAddrInt);
}
#endif
// first write the meta keys into place
writeMetaKeys (&mmapAddr, dynArray);
if (global)
{
ELEKTRA_LOG_DEBUG ("writing GLOBAL KEYSET");
if (global->size != 0) writeKeys (global, &mmapAddr, dynArray, MODE_GLOBALCACHE);
set_bit (mmapHeader->formatFlags, MMAP_FLAG_TIMESTAMPS);
mmapAddr.globalKsPtr->flags = global->flags | KS_FLAG_MMAP_STRUCT | KS_FLAG_MMAP_ARRAY;
mmapAddr.globalKsPtr->array = (Key **) mmapAddr.globalKsArrayPtr;
mmapAddr.globalKsPtr->array[global->size] = 0;
mmapAddr.globalKsPtr->array = (Key **) (mmapAddr.globalKsArrayPtr - mmapAddr.mmapAddrInt);
mmapAddr.globalKsPtr->alloc = global->alloc;
mmapAddr.globalKsPtr->size = global->size;
}
if (keySet->size != 0)
{
// now write Keys including meta KeySets
writeKeys (keySet, &mmapAddr, dynArray, MODE_STORAGE);
}
mmapAddr.ksPtr->flags = keySet->flags | KS_FLAG_MMAP_STRUCT | KS_FLAG_MMAP_ARRAY;
mmapAddr.ksPtr->array = (Key **) mmapAddr.ksArrayPtr;
mmapAddr.ksPtr->array[keySet->size] = 0;
mmapAddr.ksPtr->array = (Key **) (mmapAddr.ksArrayPtr - mmapAddr.mmapAddrInt);
mmapAddr.ksPtr->alloc = keySet->alloc;
mmapAddr.ksPtr->size = keySet->size;
memcpy ((dest + OFFSET_MMAPMETADATA), mmapMetaData, SIZEOF_MMAPMETADATA);
#ifdef ELEKTRA_MMAP_CHECKSUM
uint32_t checksum = crc32 (0L, Z_NULL, 0);
checksum = crc32 (checksum, (const unsigned char *) (dest + SIZEOF_MMAPHEADER), mmapHeader->cksumSize);
mmapHeader->checksum = checksum;
#endif
memcpy (dest, mmapHeader, SIZEOF_MMAPHEADER);
// force footer to be written last, as a consistency check
if (!test_bit (mode, MODE_NONREGULAR_FILE) && msync ((void *) dest, mmapHeader->allocSize, MS_SYNC) != 0)
{
ELEKTRA_MMAP_LOG_WARNING ("could not msync");
return -1;
}
memcpy ((dest + mmapHeader->allocSize - SIZEOF_MMAPFOOTER), mmapFooter, SIZEOF_MMAPFOOTER);
return 0;
}
#ifdef ELEKTRA_ENABLE_OPTIMIZATIONS
/**
* @brief Deletes the OPMPHM.
*
* Clears and frees all memory in Opmphm.
*
* @param opmphm the OPMPHM
*/
static void mmapOpmphmDel (Opmphm * opmphm)
{
ELEKTRA_NOT_NULL (opmphm);
if (opmphm && opmphm->size && !test_bit (opmphm->flags, OPMPHM_FLAG_MMAP_GRAPH))
{
elektraFree (opmphm->graph);
}
if (opmphm->rUniPar && !test_bit (opmphm->flags, OPMPHM_FLAG_MMAP_HASHFUNCTIONSEEDS))
{
elektraFree (opmphm->hashFunctionSeeds);
}
if (!test_bit (opmphm->flags, OPMPHM_FLAG_MMAP_STRUCT)) elektraFree (opmphm);
}