2 This file is part of GNUnet.
3 (C) 2001, 2002, 2003, 2004, 2006, 2008, 2011, 2012 Christian Grothoff (and other contributing authors)
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 2, or (at your
8 option) any later version.
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
21 * @file util/container_bloomfilter.c
22 * @brief data structure used to reduce disk accesses.
24 * The idea basically: Create a signature for each element in the
25 * database. Add those signatures to a bit array. When doing a lookup,
26 * check if the bit array matches the signature of the requested
27 * element. If yes, address the disk, otherwise return 'not found'.
29 * A property of the bloom filter is that sometimes we will have
30 * a match even if the element is not on the disk (then we do
31 * an unnecessary disk access), but what's most important is that
32 * we never get a single "false negative".
34 * To be able to delete entries from the bloom filter, we maintain
35 * a 4 bit counter in the file on the drive (we still use only one
38 * @author Igor Wronsky
39 * @author Christian Grothoff
43 #include "gnunet_common.h"
44 #include "gnunet_container_lib.h"
45 #include "gnunet_disk_lib.h"
47 #define LOG(kind,...) GNUNET_log_from (kind, "util", __VA_ARGS__)
49 #define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util", syscall)
51 #define LOG_STRERROR_FILE(kind,syscall,filename) GNUNET_log_from_strerror_file (kind, "util", syscall, filename)
53 struct GNUNET_CONTAINER_BloomFilter
57 * The actual bloomfilter bit array
62 * Filename of the filter
67 * The bit counter file on disk
69 struct GNUNET_DISK_FileHandle *fh;
72 * How many bits we set for each stored element
74 unsigned int addressesPerElement;
77 * Size of bitArray in bytes
86 * Get size of the bloom filter.
88 * @param bf the filter
89 * @return number of bytes used for the data of the bloom filter
92 GNUNET_CONTAINER_bloomfilter_get_size (const struct GNUNET_CONTAINER_BloomFilter
97 return bf->bitArraySize;
102 * Copy an existing memory. Any association with a file
103 * on-disk will be lost in the process.
104 * @param bf the filter to copy
105 * @return copy of the bf
107 struct GNUNET_CONTAINER_BloomFilter *
108 GNUNET_CONTAINER_bloomfilter_copy (const struct GNUNET_CONTAINER_BloomFilter
111 return GNUNET_CONTAINER_bloomfilter_init (bf->bitArray, bf->bitArraySize,
112 bf->addressesPerElement);
117 * Sets a bit active in the bitArray. Increment bit-specific
118 * usage counter on disk only if below 4bit max (==15).
120 * @param bitArray memory area to set the bit in
121 * @param bitIdx which bit to set
124 setBit (char *bitArray, unsigned int bitIdx)
127 unsigned int targetBit;
129 arraySlot = bitIdx / 8;
130 targetBit = (1L << (bitIdx % 8));
131 bitArray[arraySlot] |= targetBit;
135 * Clears a bit from bitArray. Bit is cleared from the array
136 * only if the respective usage counter on the disk hits/is zero.
138 * @param bitArray memory area to set the bit in
139 * @param bitIdx which bit to unset
142 clearBit (char *bitArray, unsigned int bitIdx)
145 unsigned int targetBit;
148 targetBit = (1L << (bitIdx % 8));
149 bitArray[slot] = bitArray[slot] & (~targetBit);
153 * Checks if a bit is active in the bitArray
155 * @param bitArray memory area to set the bit in
156 * @param bitIdx which bit to test
157 * @return GNUNET_YES if the bit is set, GNUNET_NO if not.
160 testBit (char *bitArray, unsigned int bitIdx)
163 unsigned int targetBit;
166 targetBit = (1L << (bitIdx % 8));
167 if (bitArray[slot] & targetBit)
174 * Sets a bit active in the bitArray and increments
175 * bit-specific usage counter on disk (but only if
176 * the counter was below 4 bit max (==15)).
178 * @param bitArray memory area to set the bit in
179 * @param bitIdx which bit to test
180 * @param fh A file to keep the 4 bit address usage counters in
183 incrementBit (char *bitArray, unsigned int bitIdx,
184 const struct GNUNET_DISK_FileHandle *fh)
190 unsigned int targetLoc;
192 setBit (bitArray, bitIdx);
193 if (GNUNET_DISK_handle_invalid (fh))
195 /* Update the counter file on disk */
196 fileSlot = bitIdx / 2;
197 targetLoc = bitIdx % 2;
199 GNUNET_assert (fileSlot ==
200 GNUNET_DISK_file_seek (fh, fileSlot, GNUNET_DISK_SEEK_SET));
201 if (1 != GNUNET_DISK_file_read (fh, &value, 1))
204 high = (value & (~0xF)) >> 4;
216 value = ((high << 4) | low);
217 GNUNET_assert (fileSlot ==
218 GNUNET_DISK_file_seek (fh, fileSlot, GNUNET_DISK_SEEK_SET));
219 GNUNET_assert (1 == GNUNET_DISK_file_write (fh, &value, 1));
223 * Clears a bit from bitArray if the respective usage
224 * counter on the disk hits/is zero.
226 * @param bitArray memory area to set the bit in
227 * @param bitIdx which bit to test
228 * @param fh A file to keep the 4bit address usage counters in
231 decrementBit (char *bitArray, unsigned int bitIdx,
232 const struct GNUNET_DISK_FileHandle *fh)
238 unsigned int targetLoc;
240 if (GNUNET_DISK_handle_invalid (fh))
241 return; /* cannot decrement! */
242 /* Each char slot in the counter file holds two 4 bit counters */
243 fileSlot = bitIdx / 2;
244 targetLoc = bitIdx % 2;
245 GNUNET_DISK_file_seek (fh, fileSlot, GNUNET_DISK_SEEK_SET);
246 if (1 != GNUNET_DISK_file_read (fh, &value, 1))
249 high = (value & 0xF0) >> 4;
251 /* decrement, but once we have reached the max, never go back! */
254 if ((low > 0) && (low < 0xF))
258 clearBit (bitArray, bitIdx);
263 if ((high > 0) && (high < 0xF))
267 clearBit (bitArray, bitIdx);
270 value = ((high << 4) | low);
271 GNUNET_DISK_file_seek (fh, fileSlot, GNUNET_DISK_SEEK_SET);
272 GNUNET_assert (1 == GNUNET_DISK_file_write (fh, &value, 1));
275 #define BUFFSIZE 65536
278 * Creates a file filled with zeroes
280 * @param fh the file handle
281 * @param size the size of the file
282 * @return GNUNET_OK if created ok, GNUNET_SYSERR otherwise
285 make_empty_file (const struct GNUNET_DISK_FileHandle *fh, size_t size)
287 char buffer[BUFFSIZE];
288 size_t bytesleft = size;
291 if (GNUNET_DISK_handle_invalid (fh))
292 return GNUNET_SYSERR;
293 memset (buffer, 0, sizeof (buffer));
294 GNUNET_DISK_file_seek (fh, 0, GNUNET_DISK_SEEK_SET);
295 while (bytesleft > 0)
297 if (bytesleft > sizeof (buffer))
299 res = GNUNET_DISK_file_write (fh, buffer, sizeof (buffer));
305 res = GNUNET_DISK_file_write (fh, buffer, bytesleft);
309 if (GNUNET_SYSERR == res)
310 return GNUNET_SYSERR;
315 /* ************** GNUNET_CONTAINER_BloomFilter iterator ********* */
318 * Iterator (callback) method to be called by the
319 * bloomfilter iterator on each bit that is to be
320 * set or tested for the key.
323 * @param bf the filter to manipulate
324 * @param bit the current bit
325 * @return GNUNET_YES to continue, GNUNET_NO to stop early
327 typedef int (*BitIterator) (void *cls,
328 const struct GNUNET_CONTAINER_BloomFilter * bf,
333 * Call an iterator for each bit that the bloomfilter
334 * must test or set for this element.
336 * @param bf the filter
337 * @param callback the method to call
338 * @param arg extra argument to callback
339 * @param key the key for which we iterate over the BF bits
342 iterateBits (const struct GNUNET_CONTAINER_BloomFilter *bf,
343 BitIterator callback, void *arg, const struct GNUNET_HashCode * key)
345 struct GNUNET_HashCode tmp[2];
348 unsigned int slot = 0;
350 bitCount = bf->addressesPerElement;
353 GNUNET_assert (bf->bitArraySize > 0);
354 GNUNET_assert (bf->bitArraySize * 8LL > bf->bitArraySize);
357 while (slot < (sizeof (struct GNUNET_HashCode) / sizeof (uint32_t)))
361 (((uint32_t *) & tmp[round & 1])[slot]) %
362 ((bf->bitArraySize * 8LL))))
371 GNUNET_CRYPTO_hash (&tmp[round & 1], sizeof (struct GNUNET_HashCode),
372 &tmp[(round + 1) & 1]);
381 * Callback: increment bit
383 * @param cls pointer to writeable form of bf
384 * @param bf the filter to manipulate
385 * @param bit the bit to increment
389 incrementBitCallback (void *cls, const struct GNUNET_CONTAINER_BloomFilter *bf,
392 struct GNUNET_CONTAINER_BloomFilter *b = cls;
394 incrementBit (b->bitArray, bit, bf->fh);
400 * Callback: decrement bit
402 * @param cls pointer to writeable form of bf
403 * @param bf the filter to manipulate
404 * @param bit the bit to decrement
408 decrementBitCallback (void *cls, const struct GNUNET_CONTAINER_BloomFilter *bf,
411 struct GNUNET_CONTAINER_BloomFilter *b = cls;
413 decrementBit (b->bitArray, bit, bf->fh);
419 * Callback: test if all bits are set
421 * @param cls pointer set to GNUNET_NO if bit is not set
422 * @param bf the filter
423 * @param bit the bit to test
424 * @return YES if the bit is set, NO if not
427 testBitCallback (void *cls, const struct GNUNET_CONTAINER_BloomFilter *bf,
432 if (GNUNET_NO == testBit (bf->bitArray, bit))
440 /* *********************** INTERFACE **************** */
443 * Load a bloom-filter from a file.
445 * @param filename the name of the file (or the prefix)
446 * @param size the size of the bloom-filter (number of
447 * bytes of storage space to use); will be rounded up
449 * @param k the number of GNUNET_CRYPTO_hash-functions to apply per
450 * element (number of bits set per element in the set)
451 * @return the bloomfilter
453 struct GNUNET_CONTAINER_BloomFilter *
454 GNUNET_CONTAINER_bloomfilter_load (const char *filename, size_t size,
457 struct GNUNET_CONTAINER_BloomFilter *bf;
465 GNUNET_assert (NULL != filename);
466 if ((k == 0) || (size == 0))
471 while ( (ui < size) &&
474 size = ui; /* make sure it's a power of 2 */
476 bf = GNUNET_malloc (sizeof (struct GNUNET_CONTAINER_BloomFilter));
477 /* Try to open a bloomfilter file */
478 if (GNUNET_YES == GNUNET_DISK_file_test (filename))
480 GNUNET_DISK_file_open (filename,
481 GNUNET_DISK_OPEN_READWRITE,
482 GNUNET_DISK_PERM_USER_READ |
483 GNUNET_DISK_PERM_USER_WRITE);
486 /* file existed, try to read it! */
487 must_read = GNUNET_YES;
489 GNUNET_DISK_file_handle_size (bf->fh, &fsize))
491 GNUNET_DISK_file_close (bf->fh);
497 /* found existing empty file, just overwrite */
498 if (GNUNET_OK != make_empty_file (bf->fh, size * 4LL))
500 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
502 GNUNET_DISK_file_close (bf->fh);
507 else if (fsize != size * 4LL)
509 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
510 _("Size of file on disk is incorrect for this Bloom filter (want %llu, have %llu)\n"),
511 (unsigned long long) (size * 4LL),
512 (unsigned long long) fsize);
513 GNUNET_DISK_file_close (bf->fh);
520 /* file did not exist, don't read, just create */
521 must_read = GNUNET_NO;
523 GNUNET_DISK_file_open (filename,
524 GNUNET_DISK_OPEN_CREATE |
525 GNUNET_DISK_OPEN_READWRITE,
526 GNUNET_DISK_PERM_USER_READ |
527 GNUNET_DISK_PERM_USER_WRITE);
533 if (GNUNET_OK != make_empty_file (bf->fh, size * 4LL))
535 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING,
537 GNUNET_DISK_file_close (bf->fh);
542 bf->filename = GNUNET_strdup (filename);
544 bf->bitArray = GNUNET_malloc_large (size);
545 if (bf->bitArray == NULL)
548 GNUNET_DISK_file_close (bf->fh);
549 GNUNET_free (bf->filename);
553 bf->bitArraySize = size;
554 bf->addressesPerElement = k;
555 if (GNUNET_YES != must_read)
556 return bf; /* already done! */
557 /* Read from the file what bits we can */
558 rbuff = GNUNET_malloc (BUFFSIZE);
560 while (pos < size * 8LL)
564 res = GNUNET_DISK_file_read (bf->fh, rbuff, BUFFSIZE);
567 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "read", bf->filename);
569 GNUNET_free (bf->filename);
570 GNUNET_DISK_file_close (bf->fh);
575 break; /* is ok! we just did not use that many bits yet */
576 for (i = 0; i < res; i++)
578 if ((rbuff[i] & 0x0F) != 0)
579 setBit (bf->bitArray, pos + i * 2);
580 if ((rbuff[i] & 0xF0) != 0)
581 setBit (bf->bitArray, pos + i * 2 + 1);
585 pos += BUFFSIZE * 2; /* 2 bits per byte in the buffer */
593 * Create a bloom filter from raw bits.
595 * @param data the raw bits in memory (maybe NULL,
596 * in which case all bits should be considered
598 * @param size the size of the bloom-filter (number of
599 * bytes of storage space to use); also size of data
600 * -- unless data is NULL
601 * @param k the number of GNUNET_CRYPTO_hash-functions to apply per
602 * element (number of bits set per element in the set)
603 * @return the bloomfilter
605 struct GNUNET_CONTAINER_BloomFilter *
606 GNUNET_CONTAINER_bloomfilter_init (const char *data, size_t size,
609 struct GNUNET_CONTAINER_BloomFilter *bf;
611 if ((0 == k) || (0 == size))
613 bf = GNUNET_malloc (sizeof (struct GNUNET_CONTAINER_BloomFilter));
616 bf->bitArray = GNUNET_malloc_large (size);
617 if (NULL == bf->bitArray)
622 bf->bitArraySize = size;
623 bf->addressesPerElement = k;
625 memcpy (bf->bitArray, data, size);
631 * Copy the raw data of this bloomfilter into
632 * the given data array.
634 * @param bf bloomfilter to take the raw data from
635 * @param data where to write the data
636 * @param size the size of the given data array
637 * @return GNUNET_SYSERR if the data array is not big enough
640 GNUNET_CONTAINER_bloomfilter_get_raw_data (const struct
641 GNUNET_CONTAINER_BloomFilter *bf,
642 char *data, size_t size)
645 return GNUNET_SYSERR;
646 if (bf->bitArraySize != size)
647 return GNUNET_SYSERR;
648 memcpy (data, bf->bitArray, size);
654 * Free the space associated with a filter
655 * in memory, flush to drive if needed (do not
656 * free the space on the drive)
658 * @param bf the filter
661 GNUNET_CONTAINER_bloomfilter_free (struct GNUNET_CONTAINER_BloomFilter *bf)
666 GNUNET_DISK_file_close (bf->fh);
667 GNUNET_free_non_null (bf->filename);
668 GNUNET_free (bf->bitArray);
674 * Reset a bloom filter to empty. Clears the file on disk.
676 * @param bf the filter
679 GNUNET_CONTAINER_bloomfilter_clear (struct GNUNET_CONTAINER_BloomFilter *bf)
684 memset (bf->bitArray, 0, bf->bitArraySize);
685 if (bf->filename != NULL)
686 make_empty_file (bf->fh, bf->bitArraySize * 4LL);
691 * Test if an element is in the filter.
693 * @param e the element
694 * @param bf the filter
695 * @return GNUNET_YES if the element is in the filter, GNUNET_NO if not
698 GNUNET_CONTAINER_bloomfilter_test (const struct GNUNET_CONTAINER_BloomFilter
699 *bf, const struct GNUNET_HashCode * e)
706 iterateBits (bf, &testBitCallback, &res, e);
712 * Add an element to the filter
714 * @param bf the filter
715 * @param e the element
718 GNUNET_CONTAINER_bloomfilter_add (struct GNUNET_CONTAINER_BloomFilter *bf,
719 const struct GNUNET_HashCode * e)
723 iterateBits (bf, &incrementBitCallback, bf, e);
728 * Or the entries of the given raw data array with the
729 * data of the given bloom filter. Assumes that
730 * the size of the data array and the current filter
733 * @param bf the filter
734 * @param data the data to or-in
735 * @param size number of bytes in data
738 GNUNET_CONTAINER_bloomfilter_or (struct GNUNET_CONTAINER_BloomFilter *bf,
739 const char *data, size_t size)
743 unsigned long long *fc;
744 const unsigned long long *dc;
748 if (bf->bitArraySize != size)
749 return GNUNET_SYSERR;
750 fc = (unsigned long long *) bf->bitArray;
751 dc = (const unsigned long long *) data;
752 n = size / sizeof (unsigned long long);
754 for (i = 0; i < n; i++)
756 for (i = n * sizeof (unsigned long long); i < size; i++)
757 bf->bitArray[i] |= data[i];
762 * Or the entries of the given raw data array with the
763 * data of the given bloom filter. Assumes that
764 * the size of the data array and the current filter
767 * @param bf the filter
768 * @param to_or the bloomfilter to or-in
769 * @param size number of bytes in data
772 GNUNET_CONTAINER_bloomfilter_or2 (struct GNUNET_CONTAINER_BloomFilter *bf,
773 const struct GNUNET_CONTAINER_BloomFilter
778 unsigned long long *fc;
779 const unsigned long long *dc;
783 if (bf->bitArraySize != size)
784 return GNUNET_SYSERR;
785 fc = (unsigned long long *) bf->bitArray;
786 dc = (const unsigned long long *) to_or->bitArray;
787 n = size / sizeof (unsigned long long);
789 for (i = 0; i < n; i++)
791 for (i = n * sizeof (unsigned long long); i < size; i++)
792 bf->bitArray[i] |= to_or->bitArray[i];
797 * Remove an element from the filter.
799 * @param bf the filter
800 * @param e the element to remove
803 GNUNET_CONTAINER_bloomfilter_remove (struct GNUNET_CONTAINER_BloomFilter *bf,
804 const struct GNUNET_HashCode * e)
808 if (bf->filename == NULL)
810 iterateBits (bf, &decrementBitCallback, bf, e);
814 * Resize a bloom filter. Note that this operation
815 * is pretty costly. Essentially, the bloom filter
816 * needs to be completely re-build.
818 * @param bf the filter
819 * @param iterator an iterator over all elements stored in the BF
820 * @param iterator_cls argument to the iterator function
821 * @param size the new size for the filter
822 * @param k the new number of GNUNET_CRYPTO_hash-function to apply per element
825 GNUNET_CONTAINER_bloomfilter_resize (struct GNUNET_CONTAINER_BloomFilter *bf,
826 GNUNET_HashCodeIterator iterator,
827 void *iterator_cls, size_t size,
830 struct GNUNET_HashCode hc;
833 GNUNET_free (bf->bitArray);
837 size = i; /* make sure it's a power of 2 */
839 bf->bitArraySize = size;
840 bf->bitArray = GNUNET_malloc (size);
841 if (bf->filename != NULL)
842 make_empty_file (bf->fh, bf->bitArraySize * 4LL);
843 while (GNUNET_YES == iterator (iterator_cls, &hc))
844 GNUNET_CONTAINER_bloomfilter_add (bf, &hc);
847 /* end of container_bloomfilter.c */