More fixes for memory management.
[bluesky.git] / bluesky / imap.c
1 /* Blue Sky: File Systems in the Cloud
2  *
3  * Copyright (C) 2009  The Regents of the University of California
4  * Written by Michael Vrable <mvrable@cs.ucsd.edu>
5  *
6  * TODO: Licensing
7  */
8
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <stdint.h>
12 #include <inttypes.h>
13 #include <glib.h>
14 #include <string.h>
15
16 #include "bluesky-private.h"
17
18 /* Inode maps.  There is both an in-memory representation as well as the
19  * serialized form in the cloud.
20  *
21  * The inode map is broken up into pieces by partitioning in the inode number
22  * space.  The checkpoint region will contain pointers to each of these map
23  * ranges. */
24
25 /* Roughly how many inodes to try to put in each inode map range. */
26 static int target_imap_size = 4096;
27
28 /* Comparison function for lookuping up inode map entries.  Reads a 64-bit
29  * value from the pointed-to address to do the comparison, so we require that
30  * the InodeMapEntry and InodeMapRange structures start with the 64-bit value
31  * they are sorted by. */
32 static gint compare(gconstpointer a, gconstpointer b, gpointer user_data)
33 {
34     uint64_t x = *(uint64_t *)a;
35     uint64_t y = *(uint64_t *)b;
36
37     if (x < y)
38         return -1;
39     else if (x > y)
40         return 1;
41     else
42         return 0;
43 }
44
45 /* Look up the inode map entry for the given inode number.  If action is +1,
46  * create a new entry if it does not already exist; if it is -1 then delete the
47  * entry instead.  If 0, return the entry if it is already present.  A non-zero
48  * action value will mark the inode map range as dirty. */
49 InodeMapEntry *bluesky_inode_map_lookup(GSequence *inode_map, uint64_t inum,
50                                         int action)
51 {
52     GSequenceIter *i;
53
54     /* First, scan through to find the inode map section that covers the
55      * appropriate range.  Create one if it does not exist but we were asked to
56      * create an entry. */
57     InodeMapRange *range = NULL;
58
59     i = g_sequence_search(inode_map, &inum, compare, NULL);
60     i = g_sequence_iter_prev(i);
61     if (!g_sequence_iter_is_end(i))
62         range = (InodeMapRange *)g_sequence_get(i);
63     if (range == NULL || inum < range->start || inum > range->end) {
64         if (action <= 0)
65             return NULL;
66
67         /* Create a new range.  First, determine bounds on the range enpoints
68          * based on neighboring ranges.  Then, shrink the size of the range to
69          * a reasonable size that covers the needed inode number. */
70         range = g_new0(InodeMapRange, 1);
71         range->start = 0;
72         range->end = G_MAXUINT64;
73         range->map_entries = g_sequence_new(NULL);
74         range->serialized = NULL;
75
76         g_print("Creating inode map range, 1: start=%"PRIu64" end=%"PRIu64"\n",
77                 range->start, range->end);
78
79         if (!g_sequence_iter_is_begin(i) && !g_sequence_iter_is_end(i))
80             range->start = ((InodeMapRange *)g_sequence_get(i))->end + 1;
81         i = g_sequence_iter_next(i);
82         if (!g_sequence_iter_is_end(i))
83             range->end = ((InodeMapRange *)g_sequence_get(i))->start - 1;
84
85         g_print("Creating inode map range, 2: start=%"PRIu64" end=%"PRIu64"\n",
86                 range->start, range->end);
87         g_assert(inum >= range->start && inum <= range->end);
88
89         range->start = MAX(range->start,
90                            inum & ~(uint64_t)(target_imap_size - 1));
91         range->end = MIN(range->end, range->start + target_imap_size - 1);
92
93         g_print("Creating inode map range, 3: start=%"PRIu64" end=%"PRIu64"\n",
94                 range->start, range->end);
95
96         g_sequence_insert_sorted(inode_map, range, compare, NULL);
97     }
98
99     /* Next, try to find the entry within this range of the inode map. */
100     InodeMapEntry *entry = NULL;
101     i = g_sequence_search(range->map_entries, &inum, compare, NULL);
102     i = g_sequence_iter_prev(i);
103     if (!g_sequence_iter_is_end(i))
104         entry = (InodeMapEntry *)g_sequence_get(i);
105     if (entry == NULL || inum != entry->inum) {
106         if (action <= 0)
107             return NULL;
108
109         entry = g_new0(InodeMapEntry, 1);
110         entry->inum = inum;
111         g_sequence_insert_sorted(range->map_entries, entry, compare, NULL);
112
113         g_print("Created inode map entry for %"PRIu64"\n", inum);
114     }
115
116     if (action != 0) {
117         bluesky_cloudlog_unref_delayed(range->serialized);
118         range->serialized = NULL;
119     }
120
121     /* Were we requested to delete the item? */
122     if (action < 0) {
123         g_sequence_remove(i);
124         entry = NULL;
125     }
126
127     return entry;
128 }
129
130 /* Convert a section of the inode map to serialized form, in preparation for
131  * writing it out to the cloud. */
132 static void bluesky_inode_map_serialize_section(BlueSkyFS *fs,
133                                                 InodeMapRange *range)
134 {
135     if (range->serialized != NULL)
136         return;
137
138     GString *buf = g_string_new("");
139     BlueSkyCloudLog *log = bluesky_cloudlog_new(fs, NULL);
140     log->type = LOGTYPE_INODE_MAP;
141     log->inum = 0;
142
143     GSequenceIter *i = g_sequence_get_begin_iter(range->map_entries);
144     while (!g_sequence_iter_is_end(i)) {
145         InodeMapEntry *entry = (InodeMapEntry *)g_sequence_get(i);
146         uint64_t inum = GUINT64_TO_LE(entry->inum);
147         g_string_append_len(buf, (const char *)&inum, sizeof(inum));
148         bluesky_cloudlog_ref(entry->item);
149         g_array_append_val(log->links, entry->item);
150         i = g_sequence_iter_next(i);
151     }
152
153     log->data = bluesky_string_new_from_gstring(buf);
154     bluesky_cloudlog_unref(range->serialized);
155     range->serialized = log;
156 }
157
158 BlueSkyCloudLog *bluesky_inode_map_serialize(BlueSkyFS *fs)
159 {
160     gboolean updated = FALSE;
161     GString *buf = g_string_new("");
162     BlueSkyCloudLog *log = bluesky_cloudlog_new(fs, NULL);
163     log->type = LOGTYPE_CHECKPOINT;
164     log->inum = 0;
165
166     GSequenceIter *i = g_sequence_get_begin_iter(fs->inode_map);
167     while (!g_sequence_iter_is_end(i)) {
168         InodeMapRange *range = (InodeMapRange *)g_sequence_get(i);
169         uint64_t inum = GUINT64_TO_LE(range->start);
170         g_string_append_len(buf, (const char *)&inum, sizeof(inum));
171         inum = GUINT64_TO_LE(range->end);
172         g_string_append_len(buf, (const char *)&inum, sizeof(inum));
173
174         if (range->serialized == NULL) {
175             bluesky_inode_map_serialize_section(fs, range);
176             updated = TRUE;
177         }
178         bluesky_cloudlog_ref(range->serialized);
179         g_array_append_val(log->links, range->serialized);
180         i = g_sequence_iter_next(i);
181     }
182
183     log->data = bluesky_string_new_from_gstring(buf);
184
185     if (updated) {
186         return log;
187     } else {
188         bluesky_cloudlog_unref(log);
189         return NULL;
190     }
191 }
192
193 /* Minimize resources consumed the inode map.  This should only be called once
194  * an updated inode map has been serialized to the cloud, and will replace
195  * cloud log objects with skeletal versions that just reference the data
196  * location in the cloud (rather than pinning all object data in memory). */
197 void bluesky_inode_map_minimize(BlueSkyFS *fs)
198 {
199     GSequenceIter *i = g_sequence_get_begin_iter(fs->inode_map);
200     while (!g_sequence_iter_is_end(i)) {
201         InodeMapRange *range = (InodeMapRange *)g_sequence_get(i);
202
203         if (range->serialized != NULL)
204             bluesky_cloudlog_erase(range->serialized);
205
206         GSequenceIter *j;
207         for (j = g_sequence_get_begin_iter(range->map_entries);
208              !g_sequence_iter_is_end(j); j = g_sequence_iter_next(j))
209         {
210             InodeMapEntry *entry = (InodeMapEntry *)g_sequence_get(j);
211             BlueSkyCloudLog *item = entry->item;
212             if (item != NULL) {
213                 g_mutex_lock(item->lock);
214                 if (g_atomic_int_get(&item->refcount) == 1) {
215                     bluesky_cloudlog_erase(item);
216                 }
217                 g_mutex_unlock(item->lock);
218             } else {
219                 g_warning("Null item for inode map entry %"PRIu64"!",
220                           entry->inum);
221             }
222         }
223
224         i = g_sequence_iter_next(i);
225     }
226 }
227
228 /* Reconstruct the inode map from data stored in the cloud. */
229 static void bluesky_inode_map_deserialize(BlueSkyFS *fs, BlueSkyCloudLog *imap)
230 {
231     g_mutex_lock(imap->lock);
232     bluesky_cloudlog_fetch(imap);
233     g_assert(imap->data != NULL);
234     g_assert(imap->data->len == 16 * imap->links->len);
235     //uint64_t *inum_range = (uint64_t *)imap->data->data;
236     for (int i = 0; i < imap->links->len; i++) {
237         //int64_t start = GUINT64_FROM_LE(*inum_range++);
238         //int64_t end = GUINT64_FROM_LE(*inum_range++);
239         BlueSkyCloudLog *section = g_array_index(imap->links,
240                                                  BlueSkyCloudLog *, i);
241         g_mutex_lock(section->lock);
242         bluesky_cloudlog_fetch(section);
243         g_print("Loaded cloudlog item (%zd bytes)\n", section->data->len);
244
245         uint64_t *inum = (uint64_t *)section->data->data;
246         for (int j = 0; j < section->links->len; j++) {
247             InodeMapEntry *entry;
248             entry = bluesky_inode_map_lookup(fs->inode_map, *inum, 1);
249             entry->inum = GUINT64_FROM_LE(*inum);
250             entry->item = g_array_index(section->links,
251                                         BlueSkyCloudLog *, j);
252             bluesky_cloudlog_ref(entry->item);
253             fs->next_inum = MAX(fs->next_inum, entry->inum + 1);
254             inum++;
255         }
256         g_mutex_unlock(section->lock);
257     }
258     g_mutex_unlock(imap->lock);
259 }
260
261 /* Find the most recent checkpoint record in the cloud and reload inode map
262  * data from it to initialize the filesystem.  Returns a boolean indicating
263  * whether a checkpoint was found and loaded or not. */
264 gboolean bluesky_checkpoint_load(BlueSkyFS *fs)
265 {
266     char *last_segment = bluesky_store_lookup_last(fs->store, "log-");
267     if (last_segment == NULL)
268         return FALSE;
269
270     g_print("Last cloud log segment: %s\n", last_segment);
271     int seq = atoi(last_segment + 13);
272     fs->log_state->location.sequence = seq + 1;
273
274     BlueSkyRCStr *last = bluesky_store_get(fs->store, last_segment);
275     g_free(last_segment);
276     if (last == NULL) {
277         g_warning("Unable to fetch last log segment from cloud!");
278         return FALSE;
279     }
280
281     /* Scan through the contents of the last log segment to find a checkpoint
282      * record.  We need to do a linear scan since at this point we don't have a
283      * direct pointer; once we have the last commit record then all other data
284      * can be loaded by directly following pointers. */
285     const char *buf = last->data;
286     size_t len = last->len;
287     const char *checkpoint = NULL;
288     size_t checkpoint_size = 0;
289     while (len > sizeof(struct cloudlog_header)) {
290         struct cloudlog_header *header = (struct cloudlog_header *)buf;
291         if (memcmp(header->magic, CLOUDLOG_MAGIC, 4) != 0) {
292             g_warning("Could not parse cloudlog entry!");
293             break;
294         }
295         int size = sizeof(struct cloudlog_header);
296         size += GUINT32_FROM_LE(header->size1);
297         size += GUINT32_FROM_LE(header->size2);
298         size += GUINT32_FROM_LE(header->size3);
299         if (size > len) {
300             g_warning("Cloudlog entry is malformed (size too large)!");
301             break;
302         }
303         if (header->type - '0' == LOGTYPE_CHECKPOINT) {
304             checkpoint = buf;
305             checkpoint_size = size;
306         }
307         buf += size;
308         len -= size;
309     }
310
311     g_print("Found checkpoint record at %zd (size %zd)\n",
312             checkpoint - last->data, checkpoint_size);
313
314     /* Bootstrap the loading process by manually setting the location of this
315      * log item. */
316     BlueSkyCloudLog *commit;
317     commit = bluesky_cloudlog_get(fs,
318                                   ((struct cloudlog_header *)checkpoint)->id);
319     g_mutex_lock(commit->lock);
320     commit->location_flags |= CLOUDLOG_CLOUD;
321     commit->location.directory = 0;
322     commit->location.sequence = seq;
323     commit->location.offset = checkpoint - last->data;
324     commit->location.size = checkpoint_size;
325     g_mutex_unlock(commit->lock);
326
327     bluesky_inode_map_deserialize(fs, commit);
328     bluesky_cloudlog_unref(commit);
329
330     return TRUE;
331 }