From 06177bcf69b8d0638264111162eeebeecece83b4 Mon Sep 17 00:00:00 2001
From: Nicolas Schichan <nschichan@freebox.fr>
Date: Tue, 15 Nov 2022 14:41:12 +0100
Subject: [PATCH 1/7] mmc-utils: allow to permanently disable permanent write
 protection of boot partitions.

---
 mmc.c      |  5 +++++
 mmc_cmds.c | 37 +++++++++++++++++++++++++++++++++++++
 mmc_cmds.h |  1 +
 3 files changed, 43 insertions(+)

diff --git a/mmc.c b/mmc.c
index 795b4e3..52dfe74 100644
--- a/mmc.c
+++ b/mmc.c
@@ -61,6 +61,11 @@ static struct Command commands[] = {
 		  "Write <value> at offset <offset> to <device>'s extcsd.",
 	  NULL
 	},
+	{ do_writeprotect_boot_perm_dis, -1,
+	  "writeprotect boot perm dis", "<device>\n"
+	  "permanently disable permanent write protection (sic)",
+	  NULL,
+	},
 	{ do_writeprotect_boot_get, -1,
 	  "writeprotect boot get", "<device>\n"
 		"Print the boot partitions write protect status for <device>.",
diff --git a/mmc_cmds.c b/mmc_cmds.c
index df66986..303c9b8 100644
--- a/mmc_cmds.c
+++ b/mmc_cmds.c
@@ -354,6 +354,43 @@ int do_writeprotect_boot_set(int nargs, char **argv)
 	return ret;
 }
 
+int do_writeprotect_boot_perm_dis(int nargs, char **argv)
+{
+	__u8 ext_csd[512], value;
+	const char *device = argv[1];
+	int fd, ret = 0;
+
+	if (nargs != 2) {
+		fprintf(stderr, "Usage: mmc writeprotect boot perm dis "
+			"<path/to/mmcblkX>\n");
+	      exit(1);
+	}
+
+	fd = open(device, O_RDWR);
+	if (fd < 0) {
+		perror("open");
+		exit(1);
+	}
+
+	ret = read_extcsd(fd, ext_csd);
+	if (ret) {
+		fprintf(stderr, "Could not read EXT_CSD from %s\n", device);
+		exit(1);
+	}
+
+	value = ext_csd[EXT_CSD_BOOT_WP];
+	value |= EXT_CSD_BOOT_WP_B_PERM_WP_DIS;
+	ret = write_extcsd_value(fd, EXT_CSD_BOOT_WP, value, 0);
+	if (ret) {
+		fprintf(stderr, "Could not write 0x%02x to "
+			"EXT_CSD[%d] in %s\n",
+			value, EXT_CSD_BOOT_WP, device);
+		exit(1);
+	}
+
+	return  ret;
+}
+
 static char *prot_desc[] = {
 	"No",
 	"Temporary",
diff --git a/mmc_cmds.h b/mmc_cmds.h
index 5f2bef1..f73abbb 100644
--- a/mmc_cmds.h
+++ b/mmc_cmds.h
@@ -22,6 +22,7 @@ int do_read_extcsd(int nargs, char **argv);
 int do_write_extcsd(int nargs, char **argv);
 int do_writeprotect_boot_get(int nargs, char **argv);
 int do_writeprotect_boot_set(int nargs, char **argv);
+int do_writeprotect_boot_perm_dis(int nargs, char **argv);
 int do_writeprotect_user_get(int nargs, char **argv);
 int do_writeprotect_user_set(int nargs, char **argv);
 int do_disable_512B_emulation(int nargs, char **argv);
-- 
2.34.1

