UPSTREAM: stlinkv3_spi.c: Clean up properly on all init error paths

If register_spi_master() fails, going to init exit cleanup is not
needed because at that point shutdown function has already been
registered and it does the job.

BUG=b:185191942
BRANCH=none
TEST=builds

Original-Change-Id: I9fabf48068635593bc86006c9642d8569eee8447
Original-Signed-off-by: Anastasia Klimchuk <aklm@chromium.org>
Original-Reviewed-on: https://review.coreboot.org/c/flashrom/+/54190
Original-Tested-by: build bot (Jenkins) <no-reply@coreboot.org>
Original-Reviewed-by: Edward O'Callaghan <quasisec@chromium.org>
Original-Reviewed-by: Miklós Márton <martonmiklosqdev@gmail.com>
(cherry picked from commit cee470ecefbfdf7a1d08cb9d5cf3824c0f76e5c5)

Change-Id: Id79436e78011c4dac9001e37b0cc15a65058fd27
Signed-off-by: Edward O'Callaghan <quasisec@google.com>
Reviewed-on: https://chromium-review.googlesource.com/c/chromiumos/third_party/flashrom/+/2908274
Reviewed-by: Edward O'Callaghan <quasisec@chromium.org>
Reviewed-by: Sean Paul <seanpaul@chromium.org>
Commit-Queue: Edward O'Callaghan <quasisec@chromium.org>
Tested-by: Edward O'Callaghan <quasisec@chromium.org>
diff --git a/stlinkv3_spi.c b/stlinkv3_spi.c
index 7712ec2..100a94b 100644
--- a/stlinkv3_spi.c
+++ b/stlinkv3_spi.c
@@ -464,6 +464,7 @@
 	char *speed_str = NULL;
 	char *serialno = NULL;
 	char *endptr = NULL;
+	int ret = 1;
 
 	libusb_init(&usb_ctx);
 	if (!usb_ctx) {
@@ -485,7 +486,7 @@
 		else
 			msg_perr("Could not find any connected STLINK-V3\n");
 		free(serialno);
-		goto err_exit;
+		goto init_err_exit;
 	}
 	free(serialno);
 
@@ -498,23 +499,30 @@
 			msg_perr("Please pass the parameter "
 				 "with a simple non-zero number in kHz\n");
 			free(speed_str);
-			return -1;
+			ret = -1;
+			goto init_err_exit;
 		}
 		free(speed_str);
 	}
 
 	if (stlinkv3_spi_open(sck_freq_kHz))
-		goto err_exit;
+		goto init_err_exit;
 
 	if (register_shutdown(stlinkv3_spi_shutdown, NULL))
-		goto err_exit;
+		goto init_err_cleanup_exit;
 
 	if (register_spi_master(&spi_programmer_stlinkv3, NULL))
-		goto err_exit;
+		return 1; /* shutdown function does cleanup */
 
 	return 0;
 
-err_exit:
-	libusb_exit(usb_ctx);
+init_err_cleanup_exit:
+	stlinkv3_spi_shutdown(NULL);
 	return 1;
+
+init_err_exit:
+	if (stlinkv3_handle)
+		libusb_close(stlinkv3_handle);
+	libusb_exit(usb_ctx);
+	return ret;
 }