break;
}
+ /* Get the device back to a known mode
+ */
+ int times = 0;
+ uint8_t mode;
+
+ /* In some modes, the device fails to return the current
+ * mode when requested, so try a couple of times
+ */
+ for (;;) {
+ err = stlink_usb_current_mode(h, &mode);
+
+ if (err == ERROR_OK) {
+ LOG_DEBUG("mode %d", mode);
+ break;
+ }
+ LOG_ERROR("current mode failed");
+ if (++times == 3)
+ goto error_open;
+ }
+
+ enum stlink_mode emode;
+
+ /* try to exit current mode */
+ switch (mode) {
+ case STLINK_DEV_DFU_MODE:
+ emode = STLINK_MODE_DFU;
+ break;
+ case STLINK_DEV_DEBUG_MODE:
+ emode = STLINK_MODE_DEBUG_SWD;
+ break;
+ case STLINK_DEV_SWIM_MODE:
+ emode = STLINK_MODE_DEBUG_SWIM;
+ break;
+ case STLINK_DEV_BOOTLOADER_MODE:
+ case STLINK_DEV_MASS_MODE:
+ default:
+ emode = STLINK_MODE_UNKNOWN;
+ break;
+ }
+
+ LOG_DEBUG("exit mode %d", emode);
+ if (emode != STLINK_MODE_UNKNOWN) {
+
+ err = stlink_usb_mode_leave(h, emode);
+
+ if (err != ERROR_OK)
+ goto error_open;
+ }
+
/* get the device version */
err = stlink_usb_version(h);