From a387b00719395001dffe34696f403e3e156d9325 Mon Sep 17 00:00:00 2001
From: Nicolas Schichan <nschichan@freebox.fr>
Date: Tue, 15 Nov 2022 15:04:09 +0100
Subject: [PATCH 3/7] mmc-utils: allow to permanently disable permanent write
 protection on user partitions.

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

diff --git a/mmc.c b/mmc.c
index 375ed48..f01118d 100644
--- a/mmc.c
+++ b/mmc.c
@@ -71,6 +71,10 @@ static struct Command commands[] = {
 	  "permanently disable permanent write protection on all partitions",
 	  NULL,
 	},
+	{ do_writeprotect_user_perm_dis, -1,
+	  "writeprotect user perm dis", "<device>\n"
+	  "permanently disable permanent write protection on user partitions",
+	},
 	{ 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 34fa810..b51f813 100644
--- a/mmc_cmds.c
+++ b/mmc_cmds.c
@@ -428,6 +428,43 @@ int do_writeprotect_device_perm_dis(int nargs, char **argv)
 	return  ret;
 }
 
+int do_writeprotect_user_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 user 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_US_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 9f6e611..4cf522c 100644
--- a/mmc_cmds.h
+++ b/mmc_cmds.h
@@ -24,6 +24,7 @@ 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_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

