]> sigrok.org Git - libsigrok.git/blob - src/scpi/scpi_usbtmc_libusb.c
2da67030ed2495c41e9a0c3dcd56f9255d72f201
[libsigrok.git] / src / scpi / scpi_usbtmc_libusb.c
1 /*
2  * This file is part of the libsigrok project.
3  *
4  * Copyright (C) 2014 Aurelien Jacobs <aurel@gnuage.org>
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program 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
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 #include <config.h>
21 #include <inttypes.h>
22 #include <string.h>
23 #include <libsigrok/libsigrok.h>
24 #include "libsigrok-internal.h"
25 #include "scpi.h"
26
27 #define LOG_PREFIX "scpi_usbtmc"
28
29 #define MAX_TRANSFER_LENGTH 2048
30 #define TRANSFER_TIMEOUT 1000
31
32 struct scpi_usbtmc_libusb {
33         struct sr_context *ctx;
34         struct sr_usb_dev_inst *usb;
35         int detached_kernel_driver;
36         uint8_t interface;
37         uint8_t bulk_in_ep;
38         uint8_t bulk_out_ep;
39         uint8_t interrupt_ep;
40         uint8_t usbtmc_int_cap;
41         uint8_t usbtmc_dev_cap;
42         uint8_t usb488_dev_cap;
43         uint8_t bTag;
44         uint8_t bulkin_attributes;
45         uint8_t buffer[MAX_TRANSFER_LENGTH];
46         int response_length;
47         int response_bytes_read;
48         int remaining_length;
49 };
50
51 /* Some USBTMC-specific enums, as defined in the USBTMC standard. */
52 #define SUBCLASS_USBTMC 0x03
53 #define USBTMC_USB488   0x01
54
55 enum {
56         /* USBTMC control requests */
57         INITIATE_ABORT_BULK_OUT     =   1,
58         CHECK_ABORT_BULK_OUT_STATUS =   2,
59         INITIATE_ABORT_BULK_IN      =   3,
60         CHECK_ABORT_BULK_IN_STATUS  =   4,
61         INITIATE_CLEAR              =   5,
62         CHECK_CLEAR_STATUS          =   6,
63         GET_CAPABILITIES            =   7,
64         INDICATOR_PULSE             =  64,
65
66         /* USB488 control requests */
67         READ_STATUS_BYTE            = 128,
68         REN_CONTROL                 = 160,
69         GO_TO_LOCAL                 = 161,
70         LOCAL_LOCKOUT               = 162,
71 };
72
73 /* USBTMC status codes */
74 #define USBTMC_STATUS_SUCCESS      0x01
75
76 /* USBTMC capabilities */
77 #define USBTMC_INT_CAP_LISTEN_ONLY 0x01
78 #define USBTMC_INT_CAP_TALK_ONLY   0x02
79 #define USBTMC_INT_CAP_INDICATOR   0x04
80
81 #define USBTMC_DEV_CAP_TERMCHAR    0x01
82
83 #define USB488_DEV_CAP_DT1         0x01
84 #define USB488_DEV_CAP_RL1         0x02
85 #define USB488_DEV_CAP_SR1         0x04
86 #define USB488_DEV_CAP_SCPI        0x08
87
88 /* Bulk messages constants */
89 #define USBTMC_BULK_HEADER_SIZE 12
90
91 /* Bulk MsgID values */
92 #define DEV_DEP_MSG_OUT        1
93 #define REQUEST_DEV_DEP_MSG_IN 2
94 #define DEV_DEP_MSG_IN         2
95
96 /* bmTransferAttributes */
97 #define EOM               0x01
98 #define TERM_CHAR_ENABLED 0x02
99
100 struct usbtmc_blacklist {
101         uint16_t vid;
102         uint16_t pid;
103 };
104
105 /* Devices that publish RL1 support, but don't support it. */
106 static struct usbtmc_blacklist blacklist_remote[] = {
107         { 0x1ab1, 0x0588 }, /* Rigol DS1000 series */
108         { 0x1ab1, 0x04b0 }, /* Rigol DS2000 series */
109         { 0x1ab1, 0x04b1 }, /* Rigol DS4000 series */
110         { 0x1ab1, 0x0515 }, /* Rigol MSO5000 series */
111         { 0x0957, 0x0588 }, /* Agilent DSO1000 series (rebadged Rigol DS1000) */
112         { 0x0b21, 0xffff }, /* All Yokogawa devices */
113         { 0xf4ec, 0xffff }, /* All Siglent SDS devices */
114         ALL_ZERO
115 };
116
117 /* Devices that shall get reset during open(). */
118 static struct usbtmc_blacklist whitelist_usb_reset[] = {
119         { 0xf4ec, 0xffff }, /* All Siglent SDS devices */
120         ALL_ZERO
121 };
122
123 static GSList *scpi_usbtmc_libusb_scan(struct drv_context *drvc)
124 {
125         struct libusb_device **devlist;
126         struct libusb_device_descriptor des;
127         struct libusb_config_descriptor *confdes;
128         const struct libusb_interface_descriptor *intfdes;
129         GSList *resources = NULL;
130         int confidx, intfidx, ret, i;
131         char *res;
132
133         ret = libusb_get_device_list(drvc->sr_ctx->libusb_ctx, &devlist);
134         if (ret < 0) {
135                 sr_err("Failed to get device list: %s.",
136                        libusb_error_name(ret));
137                 return NULL;
138         }
139         for (i = 0; devlist[i]; i++) {
140                 libusb_get_device_descriptor(devlist[i], &des);
141
142                 for (confidx = 0; confidx < des.bNumConfigurations; confidx++) {
143                         if ((ret = libusb_get_config_descriptor(devlist[i], confidx, &confdes)) < 0) {
144                                 if (ret != LIBUSB_ERROR_NOT_FOUND)
145                                         sr_dbg("Failed to get configuration descriptor: %s, "
146                                                "ignoring device.", libusb_error_name(ret));
147                                 break;
148                         }
149                         for (intfidx = 0; intfidx < confdes->bNumInterfaces; intfidx++) {
150                                 intfdes = confdes->interface[intfidx].altsetting;
151                                 if (intfdes->bInterfaceClass    != LIBUSB_CLASS_APPLICATION ||
152                                     intfdes->bInterfaceSubClass != SUBCLASS_USBTMC          ||
153                                     intfdes->bInterfaceProtocol != USBTMC_USB488)
154                                         continue;
155                                 sr_dbg("Found USBTMC device (VID:PID = %04x:%04x, "
156                                        "bus.address = %d.%d).", des.idVendor, des.idProduct,
157                                        libusb_get_bus_number(devlist[i]),
158                                        libusb_get_device_address(devlist[i]));
159                                 res = g_strdup_printf("usbtmc/%d.%d",
160                                                       libusb_get_bus_number(devlist[i]),
161                                                       libusb_get_device_address(devlist[i]));
162                                 resources = g_slist_append(resources, res);
163                         }
164                         libusb_free_config_descriptor(confdes);
165                 }
166         }
167         libusb_free_device_list(devlist, 1);
168
169         /* No log message for #devices found (caller will log that). */
170
171         return resources;
172 }
173
174 static int scpi_usbtmc_libusb_dev_inst_new(void *priv, struct drv_context *drvc,
175                 const char *resource, char **params, const char *serialcomm)
176 {
177         struct scpi_usbtmc_libusb *uscpi = priv;
178         GSList *devices;
179
180         (void)resource;
181         (void)serialcomm;
182
183         if (!params || !params[1]) {
184                 sr_err("Invalid parameters.");
185                 return SR_ERR;
186         }
187
188         uscpi->ctx = drvc->sr_ctx;
189         devices = sr_usb_find(uscpi->ctx->libusb_ctx, params[1]);
190         if (g_slist_length(devices) != 1) {
191                 sr_err("Failed to find USB device '%s'.", params[1]);
192                 g_slist_free_full(devices, (GDestroyNotify)sr_usb_dev_inst_free);
193                 return SR_ERR;
194         }
195         uscpi->usb = devices->data;
196         g_slist_free(devices);
197
198         return SR_OK;
199 }
200
201 static int check_usbtmc_blacklist(struct usbtmc_blacklist *blacklist,
202                 uint16_t vid, uint16_t pid)
203 {
204         int i;
205
206         for (i = 0; blacklist[i].vid; i++) {
207                 if ((blacklist[i].vid == vid && blacklist[i].pid == 0xFFFF) ||
208                         (blacklist[i].vid == vid && blacklist[i].pid == pid))
209                         return TRUE;
210         }
211
212         return FALSE;
213 }
214
215 static int scpi_usbtmc_remote(struct scpi_usbtmc_libusb *uscpi)
216 {
217         struct sr_usb_dev_inst *usb = uscpi->usb;
218         struct libusb_device *dev;
219         struct libusb_device_descriptor des;
220         int ret;
221         uint8_t status;
222
223         if (!(uscpi->usb488_dev_cap & USB488_DEV_CAP_RL1))
224                 return SR_OK;
225
226         dev = libusb_get_device(usb->devhdl);
227         libusb_get_device_descriptor(dev, &des);
228         if (check_usbtmc_blacklist(blacklist_remote, des.idVendor, des.idProduct))
229                 return SR_OK;
230
231         sr_dbg("Locking out local control.");
232         ret = libusb_control_transfer(usb->devhdl, LIBUSB_ENDPOINT_IN |
233                 LIBUSB_REQUEST_TYPE_CLASS | LIBUSB_RECIPIENT_INTERFACE,
234                 REN_CONTROL, 1, uscpi->interface, &status, 1, TRANSFER_TIMEOUT);
235         if (ret < 0 || status != USBTMC_STATUS_SUCCESS) {
236                 if (ret < 0)
237                         sr_dbg("Failed to enter REN state: %s.", libusb_error_name(ret));
238                 else
239                         sr_dbg("Failed to enter REN state: USBTMC status %d.", status);
240                 return SR_ERR;
241         }
242
243         ret = libusb_control_transfer(usb->devhdl, LIBUSB_ENDPOINT_IN |
244                 LIBUSB_REQUEST_TYPE_CLASS | LIBUSB_RECIPIENT_INTERFACE,
245                 LOCAL_LOCKOUT, 0, uscpi->interface, &status, 1,
246                 TRANSFER_TIMEOUT);
247         if (ret < 0 || status != USBTMC_STATUS_SUCCESS) {
248                 if (ret < 0)
249                         sr_dbg("Failed to enter local lockout state: %s.",
250                                         libusb_error_name(ret));
251                 else
252                         sr_dbg("Failed to enter local lockout state: USBTMC "
253                                         "status %d.", status);
254                 return SR_ERR;
255         }
256
257         return SR_OK;
258 }
259
260 static void scpi_usbtmc_local(struct scpi_usbtmc_libusb *uscpi)
261 {
262         struct sr_usb_dev_inst *usb = uscpi->usb;
263         struct libusb_device *dev;
264         struct libusb_device_descriptor des;
265         int ret;
266         uint8_t status;
267
268         if (!(uscpi->usb488_dev_cap & USB488_DEV_CAP_RL1))
269                 return;
270
271         dev = libusb_get_device(usb->devhdl);
272         libusb_get_device_descriptor(dev, &des);
273         if (check_usbtmc_blacklist(blacklist_remote, des.idVendor, des.idProduct))
274                 return;
275
276         sr_dbg("Returning local control.");
277         ret = libusb_control_transfer(usb->devhdl, LIBUSB_ENDPOINT_IN |
278                 LIBUSB_REQUEST_TYPE_CLASS | LIBUSB_RECIPIENT_INTERFACE,
279                 GO_TO_LOCAL, 0, uscpi->interface, &status, 1, TRANSFER_TIMEOUT);
280         if (ret < 0 || status != USBTMC_STATUS_SUCCESS) {
281                 if (ret < 0)
282                         sr_dbg("Failed to clear local lockout state: %s.",
283                                         libusb_error_name(ret));
284                 else
285                         sr_dbg("Failed to clear local lockout state: USBTMC "
286                                         "status %d.", status);
287         }
288
289         return;
290 }
291
292 static int scpi_usbtmc_libusb_open(struct sr_scpi_dev_inst *scpi)
293 {
294         struct scpi_usbtmc_libusb *uscpi = scpi->priv;
295         struct sr_usb_dev_inst *usb = uscpi->usb;
296         struct libusb_device *dev;
297         struct libusb_device_descriptor des;
298         struct libusb_config_descriptor *confdes;
299         const struct libusb_interface_descriptor *intfdes;
300         const struct libusb_endpoint_descriptor *ep;
301         int confidx, intfidx, epidx, config = 0, current_config;
302         uint8_t capabilities[24];
303         int ret, found = 0;
304         int do_reset;
305
306         if (usb->devhdl)
307                 return SR_OK;
308
309         if (sr_usb_open(uscpi->ctx->libusb_ctx, usb) != SR_OK)
310                 return SR_ERR;
311
312         dev = libusb_get_device(usb->devhdl);
313         libusb_get_device_descriptor(dev, &des);
314
315         for (confidx = 0; confidx < des.bNumConfigurations; confidx++) {
316                 if ((ret = libusb_get_config_descriptor(dev, confidx, &confdes)) < 0) {
317                         if (ret != LIBUSB_ERROR_NOT_FOUND)
318                                 sr_dbg("Failed to get configuration descriptor: %s, "
319                                        "ignoring device.", libusb_error_name(ret));
320                         continue;
321                 }
322                 for (intfidx = 0; intfidx < confdes->bNumInterfaces; intfidx++) {
323                         intfdes = confdes->interface[intfidx].altsetting;
324                         if (intfdes->bInterfaceClass    != LIBUSB_CLASS_APPLICATION ||
325                             intfdes->bInterfaceSubClass != SUBCLASS_USBTMC ||
326                             intfdes->bInterfaceProtocol != USBTMC_USB488)
327                                 continue;
328                         uscpi->interface = intfdes->bInterfaceNumber;
329                         config = confdes->bConfigurationValue;
330                         sr_dbg("Interface %d configuration %d.", uscpi->interface, config);
331                         for (epidx = 0; epidx < intfdes->bNumEndpoints; epidx++) {
332                                 ep = &intfdes->endpoint[epidx];
333                                 if (ep->bmAttributes == LIBUSB_TRANSFER_TYPE_BULK &&
334                                     !(ep->bEndpointAddress & (LIBUSB_ENDPOINT_DIR_MASK))) {
335                                         uscpi->bulk_out_ep = ep->bEndpointAddress;
336                                         sr_dbg("Bulk OUT EP %d", uscpi->bulk_out_ep);
337                                 }
338                                 if (ep->bmAttributes == LIBUSB_TRANSFER_TYPE_BULK &&
339                                     ep->bEndpointAddress & (LIBUSB_ENDPOINT_DIR_MASK)) {
340                                         uscpi->bulk_in_ep = ep->bEndpointAddress;
341                                         sr_dbg("Bulk IN EP %d", uscpi->bulk_in_ep & 0x7f);
342                                 }
343                                 if (ep->bmAttributes == LIBUSB_TRANSFER_TYPE_INTERRUPT &&
344                                     ep->bEndpointAddress & (LIBUSB_ENDPOINT_DIR_MASK)) {
345                                         uscpi->interrupt_ep = ep->bEndpointAddress;
346                                         sr_dbg("Interrupt EP %d", uscpi->interrupt_ep & 0x7f);
347                                 }
348                         }
349                         found = 1;
350                 }
351                 libusb_free_config_descriptor(confdes);
352                 if (found)
353                         break;
354         }
355
356         if (!found) {
357                 sr_err("Failed to find USBTMC interface.");
358                 return SR_ERR;
359         }
360
361         if (libusb_kernel_driver_active(usb->devhdl, uscpi->interface) == 1) {
362                 if ((ret = libusb_detach_kernel_driver(usb->devhdl,
363                                                        uscpi->interface)) < 0) {
364                         sr_err("Failed to detach kernel driver: %s.",
365                                libusb_error_name(ret));
366                         return SR_ERR;
367                 }
368                 uscpi->detached_kernel_driver = 1;
369         }
370
371         if (libusb_get_configuration(usb->devhdl, &current_config) == 0
372             && current_config != config) {
373                 if ((ret = libusb_set_configuration(usb->devhdl, config)) < 0) {
374                         sr_err("Failed to set configuration: %s.",
375                                libusb_error_name(ret));
376                         return SR_ERR;
377                 }
378         }
379
380         if ((ret = libusb_claim_interface(usb->devhdl, uscpi->interface)) < 0) {
381                 sr_err("Failed to claim interface: %s.",
382                        libusb_error_name(ret));
383                 return SR_ERR;
384         }
385
386         /* Optionally reset the USB device. */
387         do_reset = check_usbtmc_blacklist(whitelist_usb_reset,
388                 des.idVendor, des.idProduct);
389         if (do_reset)
390                 libusb_reset_device(usb->devhdl);
391
392         /* Get capabilities. */
393         ret = libusb_control_transfer(usb->devhdl, LIBUSB_ENDPOINT_IN |
394                 LIBUSB_REQUEST_TYPE_CLASS | LIBUSB_RECIPIENT_INTERFACE,
395                 GET_CAPABILITIES, 0, uscpi->interface, capabilities,
396                 sizeof(capabilities), TRANSFER_TIMEOUT);
397         if (ret == sizeof(capabilities)) {
398                 uscpi->usbtmc_int_cap = capabilities[ 4];
399                 uscpi->usbtmc_dev_cap = capabilities[ 5];
400                 uscpi->usb488_dev_cap = capabilities[15];
401         }
402         sr_dbg("Device capabilities: %s%s%s%s%s, %s, %s",
403                uscpi->usb488_dev_cap & USB488_DEV_CAP_SCPI        ? "SCPI, "    : "",
404                uscpi->usbtmc_dev_cap & USBTMC_DEV_CAP_TERMCHAR    ? "TermChar, ": "",
405                uscpi->usbtmc_int_cap & USBTMC_INT_CAP_LISTEN_ONLY ? "L3, " :
406                uscpi->usbtmc_int_cap & USBTMC_INT_CAP_TALK_ONLY   ? ""     : "L4, ",
407                uscpi->usbtmc_int_cap & USBTMC_INT_CAP_TALK_ONLY   ? "T5, " :
408                uscpi->usbtmc_int_cap & USBTMC_INT_CAP_LISTEN_ONLY ? ""     : "T6, ",
409                uscpi->usb488_dev_cap & USB488_DEV_CAP_SR1         ? "SR1"  : "SR0",
410                uscpi->usb488_dev_cap & USB488_DEV_CAP_RL1         ? "RL1"  : "RL0",
411                uscpi->usb488_dev_cap & USB488_DEV_CAP_DT1         ? "DT1"  : "DT0");
412
413         scpi_usbtmc_remote(uscpi);
414
415         return SR_OK;
416 }
417
418 static int scpi_usbtmc_libusb_connection_id(struct sr_scpi_dev_inst *scpi,
419                 char **connection_id)
420 {
421         struct scpi_usbtmc_libusb *uscpi = scpi->priv;
422         struct sr_usb_dev_inst *usb = uscpi->usb;
423
424         *connection_id = g_strdup_printf("%s/%" PRIu8 ".%" PRIu8 "",
425                 scpi->prefix, usb->bus, usb->address);
426
427         return SR_OK;
428 }
429
430 static int scpi_usbtmc_libusb_source_add(struct sr_session *session,
431                 void *priv, int events, int timeout, sr_receive_data_callback cb,
432                 void *cb_data)
433 {
434         struct scpi_usbtmc_libusb *uscpi = priv;
435         (void)events;
436         return usb_source_add(session, uscpi->ctx, timeout, cb, cb_data);
437 }
438
439 static int scpi_usbtmc_libusb_source_remove(struct sr_session *session,
440                 void *priv)
441 {
442         struct scpi_usbtmc_libusb *uscpi = priv;
443         return usb_source_remove(session, uscpi->ctx);
444 }
445
446 static void usbtmc_bulk_out_header_write(void *header, uint8_t MsgID,
447                                          uint8_t bTag,
448                                          uint32_t TransferSize,
449                                          uint8_t bmTransferAttributes,
450                                          char TermChar)
451 {
452           W8(header +  0, MsgID);
453           W8(header +  1, bTag);
454           W8(header +  2, ~bTag);
455           W8(header +  3, 0);
456         WL32(header +  4, TransferSize);
457           W8(header +  8, bmTransferAttributes);
458           W8(header +  9, TermChar);
459         WL16(header + 10, 0);
460 }
461
462 static int usbtmc_bulk_in_header_read(void *header, uint8_t MsgID,
463                                       unsigned char bTag,
464                                       int32_t *TransferSize,
465                                       uint8_t *bmTransferAttributes)
466 {
467         if (R8(header + 0) != MsgID ||
468             R8(header + 1) != bTag  ||
469             R8(header + 2) != (unsigned char)~bTag)
470                 return SR_ERR;
471         if (TransferSize)
472                 *TransferSize = RL32(header + 4);
473         if (bmTransferAttributes)
474                 *bmTransferAttributes = R8(header + 8);
475
476         return SR_OK;
477 }
478
479 static int scpi_usbtmc_bulkout(struct scpi_usbtmc_libusb *uscpi,
480                                uint8_t msg_id, const void *data, int32_t size,
481                                uint8_t transfer_attributes)
482 {
483         struct sr_usb_dev_inst *usb = uscpi->usb;
484         int padded_size, ret, transferred;
485
486         if (data && (size + USBTMC_BULK_HEADER_SIZE + 3) > (int)sizeof(uscpi->buffer)) {
487                 sr_err("USBTMC bulk out transfer is too big.");
488                 return SR_ERR;
489         }
490
491         uscpi->bTag++;
492         uscpi->bTag += !uscpi->bTag; /* bTag == 0 is invalid so avoid it. */
493
494         usbtmc_bulk_out_header_write(uscpi->buffer, msg_id, uscpi->bTag,
495                                      size, transfer_attributes, 0);
496         if (data)
497                 memcpy(uscpi->buffer + USBTMC_BULK_HEADER_SIZE, data, size);
498         else
499                 size = 0;
500         size += USBTMC_BULK_HEADER_SIZE;
501         padded_size = (size + 3) & ~0x3;
502         memset(uscpi->buffer + size, 0, padded_size - size);
503
504         ret = libusb_bulk_transfer(usb->devhdl, uscpi->bulk_out_ep,
505                                    uscpi->buffer, padded_size, &transferred,
506                                    TRANSFER_TIMEOUT);
507         if (ret < 0) {
508                 sr_err("USBTMC bulk out transfer error: %s.",
509                        libusb_error_name(ret));
510                 return SR_ERR;
511         }
512
513         if (transferred < padded_size) {
514                 sr_dbg("USBTMC bulk out partial transfer (%d/%d bytes).",
515                        transferred, padded_size);
516                 return SR_ERR;
517         }
518
519         return transferred - USBTMC_BULK_HEADER_SIZE;
520 }
521
522 static int scpi_usbtmc_bulkin_start(struct scpi_usbtmc_libusb *uscpi,
523                                     uint8_t msg_id, void *data, int32_t size,
524                                     uint8_t *transfer_attributes)
525 {
526         struct sr_usb_dev_inst *usb = uscpi->usb;
527         int ret, transferred, message_size, tries;
528
529         for (tries = 0; ; tries++) {
530                 ret = libusb_bulk_transfer(usb->devhdl, uscpi->bulk_in_ep, data,
531                                            size, &transferred,
532                                            TRANSFER_TIMEOUT);
533                 if (ret < 0) {
534                         sr_err("USBTMC bulk in transfer error: %s.",
535                                libusb_error_name(ret));
536                         return SR_ERR;
537                 }
538
539                 if (transferred == 0 && tries < 1) {
540                         /*
541                          * The DEV_DEP_MSG_IN message is empty, and the TMC
542                          * spec says it should at least contain a header.
543                          * The Rigol DS1054Z seems to do this sometimes, and
544                          * it follows up with a valid message.  Give the device
545                          * one more chance to send a header.
546                          */
547                         sr_warn("USBTMC bulk in start was empty; retrying\n");
548                         continue;
549                 }
550
551                 if (transferred < USBTMC_BULK_HEADER_SIZE) {
552                         sr_err("USBTMC bulk in returned too little data: %d/%d bytes\n", transferred, size);
553                         return SR_ERR;
554                 }
555
556                 break;
557         }
558
559         if (usbtmc_bulk_in_header_read(data, msg_id, uscpi->bTag, &message_size,
560                                        transfer_attributes) != SR_OK) {
561                 sr_err("USBTMC invalid bulk in header.");
562                 return SR_ERR;
563         }
564
565         message_size += USBTMC_BULK_HEADER_SIZE;
566         uscpi->response_length = MIN(transferred, message_size);
567         uscpi->response_bytes_read = USBTMC_BULK_HEADER_SIZE;
568         uscpi->remaining_length = message_size - uscpi->response_length;
569
570         return transferred - USBTMC_BULK_HEADER_SIZE;
571 }
572
573 static int scpi_usbtmc_bulkin_continue(struct scpi_usbtmc_libusb *uscpi,
574                                        void *data, int size)
575 {
576         struct sr_usb_dev_inst *usb = uscpi->usb;
577         int ret, transferred;
578
579         ret = libusb_bulk_transfer(usb->devhdl, uscpi->bulk_in_ep, data, size,
580                                    &transferred, TRANSFER_TIMEOUT);
581         if (ret < 0) {
582                 sr_err("USBTMC bulk in transfer error: %s.",
583                        libusb_error_name(ret));
584                 return SR_ERR;
585         }
586
587         uscpi->response_length = MIN(transferred, uscpi->remaining_length);
588         uscpi->response_bytes_read = 0;
589         uscpi->remaining_length -= uscpi->response_length;
590
591         return transferred;
592 }
593
594 static int scpi_usbtmc_libusb_send(void *priv, const char *command)
595 {
596         struct scpi_usbtmc_libusb *uscpi = priv;
597
598         if (scpi_usbtmc_bulkout(uscpi, DEV_DEP_MSG_OUT,
599                                 command, strlen(command), EOM) <= 0)
600                 return SR_ERR;
601
602         sr_spew("Successfully sent SCPI command: '%s'.", command);
603
604         return SR_OK;
605 }
606
607 static int scpi_usbtmc_libusb_read_begin(void *priv)
608 {
609         struct scpi_usbtmc_libusb *uscpi = priv;
610
611         uscpi->remaining_length = 0;
612
613         if (scpi_usbtmc_bulkout(uscpi, REQUEST_DEV_DEP_MSG_IN,
614             NULL, INT32_MAX, 0) < 0)
615                 return SR_ERR;
616         if (scpi_usbtmc_bulkin_start(uscpi, DEV_DEP_MSG_IN,
617                                      uscpi->buffer, sizeof(uscpi->buffer),
618                                      &uscpi->bulkin_attributes) < 0)
619                 return SR_ERR;
620
621         return SR_OK;
622 }
623
624 static int scpi_usbtmc_libusb_read_data(void *priv, char *buf, int maxlen)
625 {
626         struct scpi_usbtmc_libusb *uscpi = priv;
627         int read_length;
628
629         if (uscpi->response_bytes_read >= uscpi->response_length) {
630                 if (uscpi->remaining_length > 0) {
631                         if (scpi_usbtmc_bulkin_continue(uscpi, uscpi->buffer,
632                                                         sizeof(uscpi->buffer)) <= 0)
633                                 return SR_ERR;
634                 } else {
635                         if (uscpi->bulkin_attributes & EOM)
636                                 return SR_ERR;
637                         if (scpi_usbtmc_libusb_read_begin(uscpi) < 0)
638                                 return SR_ERR;
639                 }
640         }
641
642         read_length = MIN(uscpi->response_length - uscpi->response_bytes_read, maxlen);
643
644         memcpy(buf, uscpi->buffer + uscpi->response_bytes_read, read_length);
645
646         uscpi->response_bytes_read += read_length;
647
648         return read_length;
649 }
650
651 static int scpi_usbtmc_libusb_read_complete(void *priv)
652 {
653         struct scpi_usbtmc_libusb *uscpi = priv;
654         return uscpi->response_bytes_read >= uscpi->response_length &&
655                uscpi->remaining_length <= 0 &&
656                uscpi->bulkin_attributes & EOM;
657 }
658
659 static int scpi_usbtmc_libusb_close(struct sr_scpi_dev_inst *scpi)
660 {
661         struct scpi_usbtmc_libusb *uscpi = scpi->priv;
662         struct sr_usb_dev_inst *usb = uscpi->usb;
663         int ret;
664
665         if (!usb->devhdl)
666                 return SR_ERR;
667
668         scpi_usbtmc_local(uscpi);
669
670         if ((ret = libusb_release_interface(usb->devhdl, uscpi->interface)) < 0)
671                 sr_err("Failed to release interface: %s.",
672                        libusb_error_name(ret));
673
674         if (uscpi->detached_kernel_driver) {
675                 if ((ret = libusb_attach_kernel_driver(usb->devhdl,
676                                                 uscpi->interface)) < 0)
677                         sr_err("Failed to re-attach kernel driver: %s.",
678                                libusb_error_name(ret));
679
680                 uscpi->detached_kernel_driver = 0;
681         }
682         sr_usb_close(usb);
683
684         return SR_OK;
685 }
686
687 static void scpi_usbtmc_libusb_free(void *priv)
688 {
689         struct scpi_usbtmc_libusb *uscpi = priv;
690         sr_usb_dev_inst_free(uscpi->usb);
691 }
692
693 SR_PRIV const struct sr_scpi_dev_inst scpi_usbtmc_libusb_dev = {
694         .name          = "USBTMC",
695         .prefix        = "usbtmc",
696         .transport     = SCPI_TRANSPORT_USBTMC,
697         .priv_size     = sizeof(struct scpi_usbtmc_libusb),
698         .scan          = scpi_usbtmc_libusb_scan,
699         .dev_inst_new  = scpi_usbtmc_libusb_dev_inst_new,
700         .open          = scpi_usbtmc_libusb_open,
701         .connection_id = scpi_usbtmc_libusb_connection_id,
702         .source_add    = scpi_usbtmc_libusb_source_add,
703         .source_remove = scpi_usbtmc_libusb_source_remove,
704         .send          = scpi_usbtmc_libusb_send,
705         .read_begin    = scpi_usbtmc_libusb_read_begin,
706         .read_data     = scpi_usbtmc_libusb_read_data,
707         .read_complete = scpi_usbtmc_libusb_read_complete,
708         .close         = scpi_usbtmc_libusb_close,
709         .free          = scpi_usbtmc_libusb_free,
710 };