From 5844e36869cfd9dfc5e2c348c137976771b685aa Mon Sep 17 00:00:00 2001
From: Nicolas Schichan <nschichan@freebox.fr>
Date: Tue, 15 Nov 2022 14:55:13 +0100
Subject: [PATCH 2/7] mmc-utils: allow to permanently disable permanent write
 protection on whole device partitions.

---
 mmc.c      |  7 ++++++-
 mmc_cmds.c | 37 +++++++++++++++++++++++++++++++++++++
 mmc_cmds.h |  1 +
 3 files changed, 44 insertions(+), 1 deletion(-)

diff --git a/mmc.c b/mmc.c
index 52dfe74..375ed48 100644
--- a/mmc.c
+++ b/mmc.c
@@ -63,7 +63,12 @@ static struct Command commands[] = {
 	},
 	{ do_writeprotect_boot_perm_dis, -1,
 	  "writeprotect boot perm dis", "<device>\n"
-	  "permanently disable permanent write protection (sic)",
+	  "permanently disable permanent write protection on boot partitions",
+	  NULL,
+	},
+	{ do_writeprotect_device_perm_dis, -1,
+	  "writeprotect device perm dis", "<device>\n"
+	  "permanently disable permanent write protection on all partitions",
 	  NULL,
 	},
 	{ do_writeprotect_boot_get, -1,
diff --git a/mmc_cmds.c b/mmc_cmds.c
index 303c9b8..34fa810 100644
--- a/mmc_cmds.c
+++ b/mmc_cmds.c
@@ -391,6 +391,43 @@ int do_writeprotect_boot_perm_dis(int nargs, char **argv)
 	return  ret;
 }
 
+int do_writeprotect_device_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 device 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_USER_WP];
+	value |= USER_WP_CD_PERM_WP_DIS;
+	ret = write_extcsd_value(fd, EXT_CSD_USER_WP, value, 0);
+	if (ret) {
+		fprintf(stderr, "Could not write 0x%02x to "
+			"EXT_CSD[%d] in %s\n",
+			value, EXT_CSD_USER_WP, device);
+		exit(1);
+	}
+
+	return  ret;
+}
+
 static char *prot_desc[] = {
 	"No",
 	"Temporary",
diff --git a/mmc_cmds.h b/mmc_cmds.h
index f73abbb..9f6e611 100644
--- a/mmc_cmds.h
+++ b/mmc_cmds.h
@@ -23,6 +23,7 @@ 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_device_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

