trunks: Do not invoke USB clear functions, unless necessary

Invoking these functions in case USB was not initialized seems to be
working fine in the chroor, but causes lock ups when using libftdi in
Ubuntu (as opposed to libftdi1).

Add a filed to the MPSSE structure to keep track of the interface
creation progress. In fact this field was present in the original
usbmpsse package, but was dropped at some point along the way.

TEST=program does not crash on start any more, connects to the UDB
BUG=chrome-os-partner:43025
TEST=manual

Change-Id: Id0f9f327fd8847908e25611cf96818ab6d398273
Signed-off-by: Vadim Bendebury <vbendeb@chromium.org>
Reviewed-on: https://chromium-review.googlesource.com/295550
Reviewed-by: Bill Richardson <wfrichar@chromium.org>
diff --git a/ftdi/mpsse.c b/ftdi/mpsse.c
index adb1388..a516033 100644
--- a/ftdi/mpsse.c
+++ b/ftdi/mpsse.c
@@ -113,7 +113,7 @@
                                 const char* description,
                                 const char* serial,
                                 int index) {
-  int status = 0, success = 0;
+  int status = 0;
   struct mpsse_context* mpsse = NULL;
 
   mpsse = malloc(sizeof(struct mpsse_context));
@@ -164,7 +164,7 @@
 
         if (SetClock(mpsse, freq) == MPSSE_OK) {
           if (SetMode(mpsse, endianess) == MPSSE_OK) {
-            success = 1;
+            mpsse->opened = 1;
 
             /* Give the chip a few mS to initialize */
             usleep(SETUP_DELAY);
@@ -182,12 +182,12 @@
         /* Skip the setup functions if we're just operating in BITBANG mode
          */
         if (!ftdi_set_bitmode(&mpsse->ftdi, 0xFF, BITMODE_BITBANG))
-          success = 1;
+          mpsse->opened = 1;
       }
     }
   }
 
-  if (mpsse && !success) {
+  if (mpsse && !mpsse->opened) {
     Close(mpsse);
     mpsse = NULL;
   }
@@ -207,8 +207,11 @@
   if (!mpsse)
     return;
 
-  ftdi_set_bitmode(&mpsse->ftdi, 0, BITMODE_RESET);
-  ftdi_usb_close(&mpsse->ftdi);
+  if (mpsse->opened) {
+    /* Shut these down only if initialization succeeded before. */
+    ftdi_set_bitmode(&mpsse->ftdi, 0, BITMODE_RESET);
+    ftdi_usb_close(&mpsse->ftdi);
+  }
   ftdi_deinit(&mpsse->ftdi);
   free(mpsse);
 }
diff --git a/ftdi/mpsse.h b/ftdi/mpsse.h
index 0e212bf..dd00a43 100644
--- a/ftdi/mpsse.h
+++ b/ftdi/mpsse.h
@@ -149,7 +149,8 @@
   int pid;
   int clock;
   int xsize;
-  int endianess;
+  uint8_t endianess;
+  uint8_t opened;
   uint8_t tris;
   uint8_t pstart;
   uint8_t pstop;