4615a1
diff -up ./src/ccid_usb.c.max_cpu_bug ./src/ccid_usb.c
4615a1
--- ./src/ccid_usb.c.max_cpu_bug	2012-06-22 00:25:20.000000000 -0700
4615a1
+++ ./src/ccid_usb.c	2016-06-29 17:17:11.284337349 -0700
4615a1
@@ -154,6 +154,36 @@ status_t OpenUSB(unsigned int reader_ind
4615a1
 } /* OpenUSB */
4615a1
 
4615a1
 
4615a1
+ /*****************************************************************************
4615a1
+  *
4615a1
+  *                                      close_libusb_if_needed
4615a1
+  *                                      (pulled from upstream ccid_usb)
4615a1
+  *
4615a1
+  ****************************************************************************/
4615a1
+ static void close_libusb_if_needed(void)
4615a1
+ {
4615a1
+         int i, to_exit = TRUE;
4615a1
+ 
4615a1
+         if (NULL == ctx)
4615a1
+                 return;
4615a1
+ 
4615a1
+         /* if at least 1 reader is still in use we do not exit libusb */
4615a1
+         for (i=0; i
4615a1
+         {
4615a1
+                 if (usbDevice[i].dev_handle != NULL)
4615a1
+                         to_exit = FALSE;
4615a1
+         }
4615a1
+ 
4615a1
+         if (to_exit)
4615a1
+         {
4615a1
+                 DEBUG_INFO("libusb_exit");
4615a1
+                 libusb_exit(ctx);
4615a1
+                 ctx = NULL;
4615a1
+         }
4615a1
+} /* close_libusb_if_needed */
4615a1
+ 
4615a1
+
4615a1
+
4615a1
 /*****************************************************************************
4615a1
  *
4615a1
  *					OpenUSBByName
4615a1
@@ -609,8 +639,8 @@ again:
4615a1
 end:
4615a1
 	if (usbDevice[reader_index].dev_handle == NULL)
4615a1
 	{
4615a1
-		/* does not work for libusb <= 1.0.8 */
4615a1
-		/* libusb_exit(ctx); */
4615a1
+	    close_libusb_if_needed();
4615a1
+
4615a1
 		if (claim_failed)
4615a1
 			return STATUS_COMM_ERROR;
4615a1
 		return STATUS_NO_SUCH_DEVICE;
4615a1
@@ -628,6 +658,9 @@ end1:
4615a1
 	/* free bundle list */
4615a1
 	bundleRelease(&plist);
4615a1
 
4615a1
+	if (return_value != STATUS_SUCCESS)
4615a1
+		close_libusb_if_needed();
4615a1
+
4615a1
 	return return_value;
4615a1
 } /* OpenUSBByName */
4615a1
 
4615a1
@@ -776,13 +809,13 @@ status_t CloseUSB(unsigned int reader_in
4615a1
 			usbDevice[reader_index].interface);
4615a1
 		(void)libusb_close(usbDevice[reader_index].dev_handle);
4615a1
 
4615a1
-		/* does not work for libusb <= 1.0.8 */
4615a1
-		/* libusb_exit(ctx); */
4615a1
 	}
4615a1
 
4615a1
 	/* mark the resource unused */
4615a1
 	usbDevice[reader_index].dev_handle = NULL;
4615a1
 	usbDevice[reader_index].interface = 0;
4615a1
+	
4615a1
+	close_libusb_if_needed();
4615a1
 
4615a1
 	return STATUS_SUCCESS;
4615a1
 } /* CloseUSB */