util/ifdtool: Refactor GPR0 Unlock Implemetation

This patch refactors GPR0 unlock function to add few important
logic as below
1. Perform GPR0 unlock if GPR0 is locked.
2. While unlocking dump the GPRD PCH strap details
3. Additionally, print the GPR start and end range if GPR0
   protection is enabled.

TEST=Able to test GPR0 protection on google/rex and google/yahiko.

Exp 1: Trying to unlock GPR0 protection for a locked image

> ifdtool  -p mtl -g image.bin -O image.bin_unlock
File image.bin is 33554432 bytes
Value at GPRD offset (64) is 0x83220004
--------- GPR0 Protected Range --------------
Start address = 0x00004000
End address = 0x00322fff
Writing new image to image.bin_unlock

Exp 2: Trying to unlock GPR0 protection for a unlocked image

> ifdtool  -p mtl -g image.bin_unlock -O image.bin_unlock

File image.bin_unlock is 33554432 bytes
GPR0 protection is already disabled

Change-Id: Id35ebdefe83182ad7a3e735bdd2998baa0ec3ed7
Signed-off-by: Subrata Banik <subratabanik@google.com>
Reviewed-on: https://review.coreboot.org/c/coreboot/+/80216
Reviewed-by: YH Lin <yueherngl@google.com>
Tested-by: build bot (Jenkins) <no-reply@coreboot.org>
Reviewed-by: Nick Vaccaro <nvaccaro@google.com>
diff --git a/util/ifdtool/ifdtool.c b/util/ifdtool/ifdtool.c
index 191b321..07cc268 100644
--- a/util/ifdtool/ifdtool.c
+++ b/util/ifdtool/ifdtool.c
@@ -1577,10 +1577,28 @@
 		fprintf(stderr, "Disabling GPR0 not supported on this platform\n");
 		exit(EXIT_FAILURE);
 	}
+	/* If bit 31 is set then GPR0 protection is enable */
+	bool gpr0_status = fpsba->pchstrp[gpr0_offset] & 0x80000000;
+	if (!gpr0_status) {
+		printf("GPR0 protection is already disabled\n");
+		return;
+	}
 
+	printf("Value at GPRD offset (%d) is 0x%08x\n", gpr0_offset, fpsba->pchstrp[gpr0_offset]);
+	printf("--------- GPR0 Protected Range --------------\n");
+	/*
+	 * Start Address: bit 0-15 of the GPRD represents the protected region start address,
+	 * where bit 0-11 of the start address are assumed to be zero.
+	 */
+	printf("Start address = 0x%08x\n", (fpsba->pchstrp[gpr0_offset] & 0xffff) << 12);
+	/*
+	 * End Address: bit 16-30 of the GPRD represents the protected region end address,
+	 * where bit 0-11 of the end address are assumed to be 0xfff.
+	 */
+	printf("End address = 0x%08x\n",
+			 ((fpsba->pchstrp[gpr0_offset] >> 16) & 0x7fff) << 12 | 0xfff);
 	/* 0 means GPR0 protection is disabled */
 	fpsba->pchstrp[gpr0_offset] = 0;
-
 	write_image(filename, image, size);
 }