/ usbutils.c
usbutils.c
   1  /*
   2   * Copyright 2012-2013 Andrew Smith
   3   * Copyright 2013-2015 Con Kolivas <kernel@kolivas.org>
   4   *
   5   * This program is free software; you can redistribute it and/or modify it
   6   * under the terms of the GNU General Public License as published by the Free
   7   * Software Foundation; either version 3 of the License, or (at your option)
   8   * any later version.  See COPYING for more details.
   9   */
  10  
  11  #include "config.h"
  12  
  13  #include <ctype.h>
  14  #include <stdint.h>
  15  #include <stdbool.h>
  16  
  17  #include "logging.h"
  18  #include "miner.h"
  19  #include "usbutils.h"
  20  
  21  static pthread_mutex_t cgusb_lock;
  22  static pthread_mutex_t cgusbres_lock;
  23  static cglock_t cgusb_fd_lock;
  24  static cgtimer_t usb11_cgt;
  25  
  26  #define NODEV(err) ((err) != LIBUSB_SUCCESS && (err) != LIBUSB_ERROR_TIMEOUT)
  27  
  28  #define NOCONTROLDEV(err) ((err) < 0 && NODEV(err))
  29  
  30  /*
  31   * WARNING - these assume DEVLOCK(cgpu, pstate) is called first and
  32   *  DEVUNLOCK(cgpu, pstate) in called in the same function with the same pstate
  33   *  given to DEVLOCK.
  34   *  You must call DEVUNLOCK(cgpu, pstate) before exiting the function or it will leave
  35   *  the thread Cancelability unrestored
  36   */
  37  #define DEVWLOCK(cgpu, _pth_state) do { \
  38  			pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &_pth_state); \
  39  			cg_wlock(&cgpu->usbinfo.devlock); \
  40  			} while (0)
  41  
  42  #define DEVWUNLOCK(cgpu, _pth_state) do { \
  43  			cg_wunlock(&cgpu->usbinfo.devlock); \
  44  			pthread_setcancelstate(_pth_state, NULL); \
  45  			} while (0)
  46  
  47  #define DEVRLOCK(cgpu, _pth_state) do { \
  48  			pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &_pth_state); \
  49  			cg_rlock(&cgpu->usbinfo.devlock); \
  50  			} while (0)
  51  
  52  #define DEVRUNLOCK(cgpu, _pth_state) do { \
  53  			cg_runlock(&cgpu->usbinfo.devlock); \
  54  			pthread_setcancelstate(_pth_state, NULL); \
  55  			} while (0)
  56  
  57  #define USB_CONFIG 1
  58  
  59  #define BITFURY_TIMEOUT_MS 999
  60  #define DRILLBIT_TIMEOUT_MS 999
  61  #define ICARUS_TIMEOUT_MS 999
  62  
  63  // There is no windows version
  64  #define ANT_S1_TIMEOUT_MS 200
  65  #define ANT_S3_TIMEOUT_MS 200
  66  
  67  #ifdef WIN32
  68  #define BFLSC_TIMEOUT_MS 999
  69  #define BITFORCE_TIMEOUT_MS 999
  70  #define MODMINER_TIMEOUT_MS 999
  71  #define AVALON_TIMEOUT_MS 999
  72  #define AVALON4_TIMEOUT_MS 999
  73  #define AVALON7_TIMEOUT_MS 999
  74  #define AVALON8_TIMEOUT_MS 999
  75  #define AVALONM_TIMEOUT_MS 999
  76  #define KLONDIKE_TIMEOUT_MS 999
  77  #define COINTERRA_TIMEOUT_MS 999
  78  #define HASHFAST_TIMEOUT_MS 999
  79  #define HASHRATIO_TIMEOUT_MS 999
  80  #define BLOCKERUPTER_TIMEOUT_MS 999
  81  
  82  /* The safety timeout we use, cancelling async transfers on windows that fail
  83   * to timeout on their own. */
  84  #define WIN_CALLBACK_EXTRA 40
  85  #define WIN_WRITE_CBEXTRA 5000
  86  #else
  87  #define BFLSC_TIMEOUT_MS 300
  88  #define BITFORCE_TIMEOUT_MS 200
  89  #define MODMINER_TIMEOUT_MS 100
  90  #define AVALON_TIMEOUT_MS 200
  91  #define AVALON4_TIMEOUT_MS 200
  92  #define AVALON7_TIMEOUT_MS 200
  93  #define AVALON8_TIMEOUT_MS 200
  94  #define AVALONM_TIMEOUT_MS 300
  95  #define KLONDIKE_TIMEOUT_MS 200
  96  #define COINTERRA_TIMEOUT_MS 200
  97  #define HASHFAST_TIMEOUT_MS 500
  98  #define HASHRATIO_TIMEOUT_MS 200
  99  #define BLOCKERUPTER_TIMEOUT_MS 300
 100  #endif
 101  
 102  #define USB_EPS(_intx, _epinfosx) { \
 103  		.interface = _intx, \
 104  		.ctrl_transfer = _intx, \
 105  		.epinfo_count = ARRAY_SIZE(_epinfosx), \
 106  		.epinfos = _epinfosx \
 107  	}
 108  
 109  #define USB_EPS_CTRL(_inty, _ctrlinty, _epinfosy) { \
 110  		.interface = _inty, \
 111  		.ctrl_transfer = _ctrlinty, \
 112  		.epinfo_count = ARRAY_SIZE(_epinfosy), \
 113  		.epinfos = _epinfosy \
 114  	}
 115  
 116  /* Linked list of all async transfers in progress. Protected by cgusb_fd_lock.
 117   * This allows us to not stop the usb polling thread till all are complete, and
 118   * to find cancellable transfers. */
 119  static struct list_head ut_list;
 120  
 121  #ifdef USE_BFLSC
 122  static struct usb_epinfo bflsc_epinfos[] = {
 123  	{ LIBUSB_TRANSFER_TYPE_BULK,	512,	EPI(1), 0, 0 },
 124  	{ LIBUSB_TRANSFER_TYPE_BULK,	512,	EPO(2), 0, 0 }
 125  };
 126  
 127  static struct usb_intinfo bflsc_ints[] = {
 128  	USB_EPS(0, bflsc_epinfos)
 129  };
 130  #endif
 131  
 132  #ifdef USE_BITFORCE
 133  // N.B. transfer size is 512 with USB2.0, but only 64 with USB1.1
 134  static struct usb_epinfo bfl_epinfos[] = {
 135  	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPI(1), 0, 0 },
 136  	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPO(2), 0, 0 }
 137  };
 138  
 139  static struct usb_intinfo bfl_ints[] = {
 140  	USB_EPS(0, bfl_epinfos)
 141  };
 142  #endif
 143  
 144  #ifdef USE_BITFURY
 145  static struct usb_epinfo bfu0_epinfos[] = {
 146  	{ LIBUSB_TRANSFER_TYPE_INTERRUPT,	8,	EPI(2), 0, 0 }
 147  };
 148  
 149  static struct usb_epinfo bfu1_epinfos[] = {
 150  	{ LIBUSB_TRANSFER_TYPE_BULK,	16,	EPI(3), 0, 0 },
 151  	{ LIBUSB_TRANSFER_TYPE_BULK,	16,	EPO(4), 0, 0 }
 152  };
 153  
 154  /* Default to interface 1 */
 155  static struct usb_intinfo bfu_ints[] = {
 156  	USB_EPS(1,  bfu1_epinfos),
 157  	USB_EPS(0,  bfu0_epinfos)
 158  };
 159  
 160  static struct usb_epinfo bxf0_epinfos[] = {
 161  	{ LIBUSB_TRANSFER_TYPE_INTERRUPT,	8,	EPI(1), 0, 0 }
 162  };
 163  
 164  static struct usb_epinfo bxf1_epinfos[] = {
 165  	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPI(2), 0, 0 },
 166  	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPO(2), 0, 0 }
 167  };
 168  
 169  static struct usb_intinfo bxf_ints[] = {
 170  	USB_EPS(1,  bxf1_epinfos),
 171  	USB_EPS(0,  bxf0_epinfos)
 172  };
 173  
 174  static struct usb_epinfo nfu_epinfos[] = {
 175  	{ LIBUSB_TRANSFER_TYPE_INTERRUPT,	64,	EPI(1), 0, 0 },
 176  	{ LIBUSB_TRANSFER_TYPE_INTERRUPT,	64,	EPO(1), 0, 0 },
 177  };
 178  
 179  static struct usb_intinfo nfu_ints[] = {
 180  	USB_EPS(0, nfu_epinfos)
 181  };
 182  
 183  static struct usb_epinfo bxm_epinfos[] = {
 184  	{ LIBUSB_TRANSFER_TYPE_BULK,	512,	EPI(1), 0, 0 },
 185  	{ LIBUSB_TRANSFER_TYPE_BULK,	512,	EPO(2), 0, 0 }
 186  };
 187  
 188  static struct usb_intinfo bxm_ints[] = {
 189  	USB_EPS(0, bxm_epinfos)
 190  };
 191  #endif
 192  
 193  #ifdef USE_BLOCKERUPTER
 194  // BlockErupter Device
 195  static struct usb_epinfo bet_epinfos[] = {
 196  	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPI(1), 0, 0 },
 197  	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPO(1), 0, 0 }
 198  };
 199  
 200  static struct usb_intinfo bet_ints[] = {
 201  	USB_EPS(0, bet_epinfos)
 202  };
 203  #endif
 204  
 205  #ifdef USE_DRILLBIT
 206  // Drillbit Bitfury devices
 207  static struct usb_epinfo drillbit_int_epinfos[] = {
 208  	{ LIBUSB_TRANSFER_TYPE_INTERRUPT,	8,	EPI(3), 0, 0 }
 209  };
 210  
 211  static struct usb_epinfo drillbit_bulk_epinfos[] = {
 212  	{ LIBUSB_TRANSFER_TYPE_BULK,	16,	EPI(1), 0, 0 },
 213  	{ LIBUSB_TRANSFER_TYPE_BULK,	16,	EPO(2), 0, 0 },
 214  };
 215  
 216  /* Default to interface 1 */
 217  static struct usb_intinfo drillbit_ints[] = {
 218  	USB_EPS(1,  drillbit_bulk_epinfos),
 219  	USB_EPS(0,  drillbit_int_epinfos)
 220  };
 221  #endif
 222  
 223  #ifdef USE_HASHFAST
 224  #include "driver-hashfast.h"
 225  
 226  static struct usb_epinfo hfa0_epinfos[] = {
 227  	{ LIBUSB_TRANSFER_TYPE_INTERRUPT,	8,	EPI(3), 0, 0 }
 228  };
 229  
 230  static struct usb_epinfo hfa1_epinfos[] = {
 231  	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPI(1), 0, 0 },
 232  	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPO(2), 0, 0 }
 233  };
 234  
 235  /* Default to interface 1 */
 236  static struct usb_intinfo hfa_ints[] = {
 237  	USB_EPS(1,  hfa1_epinfos),
 238  	USB_EPS(0,  hfa0_epinfos)
 239  };
 240  #endif
 241  
 242  #ifdef USE_HASHRATIO
 243  static struct usb_epinfo hro_epinfos[] = {
 244  	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPI(1), 0, 0 },
 245  	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPO(2), 0, 0 }
 246  };
 247  
 248  static struct usb_intinfo hro_ints[] = {
 249  	USB_EPS(0, hro_epinfos)
 250  };
 251  #endif
 252  
 253  #ifdef USE_MODMINER
 254  static struct usb_epinfo mmq_epinfos[] = {
 255  	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPI(3), 0, 0 },
 256  	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPO(3), 0, 0 }
 257  };
 258  
 259  static struct usb_intinfo mmq_ints[] = {
 260  	USB_EPS(1, mmq_epinfos)
 261  };
 262  #endif
 263  
 264  #ifdef USE_AVALON
 265  static struct usb_epinfo ava_epinfos[] = {
 266  	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPI(1), 0, 0 },
 267  	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPO(2), 0, 0 }
 268  };
 269  
 270  static struct usb_intinfo ava_ints[] = {
 271  	USB_EPS(0, ava_epinfos)
 272  };
 273  #endif
 274  
 275  #ifdef USE_AVALON2
 276  static struct usb_epinfo ava2_epinfos[] = {
 277  	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPI(3), 0, 0 },
 278  	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPO(2), 0, 0 }
 279  };
 280  
 281  static struct usb_intinfo ava2_ints[] = {
 282  	USB_EPS(0, ava2_epinfos)
 283  };
 284  #endif
 285  
 286  #ifdef USE_AVALON4
 287  static struct usb_epinfo ava4_epinfos[] = {
 288  	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPI(1), 0, 0 },
 289  	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPO(1), 0, 0 }
 290  };
 291  
 292  static struct usb_intinfo ava4_ints[] = {
 293  	USB_EPS(1, ava4_epinfos)
 294  };
 295  #endif
 296  #ifdef USE_AVALON7
 297  static struct usb_epinfo ava7_epinfos[] = {
 298  	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPI(1), 0, 0 },
 299  	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPO(1), 0, 0 }
 300  };
 301  
 302  static struct usb_intinfo ava7_ints[] = {
 303  	USB_EPS(1, ava7_epinfos)
 304  };
 305  #endif
 306  #ifdef USE_AVALON8
 307  static struct usb_epinfo ava8_epinfos[] = {
 308  	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPI(1), 0, 0 },
 309  	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPO(1), 0, 0 }
 310  };
 311  
 312  static struct usb_intinfo ava8_ints[] = {
 313  	USB_EPS(1, ava8_epinfos)
 314  };
 315  #endif
 316  #ifdef USE_AVALON_MINER
 317  static struct usb_epinfo avam_epinfos[] = {
 318  	{ LIBUSB_TRANSFER_TYPE_INTERRUPT,	40,	EPI(1), 0, 0 },
 319  	{ LIBUSB_TRANSFER_TYPE_INTERRUPT,	40,	EPO(1), 0, 0 }
 320  };
 321  
 322  static struct usb_intinfo avam_ints[] = {
 323  	USB_EPS(1, avam_epinfos)
 324  };
 325  static struct usb_epinfo av3u_epinfos[] = {
 326  	{ LIBUSB_TRANSFER_TYPE_INTERRUPT,	40,	EPI(1), 0, 0 },
 327  	{ LIBUSB_TRANSFER_TYPE_INTERRUPT,	40,	EPO(1), 0, 0 }
 328  };
 329  
 330  static struct usb_intinfo av3u_ints[] = {
 331  	USB_EPS(0, av3u_epinfos)
 332  };
 333  #endif
 334  #ifdef USE_KLONDIKE
 335  static struct usb_epinfo kln_epinfos[] = {
 336  	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPI(1), 0, 0 },
 337  	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPO(1), 0, 0 }
 338  };
 339  
 340  static struct usb_intinfo kln_ints[] = {
 341  	USB_EPS(0, kln_epinfos)
 342  };
 343  
 344  static struct usb_epinfo kli0_epinfos[] = {
 345  	{ LIBUSB_TRANSFER_TYPE_INTERRUPT, 8,	EPI(1), 0, 0 }
 346  };
 347  
 348  static struct usb_epinfo kli1_epinfos[] = {
 349  	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPI(2), 0, 0 },
 350  	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPO(2), 0, 0 }
 351  };
 352  
 353  static struct usb_intinfo kli_ints[] = {
 354  	USB_EPS(1, kli1_epinfos),
 355  	USB_EPS(0, kli0_epinfos)
 356  };
 357  #endif
 358  
 359  #ifdef USE_ICARUS
 360  static struct usb_epinfo ica_epinfos[] = {
 361  	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPI(3), 0, 0 },
 362  	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPO(2), 0, 0 }
 363  };
 364  
 365  static struct usb_intinfo ica_ints[] = {
 366  	USB_EPS(0, ica_epinfos)
 367  };
 368  
 369  static struct usb_epinfo ica1_epinfos0[] = {
 370  	{ LIBUSB_TRANSFER_TYPE_INTERRUPT,	16,	EPI(0x82), 0, 0 }
 371  };
 372  
 373  static struct usb_epinfo ica1_epinfos1[] = {
 374  	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPI(0x81), 0, 0 },
 375  	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPO(0x01), 0, 0 }
 376  };
 377  
 378  static struct usb_intinfo ica1_ints[] = {
 379  	USB_EPS(1, ica1_epinfos1),
 380  	USB_EPS(0, ica1_epinfos0)
 381  };
 382  
 383  static struct usb_epinfo amu_epinfos[] = {
 384  	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPI(1), 0, 0 },
 385  	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPO(1), 0, 0 }
 386  };
 387  
 388  static struct usb_intinfo amu_ints[] = {
 389  	USB_EPS(0, amu_epinfos)
 390  };
 391  
 392  static struct usb_epinfo llt_epinfos[] = {
 393  	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPI(1), 0, 0 },
 394  	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPO(2), 0, 0 }
 395  };
 396  
 397  static struct usb_intinfo llt_ints[] = {
 398  	USB_EPS(0, llt_epinfos)
 399  };
 400  
 401  static struct usb_epinfo cmr1_epinfos[] = {
 402  	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPI(1), 0, 0 },
 403  	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPO(2), 0, 0 }
 404  };
 405  
 406  static struct usb_intinfo cmr1_ints[] = {
 407  	USB_EPS(0, cmr1_epinfos)
 408  };
 409  
 410  static struct usb_epinfo cmr2_epinfos0[] = {
 411  	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPI(1), 0, 0 },
 412  	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPO(2), 0, 0 }
 413  };
 414  static struct usb_epinfo cmr2_epinfos1[] = {
 415  	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPI(3), 0, 0 },
 416  	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPO(4), 0, 0 },
 417  };
 418  static struct usb_epinfo cmr2_epinfos2[] = {
 419  	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPI(5), 0, 0 },
 420  	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPO(6), 0, 0 },
 421  };
 422  static struct usb_epinfo cmr2_epinfos3[] = {
 423  	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPI(7), 0, 0 },
 424  	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPO(8), 0, 0 }
 425  };
 426  
 427  static struct usb_intinfo cmr2_ints[] = {
 428  	USB_EPS_CTRL(0, 1, cmr2_epinfos0),
 429  	USB_EPS_CTRL(1, 2, cmr2_epinfos1),
 430  	USB_EPS_CTRL(2, 3, cmr2_epinfos2),
 431  	USB_EPS_CTRL(3, 4, cmr2_epinfos3)
 432  };
 433  #endif
 434  
 435  #ifdef USE_COINTERRA
 436  static struct usb_epinfo cointerra_epinfos[] = {
 437  	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPI(1), 0, 0 },
 438  	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPO(1), 0, 0 }
 439  };
 440  
 441  static struct usb_intinfo cointerra_ints[] = {
 442  	USB_EPS(0, cointerra_epinfos)
 443  };
 444  #endif
 445  
 446  #ifdef USE_ANT_S1
 447  static struct usb_epinfo ants1_epinfos[] = {
 448  	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPI(1), 0, 0 },
 449  	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPO(1), 0, 0 }
 450  };
 451  
 452  static struct usb_intinfo ants1_ints[] = {
 453  	USB_EPS(0, ants1_epinfos)
 454  };
 455  #endif
 456  
 457  #ifdef USE_ANT_S3
 458  static struct usb_epinfo ants3_epinfos[] = {
 459  	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPI(1), 0, 0 },
 460  	{ LIBUSB_TRANSFER_TYPE_BULK,	64,	EPO(1), 0, 0 }
 461  };
 462  
 463  static struct usb_intinfo ants3_ints[] = {
 464  	USB_EPS(0, ants3_epinfos)
 465  };
 466  #endif
 467  
 468  #define IDVENDOR_FTDI 0x0403
 469  
 470  #define INTINFO(_ints) \
 471  		.intinfo_count = ARRAY_SIZE(_ints), \
 472  		.intinfos = _ints
 473  
 474  #define USBEP(_usbdev, _intinfo, _epinfo) (_usbdev->found->intinfos[_intinfo].epinfos[_epinfo].ep)
 475  #define THISIF(_found, _this) (_found->intinfos[_this].interface)
 476  #define USBIF(_usbdev, _this) THISIF(_usbdev->found, _this)
 477  
 478  static struct usb_find_devices find_dev[] = {
 479  #ifdef USE_BFLSC
 480  	/* Wish these guys would be more consistent with setting these fields */
 481  	{
 482  		.drv = DRIVER_bflsc,
 483  		.name = "BAS",
 484  		.ident = IDENT_BAS,
 485  		.idVendor = IDVENDOR_FTDI,
 486  		.idProduct = 0x6014,
 487  		.iManufacturer = "FTDI",
 488  		.iProduct = "BitFORCE SHA256 SC",
 489  		.config = 1,
 490  		.timeout = BFLSC_TIMEOUT_MS,
 491  		.latency = LATENCY_STD,
 492  		INTINFO(bflsc_ints) },
 493  	{
 494  		.drv = DRIVER_bflsc,
 495  		.name = "BAS",
 496  		.ident = IDENT_BAS,
 497  		.idVendor = IDVENDOR_FTDI,
 498  		.idProduct = 0x6014,
 499  		.iManufacturer = "Butterfly Labs",
 500  		.iProduct = "BitFORCE SHA256 SC",
 501  		.config = 1,
 502  		.timeout = BFLSC_TIMEOUT_MS,
 503  		.latency = LATENCY_STD,
 504  		INTINFO(bflsc_ints) },
 505  	{
 506  		.drv = DRIVER_bflsc,
 507  		.name = "BMA",
 508  		.ident = IDENT_BMA,
 509  		.idVendor = IDVENDOR_FTDI,
 510  		.idProduct = 0x6014,
 511  		.iManufacturer = "BUTTERFLY LABS",
 512  		.iProduct = "BitFORCE SHA256 SC",
 513  		.config = 1,
 514  		.timeout = BFLSC_TIMEOUT_MS,
 515  		.latency = LATENCY_STD,
 516  		INTINFO(bflsc_ints) },
 517  	{
 518  		.drv = DRIVER_bflsc,
 519  		.name = "BMA",
 520  		.ident = IDENT_BMA,
 521  		.idVendor = IDVENDOR_FTDI,
 522  		.idProduct = 0x6014,
 523  		.iManufacturer = "BUTTERFLY LABS",
 524  		.iProduct = "BitFORCE SC-28nm",
 525  		.config = 1,
 526  		.timeout = BFLSC_TIMEOUT_MS,
 527  		.latency = LATENCY_STD,
 528  		INTINFO(bflsc_ints) },
 529  	{
 530  		.drv = DRIVER_bflsc,
 531  		.name = "BMA",
 532  		.ident = IDENT_BMA,
 533  		.idVendor = IDVENDOR_FTDI,
 534  		.idProduct = 0x6014,
 535  		.iManufacturer = "BUTTERFLY LABS",
 536  		.iProduct = "BitFORCE SHA256",
 537  		.config = 1,
 538  		.timeout = BFLSC_TIMEOUT_MS,
 539  		.latency = LATENCY_STD,
 540  		INTINFO(bflsc_ints) },
 541  #endif
 542  #ifdef USE_BITFORCE
 543  	{
 544  		.drv = DRIVER_bitforce,
 545  		.name = "BFL",
 546  		.ident = IDENT_BFL,
 547  		.idVendor = IDVENDOR_FTDI,
 548  		.idProduct = 0x6014,
 549  		.iManufacturer = "Butterfly Labs Inc.",
 550  		.iProduct = "BitFORCE SHA256",
 551  		.config = 1,
 552  		.timeout = BITFORCE_TIMEOUT_MS,
 553  		.latency = LATENCY_STD,
 554  		INTINFO(bfl_ints) },
 555  #endif
 556  #ifdef USE_BITFURY
 557  	{
 558  		.drv = DRIVER_bitfury,
 559  		.name = "BF1",
 560  		.ident = IDENT_BF1,
 561  		.idVendor = 0x03eb,
 562  		.idProduct = 0x204b,
 563  		.config = 1,
 564  		.timeout = BITFURY_TIMEOUT_MS,
 565  		.latency = LATENCY_UNUSED,
 566  		//.iManufacturer = "BPMC",
 567  		.iProduct = "Bitfury BF1",
 568  		INTINFO(bfu_ints)
 569  	},
 570  	{
 571  		.drv = DRIVER_bitfury,
 572  		.name = "BXF",
 573  		.ident = IDENT_BXF,
 574  		.idVendor = 0x198c,
 575  		.idProduct = 0xb1f1,
 576  		.config = 1,
 577  		.timeout = BITFURY_TIMEOUT_MS,
 578  		.latency = LATENCY_UNUSED,
 579  		.iManufacturer = "c-scape",
 580  		.iProduct = "bi?fury",
 581  		INTINFO(bxf_ints)
 582  	},
 583  	{
 584  		.drv = DRIVER_bitfury,
 585  		.name = "OSM",
 586  		.ident = IDENT_OSM,
 587  		.idVendor = 0x198c,
 588  		.idProduct = 0xb1f1,
 589  		.config = 1,
 590  		.timeout = BITFURY_TIMEOUT_MS,
 591  		.latency = LATENCY_UNUSED,
 592  		.iManufacturer = "c-scape",
 593  		.iProduct = "OneString",
 594  		INTINFO(bxf_ints)
 595  	},
 596  	{
 597  		.drv = DRIVER_bitfury,
 598  		.name = "NFU",
 599  		.ident = IDENT_NFU,
 600  		.idVendor = 0x04d8,
 601  		.idProduct = 0x00de,
 602  		.config = 1,
 603  		.timeout = BITFURY_TIMEOUT_MS,
 604  		.latency = LATENCY_UNUSED,
 605  		INTINFO(nfu_ints)
 606  	},
 607  	{
 608  		.drv = DRIVER_bitfury,
 609  		.name = "BXM",
 610  		.ident = IDENT_BXM,
 611  		.idVendor = 0x0403,
 612  		.idProduct = 0x6014,
 613  		.config = 1,
 614  		.timeout = BITFURY_TIMEOUT_MS,
 615  		.latency = LATENCY_UNUSED,
 616  		INTINFO(bxm_ints)
 617  	},
 618  #endif
 619  #ifdef USE_DRILLBIT
 620  	{
 621  		.drv = DRIVER_drillbit,
 622  		.name = "DRB",
 623  		.ident = IDENT_DRB,
 624  		.idVendor = 0x03eb,
 625  		.idProduct = 0x2404,
 626  		.config = 1,
 627  		.timeout = DRILLBIT_TIMEOUT_MS,
 628  		.latency = LATENCY_UNUSED,
 629  		.iManufacturer = "Drillbit Systems",
 630  		.iProduct = NULL, /* Can be Thumb or Eight, same driver */
 631  		INTINFO(drillbit_ints)
 632  	},
 633  #endif
 634  #ifdef USE_MODMINER
 635  	{
 636  		.drv = DRIVER_modminer,
 637  		.name = "MMQ",
 638  		.ident = IDENT_MMQ,
 639  		.idVendor = 0x1fc9,
 640  		.idProduct = 0x0003,
 641  		.config = 1,
 642  		.timeout = MODMINER_TIMEOUT_MS,
 643  		.latency = LATENCY_UNUSED,
 644  		INTINFO(mmq_ints) },
 645  #endif
 646  #ifdef USE_AVALON
 647  	{
 648  		.drv = DRIVER_avalon,
 649  		.name = "BTB",
 650  		.ident = IDENT_BTB,
 651  		.idVendor = IDVENDOR_FTDI,
 652  		.idProduct = 0x6001,
 653  		.iManufacturer = "Burnin Electronics",
 654  		.iProduct = "BitBurner",
 655  		.config = 1,
 656  		.timeout = AVALON_TIMEOUT_MS,
 657  		.latency = 10,
 658  		INTINFO(ava_ints) },
 659  	{
 660  		.drv = DRIVER_avalon,
 661  		.name = "BBF",
 662  		.ident = IDENT_BBF,
 663  		.idVendor = IDVENDOR_FTDI,
 664  		.idProduct = 0x6001,
 665  		.iManufacturer = "Burnin Electronics",
 666  		.iProduct = "BitBurner Fury",
 667  		.config = 1,
 668  		.timeout = AVALON_TIMEOUT_MS,
 669  		.latency = 10,
 670  		INTINFO(ava_ints) },
 671  	{
 672  		.drv = DRIVER_avalon,
 673  		.name = "AVA",
 674  		.ident = IDENT_AVA,
 675  		.idVendor = IDVENDOR_FTDI,
 676  		.idProduct = 0x6001,
 677  		.config = 1,
 678  		.timeout = AVALON_TIMEOUT_MS,
 679  		.latency = 10,
 680  		INTINFO(ava_ints) },
 681  #endif
 682  #ifdef USE_AVALON2
 683  	{
 684  		.drv = DRIVER_avalon2,
 685  		.name = "AV2",
 686  		.ident = IDENT_AV2,
 687  		.idVendor = 0x067b,
 688  		.idProduct = 0x2303,
 689  		.config = 1,
 690  		.timeout = AVALON_TIMEOUT_MS,
 691  		.latency = LATENCY_UNUSED,
 692  		INTINFO(ava2_ints) },
 693  #endif
 694  #ifdef USE_AVALON4
 695  	{
 696  		.drv = DRIVER_avalon4,
 697  		.name = "AV4",
 698  		.ident = IDENT_AV4,
 699  		.idVendor = 0x29f1,
 700  		.idProduct = 0x33f2,
 701  		.iManufacturer = "CANAAN",
 702  		.iProduct = "USB2IIC Converter",
 703  		.config = 1,
 704  		.timeout = AVALON4_TIMEOUT_MS,
 705  		.latency = LATENCY_UNUSED,
 706  		INTINFO(ava4_ints) },
 707  #endif
 708  #ifdef USE_AVALON7
 709  	{
 710  		.drv = DRIVER_avalon7,
 711  		.name = "AV7",
 712  		.ident = IDENT_AV7,
 713  		.idVendor = 0x29f1,
 714  		.idProduct = 0x33f2,
 715  		.iManufacturer = "CANAAN",
 716  		.iProduct = "USB2IIC Converter",
 717  		.config = 1,
 718  		.timeout = AVALON7_TIMEOUT_MS,
 719  		.latency = LATENCY_UNUSED,
 720  		INTINFO(ava7_ints) },
 721  #endif
 722  #ifdef USE_AVALON8
 723  	{
 724  		.drv = DRIVER_avalon8,
 725  		.name = "AV8",
 726  		.ident = IDENT_AV8,
 727  		.idVendor = 0x29f1,
 728  		.idProduct = 0x33f2,
 729  		.iManufacturer = "CANAAN",
 730  		.iProduct = "USB2IIC Converter",
 731  		.config = 1,
 732  		.timeout = AVALON8_TIMEOUT_MS,
 733  		.latency = LATENCY_UNUSED,
 734  		INTINFO(ava8_ints) },
 735  #endif
 736  #ifdef USE_AVALON_MINER
 737  	{
 738  		.drv = DRIVER_avalonm,
 739  		.name = "AV4M",
 740  		.ident = IDENT_AVM,
 741  		.idVendor = 0x29f1,
 742  		.idProduct = 0x40f1,
 743  		.iManufacturer = "CANAAN",
 744  		.iProduct = "Avalon4 mini",
 745  		.config = 1,
 746  		.timeout = AVALONM_TIMEOUT_MS,
 747  		.latency = LATENCY_UNUSED,
 748  		INTINFO(avam_ints) },
 749  	{
 750  		.drv = DRIVER_avalonm,
 751  		.name = "AV3U",
 752  		.ident = IDENT_AVM,
 753  		.idVendor = 0x29f1,
 754  		.idProduct = 0x33f3,
 755  		.iManufacturer = "CANAAN",
 756  		.iProduct = "Avalon nano",
 757  		.config = 1,
 758  		.timeout = AVALONM_TIMEOUT_MS,
 759  		.latency = LATENCY_UNUSED,
 760  		INTINFO(av3u_ints) },
 761  
 762  #endif
 763  #ifdef USE_HASHFAST
 764  	{
 765  		.drv = DRIVER_hashfast,
 766  		.name = "HFA",
 767  		.ident = IDENT_HFA,
 768  		.idVendor = HF_USB_VENDOR_ID,
 769  		.idProduct = HF_USB_PRODUCT_ID_G1,
 770  		.iManufacturer = "HashFast LLC",
 771  		.iProduct = "M1 Module",
 772  		.config = 1,
 773  		.timeout = HASHFAST_TIMEOUT_MS,
 774  		.latency = LATENCY_UNUSED,
 775  		INTINFO(hfa_ints) },
 776  #endif
 777  #ifdef USE_HASHRATIO
 778  	{
 779  		.drv = DRIVER_hashratio,
 780  		.name = "HRO",
 781  		.ident = IDENT_HRO,
 782  		.idVendor = IDVENDOR_FTDI,
 783  		.idProduct = 0x6001,
 784  		.config = 1,
 785  		.timeout = HASHRATIO_TIMEOUT_MS,
 786  		.latency = LATENCY_UNUSED,
 787  		INTINFO(hro_ints) },
 788  #endif
 789  #ifdef USE_KLONDIKE
 790  	{
 791  		.drv = DRIVER_klondike,
 792  		.name = "KLN",
 793  		.ident = IDENT_KLN,
 794  		.idVendor = 0x04D8,
 795  		.idProduct = 0xF60A,
 796  		.config = 1,
 797  		.timeout = KLONDIKE_TIMEOUT_MS,
 798  		.latency = 10,
 799  		INTINFO(kln_ints) },
 800  	{
 801  		.drv = DRIVER_klondike,
 802  		.name = "KLI",
 803  		.ident = IDENT_KLN,
 804  		.idVendor = 0x04D8,
 805  		.idProduct = 0xF60A,
 806  		.config = 1,
 807  		.timeout = KLONDIKE_TIMEOUT_MS,
 808  		.latency = 10,
 809  		INTINFO(kli_ints) },
 810  #endif
 811  #ifdef USE_ICARUS
 812  	{
 813  		.drv = DRIVER_icarus,
 814  		.name = "ICA",
 815  		.ident = IDENT_ICA,
 816  		.idVendor = 0x067b,
 817  		.idProduct = 0x2303,
 818  		.config = 1,
 819  		.timeout = ICARUS_TIMEOUT_MS,
 820  		.latency = LATENCY_UNUSED,
 821  		INTINFO(ica_ints) },
 822   	{
 823   		.drv = DRIVER_icarus,
 824   		.name = "ICA",
 825   		.ident = IDENT_AVA,
 826   		.idVendor = 0x1fc9,
 827   		.idProduct = 0x0083,
 828   		.config = 1,
 829   		.timeout = ICARUS_TIMEOUT_MS,
 830   		.latency = LATENCY_UNUSED,
 831   		INTINFO(ica1_ints) },
 832  	{
 833  		.drv = DRIVER_icarus,
 834  		.name = "BSC",
 835  		.ident = IDENT_BSC,
 836  		.idVendor = 0x10c4,
 837  		.idProduct = 0xea60,
 838  		.iManufacturer = "bitshopperde",
 839  		.iProduct = "Compac BM1384 Bitcoin Miner",
 840  		.config = 1,
 841  		.timeout = ICARUS_TIMEOUT_MS,
 842  		.latency = LATENCY_UNUSED,
 843  		INTINFO(amu_ints) },
 844  	{
 845  		.drv = DRIVER_icarus,
 846  		.name = "GSC",
 847  		.ident = IDENT_GSC,
 848  		.idVendor = 0x10c4,
 849  		.idProduct = 0xea60,
 850  		.iManufacturer = "GekkoScience",
 851  		.iProduct = "Compac BM1384 Bitcoin Miner",
 852  		.config = 1,
 853  		.timeout = ICARUS_TIMEOUT_MS,
 854  		.latency = LATENCY_UNUSED,
 855  		INTINFO(amu_ints) },
 856  	{
 857  		.drv = DRIVER_icarus,
 858  		.name = "AMU",
 859  		.ident = IDENT_AMU,
 860  		.idVendor = 0x10c4,
 861  		.idProduct = 0xea60,
 862  		.config = 1,
 863  		.timeout = ICARUS_TIMEOUT_MS,
 864  		.latency = LATENCY_UNUSED,
 865  		INTINFO(amu_ints) },
 866  	{
 867  		.drv = DRIVER_icarus,
 868  		.name = "LIN",
 869  		.ident = IDENT_LIN,
 870  		.idVendor = 0x10c4,
 871  		.idProduct = 0xea60,
 872  		.config = 1,
 873  		.timeout = ICARUS_TIMEOUT_MS,
 874  		.latency = LATENCY_UNUSED,
 875  		INTINFO(amu_ints) },
 876  	{
 877  		.drv = DRIVER_icarus,
 878  		.name = "ANU",
 879  		.ident = IDENT_ANU,
 880  		.idVendor = 0x10c4,
 881  		.idProduct = 0xea60,
 882  		.config = 1,
 883  		.timeout = ICARUS_TIMEOUT_MS,
 884  		.latency = LATENCY_UNUSED,
 885  		INTINFO(amu_ints) },
 886  	{
 887  		.drv = DRIVER_icarus,
 888  		.name = "BLT",
 889  		.ident = IDENT_BLT,
 890  		.idVendor = IDVENDOR_FTDI,
 891  		.idProduct = 0x6001,
 892  		.iProduct = "FT232R USB UART",
 893  		.config = 1,
 894  		.timeout = ICARUS_TIMEOUT_MS,
 895  		.latency = LATENCY_STD,
 896  		INTINFO(llt_ints) },
 897  	// For any that don't match the above "BLT"
 898  	{
 899  		.drv = DRIVER_icarus,
 900  		.name = "LLT",
 901  		.ident = IDENT_LLT,
 902  		.idVendor = IDVENDOR_FTDI,
 903  		.idProduct = 0x6001,
 904  		.config = 1,
 905  		.timeout = ICARUS_TIMEOUT_MS,
 906  		.latency = LATENCY_STD,
 907  		INTINFO(llt_ints) },
 908  	{
 909  		.drv = DRIVER_icarus,
 910  		.name = "CMR",
 911  		.ident = IDENT_CMR1,
 912  		.idVendor = IDVENDOR_FTDI,
 913  		.idProduct = 0x6014,
 914  		.iProduct = "Cairnsmore1",
 915  		.config = 1,
 916  		.timeout = ICARUS_TIMEOUT_MS,
 917  		.latency = LATENCY_STD,
 918  		INTINFO(cmr1_ints) },
 919  	{
 920  		.drv = DRIVER_icarus,
 921  		.name = "CMR",
 922  		.ident = IDENT_CMR2,
 923  		.idVendor = IDVENDOR_FTDI,
 924  		.idProduct = 0x8350,
 925  		.iProduct = "Cairnsmore1",
 926  		.config = 1,
 927  		.timeout = ICARUS_TIMEOUT_MS,
 928  		.latency = LATENCY_STD,
 929  		INTINFO(cmr2_ints) },
 930  #endif
 931  #ifdef USE_COINTERRA
 932  	{
 933  		.drv = DRIVER_cointerra,
 934  		.name = "CTA",
 935  		.ident = IDENT_CTA,
 936  		.idVendor = 0x1cbe,
 937  		.idProduct = 0x0003,
 938  		.config = 1,
 939  		.timeout = COINTERRA_TIMEOUT_MS,
 940  		.latency = LATENCY_STD,
 941  		INTINFO(cointerra_ints) },
 942  #endif
 943  #ifdef USE_ANT_S1
 944  	{
 945  		.drv = DRIVER_ants1,
 946  		.name = "ANT",
 947  		.ident = IDENT_ANT,
 948  		.idVendor = 0x4254,
 949  		.idProduct = 0x4153,
 950  		.config = 1,
 951  		.timeout = ANT_S1_TIMEOUT_MS,
 952  		.latency = LATENCY_ANTS1,
 953  		INTINFO(ants1_ints) },
 954  #endif
 955  #ifdef USE_ANT_S3
 956  	{
 957  		.drv = DRIVER_ants3,
 958  		.name = "AS3",
 959  		.ident = IDENT_AS3,
 960  		.idVendor = 0x4254,
 961  		.idProduct = 0x4153,
 962  		.config = 1,
 963  		.timeout = ANT_S3_TIMEOUT_MS,
 964  		.latency = LATENCY_ANTS3,
 965  		INTINFO(ants3_ints) },
 966  #endif
 967  #ifdef USE_BLOCKERUPTER
 968  	{
 969  		.drv = DRIVER_blockerupter,
 970  		.name = "BET",
 971  		.ident = IDENT_BET,
 972  		.idVendor = 0x10c4,
 973  		.idProduct = 0xea60,
 974  		.config = 1,
 975  		.timeout = BLOCKERUPTER_TIMEOUT_MS,
 976  		.latency = LATENCY_UNUSED,
 977  		INTINFO(bet_ints) },
 978  
 979  #endif
 980  	{ DRIVER_MAX, NULL, 0, 0, 0, NULL, NULL, 0, 0, 0, 0, NULL }
 981  };
 982  
 983  #define STRBUFLEN 256
 984  static const char *BLANK = "";
 985  static const char *space = " ";
 986  static const char *nodatareturned = "no data returned ";
 987  
 988  #if 0 // enable USBDEBUG - only during development testing
 989   static const char *debug_true_str = "true";
 990   static const char *debug_false_str = "false";
 991   static const char *nodevstr = "=NODEV";
 992   #define bool_str(boo) ((boo) ? debug_true_str : debug_false_str)
 993   #define isnodev(err) (NODEV(err) ? nodevstr : BLANK)
 994   #define USBDEBUG(fmt, ...) applog(LOG_WARNING, fmt, ##__VA_ARGS__)
 995  #else
 996   #define USBDEBUG(fmt, ...)
 997  #endif
 998  
 999  // For device limits by driver
1000  static struct driver_count {
1001  	int count;
1002  	int limit;
1003  } drv_count[DRIVER_MAX];
1004  
1005  // For device limits by list of bus/dev
1006  static struct usb_busdev {
1007  	int bus_number;
1008  	int device_address;
1009  #ifdef WIN32
1010  	void *resource1;
1011  	void *resource2;
1012  #else
1013  	int fd;
1014  #endif
1015  } *busdev;
1016  
1017  static int busdev_count = 0;
1018  
1019  // Total device limit
1020  static int total_count = 0;
1021  static int total_limit = 999999;
1022  
1023  struct usb_in_use_list {
1024  	struct usb_busdev in_use;
1025  	struct usb_in_use_list *prev;
1026  	struct usb_in_use_list *next;
1027  };
1028  
1029  // List of in use devices
1030  static struct usb_in_use_list *in_use_head = NULL;
1031  static struct usb_in_use_list *blacklist_head = NULL;
1032  
1033  struct resource_work {
1034  	bool lock;
1035  	const char *dname;
1036  	uint8_t bus_number;
1037  	uint8_t device_address;
1038  	struct resource_work *next;
1039  };
1040  
1041  // Pending work for the reslock thread
1042  struct resource_work *res_work_head = NULL;
1043  
1044  struct resource_reply {
1045  	uint8_t bus_number;
1046  	uint8_t device_address;
1047  	bool got;
1048  	struct resource_reply *next;
1049  };
1050  
1051  // Replies to lock requests
1052  struct resource_reply *res_reply_head = NULL;
1053  
1054  // Some stats need to always be defined
1055  #define SEQ0 0
1056  #define SEQ1 1
1057  
1058  // NONE must be 0 - calloced
1059  #define MODE_NONE 0
1060  #define MODE_CTRL_READ (1 << 0)
1061  #define MODE_CTRL_WRITE (1 << 1)
1062  #define MODE_BULK_READ (1 << 2)
1063  #define MODE_BULK_WRITE (1 << 3)
1064  
1065  // Set this to 0 to remove stats processing
1066  #define DO_USB_STATS 1
1067  
1068  static bool stats_initialised = false;
1069  
1070  #if DO_USB_STATS
1071  
1072  #define MODE_SEP_STR "+"
1073  #define MODE_NONE_STR "X"
1074  #define MODE_CTRL_READ_STR "cr"
1075  #define MODE_CTRL_WRITE_STR "cw"
1076  #define MODE_BULK_READ_STR "br"
1077  #define MODE_BULK_WRITE_STR "bw"
1078  
1079  // One for each CMD, TIMEOUT, ERROR
1080  struct cg_usb_stats_item {
1081  	uint64_t count;
1082  	double total_delay;
1083  	double min_delay;
1084  	double max_delay;
1085  	struct timeval first;
1086  	struct timeval last;
1087  };
1088  
1089  #define CMD_CMD 0
1090  #define CMD_TIMEOUT 1
1091  #define CMD_ERROR 2
1092  
1093  // One for each C_CMD
1094  struct cg_usb_stats_details {
1095  	int seq;
1096  	uint32_t modes;
1097  	struct cg_usb_stats_item item[CMD_ERROR+1];
1098  };
1099  
1100  // One for each device
1101  struct cg_usb_stats {
1102  	char *name;
1103  	int device_id;
1104  	struct cg_usb_stats_details *details;
1105  };
1106  
1107  static struct cg_usb_stats *usb_stats = NULL;
1108  static int next_stat = USB_NOSTAT;
1109  
1110  #define SECTOMS(s) ((int)((s) * 1000))
1111  
1112  #define USB_STATS(sgpu_, sta_, fin_, err_, mode_, cmd_, seq_, tmo_) \
1113  		stats(sgpu_, sta_, fin_, err_, mode_, cmd_, seq_, tmo_)
1114  #define STATS_TIMEVAL(tv_) cgtime(tv_)
1115  #define USB_REJECT(sgpu_, mode_) rejected_inc(sgpu_, mode_)
1116  
1117  #else
1118  #define USB_STATS(sgpu_, sta_, fin_, err_, mode_, cmd_, seq_, tmo_)
1119  #define STATS_TIMEVAL(tv_)
1120  #define USB_REJECT(sgpu_, mode_)
1121  
1122  #endif // DO_USB_STATS
1123  
1124  /* Create usb_commands array from USB_PARSE_COMMANDS macro in usbutils.h */
1125  char *usb_commands[] = {
1126  	USB_PARSE_COMMANDS(JUMPTABLE)
1127  	"Null"
1128  };
1129  
1130  #ifdef EOL
1131  #undef EOL
1132  #endif
1133  #define EOL "\n"
1134  
1135  static const char *DESDEV = "Device";
1136  static const char *DESCON = "Config";
1137  static const char *DESSTR = "String";
1138  static const char *DESINT = "Interface";
1139  static const char *DESEP = "Endpoint";
1140  static const char *DESHID = "HID";
1141  static const char *DESRPT = "Report";
1142  static const char *DESPHY = "Physical";
1143  static const char *DESHUB = "Hub";
1144  
1145  static const char *EPIN = "In: ";
1146  static const char *EPOUT = "Out: ";
1147  static const char *EPX = "?: ";
1148  
1149  static const char *CONTROL = "Control";
1150  static const char *ISOCHRONOUS_X = "Isochronous+?";
1151  static const char *ISOCHRONOUS_N_X = "Isochronous+None+?";
1152  static const char *ISOCHRONOUS_N_D = "Isochronous+None+Data";
1153  static const char *ISOCHRONOUS_N_F = "Isochronous+None+Feedback";
1154  static const char *ISOCHRONOUS_N_I = "Isochronous+None+Implicit";
1155  static const char *ISOCHRONOUS_A_X = "Isochronous+Async+?";
1156  static const char *ISOCHRONOUS_A_D = "Isochronous+Async+Data";
1157  static const char *ISOCHRONOUS_A_F = "Isochronous+Async+Feedback";
1158  static const char *ISOCHRONOUS_A_I = "Isochronous+Async+Implicit";
1159  static const char *ISOCHRONOUS_D_X = "Isochronous+Adaptive+?";
1160  static const char *ISOCHRONOUS_D_D = "Isochronous+Adaptive+Data";
1161  static const char *ISOCHRONOUS_D_F = "Isochronous+Adaptive+Feedback";
1162  static const char *ISOCHRONOUS_D_I = "Isochronous+Adaptive+Implicit";
1163  static const char *ISOCHRONOUS_S_X = "Isochronous+Sync+?";
1164  static const char *ISOCHRONOUS_S_D = "Isochronous+Sync+Data";
1165  static const char *ISOCHRONOUS_S_F = "Isochronous+Sync+Feedback";
1166  static const char *ISOCHRONOUS_S_I = "Isochronous+Sync+Implicit";
1167  static const char *BULK = "Bulk";
1168  static const char *INTERRUPT = "Interrupt";
1169  static const char *UNKNOWN = "Unknown";
1170  
1171  static const char *destype(uint8_t bDescriptorType)
1172  {
1173  	switch (bDescriptorType) {
1174  		case LIBUSB_DT_DEVICE:
1175  			return DESDEV;
1176  		case LIBUSB_DT_CONFIG:
1177  			return DESCON;
1178  		case LIBUSB_DT_STRING:
1179  			return DESSTR;
1180  		case LIBUSB_DT_INTERFACE:
1181  			return DESINT;
1182  		case LIBUSB_DT_ENDPOINT:
1183  			return DESEP;
1184  		case LIBUSB_DT_HID:
1185  			return DESHID;
1186  		case LIBUSB_DT_REPORT:
1187  			return DESRPT;
1188  		case LIBUSB_DT_PHYSICAL:
1189  			return DESPHY;
1190  		case LIBUSB_DT_HUB:
1191  			return DESHUB;
1192  	}
1193  	return UNKNOWN;
1194  }
1195  
1196  static const char *epdir(uint8_t bEndpointAddress)
1197  {
1198  	switch (bEndpointAddress & LIBUSB_ENDPOINT_DIR_MASK) {
1199  		case LIBUSB_ENDPOINT_IN:
1200  			return EPIN;
1201  		case LIBUSB_ENDPOINT_OUT:
1202  			return EPOUT;
1203  	}
1204  	return EPX;
1205  }
1206  
1207  static const char *epatt(uint8_t bmAttributes)
1208  {
1209  	switch(bmAttributes & LIBUSB_TRANSFER_TYPE_MASK) {
1210  		case LIBUSB_TRANSFER_TYPE_CONTROL:
1211  			return CONTROL;
1212  		case LIBUSB_TRANSFER_TYPE_BULK:
1213  			return BULK;
1214  		case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1215  			return INTERRUPT;
1216  		case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1217  			switch(bmAttributes & LIBUSB_ISO_SYNC_TYPE_MASK) {
1218  				case LIBUSB_ISO_SYNC_TYPE_NONE:
1219  					switch(bmAttributes & LIBUSB_ISO_USAGE_TYPE_MASK) {
1220  						case LIBUSB_ISO_USAGE_TYPE_DATA:
1221  							return ISOCHRONOUS_N_D;
1222  						case LIBUSB_ISO_USAGE_TYPE_FEEDBACK:
1223  							return ISOCHRONOUS_N_F;
1224  						case LIBUSB_ISO_USAGE_TYPE_IMPLICIT:
1225  							return ISOCHRONOUS_N_I;
1226  					}
1227  					return ISOCHRONOUS_N_X;
1228  				case LIBUSB_ISO_SYNC_TYPE_ASYNC:
1229  					switch(bmAttributes & LIBUSB_ISO_USAGE_TYPE_MASK) {
1230  						case LIBUSB_ISO_USAGE_TYPE_DATA:
1231  							return ISOCHRONOUS_A_D;
1232  						case LIBUSB_ISO_USAGE_TYPE_FEEDBACK:
1233  							return ISOCHRONOUS_A_F;
1234  						case LIBUSB_ISO_USAGE_TYPE_IMPLICIT:
1235  							return ISOCHRONOUS_A_I;
1236  					}
1237  					return ISOCHRONOUS_A_X;
1238  				case LIBUSB_ISO_SYNC_TYPE_ADAPTIVE:
1239  					switch(bmAttributes & LIBUSB_ISO_USAGE_TYPE_MASK) {
1240  						case LIBUSB_ISO_USAGE_TYPE_DATA:
1241  							return ISOCHRONOUS_D_D;
1242  						case LIBUSB_ISO_USAGE_TYPE_FEEDBACK:
1243  							return ISOCHRONOUS_D_F;
1244  						case LIBUSB_ISO_USAGE_TYPE_IMPLICIT:
1245  							return ISOCHRONOUS_D_I;
1246  					}
1247  					return ISOCHRONOUS_D_X;
1248  				case LIBUSB_ISO_SYNC_TYPE_SYNC:
1249  					switch(bmAttributes & LIBUSB_ISO_USAGE_TYPE_MASK) {
1250  						case LIBUSB_ISO_USAGE_TYPE_DATA:
1251  							return ISOCHRONOUS_S_D;
1252  						case LIBUSB_ISO_USAGE_TYPE_FEEDBACK:
1253  							return ISOCHRONOUS_S_F;
1254  						case LIBUSB_ISO_USAGE_TYPE_IMPLICIT:
1255  							return ISOCHRONOUS_S_I;
1256  					}
1257  					return ISOCHRONOUS_S_X;
1258  			}
1259  			return ISOCHRONOUS_X;
1260  	}
1261  
1262  	return UNKNOWN;
1263  }
1264  
1265  static void append(char **buf, char *append, size_t *off, size_t *len)
1266  {
1267  	int new = strlen(append);
1268  	if ((new + *off) >= *len)
1269  	{
1270  		*len *= 2;
1271  		*buf = cgrealloc(*buf, *len);
1272  	}
1273  
1274  	strcpy(*buf + *off, append);
1275  	*off += new;
1276  }
1277  
1278  static bool setgetdes(ssize_t count, libusb_device *dev, struct libusb_device_handle *handle, struct libusb_config_descriptor **config, int cd, char **buf, size_t *off, size_t *len)
1279  {
1280  	char tmp[512];
1281  	int err;
1282  
1283  	err = libusb_set_configuration(handle, cd);
1284  	if (err) {
1285  		snprintf(tmp, sizeof(tmp), EOL "  ** dev %d: Failed to set config descriptor to %d, err %d",
1286  				(int)count, cd, err);
1287  		append(buf, tmp, off, len);
1288  		return false;
1289  	}
1290  
1291  	err = libusb_get_active_config_descriptor(dev, config);
1292  	if (err) {
1293  		snprintf(tmp, sizeof(tmp), EOL "  ** dev %d: Failed to get active config descriptor set to %d, err %d",
1294  				(int)count, cd, err);
1295  		append(buf, tmp, off, len);
1296  		return false;
1297  	}
1298  
1299  	snprintf(tmp, sizeof(tmp), EOL "  ** dev %d: Set & Got active config descriptor to %d, err %d",
1300  			(int)count, cd, err);
1301  	append(buf, tmp, off, len);
1302  	return true;
1303  }
1304  
1305  static void usb_full(ssize_t *count, libusb_device *dev, char **buf, size_t *off, size_t *len, int level)
1306  {
1307  	struct libusb_device_descriptor desc;
1308  	uint8_t bus_number;
1309  	uint8_t device_address;
1310  	struct libusb_device_handle *handle;
1311  	struct libusb_config_descriptor *config;
1312  	const struct libusb_interface_descriptor *idesc;
1313  	const struct libusb_endpoint_descriptor *epdesc;
1314  	unsigned char man[STRBUFLEN+1];
1315  	unsigned char prod[STRBUFLEN+1];
1316  	unsigned char ser[STRBUFLEN+1];
1317  	char tmp[512];
1318  	int err, i, j, k;
1319  
1320  	err = libusb_get_device_descriptor(dev, &desc);
1321  	if (opt_usb_list_all && err) {
1322  		snprintf(tmp, sizeof(tmp), EOL ".USB dev %d: Failed to get descriptor, err %d",
1323  					(int)(++(*count)), err);
1324  		append(buf, tmp, off, len);
1325  		return;
1326  	}
1327  
1328  	bus_number = libusb_get_bus_number(dev);
1329  	device_address = libusb_get_device_address(dev);
1330  
1331  	if (!opt_usb_list_all) {
1332  		bool known = false;
1333  
1334  		for (i = 0; find_dev[i].drv != DRIVER_MAX; i++)
1335  			if ((find_dev[i].idVendor == desc.idVendor) &&
1336  			    (find_dev[i].idProduct == desc.idProduct)) {
1337  				known = true;
1338  				break;
1339  			}
1340  
1341  		if (!known)
1342  			return;
1343  	}
1344  
1345  	(*count)++;
1346  
1347  	if (level == 0) {
1348  		snprintf(tmp, sizeof(tmp), EOL ".USB dev %d: Bus %d Device %d ID: %04x:%04x",
1349  				(int)(*count), (int)bus_number, (int)device_address,
1350  				desc.idVendor, desc.idProduct);
1351  	} else {
1352  		snprintf(tmp, sizeof(tmp), EOL ".USB dev %d: Bus %d Device %d Device Descriptor:" EOL "\tLength: %d" EOL
1353  			"\tDescriptor Type: %s" EOL "\tUSB: %04x" EOL "\tDeviceClass: %d" EOL
1354  			"\tDeviceSubClass: %d" EOL "\tDeviceProtocol: %d" EOL "\tMaxPacketSize0: %d" EOL
1355  			"\tidVendor: %04x" EOL "\tidProduct: %04x" EOL "\tDeviceRelease: %x" EOL
1356  			"\tNumConfigurations: %d",
1357  				(int)(*count), (int)bus_number, (int)device_address,
1358  				(int)(desc.bLength), destype(desc.bDescriptorType),
1359  				desc.bcdUSB, (int)(desc.bDeviceClass), (int)(desc.bDeviceSubClass),
1360  				(int)(desc.bDeviceProtocol), (int)(desc.bMaxPacketSize0),
1361  				desc.idVendor, desc.idProduct, desc.bcdDevice,
1362  				(int)(desc.bNumConfigurations));
1363  	}
1364  	append(buf, tmp, off, len);
1365  
1366  	err = libusb_open(dev, &handle);
1367  	if (err) {
1368  		snprintf(tmp, sizeof(tmp), EOL "  ** dev %d: Failed to open, err %d", (int)(*count), err);
1369  		append(buf, tmp, off, len);
1370  		return;
1371  	}
1372  
1373  	err = libusb_get_string_descriptor_ascii(handle, desc.iManufacturer, man, STRBUFLEN);
1374  	if (err < 0)
1375  		snprintf((char *)man, sizeof(man), "** err:(%d) %s", err, libusb_error_name(err));
1376  
1377  	err = libusb_get_string_descriptor_ascii(handle, desc.iProduct, prod, STRBUFLEN);
1378  	if (err < 0)
1379  		snprintf((char *)prod, sizeof(prod), "** err:(%d) %s", err, libusb_error_name(err));
1380  
1381  	if (level == 0) {
1382  		libusb_close(handle);
1383  		snprintf(tmp, sizeof(tmp), EOL "  Manufacturer: '%s'" EOL "  Product: '%s'", man, prod);
1384  		append(buf, tmp, off, len);
1385  		return;
1386  	}
1387  
1388  	if (libusb_kernel_driver_active(handle, 0) == 1) {
1389  		snprintf(tmp, sizeof(tmp), EOL "   * dev %d: kernel attached", (int)(*count));
1390  		append(buf, tmp, off, len);
1391  	}
1392  
1393  	err = libusb_get_active_config_descriptor(dev, &config);
1394  	if (err) {
1395  		if (!setgetdes(*count, dev, handle, &config, 1, buf, off, len)
1396  		&&  !setgetdes(*count, dev, handle, &config, 0, buf, off, len)) {
1397  			libusb_close(handle);
1398  			snprintf(tmp, sizeof(tmp), EOL "  ** dev %d: Failed to set config descriptor to %d or %d",
1399  					(int)(*count), 1, 0);
1400  			append(buf, tmp, off, len);
1401  			return;
1402  		}
1403  	}
1404  
1405  	snprintf(tmp, sizeof(tmp), EOL "     dev %d: Active Config:" EOL "\tDescriptorType: %s" EOL
1406  			"\tNumInterfaces: %d" EOL "\tConfigurationValue: %d" EOL
1407  			"\tAttributes: %d" EOL "\tMaxPower: %d",
1408  				(int)(*count), destype(config->bDescriptorType),
1409  				(int)(config->bNumInterfaces), (int)(config->iConfiguration),
1410  				(int)(config->bmAttributes), (int)(config->MaxPower));
1411  	append(buf, tmp, off, len);
1412  
1413  	for (i = 0; i < (int)(config->bNumInterfaces); i++) {
1414  		for (j = 0; j < config->interface[i].num_altsetting; j++) {
1415  			idesc = &(config->interface[i].altsetting[j]);
1416  
1417  			snprintf(tmp, sizeof(tmp), EOL "     _dev %d: Interface Descriptor %d:" EOL
1418  					"\tDescriptorType: %s" EOL "\tInterfaceNumber: %d" EOL
1419  					"\tNumEndpoints: %d" EOL "\tInterfaceClass: %d" EOL
1420  					"\tInterfaceSubClass: %d" EOL "\tInterfaceProtocol: %d",
1421  						(int)(*count), j, destype(idesc->bDescriptorType),
1422  						(int)(idesc->bInterfaceNumber),
1423  						(int)(idesc->bNumEndpoints),
1424  						(int)(idesc->bInterfaceClass),
1425  						(int)(idesc->bInterfaceSubClass),
1426  						(int)(idesc->bInterfaceProtocol));
1427  			append(buf, tmp, off, len);
1428  
1429  			for (k = 0; k < (int)(idesc->bNumEndpoints); k++) {
1430  				epdesc = &(idesc->endpoint[k]);
1431  
1432  				snprintf(tmp, sizeof(tmp), EOL "     __dev %d: Interface %d Endpoint %d:" EOL
1433  						"\tDescriptorType: %s" EOL
1434  						"\tEndpointAddress: %s0x%x" EOL
1435  						"\tAttributes: %s" EOL "\tMaxPacketSize: %d" EOL
1436  						"\tInterval: %d" EOL "\tRefresh: %d",
1437  							(int)(*count), (int)(idesc->bInterfaceNumber), k,
1438  							destype(epdesc->bDescriptorType),
1439  							epdir(epdesc->bEndpointAddress),
1440  							(int)(epdesc->bEndpointAddress),
1441  							epatt(epdesc->bmAttributes),
1442  							epdesc->wMaxPacketSize,
1443  							(int)(epdesc->bInterval),
1444  							(int)(epdesc->bRefresh));
1445  				append(buf, tmp, off, len);
1446  			}
1447  		}
1448  	}
1449  
1450  	libusb_free_config_descriptor(config);
1451  	config = NULL;
1452  
1453  	err = libusb_get_string_descriptor_ascii(handle, desc.iSerialNumber, ser, STRBUFLEN);
1454  	if (err < 0)
1455  		snprintf((char *)ser, sizeof(ser), "** err:(%d) %s", err, libusb_error_name(err));
1456  
1457  	snprintf(tmp, sizeof(tmp), EOL "     dev %d: More Info:" EOL "\tManufacturer: '%s'" EOL
1458  			"\tProduct: '%s'" EOL "\tSerial '%s'",
1459  				(int)(*count), man, prod, ser);
1460  	append(buf, tmp, off, len);
1461  
1462  	libusb_close(handle);
1463  }
1464  
1465  // Function to dump all USB devices
1466  void usb_all(int level)
1467  {
1468  	libusb_device **list;
1469  	ssize_t count, i, j;
1470  	char *buf;
1471  	size_t len, off;
1472  
1473  	count = libusb_get_device_list(NULL, &list);
1474  	if (count < 0) {
1475  		applog(LOG_ERR, "USB all: failed, err:(%d) %s", (int)count, libusb_error_name((int)count));
1476  		return;
1477  	}
1478  
1479  	if (count == 0)
1480  		applog(LOG_WARNING, "USB all: found no devices");
1481  	else
1482  	{
1483  		len = 10000;
1484  		buf = malloc(len+1);
1485  		if (unlikely(!buf))
1486  			quit(1, "USB failed to malloc buf in usb_all");
1487  
1488  		sprintf(buf, "USB all: found %d devices", (int)count);
1489  		off = strlen(buf);
1490  
1491  		if (!opt_usb_list_all)
1492  			append(&buf, " - listing known devices", &off, &len);
1493  
1494  		j = -1;
1495  		for (i = 0; i < count; i++)
1496  			usb_full(&j, list[i], &buf, &off, &len, level);
1497  
1498  		_applog(LOG_WARNING, buf, false);
1499  
1500  		free(buf);
1501  
1502  		if (j == -1)
1503  			applog(LOG_WARNING, "No known USB devices");
1504  		else
1505  			applog(LOG_WARNING, "%d %sUSB devices",
1506  				(int)(++j), opt_usb_list_all ? BLANK : "known ");
1507  
1508  	}
1509  
1510  	libusb_free_device_list(list, 1);
1511  }
1512  
1513  static void cgusb_check_init()
1514  {
1515  	mutex_lock(&cgusb_lock);
1516  
1517  	if (stats_initialised == false) {
1518  		// N.B. environment LIBUSB_DEBUG also sets libusb_set_debug()
1519  		if (opt_usbdump >= 0) {
1520  			libusb_set_debug(NULL, opt_usbdump);
1521  			usb_all(opt_usbdump);
1522  		}
1523  		stats_initialised = true;
1524  	}
1525  
1526  	mutex_unlock(&cgusb_lock);
1527  }
1528  
1529  const char *usb_cmdname(enum usb_cmds cmd)
1530  {
1531  	cgusb_check_init();
1532  
1533  	return usb_commands[cmd];
1534  }
1535  
1536  void usb_applog(struct cgpu_info *cgpu, enum usb_cmds cmd, char *msg, int amount, int err)
1537  {
1538  	if (msg && !*msg)
1539  		msg = NULL;
1540  
1541  	if (!msg && amount == 0 && err == LIBUSB_SUCCESS)
1542  		msg = (char *)nodatareturned;
1543  
1544          applog(LOG_ERR, "%s%i: %s failed%s%s (err=%d amt=%d)",
1545                          cgpu->drv->name, cgpu->device_id,
1546                          usb_cmdname(cmd),
1547                          msg ? space : BLANK, msg ? msg : BLANK,
1548                          err, amount);
1549  }
1550  
1551  #ifdef WIN32
1552  static void in_use_store_ress(uint8_t bus_number, uint8_t device_address, void *resource1, void *resource2)
1553  {
1554  	struct usb_in_use_list *in_use_tmp;
1555  	bool found = false, empty = true;
1556  
1557  	mutex_lock(&cgusb_lock);
1558  	in_use_tmp = in_use_head;
1559  	while (in_use_tmp) {
1560  		if (in_use_tmp->in_use.bus_number == (int)bus_number &&
1561  			in_use_tmp->in_use.device_address == (int)device_address) {
1562  			found = true;
1563  
1564  			if (in_use_tmp->in_use.resource1)
1565  				empty = false;
1566  			in_use_tmp->in_use.resource1 = resource1;
1567  
1568  			if (in_use_tmp->in_use.resource2)
1569  				empty = false;
1570  			in_use_tmp->in_use.resource2 = resource2;
1571  
1572  			break;
1573  		}
1574  		in_use_tmp = in_use_tmp->next;
1575  	}
1576  	mutex_unlock(&cgusb_lock);
1577  
1578  	if (found == false)
1579  		applog(LOG_ERR, "FAIL: USB store_ress not found (%d:%d)",
1580  				(int)bus_number, (int)device_address);
1581  
1582  	if (empty == false)
1583  		applog(LOG_ERR, "FAIL: USB store_ress not empty (%d:%d)",
1584  				(int)bus_number, (int)device_address);
1585  }
1586  
1587  static void in_use_get_ress(uint8_t bus_number, uint8_t device_address, void **resource1, void **resource2)
1588  {
1589  	struct usb_in_use_list *in_use_tmp;
1590  	bool found = false, empty = false;
1591  
1592  	mutex_lock(&cgusb_lock);
1593  	in_use_tmp = in_use_head;
1594  	while (in_use_tmp) {
1595  		if (in_use_tmp->in_use.bus_number == (int)bus_number &&
1596  			in_use_tmp->in_use.device_address == (int)device_address) {
1597  			found = true;
1598  
1599  			if (!in_use_tmp->in_use.resource1)
1600  				empty = true;
1601  			*resource1 = in_use_tmp->in_use.resource1;
1602  			in_use_tmp->in_use.resource1 = NULL;
1603  
1604  			if (!in_use_tmp->in_use.resource2)
1605  				empty = true;
1606  			*resource2 = in_use_tmp->in_use.resource2;
1607  			in_use_tmp->in_use.resource2 = NULL;
1608  
1609  			break;
1610  		}
1611  		in_use_tmp = in_use_tmp->next;
1612  	}
1613  	mutex_unlock(&cgusb_lock);
1614  
1615  	if (found == false)
1616  		applog(LOG_ERR, "FAIL: USB get_lock not found (%d:%d)",
1617  				(int)bus_number, (int)device_address);
1618  
1619  	if (empty == true)
1620  		applog(LOG_ERR, "FAIL: USB get_lock empty (%d:%d)",
1621  				(int)bus_number, (int)device_address);
1622  }
1623  #else
1624  
1625  static void in_use_store_fd(uint8_t bus_number, uint8_t device_address, int fd)
1626  {
1627  	struct usb_in_use_list *in_use_tmp;
1628  	bool found = false;
1629  
1630  	mutex_lock(&cgusb_lock);
1631  	in_use_tmp = in_use_head;
1632  	while (in_use_tmp) {
1633  		if (in_use_tmp->in_use.bus_number == (int)bus_number &&
1634  			in_use_tmp->in_use.device_address == (int)device_address) {
1635  			found = true;
1636  			in_use_tmp->in_use.fd = fd;
1637  			break;
1638  		}
1639  		in_use_tmp = in_use_tmp->next;
1640  	}
1641  	mutex_unlock(&cgusb_lock);
1642  
1643  	if (found == false) {
1644  		applog(LOG_ERR, "FAIL: USB store_fd not found (%d:%d)",
1645  				(int)bus_number, (int)device_address);
1646  	}
1647  }
1648  
1649  static int in_use_get_fd(uint8_t bus_number, uint8_t device_address)
1650  {
1651  	struct usb_in_use_list *in_use_tmp;
1652  	bool found = false;
1653  	int fd = -1;
1654  
1655  	mutex_lock(&cgusb_lock);
1656  	in_use_tmp = in_use_head;
1657  	while (in_use_tmp) {
1658  		if (in_use_tmp->in_use.bus_number == (int)bus_number &&
1659  		    in_use_tmp->in_use.device_address == (int)device_address) {
1660  			found = true;
1661  			fd = in_use_tmp->in_use.fd;
1662  			break;
1663  		}
1664  		in_use_tmp = in_use_tmp->next;
1665  	}
1666  	mutex_unlock(&cgusb_lock);
1667  
1668  	if (found == false) {
1669  		applog(LOG_ERR, "FAIL: USB get_lock not found (%d:%d)",
1670  				(int)bus_number, (int)device_address);
1671  	}
1672  	return fd;
1673  }
1674  #endif
1675  
1676  static bool _in_use(struct usb_in_use_list *head, uint8_t bus_number,
1677  		    uint8_t device_address)
1678  {
1679  	struct usb_in_use_list *in_use_tmp;
1680  	bool ret = false;
1681  
1682  	in_use_tmp = head;
1683  	while (in_use_tmp) {
1684  		if (in_use_tmp->in_use.bus_number == (int)bus_number &&
1685  		    in_use_tmp->in_use.device_address == (int)device_address) {
1686  			ret = true;
1687  			break;
1688  		}
1689  		in_use_tmp = in_use_tmp->next;
1690  		if (in_use_tmp == head)
1691  			break;
1692  	}
1693  	return ret;
1694  }
1695  
1696  static bool __is_in_use(uint8_t bus_number, uint8_t device_address)
1697  {
1698  	if (_in_use(in_use_head, bus_number, device_address))
1699  		return true;
1700  	if (_in_use(blacklist_head, bus_number, device_address))
1701  		return true;
1702  	return false;
1703  }
1704  
1705  static bool is_in_use_bd(uint8_t bus_number, uint8_t device_address)
1706  {
1707  	bool ret;
1708  
1709  	mutex_lock(&cgusb_lock);
1710  	ret = __is_in_use(bus_number, device_address);
1711  	mutex_unlock(&cgusb_lock);
1712  	return ret;
1713  }
1714  
1715  static bool is_in_use(libusb_device *dev)
1716  {
1717  	return is_in_use_bd(libusb_get_bus_number(dev), libusb_get_device_address(dev));
1718  }
1719  
1720  static bool how_in_use(uint8_t bus_number, uint8_t device_address, bool *blacklisted)
1721  {
1722  	bool ret;
1723  	mutex_lock(&cgusb_lock);
1724  	ret = _in_use(in_use_head, bus_number, device_address);
1725  	if (!ret) {
1726  		if (_in_use(blacklist_head, bus_number, device_address))
1727  			*blacklisted = true;
1728  	}
1729  	mutex_unlock(&cgusb_lock);
1730  
1731  	return ret;
1732  }
1733  
1734  void usb_list(void)
1735  {
1736  	struct libusb_device_descriptor desc;
1737  	struct libusb_device_handle *handle;
1738  	uint8_t bus_number;
1739  	uint8_t device_address;
1740  	libusb_device **list;
1741  	ssize_t count, i, j;
1742  	int err, total = 0;
1743  
1744  	count = libusb_get_device_list(NULL, &list);
1745  	if (count < 0) {
1746  		applog(LOG_ERR, "USB list: failed, err:(%d) %s", (int)count, libusb_error_name((int)count));
1747  		return;
1748  	}
1749  	if (count == 0) {
1750  		applog(LOG_WARNING, "USB list: found no devices");
1751  		return;
1752  	}
1753  	for (i = 0; i < count; i++) {
1754  		bool known = false, blacklisted = false, active;
1755  		unsigned char manuf[256], prod[256];
1756  		libusb_device *dev = list[i];
1757  
1758  		err = libusb_get_device_descriptor(dev, &desc);
1759  		if (err) {
1760  			applog(LOG_WARNING, "USB list: Failed to get descriptor %d", (int)i);
1761  			break;
1762  		}
1763  
1764  		bus_number = libusb_get_bus_number(dev);
1765  		device_address = libusb_get_device_address(dev);
1766  
1767  		for (j = 0; find_dev[j].drv != DRIVER_MAX; j++) {
1768  			if ((find_dev[j].idVendor == desc.idVendor) &&
1769  			    (find_dev[j].idProduct == desc.idProduct)) {
1770  				known = true;
1771  				break;
1772  			}
1773  		}
1774  		if (!known)
1775  			continue;
1776  
1777  		err = libusb_open(dev, &handle);
1778  		if (err) {
1779  			applog(LOG_WARNING, "USB list: Failed to open %d", (int)i);
1780  			break;
1781  		}
1782  		libusb_get_string_descriptor_ascii(handle, desc.iManufacturer, manuf, 255);
1783  		libusb_get_string_descriptor_ascii(handle, desc.iProduct, prod, 255);
1784  		total++;
1785  		active = how_in_use(bus_number, device_address, &blacklisted);
1786  		simplelog(LOG_WARNING, "Bus %u Device %u ID: %04x:%04x %s %s %sactive %s",
1787  		       bus_number, device_address, desc.idVendor, desc.idProduct,
1788  		       manuf, prod, active ? "" : "in", blacklisted ? "blacklisted" : "");
1789  	}
1790  	libusb_free_device_list(list, 1);
1791  	simplelog(LOG_WARNING, "%d total known USB device%s", total, total > 1 ? "s": "");
1792  }
1793  
1794  static void add_in_use(uint8_t bus_number, uint8_t device_address, bool blacklist)
1795  {
1796  	struct usb_in_use_list *in_use_tmp, **head;
1797  	bool found = false;
1798  
1799  	mutex_lock(&cgusb_lock);
1800  	if (unlikely(!blacklist && __is_in_use(bus_number, device_address))) {
1801  		found = true;
1802  		goto nofway;
1803  	}
1804  	if (blacklist)
1805  		head = &blacklist_head;
1806  	else
1807  		head = &in_use_head;
1808  
1809  	in_use_tmp = cgcalloc(1, sizeof(*in_use_tmp));
1810  	in_use_tmp->in_use.bus_number = (int)bus_number;
1811  	in_use_tmp->in_use.device_address = (int)device_address;
1812  	in_use_tmp->next = in_use_head;
1813  	if (*head)
1814  		(*head)->prev = in_use_tmp;
1815  	*head = in_use_tmp;
1816  nofway:
1817  	mutex_unlock(&cgusb_lock);
1818  
1819  	if (found)
1820  		applog(LOG_ERR, "FAIL: USB add already in use (%d:%d)",
1821  				(int)bus_number, (int)device_address);
1822  }
1823  
1824  static void __remove_in_use(uint8_t bus_number, uint8_t device_address, bool blacklist)
1825  {
1826  	struct usb_in_use_list *in_use_tmp, **head;
1827  	bool found = false;
1828  
1829  	mutex_lock(&cgusb_lock);
1830  	if (blacklist)
1831  		head = &blacklist_head;
1832  	else
1833  		head = &in_use_head;
1834  
1835  	in_use_tmp = *head;
1836  	while (in_use_tmp) {
1837  		if (in_use_tmp->in_use.bus_number == (int)bus_number &&
1838  		    in_use_tmp->in_use.device_address == (int)device_address) {
1839  			found = true;
1840  			if (in_use_tmp == *head) {
1841  				*head = (*head)->next;
1842  				if (*head)
1843  					(*head)->prev = NULL;
1844  			} else {
1845  				in_use_tmp->prev->next = in_use_tmp->next;
1846  				if (in_use_tmp->next)
1847  					in_use_tmp->next->prev = in_use_tmp->prev;
1848  			}
1849  			free(in_use_tmp);
1850  			break;
1851  		}
1852  		in_use_tmp = in_use_tmp->next;
1853  		if (in_use_tmp == *head)
1854  			break;
1855  	}
1856  
1857  	mutex_unlock(&cgusb_lock);
1858  
1859  	if (!found) {
1860  		applog(LOG_ERR, "FAIL: USB remove not already in use (%d:%d)",
1861  				(int)bus_number, (int)device_address);
1862  	}
1863  }
1864  
1865  static void remove_in_use(uint8_t bus_number, uint8_t device_address)
1866  {
1867  	__remove_in_use(bus_number, device_address, false);
1868  }
1869  
1870  static bool cgminer_usb_lock_bd(struct device_drv *drv, uint8_t bus_number, uint8_t device_address)
1871  {
1872  	struct resource_work *res_work;
1873  	bool ret;
1874  
1875  	applog(LOG_DEBUG, "USB lock %s %d-%d", drv->dname, (int)bus_number, (int)device_address);
1876  
1877  	res_work = cgcalloc(1, sizeof(*res_work));
1878  	res_work->lock = true;
1879  	res_work->dname = (const char *)(drv->dname);
1880  	res_work->bus_number = bus_number;
1881  	res_work->device_address = device_address;
1882  
1883  	mutex_lock(&cgusbres_lock);
1884  	res_work->next = res_work_head;
1885  	res_work_head = res_work;
1886  	mutex_unlock(&cgusbres_lock);
1887  
1888  	cgsem_post(&usb_resource_sem);
1889  
1890  	// TODO: add a timeout fail - restart the resource thread?
1891  	while (true) {
1892  		cgsleep_ms(50);
1893  
1894  		mutex_lock(&cgusbres_lock);
1895  		if (res_reply_head) {
1896  			struct resource_reply *res_reply_prev = NULL;
1897  			struct resource_reply *res_reply = res_reply_head;
1898  			while (res_reply) {
1899  				if (res_reply->bus_number == bus_number &&
1900  					res_reply->device_address == device_address) {
1901  
1902  					if (res_reply_prev)
1903  						res_reply_prev->next = res_reply->next;
1904  					else
1905  						res_reply_head = res_reply->next;
1906  
1907  					mutex_unlock(&cgusbres_lock);
1908  
1909  					ret = res_reply->got;
1910  
1911  					free(res_reply);
1912  
1913  					return ret;
1914  				}
1915  				res_reply_prev = res_reply;
1916  				res_reply = res_reply->next;
1917  			}
1918  		}
1919  		mutex_unlock(&cgusbres_lock);
1920  	}
1921  }
1922  
1923  static bool cgminer_usb_lock(struct device_drv *drv, libusb_device *dev)
1924  {
1925  	return cgminer_usb_lock_bd(drv, libusb_get_bus_number(dev), libusb_get_device_address(dev));
1926  }
1927  
1928  static void cgminer_usb_unlock_bd(struct device_drv *drv, uint8_t bus_number, uint8_t device_address)
1929  {
1930  	struct resource_work *res_work;
1931  
1932  	applog(LOG_DEBUG, "USB unlock %s %d-%d", drv->dname, (int)bus_number, (int)device_address);
1933  
1934  	res_work = cgcalloc(1, sizeof(*res_work));
1935  	res_work->lock = false;
1936  	res_work->dname = (const char *)(drv->dname);
1937  	res_work->bus_number = bus_number;
1938  	res_work->device_address = device_address;
1939  
1940  	mutex_lock(&cgusbres_lock);
1941  	res_work->next = res_work_head;
1942  	res_work_head = res_work;
1943  	mutex_unlock(&cgusbres_lock);
1944  
1945  	cgsem_post(&usb_resource_sem);
1946  
1947  	return;
1948  }
1949  
1950  static void cgminer_usb_unlock(struct device_drv *drv, libusb_device *dev)
1951  {
1952  	cgminer_usb_unlock_bd(drv, libusb_get_bus_number(dev), libusb_get_device_address(dev));
1953  }
1954  
1955  static struct cg_usb_device *free_cgusb(struct cg_usb_device *cgusb)
1956  {
1957  	applog(LOG_DEBUG, "USB free %s", cgusb->found->name);
1958  
1959  	if (cgusb->serial_string && cgusb->serial_string != BLANK)
1960  		free(cgusb->serial_string);
1961  
1962  	if (cgusb->manuf_string && cgusb->manuf_string != BLANK)
1963  		free(cgusb->manuf_string);
1964  
1965  	if (cgusb->prod_string && cgusb->prod_string != BLANK)
1966  		free(cgusb->prod_string);
1967  
1968  	if (cgusb->descriptor)
1969  		free(cgusb->descriptor);
1970  
1971  	free(cgusb->found);
1972  
1973  	free(cgusb);
1974  
1975  	return NULL;
1976  }
1977  
1978  static void _usb_uninit(struct cgpu_info *cgpu)
1979  {
1980  	int ifinfo;
1981  
1982  	// May have happened already during a failed initialisation
1983  	//  if release_cgpu() was called due to a USB NODEV(err)
1984  	if (!cgpu->usbdev)
1985  		return;
1986  
1987  	applog(LOG_DEBUG, "USB uninit %s%i",
1988  			cgpu->drv->name, cgpu->device_id);
1989  
1990  	if (cgpu->usbdev->handle) {
1991  		for (ifinfo = cgpu->usbdev->found->intinfo_count - 1; ifinfo >= 0; ifinfo--) {
1992  			libusb_release_interface(cgpu->usbdev->handle,
1993  						 THISIF(cgpu->usbdev->found, ifinfo));
1994  #ifdef LINUX
1995  			libusb_attach_kernel_driver(cgpu->usbdev->handle, THISIF(cgpu->usbdev->found, ifinfo));
1996  #endif
1997  		}
1998  		cg_wlock(&cgusb_fd_lock);
1999  		libusb_close(cgpu->usbdev->handle);
2000  		cgpu->usbdev->handle = NULL;
2001  		cg_wunlock(&cgusb_fd_lock);
2002  	}
2003  	cgpu->usbdev = free_cgusb(cgpu->usbdev);
2004  }
2005  
2006  void usb_uninit(struct cgpu_info *cgpu)
2007  {
2008  	int pstate;
2009  
2010  	DEVWLOCK(cgpu, pstate);
2011  
2012  	_usb_uninit(cgpu);
2013  
2014  	DEVWUNLOCK(cgpu, pstate);
2015  }
2016  
2017  /* We have dropped the read devlock before entering this function but we pick
2018   * up the write lock to prevent any attempts to work on dereferenced code once
2019   * the nodev flag has been set. */
2020  static bool __release_cgpu(struct cgpu_info *cgpu)
2021  {
2022  	struct cg_usb_device *cgusb = cgpu->usbdev;
2023  	bool initted = cgpu->usbinfo.initialised;
2024  	struct cgpu_info *lookcgpu;
2025  	int i;
2026  
2027  	// It has already been done
2028  	if (cgpu->usbinfo.nodev)
2029  		return false;
2030  
2031  	applog(LOG_DEBUG, "USB release %s%i",
2032  			cgpu->drv->name, cgpu->device_id);
2033  
2034  	if (initted) {
2035  		zombie_devs++;
2036  		total_count--;
2037  		drv_count[cgpu->drv->drv_id].count--;
2038  	}
2039  
2040  	cgpu->usbinfo.nodev = true;
2041  	cgpu->usbinfo.nodev_count++;
2042  	cgtime(&cgpu->usbinfo.last_nodev);
2043  
2044  	// Any devices sharing the same USB device should be marked also
2045  	for (i = 0; i < total_devices; i++) {
2046  		lookcgpu = get_devices(i);
2047  		if (lookcgpu != cgpu && lookcgpu->usbdev == cgusb) {
2048  			if (initted) {
2049  				total_count--;
2050  				drv_count[lookcgpu->drv->drv_id].count--;
2051  			}
2052  
2053  			lookcgpu->usbinfo.nodev = true;
2054  			lookcgpu->usbinfo.nodev_count++;
2055  			cg_memcpy(&(lookcgpu->usbinfo.last_nodev),
2056  				&(cgpu->usbinfo.last_nodev), sizeof(struct timeval));
2057  			lookcgpu->usbdev = NULL;
2058  		}
2059  	}
2060  
2061  	_usb_uninit(cgpu);
2062  	return true;
2063  }
2064  
2065  static void release_cgpu(struct cgpu_info *cgpu)
2066  {
2067  	if (__release_cgpu(cgpu))
2068  		cgminer_usb_unlock_bd(cgpu->drv, cgpu->usbinfo.bus_number, cgpu->usbinfo.device_address);
2069  }
2070  
2071  void blacklist_cgpu(struct cgpu_info *cgpu)
2072  {
2073  	if (cgpu->blacklisted) {
2074  		applog(LOG_WARNING, "Device already blacklisted");
2075  		return;
2076  	}
2077  	cgpu->blacklisted = true;
2078  	add_in_use(cgpu->usbinfo.bus_number, cgpu->usbinfo.device_address, true);
2079  	if (__release_cgpu(cgpu))
2080  		cgminer_usb_unlock_bd(cgpu->drv, cgpu->usbinfo.bus_number, cgpu->usbinfo.device_address);
2081  }
2082  
2083  void whitelist_cgpu(struct cgpu_info *cgpu)
2084  {
2085  	if (!cgpu->blacklisted) {
2086  		applog(LOG_WARNING, "Device not blacklisted");
2087  		return;
2088  	}
2089  	__remove_in_use(cgpu->usbinfo.bus_number, cgpu->usbinfo.device_address, true);
2090  	cgpu->blacklisted = false;
2091  }
2092  
2093  /*
2094   * Force a NODEV on a device so it goes back to hotplug
2095   */
2096  void usb_nodev(struct cgpu_info *cgpu)
2097  {
2098  	int pstate;
2099  
2100  	DEVWLOCK(cgpu, pstate);
2101  
2102  	release_cgpu(cgpu);
2103  
2104  	DEVWUNLOCK(cgpu, pstate);
2105  }
2106  
2107  /*
2108   * Use the same usbdev thus locking is across all related devices
2109   */
2110  struct cgpu_info *usb_copy_cgpu(struct cgpu_info *orig)
2111  {
2112  	struct cgpu_info *copy;
2113  	int pstate;
2114  
2115  	DEVWLOCK(orig, pstate);
2116  
2117  	copy = cgcalloc(1, sizeof(*copy));
2118  
2119  	copy->name = orig->name;
2120  	copy->drv = copy_drv(orig->drv);
2121  	copy->deven = orig->deven;
2122  	copy->threads = orig->threads;
2123  
2124  	copy->usbdev = orig->usbdev;
2125  
2126  	cg_memcpy(&(copy->usbinfo), &(orig->usbinfo), sizeof(copy->usbinfo));
2127  
2128  	copy->usbinfo.nodev = (copy->usbdev == NULL);
2129  
2130  	DEVWUNLOCK(orig, pstate);
2131  
2132  	return copy;
2133  }
2134  
2135  struct cgpu_info *usb_alloc_cgpu(struct device_drv *drv, int threads)
2136  {
2137  	struct cgpu_info *cgpu = cgcalloc(1, sizeof(*cgpu));
2138  
2139  	cgpu->drv = drv;
2140  	cgpu->deven = DEV_ENABLED;
2141  	cgpu->threads = threads;
2142  
2143  	cgpu->usbinfo.nodev = true;
2144  
2145  	cglock_init(&cgpu->usbinfo.devlock);
2146  
2147  	return cgpu;
2148  }
2149  
2150  struct cgpu_info *usb_free_cgpu(struct cgpu_info *cgpu)
2151  {
2152  	if (cgpu->drv->copy)
2153  		free(cgpu->drv);
2154  
2155  	free(cgpu->device_path);
2156  
2157  	free(cgpu);
2158  
2159  	return NULL;
2160  }
2161  
2162  #define USB_INIT_FAIL 0
2163  #define USB_INIT_OK 1
2164  #define USB_INIT_IGNORE 2
2165  
2166  static int _usb_init(struct cgpu_info *cgpu, struct libusb_device *dev, struct usb_find_devices *found)
2167  {
2168  	unsigned char man[STRBUFLEN+1], prod[STRBUFLEN+1];
2169  	struct cg_usb_device *cgusb = NULL;
2170  	struct libusb_config_descriptor *config = NULL;
2171  	const struct libusb_interface_descriptor *idesc;
2172  	const struct libusb_endpoint_descriptor *epdesc;
2173  	unsigned char strbuf[STRBUFLEN+1];
2174  	char devpath[32];
2175  	char devstr[STRBUFLEN+1];
2176  	int err, ifinfo, epinfo, alt, epnum, pstate;
2177  	int bad = USB_INIT_FAIL;
2178  	int cfg, claimed = 0, i;
2179  
2180  	DEVWLOCK(cgpu, pstate);
2181  
2182  	cgpu->usbinfo.bus_number = libusb_get_bus_number(dev);
2183  	cgpu->usbinfo.device_address = libusb_get_device_address(dev);
2184  
2185  	if (found->intinfo_count > 1) {
2186  		snprintf(devpath, sizeof(devpath), "%d:%d-i%d",
2187  			(int)(cgpu->usbinfo.bus_number),
2188  			(int)(cgpu->usbinfo.device_address),
2189  			THISIF(found, 0));
2190  	} else {
2191  		snprintf(devpath, sizeof(devpath), "%d:%d",
2192  			(int)(cgpu->usbinfo.bus_number),
2193  			(int)(cgpu->usbinfo.device_address));
2194  	}
2195  
2196  	cgpu->device_path = strdup(devpath);
2197  
2198  	snprintf(devstr, sizeof(devstr), "- %s device %s", found->name, devpath);
2199  
2200  	cgusb = cgcalloc(1, sizeof(*cgusb));
2201  	cgusb->found = found;
2202  
2203  	if (found->idVendor == IDVENDOR_FTDI)
2204  		cgusb->usb_type = USB_TYPE_FTDI;
2205  
2206  	cgusb->ident = found->ident;
2207  
2208  	cgusb->descriptor = cgcalloc(1, sizeof(*(cgusb->descriptor)));
2209  
2210  	err = libusb_get_device_descriptor(dev, cgusb->descriptor);
2211  	if (err) {
2212  		applog(LOG_DEBUG,
2213  			"USB init failed to get descriptor, err %d %s",
2214  			err, devstr);
2215  		goto dame;
2216  	}
2217  
2218  	cg_wlock(&cgusb_fd_lock);
2219  	err = libusb_open(dev, &(cgusb->handle));
2220  	cg_wunlock(&cgusb_fd_lock);
2221  	if (err) {
2222  		switch (err) {
2223  			case LIBUSB_ERROR_ACCESS:
2224  				applog(LOG_ERR,
2225  					"USB init, open device failed, err %d, "
2226  					"you don't have privilege to access %s",
2227  					err, devstr);
2228  				applog(LOG_ERR, "See README file included for help");
2229  				break;
2230  #ifdef WIN32
2231  			// Windows specific message
2232  			case LIBUSB_ERROR_NOT_SUPPORTED:
2233  				applog(LOG_ERR, "USB init, open device failed, err %d, ", err);
2234  				applog(LOG_ERR, "You need to install a WinUSB driver for %s", devstr);
2235  				applog(LOG_ERR, "And associate %s with WinUSB using zadig", devstr);
2236  				applog(LOG_ERR, "See README.txt file included for help");
2237  				break;
2238  #endif
2239  			default:
2240  				applog(LOG_DEBUG,
2241  					"USB init, open failed, err %d %s",
2242  					err, devstr);
2243  		}
2244  		goto dame;
2245  	}
2246  
2247  #ifdef LINUX
2248  	for (ifinfo = 0; ifinfo < found->intinfo_count; ifinfo++) {
2249  		if (libusb_kernel_driver_active(cgusb->handle, THISIF(found, ifinfo)) == 1) {
2250  			applog(LOG_DEBUG, "USB init, kernel attached ... %s", devstr);
2251  			err = libusb_detach_kernel_driver(cgusb->handle, THISIF(found, ifinfo));
2252  			if (err == 0) {
2253  				applog(LOG_DEBUG,
2254  					"USB init, kernel detached ifinfo %d interface %d"
2255  					" successfully %s",
2256  					ifinfo, THISIF(found, ifinfo), devstr);
2257  			} else {
2258  				applog(LOG_WARNING,
2259  					"USB init, kernel detach ifinfo %d interface %d failed,"
2260  					" err %d in use? %s",
2261  					ifinfo, THISIF(found, ifinfo), err, devstr);
2262  				goto nokernel;
2263  			}
2264  		}
2265  	}
2266  #endif
2267  
2268  	err = libusb_get_string_descriptor_ascii(cgusb->handle,
2269  							cgusb->descriptor->iManufacturer,
2270  							man, STRBUFLEN);
2271  	if (err < 0) {
2272  		applog(LOG_DEBUG,
2273  			"USB init, failed to get iManufacturer, err %d %s",
2274  			err, devstr);
2275  		goto cldame;
2276  	}
2277  	if (found->iManufacturer) {
2278  		if (strcmp((char *)man, found->iManufacturer)) {
2279  			applog(LOG_DEBUG, "USB init, iManufacturer mismatch %s",
2280  			       devstr);
2281  			applog(LOG_DEBUG, "Found %s vs %s", man, found->iManufacturer);
2282  			bad = USB_INIT_IGNORE;
2283  			goto cldame;
2284  		}
2285  	} else {
2286  		for (i = 0; find_dev[i].drv != DRIVER_MAX; i++) {
2287  			const char *iManufacturer = find_dev[i].iManufacturer;
2288  			/* If other drivers has an iManufacturer set that match,
2289  			 * don't try to claim this device. */
2290  
2291  			if (!iManufacturer)
2292  				continue;
2293  			/* If the alternative driver also has an iProduct, only
2294  			 * use that for comparison. */
2295  			if (find_dev[i].iProduct)
2296  				continue;
2297  			if (!strcmp((char *)man, iManufacturer)) {
2298  				applog(LOG_DEBUG, "USB init, alternative iManufacturer match %s",
2299  				       devstr);
2300  				applog(LOG_DEBUG, "Found %s", iManufacturer);
2301  				bad = USB_INIT_IGNORE;
2302  				goto cldame;
2303  			}
2304  		}
2305  	}
2306  
2307  	err = libusb_get_string_descriptor_ascii(cgusb->handle,
2308  							cgusb->descriptor->iProduct,
2309  							prod, STRBUFLEN);
2310  	if (err < 0) {
2311  		applog(LOG_DEBUG,
2312  			"USB init, failed to get iProduct, err %d %s",
2313  			err, devstr);
2314  		goto cldame;
2315  	}
2316  	if (found->iProduct) {
2317  		if (strcasecmp((char *)prod, found->iProduct)) {
2318  			applog(LOG_DEBUG, "USB init, iProduct mismatch %s",
2319  			       devstr);
2320  			applog(LOG_DEBUG, "Found %s vs %s", prod, found->iProduct);
2321  			bad = USB_INIT_IGNORE;
2322  			goto cldame;
2323  		}
2324  	} else {
2325  		for (i = 0; find_dev[i].drv != DRIVER_MAX; i++) {
2326  			const char *iProduct = find_dev[i].iProduct;
2327  			/* Do same for iProduct as iManufacturer above */
2328  
2329  			if (!iProduct)
2330  				continue;
2331  			if (!strcasecmp((char *)prod, iProduct)) {
2332  				applog(LOG_DEBUG, "USB init, alternative iProduct match %s",
2333  				       devstr);
2334  				applog(LOG_DEBUG, "Found %s", iProduct);
2335  				bad = USB_INIT_IGNORE;
2336  				goto cldame;
2337  			}
2338  		}
2339  	}
2340  
2341  	cfg = -1;
2342  	err = libusb_get_configuration(cgusb->handle, &cfg);
2343  	if (err)
2344  		cfg = -1;
2345  
2346  	// Try to set it if we can't read it or it's different
2347  	if (cfg != found->config) {
2348  		err = libusb_set_configuration(cgusb->handle, found->config);
2349  		if (err) {
2350  			switch(err) {
2351  				case LIBUSB_ERROR_BUSY:
2352  					applog(LOG_WARNING,
2353  						"USB init, set config %d in use %s",
2354  						found->config, devstr);
2355  					break;
2356  				default:
2357  					applog(LOG_DEBUG,
2358  						"USB init, failed to set config to %d, err %d %s",
2359  						found->config, err, devstr);
2360  			}
2361  			goto cldame;
2362  		}
2363  	}
2364  
2365  	err = libusb_get_active_config_descriptor(dev, &config);
2366  	if (err) {
2367  		applog(LOG_DEBUG,
2368  			"USB init, failed to get config descriptor, err %d %s",
2369  			err, devstr);
2370  		goto cldame;
2371  	}
2372  
2373  	int imax = -1;
2374  	for (ifinfo = 0; ifinfo < found->intinfo_count; ifinfo++)
2375  		if (found->intinfos[ifinfo].interface > imax)
2376  			imax = found->intinfos[ifinfo].interface;
2377  
2378  	if ((int)(config->bNumInterfaces) <= imax) {
2379  		applog(LOG_DEBUG, "USB init bNumInterfaces %d <= interface max %d for %s",
2380  		       (int)(config->bNumInterfaces), imax, devstr);
2381  		goto cldame;
2382  	}
2383  
2384  	for (ifinfo = 0; ifinfo < found->intinfo_count; ifinfo++)
2385  		for (epinfo = 0; epinfo < found->intinfos[ifinfo].epinfo_count; epinfo++)
2386  			found->intinfos[ifinfo].epinfos[epinfo].found = false;
2387  
2388  	for (ifinfo = 0; ifinfo < found->intinfo_count; ifinfo++) {
2389  		int interface = found->intinfos[ifinfo].interface;
2390  		for (alt = 0; alt < config->interface[interface].num_altsetting; alt++) {
2391  			idesc = &(config->interface[interface].altsetting[alt]);
2392  			for (epnum = 0; epnum < (int)(idesc->bNumEndpoints); epnum++) {
2393  				struct usb_epinfo *epinfos = found->intinfos[ifinfo].epinfos;
2394  				epdesc = &(idesc->endpoint[epnum]);
2395  				for (epinfo = 0; epinfo < found->intinfos[ifinfo].epinfo_count; epinfo++) {
2396  					if (!epinfos[epinfo].found) {
2397  						if (epdesc->bmAttributes == epinfos[epinfo].att
2398  						&&  epdesc->wMaxPacketSize >= epinfos[epinfo].size
2399  						&&  epdesc->bEndpointAddress == epinfos[epinfo].ep) {
2400  							epinfos[epinfo].found = true;
2401  							epinfos[epinfo].wMaxPacketSize = epdesc->wMaxPacketSize;
2402  							break;
2403  						}
2404  					}
2405  				}
2406  			}
2407  		}
2408  	}
2409  
2410  	for (ifinfo = 0; ifinfo < found->intinfo_count; ifinfo++)
2411  		for (epinfo = 0; epinfo < found->intinfos[ifinfo].epinfo_count; epinfo++)
2412  			if (found->intinfos[ifinfo].epinfos[epinfo].found == false) {
2413  				applog(LOG_DEBUG, "USB init found (%d,%d) == false %s",
2414  				       ifinfo, epinfo, devstr);
2415  				goto cldame;
2416  			}
2417  
2418  	claimed = 0;
2419  	for (ifinfo = 0; ifinfo < found->intinfo_count; ifinfo++) {
2420  		err = libusb_claim_interface(cgusb->handle, THISIF(found, ifinfo));
2421  		if (err == 0)
2422  			claimed++;
2423  		else {
2424  			switch(err) {
2425  				case LIBUSB_ERROR_BUSY:
2426  					applog(LOG_WARNING,
2427  						"USB init, claim ifinfo %d interface %d in use %s",
2428  						ifinfo, THISIF(found, ifinfo), devstr);
2429  					break;
2430  				default:
2431  					applog(LOG_DEBUG,
2432  						"USB init, claim ifinfo %d interface %d failed,"
2433  						" err %d %s",
2434  						ifinfo, THISIF(found, ifinfo), err, devstr);
2435  			}
2436  			goto reldame;
2437  		}
2438  	}
2439  
2440  	cfg = -1;
2441  	err = libusb_get_configuration(cgusb->handle, &cfg);
2442  	if (err)
2443  		cfg = -1;
2444  	if (cfg != found->config) {
2445  		applog(LOG_WARNING,
2446  			"USB init, incorrect config (%d!=%d) after claim of %s",
2447  			cfg, found->config, devstr);
2448  		goto reldame;
2449  	}
2450  
2451  	cgusb->usbver = cgusb->descriptor->bcdUSB;
2452  	if (cgusb->usbver < 0x0200) {
2453  		cgusb->usb11 = true;
2454  		cgusb->tt = true;
2455  	}
2456  
2457  // TODO: allow this with the right version of the libusb include and running library
2458  //	cgusb->speed = libusb_get_device_speed(dev);
2459  
2460  	err = libusb_get_string_descriptor_ascii(cgusb->handle,
2461  				cgusb->descriptor->iProduct, strbuf, STRBUFLEN);
2462  	if (err > 0)
2463  		cgusb->prod_string = strdup((char *)strbuf);
2464  	else
2465  		cgusb->prod_string = (char *)BLANK;
2466  
2467  	err = libusb_get_string_descriptor_ascii(cgusb->handle,
2468  				cgusb->descriptor->iManufacturer, strbuf, STRBUFLEN);
2469  	if (err > 0)
2470  		cgusb->manuf_string = strdup((char *)strbuf);
2471  	else
2472  		cgusb->manuf_string = (char *)BLANK;
2473  
2474  	err = libusb_get_string_descriptor_ascii(cgusb->handle,
2475  				cgusb->descriptor->iSerialNumber, strbuf, STRBUFLEN);
2476  	if (err > 0)
2477  		cgusb->serial_string = strdup((char *)strbuf);
2478  	else
2479  		cgusb->serial_string = (char *)BLANK;
2480  
2481  // TODO: ?
2482  //	cgusb->fwVersion <- for temp1/temp2 decision? or serial? (driver-modminer.c)
2483  //	cgusb->interfaceVersion
2484  
2485  	applog(LOG_DEBUG,
2486  		"USB init %s usbver=%04x prod='%s' manuf='%s' serial='%s'",
2487  		devstr, cgusb->usbver, cgusb->prod_string,
2488  		cgusb->manuf_string, cgusb->serial_string);
2489  
2490  	cgpu->usbdev = cgusb;
2491  	cgpu->usbinfo.nodev = false;
2492  
2493  	libusb_free_config_descriptor(config);
2494  
2495  	// Allow a name change based on the idVendor+idProduct
2496  	// N.B. must be done before calling add_cgpu()
2497  	if (strcasecmp(cgpu->drv->name, found->name)) {
2498  		if (!cgpu->drv->copy)
2499  			cgpu->drv = copy_drv(cgpu->drv);
2500  		cgpu->drv->name = (char *)(found->name);
2501  	}
2502  
2503  	bad = USB_INIT_OK;
2504  	goto out_unlock;
2505  
2506  reldame:
2507  
2508  	ifinfo = claimed;
2509  	while (ifinfo-- > 0)
2510  		libusb_release_interface(cgusb->handle, THISIF(found, ifinfo));
2511  
2512  cldame:
2513  #ifdef LINUX
2514  	libusb_attach_kernel_driver(cgusb->handle, THISIF(found, ifinfo));
2515  
2516  nokernel:
2517  #endif
2518  	cg_wlock(&cgusb_fd_lock);
2519  	libusb_close(cgusb->handle);
2520  	cgusb->handle = NULL;
2521  	cg_wunlock(&cgusb_fd_lock);
2522  
2523  dame:
2524  
2525  	if (config)
2526  		libusb_free_config_descriptor(config);
2527  
2528  	cgusb = free_cgusb(cgusb);
2529  
2530  out_unlock:
2531  	DEVWUNLOCK(cgpu, pstate);
2532  
2533  	return bad;
2534  }
2535  
2536  bool usb_init(struct cgpu_info *cgpu, struct libusb_device *dev, struct usb_find_devices *found_match)
2537  {
2538  	struct usb_find_devices *found_use = NULL;
2539  	int uninitialised_var(ret);
2540  	int i;
2541  
2542  	for (i = 0; find_dev[i].drv != DRIVER_MAX; i++) {
2543  		if (find_dev[i].drv == found_match->drv &&
2544  		    find_dev[i].idVendor == found_match->idVendor &&
2545  		    find_dev[i].idProduct == found_match->idProduct) {
2546  			found_use = cgmalloc(sizeof(*found_use));
2547  			cg_memcpy(found_use, &(find_dev[i]), sizeof(*found_use));
2548  
2549  			ret = _usb_init(cgpu, dev, found_use);
2550  
2551  			if (ret != USB_INIT_IGNORE)
2552  				break;
2553  		}
2554  	}
2555  
2556  	if (ret == USB_INIT_FAIL) {
2557  		applog(LOG_ERR, "%s detect (%d:%d) failed to initialise (incorrect device?), resetting",
2558  				cgpu->drv->dname,
2559  				(int)(cgpu->usbinfo.bus_number),
2560  				(int)(cgpu->usbinfo.device_address));
2561  		if (cgpu->usbdev && cgpu->usbdev->handle)
2562  			libusb_reset_device(cgpu->usbdev->handle);
2563  	}
2564  
2565  	return (ret == USB_INIT_OK);
2566  }
2567  
2568  static bool usb_check_device(struct device_drv *drv, struct libusb_device *dev, struct usb_find_devices *look)
2569  {
2570  	struct libusb_device_descriptor desc;
2571  	int bus_number, device_address;
2572  	int err, i;
2573  	bool ok;
2574  
2575  	err = libusb_get_device_descriptor(dev, &desc);
2576  	if (err) {
2577  		applog(LOG_DEBUG, "USB check device: Failed to get descriptor, err %d", err);
2578  		return false;
2579  	}
2580  
2581  	if (desc.idVendor != look->idVendor || desc.idProduct != look->idProduct) {
2582  		applog(LOG_DEBUG, "%s looking for %s %04x:%04x but found %04x:%04x instead",
2583  			drv->name, look->name, look->idVendor, look->idProduct, desc.idVendor, desc.idProduct);
2584  
2585  		return false;
2586  	}
2587  
2588  	if (busdev_count > 0) {
2589  		bus_number = (int)libusb_get_bus_number(dev);
2590  		device_address = (int)libusb_get_device_address(dev);
2591  		ok = false;
2592  		for (i = 0; i < busdev_count; i++) {
2593  			if (bus_number == busdev[i].bus_number) {
2594  				if (busdev[i].device_address == -1 ||
2595  				    device_address == busdev[i].device_address) {
2596  					ok = true;
2597  					break;
2598  				}
2599  			}
2600  		}
2601  		if (!ok) {
2602  			applog(LOG_DEBUG, "%s rejected %s %04x:%04x with bus:dev (%d:%d)",
2603  				drv->name, look->name, look->idVendor, look->idProduct,
2604  				bus_number, device_address);
2605  			return false;
2606  		}
2607  	}
2608  
2609  	applog(LOG_DEBUG, "%s looking for and found %s %04x:%04x",
2610  		drv->name, look->name, look->idVendor, look->idProduct);
2611  
2612  	return true;
2613  }
2614  
2615  static struct usb_find_devices *usb_check_each(int drvnum, struct device_drv *drv, struct libusb_device *dev)
2616  {
2617  	struct usb_find_devices *found;
2618  	int i;
2619  
2620  	for (i = 0; find_dev[i].drv != DRIVER_MAX; i++)
2621  		if (find_dev[i].drv == drvnum) {
2622  			if (usb_check_device(drv, dev, &(find_dev[i]))) {
2623  				found = cgmalloc(sizeof(*found));
2624  				cg_memcpy(found, &(find_dev[i]), sizeof(*found));
2625  				return found;
2626  			}
2627  		}
2628  
2629  	return NULL;
2630  }
2631  
2632  #define DRIVER_USB_CHECK_EACH(X) 	if (drv->drv_id == DRIVER_##X) \
2633  		return usb_check_each(DRIVER_##X, drv, dev);
2634  
2635  static struct usb_find_devices *usb_check(__maybe_unused struct device_drv *drv, __maybe_unused struct libusb_device *dev)
2636  {
2637  	if (drv_count[drv->drv_id].count >= drv_count[drv->drv_id].limit) {
2638  		applog(LOG_DEBUG,
2639  			"USB scan devices3: %s limit %d reached",
2640  			drv->dname, drv_count[drv->drv_id].limit);
2641  		return NULL;
2642  	}
2643  
2644  	DRIVER_PARSE_COMMANDS(DRIVER_USB_CHECK_EACH)
2645  
2646  	return NULL;
2647  }
2648  
2649  void __usb_detect(struct device_drv *drv, struct cgpu_info *(*device_detect)(struct libusb_device *, struct usb_find_devices *),
2650  		  bool single)
2651  {
2652  	libusb_device **list;
2653  	ssize_t count, i;
2654  	struct usb_find_devices *found;
2655  	struct cgpu_info *cgpu;
2656  
2657  	applog(LOG_DEBUG, "USB scan devices: checking for %s devices", drv->name);
2658  
2659  	if (total_count >= total_limit) {
2660  		applog(LOG_DEBUG, "USB scan devices: total limit %d reached", total_limit);
2661  		return;
2662  	}
2663  
2664  	if (drv_count[drv->drv_id].count >= drv_count[drv->drv_id].limit) {
2665  		applog(LOG_DEBUG,
2666  			"USB scan devices: %s limit %d reached",
2667  			drv->dname, drv_count[drv->drv_id].limit);
2668  		return;
2669  	}
2670  
2671  	count = libusb_get_device_list(NULL, &list);
2672  	if (count < 0) {
2673  		applog(LOG_DEBUG, "USB scan devices: failed, err %d", (int)count);
2674  		return;
2675  	}
2676  
2677  	if (count == 0)
2678  		applog(LOG_DEBUG, "USB scan devices: found no devices");
2679  	else
2680  		cgsleep_ms(166);
2681  
2682  	for (i = 0; i < count; i++) {
2683  		if (total_count >= total_limit) {
2684  			applog(LOG_DEBUG, "USB scan devices2: total limit %d reached", total_limit);
2685  			break;
2686  		}
2687  
2688  		if (drv_count[drv->drv_id].count >= drv_count[drv->drv_id].limit) {
2689  			applog(LOG_DEBUG,
2690  				"USB scan devices2: %s limit %d reached",
2691  				drv->dname, drv_count[drv->drv_id].limit);
2692  			break;
2693  		}
2694  
2695  		found = usb_check(drv, list[i]);
2696  		if (found != NULL) {
2697  			bool new_dev = false;
2698  
2699  			if (is_in_use(list[i]) || cgminer_usb_lock(drv, list[i]) == false)
2700  				free(found);
2701  			else {
2702  				cgpu = device_detect(list[i], found);
2703  				if (!cgpu)
2704  					cgminer_usb_unlock(drv, list[i]);
2705  				else {
2706  					new_dev = true;
2707  					cgpu->usbinfo.initialised = true;
2708  					total_count++;
2709  					drv_count[drv->drv_id].count++;
2710  				}
2711  				free(found);
2712  			}
2713  			if (single && new_dev)
2714  				break;
2715  		}
2716  	}
2717  
2718  	libusb_free_device_list(list, 1);
2719  }
2720  
2721  #if DO_USB_STATS
2722  static void modes_str(char *buf, uint32_t modes)
2723  {
2724  	bool first;
2725  
2726  	*buf = '\0';
2727  
2728  	if (modes == MODE_NONE)
2729  		strcpy(buf, MODE_NONE_STR);
2730  	else {
2731  		first = true;
2732  
2733  		if (modes & MODE_CTRL_READ) {
2734  			strcpy(buf, MODE_CTRL_READ_STR);
2735  			first = false;
2736  		}
2737  
2738  		if (modes & MODE_CTRL_WRITE) {
2739  			if (!first)
2740  				strcat(buf, MODE_SEP_STR);
2741  			strcat(buf, MODE_CTRL_WRITE_STR);
2742  			first = false;
2743  		}
2744  
2745  		if (modes & MODE_BULK_READ) {
2746  			if (!first)
2747  				strcat(buf, MODE_SEP_STR);
2748  			strcat(buf, MODE_BULK_READ_STR);
2749  			first = false;
2750  		}
2751  
2752  		if (modes & MODE_BULK_WRITE) {
2753  			if (!first)
2754  				strcat(buf, MODE_SEP_STR);
2755  			strcat(buf, MODE_BULK_WRITE_STR);
2756  			first = false;
2757  		}
2758  	}
2759  }
2760  #endif
2761  
2762  // The stat data can be spurious due to not locking it before copying it -
2763  // however that would require the stat() function to also lock and release
2764  // a mutex every time a usb read or write is called which would slow
2765  // things down more
2766  struct api_data *api_usb_stats(__maybe_unused int *count)
2767  {
2768  #if DO_USB_STATS
2769  	struct cg_usb_stats_details *details;
2770  	struct cg_usb_stats *sta;
2771  	struct api_data *root = NULL;
2772  	int device;
2773  	int cmdseq;
2774  	char modes_s[32];
2775  
2776  	if (next_stat == USB_NOSTAT)
2777  		return NULL;
2778  
2779  	while (*count < next_stat * C_MAX * 2) {
2780  		device = *count / (C_MAX * 2);
2781  		cmdseq = *count % (C_MAX * 2);
2782  
2783  		(*count)++;
2784  
2785  		sta = &(usb_stats[device]);
2786  		details = &(sta->details[cmdseq]);
2787  
2788  		// Only show stats that have results
2789  		if (details->item[CMD_CMD].count == 0 &&
2790  		    details->item[CMD_TIMEOUT].count == 0 &&
2791  		    details->item[CMD_ERROR].count == 0)
2792  			continue;
2793  
2794  		root = api_add_string(root, "Name", sta->name, false);
2795  		root = api_add_int(root, "ID", &(sta->device_id), false);
2796  		root = api_add_const(root, "Stat", usb_commands[cmdseq/2], false);
2797  		root = api_add_int(root, "Seq", &(details->seq), true);
2798  		modes_str(modes_s, details->modes);
2799  		root = api_add_string(root, "Modes", modes_s, true);
2800  		root = api_add_uint64(root, "Count",
2801  					&(details->item[CMD_CMD].count), true);
2802  		root = api_add_double(root, "Total Delay",
2803  					&(details->item[CMD_CMD].total_delay), true);
2804  		root = api_add_double(root, "Min Delay",
2805  					&(details->item[CMD_CMD].min_delay), true);
2806  		root = api_add_double(root, "Max Delay",
2807  					&(details->item[CMD_CMD].max_delay), true);
2808  		root = api_add_uint64(root, "Timeout Count",
2809  					&(details->item[CMD_TIMEOUT].count), true);
2810  		root = api_add_double(root, "Timeout Total Delay",
2811  					&(details->item[CMD_TIMEOUT].total_delay), true);
2812  		root = api_add_double(root, "Timeout Min Delay",
2813  					&(details->item[CMD_TIMEOUT].min_delay), true);
2814  		root = api_add_double(root, "Timeout Max Delay",
2815  					&(details->item[CMD_TIMEOUT].max_delay), true);
2816  		root = api_add_uint64(root, "Error Count",
2817  					&(details->item[CMD_ERROR].count), true);
2818  		root = api_add_double(root, "Error Total Delay",
2819  					&(details->item[CMD_ERROR].total_delay), true);
2820  		root = api_add_double(root, "Error Min Delay",
2821  					&(details->item[CMD_ERROR].min_delay), true);
2822  		root = api_add_double(root, "Error Max Delay",
2823  					&(details->item[CMD_ERROR].max_delay), true);
2824  		root = api_add_timeval(root, "First Command",
2825  					&(details->item[CMD_CMD].first), true);
2826  		root = api_add_timeval(root, "Last Command",
2827  					&(details->item[CMD_CMD].last), true);
2828  		root = api_add_timeval(root, "First Timeout",
2829  					&(details->item[CMD_TIMEOUT].first), true);
2830  		root = api_add_timeval(root, "Last Timeout",
2831  					&(details->item[CMD_TIMEOUT].last), true);
2832  		root = api_add_timeval(root, "First Error",
2833  					&(details->item[CMD_ERROR].first), true);
2834  		root = api_add_timeval(root, "Last Error",
2835  					&(details->item[CMD_ERROR].last), true);
2836  
2837  		return root;
2838  	}
2839  #endif
2840  	return NULL;
2841  }
2842  
2843  #if DO_USB_STATS
2844  static void newstats(struct cgpu_info *cgpu)
2845  {
2846  	int i;
2847  
2848  	mutex_lock(&cgusb_lock);
2849  
2850  	cgpu->usbinfo.usbstat = next_stat + 1;
2851  
2852  	usb_stats = cgrealloc(usb_stats, sizeof(*usb_stats) * (next_stat+1));
2853  	usb_stats[next_stat].name = cgpu->drv->name;
2854  	usb_stats[next_stat].device_id = -1;
2855  	usb_stats[next_stat].details = cgcalloc(2, sizeof(struct cg_usb_stats_details) * (C_MAX + 1));
2856  
2857  	for (i = 1; i < C_MAX * 2; i += 2)
2858  		usb_stats[next_stat].details[i].seq = 1;
2859  
2860  	next_stat++;
2861  
2862  	mutex_unlock(&cgusb_lock);
2863  }
2864  #endif
2865  
2866  void update_usb_stats(__maybe_unused struct cgpu_info *cgpu)
2867  {
2868  #if DO_USB_STATS
2869  	if (cgpu->usbinfo.usbstat < 1)
2870  		newstats(cgpu);
2871  
2872  	// we don't know the device_id until after add_cgpu()
2873  	usb_stats[cgpu->usbinfo.usbstat - 1].device_id = cgpu->device_id;
2874  #endif
2875  }
2876  
2877  #if DO_USB_STATS
2878  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)
2879  {
2880  	struct cg_usb_stats_details *details;
2881  	double diff;
2882  	int item, extrams;
2883  
2884  	if (cgpu->usbinfo.usbstat < 1)
2885  		newstats(cgpu);
2886  
2887  	cgpu->usbinfo.tmo_count++;
2888  
2889  	// timeout checks are only done when stats are enabled
2890  	extrams = SECTOMS(tdiff(tv_finish, tv_start)) - timeout;
2891  	if (extrams >= USB_TMO_0) {
2892  		uint32_t totms = (uint32_t)(timeout + extrams);
2893  		int offset = 0;
2894  
2895  		if (extrams >= USB_TMO_2) {
2896  			applog(LOG_INFO, "%s%i: TIMEOUT %s took %dms but was %dms",
2897  					cgpu->drv->name, cgpu->device_id,
2898  					usb_cmdname(cmd), totms, timeout) ;
2899  			offset = 2;
2900  		} else if (extrams >= USB_TMO_1)
2901  			offset = 1;
2902  
2903  		cgpu->usbinfo.usb_tmo[offset].count++;
2904  		cgpu->usbinfo.usb_tmo[offset].total_over += extrams;
2905  		cgpu->usbinfo.usb_tmo[offset].total_tmo += timeout;
2906  		if (cgpu->usbinfo.usb_tmo[offset].min_tmo == 0) {
2907  			cgpu->usbinfo.usb_tmo[offset].min_tmo = totms;
2908  			cgpu->usbinfo.usb_tmo[offset].max_tmo = totms;
2909  		} else {
2910  			if (cgpu->usbinfo.usb_tmo[offset].min_tmo > totms)
2911  				cgpu->usbinfo.usb_tmo[offset].min_tmo = totms;
2912  			if (cgpu->usbinfo.usb_tmo[offset].max_tmo < totms)
2913  				cgpu->usbinfo.usb_tmo[offset].max_tmo = totms;
2914  		}
2915  	}
2916  
2917  	details = &(usb_stats[cgpu->usbinfo.usbstat - 1].details[cmd * 2 + seq]);
2918  	details->modes |= mode;
2919  
2920  	diff = tdiff(tv_finish, tv_start);
2921  
2922  	switch (err) {
2923  		case LIBUSB_SUCCESS:
2924  			item = CMD_CMD;
2925  			break;
2926  		case LIBUSB_ERROR_TIMEOUT:
2927  			item = CMD_TIMEOUT;
2928  			break;
2929  		default:
2930  			item = CMD_ERROR;
2931  			break;
2932  	}
2933  
2934  	if (details->item[item].count == 0) {
2935  		details->item[item].min_delay = diff;
2936  		cg_memcpy(&(details->item[item].first), tv_start, sizeof(*tv_start));
2937  	} else if (diff < details->item[item].min_delay)
2938  		details->item[item].min_delay = diff;
2939  
2940  	if (diff > details->item[item].max_delay)
2941  		details->item[item].max_delay = diff;
2942  
2943  	details->item[item].total_delay += diff;
2944  	cg_memcpy(&(details->item[item].last), tv_start, sizeof(*tv_start));
2945  	details->item[item].count++;
2946  }
2947  
2948  static void rejected_inc(struct cgpu_info *cgpu, uint32_t mode)
2949  {
2950  	struct cg_usb_stats_details *details;
2951  	int item = CMD_ERROR;
2952  
2953  	if (cgpu->usbinfo.usbstat < 1)
2954  		newstats(cgpu);
2955  
2956  	details = &(usb_stats[cgpu->usbinfo.usbstat - 1].details[C_REJECTED * 2 + 0]);
2957  	details->modes |= mode;
2958  	details->item[item].count++;
2959  }
2960  #endif
2961  
2962  #define USB_RETRY_MAX 5
2963  
2964  struct usb_transfer {
2965  	cgsem_t cgsem;
2966  	struct libusb_transfer *transfer;
2967  	bool cancellable;
2968  	struct list_head list;
2969  };
2970  
2971  bool async_usb_transfers(void)
2972  {
2973  	bool ret;
2974  
2975  	cg_rlock(&cgusb_fd_lock);
2976  	ret = !list_empty(&ut_list);
2977  	cg_runlock(&cgusb_fd_lock);
2978  
2979  	return ret;
2980  }
2981  
2982  /* Cancellable transfers should only be labelled as such if it is safe for them
2983   * to effectively mimic timing out early. This flag is usually used to signify
2984   * a read is waiting on a non-critical response that takes a long time and the
2985   * driver wishes it be aborted if work restart message has been sent. */
2986  void cancel_usb_transfers(void)
2987  {
2988  	struct usb_transfer *ut;
2989  	int cancellations = 0;
2990  
2991  	cg_wlock(&cgusb_fd_lock);
2992  	list_for_each_entry(ut, &ut_list, list) {
2993  		if (ut->cancellable) {
2994  			ut->cancellable = false;
2995  			libusb_cancel_transfer(ut->transfer);
2996  			cancellations++;
2997  		}
2998  	}
2999  	cg_wunlock(&cgusb_fd_lock);
3000  
3001  	if (cancellations)
3002  		applog(LOG_DEBUG, "Cancelled %d USB transfers", cancellations);
3003  }
3004  
3005  static void init_usb_transfer(struct usb_transfer *ut)
3006  {
3007  	cgsem_init(&ut->cgsem);
3008  	ut->transfer = libusb_alloc_transfer(0);
3009  	if (unlikely(!ut->transfer))
3010  		quit(1, "Failed to libusb_alloc_transfer");
3011  	ut->transfer->user_data = ut;
3012  	ut->cancellable = false;
3013  }
3014  
3015  static void complete_usb_transfer(struct usb_transfer *ut)
3016  {
3017  	cg_wlock(&cgusb_fd_lock);
3018  	list_del(&ut->list);
3019  	cg_wunlock(&cgusb_fd_lock);
3020  
3021  	cgsem_destroy(&ut->cgsem);
3022  	libusb_free_transfer(ut->transfer);
3023  }
3024  
3025  static void LIBUSB_CALL transfer_callback(struct libusb_transfer *transfer)
3026  {
3027  	struct usb_transfer *ut = transfer->user_data;
3028  
3029  	ut->cancellable = false;
3030  	cgsem_post(&ut->cgsem);
3031  }
3032  
3033  static int usb_transfer_toerr(int ret)
3034  {
3035  	if (ret <= 0)
3036  		return ret;
3037  
3038  	switch (ret) {
3039  		default:
3040  		case LIBUSB_TRANSFER_COMPLETED:
3041  			ret = LIBUSB_SUCCESS;
3042  			break;
3043  		case LIBUSB_TRANSFER_ERROR:
3044  			ret = LIBUSB_ERROR_IO;
3045  			break;
3046  		case LIBUSB_TRANSFER_TIMED_OUT:
3047  		case LIBUSB_TRANSFER_CANCELLED:
3048  			ret = LIBUSB_ERROR_TIMEOUT;
3049  			break;
3050  		case LIBUSB_TRANSFER_STALL:
3051  			ret = LIBUSB_ERROR_PIPE;
3052  			break;
3053  		case LIBUSB_TRANSFER_NO_DEVICE:
3054  			ret = LIBUSB_ERROR_NO_DEVICE;
3055  			break;
3056  		case LIBUSB_TRANSFER_OVERFLOW:
3057  			ret = LIBUSB_ERROR_OVERFLOW;
3058  			break;
3059  	}
3060  	return ret;
3061  }
3062  
3063  /* Wait for callback function to tell us it has finished the USB transfer, but
3064   * use our own timer to cancel the request if we go beyond the timeout. */
3065  static int callback_wait(struct usb_transfer *ut, int *transferred, unsigned int timeout)
3066  {
3067  	struct libusb_transfer *transfer= ut->transfer;
3068  	int ret;
3069  
3070  	ret = cgsem_mswait(&ut->cgsem, timeout);
3071  	if (ret == ETIMEDOUT) {
3072  		/* We are emulating a timeout ourself here */
3073  		libusb_cancel_transfer(transfer);
3074  
3075  		/* Now wait for the callback function to be invoked. */
3076  		cgsem_wait(&ut->cgsem);
3077  	}
3078  	ret = transfer->status;
3079  	ret = usb_transfer_toerr(ret);
3080  
3081  	/* No need to sort out mutexes here since they won't be reused */
3082  	*transferred = transfer->actual_length;
3083  
3084  	return ret;
3085  }
3086  
3087  static int usb_submit_transfer(struct usb_transfer *ut, struct libusb_transfer *transfer,
3088  			       bool cancellable, bool tt)
3089  {
3090  	int err;
3091  
3092  	INIT_LIST_HEAD(&ut->list);
3093  
3094  	cg_wlock(&cgusb_fd_lock);
3095  	/* Imitate a transaction translator for writes to usb1.1 devices */
3096  	if (tt)
3097  		cgsleep_ms_r(&usb11_cgt, 1);
3098  	err = libusb_submit_transfer(transfer);
3099  	if (likely(!err))
3100  		ut->cancellable = cancellable;
3101  	list_add(&ut->list, &ut_list);
3102  	if (tt)
3103  		cgtimer_time(&usb11_cgt);
3104  	cg_wunlock(&cgusb_fd_lock);
3105  
3106  	return err;
3107  }
3108  
3109  static int
3110  usb_perform_transfer(struct cgpu_info *cgpu, struct cg_usb_device *usbdev, int intinfo,
3111  		  int epinfo, unsigned char *data, int length, int *transferred,
3112  		  unsigned int timeout, __maybe_unused int mode, enum usb_cmds cmd,
3113  		  __maybe_unused int seq, bool cancellable, bool tt)
3114  {
3115  	int bulk_timeout, callback_timeout = timeout, err_retries = 0;
3116  	struct libusb_device_handle *dev_handle = usbdev->handle;
3117  	struct usb_epinfo *usb_epinfo;
3118  	struct usb_transfer ut;
3119  	unsigned char endpoint;
3120  	bool interrupt;
3121  	int err, errn;
3122  #if DO_USB_STATS
3123  	struct timeval tv_start, tv_finish;
3124  #endif
3125  	unsigned char buf[512];
3126  #ifdef WIN32
3127  	/* On windows the callback_timeout is a safety mechanism only. */
3128  	bulk_timeout = timeout;
3129  	callback_timeout += WIN_CALLBACK_EXTRA;
3130  #else
3131  	/* We give the transfer no timeout since we manage timeouts ourself on
3132  	 * non windows. */
3133  	bulk_timeout = 0;
3134  #endif
3135  
3136  	usb_epinfo = &(usbdev->found->intinfos[intinfo].epinfos[epinfo]);
3137  	interrupt = usb_epinfo->att == LIBUSB_TRANSFER_TYPE_INTERRUPT;
3138  	endpoint = usb_epinfo->ep;
3139  
3140  	if (unlikely(!data)) {
3141  		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",
3142  		       cgpu->drv->name, intinfo, epinfo, length, timeout, mode, usb_cmdname(cmd), seq, (int)endpoint);
3143  		err = LIBUSB_ERROR_IO;
3144  		goto out_fail;
3145  	}
3146  	/* Avoid any async transfers during shutdown to allow the polling
3147  	 * thread to be shut down after all existing transfers are complete */
3148  	if (opt_lowmem || cgpu->shutdown)
3149  		return libusb_bulk_transfer(dev_handle, endpoint, data, length, transferred, timeout);
3150  err_retry:
3151  	init_usb_transfer(&ut);
3152  
3153  	if ((endpoint & LIBUSB_ENDPOINT_DIR_MASK) == LIBUSB_ENDPOINT_OUT) {
3154  		cg_memcpy(buf, data, length);
3155  #ifndef HAVE_LIBUSB
3156  		/* Older versions may not have this feature so only enable it
3157  		 * when we know we're compiling with included static libusb. We
3158  		 * only do this for bulk transfer, not interrupt. */
3159  		if (!cgpu->nozlp && !interrupt)
3160  			ut.transfer->flags |= LIBUSB_TRANSFER_ADD_ZERO_PACKET;
3161  #endif
3162  #ifdef WIN32
3163  		/* Writes on windows really don't like to be cancelled, but
3164  		 * are prone to timeouts under heavy USB traffic, so make this
3165  		 * a last resort cancellation delayed long after the write
3166  		 * would have timed out on its own. */
3167  		callback_timeout += WIN_WRITE_CBEXTRA;
3168  #endif
3169  	}
3170  
3171  	USBDEBUG("USB debug: @usb_perform_transfer(%s (nodev=%s),intinfo=%d,epinfo=%d,data=%p,length=%d,timeout=%u,mode=%d,cmd=%s,seq=%d) endpoint=%d", cgpu->drv->name, bool_str(cgpu->usbinfo.nodev), intinfo, epinfo, data, length, timeout, mode, usb_cmdname(cmd), seq, (int)endpoint);
3172  
3173  	if (interrupt) {
3174  		libusb_fill_interrupt_transfer(ut.transfer, dev_handle, endpoint,
3175  					       buf, length, transfer_callback, &ut,
3176  				 bulk_timeout);
3177  	} else {
3178  		libusb_fill_bulk_transfer(ut.transfer, dev_handle, endpoint, buf,
3179  					  length, transfer_callback, &ut, bulk_timeout);
3180  	}
3181  	STATS_TIMEVAL(&tv_start);
3182  	err = usb_submit_transfer(&ut, ut.transfer, cancellable, tt);
3183  	errn = errno;
3184  	if (!err)
3185  		err = callback_wait(&ut, transferred, callback_timeout);
3186  	else
3187  		err = usb_transfer_toerr(err);
3188  	complete_usb_transfer(&ut);
3189  
3190  	STATS_TIMEVAL(&tv_finish);
3191  	USB_STATS(cgpu, &tv_start, &tv_finish, err, mode, cmd, seq, timeout);
3192  
3193  	if (err < 0) {
3194  		applog(LOG_DEBUG, "%s%i: %s (amt=%d err=%d ern=%d)",
3195  				cgpu->drv->name, cgpu->device_id,
3196  				usb_cmdname(cmd), *transferred, err, errn);
3197  	}
3198  
3199  	if (err == LIBUSB_ERROR_PIPE) {
3200  		int pipeerr, retries = 0;
3201  
3202  		do {
3203  			cgpu->usbinfo.last_pipe = time(NULL);
3204  			cgpu->usbinfo.pipe_count++;
3205  			applog(LOG_INFO, "%s%i: libusb pipe error, trying to clear",
3206  				cgpu->drv->name, cgpu->device_id);
3207  			pipeerr = libusb_clear_halt(dev_handle, endpoint);
3208  			applog(LOG_DEBUG, "%s%i: libusb pipe error%scleared",
3209  				cgpu->drv->name, cgpu->device_id, err ? " not " : " ");
3210  
3211  			if (pipeerr)
3212  				cgpu->usbinfo.clear_fail_count++;
3213  		} while (pipeerr && ++retries < USB_RETRY_MAX);
3214  		if (!pipeerr && ++err_retries < USB_RETRY_MAX)
3215  			goto err_retry;
3216  	}
3217  	if (err == LIBUSB_ERROR_IO && ++err_retries < USB_RETRY_MAX)
3218  		goto err_retry;
3219  out_fail:
3220  	if (NODEV(err))
3221  		*transferred = 0;
3222  	else if ((endpoint & LIBUSB_ENDPOINT_DIR_MASK) == LIBUSB_ENDPOINT_IN && *transferred)
3223  		cg_memcpy(data, buf, *transferred);
3224  
3225  	return err;
3226  }
3227  
3228  void usb_reset(struct cgpu_info *cgpu)
3229  {
3230  	int pstate, err = 0;
3231  
3232  	DEVWLOCK(cgpu, pstate);
3233  	if (!cgpu->usbinfo.nodev) {
3234  		err = libusb_reset_device(cgpu->usbdev->handle);
3235  		applog(LOG_WARNING, "%s %i attempted reset got err:(%d) %s",
3236  			cgpu->drv->name, cgpu->device_id, err, libusb_error_name(err));
3237  	}
3238  	if (NODEV(err))
3239  		release_cgpu(cgpu);
3240  	DEVWUNLOCK(cgpu, pstate);
3241  }
3242  
3243  int _usb_read(struct cgpu_info *cgpu, int intinfo, int epinfo, char *buf, size_t bufsiz,
3244  	      int *processed, int timeout, const char *end, enum usb_cmds cmd, bool readonce, bool cancellable)
3245  {
3246  	unsigned char *ptr, usbbuf[USB_READ_BUFSIZE];
3247  	struct timeval read_start, tv_finish;
3248  	int bufleft, err, got, tot, pstate, tried_reset;
3249  	struct cg_usb_device *usbdev;
3250  	unsigned int initial_timeout;
3251  	bool first = true;
3252  	size_t usbbufread;
3253  	int endlen = 0;
3254  	char *eom = NULL;
3255  	double done;
3256  	bool ftdi;
3257  
3258  	memset(usbbuf, 0, USB_READ_BUFSIZE);
3259  	memset(buf, 0, bufsiz);
3260  
3261  	if (end)
3262  		endlen = strlen(end);
3263  
3264  	DEVRLOCK(cgpu, pstate);
3265  	if (cgpu->usbinfo.nodev) {
3266  		*processed = 0;
3267  		USB_REJECT(cgpu, MODE_BULK_READ);
3268  
3269  		err = LIBUSB_ERROR_NO_DEVICE;
3270  		goto out_noerrmsg;
3271  	}
3272  
3273  	usbdev = cgpu->usbdev;
3274  	/* Interrupt transfers are guaranteed to be of an expected size (we hope) */
3275  	if (usbdev->found->intinfos[intinfo].epinfos[epinfo].att == LIBUSB_TRANSFER_TYPE_INTERRUPT)
3276  		usbbufread = bufsiz;
3277  	else
3278  		usbbufread = 512;
3279  
3280  	ftdi = (usbdev->usb_type == USB_TYPE_FTDI);
3281  
3282  	USBDEBUG("USB debug: _usb_read(%s (nodev=%s),intinfo=%d,epinfo=%d,buf=%p,bufsiz=%d,proc=%p,timeout=%u,end=%s,cmd=%s,ftdi=%s,readonce=%s)", cgpu->drv->name, bool_str(cgpu->usbinfo.nodev), intinfo, epinfo, buf, (int)bufsiz, processed, timeout, end ? (char *)str_text((char *)end) : "NULL", usb_cmdname(cmd), bool_str(ftdi), bool_str(readonce));
3283  
3284  	if (bufsiz > USB_MAX_READ)
3285  		quit(1, "%s USB read request %d too large (max=%d)", cgpu->drv->name, (int)bufsiz, USB_MAX_READ);
3286  
3287  	if (timeout == DEVTIMEOUT)
3288  		timeout = usbdev->found->timeout;
3289  
3290  	tot = usbdev->bufamt;
3291  	bufleft = bufsiz - tot;
3292  	if (tot)
3293  		cg_memcpy(usbbuf, usbdev->buffer, tot);
3294  	ptr = usbbuf + tot;
3295  	usbdev->bufamt = 0;
3296  
3297  	err = LIBUSB_SUCCESS;
3298  	if (end != NULL)
3299  		eom = strstr((const char *)usbbuf, end);
3300  
3301  	initial_timeout = timeout;
3302  	cgtime(&read_start);
3303  	tried_reset = 0;
3304  	while (bufleft > 0 && !eom) {
3305  		err = usb_perform_transfer(cgpu, usbdev, intinfo, epinfo, ptr, usbbufread,
3306  					&got, timeout, MODE_BULK_READ, cmd,
3307  					first ? SEQ0 : SEQ1, cancellable, false);
3308  		if (NODEV(err))
3309  			goto out_noerrmsg;
3310  
3311  		cgtime(&tv_finish);
3312  		ptr[got] = '\0';
3313  
3314  		USBDEBUG("USB debug: @_usb_read(%s (nodev=%s)) first=%s err=%d%s got=%d ptr='%s' usbbufread=%d", cgpu->drv->name, bool_str(cgpu->usbinfo.nodev), bool_str(first), err, isnodev(err), got, (char *)str_text((char *)ptr), (int)usbbufread);
3315  
3316  		if (ftdi) {
3317  			// first 2 bytes returned are an FTDI status
3318  			if (got > 2) {
3319  				got -= 2;
3320  				memmove(ptr, ptr+2, got+1);
3321  			} else {
3322  				got = 0;
3323  				*ptr = '\0';
3324  			}
3325  		}
3326  
3327  		tot += got;
3328  		if (end != NULL)
3329  			eom = strstr((const char *)usbbuf, end);
3330  
3331  		/* Attempt a usb reset for an error that will otherwise cause
3332  		 * this device to drop out provided we know the device still
3333  		 * might exist. */
3334  		if (err && err != LIBUSB_ERROR_TIMEOUT) {
3335  			applog(LOG_WARNING, "%s %i %s usb read err:(%d) %s", cgpu->drv->name,
3336  			       cgpu->device_id, usb_cmdname(cmd), err, libusb_error_name(err));
3337  			if (err != LIBUSB_ERROR_NO_DEVICE && !tried_reset) {
3338  				err = libusb_reset_device(usbdev->handle);
3339  				tried_reset = 1; // don't call reset twice in a row
3340  				applog(LOG_WARNING, "%s %i attempted reset got err:(%d) %s",
3341  				       cgpu->drv->name, cgpu->device_id, err, libusb_error_name(err));
3342  			}
3343  		} else {
3344  			tried_reset = 0;
3345  		}
3346  
3347  		if (NODEV(err))
3348  			goto out_noerrmsg;
3349  
3350  		ptr += got;
3351  		bufleft -= got;
3352  		if (bufleft < 1)
3353  			err = LIBUSB_SUCCESS;
3354  
3355  		if (err || readonce)
3356  			break;
3357  
3358  
3359  		first = false;
3360  
3361  		done = tdiff(&tv_finish, &read_start);
3362  		// N.B. this is: return last err with whatever size has already been read
3363  		timeout = initial_timeout - (done * 1000);
3364  		if (timeout <= 0)
3365  			break;
3366  	}
3367  
3368  	/* If we found the end of message marker, just use that data and
3369  	 * return success. */
3370  	if (eom) {
3371  		size_t eomlen = (void *)eom - (void *)usbbuf + endlen;
3372  
3373  		if (eomlen < bufsiz) {
3374  			bufsiz = eomlen;
3375  			err = LIBUSB_SUCCESS;
3376  		}
3377  	}
3378  
3379  	// N.B. usbdev->buffer was emptied before the while() loop
3380  	if (tot > (int)bufsiz) {
3381  		usbdev->bufamt = tot - bufsiz;
3382  		cg_memcpy(usbdev->buffer, usbbuf + bufsiz, usbdev->bufamt);
3383  		tot -= usbdev->bufamt;
3384  		usbbuf[tot] = '\0';
3385  		applog(LOG_DEBUG, "USB: %s%i read1 buffering %d extra bytes",
3386  			cgpu->drv->name, cgpu->device_id, usbdev->bufamt);
3387  	}
3388  
3389  	*processed = tot;
3390  	cg_memcpy((char *)buf, (const char *)usbbuf, (tot < (int)bufsiz) ? tot + 1 : (int)bufsiz);
3391  
3392  out_noerrmsg:
3393  	if (NODEV(err)) {
3394  		cg_ruwlock(&cgpu->usbinfo.devlock);
3395  		release_cgpu(cgpu);
3396  		DEVWUNLOCK(cgpu, pstate);
3397  	} else
3398  		DEVRUNLOCK(cgpu, pstate);
3399  
3400  	return err;
3401  }
3402  
3403  int _usb_write(struct cgpu_info *cgpu, int intinfo, int epinfo, char *buf, size_t bufsiz, int *processed, int timeout, enum usb_cmds cmd)
3404  {
3405  	struct timeval write_start, tv_finish;
3406  	struct cg_usb_device *usbdev;
3407  	unsigned int initial_timeout;
3408  	int err, sent, tot, pstate, tried_reset;
3409  	bool first = true;
3410  	double done;
3411  
3412  	DEVRLOCK(cgpu, pstate);
3413  
3414  	USBDEBUG("USB debug: _usb_write(%s (nodev=%s),intinfo=%d,epinfo=%d,buf='%s',bufsiz=%d,proc=%p,timeout=%u,cmd=%s)", cgpu->drv->name, bool_str(cgpu->usbinfo.nodev), intinfo, epinfo, (char *)str_text(buf), (int)bufsiz, processed, timeout, usb_cmdname(cmd));
3415  
3416  	*processed = 0;
3417  
3418  	if (cgpu->usbinfo.nodev) {
3419  		USB_REJECT(cgpu, MODE_BULK_WRITE);
3420  
3421  		err = LIBUSB_ERROR_NO_DEVICE;
3422  		goto out_noerrmsg;
3423  	}
3424  
3425  	usbdev = cgpu->usbdev;
3426  	if (timeout == DEVTIMEOUT)
3427  		timeout = usbdev->found->timeout;
3428  
3429  	tot = 0;
3430  	err = LIBUSB_SUCCESS;
3431  	initial_timeout = timeout;
3432  	cgtime(&write_start);
3433  	tried_reset = 0;
3434  	while (bufsiz > 0) {
3435  		int tosend = bufsiz;
3436  
3437  		/* USB 1.1 devices don't handle zero packets well so split them
3438  		 * up to not have the final transfer equal to the wMaxPacketSize
3439  		 * or they will stall waiting for more data. */
3440  		if (usbdev->usb11) {
3441  			struct usb_epinfo *ue = &usbdev->found->intinfos[intinfo].epinfos[epinfo];
3442  
3443  			if (tosend == ue->wMaxPacketSize) {
3444  				tosend >>= 1;
3445  				if (unlikely(!tosend))
3446  					tosend = 1;
3447  			}
3448  		}
3449  		err = usb_perform_transfer(cgpu, usbdev, intinfo, epinfo, (unsigned char *)buf,
3450  					tosend, &sent, timeout, MODE_BULK_WRITE,
3451  					cmd, first ? SEQ0 : SEQ1, false, usbdev->tt);
3452  		if (NODEV(err))
3453  			goto out_noerrmsg;
3454  
3455  		cgtime(&tv_finish);
3456  
3457  		USBDEBUG("USB debug: @_usb_write(%s (nodev=%s)) err=%d%s sent=%d", cgpu->drv->name, bool_str(cgpu->usbinfo.nodev), err, isnodev(err), sent);
3458  
3459  		tot += sent;
3460  
3461  		/* Unlike reads, even a timeout error is unrecoverable on
3462  		 * writes. */
3463  		if (err) {
3464  			applog(LOG_WARNING, "%s %i %s usb write err:(%d) %s", cgpu->drv->name,
3465  			       cgpu->device_id, usb_cmdname(cmd), err, libusb_error_name(err));
3466  			if (err != LIBUSB_ERROR_NO_DEVICE && !tried_reset) {
3467  				err = libusb_reset_device(usbdev->handle);
3468  				tried_reset = 1; // don't try reset twice in a row
3469  				applog(LOG_WARNING, "%s %i attempted reset got err:(%d) %s",
3470  				       cgpu->drv->name, cgpu->device_id, err, libusb_error_name(err));
3471  			}
3472  		} else {
3473  			tried_reset = 0;
3474  		}
3475  		if (err)
3476  			break;
3477  
3478  		buf += sent;
3479  		bufsiz -= sent;
3480  
3481  		first = false;
3482  
3483  		done = tdiff(&tv_finish, &write_start);
3484  		// N.B. this is: return last err with whatever size was written
3485  		timeout = initial_timeout - (done * 1000);
3486  		if (timeout <= 0)
3487  			break;
3488  	}
3489  
3490  	*processed = tot;
3491  
3492  out_noerrmsg:
3493  	if (NODEV(err)) {
3494  		cg_ruwlock(&cgpu->usbinfo.devlock);
3495  		release_cgpu(cgpu);
3496  		DEVWUNLOCK(cgpu, pstate);
3497  	} else
3498  		DEVRUNLOCK(cgpu, pstate);
3499  
3500  	return err;
3501  }
3502  
3503  /* As we do for bulk reads, emulate a sync function for control transfers using
3504   * our own timeouts that takes the same parameters as libusb_control_transfer.
3505   */
3506  static int usb_control_transfer(struct cgpu_info *cgpu, libusb_device_handle *dev_handle, uint8_t bmRequestType,
3507  				uint8_t bRequest, uint16_t wValue, uint16_t wIndex,
3508  				unsigned char *buffer, uint16_t wLength, unsigned int timeout)
3509  {
3510  	struct usb_transfer ut;
3511  	unsigned char buf[70];
3512  	int err, transferred;
3513  	bool tt = false;
3514  
3515  	if (unlikely(cgpu->shutdown))
3516  		return libusb_control_transfer(dev_handle, bmRequestType, bRequest, wValue, wIndex, buffer, wLength, timeout);
3517  
3518  	init_usb_transfer(&ut);
3519  	libusb_fill_control_setup(buf, bmRequestType, bRequest, wValue,
3520  				  wIndex, wLength);
3521  	if ((bmRequestType & LIBUSB_ENDPOINT_DIR_MASK) == LIBUSB_ENDPOINT_OUT) {
3522  		if (wLength)
3523  			cg_memcpy(buf + LIBUSB_CONTROL_SETUP_SIZE, buffer, wLength);
3524  		if (cgpu->usbdev->descriptor->bcdUSB < 0x0200)
3525  			tt = true;
3526  	}
3527  	libusb_fill_control_transfer(ut.transfer, dev_handle, buf, transfer_callback,
3528  				     &ut, 0);
3529  	err = usb_submit_transfer(&ut, ut.transfer, false, tt);
3530  	if (!err)
3531  		err = callback_wait(&ut, &transferred, timeout);
3532  	if (err == LIBUSB_SUCCESS && transferred) {
3533  		if ((bmRequestType & LIBUSB_ENDPOINT_DIR_MASK) == LIBUSB_ENDPOINT_IN)
3534  			cg_memcpy(buffer, libusb_control_transfer_get_data(ut.transfer),
3535  			       transferred);
3536  		err = transferred;
3537  		goto out;
3538  	}
3539  	err = usb_transfer_toerr(err);
3540  out:
3541  	complete_usb_transfer(&ut);
3542  	return err;
3543  }
3544  
3545  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, __maybe_unused enum usb_cmds cmd)
3546  {
3547  	struct cg_usb_device *usbdev;
3548  #if DO_USB_STATS
3549  	struct timeval tv_start, tv_finish;
3550  #endif
3551  	unsigned char buf[64];
3552  	uint32_t *buf32 = (uint32_t *)buf;
3553  	int err, i, bufsiz;
3554  
3555  	USBDEBUG("USB debug: _usb_transfer(%s (nodev=%s),type=%"PRIu8",req=%"PRIu8",value=%"PRIu16",index=%"PRIu16",siz=%d,timeout=%u,cmd=%s)", cgpu->drv->name, bool_str(cgpu->usbinfo.nodev), request_type, bRequest, wValue, wIndex, siz, timeout, usb_cmdname(cmd));
3556  
3557  	if (cgpu->usbinfo.nodev) {
3558  		USB_REJECT(cgpu, MODE_CTRL_WRITE);
3559  
3560  		err = LIBUSB_ERROR_NO_DEVICE;
3561  		goto out_;
3562  	}
3563  	usbdev = cgpu->usbdev;
3564  	if (timeout == DEVTIMEOUT)
3565  		timeout = usbdev->found->timeout;
3566  
3567  	USBDEBUG("USB debug: @_usb_transfer() data=%s", bin2hex((unsigned char *)data, (size_t)siz));
3568  
3569  	if (siz > 0) {
3570  		bufsiz = siz - 1;
3571  		bufsiz >>= 2;
3572  		bufsiz++;
3573  		for (i = 0; i < bufsiz; i++)
3574  			buf32[i] = htole32(data[i]);
3575  	}
3576  
3577  	USBDEBUG("USB debug: @_usb_transfer() buf=%s", bin2hex(buf, (size_t)siz));
3578  
3579  	STATS_TIMEVAL(&tv_start);
3580  	err = usb_control_transfer(cgpu, usbdev->handle, request_type, bRequest,
3581  				   wValue, wIndex, buf, (uint16_t)siz, timeout);
3582  	STATS_TIMEVAL(&tv_finish);
3583  	USB_STATS(cgpu, &tv_start, &tv_finish, err, MODE_CTRL_WRITE, cmd, SEQ0, timeout);
3584  
3585  	USBDEBUG("USB debug: @_usb_transfer(%s (nodev=%s)) err=%d%s", cgpu->drv->name, bool_str(cgpu->usbinfo.nodev), err, isnodev(err));
3586  
3587  	if (err < 0 && err != LIBUSB_ERROR_TIMEOUT) {
3588  		applog(LOG_WARNING, "%s %i usb transfer err:(%d) %s", cgpu->drv->name, cgpu->device_id,
3589  		       err, libusb_error_name(err));
3590  	}
3591  out_:
3592  	return err;
3593  }
3594  
3595  /* We use the write devlock for control transfers since some control transfers
3596   * are rare but may be changing settings within the device causing problems
3597   * if concurrent transfers are happening. Using the write lock serialises
3598   * any transfers. */
3599  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)
3600  {
3601  	int pstate, err;
3602  
3603  	DEVWLOCK(cgpu, pstate);
3604  
3605  	err = __usb_transfer(cgpu, request_type, bRequest, wValue, wIndex, data, siz, timeout, cmd);
3606  
3607  	if (NOCONTROLDEV(err))
3608  		release_cgpu(cgpu);
3609  
3610  	DEVWUNLOCK(cgpu, pstate);
3611  
3612  	return err;
3613  }
3614  
3615  int _usb_transfer_read(struct cgpu_info *cgpu, uint8_t request_type, uint8_t bRequest, uint16_t wValue, uint16_t wIndex, char *buf, int bufsiz, int *amount, unsigned int timeout, __maybe_unused enum usb_cmds cmd)
3616  {
3617  	struct cg_usb_device *usbdev;
3618  #if DO_USB_STATS
3619  	struct timeval tv_start, tv_finish;
3620  #endif
3621  	unsigned char tbuf[64];
3622  	int err, pstate;
3623  
3624  	DEVWLOCK(cgpu, pstate);
3625  
3626  	USBDEBUG("USB debug: _usb_transfer_read(%s (nodev=%s),type=%"PRIu8",req=%"PRIu8",value=%"PRIu16",index=%"PRIu16",bufsiz=%d,timeout=%u,cmd=%s)", cgpu->drv->name, bool_str(cgpu->usbinfo.nodev), request_type, bRequest, wValue, wIndex, bufsiz, timeout, usb_cmdname(cmd));
3627  
3628  	if (cgpu->usbinfo.nodev) {
3629  		USB_REJECT(cgpu, MODE_CTRL_READ);
3630  
3631  		err = LIBUSB_ERROR_NO_DEVICE;
3632  		goto out_noerrmsg;
3633  	}
3634  	usbdev = cgpu->usbdev;
3635  	if (timeout == DEVTIMEOUT)
3636  		timeout = usbdev->found->timeout;
3637  
3638  	*amount = 0;
3639  
3640  	memset(tbuf, 0, 64);
3641  	STATS_TIMEVAL(&tv_start);
3642  	err = usb_control_transfer(cgpu, usbdev->handle, request_type, bRequest,
3643  				   wValue, wIndex, tbuf, (uint16_t)bufsiz, timeout);
3644  	STATS_TIMEVAL(&tv_finish);
3645  	USB_STATS(cgpu, &tv_start, &tv_finish, err, MODE_CTRL_READ, cmd, SEQ0, timeout);
3646  	cg_memcpy(buf, tbuf, bufsiz);
3647  
3648  	USBDEBUG("USB debug: @_usb_transfer_read(%s (nodev=%s)) amt/err=%d%s%s%s", cgpu->drv->name, bool_str(cgpu->usbinfo.nodev), err, isnodev(err), err > 0 ? " = " : BLANK, err > 0 ? bin2hex((unsigned char *)buf, (size_t)err) : BLANK);
3649  
3650  	if (err > 0) {
3651  		*amount = err;
3652  		err = 0;
3653  	}
3654  	if (err < 0 && err != LIBUSB_ERROR_TIMEOUT) {
3655  		applog(LOG_WARNING, "%s %i usb transfer read err:(%d) %s", cgpu->drv->name, cgpu->device_id,
3656  		       err, libusb_error_name(err));
3657  	}
3658  out_noerrmsg:
3659  	if (NOCONTROLDEV(err))
3660  		release_cgpu(cgpu);
3661  
3662  	DEVWUNLOCK(cgpu, pstate);
3663  
3664  	return err;
3665  }
3666  
3667  #define FTDI_STATUS_B0_MASK     (FTDI_RS0_CTS | FTDI_RS0_DSR | FTDI_RS0_RI | FTDI_RS0_RLSD)
3668  #define FTDI_RS0_CTS    (1 << 4)
3669  #define FTDI_RS0_DSR    (1 << 5)
3670  #define FTDI_RS0_RI     (1 << 6)
3671  #define FTDI_RS0_RLSD   (1 << 7)
3672  
3673  /* Clear to send for FTDI */
3674  int usb_ftdi_cts(struct cgpu_info *cgpu)
3675  {
3676  	char buf[2], ret;
3677  	int err, amount;
3678  
3679  	err = _usb_transfer_read(cgpu, (uint8_t)FTDI_TYPE_IN, (uint8_t)5,
3680  				 (uint16_t)0, (uint16_t)0, buf, 2,
3681  				 &amount, DEVTIMEOUT, C_FTDI_STATUS);
3682  	/* We return true in case drivers are waiting indefinitely to try and
3683  	 * write to something that's not there. */
3684  	if (err)
3685  		return true;
3686  
3687  	ret = buf[0] & FTDI_STATUS_B0_MASK;
3688  	return (ret & FTDI_RS0_CTS);
3689  }
3690  
3691  int _usb_ftdi_set_latency(struct cgpu_info *cgpu, int intinfo)
3692  {
3693  	int err = 0;
3694  	int pstate;
3695  
3696  	DEVWLOCK(cgpu, pstate);
3697  
3698  	if (cgpu->usbdev) {
3699  		if (cgpu->usbdev->usb_type != USB_TYPE_FTDI) {
3700  			applog(LOG_ERR, "%s: cgid %d latency request on non-FTDI device",
3701  				cgpu->drv->name, cgpu->cgminer_id);
3702  			err = LIBUSB_ERROR_NOT_SUPPORTED;
3703  		} else if (cgpu->usbdev->found->latency == LATENCY_UNUSED) {
3704  			applog(LOG_ERR, "%s: cgid %d invalid latency (UNUSED)",
3705  				cgpu->drv->name, cgpu->cgminer_id);
3706  			err = LIBUSB_ERROR_NOT_SUPPORTED;
3707  		}
3708  
3709  		if (!err)
3710  			err = __usb_transfer(cgpu, FTDI_TYPE_OUT, FTDI_REQUEST_LATENCY,
3711  						cgpu->usbdev->found->latency,
3712  						USBIF(cgpu->usbdev, intinfo),
3713  						NULL, 0, DEVTIMEOUT, C_LATENCY);
3714  	}
3715  
3716  	DEVWUNLOCK(cgpu, pstate);
3717  
3718  	applog(LOG_DEBUG, "%s: cgid %d %s got err %d",
3719  				cgpu->drv->name, cgpu->cgminer_id,
3720  				usb_cmdname(C_LATENCY), err);
3721  
3722  	return err;
3723  }
3724  
3725  void usb_buffer_clear(struct cgpu_info *cgpu)
3726  {
3727  	int pstate;
3728  
3729  	DEVWLOCK(cgpu, pstate);
3730  
3731  	if (cgpu->usbdev)
3732  		cgpu->usbdev->bufamt = 0;
3733  
3734  	DEVWUNLOCK(cgpu, pstate);
3735  }
3736  
3737  uint32_t usb_buffer_size(struct cgpu_info *cgpu)
3738  {
3739  	uint32_t ret = 0;
3740  	int pstate;
3741  
3742  	DEVRLOCK(cgpu, pstate);
3743  
3744  	if (cgpu->usbdev)
3745  		ret = cgpu->usbdev->bufamt;
3746  
3747  	DEVRUNLOCK(cgpu, pstate);
3748  
3749  	return ret;
3750  }
3751  
3752  /*
3753   * The value returned (0) when usbdev is NULL
3754   * doesn't matter since it also means the next call to
3755   * any usbutils function will fail with a nodev
3756   * N.B. this is to get the interface number to use in a control_transfer
3757   * which for some devices isn't actually the interface number
3758   */
3759  int _usb_interface(struct cgpu_info *cgpu, int intinfo)
3760  {
3761  	int interface = 0;
3762  	int pstate;
3763  
3764  	DEVRLOCK(cgpu, pstate);
3765  
3766  	if (cgpu->usbdev)
3767  		interface = cgpu->usbdev->found->intinfos[intinfo].ctrl_transfer;
3768  
3769  	DEVRUNLOCK(cgpu, pstate);
3770  
3771  	return interface;
3772  }
3773  
3774  enum sub_ident usb_ident(struct cgpu_info *cgpu)
3775  {
3776  	enum sub_ident ident = IDENT_UNK;
3777  	int pstate;
3778  
3779  	DEVRLOCK(cgpu, pstate);
3780  
3781  	if (cgpu->usbdev)
3782  		ident = cgpu->usbdev->ident;
3783  
3784  	DEVRUNLOCK(cgpu, pstate);
3785  
3786  	return ident;
3787  }
3788  
3789  // Need to set all devices with matching usbdev
3790  void usb_set_dev_start(struct cgpu_info *cgpu)
3791  {
3792  	struct cg_usb_device *cgusb;
3793  	struct cgpu_info *cgpu2;
3794  	struct timeval now;
3795  	int pstate;
3796  
3797  	DEVWLOCK(cgpu, pstate);
3798  
3799  	cgusb = cgpu->usbdev;
3800  
3801  	// If the device wasn't dropped
3802  	if (cgusb != NULL) {
3803  		int i;
3804  
3805  		cgtime(&now);
3806  
3807  		for (i = 0; i < total_devices; i++) {
3808  			cgpu2 = get_devices(i);
3809  			if (cgpu2->usbdev == cgusb)
3810  				copy_time(&(cgpu2->dev_start_tv), &now);
3811  		}
3812  	}
3813  
3814  	DEVWUNLOCK(cgpu, pstate);
3815  }
3816  
3817  void usb_cleanup(void)
3818  {
3819  	struct cgpu_info *cgpu;
3820  	int count, pstate;
3821  	int i;
3822  
3823  	hotplug_time = 0;
3824  
3825  	cgsleep_ms(10);
3826  
3827  	count = 0;
3828  	for (i = 0; i < total_devices; i++) {
3829  		cgpu = devices[i];
3830  		switch (cgpu->drv->drv_id) {
3831  			case DRIVER_bflsc:
3832  			case DRIVER_bitforce:
3833  			case DRIVER_bitfury:
3834  			case DRIVER_cointerra:
3835  			case DRIVER_drillbit:
3836  			case DRIVER_modminer:
3837  			case DRIVER_icarus:
3838  			case DRIVER_avalon:
3839  			case DRIVER_avalon2:
3840  			case DRIVER_avalon4:
3841  			case DRIVER_avalon7:
3842  			case DRIVER_avalon8:
3843  			case DRIVER_avalonm:
3844  			case DRIVER_klondike:
3845  			case DRIVER_hashfast:
3846  				DEVWLOCK(cgpu, pstate);
3847  				release_cgpu(cgpu);
3848  				DEVWUNLOCK(cgpu, pstate);
3849  				count++;
3850  				break;
3851  			default:
3852  				break;
3853  		}
3854  	}
3855  
3856  	/*
3857  	 * Must attempt to wait for the resource thread to release coz
3858  	 * during a restart it won't automatically release them in linux
3859  	 */
3860  	if (count) {
3861  		struct timeval start, now;
3862  
3863  		cgtime(&start);
3864  		while (42) {
3865  			cgsleep_ms(50);
3866  
3867  			mutex_lock(&cgusbres_lock);
3868  
3869  			if (!res_work_head)
3870  				break;
3871  
3872  			cgtime(&now);
3873  			if (tdiff(&now, &start) > 0.366) {
3874  				applog(LOG_WARNING,
3875  					"usb_cleanup gave up waiting for resource thread");
3876  				break;
3877  			}
3878  
3879  			mutex_unlock(&cgusbres_lock);
3880  		}
3881  		mutex_unlock(&cgusbres_lock);
3882  	}
3883  
3884  	cgsem_destroy(&usb_resource_sem);
3885  }
3886  
3887  #define DRIVER_COUNT_FOUND(X) if (X##_drv.name && strcasecmp(ptr, X##_drv.name) == 0) { \
3888  	drv_count[X##_drv.drv_id].limit = lim; \
3889  	found = true; \
3890  	}
3891  void usb_initialise(void)
3892  {
3893  	char *fre, *ptr, *comma, *colon;
3894  	int bus, dev, lim, i;
3895  	bool found;
3896  
3897  	INIT_LIST_HEAD(&ut_list);
3898  
3899  	for (i = 0; i < DRIVER_MAX; i++) {
3900  		drv_count[i].count = 0;
3901  		drv_count[i].limit = 999999;
3902  	}
3903  
3904  	cgusb_check_init();
3905  
3906  	if (opt_usb_select && *opt_usb_select) {
3907  		// Absolute device limit
3908  		if (*opt_usb_select == ':') {
3909  			total_limit = atoi(opt_usb_select+1);
3910  			if (total_limit < 0)
3911  				quit(1, "Invalid --usb total limit");
3912  		// Comma list of bus:dev devices to match
3913  		} else if (isdigit(*opt_usb_select)) {
3914  			fre = ptr = strdup(opt_usb_select);
3915  			do {
3916  				comma = strchr(ptr, ',');
3917  				if (comma)
3918  					*(comma++) = '\0';
3919  
3920  				colon = strchr(ptr, ':');
3921  				if (!colon)
3922  					quit(1, "Invalid --usb bus:dev missing ':'");
3923  
3924  				*(colon++) = '\0';
3925  
3926  				if (!isdigit(*ptr))
3927  					quit(1, "Invalid --usb bus:dev - bus must be a number");
3928  
3929  				if (!isdigit(*colon) && *colon != '*')
3930  					quit(1, "Invalid --usb bus:dev - dev must be a number or '*'");
3931  
3932  				bus = atoi(ptr);
3933  				if (bus <= 0)
3934  					quit(1, "Invalid --usb bus:dev - bus must be > 0");
3935  
3936  				if (*colon == '*')
3937  					dev = -1;
3938  				else {
3939  					dev = atoi(colon);
3940  					if (dev <= 0)
3941  						quit(1, "Invalid --usb bus:dev - dev must be > 0 or '*'");
3942  				}
3943  
3944  				busdev = cgrealloc(busdev, sizeof(*busdev) * (++busdev_count));
3945  				busdev[busdev_count-1].bus_number = bus;
3946  				busdev[busdev_count-1].device_address = dev;
3947  
3948  				ptr = comma;
3949  			} while (ptr);
3950  			free(fre);
3951  		// Comma list of DRV:limit
3952  		} else {
3953  			fre = ptr = strdup(opt_usb_select);
3954  			do {
3955  				comma = strchr(ptr, ',');
3956  				if (comma)
3957  					*(comma++) = '\0';
3958  
3959  				colon = strchr(ptr, ':');
3960  				if (!colon)
3961  					quit(1, "Invalid --usb DRV:limit missing ':'");
3962  
3963  				*(colon++) = '\0';
3964  
3965  				if (!isdigit(*colon))
3966  					quit(1, "Invalid --usb DRV:limit - limit must be a number");
3967  
3968  				lim = atoi(colon);
3969  				if (lim < 0)
3970  					quit(1, "Invalid --usb DRV:limit - limit must be >= 0");
3971  
3972  				found = false;
3973  				/* Use the DRIVER_PARSE_COMMANDS macro to iterate
3974  				 * over all the drivers. */
3975  				DRIVER_PARSE_COMMANDS(DRIVER_COUNT_FOUND)
3976  				if (!found)
3977  					quit(1, "Invalid --usb DRV:limit - unknown DRV='%s'", ptr);
3978  
3979  				ptr = comma;
3980  			} while (ptr);
3981  			free(fre);
3982  		}
3983  	}
3984  }
3985  
3986  #ifndef WIN32
3987  #include <errno.h>
3988  #include <unistd.h>
3989  #include <sys/stat.h>
3990  #include <sys/file.h>
3991  #include <fcntl.h>
3992  
3993  #ifndef __APPLE__
3994  union semun {
3995  	int val;
3996  	struct semid_ds *buf;
3997  	unsigned short *array;
3998  	struct seminfo *__buf;
3999  };
4000  #endif
4001  
4002  #else
4003  static LPSECURITY_ATTRIBUTES unsec(LPSECURITY_ATTRIBUTES sec)
4004  {
4005  	SECURITY_DESCRIPTOR *sd = (PSECURITY_DESCRIPTOR)(sec->lpSecurityDescriptor);
4006  	FreeSid(sd->Group);
4007  	free(sec->lpSecurityDescriptor);
4008  	free(sec);
4009  	return NULL;
4010  }
4011  
4012  static LPSECURITY_ATTRIBUTES mksec(const char *dname, uint8_t bus_number, uint8_t device_address)
4013  {
4014  	SID_IDENTIFIER_AUTHORITY SIDAuthWorld = {SECURITY_WORLD_SID_AUTHORITY};
4015  	PSID gsid = NULL;
4016  	LPSECURITY_ATTRIBUTES sec_att = NULL;
4017  	PSECURITY_DESCRIPTOR sec_des = NULL;
4018  
4019  	sec_des = cgmalloc(SECURITY_DESCRIPTOR_MIN_LENGTH);
4020  
4021  	if (!InitializeSecurityDescriptor(sec_des, SECURITY_DESCRIPTOR_REVISION)) {
4022  		applog(LOG_ERR,
4023  			"MTX: %s (%d:%d) USB failed to init secdes err (%d)",
4024  			dname, (int)bus_number, (int)device_address,
4025  			(int)GetLastError());
4026  		free(sec_des);
4027  		return NULL;
4028  	}
4029  
4030  	if (!SetSecurityDescriptorDacl(sec_des, TRUE, NULL, FALSE)) {
4031  		applog(LOG_ERR,
4032  			"MTX: %s (%d:%d) USB failed to secdes dacl err (%d)",
4033  			dname, (int)bus_number, (int)device_address,
4034  			(int)GetLastError());
4035  		free(sec_des);
4036  		return NULL;
4037  	}
4038  
4039  	if(!AllocateAndInitializeSid(&SIDAuthWorld, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &gsid)) {
4040  		applog(LOG_ERR,
4041  			"MTX: %s (%d:%d) USB failed to create gsid err (%d)",
4042  			dname, (int)bus_number, (int)device_address,
4043  			(int)GetLastError());
4044  		free(sec_des);
4045  		return NULL;
4046  	}
4047  
4048  	if (!SetSecurityDescriptorGroup(sec_des, gsid, FALSE)) {
4049  		applog(LOG_ERR,
4050  			"MTX: %s (%d:%d) USB failed to secdes grp err (%d)",
4051  			dname, (int)bus_number, (int)device_address,
4052  			(int)GetLastError());
4053  		FreeSid(gsid);
4054  		free(sec_des);
4055  		return NULL;
4056  	}
4057  
4058  	sec_att = cgmalloc(sizeof(*sec_att));
4059  
4060  	sec_att->nLength = sizeof(*sec_att);
4061  	sec_att->lpSecurityDescriptor = sec_des;
4062  	sec_att->bInheritHandle = FALSE;
4063  
4064  	return sec_att;
4065  }
4066  #endif
4067  
4068  // Any errors should always be printed since they will rarely if ever occur
4069  // and thus it is best to always display them
4070  static bool resource_lock(const char *dname, uint8_t bus_number, uint8_t device_address)
4071  {
4072  	applog(LOG_DEBUG, "USB res lock %s %d-%d", dname, (int)bus_number, (int)device_address);
4073  #ifdef WIN32
4074  	struct cgpu_info *cgpu;
4075  	LPSECURITY_ATTRIBUTES sec;
4076  	HANDLE usbMutex;
4077  	char name[64];
4078  	DWORD res;
4079  	int i;
4080  
4081  	if (is_in_use_bd(bus_number, device_address))
4082  		return false;
4083  
4084  	snprintf(name, sizeof(name), "cg-usb-%d-%d", (int)bus_number, (int)device_address);
4085  
4086  	sec = mksec(dname, bus_number, device_address);
4087  	if (!sec)
4088  		return false;
4089  
4090  	usbMutex = CreateMutex(sec, FALSE, name);
4091  	if (usbMutex == NULL) {
4092  		applog(LOG_ERR,
4093  			"MTX: %s USB failed to get '%s' err (%d)",
4094  			dname, name, (int)GetLastError());
4095  		sec = unsec(sec);
4096  		return false;
4097  	}
4098  
4099  	res = WaitForSingleObject(usbMutex, 0);
4100  
4101  	switch(res) {
4102  		case WAIT_OBJECT_0:
4103  		case WAIT_ABANDONED:
4104  			// Am I using it already?
4105  			for (i = 0; i < total_devices; i++) {
4106  				cgpu = get_devices(i);
4107  				if (cgpu->usbinfo.bus_number == bus_number &&
4108  				    cgpu->usbinfo.device_address == device_address &&
4109  				    cgpu->usbinfo.nodev == false) {
4110  					if (ReleaseMutex(usbMutex)) {
4111  						applog(LOG_WARNING,
4112  							"MTX: %s USB can't get '%s' - device in use",
4113  							dname, name);
4114  						goto fail;
4115  					}
4116  					applog(LOG_ERR,
4117  						"MTX: %s USB can't get '%s' - device in use - failure (%d)",
4118  						dname, name, (int)GetLastError());
4119  					goto fail;
4120  				}
4121  			}
4122  			break;
4123  		case WAIT_TIMEOUT:
4124  			if (!hotplug_mode)
4125  				applog(LOG_WARNING,
4126  					"MTX: %s USB failed to get '%s' - device in use",
4127  					dname, name);
4128  			goto fail;
4129  		case WAIT_FAILED:
4130  			applog(LOG_ERR,
4131  				"MTX: %s USB failed to get '%s' err (%d)",
4132  				dname, name, (int)GetLastError());
4133  			goto fail;
4134  		default:
4135  			applog(LOG_ERR,
4136  				"MTX: %s USB failed to get '%s' unknown reply (%d)",
4137  				dname, name, (int)res);
4138  			goto fail;
4139  	}
4140  
4141  	add_in_use(bus_number, device_address, false);
4142  	in_use_store_ress(bus_number, device_address, (void *)usbMutex, (void *)sec);
4143  
4144  	return true;
4145  fail:
4146  	CloseHandle(usbMutex);
4147  	sec = unsec(sec);
4148  	return false;
4149  #else
4150  	char name[64];
4151  	int fd;
4152  
4153  	if (is_in_use_bd(bus_number, device_address))
4154  		return false;
4155  
4156  	snprintf(name, sizeof(name), "/tmp/cgminer-usb-%d-%d", (int)bus_number, (int)device_address);
4157  	fd = open(name, O_CREAT|O_RDONLY, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
4158  	if (fd == -1) {
4159  		applog(LOG_ERR, "%s USB open failed '%s' err (%d) %s",
4160  		       dname, name, errno, strerror(errno));
4161  		return false;
4162  	}
4163  	if (flock(fd, LOCK_EX | LOCK_NB)) {
4164  		applog(LOG_INFO, "%s USB failed to get '%s' - device in use",
4165  		       dname, name);
4166  		close(fd);
4167  		return false;
4168  	}
4169  
4170  	add_in_use(bus_number, device_address, false);
4171  	in_use_store_fd(bus_number, device_address, fd);
4172  	return true;
4173  #endif
4174  }
4175  
4176  // Any errors should always be printed since they will rarely if ever occur
4177  // and thus it is best to always display them
4178  static void resource_unlock(const char *dname, uint8_t bus_number, uint8_t device_address)
4179  {
4180  	applog(LOG_DEBUG, "USB res unlock %s %d-%d", dname, (int)bus_number, (int)device_address);
4181  
4182  #ifdef WIN32
4183  	LPSECURITY_ATTRIBUTES sec = NULL;
4184  	HANDLE usbMutex = NULL;
4185  	char name[64];
4186  
4187  	snprintf(name, sizeof(name), "cg-usb-%d-%d", (int)bus_number, (int)device_address);
4188  
4189  	in_use_get_ress(bus_number, device_address, (void **)(&usbMutex), (void **)(&sec));
4190  
4191  	if (!usbMutex || !sec)
4192  		goto fila;
4193  
4194  	if (!ReleaseMutex(usbMutex))
4195  		applog(LOG_ERR,
4196  			"MTX: %s USB failed to release '%s' err (%d)",
4197  			dname, name, (int)GetLastError());
4198  
4199  fila:
4200  
4201  	if (usbMutex)
4202  		CloseHandle(usbMutex);
4203  	if (sec)
4204  		unsec(sec);
4205  	remove_in_use(bus_number, device_address);
4206  	return;
4207  #else
4208  	char name[64];
4209  	int fd;
4210  
4211  	snprintf(name, sizeof(name), "/tmp/cgminer-usb-%d-%d", (int)bus_number, (int)device_address);
4212  
4213  	fd = in_use_get_fd(bus_number, device_address);
4214  	if (fd < 0)
4215  		return;
4216  	remove_in_use(bus_number, device_address);
4217  	close(fd);
4218  	unlink(name);
4219  	return;
4220  #endif
4221  }
4222  
4223  static void resource_process()
4224  {
4225  	struct resource_work *res_work = NULL;
4226  	struct resource_reply *res_reply = NULL;
4227  	bool ok;
4228  
4229  	applog(LOG_DEBUG, "RES: %s (%d:%d) lock=%d",
4230  			res_work_head->dname,
4231  			(int)res_work_head->bus_number,
4232  			(int)res_work_head->device_address,
4233  			res_work_head->lock);
4234  
4235  	if (res_work_head->lock) {
4236  		ok = resource_lock(res_work_head->dname,
4237  					res_work_head->bus_number,
4238  					res_work_head->device_address);
4239  
4240  		applog(LOG_DEBUG, "RES: %s (%d:%d) lock ok=%d",
4241  				res_work_head->dname,
4242  				(int)res_work_head->bus_number,
4243  				(int)res_work_head->device_address,
4244  				ok);
4245  
4246  		res_reply = cgcalloc(1, sizeof(*res_reply));
4247  
4248  		res_reply->bus_number = res_work_head->bus_number;
4249  		res_reply->device_address = res_work_head->device_address;
4250  		res_reply->got = ok;
4251  		res_reply->next = res_reply_head;
4252  
4253  		res_reply_head = res_reply;
4254  	}
4255  	else
4256  		resource_unlock(res_work_head->dname,
4257  				res_work_head->bus_number,
4258  				res_work_head->device_address);
4259  
4260  	res_work = res_work_head;
4261  	res_work_head = res_work_head->next;
4262  	free(res_work);
4263  }
4264  
4265  void *usb_resource_thread(void __maybe_unused *userdata)
4266  {
4267  	pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
4268  
4269  	RenameThread("USBResource");
4270  
4271  	applog(LOG_DEBUG, "RES: thread starting");
4272  
4273  	while (42) {
4274  		/* Wait to be told we have work to do */
4275  		cgsem_wait(&usb_resource_sem);
4276  
4277  		mutex_lock(&cgusbres_lock);
4278  		while (res_work_head)
4279  			resource_process();
4280  		mutex_unlock(&cgusbres_lock);
4281  	}
4282  
4283  	return NULL;
4284  }
4285  
4286  void initialise_usblocks(void)
4287  {
4288  	mutex_init(&cgusb_lock);
4289  	mutex_init(&cgusbres_lock);
4290  	cglock_init(&cgusb_fd_lock);
4291  }