subrascasse

Sub Rascasse: an iPhone dive log for Subsurface cloud storage, with a pure-Swift git client (GPL-2.0)
git clone https://git.schurger.org/subrascasse.git
Log | Files | Refs | README | LICENSE

oceanic_common.c (23732B)


      1 /*
      2  * libdivecomputer
      3  *
      4  * Copyright (C) 2009 Jef Driesen
      5  *
      6  * This library is free software; you can redistribute it and/or
      7  * modify it under the terms of the GNU Lesser General Public
      8  * License as published by the Free Software Foundation; either
      9  * version 2.1 of the License, or (at your option) any later version.
     10  *
     11  * This library is distributed in the hope that it will be useful,
     12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
     13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
     14  * Lesser General Public License for more details.
     15  *
     16  * You should have received a copy of the GNU Lesser General Public
     17  * License along with this library; if not, write to the Free Software
     18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
     19  * MA 02110-1301 USA
     20  */
     21 
     22 #include <string.h> // memcpy, memmove
     23 #include <stdlib.h> // malloc, free
     24 #include <assert.h> // assert
     25 
     26 #include "oceanic_common.h"
     27 #include "context-private.h"
     28 #include "device-private.h"
     29 #include "ringbuffer.h"
     30 #include "rbstream.h"
     31 #include "array.h"
     32 
     33 #define VTABLE(abstract)	((const oceanic_common_device_vtable_t *) abstract->vtable)
     34 
     35 #define RB_LOGBOOK_DISTANCE(a,b,l,m) ringbuffer_distance (a, b, m, l->rb_logbook_begin, l->rb_logbook_end)
     36 
     37 #define RB_PROFILE_DISTANCE(a,b,l,m) ringbuffer_distance (a, b, m, l->rb_profile_begin, l->rb_profile_end)
     38 
     39 #define INVALID 0
     40 
     41 static dc_status_t
     42 oceanic_common_device_get_profile (const unsigned char data[], const oceanic_common_layout_t *layout, unsigned int *begin, unsigned int *end)
     43 {
     44 	assert (layout != NULL);
     45 	assert (begin != NULL && end != NULL);
     46 
     47 	// Get the pagesize
     48 	unsigned int pagesize = layout->highmem ? 16 * PAGESIZE : PAGESIZE;
     49 
     50 	// Get the profile pointers.
     51 	unsigned int first = 0, last = 0;
     52 	if (layout->pt_mode_logbook == 0) {
     53 		first = array_uint16_le (data + 5);
     54 		last  = array_uint16_le (data + 6) >> 4;
     55 	} else if (layout->pt_mode_logbook == 1) {
     56 		first = array_uint16_le (data + 4);
     57 		last  = array_uint16_le (data + 6);
     58 	} else if (layout->pt_mode_logbook == 2 || layout->pt_mode_logbook == 3) {
     59 		first = array_uint16_le (data + 16);
     60 		last  = array_uint16_le (data + 18);
     61 	} else if (layout->pt_mode_logbook == 4) {
     62 		first = array_uint32_le (data + 8);
     63 		last  = array_uint32_le (data + 12);
     64 	}
     65 
     66 	// Convert pages to bytes.
     67 	if (layout->pt_mode_logbook < 3) {
     68 		unsigned int npages = (layout->memsize - layout->highmem) / pagesize;
     69 		if (npages > 0x4000) {
     70 			first &= 0x7FFF;
     71 			last  &= 0x7FFF;
     72 		} else if (npages > 0x2000) {
     73 			first &= 0x3FFF;
     74 			last  &= 0x3FFF;
     75 		} else if (npages > 0x1000) {
     76 			first &= 0x1FFF;
     77 			last  &= 0x1FFF;
     78 		} else {
     79 			first &= 0x0FFF;
     80 			last  &= 0x0FFF;
     81 		}
     82 
     83 		first *= pagesize;
     84 		last  *= pagesize;
     85 	}
     86 
     87 	*begin = layout->highmem + first;
     88 	*end   = layout->highmem + last + (layout->pt_mode_logbook < 4 ? pagesize : 0);
     89 
     90 	return DC_STATUS_SUCCESS;
     91 }
     92 
     93 
     94 static int
     95 oceanic_common_match_pattern (const unsigned char *string, const unsigned char *pattern, unsigned int *firmware)
     96 {
     97 	unsigned int value = 0;
     98 	unsigned int count = 0;
     99 
    100 	for (unsigned int i = 0; i < PAGESIZE; ++i, ++pattern, ++string) {
    101 		if (*pattern != '\0') {
    102 			// Compare the pattern.
    103 			if (*pattern != *string)
    104 				return 0;
    105 		} else {
    106 			// Extract the firmware version.
    107 			// This is based on the assumption that (only) the first block of
    108 			// zeros in the pattern contains the firmware version.
    109 			if (i == 0 || *(pattern - 1) != '\0')
    110 				count++;
    111 			if (count == 1) {
    112 				value <<= 8;
    113 				value |= *string;
    114 			}
    115 		}
    116 	}
    117 
    118 	if (firmware) {
    119 		*firmware = value;
    120 	}
    121 
    122 	return 1;
    123 }
    124 
    125 const oceanic_common_version_t *
    126 oceanic_common_match (const unsigned char *version, const oceanic_common_version_t patterns[], size_t n, unsigned int *firmware)
    127 {
    128 	for (size_t i = 0; i < n; ++i) {
    129 		unsigned int fw = 0;
    130 		if (oceanic_common_match_pattern (version, patterns[i].pattern, &fw) &&
    131 			fw >= patterns[i].firmware)
    132 		{
    133 			if (firmware) {
    134 				*firmware = fw;
    135 			}
    136 			return patterns + i;
    137 		}
    138 	}
    139 
    140 	return NULL;
    141 }
    142 
    143 
    144 void
    145 oceanic_common_device_init (oceanic_common_device_t *device)
    146 {
    147 	assert (device != NULL);
    148 
    149 	// Set the default values.
    150 	device->firmware = 0;
    151 	memset (device->version, 0, sizeof (device->version));
    152 	memset (device->fingerprint, 0, sizeof (device->fingerprint));
    153 	device->model = 0;
    154 	device->layout = NULL;
    155 	device->multipage = 1;
    156 }
    157 
    158 
    159 dc_status_t
    160 oceanic_common_device_set_fingerprint (dc_device_t *abstract, const unsigned char data[], unsigned int size)
    161 {
    162 	oceanic_common_device_t *device = (oceanic_common_device_t *) abstract;
    163 
    164 	assert (device != NULL);
    165 	assert (device->layout != NULL);
    166 	assert (device->layout->rb_logbook_entry_size <= sizeof (device->fingerprint));
    167 
    168 	unsigned int fpsize = device->layout->rb_logbook_entry_size;
    169 
    170 	if (size && size != fpsize)
    171 		return DC_STATUS_INVALIDARGS;
    172 
    173 	if (size)
    174 		memcpy (device->fingerprint, data, fpsize);
    175 	else
    176 		memset (device->fingerprint, 0, fpsize);
    177 
    178 	return DC_STATUS_SUCCESS;
    179 }
    180 
    181 
    182 dc_status_t
    183 oceanic_common_device_dump (dc_device_t *abstract, dc_buffer_t *buffer)
    184 {
    185 	dc_status_t status = DC_STATUS_SUCCESS;
    186 	oceanic_common_device_t *device = (oceanic_common_device_t *) abstract;
    187 
    188 	assert (device != NULL);
    189 	assert (device->layout != NULL);
    190 
    191 	const oceanic_common_layout_t *layout = device->layout;
    192 
    193 	// Allocate the required amount of memory.
    194 	if (!dc_buffer_resize (buffer, layout->memsize)) {
    195 		ERROR (abstract->context, "Insufficient buffer space available.");
    196 		return DC_STATUS_NOMEMORY;
    197 	}
    198 
    199 	// Read the device info.
    200 	status = VTABLE(abstract)->devinfo (abstract, NULL);
    201 	if (status != DC_STATUS_SUCCESS) {
    202 		return status;
    203 	}
    204 
    205 	// Download the memory dump.
    206 	status = device_dump_read (abstract, 0, dc_buffer_get_data (buffer),
    207 		dc_buffer_get_size (buffer), PAGESIZE * device->multipage);
    208 	if (status != DC_STATUS_SUCCESS) {
    209 		return status;
    210 	}
    211 
    212 	return status;
    213 }
    214 
    215 
    216 dc_status_t
    217 oceanic_common_device_devinfo (dc_device_t *abstract, dc_event_progress_t *progress)
    218 {
    219 	dc_status_t status = DC_STATUS_SUCCESS;
    220 	oceanic_common_device_t *device = (oceanic_common_device_t *) abstract;
    221 
    222 	assert (device != NULL);
    223 	assert (device->layout != NULL);
    224 
    225 	const oceanic_common_layout_t *layout = device->layout;
    226 
    227 	// Read the device id.
    228 	unsigned char id[PAGESIZE] = {0};
    229 	status = dc_device_read (abstract, layout->cf_devinfo, id, sizeof (id));
    230 	if (status != DC_STATUS_SUCCESS) {
    231 		ERROR (abstract->context, "Failed to read the memory page.");
    232 		return status;
    233 	}
    234 
    235 	// Update and emit a progress event.
    236 	if (progress) {
    237 		progress->current += PAGESIZE;
    238 		progress->maximum += PAGESIZE;
    239 		device_event_emit (abstract, DC_EVENT_PROGRESS, progress);
    240 	}
    241 
    242 	// Emit a vendor event.
    243 	dc_event_vendor_t vendor;
    244 	vendor.data = device->version;
    245 	vendor.size = sizeof (device->version);
    246 	device_event_emit (abstract, DC_EVENT_VENDOR, &vendor);
    247 
    248 	// Emit a device info event.
    249 	dc_event_devinfo_t devinfo;
    250 	devinfo.model = array_uint16_be (id + 8);
    251 	devinfo.firmware = device->firmware;
    252 	if (layout->pt_mode_serial == 0)
    253 		devinfo.serial = array_convert_bcd2dec (id + 10, 3);
    254 	else if (layout->pt_mode_serial == 1)
    255 		devinfo.serial = array_convert_bin2dec (id + 11, 3);
    256 	else
    257 		devinfo.serial =
    258 			(id[11] & 0x0F) * 100000 + ((id[11] & 0xF0) >> 4) * 10000 +
    259 			(id[12] & 0x0F) * 1000   + ((id[12] & 0xF0) >> 4) * 100 +
    260 			(id[13] & 0x0F) * 10     + ((id[13] & 0xF0) >> 4) * 1;
    261 	device_event_emit (abstract, DC_EVENT_DEVINFO, &devinfo);
    262 
    263 	return status;
    264 }
    265 
    266 
    267 dc_status_t
    268 oceanic_common_device_pointers (dc_device_t *abstract, dc_event_progress_t *progress,
    269 	unsigned int *rb_logbook_begin, unsigned int *rb_logbook_end,
    270 	unsigned int *rb_profile_begin, unsigned int *rb_profile_end)
    271 {
    272 	dc_status_t status = DC_STATUS_SUCCESS;
    273 	oceanic_common_device_t *device = (oceanic_common_device_t *) abstract;
    274 
    275 	assert (device != NULL);
    276 	assert (device->layout != NULL);
    277 	assert (rb_logbook_begin != NULL && rb_logbook_end != NULL);
    278 	assert (rb_profile_begin != NULL && rb_profile_end != NULL);
    279 
    280 	const oceanic_common_layout_t *layout = device->layout;
    281 
    282 	// Read the pointer data.
    283 	unsigned char pointers[PAGESIZE] = {0};
    284 	status = dc_device_read (abstract, layout->cf_pointers, pointers, sizeof (pointers));
    285 	if (status != DC_STATUS_SUCCESS) {
    286 		ERROR (abstract->context, "Failed to read the memory page.");
    287 		return status;
    288 	}
    289 
    290 	// Update and emit a progress event.
    291 	if (progress) {
    292 		progress->current += PAGESIZE;
    293 		progress->maximum += PAGESIZE;
    294 		device_event_emit (abstract, DC_EVENT_PROGRESS, progress);
    295 	}
    296 
    297 	// Get the pointers.
    298 	unsigned int rb_logbook_first = array_uint16_le (pointers + 4);
    299 	unsigned int rb_logbook_last  = array_uint16_le (pointers + 6);
    300 	unsigned int rb_profile_first = array_uint16_le (pointers + 8);
    301 	unsigned int rb_profile_last  = array_uint16_le (pointers + 10);
    302 
    303 	*rb_logbook_begin = rb_logbook_first;
    304 	*rb_logbook_end   = rb_logbook_last + (layout->pt_mode_global == 0 ? layout->rb_logbook_entry_size : 0);
    305 	*rb_profile_begin = rb_profile_first;
    306 	*rb_profile_end   = rb_profile_last;
    307 
    308 	return status;
    309 }
    310 
    311 dc_status_t
    312 oceanic_common_device_logbook (dc_device_t *abstract, dc_event_progress_t *progress, dc_buffer_t *logbook, unsigned int begin, unsigned int end)
    313 {
    314 	oceanic_common_device_t *device = (oceanic_common_device_t *) abstract;
    315 	dc_status_t rc = DC_STATUS_SUCCESS;
    316 
    317 	assert (device != NULL);
    318 	assert (device->layout != NULL);
    319 	assert (device->layout->rb_logbook_entry_size <= sizeof (device->fingerprint));
    320 	assert (progress != NULL);
    321 
    322 	const oceanic_common_layout_t *layout = device->layout;
    323 
    324 	// Erase the buffer.
    325 	if (!dc_buffer_clear (logbook))
    326 		return DC_STATUS_NOMEMORY;
    327 
    328 	// Validate the logbook pointers.
    329 	unsigned int rb_logbook_begin = begin;
    330 	unsigned int rb_logbook_end   = end;
    331 	if (rb_logbook_begin < layout->rb_logbook_begin ||
    332 		rb_logbook_begin > layout->rb_logbook_end)
    333 	{
    334 		ERROR (abstract->context, "Invalid logbook begin pointer detected (0x%04x).", rb_logbook_begin);
    335 		if (layout->rb_logbook_direction == 0) {
    336 			return DC_STATUS_DATAFORMAT;
    337 		}
    338 		// Fall back to downloading the entire logbook ringbuffer as
    339 		// workaround for an invalid logbook begin pointer!
    340 		rb_logbook_begin = rb_logbook_end;
    341 	}
    342 	if (rb_logbook_end < layout->rb_logbook_begin ||
    343 		rb_logbook_end > layout->rb_logbook_end)
    344 	{
    345 		ERROR (abstract->context, "Invalid logbook end pointer detected (0x%04x).", rb_logbook_end);
    346 		if (layout->rb_logbook_direction != 0) {
    347 			return DC_STATUS_DATAFORMAT;
    348 		}
    349 		// Fall back to downloading the entire logbook ringbuffer as
    350 		// workaround for an invalid logbook end pointer!
    351 		rb_logbook_end = rb_logbook_begin;
    352 	}
    353 
    354 	// Calculate the number of bytes.
    355 	// In a typical ringbuffer implementation with only two begin/end
    356 	// pointers, there is no distinction possible between an empty and a
    357 	// full ringbuffer. We always consider the ringbuffer full in that
    358 	// case, because an empty ringbuffer can be detected by inspecting
    359 	// the logbook entries once they are downloaded.
    360 	unsigned int rb_logbook_size = RB_LOGBOOK_DISTANCE (rb_logbook_begin, rb_logbook_end, layout, DC_RINGBUFFER_FULL);
    361 
    362 	// Update and emit a progress event.
    363 	progress->maximum -= (layout->rb_logbook_end - layout->rb_logbook_begin) - rb_logbook_size;
    364 	device_event_emit (abstract, DC_EVENT_PROGRESS, progress);
    365 
    366 	// Exit if there are no dives.
    367 	if (rb_logbook_size == 0) {
    368 		return DC_STATUS_SUCCESS;
    369 	}
    370 
    371 	// Allocate memory for the logbook entries.
    372 	if (!dc_buffer_resize (logbook, rb_logbook_size))
    373 		return DC_STATUS_NOMEMORY;
    374 
    375 	// Cache the logbook pointer.
    376 	unsigned char *logbooks = dc_buffer_get_data (logbook);
    377 
    378 	// Create the ringbuffer stream.
    379 	dc_rbstream_t *rbstream = NULL;
    380 	rc = dc_rbstream_new (&rbstream, abstract,
    381 		PAGESIZE, PAGESIZE * device->multipage,
    382 		layout->rb_logbook_begin, layout->rb_logbook_end,
    383 		layout->rb_logbook_direction ? rb_logbook_end : rb_logbook_begin,
    384 		layout->rb_logbook_direction ? DC_RBSTREAM_BACKWARD : DC_RBSTREAM_FORWARD);
    385 	if (rc != DC_STATUS_SUCCESS) {
    386 		ERROR (abstract->context, "Failed to create the ringbuffer stream.");
    387 		return rc;
    388 	}
    389 
    390 	// The logbook ringbuffer is read backwards to retrieve the most recent
    391 	// entries first. If an already downloaded entry is identified (by means
    392 	// of its fingerprint), the transfer is aborted immediately to reduce
    393 	// the transfer time.
    394 	unsigned int count = 0;
    395 	unsigned int nbytes = 0;
    396 	unsigned int offset = rb_logbook_size;
    397 	while (nbytes < rb_logbook_size) {
    398 		// Move to the start of the current entry.
    399 		offset -= layout->rb_logbook_entry_size;
    400 
    401 		// Read the logbook entry.
    402 		rc = dc_rbstream_read (rbstream, progress, logbooks + offset, layout->rb_logbook_entry_size);
    403 		if (rc != DC_STATUS_SUCCESS) {
    404 			ERROR (abstract->context, "Failed to read the memory.");
    405 			dc_rbstream_free (rbstream);
    406 			return rc;
    407 		}
    408 
    409 		nbytes += layout->rb_logbook_entry_size;
    410 
    411 		// Check for uninitialized entries. Normally, such entries are
    412 		// never present, except when the ringbuffer is actually empty,
    413 		// but the ringbuffer pointers are not set to their empty values.
    414 		// This appears to happen on some devices, and we attempt to
    415 		// fix this here.
    416 		if (array_isequal (logbooks + offset, layout->rb_logbook_entry_size, 0xFF)) {
    417 			WARNING (abstract->context, "Uninitialized logbook entries detected!");
    418 			continue;
    419 		}
    420 
    421 		// Compare the fingerprint to identify previously downloaded entries.
    422 		if (memcmp (logbooks + offset, device->fingerprint, layout->rb_logbook_entry_size) == 0) {
    423 			offset += layout->rb_logbook_entry_size;
    424 			break;
    425 		}
    426 
    427 		count++;
    428 	}
    429 
    430 	// Update and emit a progress event.
    431 	progress->maximum -= rb_logbook_size - nbytes;
    432 	device_event_emit (abstract, DC_EVENT_PROGRESS, progress);
    433 
    434 	if (count) {
    435 		dc_buffer_slice (logbook, offset, rb_logbook_size - offset);
    436 	} else {
    437 		dc_buffer_clear (logbook);
    438 	}
    439 
    440 	dc_rbstream_free (rbstream);
    441 
    442 	return DC_STATUS_SUCCESS;
    443 }
    444 
    445 
    446 dc_status_t
    447 oceanic_common_device_profile (dc_device_t *abstract, dc_event_progress_t *progress, dc_buffer_t *logbook, dc_dive_callback_t callback, void *userdata)
    448 {
    449 	oceanic_common_device_t *device = (oceanic_common_device_t *) abstract;
    450 	dc_status_t status = DC_STATUS_SUCCESS;
    451 	dc_status_t rc = DC_STATUS_SUCCESS;
    452 
    453 	assert (device != NULL);
    454 	assert (device->layout != NULL);
    455 	assert (device->layout->rb_logbook_entry_size <= sizeof (device->fingerprint));
    456 	assert (progress != NULL);
    457 
    458 	const oceanic_common_layout_t *layout = device->layout;
    459 
    460 	// Cache the logbook pointer and size.
    461 	const unsigned char *logbooks = dc_buffer_get_data (logbook);
    462 	unsigned int rb_logbook_size = dc_buffer_get_size (logbook);
    463 
    464 	// Go through the logbook entries a first time, to get the end of
    465 	// profile pointer and calculate the total amount of bytes in the
    466 	// profile ringbuffer.
    467 	unsigned int rb_profile_begin = INVALID;
    468 	unsigned int rb_profile_end  = INVALID;
    469 	unsigned int rb_profile_size = 0;
    470 
    471 	// Traverse the logbook ringbuffer backwards to retrieve the most recent
    472 	// dives first. The logbook ringbuffer is linearized at this point, so
    473 	// we do not have to take into account any memory wrapping near the end
    474 	// of the memory buffer.
    475 	unsigned int remaining = layout->rb_profile_end - layout->rb_profile_begin;
    476 	unsigned int previous = rb_profile_end;
    477 	unsigned int entry = rb_logbook_size;
    478 	while (entry) {
    479 		// Move to the start of the current entry.
    480 		entry -= layout->rb_logbook_entry_size;
    481 
    482 		// Skip uninitialized entries.
    483 		if (array_isequal (logbooks + entry, layout->rb_logbook_entry_size, 0xFF)) {
    484 			WARNING (abstract->context, "Skipping uninitialized logbook entry!");
    485 			continue;
    486 		}
    487 
    488 		// Get the profile pointers.
    489 		unsigned int rb_entry_begin = 0, rb_entry_end = 0;
    490 		oceanic_common_device_get_profile (logbooks + entry, layout, &rb_entry_begin, &rb_entry_end);
    491 		if (rb_entry_begin < layout->rb_profile_begin ||
    492 			rb_entry_begin > layout->rb_profile_end ||
    493 			rb_entry_end < layout->rb_profile_begin ||
    494 			rb_entry_end > layout->rb_profile_end)
    495 		{
    496 			ERROR (abstract->context, "Invalid ringbuffer pointer detected (0x%06x 0x%06x).",
    497 				rb_entry_begin, rb_entry_end);
    498 			status = DC_STATUS_DATAFORMAT;
    499 			continue;
    500 		}
    501 
    502 		DEBUG (abstract->context, "Entry: %08x %08x", rb_entry_begin, rb_entry_end);
    503 
    504 		// Take the end pointer of the most recent logbook entry as the
    505 		// end of profile pointer.
    506 		if (rb_profile_end == INVALID) {
    507 			rb_profile_end = previous = rb_entry_end;
    508 		}
    509 
    510 		// Calculate the number of bytes.
    511 		unsigned int rb_entry_size = RB_PROFILE_DISTANCE (rb_entry_begin, rb_entry_end, layout, DC_RINGBUFFER_FULL);
    512 
    513 		// Skip gaps between the profiles.
    514 		unsigned int gap = RB_PROFILE_DISTANCE (rb_entry_end, previous, layout, DC_RINGBUFFER_EMPTY);
    515 		if (gap) {
    516 			WARNING (abstract->context, "Profiles are not continuous (%u bytes).", gap);
    517 		}
    518 
    519 		// Make sure the profile size is valid.
    520 		if (rb_entry_size + gap > remaining) {
    521 			WARNING (abstract->context, "Unexpected profile size.");
    522 			break;
    523 		}
    524 
    525 		// Update the profile begin pointer.
    526 		rb_profile_begin = rb_entry_begin;
    527 
    528 		// Update the total profile size.
    529 		rb_profile_size += rb_entry_size + gap;
    530 
    531 		remaining -= rb_entry_size + gap;
    532 		previous = rb_entry_begin;
    533 	}
    534 
    535 	DEBUG (abstract->context, "Profile: %08x %08x", rb_profile_begin, rb_profile_end);
    536 
    537 	// At this point, we know the exact amount of data
    538 	// that needs to be transfered for the profiles.
    539 	progress->maximum -= (layout->rb_profile_end - layout->rb_profile_begin) - rb_profile_size;
    540 	device_event_emit (abstract, DC_EVENT_PROGRESS, progress);
    541 
    542 	// Exit if there are no dives.
    543 	if (rb_profile_size == 0) {
    544 		return status;
    545 	}
    546 
    547 	// Create the ringbuffer stream.
    548 	dc_rbstream_t *rbstream = NULL;
    549 	rc = dc_rbstream_new (&rbstream, abstract, PAGESIZE, PAGESIZE * device->multipage, layout->rb_profile_begin, layout->rb_profile_end, rb_profile_end, DC_RBSTREAM_BACKWARD);
    550 	if (rc != DC_STATUS_SUCCESS) {
    551 		ERROR (abstract->context, "Failed to create the ringbuffer stream.");
    552 		return rc;
    553 	}
    554 
    555 	// Memory buffer for the profile data.
    556 	unsigned char *profiles = (unsigned char *) malloc (rb_profile_size + rb_logbook_size);
    557 	if (profiles == NULL) {
    558 		ERROR (abstract->context, "Failed to allocate memory.");
    559 		dc_rbstream_free (rbstream);
    560 		return DC_STATUS_NOMEMORY;
    561 	}
    562 
    563 	// Keep track of the current position.
    564 	unsigned int offset = rb_profile_size + rb_logbook_size;
    565 
    566 	// Traverse the logbook ringbuffer backwards to retrieve the most recent
    567 	// dives first. The logbook ringbuffer is linearized at this point, so
    568 	// we do not have to take into account any memory wrapping near the end
    569 	// of the memory buffer.
    570 	remaining = rb_profile_size;
    571 	previous = rb_profile_end;
    572 	entry = rb_logbook_size;
    573 	while (entry) {
    574 		// Move to the start of the current entry.
    575 		entry -= layout->rb_logbook_entry_size;
    576 
    577 		// Skip uninitialized entries.
    578 		if (array_isequal (logbooks + entry, layout->rb_logbook_entry_size, 0xFF)) {
    579 			WARNING (abstract->context, "Skipping uninitialized logbook entry!");
    580 			continue;
    581 		}
    582 
    583 		// Get the profile pointers.
    584 		unsigned int rb_entry_begin = 0, rb_entry_end = 0;
    585 		oceanic_common_device_get_profile (logbooks + entry, layout, &rb_entry_begin, &rb_entry_end);
    586 		if (rb_entry_begin < layout->rb_profile_begin ||
    587 			rb_entry_begin > layout->rb_profile_end ||
    588 			rb_entry_end < layout->rb_profile_begin ||
    589 			rb_entry_end > layout->rb_profile_end)
    590 		{
    591 			ERROR (abstract->context, "Invalid ringbuffer pointer detected (0x%06x 0x%06x).",
    592 				rb_entry_begin, rb_entry_end);
    593 			status = DC_STATUS_DATAFORMAT;
    594 			continue;
    595 		}
    596 
    597 		DEBUG (abstract->context, "Entry: %08x %08x", rb_entry_begin, rb_entry_end);
    598 
    599 		// Calculate the number of bytes.
    600 		unsigned int rb_entry_size = RB_PROFILE_DISTANCE (rb_entry_begin, rb_entry_end, layout, DC_RINGBUFFER_FULL);
    601 
    602 		// Skip gaps between the profiles.
    603 		unsigned int gap = RB_PROFILE_DISTANCE (rb_entry_end, previous, layout, DC_RINGBUFFER_EMPTY);
    604 		if (gap) {
    605 			WARNING (abstract->context, "Profiles are not continuous (%u bytes).", gap);
    606 		}
    607 
    608 		// Make sure the profile size is valid.
    609 		if (rb_entry_size + gap > remaining) {
    610 			WARNING (abstract->context, "Unexpected profile size.");
    611 			break;
    612 		}
    613 
    614 		// Move to the start of the current dive.
    615 		offset -= rb_entry_size + gap;
    616 
    617 		// Read the dive.
    618 		rc = dc_rbstream_read (rbstream, progress, profiles + offset, rb_entry_size + gap);
    619 		if (rc != DC_STATUS_SUCCESS) {
    620 			ERROR (abstract->context, "Failed to read the dive.");
    621 			status = rc;
    622 			break;
    623 		}
    624 
    625 		remaining -= rb_entry_size + gap;
    626 		previous = rb_entry_begin;
    627 
    628 		// Prepend the logbook entry to the profile data. The memory buffer is
    629 		// large enough to store this entry.
    630 		offset -= layout->rb_logbook_entry_size;
    631 		memcpy (profiles + offset, logbooks + entry, layout->rb_logbook_entry_size);
    632 
    633 		// Remove padding from the profile.
    634 		if (layout->highmem) {
    635 			// The logbook entry contains the total number of pages containing
    636 			// profile data, excluding the footer page. Limit the profile size
    637 			// to this size.
    638 			unsigned int value = array_uint16_le (profiles + offset + 12);
    639 			unsigned int value_hi = value & 0xE000;
    640 			unsigned int value_lo = value & 0x0FFF;
    641 			unsigned int npages = ((value_hi >> 1) | value_lo) + 1;
    642 			unsigned int length = npages * PAGESIZE;
    643 			if (rb_entry_size > length) {
    644 				rb_entry_size = length;
    645 			}
    646 		}
    647 
    648 		unsigned char *p = profiles + offset;
    649 		if (callback && !callback (p, rb_entry_size + layout->rb_logbook_entry_size, p, layout->rb_logbook_entry_size, userdata)) {
    650 			break;
    651 		}
    652 	}
    653 
    654 	dc_rbstream_free (rbstream);
    655 	free (profiles);
    656 
    657 	return status;
    658 }
    659 
    660 
    661 dc_status_t
    662 oceanic_common_device_foreach (dc_device_t *abstract, dc_dive_callback_t callback, void *userdata)
    663 {
    664 	dc_status_t rc = DC_STATUS_SUCCESS;
    665 	oceanic_common_device_t *device = (oceanic_common_device_t *) abstract;
    666 
    667 	assert (device != NULL);
    668 	assert (device->layout != NULL);
    669 
    670 	const oceanic_common_layout_t *layout = device->layout;
    671 
    672 	// For devices without a logbook and profile ringbuffer, downloading dives
    673 	// isn't possible. This is not considered a fatal error, but handled as if
    674 	// there are no dives present.
    675 	if (layout->rb_logbook_begin == layout->rb_logbook_end &&
    676 		layout->rb_profile_begin == layout->rb_profile_end) {
    677 		return DC_STATUS_SUCCESS;
    678 	}
    679 
    680 	// Enable progress notifications.
    681 	dc_event_progress_t progress = EVENT_PROGRESS_INITIALIZER;
    682 	progress.maximum =
    683 		(layout->rb_logbook_end - layout->rb_logbook_begin) +
    684 		(layout->rb_profile_end - layout->rb_profile_begin);
    685 	device_event_emit (abstract, DC_EVENT_PROGRESS, &progress);
    686 
    687 	// Read the device info.
    688 	rc = VTABLE(abstract)->devinfo (abstract, &progress);
    689 	if (rc != DC_STATUS_SUCCESS) {
    690 		return rc;
    691 	}
    692 
    693 	// Read the ringbuffer pointers.
    694 	unsigned int rb_logbook_begin = 0, rb_logbook_end = 0;
    695 	unsigned int rb_profile_begin = 0, rb_profile_end = 0;
    696 	rc = VTABLE(abstract)->pointers (abstract, &progress, &rb_logbook_begin, &rb_logbook_end, &rb_profile_begin, &rb_profile_end);
    697 	if (rc != DC_STATUS_SUCCESS) {
    698 		return rc;
    699 	}
    700 
    701 	DEBUG (abstract->context, "Logbook: %08x %08x", rb_logbook_begin, rb_logbook_end);
    702 	DEBUG (abstract->context, "Profile: %08x %08x", rb_profile_begin, rb_profile_end);
    703 
    704 	// Memory buffer for the logbook data.
    705 	dc_buffer_t *logbook = dc_buffer_new (0);
    706 	if (logbook == NULL) {
    707 		return DC_STATUS_NOMEMORY;
    708 	}
    709 
    710 	// Download the logbook ringbuffer.
    711 	rc = VTABLE(abstract)->logbook (abstract, &progress, logbook, rb_logbook_begin, rb_logbook_end);
    712 	if (rc != DC_STATUS_SUCCESS) {
    713 		dc_buffer_free (logbook);
    714 		return rc;
    715 	}
    716 
    717 	// Exit if there are no (new) dives.
    718 	if (dc_buffer_get_size (logbook) == 0) {
    719 		dc_buffer_free (logbook);
    720 		return DC_STATUS_SUCCESS;
    721 	}
    722 
    723 	// Download the profile ringbuffer.
    724 	rc = VTABLE(abstract)->profile (abstract, &progress, logbook, callback, userdata);
    725 	if (rc != DC_STATUS_SUCCESS) {
    726 		dc_buffer_free (logbook);
    727 		return rc;
    728 	}
    729 
    730 	dc_buffer_free (logbook);
    731 
    732 	return DC_STATUS_SUCCESS;
    733 }