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