flashrom.c: implement chip restore callback registration

Allows drivers to register a callback function to reset the
chip state once programming has finished. This is used by
the s25f driver added in a later patch, which needs to change
the chip's sector layout to be able to write to the entire flash.

Adapted from cros flashrom at
`9c4c9a56b6a0370b383df9c75d71b3bd469e672d`.

Change-Id: I2a522dc1fd3952793fbcad70afc6dd43850fbbc5
Signed-off-by: Nikolai Artemiev <nartemiev@google.com>
Original-Reviewed-on: https://review.coreboot.org/c/flashrom/+/47276
Original-Reviewed-by: Edward O'Callaghan <quasisec@chromium.org>
Reviewed-on: https://review.coreboot.org/c/flashrom-stable/+/70940
Reviewed-by: Nico Huber <nico.h@gmx.de>
Reviewed-by: Nico Huber <nico.h@gmx.de>
diff --git a/flashrom.c b/flashrom.c
index 61e9530..430c871 100644
--- a/flashrom.c
+++ b/flashrom.c
@@ -526,6 +526,34 @@
 	return 0;
 }
 
+int register_chip_restore(chip_restore_fn_cb_t func,
+			  struct flashctx *flash, uint8_t status)
+{
+	if (flash->chip_restore_fn_count >= MAX_CHIP_RESTORE_FUNCTIONS) {
+		msg_perr("Tried to register more than %i chip restore"
+		         " functions.\n", MAX_CHIP_RESTORE_FUNCTIONS);
+		return 1;
+	}
+	flash->chip_restore_fn[flash->chip_restore_fn_count].func = func;
+	flash->chip_restore_fn[flash->chip_restore_fn_count].status = status;
+	flash->chip_restore_fn_count++;
+
+	return 0;
+}
+
+static int deregister_chip_restore(struct flashctx *flash)
+{
+	int rc = 0;
+
+	while (flash->chip_restore_fn_count > 0) {
+		int i = --flash->chip_restore_fn_count;
+		rc |= flash->chip_restore_fn[i].func(
+			flash, flash->chip_restore_fn[i].status);
+	}
+
+	return rc;
+}
+
 int programmer_init(enum programmer prog, const char *param)
 {
 	int ret;
@@ -2195,6 +2223,9 @@
 	if (map_flash(flash) != 0)
 		return 1;
 
+	/* Initialize chip_restore_fn_count before chip unlock calls. */
+	flash->chip_restore_fn_count = 0;
+
 	/* Given the existence of read locks, we want to unlock for read,
 	   erase and write. */
 	if (flash->chip->unlock)
@@ -2231,6 +2262,7 @@
 
 void finalize_flash_access(struct flashctx *const flash)
 {
+	deregister_chip_restore(flash);
 	unmap_flash(flash);
 }