Usbutils
Usbutils
#include "config.h"
#include <ctype.h>
#include <stdint.h>
#include <stdbool.h>
#include "logging.h"
#include "miner.h"
#include "usbutils.h"
/*
* WARNING - these assume DEVLOCK(cgpu, pstate) is called first and
* DEVUNLOCK(cgpu, pstate) in called in the same function with the same pstate
* given to DEVLOCK.
* You must call DEVUNLOCK(cgpu, pstate) before exiting the function or it will
leave
* the thread Cancelability unrestored
*/
#define DEVWLOCK(cgpu, _pth_state) do { \
pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &_pth_state); \
cg_wlock(&cgpu->usbinfo.devlock); \
} while (0)
#define USB_CONFIG 1
#define BITFURY_TIMEOUT_MS 999
#define DRILLBIT_TIMEOUT_MS 999
#define ICARUS_TIMEOUT_MS 999
#ifdef WIN32
#define BFLSC_TIMEOUT_MS 999
#define BITFORCE_TIMEOUT_MS 999
#define MODMINER_TIMEOUT_MS 999
#define AVALON_TIMEOUT_MS 999
#define AVALON4_TIMEOUT_MS 999
#define AVALON7_TIMEOUT_MS 999
#define AVALONM_TIMEOUT_MS 999
#define KLONDIKE_TIMEOUT_MS 999
#define COINTERRA_TIMEOUT_MS 999
#define HASHFAST_TIMEOUT_MS 999
#define HASHRATIO_TIMEOUT_MS 999
#define BLOCKERUPTER_TIMEOUT_MS 999
/* The safety timeout we use, cancelling async transfers on windows that fail
* to timeout on their own. */
#define WIN_CALLBACK_EXTRA 40
#define WIN_WRITE_CBEXTRA 5000
#else
#define BFLSC_TIMEOUT_MS 300
#define BITFORCE_TIMEOUT_MS 200
#define MODMINER_TIMEOUT_MS 100
#define AVALON_TIMEOUT_MS 200
#define AVALON4_TIMEOUT_MS 200
#define AVALON7_TIMEOUT_MS 200
#define AVALONM_TIMEOUT_MS 300
#define KLONDIKE_TIMEOUT_MS 200
#define COINTERRA_TIMEOUT_MS 200
#define HASHFAST_TIMEOUT_MS 500
#define HASHRATIO_TIMEOUT_MS 200
#define BLOCKERUPTER_TIMEOUT_MS 300
#endif
#ifdef USE_BITFORCE
// N.B. transfer size is 512 with USB2.0, but only 64 with USB1.1
static struct usb_epinfo bfl_epinfos[] = {
{ LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(1), 0, 0 },
{ LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(2), 0, 0 }
};
#ifdef USE_BITFURY
static struct usb_epinfo bfu0_epinfos[] = {
{ LIBUSB_TRANSFER_TYPE_INTERRUPT, 8, EPI(2), 0, 0 }
};
/* Default to interface 1 */
static struct usb_intinfo bfu_ints[] = {
USB_EPS(1, bfu1_epinfos),
USB_EPS(0, bfu0_epinfos)
};
#ifdef USE_BLOCKERUPTER
// BlockErupter Device
static struct usb_epinfo bet_epinfos[] = {
{ LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(1), 0, 0 },
{ LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(1), 0, 0 }
};
#ifdef USE_DRILLBIT
// Drillbit Bitfury devices
static struct usb_epinfo drillbit_int_epinfos[] = {
{ LIBUSB_TRANSFER_TYPE_INTERRUPT, 8, EPI(3), 0, 0 }
};
/* Default to interface 1 */
static struct usb_intinfo drillbit_ints[] = {
USB_EPS(1, drillbit_bulk_epinfos),
USB_EPS(0, drillbit_int_epinfos)
};
#endif
#ifdef USE_HASHFAST
#include "driver-hashfast.h"
/* Default to interface 1 */
static struct usb_intinfo hfa_ints[] = {
USB_EPS(1, hfa1_epinfos),
USB_EPS(0, hfa0_epinfos)
};
#endif
#ifdef USE_HASHRATIO
static struct usb_epinfo hro_epinfos[] = {
{ LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(1), 0, 0 },
{ LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(2), 0, 0 }
};
#ifdef USE_MODMINER
static struct usb_epinfo mmq_epinfos[] = {
{ LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(3), 0, 0 },
{ LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(3), 0, 0 }
};
#ifdef USE_AVALON
static struct usb_epinfo ava_epinfos[] = {
{ LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(1), 0, 0 },
{ LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(2), 0, 0 }
};
#ifdef USE_AVALON2
static struct usb_epinfo ava2_epinfos[] = {
{ LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(3), 0, 0 },
{ LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(2), 0, 0 }
};
#ifdef USE_AVALON4
static struct usb_epinfo ava4_epinfos[] = {
{ LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(1), 0, 0 },
{ LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(1), 0, 0 }
};
#ifdef USE_ICARUS
static struct usb_epinfo ica_epinfos[] = {
{ LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(3), 0, 0 },
{ LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(2), 0, 0 }
};
#ifdef USE_COINTERRA
static struct usb_epinfo cointerra_epinfos[] = {
{ LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(1), 0, 0 },
{ LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(1), 0, 0 }
};
#ifdef USE_ANT_S1
static struct usb_epinfo ants1_epinfos[] = {
{ LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(1), 0, 0 },
{ LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(1), 0, 0 }
};
#ifdef USE_ANT_S3
static struct usb_epinfo ants3_epinfos[] = {
{ LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(1), 0, 0 },
{ LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(1), 0, 0 }
};
#define INTINFO(_ints) \
.intinfo_count = ARRAY_SIZE(_ints), \
.intinfos = _ints
#endif
#ifdef USE_HASHFAST
{
.drv = DRIVER_hashfast,
.name = "HFA",
.ident = IDENT_HFA,
.idVendor = HF_USB_VENDOR_ID,
.idProduct = HF_USB_PRODUCT_ID_G1,
.iManufacturer = "HashFast LLC",
.iProduct = "M1 Module",
.config = 1,
.timeout = HASHFAST_TIMEOUT_MS,
.latency = LATENCY_UNUSED,
INTINFO(hfa_ints) },
#endif
#ifdef USE_HASHRATIO
{
.drv = DRIVER_hashratio,
.name = "HRO",
.ident = IDENT_HRO,
.idVendor = IDVENDOR_FTDI,
.idProduct = 0x6001,
.config = 1,
.timeout = HASHRATIO_TIMEOUT_MS,
.latency = LATENCY_UNUSED,
INTINFO(hro_ints) },
#endif
#ifdef USE_KLONDIKE
{
.drv = DRIVER_klondike,
.name = "KLN",
.ident = IDENT_KLN,
.idVendor = 0x04D8,
.idProduct = 0xF60A,
.config = 1,
.timeout = KLONDIKE_TIMEOUT_MS,
.latency = 10,
INTINFO(kln_ints) },
{
.drv = DRIVER_klondike,
.name = "KLI",
.ident = IDENT_KLN,
.idVendor = 0x04D8,
.idProduct = 0xF60A,
.config = 1,
.timeout = KLONDIKE_TIMEOUT_MS,
.latency = 10,
INTINFO(kli_ints) },
#endif
#ifdef USE_ICARUS
{
.drv = DRIVER_icarus,
.name = "ICA",
.ident = IDENT_ICA,
.idVendor = 0x067b,
.idProduct = 0x2303,
.config = 1,
.timeout = ICARUS_TIMEOUT_MS,
.latency = LATENCY_UNUSED,
INTINFO(ica_ints) },
{
.drv = DRIVER_icarus,
.name = "ICA",
.ident = IDENT_AVA,
.idVendor = 0x1fc9,
.idProduct = 0x0083,
.config = 1,
.timeout = ICARUS_TIMEOUT_MS,
.latency = LATENCY_UNUSED,
INTINFO(ica1_ints) },
{
.drv = DRIVER_icarus,
.name = "BSC",
.ident = IDENT_BSC,
.idVendor = 0x10c4,
.idProduct = 0xea60,
.iManufacturer = "bitshopperde",
.iProduct = "Compac BM1384 Bitcoin Miner",
.config = 1,
.timeout = ICARUS_TIMEOUT_MS,
.latency = LATENCY_UNUSED,
INTINFO(amu_ints) },
{
.drv = DRIVER_icarus,
.name = "GSC",
.ident = IDENT_GSC,
.idVendor = 0x10c4,
.idProduct = 0xea60,
.iManufacturer = "GekkoScience",
.iProduct = "Compac BM1384 Bitcoin Miner",
.config = 1,
.timeout = ICARUS_TIMEOUT_MS,
.latency = LATENCY_UNUSED,
INTINFO(amu_ints) },
{
.drv = DRIVER_icarus,
.name = "AMU",
.ident = IDENT_AMU,
.idVendor = 0x10c4,
.idProduct = 0xea60,
.config = 1,
.timeout = ICARUS_TIMEOUT_MS,
.latency = LATENCY_UNUSED,
INTINFO(amu_ints) },
{
.drv = DRIVER_icarus,
.name = "LIN",
.ident = IDENT_LIN,
.idVendor = 0x10c4,
.idProduct = 0xea60,
.config = 1,
.timeout = ICARUS_TIMEOUT_MS,
.latency = LATENCY_UNUSED,
INTINFO(amu_ints) },
{
.drv = DRIVER_icarus,
.name = "ANU",
.ident = IDENT_ANU,
.idVendor = 0x10c4,
.idProduct = 0xea60,
.config = 1,
.timeout = ICARUS_TIMEOUT_MS,
.latency = LATENCY_UNUSED,
INTINFO(amu_ints) },
{
.drv = DRIVER_icarus,
.name = "BLT",
.ident = IDENT_BLT,
.idVendor = IDVENDOR_FTDI,
.idProduct = 0x6001,
.iProduct = "FT232R USB UART",
.config = 1,
.timeout = ICARUS_TIMEOUT_MS,
.latency = LATENCY_STD,
INTINFO(llt_ints) },
// For any that don't match the above "BLT"
{
.drv = DRIVER_icarus,
.name = "LLT",
.ident = IDENT_LLT,
.idVendor = IDVENDOR_FTDI,
.idProduct = 0x6001,
.config = 1,
.timeout = ICARUS_TIMEOUT_MS,
.latency = LATENCY_STD,
INTINFO(llt_ints) },
{
.drv = DRIVER_icarus,
.name = "CMR",
.ident = IDENT_CMR1,
.idVendor = IDVENDOR_FTDI,
.idProduct = 0x6014,
.iProduct = "Cairnsmore1",
.config = 1,
.timeout = ICARUS_TIMEOUT_MS,
.latency = LATENCY_STD,
INTINFO(cmr1_ints) },
{
.drv = DRIVER_icarus,
.name = "CMR",
.ident = IDENT_CMR2,
.idVendor = IDVENDOR_FTDI,
.idProduct = 0x8350,
.iProduct = "Cairnsmore1",
.config = 1,
.timeout = ICARUS_TIMEOUT_MS,
.latency = LATENCY_STD,
INTINFO(cmr2_ints) },
#endif
#ifdef USE_COINTERRA
{
.drv = DRIVER_cointerra,
.name = "CTA",
.ident = IDENT_CTA,
.idVendor = 0x1cbe,
.idProduct = 0x0003,
.config = 1,
.timeout = COINTERRA_TIMEOUT_MS,
.latency = LATENCY_STD,
INTINFO(cointerra_ints) },
#endif
#ifdef USE_ANT_S1
{
.drv = DRIVER_ants1,
.name = "ANT",
.ident = IDENT_ANT,
.idVendor = 0x4254,
.idProduct = 0x4153,
.config = 1,
.timeout = ANT_S1_TIMEOUT_MS,
.latency = LATENCY_ANTS1,
INTINFO(ants1_ints) },
#endif
#ifdef USE_ANT_S3
{
.drv = DRIVER_ants3,
.name = "AS3",
.ident = IDENT_AS3,
.idVendor = 0x4254,
.idProduct = 0x4153,
.config = 1,
.timeout = ANT_S3_TIMEOUT_MS,
.latency = LATENCY_ANTS3,
INTINFO(ants3_ints) },
#endif
#ifdef USE_BLOCKERUPTER
{
.drv = DRIVER_blockerupter,
.name = "BET",
.ident = IDENT_BET,
.idVendor = 0x10c4,
.idProduct = 0xea60,
.config = 1,
.timeout = BLOCKERUPTER_TIMEOUT_MS,
.latency = LATENCY_UNUSED,
INTINFO(bet_ints) },
#endif
{ DRIVER_MAX, NULL, 0, 0, 0, NULL, NULL, 0, 0, 0, 0, NULL }
};
struct usb_in_use_list {
struct usb_busdev in_use;
struct usb_in_use_list *prev;
struct usb_in_use_list *next;
};
// List of in use devices
static struct usb_in_use_list *in_use_head = NULL;
static struct usb_in_use_list *blacklist_head = NULL;
struct resource_work {
bool lock;
const char *dname;
uint8_t bus_number;
uint8_t device_address;
struct resource_work *next;
};
struct resource_reply {
uint8_t bus_number;
uint8_t device_address;
bool got;
struct resource_reply *next;
};
#if DO_USB_STATS
#define CMD_CMD 0
#define CMD_TIMEOUT 1
#define CMD_ERROR 2
#else
#define USB_STATS(sgpu_, sta_, fin_, err_, mode_, cmd_, seq_, tmo_)
#define STATS_TIMEVAL(tv_)
#define USB_REJECT(sgpu_, mode_)
#endif // DO_USB_STATS
#ifdef EOL
#undef EOL
#endif
#define EOL "\n"
return UNKNOWN;
}
static void append(char **buf, char *append, size_t *off, size_t *len)
{
int new = strlen(append);
if ((new + *off) >= *len)
{
*len *= 2;
*buf = cgrealloc(*buf, *len);
}
snprintf(tmp, sizeof(tmp), EOL " ** dev %d: Set & Got active config
descriptor to %d, err %d",
(int)count, cd, err);
append(buf, tmp, off, len);
return true;
}
static void usb_full(ssize_t *count, libusb_device *dev, char **buf, size_t *off,
size_t *len, int level)
{
struct libusb_device_descriptor desc;
uint8_t bus_number;
uint8_t device_address;
struct libusb_device_handle *handle;
struct libusb_config_descriptor *config;
const struct libusb_interface_descriptor *idesc;
const struct libusb_endpoint_descriptor *epdesc;
unsigned char man[STRBUFLEN+1];
unsigned char prod[STRBUFLEN+1];
unsigned char ser[STRBUFLEN+1];
char tmp[512];
int err, i, j, k;
bus_number = libusb_get_bus_number(dev);
device_address = libusb_get_device_address(dev);
if (!opt_usb_list_all) {
bool known = false;
if (!known)
return;
}
(*count)++;
if (level == 0) {
snprintf(tmp, sizeof(tmp), EOL ".USB dev %d: Bus %d Device %d ID: %04x:
%04x",
(int)(*count), (int)bus_number, (int)device_address,
desc.idVendor, desc.idProduct);
} else {
snprintf(tmp, sizeof(tmp), EOL ".USB dev %d: Bus %d Device %d Device
Descriptor:" EOL "\tLength: %d" EOL
"\tDescriptor Type: %s" EOL "\tUSB: %04x" EOL "\tDeviceClass: %d"
EOL
"\tDeviceSubClass: %d" EOL "\tDeviceProtocol: %d" EOL "\
tMaxPacketSize0: %d" EOL
"\tidVendor: %04x" EOL "\tidProduct: %04x" EOL "\tDeviceRelease:
%x" EOL
"\tNumConfigurations: %d",
(int)(*count), (int)bus_number, (int)device_address,
(int)(desc.bLength), destype(desc.bDescriptorType),
desc.bcdUSB, (int)(desc.bDeviceClass), (int)
(desc.bDeviceSubClass),
(int)(desc.bDeviceProtocol), (int)(desc.bMaxPacketSize0),
desc.idVendor, desc.idProduct, desc.bcdDevice,
(int)(desc.bNumConfigurations));
}
append(buf, tmp, off, len);
if (level == 0) {
libusb_close(handle);
snprintf(tmp, sizeof(tmp), EOL " Manufacturer: '%s'" EOL " Product:
'%s'", man, prod);
append(buf, tmp, off, len);
return;
}
if (libusb_kernel_driver_active(handle, 0) == 1) {
snprintf(tmp, sizeof(tmp), EOL " * dev %d: kernel attached", (int)
(*count));
append(buf, tmp, off, len);
}
snprintf(tmp, sizeof(tmp), EOL " dev %d: Active Config:" EOL "\
tDescriptorType: %s" EOL
"\tNumInterfaces: %d" EOL "\tConfigurationValue: %d" EOL
"\tAttributes: %d" EOL "\tMaxPower: %d",
(int)(*count), destype(config->bDescriptorType),
(int)(config->bNumInterfaces), (int)(config-
>iConfiguration),
(int)(config->bmAttributes), (int)(config->MaxPower));
append(buf, tmp, off, len);
libusb_free_config_descriptor(config);
config = NULL;
snprintf(tmp, sizeof(tmp), EOL " dev %d: More Info:" EOL "\tManufacturer:
'%s'" EOL
"\tProduct: '%s'" EOL "\tSerial '%s'",
(int)(*count), man, prod, ser);
append(buf, tmp, off, len);
libusb_close(handle);
}
if (count == 0)
applog(LOG_WARNING, "USB all: found no devices");
else
{
len = 10000;
buf = malloc(len+1);
if (unlikely(!buf))
quit(1, "USB failed to malloc buf in usb_all");
if (!opt_usb_list_all)
append(&buf, " - listing known devices", &off, &len);
j = -1;
for (i = 0; i < count; i++)
usb_full(&j, list[i], &buf, &off, &len, level);
free(buf);
if (j == -1)
applog(LOG_WARNING, "No known USB devices");
else
applog(LOG_WARNING, "%d %sUSB devices",
(int)(++j), opt_usb_list_all ? BLANK : "known ");
libusb_free_device_list(list, 1);
}
if (stats_initialised == false) {
// N.B. environment LIBUSB_DEBUG also sets libusb_set_debug()
if (opt_usbdump >= 0) {
libusb_set_debug(NULL, opt_usbdump);
usb_all(opt_usbdump);
}
stats_initialised = true;
}
mutex_unlock(&cgusb_lock);
}
return usb_commands[cmd];
}
void usb_applog(struct cgpu_info *cgpu, enum usb_cmds cmd, char *msg, int amount,
int err)
{
if (msg && !*msg)
msg = NULL;
#ifdef WIN32
static void in_use_store_ress(uint8_t bus_number, uint8_t device_address, void
*resource1, void *resource2)
{
struct usb_in_use_list *in_use_tmp;
bool found = false, empty = true;
mutex_lock(&cgusb_lock);
in_use_tmp = in_use_head;
while (in_use_tmp) {
if (in_use_tmp->in_use.bus_number == (int)bus_number &&
in_use_tmp->in_use.device_address == (int)device_address) {
found = true;
if (in_use_tmp->in_use.resource1)
empty = false;
in_use_tmp->in_use.resource1 = resource1;
if (in_use_tmp->in_use.resource2)
empty = false;
in_use_tmp->in_use.resource2 = resource2;
break;
}
in_use_tmp = in_use_tmp->next;
}
mutex_unlock(&cgusb_lock);
if (found == false)
applog(LOG_ERR, "FAIL: USB store_ress not found (%d:%d)",
(int)bus_number, (int)device_address);
if (empty == false)
applog(LOG_ERR, "FAIL: USB store_ress not empty (%d:%d)",
(int)bus_number, (int)device_address);
}
mutex_lock(&cgusb_lock);
in_use_tmp = in_use_head;
while (in_use_tmp) {
if (in_use_tmp->in_use.bus_number == (int)bus_number &&
in_use_tmp->in_use.device_address == (int)device_address) {
found = true;
if (!in_use_tmp->in_use.resource1)
empty = true;
*resource1 = in_use_tmp->in_use.resource1;
in_use_tmp->in_use.resource1 = NULL;
if (!in_use_tmp->in_use.resource2)
empty = true;
*resource2 = in_use_tmp->in_use.resource2;
in_use_tmp->in_use.resource2 = NULL;
break;
}
in_use_tmp = in_use_tmp->next;
}
mutex_unlock(&cgusb_lock);
if (found == false)
applog(LOG_ERR, "FAIL: USB get_lock not found (%d:%d)",
(int)bus_number, (int)device_address);
if (empty == true)
applog(LOG_ERR, "FAIL: USB get_lock empty (%d:%d)",
(int)bus_number, (int)device_address);
}
#else
mutex_lock(&cgusb_lock);
in_use_tmp = in_use_head;
while (in_use_tmp) {
if (in_use_tmp->in_use.bus_number == (int)bus_number &&
in_use_tmp->in_use.device_address == (int)device_address) {
found = true;
in_use_tmp->in_use.fd = fd;
break;
}
in_use_tmp = in_use_tmp->next;
}
mutex_unlock(&cgusb_lock);
if (found == false) {
applog(LOG_ERR, "FAIL: USB store_fd not found (%d:%d)",
(int)bus_number, (int)device_address);
}
}
mutex_lock(&cgusb_lock);
in_use_tmp = in_use_head;
while (in_use_tmp) {
if (in_use_tmp->in_use.bus_number == (int)bus_number &&
in_use_tmp->in_use.device_address == (int)device_address) {
found = true;
fd = in_use_tmp->in_use.fd;
break;
}
in_use_tmp = in_use_tmp->next;
}
mutex_unlock(&cgusb_lock);
if (found == false) {
applog(LOG_ERR, "FAIL: USB get_lock not found (%d:%d)",
(int)bus_number, (int)device_address);
}
return fd;
}
#endif
in_use_tmp = head;
while (in_use_tmp) {
if (in_use_tmp->in_use.bus_number == (int)bus_number &&
in_use_tmp->in_use.device_address == (int)device_address) {
ret = true;
break;
}
in_use_tmp = in_use_tmp->next;
if (in_use_tmp == head)
break;
}
return ret;
}
mutex_lock(&cgusb_lock);
ret = __is_in_use(bus_number, device_address);
mutex_unlock(&cgusb_lock);
return ret;
}
return ret;
}
void usb_list(void)
{
struct libusb_device_descriptor desc;
struct libusb_device_handle *handle;
uint8_t bus_number;
uint8_t device_address;
libusb_device **list;
ssize_t count, i, j;
int err, total = 0;
bus_number = libusb_get_bus_number(dev);
device_address = libusb_get_device_address(dev);
mutex_lock(&cgusb_lock);
if (unlikely(!blacklist && __is_in_use(bus_number, device_address))) {
found = true;
goto nofway;
}
if (blacklist)
head = &blacklist_head;
else
head = &in_use_head;
in_use_tmp = cgcalloc(1, sizeof(*in_use_tmp));
in_use_tmp->in_use.bus_number = (int)bus_number;
in_use_tmp->in_use.device_address = (int)device_address;
in_use_tmp->next = in_use_head;
if (*head)
(*head)->prev = in_use_tmp;
*head = in_use_tmp;
nofway:
mutex_unlock(&cgusb_lock);
if (found)
applog(LOG_ERR, "FAIL: USB add already in use (%d:%d)",
(int)bus_number, (int)device_address);
}
mutex_lock(&cgusb_lock);
if (blacklist)
head = &blacklist_head;
else
head = &in_use_head;
in_use_tmp = *head;
while (in_use_tmp) {
if (in_use_tmp->in_use.bus_number == (int)bus_number &&
in_use_tmp->in_use.device_address == (int)device_address) {
found = true;
if (in_use_tmp == *head) {
*head = (*head)->next;
if (*head)
(*head)->prev = NULL;
} else {
in_use_tmp->prev->next = in_use_tmp->next;
if (in_use_tmp->next)
in_use_tmp->next->prev = in_use_tmp->prev;
}
free(in_use_tmp);
break;
}
in_use_tmp = in_use_tmp->next;
if (in_use_tmp == *head)
break;
}
mutex_unlock(&cgusb_lock);
if (!found) {
applog(LOG_ERR, "FAIL: USB remove not already in use (%d:%d)",
(int)bus_number, (int)device_address);
}
}
mutex_lock(&cgusbres_lock);
res_work->next = res_work_head;
res_work_head = res_work;
mutex_unlock(&cgusbres_lock);
cgsem_post(&usb_resource_sem);
mutex_lock(&cgusbres_lock);
if (res_reply_head) {
struct resource_reply *res_reply_prev = NULL;
struct resource_reply *res_reply = res_reply_head;
while (res_reply) {
if (res_reply->bus_number == bus_number &&
res_reply->device_address == device_address) {
if (res_reply_prev)
res_reply_prev->next = res_reply->next;
else
res_reply_head = res_reply->next;
mutex_unlock(&cgusbres_lock);
ret = res_reply->got;
free(res_reply);
return ret;
}
res_reply_prev = res_reply;
res_reply = res_reply->next;
}
}
mutex_unlock(&cgusbres_lock);
}
}
mutex_lock(&cgusbres_lock);
res_work->next = res_work_head;
res_work_head = res_work;
mutex_unlock(&cgusbres_lock);
cgsem_post(&usb_resource_sem);
return;
}
if (cgusb->descriptor)
free(cgusb->descriptor);
free(cgusb->found);
free(cgusb);
return NULL;
}
if (cgpu->usbdev->handle) {
for (ifinfo = cgpu->usbdev->found->intinfo_count - 1; ifinfo >= 0;
ifinfo--) {
libusb_release_interface(cgpu->usbdev->handle,
THISIF(cgpu->usbdev->found, ifinfo));
#ifdef LINUX
libusb_attach_kernel_driver(cgpu->usbdev->handle, THISIF(cgpu-
>usbdev->found, ifinfo));
#endif
}
cg_wlock(&cgusb_fd_lock);
libusb_close(cgpu->usbdev->handle);
cgpu->usbdev->handle = NULL;
cg_wunlock(&cgusb_fd_lock);
}
cgpu->usbdev = free_cgusb(cgpu->usbdev);
}
DEVWLOCK(cgpu, pstate);
_usb_uninit(cgpu);
DEVWUNLOCK(cgpu, pstate);
}
/* We have dropped the read devlock before entering this function but we pick
* up the write lock to prevent any attempts to work on dereferenced code once
* the nodev flag has been set. */
static bool __release_cgpu(struct cgpu_info *cgpu)
{
struct cg_usb_device *cgusb = cgpu->usbdev;
bool initted = cgpu->usbinfo.initialised;
struct cgpu_info *lookcgpu;
int i;
if (initted) {
zombie_devs++;
total_count--;
drv_count[cgpu->drv->drv_id].count--;
}
cgpu->usbinfo.nodev = true;
cgpu->usbinfo.nodev_count++;
cgtime(&cgpu->usbinfo.last_nodev);
// Any devices sharing the same USB device should be marked also
for (i = 0; i < total_devices; i++) {
lookcgpu = get_devices(i);
if (lookcgpu != cgpu && lookcgpu->usbdev == cgusb) {
if (initted) {
total_count--;
drv_count[lookcgpu->drv->drv_id].count--;
}
lookcgpu->usbinfo.nodev = true;
lookcgpu->usbinfo.nodev_count++;
cg_memcpy(&(lookcgpu->usbinfo.last_nodev),
&(cgpu->usbinfo.last_nodev), sizeof(struct timeval));
lookcgpu->usbdev = NULL;
}
}
_usb_uninit(cgpu);
return true;
}
DEVWLOCK(cgpu, pstate);
release_cgpu(cgpu);
DEVWUNLOCK(cgpu, pstate);
}
/*
* Use the same usbdev thus locking is across all related devices
*/
struct cgpu_info *usb_copy_cgpu(struct cgpu_info *orig)
{
struct cgpu_info *copy;
int pstate;
DEVWLOCK(orig, pstate);
copy->name = orig->name;
copy->drv = copy_drv(orig->drv);
copy->deven = orig->deven;
copy->threads = orig->threads;
copy->usbdev = orig->usbdev;
DEVWUNLOCK(orig, pstate);
return copy;
}
cgpu->drv = drv;
cgpu->deven = DEV_ENABLED;
cgpu->threads = threads;
cgpu->usbinfo.nodev = true;
cglock_init(&cgpu->usbinfo.devlock);
return cgpu;
}
free(cgpu->device_path);
free(cgpu);
return NULL;
}
#define USB_INIT_FAIL 0
#define USB_INIT_OK 1
#define USB_INIT_IGNORE 2
DEVWLOCK(cgpu, pstate);
cgpu->usbinfo.bus_number = libusb_get_bus_number(dev);
cgpu->usbinfo.device_address = libusb_get_device_address(dev);
if (found->intinfo_count > 1) {
snprintf(devpath, sizeof(devpath), "%d:%d-i%d",
(int)(cgpu->usbinfo.bus_number),
(int)(cgpu->usbinfo.device_address),
THISIF(found, 0));
} else {
snprintf(devpath, sizeof(devpath), "%d:%d",
(int)(cgpu->usbinfo.bus_number),
(int)(cgpu->usbinfo.device_address));
}
cgpu->device_path = strdup(devpath);
if (found->idVendor == IDVENDOR_FTDI)
cgusb->usb_type = USB_TYPE_FTDI;
cgusb->ident = found->ident;
cg_wlock(&cgusb_fd_lock);
err = libusb_open(dev, &(cgusb->handle));
cg_wunlock(&cgusb_fd_lock);
if (err) {
switch (err) {
case LIBUSB_ERROR_ACCESS:
applog(LOG_ERR,
"USB init, open device failed, err %d, "
"you don't have privilege to access %s",
err, devstr);
applog(LOG_ERR, "See README file included for help");
break;
#ifdef WIN32
// Windows specific message
case LIBUSB_ERROR_NOT_SUPPORTED:
applog(LOG_ERR, "USB init, open device failed, err %d, ",
err);
applog(LOG_ERR, "You need to install a WinUSB driver for
%s", devstr);
applog(LOG_ERR, "And associate %s with WinUSB using zadig",
devstr);
applog(LOG_ERR, "See README.txt file included for help");
break;
#endif
default:
applog(LOG_DEBUG,
"USB init, open failed, err %d %s",
err, devstr);
}
goto dame;
}
#ifdef LINUX
for (ifinfo = 0; ifinfo < found->intinfo_count; ifinfo++) {
if (libusb_kernel_driver_active(cgusb->handle, THISIF(found, ifinfo))
== 1) {
applog(LOG_DEBUG, "USB init, kernel attached ... %s", devstr);
err = libusb_detach_kernel_driver(cgusb->handle, THISIF(found,
ifinfo));
if (err == 0) {
applog(LOG_DEBUG,
"USB init, kernel detached ifinfo %d interface %d"
" successfully %s",
ifinfo, THISIF(found, ifinfo), devstr);
} else {
applog(LOG_WARNING,
"USB init, kernel detach ifinfo %d interface %d
failed,"
" err %d in use? %s",
ifinfo, THISIF(found, ifinfo), err, devstr);
goto nokernel;
}
}
}
#endif
err = libusb_get_string_descriptor_ascii(cgusb->handle,
cgusb->descriptor->iManufacturer,
man, STRBUFLEN);
if (err < 0) {
applog(LOG_DEBUG,
"USB init, failed to get iManufacturer, err %d %s",
err, devstr);
goto cldame;
}
if (found->iManufacturer) {
if (strcmp((char *)man, found->iManufacturer)) {
applog(LOG_DEBUG, "USB init, iManufacturer mismatch %s",
devstr);
applog(LOG_DEBUG, "Found %s vs %s", man, found->iManufacturer);
bad = USB_INIT_IGNORE;
goto cldame;
}
} else {
for (i = 0; find_dev[i].drv != DRIVER_MAX; i++) {
const char *iManufacturer = find_dev[i].iManufacturer;
/* If other drivers has an iManufacturer set that match,
* don't try to claim this device. */
if (!iManufacturer)
continue;
/* If the alternative driver also has an iProduct, only
* use that for comparison. */
if (find_dev[i].iProduct)
continue;
if (!strcmp((char *)man, iManufacturer)) {
applog(LOG_DEBUG, "USB init, alternative iManufacturer
match %s",
devstr);
applog(LOG_DEBUG, "Found %s", iManufacturer);
bad = USB_INIT_IGNORE;
goto cldame;
}
}
}
err = libusb_get_string_descriptor_ascii(cgusb->handle,
cgusb->descriptor->iProduct,
prod, STRBUFLEN);
if (err < 0) {
applog(LOG_DEBUG,
"USB init, failed to get iProduct, err %d %s",
err, devstr);
goto cldame;
}
if (found->iProduct) {
if (strcasecmp((char *)prod, found->iProduct)) {
applog(LOG_DEBUG, "USB init, iProduct mismatch %s",
devstr);
applog(LOG_DEBUG, "Found %s vs %s", prod, found->iProduct);
bad = USB_INIT_IGNORE;
goto cldame;
}
} else {
for (i = 0; find_dev[i].drv != DRIVER_MAX; i++) {
const char *iProduct = find_dev[i].iProduct;
/* Do same for iProduct as iManufacturer above */
if (!iProduct)
continue;
if (!strcasecmp((char *)prod, iProduct)) {
applog(LOG_DEBUG, "USB init, alternative iProduct match
%s",
devstr);
applog(LOG_DEBUG, "Found %s", iProduct);
bad = USB_INIT_IGNORE;
goto cldame;
}
}
}
cfg = -1;
err = libusb_get_configuration(cgusb->handle, &cfg);
if (err)
cfg = -1;
claimed = 0;
for (ifinfo = 0; ifinfo < found->intinfo_count; ifinfo++) {
err = libusb_claim_interface(cgusb->handle, THISIF(found, ifinfo));
if (err == 0)
claimed++;
else {
switch(err) {
case LIBUSB_ERROR_BUSY:
applog(LOG_WARNING,
"USB init, claim ifinfo %d interface %d in use
%s",
ifinfo, THISIF(found, ifinfo), devstr);
break;
default:
applog(LOG_DEBUG,
"USB init, claim ifinfo %d interface %d
failed,"
" err %d %s",
ifinfo, THISIF(found, ifinfo), err, devstr);
}
goto reldame;
}
}
cfg = -1;
err = libusb_get_configuration(cgusb->handle, &cfg);
if (err)
cfg = -1;
if (cfg != found->config) {
applog(LOG_WARNING,
"USB init, incorrect config (%d!=%d) after claim of %s",
cfg, found->config, devstr);
goto reldame;
}
cgusb->usbver = cgusb->descriptor->bcdUSB;
if (cgusb->usbver < 0x0200) {
cgusb->usb11 = true;
cgusb->tt = true;
}
// TODO: allow this with the right version of the libusb include and running
library
// cgusb->speed = libusb_get_device_speed(dev);
err = libusb_get_string_descriptor_ascii(cgusb->handle,
cgusb->descriptor->iProduct, strbuf, STRBUFLEN);
if (err > 0)
cgusb->prod_string = strdup((char *)strbuf);
else
cgusb->prod_string = (char *)BLANK;
err = libusb_get_string_descriptor_ascii(cgusb->handle,
cgusb->descriptor->iManufacturer, strbuf, STRBUFLEN);
if (err > 0)
cgusb->manuf_string = strdup((char *)strbuf);
else
cgusb->manuf_string = (char *)BLANK;
err = libusb_get_string_descriptor_ascii(cgusb->handle,
cgusb->descriptor->iSerialNumber, strbuf, STRBUFLEN);
if (err > 0)
cgusb->serial_string = strdup((char *)strbuf);
else
cgusb->serial_string = (char *)BLANK;
// TODO: ?
// cgusb->fwVersion <- for temp1/temp2 decision? or serial? (driver-modminer.c)
// cgusb->interfaceVersion
applog(LOG_DEBUG,
"USB init %s usbver=%04x prod='%s' manuf='%s' serial='%s'",
devstr, cgusb->usbver, cgusb->prod_string,
cgusb->manuf_string, cgusb->serial_string);
cgpu->usbdev = cgusb;
cgpu->usbinfo.nodev = false;
libusb_free_config_descriptor(config);
bad = USB_INIT_OK;
goto out_unlock;
reldame:
ifinfo = claimed;
while (ifinfo-- > 0)
libusb_release_interface(cgusb->handle, THISIF(found, ifinfo));
cldame:
#ifdef LINUX
libusb_attach_kernel_driver(cgusb->handle, THISIF(found, ifinfo));
nokernel:
#endif
cg_wlock(&cgusb_fd_lock);
libusb_close(cgusb->handle);
cgusb->handle = NULL;
cg_wunlock(&cgusb_fd_lock);
dame:
if (config)
libusb_free_config_descriptor(config);
cgusb = free_cgusb(cgusb);
out_unlock:
DEVWUNLOCK(cgpu, pstate);
return bad;
}
if (ret != USB_INIT_IGNORE)
break;
}
}
if (ret == USB_INIT_FAIL) {
applog(LOG_ERR, "%s detect (%d:%d) failed to initialise (incorrect
device?), resetting",
cgpu->drv->dname,
(int)(cgpu->usbinfo.bus_number),
(int)(cgpu->usbinfo.device_address));
if (cgpu->usbdev && cgpu->usbdev->handle)
libusb_reset_device(cgpu->usbdev->handle);
}
return false;
}
if (busdev_count > 0) {
bus_number = (int)libusb_get_bus_number(dev);
device_address = (int)libusb_get_device_address(dev);
ok = false;
for (i = 0; i < busdev_count; i++) {
if (bus_number == busdev[i].bus_number) {
if (busdev[i].device_address == -1 ||
device_address == busdev[i].device_address) {
ok = true;
break;
}
}
}
if (!ok) {
applog(LOG_DEBUG, "%s rejected %s %04x:%04x with bus:dev (%d:
%d)",
drv->name, look->name, look->idVendor, look->idProduct,
bus_number, device_address);
return false;
}
}
return true;
}
return NULL;
}
DRIVER_PARSE_COMMANDS(DRIVER_USB_CHECK_EACH)
return NULL;
}
if (count == 0)
applog(LOG_DEBUG, "USB scan devices: found no devices");
else
cgsleep_ms(166);
libusb_free_device_list(list, 1);
}
#if DO_USB_STATS
static void modes_str(char *buf, uint32_t modes)
{
bool first;
*buf = '\0';
if (modes == MODE_NONE)
strcpy(buf, MODE_NONE_STR);
else {
first = true;
// The stat data can be spurious due to not locking it before copying it -
// however that would require the stat() function to also lock and release
// a mutex every time a usb read or write is called which would slow
// things down more
struct api_data *api_usb_stats(__maybe_unused int *count)
{
#if DO_USB_STATS
struct cg_usb_stats_details *details;
struct cg_usb_stats *sta;
struct api_data *root = NULL;
int device;
int cmdseq;
char modes_s[32];
if (next_stat == USB_NOSTAT)
return NULL;
(*count)++;
sta = &(usb_stats[device]);
details = &(sta->details[cmdseq]);
return root;
}
#endif
return NULL;
}
#if DO_USB_STATS
static void newstats(struct cgpu_info *cgpu)
{
int i;
mutex_lock(&cgusb_lock);
cgpu->usbinfo.usbstat = next_stat + 1;
next_stat++;
mutex_unlock(&cgusb_lock);
}
#endif
#if DO_USB_STATS
static void stats(struct cgpu_info *cgpu, struct timeval *tv_start, struct timeval
*tv_finish, int err, int mode, enum usb_cmds cmd, int seq, int timeout)
{
struct cg_usb_stats_details *details;
double diff;
int item, extrams;
if (cgpu->usbinfo.usbstat < 1)
newstats(cgpu);
cgpu->usbinfo.tmo_count++;
cgpu->usbinfo.usb_tmo[offset].count++;
cgpu->usbinfo.usb_tmo[offset].total_over += extrams;
cgpu->usbinfo.usb_tmo[offset].total_tmo += timeout;
if (cgpu->usbinfo.usb_tmo[offset].min_tmo == 0) {
cgpu->usbinfo.usb_tmo[offset].min_tmo = totms;
cgpu->usbinfo.usb_tmo[offset].max_tmo = totms;
} else {
if (cgpu->usbinfo.usb_tmo[offset].min_tmo > totms)
cgpu->usbinfo.usb_tmo[offset].min_tmo = totms;
if (cgpu->usbinfo.usb_tmo[offset].max_tmo < totms)
cgpu->usbinfo.usb_tmo[offset].max_tmo = totms;
}
}
switch (err) {
case LIBUSB_SUCCESS:
item = CMD_CMD;
break;
case LIBUSB_ERROR_TIMEOUT:
item = CMD_TIMEOUT;
break;
default:
item = CMD_ERROR;
break;
}
if (details->item[item].count == 0) {
details->item[item].min_delay = diff;
cg_memcpy(&(details->item[item].first), tv_start, sizeof(*tv_start));
} else if (diff < details->item[item].min_delay)
details->item[item].min_delay = diff;
if (diff > details->item[item].max_delay)
details->item[item].max_delay = diff;
details->item[item].total_delay += diff;
cg_memcpy(&(details->item[item].last), tv_start, sizeof(*tv_start));
details->item[item].count++;
}
if (cgpu->usbinfo.usbstat < 1)
newstats(cgpu);
#define USB_RETRY_MAX 5
struct usb_transfer {
cgsem_t cgsem;
struct libusb_transfer *transfer;
bool cancellable;
struct list_head list;
};
bool async_usb_transfers(void)
{
bool ret;
cg_rlock(&cgusb_fd_lock);
ret = !list_empty(&ut_list);
cg_runlock(&cgusb_fd_lock);
return ret;
}
cg_wlock(&cgusb_fd_lock);
list_for_each_entry(ut, &ut_list, list) {
if (ut->cancellable) {
ut->cancellable = false;
libusb_cancel_transfer(ut->transfer);
cancellations++;
}
}
cg_wunlock(&cgusb_fd_lock);
if (cancellations)
applog(LOG_DEBUG, "Cancelled %d USB transfers", cancellations);
}
cgsem_destroy(&ut->cgsem);
libusb_free_transfer(ut->transfer);
}
ut->cancellable = false;
cgsem_post(&ut->cgsem);
}
switch (ret) {
default:
case LIBUSB_TRANSFER_COMPLETED:
ret = LIBUSB_SUCCESS;
break;
case LIBUSB_TRANSFER_ERROR:
ret = LIBUSB_ERROR_IO;
break;
case LIBUSB_TRANSFER_TIMED_OUT:
case LIBUSB_TRANSFER_CANCELLED:
ret = LIBUSB_ERROR_TIMEOUT;
break;
case LIBUSB_TRANSFER_STALL:
ret = LIBUSB_ERROR_PIPE;
break;
case LIBUSB_TRANSFER_NO_DEVICE:
ret = LIBUSB_ERROR_NO_DEVICE;
break;
case LIBUSB_TRANSFER_OVERFLOW:
ret = LIBUSB_ERROR_OVERFLOW;
break;
}
return ret;
}
/* Wait for callback function to tell us it has finished the USB transfer, but
* use our own timer to cancel the request if we go beyond the timeout. */
static int callback_wait(struct usb_transfer *ut, int *transferred, unsigned int
timeout)
{
struct libusb_transfer *transfer= ut->transfer;
int ret;
return ret;
}
INIT_LIST_HEAD(&ut->list);
cg_wlock(&cgusb_fd_lock);
/* Imitate a transaction translator for writes to usb1.1 devices */
if (tt)
cgsleep_ms_r(&usb11_cgt, 1);
err = libusb_submit_transfer(transfer);
if (likely(!err))
ut->cancellable = cancellable;
list_add(&ut->list, &ut_list);
if (tt)
cgtimer_time(&usb11_cgt);
cg_wunlock(&cgusb_fd_lock);
return err;
}
static int
usb_perform_transfer(struct cgpu_info *cgpu, struct cg_usb_device *usbdev, int
intinfo,
int epinfo, unsigned char *data, int length, int *transferred,
unsigned int timeout, __maybe_unused int mode, enum usb_cmds cmd,
__maybe_unused int seq, bool cancellable, bool tt)
{
int bulk_timeout, callback_timeout = timeout, err_retries = 0;
struct libusb_device_handle *dev_handle = usbdev->handle;
struct usb_epinfo *usb_epinfo;
struct usb_transfer ut;
unsigned char endpoint;
bool interrupt;
int err, errn;
#if DO_USB_STATS
struct timeval tv_start, tv_finish;
#endif
unsigned char buf[512];
#ifdef WIN32
/* On windows the callback_timeout is a safety mechanism only. */
bulk_timeout = timeout;
callback_timeout += WIN_CALLBACK_EXTRA;
#else
/* We give the transfer no timeout since we manage timeouts ourself on
* non windows. */
bulk_timeout = 0;
#endif
usb_epinfo = &(usbdev->found->intinfos[intinfo].epinfos[epinfo]);
interrupt = usb_epinfo->att == LIBUSB_TRANSFER_TYPE_INTERRUPT;
endpoint = usb_epinfo->ep;
if (unlikely(!data)) {
applog(LOG_ERR, "USB error: usb_perform_transfer sent NULL data
(%s,intinfo=%d,epinfo=%d,length=%d,timeout=%u,mode=%d,cmd=%s,seq=%d) endpoint=%d",
cgpu->drv->name, intinfo, epinfo, length, timeout, mode,
usb_cmdname(cmd), seq, (int)endpoint);
err = LIBUSB_ERROR_IO;
goto out_fail;
}
/* Avoid any async transfers during shutdown to allow the polling
* thread to be shut down after all existing transfers are complete */
if (opt_lowmem || cgpu->shutdown)
return libusb_bulk_transfer(dev_handle, endpoint, data, length,
transferred, timeout);
err_retry:
init_usb_transfer(&ut);
if (interrupt) {
libusb_fill_interrupt_transfer(ut.transfer, dev_handle, endpoint,
buf, length, transfer_callback, &ut,
bulk_timeout);
} else {
libusb_fill_bulk_transfer(ut.transfer, dev_handle, endpoint, buf,
length, transfer_callback, &ut, bulk_timeout);
}
STATS_TIMEVAL(&tv_start);
err = usb_submit_transfer(&ut, ut.transfer, cancellable, tt);
errn = errno;
if (!err)
err = callback_wait(&ut, transferred, callback_timeout);
else
err = usb_transfer_toerr(err);
complete_usb_transfer(&ut);
STATS_TIMEVAL(&tv_finish);
USB_STATS(cgpu, &tv_start, &tv_finish, err, mode, cmd, seq, timeout);
if (err < 0) {
applog(LOG_DEBUG, "%s%i: %s (amt=%d err=%d ern=%d)",
cgpu->drv->name, cgpu->device_id,
usb_cmdname(cmd), *transferred, err, errn);
}
if (err == LIBUSB_ERROR_PIPE) {
int pipeerr, retries = 0;
do {
cgpu->usbinfo.last_pipe = time(NULL);
cgpu->usbinfo.pipe_count++;
applog(LOG_INFO, "%s%i: libusb pipe error, trying to clear",
cgpu->drv->name, cgpu->device_id);
pipeerr = libusb_clear_halt(dev_handle, endpoint);
applog(LOG_DEBUG, "%s%i: libusb pipe error%scleared",
cgpu->drv->name, cgpu->device_id, err ? " not " : " ");
if (pipeerr)
cgpu->usbinfo.clear_fail_count++;
} while (pipeerr && ++retries < USB_RETRY_MAX);
if (!pipeerr && ++err_retries < USB_RETRY_MAX)
goto err_retry;
}
if (err == LIBUSB_ERROR_IO && ++err_retries < USB_RETRY_MAX)
goto err_retry;
out_fail:
if (NODEV(err))
*transferred = 0;
else if ((endpoint & LIBUSB_ENDPOINT_DIR_MASK) == LIBUSB_ENDPOINT_IN &&
*transferred)
cg_memcpy(data, buf, *transferred);
return err;
}
DEVWLOCK(cgpu, pstate);
if (!cgpu->usbinfo.nodev) {
err = libusb_reset_device(cgpu->usbdev->handle);
applog(LOG_WARNING, "%s %i attempted reset got err:(%d) %s",
cgpu->drv->name, cgpu->device_id, err, libusb_error_name(err));
}
if (NODEV(err))
release_cgpu(cgpu);
DEVWUNLOCK(cgpu, pstate);
}
int _usb_read(struct cgpu_info *cgpu, int intinfo, int epinfo, char *buf, size_t
bufsiz,
int *processed, int timeout, const char *end, enum usb_cmds cmd, bool
readonce, bool cancellable)
{
unsigned char *ptr, usbbuf[USB_READ_BUFSIZE];
struct timeval read_start, tv_finish;
int bufleft, err, got, tot, pstate, tried_reset;
struct cg_usb_device *usbdev;
unsigned int initial_timeout;
bool first = true;
size_t usbbufread;
int endlen = 0;
char *eom = NULL;
double done;
bool ftdi;
memset(usbbuf, 0, USB_READ_BUFSIZE);
memset(buf, 0, bufsiz);
if (end)
endlen = strlen(end);
DEVRLOCK(cgpu, pstate);
if (cgpu->usbinfo.nodev) {
*processed = 0;
USB_REJECT(cgpu, MODE_BULK_READ);
err = LIBUSB_ERROR_NO_DEVICE;
goto out_noerrmsg;
}
usbdev = cgpu->usbdev;
/* Interrupt transfers are guaranteed to be of an expected size (we hope) */
if (usbdev->found->intinfos[intinfo].epinfos[epinfo].att ==
LIBUSB_TRANSFER_TYPE_INTERRUPT)
usbbufread = bufsiz;
else
usbbufread = 512;
ftdi = (usbdev->usb_type == USB_TYPE_FTDI);
if (timeout == DEVTIMEOUT)
timeout = usbdev->found->timeout;
tot = usbdev->bufamt;
bufleft = bufsiz - tot;
if (tot)
cg_memcpy(usbbuf, usbdev->buffer, tot);
ptr = usbbuf + tot;
usbdev->bufamt = 0;
err = LIBUSB_SUCCESS;
if (end != NULL)
eom = strstr((const char *)usbbuf, end);
initial_timeout = timeout;
cgtime(&read_start);
tried_reset = 0;
while (bufleft > 0 && !eom) {
err = usb_perform_transfer(cgpu, usbdev, intinfo, epinfo, ptr,
usbbufread,
&got, timeout, MODE_BULK_READ, cmd,
first ? SEQ0 : SEQ1, cancellable, false);
if (NODEV(err))
goto out_noerrmsg;
cgtime(&tv_finish);
ptr[got] = '\0';
if (ftdi) {
// first 2 bytes returned are an FTDI status
if (got > 2) {
got -= 2;
memmove(ptr, ptr+2, got+1);
} else {
got = 0;
*ptr = '\0';
}
}
tot += got;
if (end != NULL)
eom = strstr((const char *)usbbuf, end);
/* Attempt a usb reset for an error that will otherwise cause
* this device to drop out provided we know the device still
* might exist. */
if (err && err != LIBUSB_ERROR_TIMEOUT) {
applog(LOG_WARNING, "%s %i %s usb read err:(%d) %s", cgpu->drv-
>name,
cgpu->device_id, usb_cmdname(cmd), err,
libusb_error_name(err));
if (err != LIBUSB_ERROR_NO_DEVICE && !tried_reset) {
err = libusb_reset_device(usbdev->handle);
tried_reset = 1; // don't call reset twice in a row
applog(LOG_WARNING, "%s %i attempted reset got err:(%d)
%s",
cgpu->drv->name, cgpu->device_id, err,
libusb_error_name(err));
}
} else {
tried_reset = 0;
}
if (NODEV(err))
goto out_noerrmsg;
ptr += got;
bufleft -= got;
if (bufleft < 1)
err = LIBUSB_SUCCESS;
if (err || readonce)
break;
first = false;
/* If we found the end of message marker, just use that data and
* return success. */
if (eom) {
size_t eomlen = (void *)eom - (void *)usbbuf + endlen;
*processed = tot;
cg_memcpy((char *)buf, (const char *)usbbuf, (tot < (int)bufsiz) ? tot + 1 :
(int)bufsiz);
out_noerrmsg:
if (NODEV(err)) {
cg_ruwlock(&cgpu->usbinfo.devlock);
release_cgpu(cgpu);
DEVWUNLOCK(cgpu, pstate);
} else
DEVRUNLOCK(cgpu, pstate);
return err;
}
int _usb_write(struct cgpu_info *cgpu, int intinfo, int epinfo, char *buf, size_t
bufsiz, int *processed, int timeout, enum usb_cmds cmd)
{
struct timeval write_start, tv_finish;
struct cg_usb_device *usbdev;
unsigned int initial_timeout;
int err, sent, tot, pstate, tried_reset;
bool first = true;
double done;
DEVRLOCK(cgpu, pstate);
*processed = 0;
if (cgpu->usbinfo.nodev) {
USB_REJECT(cgpu, MODE_BULK_WRITE);
err = LIBUSB_ERROR_NO_DEVICE;
goto out_noerrmsg;
}
usbdev = cgpu->usbdev;
if (timeout == DEVTIMEOUT)
timeout = usbdev->found->timeout;
tot = 0;
err = LIBUSB_SUCCESS;
initial_timeout = timeout;
cgtime(&write_start);
tried_reset = 0;
while (bufsiz > 0) {
int tosend = bufsiz;
/* USB 1.1 devices don't handle zero packets well so split them
* up to not have the final transfer equal to the wMaxPacketSize
* or they will stall waiting for more data. */
if (usbdev->usb11) {
struct usb_epinfo *ue = &usbdev->found-
>intinfos[intinfo].epinfos[epinfo];
if (tosend == ue->wMaxPacketSize) {
tosend >>= 1;
if (unlikely(!tosend))
tosend = 1;
}
}
err = usb_perform_transfer(cgpu, usbdev, intinfo, epinfo, (unsigned
char *)buf,
tosend, &sent, timeout, MODE_BULK_WRITE,
cmd, first ? SEQ0 : SEQ1, false, usbdev->tt);
if (NODEV(err))
goto out_noerrmsg;
cgtime(&tv_finish);
tot += sent;
buf += sent;
bufsiz -= sent;
first = false;
out_noerrmsg:
if (NODEV(err)) {
cg_ruwlock(&cgpu->usbinfo.devlock);
release_cgpu(cgpu);
DEVWUNLOCK(cgpu, pstate);
} else
DEVRUNLOCK(cgpu, pstate);
return err;
}
/* As we do for bulk reads, emulate a sync function for control transfers using
* our own timeouts that takes the same parameters as libusb_control_transfer.
*/
static int usb_control_transfer(struct cgpu_info *cgpu, libusb_device_handle
*dev_handle, uint8_t bmRequestType,
uint8_t bRequest, uint16_t wValue, uint16_t wIndex,
unsigned char *buffer, uint16_t wLength, unsigned int
timeout)
{
struct usb_transfer ut;
unsigned char buf[70];
int err, transferred;
bool tt = false;
if (unlikely(cgpu->shutdown))
return libusb_control_transfer(dev_handle, bmRequestType, bRequest,
wValue, wIndex, buffer, wLength, timeout);
init_usb_transfer(&ut);
libusb_fill_control_setup(buf, bmRequestType, bRequest, wValue,
wIndex, wLength);
if ((bmRequestType & LIBUSB_ENDPOINT_DIR_MASK) == LIBUSB_ENDPOINT_OUT) {
if (wLength)
cg_memcpy(buf + LIBUSB_CONTROL_SETUP_SIZE, buffer, wLength);
if (cgpu->usbdev->descriptor->bcdUSB < 0x0200)
tt = true;
}
libusb_fill_control_transfer(ut.transfer, dev_handle, buf, transfer_callback,
&ut, 0);
err = usb_submit_transfer(&ut, ut.transfer, false, tt);
if (!err)
err = callback_wait(&ut, &transferred, timeout);
if (err == LIBUSB_SUCCESS && transferred) {
if ((bmRequestType & LIBUSB_ENDPOINT_DIR_MASK) == LIBUSB_ENDPOINT_IN)
cg_memcpy(buffer, libusb_control_transfer_get_data(ut.transfer),
transferred);
err = transferred;
goto out;
}
err = usb_transfer_toerr(err);
out:
complete_usb_transfer(&ut);
return err;
}
if (cgpu->usbinfo.nodev) {
USB_REJECT(cgpu, MODE_CTRL_WRITE);
err = LIBUSB_ERROR_NO_DEVICE;
goto out_;
}
usbdev = cgpu->usbdev;
if (timeout == DEVTIMEOUT)
timeout = usbdev->found->timeout;
if (siz > 0) {
bufsiz = siz - 1;
bufsiz >>= 2;
bufsiz++;
for (i = 0; i < bufsiz; i++)
buf32[i] = htole32(data[i]);
}
STATS_TIMEVAL(&tv_start);
err = usb_control_transfer(cgpu, usbdev->handle, request_type, bRequest,
wValue, wIndex, buf, (uint16_t)siz, timeout);
STATS_TIMEVAL(&tv_finish);
USB_STATS(cgpu, &tv_start, &tv_finish, err, MODE_CTRL_WRITE, cmd, SEQ0,
timeout);
/* We use the write devlock for control transfers since some control transfers
* are rare but may be changing settings within the device causing problems
* if concurrent transfers are happening. Using the write lock serialises
* any transfers. */
int _usb_transfer(struct cgpu_info *cgpu, uint8_t request_type, uint8_t bRequest,
uint16_t wValue, uint16_t wIndex, uint32_t *data, int siz, unsigned int timeout,
enum usb_cmds cmd)
{
int pstate, err;
DEVWLOCK(cgpu, pstate);
if (NOCONTROLDEV(err))
release_cgpu(cgpu);
DEVWUNLOCK(cgpu, pstate);
return err;
}
DEVWLOCK(cgpu, pstate);
if (cgpu->usbinfo.nodev) {
USB_REJECT(cgpu, MODE_CTRL_READ);
err = LIBUSB_ERROR_NO_DEVICE;
goto out_noerrmsg;
}
usbdev = cgpu->usbdev;
if (timeout == DEVTIMEOUT)
timeout = usbdev->found->timeout;
*amount = 0;
memset(tbuf, 0, 64);
STATS_TIMEVAL(&tv_start);
err = usb_control_transfer(cgpu, usbdev->handle, request_type, bRequest,
wValue, wIndex, tbuf, (uint16_t)bufsiz, timeout);
STATS_TIMEVAL(&tv_finish);
USB_STATS(cgpu, &tv_start, &tv_finish, err, MODE_CTRL_READ, cmd, SEQ0,
timeout);
cg_memcpy(buf, tbuf, bufsiz);
if (err > 0) {
*amount = err;
err = 0;
}
if (err < 0 && err != LIBUSB_ERROR_TIMEOUT) {
applog(LOG_WARNING, "%s %i usb transfer read err:(%d) %s", cgpu->drv-
>name, cgpu->device_id,
err, libusb_error_name(err));
}
out_noerrmsg:
if (NOCONTROLDEV(err))
release_cgpu(cgpu);
DEVWUNLOCK(cgpu, pstate);
return err;
}
DEVWLOCK(cgpu, pstate);
if (cgpu->usbdev) {
if (cgpu->usbdev->usb_type != USB_TYPE_FTDI) {
applog(LOG_ERR, "%s: cgid %d latency request on non-FTDI device",
cgpu->drv->name, cgpu->cgminer_id);
err = LIBUSB_ERROR_NOT_SUPPORTED;
} else if (cgpu->usbdev->found->latency == LATENCY_UNUSED) {
applog(LOG_ERR, "%s: cgid %d invalid latency (UNUSED)",
cgpu->drv->name, cgpu->cgminer_id);
err = LIBUSB_ERROR_NOT_SUPPORTED;
}
if (!err)
err = __usb_transfer(cgpu, FTDI_TYPE_OUT, FTDI_REQUEST_LATENCY,
cgpu->usbdev->found->latency,
USBIF(cgpu->usbdev, intinfo),
NULL, 0, DEVTIMEOUT, C_LATENCY);
}
DEVWUNLOCK(cgpu, pstate);
return err;
}
DEVWLOCK(cgpu, pstate);
if (cgpu->usbdev)
cgpu->usbdev->bufamt = 0;
DEVWUNLOCK(cgpu, pstate);
}
DEVRLOCK(cgpu, pstate);
if (cgpu->usbdev)
ret = cgpu->usbdev->bufamt;
DEVRUNLOCK(cgpu, pstate);
return ret;
}
/*
* The value returned (0) when usbdev is NULL
* doesn't matter since it also means the next call to
* any usbutils function will fail with a nodev
* N.B. this is to get the interface number to use in a control_transfer
* which for some devices isn't actually the interface number
*/
int _usb_interface(struct cgpu_info *cgpu, int intinfo)
{
int interface = 0;
int pstate;
DEVRLOCK(cgpu, pstate);
if (cgpu->usbdev)
interface = cgpu->usbdev->found->intinfos[intinfo].ctrl_transfer;
DEVRUNLOCK(cgpu, pstate);
return interface;
}
DEVRLOCK(cgpu, pstate);
if (cgpu->usbdev)
ident = cgpu->usbdev->ident;
DEVRUNLOCK(cgpu, pstate);
return ident;
}
DEVWLOCK(cgpu, pstate);
cgusb = cgpu->usbdev;
cgtime(&now);
DEVWUNLOCK(cgpu, pstate);
}
void usb_cleanup(void)
{
struct cgpu_info *cgpu;
int count, pstate;
int i;
hotplug_time = 0;
cgsleep_ms(10);
count = 0;
for (i = 0; i < total_devices; i++) {
cgpu = devices[i];
switch (cgpu->drv->drv_id) {
case DRIVER_bflsc:
case DRIVER_bitforce:
case DRIVER_bitfury:
case DRIVER_cointerra:
case DRIVER_drillbit:
case DRIVER_modminer:
case DRIVER_icarus:
case DRIVER_avalon:
case DRIVER_avalon2:
case DRIVER_avalon4:
case DRIVER_avalon7:
case DRIVER_avalonm:
case DRIVER_klondike:
case DRIVER_hashfast:
DEVWLOCK(cgpu, pstate);
release_cgpu(cgpu);
DEVWUNLOCK(cgpu, pstate);
count++;
break;
default:
break;
}
}
/*
* Must attempt to wait for the resource thread to release coz
* during a restart it won't automatically release them in linux
*/
if (count) {
struct timeval start, now;
cgtime(&start);
while (42) {
cgsleep_ms(50);
mutex_lock(&cgusbres_lock);
if (!res_work_head)
break;
cgtime(&now);
if (tdiff(&now, &start) > 0.366) {
applog(LOG_WARNING,
"usb_cleanup gave up waiting for resource thread");
break;
}
mutex_unlock(&cgusbres_lock);
}
mutex_unlock(&cgusbres_lock);
}
cgsem_destroy(&usb_resource_sem);
}
INIT_LIST_HEAD(&ut_list);
cgusb_check_init();
*(colon++) = '\0';
if (!isdigit(*ptr))
quit(1, "Invalid --usb bus:dev - bus must be a
number");
bus = atoi(ptr);
if (bus <= 0)
quit(1, "Invalid --usb bus:dev - bus must be > 0");
if (*colon == '*')
dev = -1;
else {
dev = atoi(colon);
if (dev <= 0)
quit(1, "Invalid --usb bus:dev - dev must be >
0 or '*'");
}
ptr = comma;
} while (ptr);
free(fre);
// Comma list of DRV:limit
} else {
fre = ptr = strdup(opt_usb_select);
do {
comma = strchr(ptr, ',');
if (comma)
*(comma++) = '\0';
*(colon++) = '\0';
if (!isdigit(*colon))
quit(1, "Invalid --usb DRV:limit - limit must be a
number");
lim = atoi(colon);
if (lim < 0)
quit(1, "Invalid --usb DRV:limit - limit must be >=
0");
found = false;
/* Use the DRIVER_PARSE_COMMANDS macro to iterate
* over all the drivers. */
DRIVER_PARSE_COMMANDS(DRIVER_COUNT_FOUND)
if (!found)
quit(1, "Invalid --usb DRV:limit - unknown DRV='%s'",
ptr);
ptr = comma;
} while (ptr);
free(fre);
}
}
}
#ifndef WIN32
#include <errno.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/file.h>
#include <fcntl.h>
#ifndef __APPLE__
union semun {
int val;
struct semid_ds *buf;
unsigned short *array;
struct seminfo *__buf;
};
#endif
#else
static LPSECURITY_ATTRIBUTES unsec(LPSECURITY_ATTRIBUTES sec)
{
SECURITY_DESCRIPTOR *sd = (PSECURITY_DESCRIPTOR)(sec->lpSecurityDescriptor);
FreeSid(sd->Group);
free(sec->lpSecurityDescriptor);
free(sec);
return NULL;
}
sec_des = cgmalloc(SECURITY_DESCRIPTOR_MIN_LENGTH);
if (!InitializeSecurityDescriptor(sec_des, SECURITY_DESCRIPTOR_REVISION)) {
applog(LOG_ERR,
"MTX: %s (%d:%d) USB failed to init secdes err (%d)",
dname, (int)bus_number, (int)device_address,
(int)GetLastError());
free(sec_des);
return NULL;
}
if(!AllocateAndInitializeSid(&SIDAuthWorld, 1, SECURITY_WORLD_RID, 0, 0, 0,
0, 0, 0, 0, &gsid)) {
applog(LOG_ERR,
"MTX: %s (%d:%d) USB failed to create gsid err (%d)",
dname, (int)bus_number, (int)device_address,
(int)GetLastError());
free(sec_des);
return NULL;
}
sec_att = cgmalloc(sizeof(*sec_att));
sec_att->nLength = sizeof(*sec_att);
sec_att->lpSecurityDescriptor = sec_des;
sec_att->bInheritHandle = FALSE;
return sec_att;
}
#endif
// Any errors should always be printed since they will rarely if ever occur
// and thus it is best to always display them
static bool resource_lock(const char *dname, uint8_t bus_number, uint8_t
device_address)
{
applog(LOG_DEBUG, "USB res lock %s %d-%d", dname, (int)bus_number,
(int)device_address);
#ifdef WIN32
struct cgpu_info *cgpu;
LPSECURITY_ATTRIBUTES sec;
HANDLE usbMutex;
char name[64];
DWORD res;
int i;
if (is_in_use_bd(bus_number, device_address))
return false;
switch(res) {
case WAIT_OBJECT_0:
case WAIT_ABANDONED:
// Am I using it already?
for (i = 0; i < total_devices; i++) {
cgpu = get_devices(i);
if (cgpu->usbinfo.bus_number == bus_number &&
cgpu->usbinfo.device_address == device_address &&
cgpu->usbinfo.nodev == false) {
if (ReleaseMutex(usbMutex)) {
applog(LOG_WARNING,
"MTX: %s USB can't get '%s' - device in
use",
dname, name);
goto fail;
}
applog(LOG_ERR,
"MTX: %s USB can't get '%s' - device in use -
failure (%d)",
dname, name, (int)GetLastError());
goto fail;
}
}
break;
case WAIT_TIMEOUT:
if (!hotplug_mode)
applog(LOG_WARNING,
"MTX: %s USB failed to get '%s' - device in use",
dname, name);
goto fail;
case WAIT_FAILED:
applog(LOG_ERR,
"MTX: %s USB failed to get '%s' err (%d)",
dname, name, (int)GetLastError());
goto fail;
default:
applog(LOG_ERR,
"MTX: %s USB failed to get '%s' unknown reply (%d)",
dname, name, (int)res);
goto fail;
}
return true;
fail:
CloseHandle(usbMutex);
sec = unsec(sec);
return false;
#else
char name[64];
int fd;
if (is_in_use_bd(bus_number, device_address))
return false;
// Any errors should always be printed since they will rarely if ever occur
// and thus it is best to always display them
static void resource_unlock(const char *dname, uint8_t bus_number, uint8_t
device_address)
{
applog(LOG_DEBUG, "USB res unlock %s %d-%d", dname, (int)bus_number,
(int)device_address);
#ifdef WIN32
LPSECURITY_ATTRIBUTES sec = NULL;
HANDLE usbMutex = NULL;
char name[64];
if (!usbMutex || !sec)
goto fila;
if (!ReleaseMutex(usbMutex))
applog(LOG_ERR,
"MTX: %s USB failed to release '%s' err (%d)",
dname, name, (int)GetLastError());
fila:
if (usbMutex)
CloseHandle(usbMutex);
if (sec)
unsec(sec);
remove_in_use(bus_number, device_address);
return;
#else
char name[64];
int fd;
if (res_work_head->lock) {
ok = resource_lock(res_work_head->dname,
res_work_head->bus_number,
res_work_head->device_address);
res_reply->bus_number = res_work_head->bus_number;
res_reply->device_address = res_work_head->device_address;
res_reply->got = ok;
res_reply->next = res_reply_head;
res_reply_head = res_reply;
}
else
resource_unlock(res_work_head->dname,
res_work_head->bus_number,
res_work_head->device_address);
res_work = res_work_head;
res_work_head = res_work_head->next;
free(res_work);
}
RenameThread("USBResource");
applog(LOG_DEBUG, "RES: thread starting");
while (42) {
/* Wait to be told we have work to do */
cgsem_wait(&usb_resource_sem);
mutex_lock(&cgusbres_lock);
while (res_work_head)
resource_process();
mutex_unlock(&cgusbres_lock);
}
return NULL;
}
void initialise_usblocks(void)
{
mutex_init(&cgusb_lock);
mutex_init(&cgusbres_lock);
cglock_init(&cgusb_fd_lock);
}