]> sigrok.org Git - libsigrok.git/blob - src/scpi/scpi_usbtmc_libusb.c
c8bcd0dc4e3e42cd389fc9a243096f1866c61a19
[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;
528
529         ret = libusb_bulk_transfer(usb->devhdl, uscpi->bulk_in_ep, data, size,
530                                    &transferred, TRANSFER_TIMEOUT);
531         if (ret < 0) {
532                 sr_err("USBTMC bulk in transfer error: %s.",
533                        libusb_error_name(ret));
534                 return SR_ERR;
535         }
536
537         if (transferred < USBTMC_BULK_HEADER_SIZE) {
538                 sr_err("USBTMC bulk in returned too little data: %d/%d bytes\n", transferred, size);
539                 return SR_ERR;
540         }
541
542         if (usbtmc_bulk_in_header_read(data, msg_id, uscpi->bTag, &message_size,
543                                        transfer_attributes) != SR_OK) {
544                 sr_err("USBTMC invalid bulk in header.");
545                 return SR_ERR;
546         }
547
548         message_size += USBTMC_BULK_HEADER_SIZE;
549         uscpi->response_length = MIN(transferred, message_size);
550         uscpi->response_bytes_read = USBTMC_BULK_HEADER_SIZE;
551         uscpi->remaining_length = message_size - uscpi->response_length;
552
553         return transferred - USBTMC_BULK_HEADER_SIZE;
554 }
555
556 static int scpi_usbtmc_bulkin_continue(struct scpi_usbtmc_libusb *uscpi,
557                                        void *data, int size)
558 {
559         struct sr_usb_dev_inst *usb = uscpi->usb;
560         int ret, transferred;
561
562         ret = libusb_bulk_transfer(usb->devhdl, uscpi->bulk_in_ep, data, size,
563                                    &transferred, TRANSFER_TIMEOUT);
564         if (ret < 0) {
565                 sr_err("USBTMC bulk in transfer error: %s.",
566                        libusb_error_name(ret));
567                 return SR_ERR;
568         }
569
570         uscpi->response_length = MIN(transferred, uscpi->remaining_length);
571         uscpi->response_bytes_read = 0;
572         uscpi->remaining_length -= uscpi->response_length;
573
574         return transferred;
575 }
576
577 static int scpi_usbtmc_libusb_send(void *priv, const char *command)
578 {
579         struct scpi_usbtmc_libusb *uscpi = priv;
580
581         if (scpi_usbtmc_bulkout(uscpi, DEV_DEP_MSG_OUT,
582                                 command, strlen(command), EOM) <= 0)
583                 return SR_ERR;
584
585         sr_spew("Successfully sent SCPI command: '%s'.", command);
586
587         return SR_OK;
588 }
589
590 static int scpi_usbtmc_libusb_read_begin(void *priv)
591 {
592         struct scpi_usbtmc_libusb *uscpi = priv;
593
594         uscpi->remaining_length = 0;
595
596         if (scpi_usbtmc_bulkout(uscpi, REQUEST_DEV_DEP_MSG_IN,
597             NULL, INT32_MAX, 0) < 0)
598                 return SR_ERR;
599         if (scpi_usbtmc_bulkin_start(uscpi, DEV_DEP_MSG_IN,
600                                      uscpi->buffer, sizeof(uscpi->buffer),
601                                      &uscpi->bulkin_attributes) < 0)
602                 return SR_ERR;
603
604         return SR_OK;
605 }
606
607 static int scpi_usbtmc_libusb_read_data(void *priv, char *buf, int maxlen)
608 {
609         struct scpi_usbtmc_libusb *uscpi = priv;
610         int read_length;
611
612         if (uscpi->response_bytes_read >= uscpi->response_length) {
613                 if (uscpi->remaining_length > 0) {
614                         if (scpi_usbtmc_bulkin_continue(uscpi, uscpi->buffer,
615                                                         sizeof(uscpi->buffer)) <= 0)
616                                 return SR_ERR;
617                 } else {
618                         if (uscpi->bulkin_attributes & EOM)
619                                 return SR_ERR;
620                         if (scpi_usbtmc_libusb_read_begin(uscpi) < 0)
621                                 return SR_ERR;
622                 }
623         }
624
625         read_length = MIN(uscpi->response_length - uscpi->response_bytes_read, maxlen);
626
627         memcpy(buf, uscpi->buffer + uscpi->response_bytes_read, read_length);
628
629         uscpi->response_bytes_read += read_length;
630
631         return read_length;
632 }
633
634 static int scpi_usbtmc_libusb_read_complete(void *priv)
635 {
636         struct scpi_usbtmc_libusb *uscpi = priv;
637         return uscpi->response_bytes_read >= uscpi->response_length &&
638                uscpi->remaining_length <= 0 &&
639                uscpi->bulkin_attributes & EOM;
640 }
641
642 static int scpi_usbtmc_libusb_close(struct sr_scpi_dev_inst *scpi)
643 {
644         struct scpi_usbtmc_libusb *uscpi = scpi->priv;
645         struct sr_usb_dev_inst *usb = uscpi->usb;
646         int ret;
647
648         if (!usb->devhdl)
649                 return SR_ERR;
650
651         scpi_usbtmc_local(uscpi);
652
653         if ((ret = libusb_release_interface(usb->devhdl, uscpi->interface)) < 0)
654                 sr_err("Failed to release interface: %s.",
655                        libusb_error_name(ret));
656
657         if (uscpi->detached_kernel_driver) {
658                 if ((ret = libusb_attach_kernel_driver(usb->devhdl,
659                                                 uscpi->interface)) < 0)
660                         sr_err("Failed to re-attach kernel driver: %s.",
661                                libusb_error_name(ret));
662
663                 uscpi->detached_kernel_driver = 0;
664         }
665         sr_usb_close(usb);
666
667         return SR_OK;
668 }
669
670 static void scpi_usbtmc_libusb_free(void *priv)
671 {
672         struct scpi_usbtmc_libusb *uscpi = priv;
673         sr_usb_dev_inst_free(uscpi->usb);
674 }
675
676 SR_PRIV const struct sr_scpi_dev_inst scpi_usbtmc_libusb_dev = {
677         .name          = "USBTMC",
678         .prefix        = "usbtmc",
679         .transport     = SCPI_TRANSPORT_USBTMC,
680         .priv_size     = sizeof(struct scpi_usbtmc_libusb),
681         .scan          = scpi_usbtmc_libusb_scan,
682         .dev_inst_new  = scpi_usbtmc_libusb_dev_inst_new,
683         .open          = scpi_usbtmc_libusb_open,
684         .connection_id = scpi_usbtmc_libusb_connection_id,
685         .source_add    = scpi_usbtmc_libusb_source_add,
686         .source_remove = scpi_usbtmc_libusb_source_remove,
687         .send          = scpi_usbtmc_libusb_send,
688         .read_begin    = scpi_usbtmc_libusb_read_begin,
689         .read_data     = scpi_usbtmc_libusb_read_data,
690         .read_complete = scpi_usbtmc_libusb_read_complete,
691         .close         = scpi_usbtmc_libusb_close,
692         .free          = scpi_usbtmc_libusb_free,
693 };