From: Javier Viguera <javier.viguera@digi.com>
Date: Thu, 16 Feb 2017 14:53:44 +0100
Subject: [PATCH] fw_env: add support to unlock emmc boot partition

Signed-off-by: Javier Viguera <javier.viguera@digi.com>
---
 tools/env/fw_env.c | 31 +++++++++++++++++++++++++++++++
 1 file changed, 31 insertions(+)

diff --git a/tools/env/fw_env.c b/tools/env/fw_env.c
index 46c619b211b5..1c337b4727a9 100644
--- a/tools/env/fw_env.c
+++ b/tools/env/fw_env.c
@@ -1177,9 +1177,31 @@ static int flash_read (int fd)
 	return 0;
 }
 
+/*
+ * Set mmcboot partition read-write protection
+ */
+static int sysfs_mmcboot_set_protection(const char *device, int value)
+{
+	int fd;
+	char buf[64];
+
+	snprintf(buf, sizeof(buf), "/sys/block/%s/force_ro", device);
+	fd = open(buf, O_WRONLY);
+	if (fd < 0) {
+		perror("sysfs_mmcboot_set_protection");
+		return fd;
+	}
+	snprintf(buf, sizeof(buf), "%s", value ? "1" : "0");
+	write(fd, buf, 2);
+	close(fd);
+
+	return 0;
+}
+
 static int flash_io (int mode)
 {
 	int fd_current, fd_target, rc, dev_target;
+	char *mmcblk = NULL;
 
 	/* dev_current: fd_current, erase_current */
 	fd_current = open (DEVNAME (dev_current), mode);
@@ -1209,8 +1231,17 @@ static int flash_io (int mode)
 			fd_target = fd_current;
 		}
 
+		/* Disable mmcboot protection if using EMMC (set read-write) */
+		mmcblk = strstr(DEVNAME(dev_target), "mmcblk");
+		if (mmcblk)
+			sysfs_mmcboot_set_protection(mmcblk, 0);
+
 		rc = flash_write (fd_current, fd_target, dev_target);
 
+		/* Re-enable mmcboot protection (set read-only) */
+		if (mmcblk)
+			sysfs_mmcboot_set_protection(mmcblk, 1);
+
 		if (HaveRedundEnv) {
 			if (close (fd_target)) {
 				fprintf (stderr,
