Work to allow mmap-ed log entries to be used for data blocks.
[bluesky.git] / bluesky / util.c
index 3ac6596..c4bac19 100644 (file)
@@ -10,6 +10,7 @@
 #include <stdint.h>
 #include <glib.h>
 #include <string.h>
+#include <sys/mman.h>
 
 #include "bluesky-private.h"
 
@@ -52,6 +53,17 @@ gboolean bluesky_inode_is_ready(BlueSkyInode *inode)
 
 /**** Reference-counted strings. ****/
 
+void bluesky_mmap_unref(BlueSkyMmap *mmap)
+{
+    if (mmap == NULL)
+        return;
+
+    if (g_atomic_int_dec_and_test(&mmap->refcount)) {
+        munmap((void *)mmap->addr, mmap->len);
+        g_free(mmap);
+    }
+}
+
 /* Create and return a new reference-counted string.  The reference count is
  * initially one.  The newly-returned string takes ownership of the memory
  * pointed at by data, and will call g_free on it when the reference count
@@ -59,6 +71,7 @@ gboolean bluesky_inode_is_ready(BlueSkyInode *inode)
 BlueSkyRCStr *bluesky_string_new(gpointer data, gsize len)
 {
     BlueSkyRCStr *string = g_new(BlueSkyRCStr, 1);
+    string->mmap = NULL;
     string->data = data;
     string->len = len;
     g_atomic_int_set(&string->refcount, 1);
@@ -72,6 +85,19 @@ BlueSkyRCStr *bluesky_string_new_from_gstring(GString *s)
     return bluesky_string_new(g_string_free(s, FALSE), len);
 }
 
+/* Create a new BlueSkyRCStr from a memory-mapped buffer. */
+BlueSkyRCStr *bluesky_string_new_from_mmap(BlueSkyMmap *mmap,
+                                           int offset, gsize len)
+{
+    BlueSkyRCStr *string = g_new(BlueSkyRCStr, 1);
+    string->mmap = mmap;
+    g_atomic_int_inc(&mmap->refcount);
+    string->data = (char *)mmap->addr + offset;
+    string->len = len;
+    g_atomic_int_set(&string->refcount, 1);
+    return string;
+}
+
 void bluesky_string_ref(BlueSkyRCStr *string)
 {
     if (string == NULL)
@@ -86,7 +112,11 @@ void bluesky_string_unref(BlueSkyRCStr *string)
         return;
 
     if (g_atomic_int_dec_and_test(&string->refcount)) {
-        g_free(string->data);
+        if (string->mmap == NULL) {
+            g_free(string->data);
+        } else {
+            bluesky_mmap_unref(string->mmap);
+        }
         g_free(string);
     }
 }
@@ -102,6 +132,14 @@ BlueSkyRCStr *bluesky_string_dup(BlueSkyRCStr *string)
     if (string == NULL)
         return NULL;
 
+    if (string->mmap != NULL) {
+        BlueSkyRCStr *s;
+        s = bluesky_string_new(g_memdup(string->data, string->len),
+                               string->len);
+        bluesky_string_unref(string);
+        return s;
+    }
+
     if (g_atomic_int_dec_and_test(&string->refcount)) {
         /* There are no other shared copies, so return this one. */
         g_atomic_int_inc(&string->refcount);
@@ -119,6 +157,8 @@ BlueSkyRCStr *bluesky_string_dup(BlueSkyRCStr *string)
  * if needed). */
 void bluesky_string_resize(BlueSkyRCStr *string, gsize len)
 {
+    g_assert(string->mmap == NULL);
+
     if (string->len == len)
         return;