Limit the number of concurrent log uploads to the cloud
[bluesky.git] / bluesky / cloudlog.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 <stdint.h>
11 #include <glib.h>
12 #include <string.h>
13
14 #include "bluesky-private.h"
15
16 // Rough size limit for a log segment.  This is not a firm limit and there are
17 // no absolute guarantees on the size of a log segment.
18 #define CLOUDLOG_SEGMENT_SIZE (4 << 20)
19
20 // Maximum number of segments to attempt to upload concurrently
21 int cloudlog_concurrent_uploads = 32;
22
23 BlueSkyCloudID bluesky_cloudlog_new_id()
24 {
25     BlueSkyCloudID id;
26     bluesky_crypt_random_bytes((uint8_t *)&id.bytes, sizeof(id));
27     return id;
28 }
29
30 gchar *bluesky_cloudlog_id_to_string(BlueSkyCloudID id)
31 {
32     char buf[sizeof(BlueSkyCloudID) * 2 + 1];
33     buf[0] = '\0';
34
35     for (int i = 0; i < sizeof(BlueSkyCloudID); i++) {
36         sprintf(&buf[2*i], "%02x", (uint8_t)(id.bytes[i]));
37     }
38
39     return g_strdup(buf);
40 }
41
42 BlueSkyCloudID bluesky_cloudlog_id_from_string(const gchar *idstr)
43 {
44     BlueSkyCloudID id;
45     memset(&id, 0, sizeof(id));
46     for (int i = 0; i < 2*sizeof(BlueSkyCloudID); i++) {
47         char c = idstr[i];
48         if (c == '\0') {
49             g_warning("Short cloud id: %s\n", idstr);
50             break;
51         }
52         int val = 0;
53         if (c >= '0' && c <= '9')
54             val = c - '0';
55         else if (c >= 'a' && c <= 'f')
56             val = c - 'a' + 10;
57         else
58             g_warning("Bad character in cloud id: %s\n", idstr);
59         id.bytes[i / 2] += val << (i % 2 ? 0 : 4);
60     }
61     return id;
62 }
63
64 gboolean bluesky_cloudlog_equal(gconstpointer a, gconstpointer b)
65 {
66     BlueSkyCloudID *id1 = (BlueSkyCloudID *)a, *id2 = (BlueSkyCloudID *)b;
67
68     return memcmp(id1, id2, sizeof(BlueSkyCloudID)) == 0;
69 }
70
71 guint bluesky_cloudlog_hash(gconstpointer a)
72 {
73     BlueSkyCloudID *id = (BlueSkyCloudID *)a;
74
75     // Assume that bits in the ID are randomly chosen so that any subset of the
76     // bits can be used as a hash key.
77     return *(guint *)(&id->bytes);
78 }
79
80 /* Formatting of cloud log segments.  This handles grouping items together
81  * before writing a batch to the cloud, handling indirection through items like
82  * the inode map, etc. */
83
84 BlueSkyCloudLog *bluesky_cloudlog_new(BlueSkyFS *fs, const BlueSkyCloudID *id)
85 {
86     BlueSkyCloudLog *log = g_new0(BlueSkyCloudLog, 1);
87
88     log->lock = g_mutex_new();
89     log->cond = g_cond_new();
90     log->fs = fs;
91     log->type = LOGTYPE_UNKNOWN;
92     if (id != NULL)
93         memcpy(&log->id, id, sizeof(BlueSkyCloudID));
94     else
95         log->id = bluesky_cloudlog_new_id();
96     log->links = g_array_new(FALSE, TRUE, sizeof(BlueSkyCloudLog *));
97     g_atomic_int_set(&log->refcount, 1);
98
99     return log;
100 }
101
102 /* Helper function for updating memory usage statistics for a filesystem (the
103  * cache_log_* variables).  This will increment (type=1) or decrement (type=-1)
104  * the counter associated with the current state of the cloud log item.  The
105  * item should be locked or otherwise protected from concurrent access. */
106 void bluesky_cloudlog_stats_update(BlueSkyCloudLog *log, int type)
107 {
108     BlueSkyFS *fs = log->fs;
109
110     if (log->location_flags & CLOUDLOG_CLOUD) {
111         g_atomic_int_add(&fs->cache_log_cloud, type);
112     } else if (log->location_flags & CLOUDLOG_JOURNAL) {
113         g_atomic_int_add(&fs->cache_log_journal, type);
114     } else if (log->pending_write & CLOUDLOG_JOURNAL) {
115         g_atomic_int_add(&fs->cache_log_journal, type);
116     } else if (log->data != NULL) {
117         g_atomic_int_add(&fs->cache_log_dirty, type);
118     }
119 }
120
121 /* The reference held by the hash table does not count towards the reference
122  * count.  When a new object is created, it initially has a reference count of
123  * 1 for the creator, and similarly fetching an item from the hash table will
124  * also create a reference.  If the reference count drops to zero,
125  * bluesky_cloudlog_unref attempts to remove the object from the hash
126  * table--but there is a potential race since another thread might read the
127  * object from the hash table at the same time.  So an object with a reference
128  * count of zero may still be resurrected, in which case we need to abort the
129  * destruction.  Once the object is gone from the hash table, and if the
130  * reference count is still zero, it can actually be deleted. */
131 void bluesky_cloudlog_ref(BlueSkyCloudLog *log)
132 {
133     if (log == NULL)
134         return;
135
136     g_atomic_int_inc(&log->refcount);
137 }
138
139 void bluesky_cloudlog_unref(BlueSkyCloudLog *log)
140 {
141     if (log == NULL)
142         return;
143
144     if (g_atomic_int_dec_and_test(&log->refcount)) {
145         BlueSkyFS *fs = log->fs;
146
147         g_mutex_lock(fs->lock);
148         if (g_atomic_int_get(&log->refcount) > 0) {
149             g_mutex_unlock(fs->lock);
150             return;
151         }
152
153         if (!g_hash_table_remove(fs->locations, &log->id)) {
154             if (bluesky_verbose)
155                 g_warning("Could not find and remove cloud log item from hash table!");
156         }
157         g_mutex_unlock(fs->lock);
158
159         bluesky_cloudlog_stats_update(log, -1);
160         log->type = LOGTYPE_INVALID;
161         g_mutex_free(log->lock);
162         g_cond_free(log->cond);
163         for (int i = 0; i < log->links->len; i++) {
164             BlueSkyCloudLog *c = g_array_index(log->links,
165                                                BlueSkyCloudLog *, i);
166             bluesky_cloudlog_unref(c);
167         }
168         g_array_unref(log->links);
169         bluesky_string_unref(log->data);
170         g_free(log);
171     }
172 }
173
174 /* For locking reasons cloudlog unrefs may sometimes need to be performed in
175  * the future.  We launch a thread for handling these delayed unreference
176  * requests. */
177 static gpointer cloudlog_unref_thread(gpointer q)
178 {
179     GAsyncQueue *queue = (GAsyncQueue *)q;
180
181     while (TRUE) {
182         BlueSkyCloudLog *item = (BlueSkyCloudLog *)g_async_queue_pop(queue);
183         bluesky_cloudlog_unref(item);
184     }
185
186     return NULL;
187 }
188
189 void bluesky_cloudlog_unref_delayed(BlueSkyCloudLog *log)
190 {
191     if (log != NULL)
192         g_async_queue_push(log->fs->unref_queue, log);
193 }
194
195 void bluesky_cloudlog_threads_init(BlueSkyFS *fs)
196 {
197     fs->unref_queue = g_async_queue_new();
198     g_thread_create(cloudlog_unref_thread, fs->unref_queue, FALSE, NULL);
199 }
200
201 /* Erase the information contained within the in-memory cloud log
202  * representation.  This does not free up the item itself, but frees the data
203  * and references to other log items and resets the type back to unknown.  If
204  * the object was written out to persistent storage, all state about it can be
205  * recovered by loading the object back in.  The object must be locked before
206  * calling this function. */
207 void bluesky_cloudlog_erase(BlueSkyCloudLog *log)
208 {
209     g_assert(log->data_lock_count == 0);
210
211     if (log->type == LOGTYPE_UNKNOWN)
212         return;
213
214     log->type = LOGTYPE_UNKNOWN;
215     log->data_size = 0;
216     bluesky_string_unref(log->data);
217     log->data = NULL;
218     log->data_lock_count = 0;
219
220     for (int i = 0; i < log->links->len; i++) {
221         BlueSkyCloudLog *c = g_array_index(log->links,
222                                            BlueSkyCloudLog *, i);
223         bluesky_cloudlog_unref(c);
224     }
225     g_array_unref(log->links);
226     log->links = g_array_new(FALSE, TRUE, sizeof(BlueSkyCloudLog *));
227 }
228
229 /* Start a write of the object to the local log. */
230 void bluesky_cloudlog_sync(BlueSkyCloudLog *log)
231 {
232     bluesky_log_item_submit(log, log->fs->log);
233 }
234
235 /* Add the given entry to the global hash table containing cloud log entries.
236  * Takes ownership of the caller's reference. */
237 void bluesky_cloudlog_insert_locked(BlueSkyCloudLog *log)
238 {
239     g_hash_table_insert(log->fs->locations, &log->id, log);
240 }
241
242 void bluesky_cloudlog_insert(BlueSkyCloudLog *log)
243 {
244     g_mutex_lock(log->fs->lock);
245     bluesky_cloudlog_insert_locked(log);
246     g_mutex_unlock(log->fs->lock);
247 }
248
249 /* Look up the cloud log entry for the given ID.  If create is TRUE and the
250  * item does not exist, create a special pending entry that can later be filled
251  * in when the real item is loaded.  The returned item has a reference held.
252  * As a special case, if a null ID is provided then NULL is returned. */
253 BlueSkyCloudLog *bluesky_cloudlog_get(BlueSkyFS *fs, BlueSkyCloudID id)
254 {
255     static BlueSkyCloudID id0 = {{0}};
256
257     if (memcmp(&id, &id0, sizeof(BlueSkyCloudID)) == 0)
258         return NULL;
259
260     g_mutex_lock(fs->lock);
261     BlueSkyCloudLog *item;
262     item = g_hash_table_lookup(fs->locations, &id);
263     if (item == NULL) {
264         item = bluesky_cloudlog_new(fs, &id);
265         bluesky_cloudlog_stats_update(item, 1);
266         bluesky_cloudlog_insert_locked(item);
267     } else {
268         bluesky_cloudlog_ref(item);
269     }
270     g_mutex_unlock(fs->lock);
271     return item;
272 }
273
274 /* Attempt to prefetch a cloud log item.  This does not guarantee that it will
275  * be made available, but does make it more likely that a future call to
276  * bluesky_cloudlog_fetch will complete quickly.  Item must be locked? */
277 void bluesky_cloudlog_prefetch(BlueSkyCloudLog *item)
278 {
279     if (item->data != NULL)
280         return;
281
282     /* TODO: Some of the code here is duplicated with bluesky_log_map_object.
283      * Refactor to fix that. */
284     BlueSkyFS *fs = item->fs;
285     BlueSkyCacheFile *map = NULL;
286
287     /* First, check to see if the journal still contains a copy of the item and
288      * if so update the atime on the journal so it is likely to be kept around
289      * until we need it. */
290     if ((item->location_flags | item->pending_write) & CLOUDLOG_JOURNAL) {
291         map = bluesky_cachefile_lookup(fs, -1, item->log_seq, TRUE);
292         if (map != NULL) {
293             map->atime = bluesky_get_current_time();
294             bluesky_cachefile_unref(map);
295             g_mutex_unlock(map->lock);
296             return;
297         }
298     }
299
300     item->location_flags &= ~CLOUDLOG_JOURNAL;
301     if (!(item->location_flags & CLOUDLOG_CLOUD))
302         return;
303
304     map = bluesky_cachefile_lookup(fs,
305                                    item->location.directory,
306                                    item->location.sequence,
307                                    FALSE);
308     if (map == NULL)
309         return;
310
311     /* At this point, we have information about the log segment containing the
312      * item we need.  If our item is already fetched, we have nothing to do
313      * except update the atime.  If not, queue up a fetch of our object. */
314     const BlueSkyRangesetItem *rangeitem;
315     rangeitem = bluesky_rangeset_lookup(map->items,
316                                         item->location.offset);
317     if (rangeitem == NULL) {
318         if (map->prefetches == NULL)
319             map->prefetches = bluesky_rangeset_new();
320
321         gchar *id = bluesky_cloudlog_id_to_string(item->id);
322         if (bluesky_verbose)
323             g_print("Need to prefetch %s\n", id);
324         g_free(id);
325
326         bluesky_rangeset_insert(map->prefetches,
327                                 item->location.offset,
328                                 item->location.size, NULL);
329
330         uint64_t start, length;
331         bluesky_rangeset_get_extents(map->prefetches, &start, &length);
332         if (bluesky_verbose)
333             g_print("Range to prefetch: %"PRIu64" + %"PRIu64"\n",
334                     start, length);
335     }
336
337     bluesky_cachefile_unref(map);
338     g_mutex_unlock(map->lock);
339 }
340
341 /* Ensure that a cloud log item is loaded in memory, and if not read it in.
342  * TODO: Make asynchronous, and make this also fetch from the cloud.  Right now
343  * we only read from the log.  Log item must be locked. */
344 void bluesky_cloudlog_fetch(BlueSkyCloudLog *log)
345 {
346     if (log->data != NULL)
347         return;
348
349     BlueSkyProfile *profile = bluesky_profile_get();
350     if (profile != NULL)
351         bluesky_profile_add_event(profile, g_strdup_printf("Fetch log entry"));
352
353     /* There are actually two cases: a full deserialization if we have not ever
354      * read the object before, and a partial deserialization where the metadata
355      * is already in memory and we just need to remap the data.  If the object
356      * type has not yet been set, we'll need to read and parse the metadata.
357      * Once that is done, we can fall through the case of remapping the data
358      * itself. */
359     if (log->type == LOGTYPE_UNKNOWN) {
360         BlueSkyRCStr *raw = bluesky_log_map_object(log, FALSE);
361         g_assert(raw != NULL);
362         bluesky_deserialize_cloudlog(log, raw->data, raw->len);
363         bluesky_string_unref(raw);
364     }
365
366     /* At this point all metadata should be available and we need only remap
367      * the object data. */
368     log->data = bluesky_log_map_object(log, TRUE);
369
370     if (log->data == NULL) {
371         g_error("Unable to fetch cloudlog entry!");
372     }
373
374     if (profile != NULL)
375         bluesky_profile_add_event(profile, g_strdup_printf("Fetch complete"));
376     g_cond_broadcast(log->cond);
377 }
378
379 BlueSkyCloudPointer bluesky_cloudlog_serialize(BlueSkyCloudLog *log,
380                                                BlueSkyFS *fs)
381 {
382     BlueSkyCloudLogState *state = fs->log_state;
383
384     if ((log->location_flags | log->pending_write) & CLOUDLOG_CLOUD) {
385         return log->location;
386     }
387
388     for (int i = 0; i < log->links->len; i++) {
389         BlueSkyCloudLog *ref = g_array_index(log->links,
390                                              BlueSkyCloudLog *, i);
391         if (ref != NULL)
392             bluesky_cloudlog_serialize(ref, fs);
393     }
394
395     /* FIXME: Ought lock to be taken earlier? */
396     g_mutex_lock(log->lock);
397     bluesky_cloudlog_fetch(log);
398     g_assert(log->data != NULL);
399
400     bluesky_cloudlog_stats_update(log, -1);
401
402     GString *data1 = g_string_new("");
403     GString *data2 = g_string_new("");
404     GString *data3 = g_string_new("");
405     bluesky_serialize_cloudlog(log, data1, data2, data3);
406
407     log->location = state->location;
408     log->location.offset = state->data->len;
409     log->data_size = data1->len;
410
411     struct cloudlog_header header;
412     memcpy(header.magic, CLOUDLOG_MAGIC, 4);
413     memset(header.crypt_auth, sizeof(header.crypt_auth), 0);
414     memset(header.crypt_iv, sizeof(header.crypt_iv), 0);
415     header.type = log->type + '0';
416     header.size1 = GUINT32_TO_LE(data1->len);
417     header.size2 = GUINT32_TO_LE(data2->len);
418     header.size3 = GUINT32_TO_LE(data3->len);
419     header.id = log->id;
420     header.inum = GUINT64_TO_LE(log->inum);
421
422     g_string_append_len(state->data, (const char *)&header, sizeof(header));
423     g_string_append_len(state->data, data1->str, data1->len);
424     g_string_append_len(state->data, data2->str, data2->len);
425     g_string_append_len(state->data, data3->str, data3->len);
426
427     log->location.size = state->data->len - log->location.offset;
428
429     g_string_free(data1, TRUE);
430     g_string_free(data2, TRUE);
431     g_string_free(data3, TRUE);
432
433     /* If the object we flushed was an inode, update the inode map. */
434     if (log->type == LOGTYPE_INODE) {
435         g_mutex_lock(fs->lock);
436         InodeMapEntry *entry = bluesky_inode_map_lookup(fs->inode_map,
437                                                         log->inum, 1);
438         bluesky_cloudlog_unref_delayed(entry->item);
439         entry->item = log;
440         bluesky_cloudlog_ref(entry->item);
441         g_mutex_unlock(fs->lock);
442     }
443
444     /* TODO: We should mark the objects as committed on the cloud until the
445      * data is flushed and acknowledged. */
446     log->pending_write |= CLOUDLOG_CLOUD;
447     bluesky_cloudlog_stats_update(log, 1);
448     state->writeback_list = g_slist_prepend(state->writeback_list, log);
449     bluesky_cloudlog_ref(log);
450     g_mutex_unlock(log->lock);
451
452     if (state->data->len > CLOUDLOG_SEGMENT_SIZE)
453         bluesky_cloudlog_flush(fs);
454
455     return log->location;
456 }
457
458 static void cloudlog_flush_complete(BlueSkyStoreAsync *async,
459                                     SerializedRecord *record)
460 {
461     g_print("Write of %s to cloud complete, status = %d\n",
462             async->key, async->result);
463
464     g_mutex_lock(record->lock);
465     if (async->result >= 0) {
466         while (record->items != NULL) {
467             BlueSkyCloudLog *item = (BlueSkyCloudLog *)record->items->data;
468             g_mutex_lock(item->lock);
469             bluesky_cloudlog_stats_update(item, -1);
470             item->pending_write &= ~CLOUDLOG_CLOUD;
471             item->location_flags |= CLOUDLOG_CLOUD;
472             bluesky_cloudlog_stats_update(item, 1);
473             g_mutex_unlock(item->lock);
474             bluesky_cloudlog_unref(item);
475
476             record->items = g_slist_delete_link(record->items, record->items);
477         }
478
479         bluesky_string_unref(record->data);
480         record->data = NULL;
481         g_slist_free(record->items);
482         record->items = NULL;
483         record->complete = TRUE;
484
485         BlueSkyCloudLogState *state = record->fs->log_state;
486         g_mutex_lock(state->uploads_pending_lock);
487         state->uploads_pending--;
488         g_cond_broadcast(state->uploads_pending_cond);
489         g_mutex_unlock(state->uploads_pending_lock);
490
491         g_cond_broadcast(record->cond);
492     } else {
493         g_print("Write should be resubmitted...\n");
494
495         BlueSkyStoreAsync *async2 = bluesky_store_async_new(async->store);
496         async2->op = STORE_OP_PUT;
497         async2->key = g_strdup(async->key);
498         async2->data = record->data;
499         async2->profile = async->profile;
500         bluesky_string_ref(record->data);
501         bluesky_store_async_submit(async2);
502         bluesky_store_async_add_notifier(async2,
503                                          (GFunc)cloudlog_flush_complete,
504                                          record);
505         bluesky_store_async_unref(async2);
506     }
507     g_mutex_unlock(record->lock);
508 }
509
510 /* Finish up a partially-written cloud log segment and flush it to storage. */
511 static void cloud_flush_background(SerializedRecord *record)
512 {
513     bluesky_cloudlog_encrypt(record->raw_data, record->fs->keys);
514     record->data = bluesky_string_new_from_gstring(record->raw_data);
515     record->raw_data = NULL;
516
517     BlueSkyStoreAsync *async = bluesky_store_async_new(record->fs->store);
518     async->op = STORE_OP_PUT;
519     async->key = record->key;
520     async->data = record->data;
521     bluesky_string_ref(record->data);
522     bluesky_store_async_submit(async);
523     bluesky_store_async_add_notifier(async,
524                                      (GFunc)cloudlog_flush_complete,
525                                      record);
526     bluesky_store_async_unref(async);
527 }
528
529 void bluesky_cloudlog_flush(BlueSkyFS *fs)
530 {
531     BlueSkyCloudLogState *state = fs->log_state;
532     if (state->data == NULL || state->data->len == 0)
533         return;
534
535     g_mutex_lock(state->uploads_pending_lock);
536     while (state->uploads_pending > cloudlog_concurrent_uploads)
537         g_cond_wait(state->uploads_pending_cond, state->uploads_pending_lock);
538     state->uploads_pending++;
539     g_mutex_unlock(state->uploads_pending_lock);
540
541     /* TODO: Append some type of commit record to the log segment? */
542
543     g_print("Serializing %zd bytes of data to cloud\n", state->data->len);
544     SerializedRecord *record = g_new0(SerializedRecord, 1);
545     record->fs = fs;
546     record->raw_data = state->data;
547     record->data = NULL;
548     record->items = state->writeback_list;
549     record->lock = g_mutex_new();
550     record->cond = g_cond_new();
551     state->writeback_list = NULL;
552
553     record->key = g_strdup_printf("log-%08d-%08d",
554                                   state->location.directory,
555                                   state->location.sequence);
556
557     state->pending_segments = g_list_prepend(state->pending_segments, record);
558
559     /* Encryption of data and upload happen in the background, for additional
560      * parallelism when uploading large amounts of data. */
561     g_thread_create((GThreadFunc)cloud_flush_background, record, FALSE, NULL);
562
563     state->location.sequence++;
564     state->location.offset = 0;
565     state->data = g_string_new("");
566 }
567
568 /* Make an encryption pass over a cloud log segment to encrypt private data in
569  * it. */
570 void bluesky_cloudlog_encrypt(GString *segment, BlueSkyCryptKeys *keys)
571 {
572     char *data = segment->str;
573     size_t remaining_size = segment->len;
574
575     while (remaining_size >= sizeof(struct cloudlog_header)) {
576         struct cloudlog_header *header = (struct cloudlog_header *)data;
577         size_t item_size = sizeof(struct cloudlog_header)
578                            + GUINT32_FROM_LE(header->size1)
579                            + GUINT32_FROM_LE(header->size2)
580                            + GUINT32_FROM_LE(header->size3);
581         if (item_size > remaining_size)
582             break;
583         bluesky_crypt_block_encrypt(data, item_size, keys);
584
585         data += item_size;
586         remaining_size -= item_size;
587     }
588 }
589
590 /* Make an decryption pass over a cloud log segment to decrypt items which were
591  * encrypted.  Also computes a list of all offsets which at which valid
592  * cloud log items are found and adds those offsets to items (if non-NULL).
593  *
594  * If allow_unauth is set to true, then allow a limited set of unauthenticated
595  * items that may have been rewritten by a file system cleaner.  These include
596  * the checkpoint and inode map records only; other items must still pass
597  * authentication. */
598 void bluesky_cloudlog_decrypt(char *segment, size_t len,
599                               BlueSkyCryptKeys *keys,
600                               BlueSkyRangeset *items,
601                               gboolean allow_unauth)
602 {
603     char *data = segment;
604     size_t remaining_size = len;
605     size_t offset = 0;
606
607     while (remaining_size >= sizeof(struct cloudlog_header)) {
608         struct cloudlog_header *header = (struct cloudlog_header *)data;
609         size_t item_size = sizeof(struct cloudlog_header)
610                            + GUINT32_FROM_LE(header->size1)
611                            + GUINT32_FROM_LE(header->size2)
612                            + GUINT32_FROM_LE(header->size3);
613         if (item_size > remaining_size)
614             break;
615         if (bluesky_crypt_block_decrypt(data, item_size, keys, allow_unauth)) {
616             if (items != NULL) {
617                 if (bluesky_verbose)
618                     g_print("  data item at %zx\n", offset);
619                 bluesky_rangeset_insert(items, offset, item_size,
620                                         GINT_TO_POINTER(TRUE));
621             }
622         } else {
623             g_warning("Unauthenticated data at offset %zd", offset);
624             if (items != NULL) {
625                 bluesky_rangeset_insert(items, offset, item_size,
626                                         GINT_TO_POINTER(TRUE));
627             }
628         }
629
630         data += item_size;
631         offset += item_size;
632         remaining_size -= item_size;
633     }
634 }