dediprog: Separate shutdown from failed init cleanup

Shutdown function was covering two different jobs here: 1) the actual
shutdown which is run at the end of the driver's lifecycle and
2) cleanup in cases when initialisation failed. Now, shutdown is only
doing its main job (#1), and the driver itself is doing cleanup
when init fails (#2).

The good thing is that now resources are released/closed immediately
in cases when init fails (vs shutdown function which was run at some
point later), and the driver leaves clean space after itself if init
fails.

And very importantly this unlocks API change which plans to move
register_shutdown inside register master API, see
https://review.coreboot.org/c/flashrom/+/51761

Change-Id: I3273da907614a042d50090338c337dfd64695354
Signed-off-by: Anastasia Klimchuk <aklm@chromium.org>
Original-Reviewed-on: https://review.coreboot.org/c/flashrom/+/55887
Original-Reviewed-by: Angel Pons <th3fanbus@gmail.com>
Original-Reviewed-by: Nico Huber <nico.h@gmx.de>
Reviewed-on: https://review.coreboot.org/c/flashrom-stable/+/71398
Reviewed-by: Nico Huber <nico.h@gmx.de>
Reviewed-by: Angel Pons <th3fanbus@gmail.com>
Tested-by: build bot (Jenkins) <no-reply@coreboot.org>
diff --git a/dediprog.c b/dediprog.c
index aa1923b..0dadf37 100644
--- a/dediprog.c
+++ b/dediprog.c
@@ -1227,16 +1227,13 @@
 		msg_pinfo("Using dediprog id SF%06d.\n", found_id);
 	}
 
-	if (register_shutdown(dediprog_shutdown, NULL))
-		return 1;
-
 	/* Try reading the devicestring. If that fails and the device is old (FW < 6.0.0, which we can not know)
 	 * then we need to try the "set voltage" command and then attempt to read the devicestring again. */
 	if (dediprog_check_devicestring()) {
 		if (dediprog_set_voltage())
-			return 1;
+			goto init_err_cleanup_exit;
 		if (dediprog_check_devicestring())
-			return 1;
+			goto init_err_cleanup_exit;
 	}
 
 	/* SF100/SF200 uses one in/out endpoint, SF600 uses separate in/out endpoints */
@@ -1261,11 +1258,11 @@
 	    dediprog_set_spi_speed(spispeed_idx) ||
 	    dediprog_set_spi_voltage(millivolt)) {
 		dediprog_set_leds(LED_ERROR);
-		return 1;
+		goto init_err_cleanup_exit;
 	}
 
 	if (dediprog_standalone_mode())
-		return 1;
+		goto init_err_cleanup_exit;
 
 	if ((dediprog_devicetype == DEV_SF100) ||
 	    (dediprog_devicetype == DEV_SF600 && protocol() == PROTOCOL_V3))
@@ -1274,10 +1271,17 @@
 	if (protocol() >= PROTOCOL_V2)
 		spi_master_dediprog.features |= SPI_MASTER_4BA;
 
+	if (register_shutdown(dediprog_shutdown, NULL))
+		goto init_err_cleanup_exit;
+
 	if (register_spi_master(&spi_master_dediprog) || dediprog_set_leds(LED_NONE))
-		return 1;
+		return 1; /* shutdown function does cleanup */
 
 	return 0;
+
+init_err_cleanup_exit:
+	dediprog_shutdown(NULL);
+	return 1;
 }
 
 const struct programmer_entry programmer_dediprog = {