]> sigrok.org Git - libsigrok.git/blob - src/scpi/scpi_usbtmc_libusb.c
output/csv: use intermediate time_t var, silence compiler warning
[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 <string.h>
22 #include <libsigrok/libsigrok.h>
23 #include "libsigrok-internal.h"
24 #include "scpi.h"
25
26 #define LOG_PREFIX "scpi_usbtmc"
27
28 #define MAX_TRANSFER_LENGTH 2048
29 #define TRANSFER_TIMEOUT 1000
30
31 struct scpi_usbtmc_libusb {
32         struct sr_context *ctx;
33         struct sr_usb_dev_inst *usb;
34         int detached_kernel_driver;
35         uint8_t interface;
36         uint8_t bulk_in_ep;
37         uint8_t bulk_out_ep;
38         uint8_t interrupt_ep;
39         uint8_t usbtmc_int_cap;
40         uint8_t usbtmc_dev_cap;
41         uint8_t usb488_dev_cap;
42         uint8_t bTag;
43         uint8_t bulkin_attributes;
44         uint8_t buffer[MAX_TRANSFER_LENGTH];
45         int response_length;
46         int response_bytes_read;
47         int remaining_length;
48 };
49
50 /* Some USBTMC-specific enums, as defined in the USBTMC standard. */
51 #define SUBCLASS_USBTMC  0x03
52 #define USBTMC_USB488    0x01
53
54 enum {
55         /* USBTMC control requests */
56         INITIATE_ABORT_BULK_OUT     =   1,
57         CHECK_ABORT_BULK_OUT_STATUS =   2,
58         INITIATE_ABORT_BULK_IN      =   3,
59         CHECK_ABORT_BULK_IN_STATUS  =   4,
60         INITIATE_CLEAR              =   5,
61         CHECK_CLEAR_STATUS          =   6,
62         GET_CAPABILITIES            =   7,
63         INDICATOR_PULSE             =  64,
64
65         /* USB488 control requests */
66         READ_STATUS_BYTE            = 128,
67         REN_CONTROL                 = 160,
68         GO_TO_LOCAL                 = 161,
69         LOCAL_LOCKOUT               = 162,
70 };
71
72 /* USBTMC status codes */
73 #define USBTMC_STATUS_SUCCESS      0x01
74
75 /* USBTMC capabilities */
76 #define USBTMC_INT_CAP_LISTEN_ONLY 0x01
77 #define USBTMC_INT_CAP_TALK_ONLY   0x02
78 #define USBTMC_INT_CAP_INDICATOR   0x04
79
80 #define USBTMC_DEV_CAP_TERMCHAR    0x01
81
82 #define USB488_DEV_CAP_DT1         0x01
83 #define USB488_DEV_CAP_RL1         0x02
84 #define USB488_DEV_CAP_SR1         0x04
85 #define USB488_DEV_CAP_SCPI        0x08
86
87 /* Bulk messages constants */
88 #define USBTMC_BULK_HEADER_SIZE  12
89
90 /* Bulk MsgID values */
91 #define DEV_DEP_MSG_OUT         1
92 #define REQUEST_DEV_DEP_MSG_IN  2
93 #define DEV_DEP_MSG_IN          2
94
95 /* bmTransferAttributes */
96 #define EOM                0x01
97 #define TERM_CHAR_ENABLED  0x02
98
99 struct usbtmc_blacklist {
100         uint16_t vid;
101         uint16_t pid;
102 };
103
104 /* Devices that publish RL1 support, but don't support it. */
105 static struct usbtmc_blacklist blacklist_remote[] = {
106         { 0x1ab1, 0x0588 },  /* Rigol DS1000 series */
107         { 0x1ab1, 0x04b0 },  /* Rigol DS2000 series */
108         { 0x0957, 0x0588 },  /* Agilent DSO1000 series (rebadged Rigol DS1000) */
109         ALL_ZERO
110 };
111
112 static GSList *scpi_usbtmc_libusb_scan(struct drv_context *drvc)
113 {
114         struct libusb_device **devlist;
115         struct libusb_device_descriptor des;
116         struct libusb_config_descriptor *confdes;
117         const struct libusb_interface_descriptor *intfdes;
118         GSList *resources = NULL;
119         int confidx, intfidx, ret, i;
120         char *res;
121
122         ret = libusb_get_device_list(drvc->sr_ctx->libusb_ctx, &devlist);
123         if (ret < 0) {
124                 sr_err("Failed to get device list: %s.",
125                        libusb_error_name(ret));
126                 return NULL;
127         }
128         for (i = 0; devlist[i]; i++) {
129                 libusb_get_device_descriptor(devlist[i], &des);
130
131                 for (confidx = 0; confidx < des.bNumConfigurations; confidx++) {
132                         if ((ret = libusb_get_config_descriptor(devlist[i], confidx, &confdes)) < 0) {
133                                 sr_dbg("Failed to get configuration descriptor: %s, "
134                                        "ignoring device.", libusb_error_name(ret));
135                                 break;
136                         }
137                         for (intfidx = 0; intfidx < confdes->bNumInterfaces; intfidx++) {
138                                 intfdes = confdes->interface[intfidx].altsetting;
139                                 if (intfdes->bInterfaceClass    != LIBUSB_CLASS_APPLICATION ||
140                                     intfdes->bInterfaceSubClass != SUBCLASS_USBTMC          ||
141                                     intfdes->bInterfaceProtocol != USBTMC_USB488)
142                                         continue;
143                                 sr_dbg("Found USBTMC device (VID:PID = %04x:%04x, "
144                                        "bus.address = %d.%d).", des.idVendor, des.idProduct,
145                                        libusb_get_bus_number(devlist[i]),
146                                        libusb_get_device_address(devlist[i]));
147                                 res = g_strdup_printf("usbtmc/%d.%d",
148                                                       libusb_get_bus_number(devlist[i]),
149                                                       libusb_get_device_address(devlist[i]));
150                                 resources = g_slist_append(resources, res);
151                         }
152                         libusb_free_config_descriptor(confdes);
153                 }
154         }
155         libusb_free_device_list(devlist, 1);
156
157         sr_dbg("Found %d device(s).", g_slist_length(resources));
158
159         return resources;
160 }
161
162 static int scpi_usbtmc_libusb_dev_inst_new(void *priv, struct drv_context *drvc,
163                 const char *resource, char **params, const char *serialcomm)
164 {
165         struct scpi_usbtmc_libusb *uscpi = priv;
166         GSList *devices;
167
168         (void)resource;
169         (void)serialcomm;
170
171         if (!params || !params[1]) {
172                 sr_err("Invalid parameters.");
173                 return SR_ERR;
174         }
175
176         uscpi->ctx = drvc->sr_ctx;
177         devices = sr_usb_find(uscpi->ctx->libusb_ctx, params[1]);
178         if (g_slist_length(devices) != 1) {
179                 sr_err("Failed to find USB device '%s'.", params[1]);
180                 g_slist_free_full(devices, (GDestroyNotify)sr_usb_dev_inst_free);
181                 return SR_ERR;
182         }
183         uscpi->usb = devices->data;
184         g_slist_free(devices);
185
186         return SR_OK;
187 }
188
189 static int check_usbtmc_blacklist(struct usbtmc_blacklist *blacklist,
190                 uint16_t vid, uint16_t pid)
191 {
192         int i;
193
194         for (i = 0; blacklist[i].vid; i++) {
195                 if (blacklist[i].vid == vid && blacklist[i].pid == pid)
196                         return TRUE;
197         }
198
199         return FALSE;
200 }
201
202 static int scpi_usbtmc_remote(struct scpi_usbtmc_libusb *uscpi)
203 {
204         struct sr_usb_dev_inst *usb = uscpi->usb;
205         struct libusb_device *dev;
206         struct libusb_device_descriptor des;
207         int ret;
208         uint8_t status;
209
210         if (!(uscpi->usb488_dev_cap & USB488_DEV_CAP_RL1))
211                 return SR_OK;
212
213         dev = libusb_get_device(usb->devhdl);
214         libusb_get_device_descriptor(dev, &des);
215         if (check_usbtmc_blacklist(blacklist_remote, des.idVendor, des.idProduct))
216                 return SR_OK;
217
218         sr_dbg("Locking out local control.");
219         ret = libusb_control_transfer(usb->devhdl,
220                         LIBUSB_ENDPOINT_IN         |
221                         LIBUSB_REQUEST_TYPE_CLASS  |
222                         LIBUSB_RECIPIENT_INTERFACE,
223                         REN_CONTROL, 1,
224                         uscpi->interface,
225                         &status, 1,
226                         TRANSFER_TIMEOUT);
227         if (ret < 0 || status != USBTMC_STATUS_SUCCESS) {
228                 if (ret < 0)
229                         sr_dbg("Failed to enter REN state: %s.", libusb_error_name(ret));
230                 else
231                         sr_dbg("Failed to enter REN state: USBTMC status %d.", status);
232                 return SR_ERR;
233         }
234
235         ret = libusb_control_transfer(usb->devhdl,
236                         LIBUSB_ENDPOINT_IN         |
237                         LIBUSB_REQUEST_TYPE_CLASS  |
238                         LIBUSB_RECIPIENT_INTERFACE,
239                         LOCAL_LOCKOUT, 1,
240                         uscpi->interface,
241                         &status, 1,
242                         TRANSFER_TIMEOUT);
243         if (ret < 0 || status != USBTMC_STATUS_SUCCESS) {
244                 if (ret < 0)
245                         sr_dbg("Failed to enter local lockout state: %s.",
246                                         libusb_error_name(ret));
247                 else
248                         sr_dbg("Failed to enter local lockout state: USBTMC "
249                                         "status %d.", status);
250                 return SR_ERR;
251         }
252
253         return SR_OK;
254 }
255
256 static void scpi_usbtmc_local(struct scpi_usbtmc_libusb *uscpi)
257 {
258         struct sr_usb_dev_inst *usb = uscpi->usb;
259         struct libusb_device *dev;
260         struct libusb_device_descriptor des;
261         int ret;
262         uint8_t status;
263
264         if (!(uscpi->usb488_dev_cap & USB488_DEV_CAP_RL1))
265                 return;
266
267         dev = libusb_get_device(usb->devhdl);
268         libusb_get_device_descriptor(dev, &des);
269         if (check_usbtmc_blacklist(blacklist_remote, des.idVendor, des.idProduct))
270                 return;
271
272         sr_dbg("Returning local control.");
273         ret = libusb_control_transfer(usb->devhdl,
274                         LIBUSB_ENDPOINT_IN         |
275                         LIBUSB_REQUEST_TYPE_CLASS  |
276                         LIBUSB_RECIPIENT_INTERFACE,
277                         GO_TO_LOCAL, 1,
278                         uscpi->interface,
279                         &status, 1,
280                         TRANSFER_TIMEOUT);
281         if (ret < 0 || status != USBTMC_STATUS_SUCCESS) {
282                 if (ret < 0)
283                         sr_dbg("Failed to clear local lockout state: %s.",
284                                         libusb_error_name(ret));
285                 else
286                         sr_dbg("Failed to clear local lockout state: USBTMC "
287                                         "status %d.", status);
288         }
289
290         return;
291 }
292
293 static int scpi_usbtmc_libusb_open(struct sr_scpi_dev_inst *scpi)
294 {
295         struct scpi_usbtmc_libusb *uscpi = scpi->priv;
296         struct sr_usb_dev_inst *usb = uscpi->usb;
297         struct libusb_device *dev;
298         struct libusb_device_descriptor des;
299         struct libusb_config_descriptor *confdes;
300         const struct libusb_interface_descriptor *intfdes;
301         const struct libusb_endpoint_descriptor *ep;
302         int confidx, intfidx, epidx, config = 0, current_config;
303         uint8_t capabilities[24];
304         int ret, found = 0;
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                         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         /* Get capabilities. */
386         ret = libusb_control_transfer(usb->devhdl,
387                                       LIBUSB_ENDPOINT_IN         |
388                                       LIBUSB_REQUEST_TYPE_CLASS  |
389                                       LIBUSB_RECIPIENT_INTERFACE,
390                                       GET_CAPABILITIES, 0,
391                                       uscpi->interface,
392                                       capabilities, sizeof(capabilities),
393                                       TRANSFER_TIMEOUT);
394         if (ret == sizeof(capabilities)) {
395                 uscpi->usbtmc_int_cap = capabilities[ 4];
396                 uscpi->usbtmc_dev_cap = capabilities[ 5];
397                 uscpi->usb488_dev_cap = capabilities[15];
398         }
399         sr_dbg("Device capabilities: %s%s%s%s%s, %s, %s",
400                uscpi->usb488_dev_cap & USB488_DEV_CAP_SCPI       ? "SCPI, "    : "",
401                uscpi->usbtmc_dev_cap & USBTMC_DEV_CAP_TERMCHAR   ? "TermChar, ": "",
402                uscpi->usbtmc_int_cap & USBTMC_INT_CAP_LISTEN_ONLY? "L3, " :
403                uscpi->usbtmc_int_cap & USBTMC_INT_CAP_TALK_ONLY  ? ""     : "L4, ",
404                uscpi->usbtmc_int_cap & USBTMC_INT_CAP_TALK_ONLY  ? "T5, " :
405                uscpi->usbtmc_int_cap & USBTMC_INT_CAP_LISTEN_ONLY? ""     : "T6, ",
406                uscpi->usb488_dev_cap & USB488_DEV_CAP_SR1        ? "SR1"  : "SR0",
407                uscpi->usb488_dev_cap & USB488_DEV_CAP_RL1        ? "RL1"  : "RL0",
408                uscpi->usb488_dev_cap & USB488_DEV_CAP_DT1        ? "DT1"  : "DT0");
409
410         scpi_usbtmc_remote(uscpi);
411
412         return SR_OK;
413 }
414
415 static int scpi_usbtmc_libusb_source_add(struct sr_session *session,
416                 void *priv, int events, int timeout, sr_receive_data_callback cb,
417                 void *cb_data)
418 {
419         struct scpi_usbtmc_libusb *uscpi = priv;
420         (void)events;
421         return usb_source_add(session, uscpi->ctx, timeout, cb, cb_data);
422 }
423
424 static int scpi_usbtmc_libusb_source_remove(struct sr_session *session,
425                 void *priv)
426 {
427         struct scpi_usbtmc_libusb *uscpi = priv;
428         return usb_source_remove(session, uscpi->ctx);
429 }
430
431 static void usbtmc_bulk_out_header_write(void *header, uint8_t MsgID,
432                                          uint8_t bTag,
433                                          uint32_t TransferSize,
434                                          uint8_t bmTransferAttributes,
435                                          char TermChar)
436 {
437           W8(header+ 0, MsgID);
438           W8(header+ 1, bTag);
439           W8(header+ 2, ~bTag);
440           W8(header+ 3, 0);
441         WL32(header+ 4, TransferSize);
442           W8(header+ 8, bmTransferAttributes);
443           W8(header+ 9, TermChar);
444         WL16(header+10, 0);
445 }
446
447 static int usbtmc_bulk_in_header_read(void *header, uint8_t MsgID,
448                                       unsigned char bTag,
449                                       int32_t *TransferSize,
450                                       uint8_t *bmTransferAttributes)
451 {
452         if (R8(header+0) != MsgID ||
453             R8(header+1) != bTag  ||
454             R8(header+2) != (unsigned char)~bTag)
455                 return SR_ERR;
456         if (TransferSize)
457                 *TransferSize = RL32(header+4);
458         if (bmTransferAttributes)
459                 *bmTransferAttributes = R8(header+8);
460         return SR_OK;
461 }
462
463 static int scpi_usbtmc_bulkout(struct scpi_usbtmc_libusb *uscpi,
464                                uint8_t msg_id, const void *data, int32_t size,
465                                uint8_t transfer_attributes)
466 {
467         struct sr_usb_dev_inst *usb = uscpi->usb;
468         int padded_size, ret, transferred;
469
470         if (data && size+USBTMC_BULK_HEADER_SIZE+3 > (int)sizeof(uscpi->buffer)) {
471                 sr_err("USBTMC bulk out transfer is too big.");
472                 return SR_ERR;
473         }
474
475         uscpi->bTag++;
476         uscpi->bTag += !uscpi->bTag;  /* bTag == 0 is invalid so avoid it. */
477
478         usbtmc_bulk_out_header_write(uscpi->buffer, msg_id, uscpi->bTag,
479                                      size, transfer_attributes, 0);
480         if (data)
481                 memcpy(uscpi->buffer+USBTMC_BULK_HEADER_SIZE, data, size);
482         else
483                 size = 0;
484         size += USBTMC_BULK_HEADER_SIZE;
485         padded_size = (size + 3) & ~0x3;
486         memset(uscpi->buffer+size, 0, padded_size - size);
487
488         ret = libusb_bulk_transfer(usb->devhdl, uscpi->bulk_out_ep,
489                                    uscpi->buffer, padded_size, &transferred,
490                                    TRANSFER_TIMEOUT);
491         if (ret < 0) {
492                 sr_err("USBTMC bulk out transfer error: %s.",
493                        libusb_error_name(ret));
494                 return SR_ERR;
495         }
496
497         if (transferred < padded_size) {
498                 sr_dbg("USBTMC bulk out partial transfer (%d/%d bytes).",
499                        transferred, padded_size);
500                 return SR_ERR;
501         }
502
503         return transferred - USBTMC_BULK_HEADER_SIZE;
504 }
505
506 static int scpi_usbtmc_bulkin_start(struct scpi_usbtmc_libusb *uscpi,
507                                     uint8_t msg_id, void *data, int32_t size,
508                                     uint8_t *transfer_attributes)
509 {
510         struct sr_usb_dev_inst *usb = uscpi->usb;
511         int ret, transferred, message_size;
512
513         ret = libusb_bulk_transfer(usb->devhdl, uscpi->bulk_in_ep, data, size,
514                                    &transferred, TRANSFER_TIMEOUT);
515         if (ret < 0) {
516                 sr_err("USBTMC bulk in transfer error: %s.",
517                        libusb_error_name(ret));
518                 return SR_ERR;
519         }
520
521         if (usbtmc_bulk_in_header_read(data, msg_id, uscpi->bTag, &message_size,
522                                        transfer_attributes) != SR_OK) {
523                 sr_err("USBTMC invalid bulk in header.");
524                 return SR_ERR;
525         }
526
527         message_size += USBTMC_BULK_HEADER_SIZE;
528         uscpi->response_length = MIN(transferred, message_size);
529         uscpi->response_bytes_read = USBTMC_BULK_HEADER_SIZE;
530         uscpi->remaining_length = message_size - uscpi->response_length;
531
532         return transferred - USBTMC_BULK_HEADER_SIZE;
533 }
534
535 static int scpi_usbtmc_bulkin_continue(struct scpi_usbtmc_libusb *uscpi,
536                                        void *data, int size)
537 {
538         struct sr_usb_dev_inst *usb = uscpi->usb;
539         int ret, transferred;
540
541         ret = libusb_bulk_transfer(usb->devhdl, uscpi->bulk_in_ep, data, size,
542                                    &transferred, TRANSFER_TIMEOUT);
543         if (ret < 0) {
544                 sr_err("USBTMC bulk in transfer error: %s.",
545                        libusb_error_name(ret));
546                 return SR_ERR;
547         }
548
549         uscpi->response_length = MIN(transferred, uscpi->remaining_length);
550         uscpi->response_bytes_read = 0;
551         uscpi->remaining_length -= uscpi->response_length;
552
553         return transferred;
554 }
555
556 static int scpi_usbtmc_libusb_send(void *priv, const char *command)
557 {
558         struct scpi_usbtmc_libusb *uscpi = priv;
559
560         if (scpi_usbtmc_bulkout(uscpi, DEV_DEP_MSG_OUT,
561                                 command, strlen(command), EOM) <= 0)
562                 return SR_ERR;
563
564         sr_spew("Successfully sent SCPI command: '%s'.", command);
565
566         return SR_OK;
567 }
568
569 static int scpi_usbtmc_libusb_read_begin(void *priv)
570 {
571         struct scpi_usbtmc_libusb *uscpi = priv;
572
573         uscpi->remaining_length = 0;
574
575         if (scpi_usbtmc_bulkout(uscpi, REQUEST_DEV_DEP_MSG_IN,
576             NULL, INT32_MAX, 0) < 0)
577                 return SR_ERR;
578         if (scpi_usbtmc_bulkin_start(uscpi, DEV_DEP_MSG_IN,
579                                      uscpi->buffer, sizeof(uscpi->buffer),
580                                      &uscpi->bulkin_attributes) < 0)
581                 return SR_ERR;
582
583         return SR_OK;
584 }
585
586 static int scpi_usbtmc_libusb_read_data(void *priv, char *buf, int maxlen)
587 {
588         struct scpi_usbtmc_libusb *uscpi = priv;
589         int read_length;
590
591         if (uscpi->response_bytes_read >= uscpi->response_length) {
592                 if (uscpi->remaining_length > 0) {
593                         if (scpi_usbtmc_bulkin_continue(uscpi, uscpi->buffer,
594                                                         sizeof(uscpi->buffer)) <= 0)
595                                 return SR_ERR;
596                 } else {
597                         if (uscpi->bulkin_attributes & EOM)
598                                 return SR_ERR;
599                         if (scpi_usbtmc_libusb_read_begin(uscpi) < 0)
600                                 return SR_ERR;
601                 }
602         }
603
604         read_length = MIN(uscpi->response_length - uscpi->response_bytes_read, maxlen);
605
606         memcpy(buf, uscpi->buffer + uscpi->response_bytes_read, read_length);
607
608         uscpi->response_bytes_read += read_length;
609
610         return read_length;
611 }
612
613 static int scpi_usbtmc_libusb_read_complete(void *priv)
614 {
615         struct scpi_usbtmc_libusb *uscpi = priv;
616         return uscpi->response_bytes_read >= uscpi->response_length &&
617                uscpi->remaining_length <= 0 &&
618                uscpi->bulkin_attributes & EOM;
619 }
620
621 static int scpi_usbtmc_libusb_close(struct sr_scpi_dev_inst *scpi)
622 {
623         struct scpi_usbtmc_libusb *uscpi = scpi->priv;
624         struct sr_usb_dev_inst *usb = uscpi->usb;
625         int ret;
626
627         if (!usb->devhdl)
628                 return SR_ERR;
629
630         scpi_usbtmc_local(uscpi);
631
632         if ((ret = libusb_release_interface(usb->devhdl, uscpi->interface)) < 0)
633                 sr_err("Failed to release interface: %s.",
634                        libusb_error_name(ret));
635         
636         if (uscpi->detached_kernel_driver) {
637                 if ((ret = libusb_attach_kernel_driver(usb->devhdl,
638                                                 uscpi->interface)) < 0)
639                         sr_err("Failed to re-attach kernel driver: %s.",
640                                libusb_error_name(ret));
641
642                 uscpi->detached_kernel_driver = 0;
643         }
644         sr_usb_close(usb);
645
646         return SR_OK;
647 }
648
649 static void scpi_usbtmc_libusb_free(void *priv)
650 {
651         struct scpi_usbtmc_libusb *uscpi = priv;
652         sr_usb_dev_inst_free(uscpi->usb);
653 }
654
655 SR_PRIV const struct sr_scpi_dev_inst scpi_usbtmc_libusb_dev = {
656         .name          = "USBTMC",
657         .prefix        = "usbtmc",
658         .priv_size     = sizeof(struct scpi_usbtmc_libusb),
659         .scan          = scpi_usbtmc_libusb_scan,
660         .dev_inst_new  = scpi_usbtmc_libusb_dev_inst_new,
661         .open          = scpi_usbtmc_libusb_open,
662         .source_add    = scpi_usbtmc_libusb_source_add,
663         .source_remove = scpi_usbtmc_libusb_source_remove,
664         .send          = scpi_usbtmc_libusb_send,
665         .read_begin    = scpi_usbtmc_libusb_read_begin,
666         .read_data     = scpi_usbtmc_libusb_read_data,
667         .read_complete = scpi_usbtmc_libusb_read_complete,
668         .close         = scpi_usbtmc_libusb_close,
669         .free          = scpi_usbtmc_libusb_free,
670 };