]> sigrok.org Git - libsigrok.git/blob - src/scpi/scpi_usbtmc_libusb.c
d09b35ffb42b165bd12880e123cf0aba42221f00
[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         { 0x0957, 0x0588 }, /* Agilent DSO1000 series (rebadged Rigol DS1000) */
111         { 0x0b21, 0xffff }, /* All Yokogawa devices */
112         { 0xf4ec, 0xffff }, /* All Siglent SDS devices */
113         ALL_ZERO
114 };
115
116 /* Devices that shall get reset during open(). */
117 static struct usbtmc_blacklist whitelist_usb_reset[] = {
118         { 0xf4ec, 0xffff }, /* All Siglent SDS devices */
119         ALL_ZERO
120 };
121
122 static GSList *scpi_usbtmc_libusb_scan(struct drv_context *drvc)
123 {
124         struct libusb_device **devlist;
125         struct libusb_device_descriptor des;
126         struct libusb_config_descriptor *confdes;
127         const struct libusb_interface_descriptor *intfdes;
128         GSList *resources = NULL;
129         int confidx, intfidx, ret, i;
130         char *res;
131
132         ret = libusb_get_device_list(drvc->sr_ctx->libusb_ctx, &devlist);
133         if (ret < 0) {
134                 sr_err("Failed to get device list: %s.",
135                        libusb_error_name(ret));
136                 return NULL;
137         }
138         for (i = 0; devlist[i]; i++) {
139                 libusb_get_device_descriptor(devlist[i], &des);
140
141                 for (confidx = 0; confidx < des.bNumConfigurations; confidx++) {
142                         if ((ret = libusb_get_config_descriptor(devlist[i], confidx, &confdes)) < 0) {
143                                 if (ret != LIBUSB_ERROR_NOT_FOUND)
144                                         sr_dbg("Failed to get configuration descriptor: %s, "
145                                                "ignoring device.", libusb_error_name(ret));
146                                 break;
147                         }
148                         for (intfidx = 0; intfidx < confdes->bNumInterfaces; intfidx++) {
149                                 intfdes = confdes->interface[intfidx].altsetting;
150                                 if (intfdes->bInterfaceClass    != LIBUSB_CLASS_APPLICATION ||
151                                     intfdes->bInterfaceSubClass != SUBCLASS_USBTMC          ||
152                                     intfdes->bInterfaceProtocol != USBTMC_USB488)
153                                         continue;
154                                 sr_dbg("Found USBTMC device (VID:PID = %04x:%04x, "
155                                        "bus.address = %d.%d).", des.idVendor, des.idProduct,
156                                        libusb_get_bus_number(devlist[i]),
157                                        libusb_get_device_address(devlist[i]));
158                                 res = g_strdup_printf("usbtmc/%d.%d",
159                                                       libusb_get_bus_number(devlist[i]),
160                                                       libusb_get_device_address(devlist[i]));
161                                 resources = g_slist_append(resources, res);
162                         }
163                         libusb_free_config_descriptor(confdes);
164                 }
165         }
166         libusb_free_device_list(devlist, 1);
167
168         /* No log message for #devices found (caller will log that). */
169
170         return resources;
171 }
172
173 static int scpi_usbtmc_libusb_dev_inst_new(void *priv, struct drv_context *drvc,
174                 const char *resource, char **params, const char *serialcomm)
175 {
176         struct scpi_usbtmc_libusb *uscpi = priv;
177         GSList *devices;
178
179         (void)resource;
180         (void)serialcomm;
181
182         if (!params || !params[1]) {
183                 sr_err("Invalid parameters.");
184                 return SR_ERR;
185         }
186
187         uscpi->ctx = drvc->sr_ctx;
188         devices = sr_usb_find(uscpi->ctx->libusb_ctx, params[1]);
189         if (g_slist_length(devices) != 1) {
190                 sr_err("Failed to find USB device '%s'.", params[1]);
191                 g_slist_free_full(devices, (GDestroyNotify)sr_usb_dev_inst_free);
192                 return SR_ERR;
193         }
194         uscpi->usb = devices->data;
195         g_slist_free(devices);
196
197         return SR_OK;
198 }
199
200 static int check_usbtmc_blacklist(struct usbtmc_blacklist *blacklist,
201                 uint16_t vid, uint16_t pid)
202 {
203         int i;
204
205         for (i = 0; blacklist[i].vid; i++) {
206                 if ((blacklist[i].vid == vid && blacklist[i].pid == 0xFFFF) ||
207                         (blacklist[i].vid == vid && blacklist[i].pid == pid))
208                         return TRUE;
209         }
210
211         return FALSE;
212 }
213
214 static int scpi_usbtmc_remote(struct scpi_usbtmc_libusb *uscpi)
215 {
216         struct sr_usb_dev_inst *usb = uscpi->usb;
217         struct libusb_device *dev;
218         struct libusb_device_descriptor des;
219         int ret;
220         uint8_t status;
221
222         if (!(uscpi->usb488_dev_cap & USB488_DEV_CAP_RL1))
223                 return SR_OK;
224
225         dev = libusb_get_device(usb->devhdl);
226         libusb_get_device_descriptor(dev, &des);
227         if (check_usbtmc_blacklist(blacklist_remote, des.idVendor, des.idProduct))
228                 return SR_OK;
229
230         sr_dbg("Locking out local control.");
231         ret = libusb_control_transfer(usb->devhdl, LIBUSB_ENDPOINT_IN |
232                 LIBUSB_REQUEST_TYPE_CLASS | LIBUSB_RECIPIENT_INTERFACE,
233                 REN_CONTROL, 1, uscpi->interface, &status, 1, TRANSFER_TIMEOUT);
234         if (ret < 0 || status != USBTMC_STATUS_SUCCESS) {
235                 if (ret < 0)
236                         sr_dbg("Failed to enter REN state: %s.", libusb_error_name(ret));
237                 else
238                         sr_dbg("Failed to enter REN state: USBTMC status %d.", status);
239                 return SR_ERR;
240         }
241
242         ret = libusb_control_transfer(usb->devhdl, LIBUSB_ENDPOINT_IN |
243                 LIBUSB_REQUEST_TYPE_CLASS | LIBUSB_RECIPIENT_INTERFACE,
244                 LOCAL_LOCKOUT, 0, uscpi->interface, &status, 1,
245                 TRANSFER_TIMEOUT);
246         if (ret < 0 || status != USBTMC_STATUS_SUCCESS) {
247                 if (ret < 0)
248                         sr_dbg("Failed to enter local lockout state: %s.",
249                                         libusb_error_name(ret));
250                 else
251                         sr_dbg("Failed to enter local lockout state: USBTMC "
252                                         "status %d.", status);
253                 return SR_ERR;
254         }
255
256         return SR_OK;
257 }
258
259 static void scpi_usbtmc_local(struct scpi_usbtmc_libusb *uscpi)
260 {
261         struct sr_usb_dev_inst *usb = uscpi->usb;
262         struct libusb_device *dev;
263         struct libusb_device_descriptor des;
264         int ret;
265         uint8_t status;
266
267         if (!(uscpi->usb488_dev_cap & USB488_DEV_CAP_RL1))
268                 return;
269
270         dev = libusb_get_device(usb->devhdl);
271         libusb_get_device_descriptor(dev, &des);
272         if (check_usbtmc_blacklist(blacklist_remote, des.idVendor, des.idProduct))
273                 return;
274
275         sr_dbg("Returning local control.");
276         ret = libusb_control_transfer(usb->devhdl, LIBUSB_ENDPOINT_IN |
277                 LIBUSB_REQUEST_TYPE_CLASS | LIBUSB_RECIPIENT_INTERFACE,
278                 GO_TO_LOCAL, 0, uscpi->interface, &status, 1, TRANSFER_TIMEOUT);
279         if (ret < 0 || status != USBTMC_STATUS_SUCCESS) {
280                 if (ret < 0)
281                         sr_dbg("Failed to clear local lockout state: %s.",
282                                         libusb_error_name(ret));
283                 else
284                         sr_dbg("Failed to clear local lockout state: USBTMC "
285                                         "status %d.", status);
286         }
287
288         return;
289 }
290
291 static int scpi_usbtmc_libusb_open(struct sr_scpi_dev_inst *scpi)
292 {
293         struct scpi_usbtmc_libusb *uscpi = scpi->priv;
294         struct sr_usb_dev_inst *usb = uscpi->usb;
295         struct libusb_device *dev;
296         struct libusb_device_descriptor des;
297         struct libusb_config_descriptor *confdes;
298         const struct libusb_interface_descriptor *intfdes;
299         const struct libusb_endpoint_descriptor *ep;
300         int confidx, intfidx, epidx, config = 0, current_config;
301         uint8_t capabilities[24];
302         int ret, found = 0;
303         int do_reset;
304
305         if (usb->devhdl)
306                 return SR_OK;
307
308         if (sr_usb_open(uscpi->ctx->libusb_ctx, usb) != SR_OK)
309                 return SR_ERR;
310
311         dev = libusb_get_device(usb->devhdl);
312         libusb_get_device_descriptor(dev, &des);
313
314         for (confidx = 0; confidx < des.bNumConfigurations; confidx++) {
315                 if ((ret = libusb_get_config_descriptor(dev, confidx, &confdes)) < 0) {
316                         if (ret != LIBUSB_ERROR_NOT_FOUND)
317                                 sr_dbg("Failed to get configuration descriptor: %s, "
318                                        "ignoring device.", libusb_error_name(ret));
319                         continue;
320                 }
321                 for (intfidx = 0; intfidx < confdes->bNumInterfaces; intfidx++) {
322                         intfdes = confdes->interface[intfidx].altsetting;
323                         if (intfdes->bInterfaceClass    != LIBUSB_CLASS_APPLICATION ||
324                             intfdes->bInterfaceSubClass != SUBCLASS_USBTMC ||
325                             intfdes->bInterfaceProtocol != USBTMC_USB488)
326                                 continue;
327                         uscpi->interface = intfdes->bInterfaceNumber;
328                         config = confdes->bConfigurationValue;
329                         sr_dbg("Interface %d configuration %d.", uscpi->interface, config);
330                         for (epidx = 0; epidx < intfdes->bNumEndpoints; epidx++) {
331                                 ep = &intfdes->endpoint[epidx];
332                                 if (ep->bmAttributes == LIBUSB_TRANSFER_TYPE_BULK &&
333                                     !(ep->bEndpointAddress & (LIBUSB_ENDPOINT_DIR_MASK))) {
334                                         uscpi->bulk_out_ep = ep->bEndpointAddress;
335                                         sr_dbg("Bulk OUT EP %d", uscpi->bulk_out_ep);
336                                 }
337                                 if (ep->bmAttributes == LIBUSB_TRANSFER_TYPE_BULK &&
338                                     ep->bEndpointAddress & (LIBUSB_ENDPOINT_DIR_MASK)) {
339                                         uscpi->bulk_in_ep = ep->bEndpointAddress;
340                                         sr_dbg("Bulk IN EP %d", uscpi->bulk_in_ep & 0x7f);
341                                 }
342                                 if (ep->bmAttributes == LIBUSB_TRANSFER_TYPE_INTERRUPT &&
343                                     ep->bEndpointAddress & (LIBUSB_ENDPOINT_DIR_MASK)) {
344                                         uscpi->interrupt_ep = ep->bEndpointAddress;
345                                         sr_dbg("Interrupt EP %d", uscpi->interrupt_ep & 0x7f);
346                                 }
347                         }
348                         found = 1;
349                 }
350                 libusb_free_config_descriptor(confdes);
351                 if (found)
352                         break;
353         }
354
355         if (!found) {
356                 sr_err("Failed to find USBTMC interface.");
357                 return SR_ERR;
358         }
359
360         if (libusb_kernel_driver_active(usb->devhdl, uscpi->interface) == 1) {
361                 if ((ret = libusb_detach_kernel_driver(usb->devhdl,
362                                                        uscpi->interface)) < 0) {
363                         sr_err("Failed to detach kernel driver: %s.",
364                                libusb_error_name(ret));
365                         return SR_ERR;
366                 }
367                 uscpi->detached_kernel_driver = 1;
368         }
369
370         if (libusb_get_configuration(usb->devhdl, &current_config) == 0
371             && current_config != config) {
372                 if ((ret = libusb_set_configuration(usb->devhdl, config)) < 0) {
373                         sr_err("Failed to set configuration: %s.",
374                                libusb_error_name(ret));
375                         return SR_ERR;
376                 }
377         }
378
379         if ((ret = libusb_claim_interface(usb->devhdl, uscpi->interface)) < 0) {
380                 sr_err("Failed to claim interface: %s.",
381                        libusb_error_name(ret));
382                 return SR_ERR;
383         }
384
385         /* Optionally reset the USB device. */
386         do_reset = check_usbtmc_blacklist(whitelist_usb_reset,
387                 des.idVendor, des.idProduct);
388         if (do_reset)
389                 libusb_reset_device(usb->devhdl);
390
391         /* Get capabilities. */
392         ret = libusb_control_transfer(usb->devhdl, LIBUSB_ENDPOINT_IN |
393                 LIBUSB_REQUEST_TYPE_CLASS | LIBUSB_RECIPIENT_INTERFACE,
394                 GET_CAPABILITIES, 0, uscpi->interface, capabilities,
395                 sizeof(capabilities), TRANSFER_TIMEOUT);
396         if (ret == sizeof(capabilities)) {
397                 uscpi->usbtmc_int_cap = capabilities[ 4];
398                 uscpi->usbtmc_dev_cap = capabilities[ 5];
399                 uscpi->usb488_dev_cap = capabilities[15];
400         }
401         sr_dbg("Device capabilities: %s%s%s%s%s, %s, %s",
402                uscpi->usb488_dev_cap & USB488_DEV_CAP_SCPI        ? "SCPI, "    : "",
403                uscpi->usbtmc_dev_cap & USBTMC_DEV_CAP_TERMCHAR    ? "TermChar, ": "",
404                uscpi->usbtmc_int_cap & USBTMC_INT_CAP_LISTEN_ONLY ? "L3, " :
405                uscpi->usbtmc_int_cap & USBTMC_INT_CAP_TALK_ONLY   ? ""     : "L4, ",
406                uscpi->usbtmc_int_cap & USBTMC_INT_CAP_TALK_ONLY   ? "T5, " :
407                uscpi->usbtmc_int_cap & USBTMC_INT_CAP_LISTEN_ONLY ? ""     : "T6, ",
408                uscpi->usb488_dev_cap & USB488_DEV_CAP_SR1         ? "SR1"  : "SR0",
409                uscpi->usb488_dev_cap & USB488_DEV_CAP_RL1         ? "RL1"  : "RL0",
410                uscpi->usb488_dev_cap & USB488_DEV_CAP_DT1         ? "DT1"  : "DT0");
411
412         scpi_usbtmc_remote(uscpi);
413
414         return SR_OK;
415 }
416
417 static int scpi_usbtmc_libusb_connection_id(struct sr_scpi_dev_inst *scpi,
418                 char **connection_id)
419 {
420         struct scpi_usbtmc_libusb *uscpi = scpi->priv;
421         struct sr_usb_dev_inst *usb = uscpi->usb;
422
423         *connection_id = g_strdup_printf("%s/%" PRIu8 ".%" PRIu8 "",
424                 scpi->prefix, usb->bus, usb->address);
425
426         return SR_OK;
427 }
428
429 static int scpi_usbtmc_libusb_source_add(struct sr_session *session,
430                 void *priv, int events, int timeout, sr_receive_data_callback cb,
431                 void *cb_data)
432 {
433         struct scpi_usbtmc_libusb *uscpi = priv;
434         (void)events;
435         return usb_source_add(session, uscpi->ctx, timeout, cb, cb_data);
436 }
437
438 static int scpi_usbtmc_libusb_source_remove(struct sr_session *session,
439                 void *priv)
440 {
441         struct scpi_usbtmc_libusb *uscpi = priv;
442         return usb_source_remove(session, uscpi->ctx);
443 }
444
445 static void usbtmc_bulk_out_header_write(void *header, uint8_t MsgID,
446                                          uint8_t bTag,
447                                          uint32_t TransferSize,
448                                          uint8_t bmTransferAttributes,
449                                          char TermChar)
450 {
451           W8(header +  0, MsgID);
452           W8(header +  1, bTag);
453           W8(header +  2, ~bTag);
454           W8(header +  3, 0);
455         WL32(header +  4, TransferSize);
456           W8(header +  8, bmTransferAttributes);
457           W8(header +  9, TermChar);
458         WL16(header + 10, 0);
459 }
460
461 static int usbtmc_bulk_in_header_read(void *header, uint8_t MsgID,
462                                       unsigned char bTag,
463                                       int32_t *TransferSize,
464                                       uint8_t *bmTransferAttributes)
465 {
466         if (R8(header + 0) != MsgID ||
467             R8(header + 1) != bTag  ||
468             R8(header + 2) != (unsigned char)~bTag)
469                 return SR_ERR;
470         if (TransferSize)
471                 *TransferSize = RL32(header + 4);
472         if (bmTransferAttributes)
473                 *bmTransferAttributes = R8(header + 8);
474
475         return SR_OK;
476 }
477
478 static int scpi_usbtmc_bulkout(struct scpi_usbtmc_libusb *uscpi,
479                                uint8_t msg_id, const void *data, int32_t size,
480                                uint8_t transfer_attributes)
481 {
482         struct sr_usb_dev_inst *usb = uscpi->usb;
483         int padded_size, ret, transferred;
484
485         if (data && (size + USBTMC_BULK_HEADER_SIZE + 3) > (int)sizeof(uscpi->buffer)) {
486                 sr_err("USBTMC bulk out transfer is too big.");
487                 return SR_ERR;
488         }
489
490         uscpi->bTag++;
491         uscpi->bTag += !uscpi->bTag; /* bTag == 0 is invalid so avoid it. */
492
493         usbtmc_bulk_out_header_write(uscpi->buffer, msg_id, uscpi->bTag,
494                                      size, transfer_attributes, 0);
495         if (data)
496                 memcpy(uscpi->buffer + USBTMC_BULK_HEADER_SIZE, data, size);
497         else
498                 size = 0;
499         size += USBTMC_BULK_HEADER_SIZE;
500         padded_size = (size + 3) & ~0x3;
501         memset(uscpi->buffer + size, 0, padded_size - size);
502
503         ret = libusb_bulk_transfer(usb->devhdl, uscpi->bulk_out_ep,
504                                    uscpi->buffer, padded_size, &transferred,
505                                    TRANSFER_TIMEOUT);
506         if (ret < 0) {
507                 sr_err("USBTMC bulk out transfer error: %s.",
508                        libusb_error_name(ret));
509                 return SR_ERR;
510         }
511
512         if (transferred < padded_size) {
513                 sr_dbg("USBTMC bulk out partial transfer (%d/%d bytes).",
514                        transferred, padded_size);
515                 return SR_ERR;
516         }
517
518         return transferred - USBTMC_BULK_HEADER_SIZE;
519 }
520
521 static int scpi_usbtmc_bulkin_start(struct scpi_usbtmc_libusb *uscpi,
522                                     uint8_t msg_id, void *data, int32_t size,
523                                     uint8_t *transfer_attributes)
524 {
525         struct sr_usb_dev_inst *usb = uscpi->usb;
526         int ret, transferred, message_size;
527
528         ret = libusb_bulk_transfer(usb->devhdl, uscpi->bulk_in_ep, data, size,
529                                    &transferred, TRANSFER_TIMEOUT);
530         if (ret < 0) {
531                 sr_err("USBTMC bulk in transfer error: %s.",
532                        libusb_error_name(ret));
533                 return SR_ERR;
534         }
535
536         if (usbtmc_bulk_in_header_read(data, msg_id, uscpi->bTag, &message_size,
537                                        transfer_attributes) != SR_OK) {
538                 sr_err("USBTMC invalid bulk in header.");
539                 return SR_ERR;
540         }
541
542         message_size += USBTMC_BULK_HEADER_SIZE;
543         uscpi->response_length = MIN(transferred, message_size);
544         uscpi->response_bytes_read = USBTMC_BULK_HEADER_SIZE;
545         uscpi->remaining_length = message_size - uscpi->response_length;
546
547         return transferred - USBTMC_BULK_HEADER_SIZE;
548 }
549
550 static int scpi_usbtmc_bulkin_continue(struct scpi_usbtmc_libusb *uscpi,
551                                        void *data, int size)
552 {
553         struct sr_usb_dev_inst *usb = uscpi->usb;
554         int ret, transferred;
555
556         ret = libusb_bulk_transfer(usb->devhdl, uscpi->bulk_in_ep, data, size,
557                                    &transferred, TRANSFER_TIMEOUT);
558         if (ret < 0) {
559                 sr_err("USBTMC bulk in transfer error: %s.",
560                        libusb_error_name(ret));
561                 return SR_ERR;
562         }
563
564         uscpi->response_length = MIN(transferred, uscpi->remaining_length);
565         uscpi->response_bytes_read = 0;
566         uscpi->remaining_length -= uscpi->response_length;
567
568         return transferred;
569 }
570
571 static int scpi_usbtmc_libusb_send(void *priv, const char *command)
572 {
573         struct scpi_usbtmc_libusb *uscpi = priv;
574
575         if (scpi_usbtmc_bulkout(uscpi, DEV_DEP_MSG_OUT,
576                                 command, strlen(command), EOM) <= 0)
577                 return SR_ERR;
578
579         sr_spew("Successfully sent SCPI command: '%s'.", command);
580
581         return SR_OK;
582 }
583
584 static int scpi_usbtmc_libusb_read_begin(void *priv)
585 {
586         struct scpi_usbtmc_libusb *uscpi = priv;
587
588         uscpi->remaining_length = 0;
589
590         if (scpi_usbtmc_bulkout(uscpi, REQUEST_DEV_DEP_MSG_IN,
591             NULL, INT32_MAX, 0) < 0)
592                 return SR_ERR;
593         if (scpi_usbtmc_bulkin_start(uscpi, DEV_DEP_MSG_IN,
594                                      uscpi->buffer, sizeof(uscpi->buffer),
595                                      &uscpi->bulkin_attributes) < 0)
596                 return SR_ERR;
597
598         return SR_OK;
599 }
600
601 static int scpi_usbtmc_libusb_read_data(void *priv, char *buf, int maxlen)
602 {
603         struct scpi_usbtmc_libusb *uscpi = priv;
604         int read_length;
605
606         if (uscpi->response_bytes_read >= uscpi->response_length) {
607                 if (uscpi->remaining_length > 0) {
608                         if (scpi_usbtmc_bulkin_continue(uscpi, uscpi->buffer,
609                                                         sizeof(uscpi->buffer)) <= 0)
610                                 return SR_ERR;
611                 } else {
612                         if (uscpi->bulkin_attributes & EOM)
613                                 return SR_ERR;
614                         if (scpi_usbtmc_libusb_read_begin(uscpi) < 0)
615                                 return SR_ERR;
616                 }
617         }
618
619         read_length = MIN(uscpi->response_length - uscpi->response_bytes_read, maxlen);
620
621         memcpy(buf, uscpi->buffer + uscpi->response_bytes_read, read_length);
622
623         uscpi->response_bytes_read += read_length;
624
625         return read_length;
626 }
627
628 static int scpi_usbtmc_libusb_read_complete(void *priv)
629 {
630         struct scpi_usbtmc_libusb *uscpi = priv;
631         return uscpi->response_bytes_read >= uscpi->response_length &&
632                uscpi->remaining_length <= 0 &&
633                uscpi->bulkin_attributes & EOM;
634 }
635
636 static int scpi_usbtmc_libusb_close(struct sr_scpi_dev_inst *scpi)
637 {
638         struct scpi_usbtmc_libusb *uscpi = scpi->priv;
639         struct sr_usb_dev_inst *usb = uscpi->usb;
640         int ret;
641
642         if (!usb->devhdl)
643                 return SR_ERR;
644
645         scpi_usbtmc_local(uscpi);
646
647         if ((ret = libusb_release_interface(usb->devhdl, uscpi->interface)) < 0)
648                 sr_err("Failed to release interface: %s.",
649                        libusb_error_name(ret));
650
651         if (uscpi->detached_kernel_driver) {
652                 if ((ret = libusb_attach_kernel_driver(usb->devhdl,
653                                                 uscpi->interface)) < 0)
654                         sr_err("Failed to re-attach kernel driver: %s.",
655                                libusb_error_name(ret));
656
657                 uscpi->detached_kernel_driver = 0;
658         }
659         sr_usb_close(usb);
660
661         return SR_OK;
662 }
663
664 static void scpi_usbtmc_libusb_free(void *priv)
665 {
666         struct scpi_usbtmc_libusb *uscpi = priv;
667         sr_usb_dev_inst_free(uscpi->usb);
668 }
669
670 SR_PRIV const struct sr_scpi_dev_inst scpi_usbtmc_libusb_dev = {
671         .name          = "USBTMC",
672         .prefix        = "usbtmc",
673         .transport     = SCPI_TRANSPORT_USBTMC,
674         .priv_size     = sizeof(struct scpi_usbtmc_libusb),
675         .scan          = scpi_usbtmc_libusb_scan,
676         .dev_inst_new  = scpi_usbtmc_libusb_dev_inst_new,
677         .open          = scpi_usbtmc_libusb_open,
678         .connection_id = scpi_usbtmc_libusb_connection_id,
679         .source_add    = scpi_usbtmc_libusb_source_add,
680         .source_remove = scpi_usbtmc_libusb_source_remove,
681         .send          = scpi_usbtmc_libusb_send,
682         .read_begin    = scpi_usbtmc_libusb_read_begin,
683         .read_data     = scpi_usbtmc_libusb_read_data,
684         .read_complete = scpi_usbtmc_libusb_read_complete,
685         .close         = scpi_usbtmc_libusb_close,
686         .free          = scpi_usbtmc_libusb_free,
687 };