aboutsummaryrefslogtreecommitdiff
path: root/libjaylink/transport.c
blob: a82b83dc99a447b047c0467305de3a8d6ca4ef71 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
/*
 * This file is part of the libjaylink project.
 *
 * Copyright (C) 2014-2015 Marc Schink <jaylink-dev@marcschink.de>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
#include <string.h>

#include "libjaylink.h"
#include "libjaylink-internal.h"

/**
 * @file
 *
 * Transport abstraction layer.
 */

/** Timeout of an USB transfer in milliseconds. */
#define USB_TIMEOUT	1000

/**
 * Number of consecutive timeouts before an USB transfer will be treated as
 * timed out.
 */
#define NUM_TIMEOUTS	2

/** Chunk size in bytes in which data is transferred. */
#define CHUNK_SIZE	2048

static int initialize_handle(struct jaylink_device_handle *devh)
{
	int ret;
	struct jaylink_context *ctx;
	struct libusb_config_descriptor *config;
	const struct libusb_interface *interface;
	const struct libusb_interface_descriptor *desc;
	const struct libusb_endpoint_descriptor *epdesc;
	bool found_interface;
	bool found_endpoint_in;
	bool found_endpoint_out;
	uint8_t i;

	ctx = devh->dev->ctx;
	devh->interface_number = 0;

	/*
	 * Retrieve active configuration descriptor to determine the endpoints
	 * for the interface number of the device.
	 */
	ret = libusb_get_active_config_descriptor(devh->dev->usb_dev, &config);

	if (ret == LIBUSB_ERROR_IO) {
		log_err(ctx, "Failed to get configuration descriptor: "
			"input/output error.");
		return JAYLINK_ERR_IO;
	} else if (ret != LIBUSB_SUCCESS) {
		log_err(ctx, "Failed to get configuration descriptor: %s.",
			libusb_error_name(ret));
		return JAYLINK_ERR;
	}

	found_interface = false;

	for (i = 0; i < config->bNumInterfaces; i++) {
		interface = &config->interface[i];
		desc = &interface->altsetting[0];

		if (desc->bInterfaceClass != LIBUSB_CLASS_VENDOR_SPEC)
			continue;

		if (desc->bInterfaceSubClass != LIBUSB_CLASS_VENDOR_SPEC)
			continue;

		if (desc->bNumEndpoints < 2)
			continue;

		found_interface = true;
		devh->interface_number = i;
		break;
	}

	if (!found_interface) {
		log_err(ctx, "No suitable interface found.");
		libusb_free_config_descriptor(config);
		return JAYLINK_ERR;
	}

	found_endpoint_in = false;
	found_endpoint_out = false;

	for (i = 0; i < desc->bNumEndpoints; i++) {
		epdesc = &desc->endpoint[i];

		if (epdesc->bEndpointAddress & LIBUSB_ENDPOINT_IN) {
			devh->endpoint_in = epdesc->bEndpointAddress;
			found_endpoint_in = true;
		} else {
			devh->endpoint_out = epdesc->bEndpointAddress;
			found_endpoint_out = true;
		}
	}

	libusb_free_config_descriptor(config);

	if (!found_endpoint_in) {
		log_err(ctx, "Interface IN endpoint not found.");
		return JAYLINK_ERR;
	}

	if (!found_endpoint_out) {
		log_err(ctx, "Interface OUT endpoint not found.");
		return JAYLINK_ERR;
	}

	log_dbg(ctx, "Using endpoint %02x (IN) and %02x (OUT).",
		devh->endpoint_in, devh->endpoint_out);

	/* Buffer size must be a multiple of CHUNK_SIZE bytes. */
	devh->buffer_size = CHUNK_SIZE;
	devh->buffer = malloc(devh->buffer_size);

	if (!devh->buffer) {
		log_err(ctx, "Transport buffer malloc failed.");
		return JAYLINK_ERR_MALLOC;
	}

	devh->read_length = 0;
	devh->bytes_available = 0;
	devh->read_pos = 0;

	devh->write_length = 0;
	devh->write_pos = 0;

	return JAYLINK_OK;
}

static void cleanup_handle(struct jaylink_device_handle *devh)
{
	free(devh->buffer);
}

/**
 * Open a device.
 *
 * This function must be called before any other function of the transport
 * abstraction layer for the given device handle is called.
 *
 * @param[in,out] devh Device handle.
 *
 * @retval JAYLINK_OK Success.
 * @retval JAYLINK_ERR_IO Input/output error.
 * @retval JAYLINK_ERR Other error conditions.
 */
JAYLINK_PRIV int transport_open(struct jaylink_device_handle *devh)
{
	int ret;
	struct jaylink_device *dev;
	struct jaylink_context *ctx;
	struct libusb_device_handle *usb_devh;

	dev = devh->dev;
	ctx = dev->ctx;

	log_dbg(ctx, "Trying to open device (bus:address = %03u:%03u).",
		libusb_get_bus_number(dev->usb_dev),
		libusb_get_device_address(dev->usb_dev));

	ret = initialize_handle(devh);

	if (ret != JAYLINK_OK) {
		log_err(ctx, "Failed to initialize device handle.");
		return ret;
	}

	ret = libusb_open(dev->usb_dev, &usb_devh);

	if (ret == LIBUSB_ERROR_IO) {
		log_err(ctx, "Failed to open device: input/output error.");
		cleanup_handle(devh);
		return JAYLINK_ERR_IO;
	} else if (ret != LIBUSB_SUCCESS) {
		log_err(ctx, "Failed to open device: %s.",
			libusb_error_name(ret));
		cleanup_handle(devh);
		return JAYLINK_ERR;
	}

	ret = libusb_claim_interface(usb_devh, devh->interface_number);

	if (ret == LIBUSB_ERROR_IO) {
		log_err(ctx, "Failed to claim interface: input/output error.");
		return JAYLINK_ERR_IO;
	} else if (ret != LIBUSB_SUCCESS) {
		log_err(ctx, "Failed to claim interface: %s.",
			libusb_error_name(ret));
		cleanup_handle(devh);
		libusb_close(usb_devh);
		return JAYLINK_ERR;
	}

	log_dbg(ctx, "Device opened successfully.");

	devh->usb_devh = usb_devh;

	return JAYLINK_OK;
}

/**
 * Close a device.
 *
 * After this function has been called no other function of the transport
 * abstraction layer for the given device handle must be called.
 *
 * @param[in,out] devh Device handle.
 *
 * @retval JAYLINK_OK Success.
 * @retval JAYLINK_ERR Other error conditions.
 */
JAYLINK_PRIV int transport_close(struct jaylink_device_handle *devh)
{
	int ret;
	struct jaylink_device *dev;
	struct jaylink_context *ctx;

	dev = devh->dev;
	ctx = dev->ctx;

	log_dbg(ctx, "Closing device (bus:address = %03u:%03u).",
		libusb_get_bus_number(dev->usb_dev),
		libusb_get_device_address(dev->usb_dev));

	ret = libusb_release_interface(devh->usb_devh, devh->interface_number);

	libusb_close(devh->usb_devh);
	cleanup_handle(devh);

	if (ret != LIBUSB_SUCCESS) {
		log_err(ctx, "Failed to release interface: %s.",
			libusb_error_name(ret));
		return JAYLINK_ERR;
	}

	log_dbg(ctx, "Device closed successfully.");

	return JAYLINK_OK;
}

/**
 * Start a write operation for a device.
 *
 * The data of a write operation must be written with at least one call of
 * transport_write(). It is required that all data of a write operation is
 * written before an other write and/or read operation is started.
 *
 * @param[in,out] devh Device handle.
 * @param[in] length Number of bytes of the write operation.
 * @param[in] has_command Determines whether the data of the write operation
 *                        contains the protocol command.
 *
 * @retval JAYLINK_OK Success.
 * @retval JAYLINK_ERR_ARG Invalid arguments.
 */
JAYLINK_PRIV int transport_start_write(struct jaylink_device_handle *devh,
		size_t length, bool has_command)
{
	struct jaylink_context *ctx;

	(void)has_command;

	if (!length)
		return JAYLINK_ERR_ARG;

	ctx = devh->dev->ctx;

	log_dbg(ctx, "Starting write operation (length = %zu bytes).", length);

	if (devh->write_pos > 0)
		log_warn(ctx, "Last write operation left %zu bytes in the "
			"buffer.", devh->write_pos);

	if (devh->write_length > 0)
		log_warn(ctx, "Last write operation was not performed.");

	devh->write_length = length;
	devh->write_pos = 0;

	return JAYLINK_OK;
}

/**
 * Start a read operation for a device.
 *
 * The data of a read operation must be read with at least one call of
 * transport_read(). It is required that all data of a read operation is read
 * before an other write and/or read operation is started.
 *
 * @param[in,out] devh Device handle.
 * @param[in] length Number of bytes of the read operation.
 *
 * @retval JAYLINK_OK Success.
 * @retval JAYLINK_ERR_ARG Invalid arguments.
 */
JAYLINK_PRIV int transport_start_read(struct jaylink_device_handle *devh,
		size_t length)
{
	struct jaylink_context *ctx;

	if (!length)
		return JAYLINK_ERR_ARG;

	ctx = devh->dev->ctx;

	log_dbg(ctx, "Starting read operation (length = %zu bytes).", length);

	if (devh->bytes_available > 0)
		log_dbg(ctx, "Last read operation left %zu bytes in the "
			"buffer.", devh->bytes_available);

	if (devh->read_length > 0)
		log_warn(ctx, "Last read operation left %zu bytes.",
			devh->read_length);

	devh->read_length = length;

	return JAYLINK_OK;
}

/**
 * Start a write and read operation for a device.
 *
 * This function starts a write and read operation as the consecutive call of
 * transport_start_write() and transport_start_read() but has a different
 * meaning from the protocol perspective and can therefore not be replaced by
 * these functions and vice versa.
 *
 * @note The write operation must be completed first before the read operation
 *       must be processed.
 *
 * @param[in,out] devh Device handle.
 * @param[in] write_length Number of bytes of the write operation.
 * @param[in] read_length Number of bytes of the read operation.
 * @param[in] has_command Determines whether the data of the write operation
 *                        contains the protocol command.
 *
 * @retval JAYLINK_OK Success.
 * @retval JAYLINK_ERR_ARG Invalid arguments.
 */
JAYLINK_PRIV int transport_start_write_read(struct jaylink_device_handle *devh,
		size_t write_length, size_t read_length, bool has_command)
{
	struct jaylink_context *ctx;

	(void)has_command;

	if (!read_length || !write_length)
		return JAYLINK_ERR_ARG;

	ctx = devh->dev->ctx;

	log_dbg(ctx, "Starting write / read operation (length = "
		"%zu / %zu bytes).", write_length, read_length);

	if (devh->write_pos > 0)
		log_warn(ctx, "Last write operation left %zu bytes in the "
			"buffer.", devh->write_pos);

	if (devh->write_length > 0)
		log_warn(ctx, "Last write operation was not performed.");

	if (devh->bytes_available > 0)
		log_warn(ctx, "Last read operation left %zu bytes in the "
			"buffer.", devh->bytes_available);

	if (devh->read_length > 0)
		log_warn(ctx, "Last read operation left %zu bytes.",
			devh->read_length);

	devh->write_length = write_length;
	devh->write_pos = 0;

	devh->read_length = read_length;
	devh->bytes_available = 0;
	devh->read_pos = 0;

	return JAYLINK_OK;
}

static bool adjust_buffer(struct jaylink_device_handle *devh, size_t size)
{
	struct jaylink_context *ctx;
	size_t num_chunks;
	uint8_t *buffer;

	ctx = devh->dev->ctx;

	/* Adjust buffer size to a multiple of CHUNK_SIZE bytes. */
	num_chunks = size / CHUNK_SIZE;

	if (size % CHUNK_SIZE > 0)
		num_chunks++;

	size = num_chunks * CHUNK_SIZE;
	buffer = realloc(devh->buffer, size);

	if (!buffer) {
		log_err(ctx, "Failed to adjust buffer size to %zu bytes.",
			size);
		return false;
	}

	devh->buffer = buffer;
	devh->buffer_size = size;

	log_dbg(ctx, "Adjusted buffer size to %zu bytes.", size);

	return true;
}

static int usb_send(struct jaylink_device_handle *devh, const uint8_t *buffer,
		size_t length)
{
	int ret;
	struct jaylink_context *ctx;
	unsigned int tries;
	int transferred;

	ctx = devh->dev->ctx;
	tries = NUM_TIMEOUTS;

	while (tries > 0 && length > 0) {
		/* Send data in chunks of CHUNK_SIZE bytes to the device. */
		ret = libusb_bulk_transfer(devh->usb_devh, devh->endpoint_out,
			(unsigned char *)buffer, MIN(CHUNK_SIZE, length),
			&transferred, USB_TIMEOUT);

		if (ret == LIBUSB_SUCCESS) {
			tries = NUM_TIMEOUTS;
		} else if (ret == LIBUSB_ERROR_TIMEOUT) {
			log_warn(ctx, "Sending data to device timed out, "
				"retrying.");
			tries--;
		} else if (ret == LIBUSB_ERROR_IO) {
			log_err(ctx, "Failed to send data to device: "
				"input/output error.");
			return JAYLINK_ERR_IO;
		} else {
			log_err(ctx, "Failed to send data to device: %s.",
				libusb_error_name(ret));
			return JAYLINK_ERR;
		}

		buffer += transferred;
		length -= transferred;

		log_dbg(ctx, "Sent %i bytes to device.", transferred);
	}

	if (!length)
		return JAYLINK_OK;

	log_err(ctx, "Sending data to device timed out.");

	return JAYLINK_ERR_TIMEOUT;
}

/**
 * Write data to a device.
 *
 * Before this function is used transport_start_write() or
 * transport_start_write_read() must be called to start a write operation. The
 * total number of written bytes must not exceed the number of bytes of the
 * write operation.
 *
 * @note A write operation will be performed and the data will be sent to the
 *       device when the number of written bytes reaches the number of bytes of
 *       the write operation. Before that the data will be written into a
 *       buffer.
 *
 * @param[in,out] devh Device handle.
 * @param[in] buffer Buffer to write data from.
 * @param[in] length Number of bytes to write.
 *
 * @retval JAYLINK_OK Success.
 * @retval JAYLINK_ERR_ARG Invalid arguments.
 * @retval JAYLINK_ERR_TIMEOUT A timeout occurred.
 * @retval JAYLINK_ERR_IO Input/output error.
 * @retval JAYLINK_ERR Other error conditions.
 */
JAYLINK_PRIV int transport_write(struct jaylink_device_handle *devh,
		const uint8_t *buffer, size_t length)
{
	int ret;
	struct jaylink_context *ctx;
	size_t num_chunks;
	size_t fill_bytes;
	size_t tmp;

	ctx = devh->dev->ctx;

	if (length > devh->write_length) {
		log_err(ctx, "Requested to write %zu bytes but only %zu bytes "
			"are expected for the write operation.", length,
			devh->write_length);
		return JAYLINK_ERR_ARG;
	}

	/*
	 * Store data in the buffer if the expected number of bytes for the
	 * write operation is not reached.
	 */
	if (length < devh->write_length) {
		if (devh->write_pos + length > devh->buffer_size) {
			if (!adjust_buffer(devh, devh->write_pos + length))
				return JAYLINK_ERR_MALLOC;
		}

		memcpy(devh->buffer + devh->write_pos, buffer, length);

		devh->write_length -= length;
		devh->write_pos += length;

		log_dbg(ctx, "Wrote %zu bytes into buffer.", length);
		return JAYLINK_OK;
	}

	/*
	 * Expected number of bytes for this write operation is reached and
	 * therefore the write operation will be performed.
	 */
	devh->write_length = 0;

	/* Send data directly to the device if the buffer is empty. */
	if (!devh->write_pos)
		return usb_send(devh, buffer, length);

	/*
	 * Calculate the number of bytes to fill up the buffer to reach a
	 * multiple of CHUNK_SIZE bytes. This ensures that the data from the
	 * buffer will be sent to the device in chunks of CHUNK_SIZE bytes.
	 * Note that this is why the buffer size must be a multiple of
	 * CHUNK_SIZE bytes.
	 */
	num_chunks = devh->write_pos / CHUNK_SIZE;

	if (devh->write_pos % CHUNK_SIZE)
		num_chunks++;

	fill_bytes = (num_chunks * CHUNK_SIZE) - devh->write_pos;
	tmp = MIN(length, fill_bytes);

	if (tmp > 0) {
		memcpy(devh->buffer + devh->write_pos, buffer, tmp);

		length -= tmp;
		buffer += tmp;

		log_dbg(ctx, "Buffer filled up with %zu bytes.", tmp);
	}

	/* Send buffered data to the device. */
	ret = usb_send(devh, devh->buffer, devh->write_pos + tmp);
	devh->write_pos = 0;

	if (ret != JAYLINK_OK)
		return ret;

	if (!length)
		return JAYLINK_OK;

	/* Send remaining data to the device. */
	return usb_send(devh, buffer, length);
}

static int usb_recv(struct jaylink_device_handle *devh, uint8_t *buffer,
		size_t *length)
{
	int ret;
	struct jaylink_context *ctx;
	unsigned int tries;
	int transferred;

	ctx = devh->dev->ctx;
	tries = NUM_TIMEOUTS;
	transferred = 0;

	while (tries > 0 && !transferred) {
		/* Always request CHUNK_SIZE bytes from the device. */
		ret = libusb_bulk_transfer(devh->usb_devh, devh->endpoint_in,
			(unsigned char *)buffer, CHUNK_SIZE, &transferred,
			USB_TIMEOUT);

		if (ret == LIBUSB_ERROR_TIMEOUT) {
			log_warn(ctx, "Receiving data from device timed out, "
				"retrying.");
			tries--;
			continue;
		} else if (ret == LIBUSB_ERROR_IO) {
			log_err(ctx, "Failed to receive data from device: "
				"input/output error.");
			return JAYLINK_ERR_IO;
		} else if (ret != LIBUSB_SUCCESS) {
			log_err(ctx, "Failed to receive data from device: %s.",
				libusb_error_name(ret));
			return JAYLINK_ERR;
		}

		log_dbg(ctx, "Received %i bytes from device.", transferred);
	}

	/* Ignore a possible timeout if at least one byte was received. */
	if (transferred > 0) {
		*length = transferred;
		return JAYLINK_OK;
	}

	log_err(ctx, "Receiving data from device timed out.");

	return JAYLINK_ERR_TIMEOUT;
}

/**
 * Read data from a device.
 *
 * Before this function is used transport_start_read() or
 * transport_start_write_read() must be called to start a read operation. The
 * total number of read bytes must not exceed the number of bytes of the read
 * operation.
 *
 * @param[in,out] devh Device handle.
 * @param[out] buffer Buffer to read data into on success. Its content is
 *                    undefined on failure.
 * @param[in] length Number of bytes to read.
 *
 * @retval JAYLINK_OK Success.
 * @retval JAYLINK_ERR_ARG Invalid arguments.
 * @retval JAYLINK_ERR_TIMEOUT A timeout occurred.
 * @retval JAYLINK_ERR_IO Input/output error.
 * @retval JAYLINK_ERR Other error conditions.
 */
JAYLINK_PRIV int transport_read(struct jaylink_device_handle *devh,
		uint8_t *buffer, size_t length)
{
	int ret;
	struct jaylink_context *ctx;
	size_t bytes_received;
	size_t tmp;

	ctx = devh->dev->ctx;

	if (length > devh->read_length) {
		log_err(ctx, "Requested to read %zu bytes but only %zu bytes "
			"are expected for the read operation.", length,
			devh->read_length);
		return JAYLINK_ERR_ARG;
	}

	if (length <= devh->bytes_available) {
		memcpy(buffer, devh->buffer + devh->read_pos, length);

		devh->read_length -= length;
		devh->bytes_available -= length;
		devh->read_pos += length;

		log_dbg(ctx, "Read %zu bytes from buffer.", length);
		return JAYLINK_OK;
	}

	if (devh->bytes_available > 0) {
		memcpy(buffer, devh->buffer + devh->read_pos,
			devh->bytes_available);

		buffer += devh->bytes_available;
		length -= devh->bytes_available;
		devh->read_length -= devh->bytes_available;

		log_dbg(ctx, "Read %zu bytes from buffer to flush it.",
			devh->bytes_available);

		devh->bytes_available = 0;
		devh->read_pos = 0;
	}

	while (length > 0) {
		/*
		 * If less than CHUNK_SIZE bytes are requested from the device,
		 * store the received data into the internal buffer instead of
		 * directly into the user provided buffer. This is necessary to
		 * prevent a possible buffer overflow because the number of
		 * requested bytes from the device is always CHUNK_SIZE and
		 * therefore up to CHUNK_SIZE bytes may be received.
		 * Note that this is why the internal buffer size must be at
		 * least CHUNK_SIZE bytes.
		 */
		if (length < CHUNK_SIZE) {
			ret = usb_recv(devh, devh->buffer, &bytes_received);

			if (ret != JAYLINK_OK)
				return ret;

			tmp = MIN(bytes_received, length);
			memcpy(buffer, devh->buffer, tmp);

			/*
			 * Setup the buffer for the remaining data if more data
			 * was received from the device than was requested.
			 */
			if (bytes_received > length) {
				devh->bytes_available = bytes_received - tmp;
				devh->read_pos = tmp;
			}

			buffer += tmp;
			length -= tmp;
			devh->read_length -= tmp;

			log_dbg(ctx, "Read %zu bytes from buffer.", tmp);
		} else {
			ret = usb_recv(devh, buffer, &bytes_received);

			if (ret != JAYLINK_OK)
				return ret;

			buffer += bytes_received;
			length -= bytes_received;
			devh->read_length -= bytes_received;

			log_dbg(ctx, "Read %zu bytes from device.",
				bytes_received);
		}
	}

	return JAYLINK_OK;
}