Flush mtdblock buffer after writes to hnvram

The mtdblock driver in Linux caches erase blocks indefinitely until the
last file descriptor to /dev/mtdblockX has been closed. This is not
acceptable because we assume that data has been flushed to flash storage
when the hnvram tool returns.

Steps to reproduce:
Open a fd to /dev/mtdblockX and leave it open:

cat > /dev/mtd/hnvram

On a different tty, run

hnvram -w ACTIVATED_KERNEL_NAME=kernel7 ; reboot

On the next boot, the main parition of HNVRAM will contain
ACTIVATED_KERNEL_NAME=kernel7, but the backup partition still has the
old value. Hence, the main and backup HNVRAM partition are inconsistent.

Hint: The hnvram tool internally subdivides the HNVRAM partition in the
NOR into a main and backup partition. (Look for NVRAM_RW_OFFSET and
NVRAM_RWB_OFFSET in hmx_upgrade_nvram.c)

Change-Id: Ifd3c095a5bfe966b3e512ded81164b710f506fd2
diff --git a/libupgrade/hmx_upgrade_flash.c b/libupgrade/hmx_upgrade_flash.c
index 6153d01..9f9ae2c 100644
--- a/libupgrade/hmx_upgrade_flash.c
+++ b/libupgrade/hmx_upgrade_flash.c
@@ -142,6 +142,16 @@
     return -1;
   }
 
+  /* Writes to /dev/mtdblockX are cached indefinitely until the last file
+   * descriptor is closed. Flush this cache after writing. The user depends on
+   * data being physically written to flash when this function returns.
+   * Requires CAP_SYS_ADMIN. */
+  ret = ioctl(fd_nvram, BLKFLSBUF, 0);
+  if(ret < 0) {
+    perror("ioctl(hnvram, BLKFLSBUF, 0)");
+    return -1;
+  }
+
   return 0;
 }