partition: Perform BLKDISCARD on the block device before flashing image

Change-Id: Ifb13d47693edfc96369053199ac0b5d81910f104
(cherry picked from commit 7669320c931f991c908e240638091d259304d636)
diff --git a/Android.mk b/Android.mk
index 59fdc16..284e325 100644
--- a/Android.mk
+++ b/Android.mk
@@ -440,6 +440,9 @@
 ifeq ($(TW_INCLUDE_FASTBOOTD), true)
     LOCAL_CFLAGS += -DTW_INCLUDE_FASTBOOTD
 endif
+ifeq ($(TW_ENABLE_BLKDISCARD), true)
+    LOCAL_CFLAGS += -DTW_ENABLE_BLKDISCARD
+endif
 
 LOCAL_C_INCLUDES += system/vold \
 
diff --git a/partition.cpp b/partition.cpp
index 330f71c..a362663 100755
--- a/partition.cpp
+++ b/partition.cpp
@@ -1770,6 +1770,13 @@
 	return ret;
 }
 
+bool TWPartition::BlkDiscard() {
+	string cmd;
+	LOGINFO("Perform BLKDISCARD on block device %s\n", Actual_Block_Device.c_str());
+	cmd = "/system/bin/toybox blkdiscard " + Actual_Block_Device;
+	return (TWFunc::Exec_Cmd(cmd) == 0);
+}
+
 bool TWPartition::Wipe(string New_File_System) {
 	bool wiped = false, update_crypt = false, recreate_media = false;
 	int check;
@@ -2786,6 +2793,9 @@
 		}
 	}
 	else {
+#ifdef TW_ENABLE_BLKDISCARD
+		BlkDiscard();
+#endif
 		destfn = Actual_Block_Device;
 		if (part_settings->adbbackup) {
 			srcfn = TW_ADB_RESTORE;
@@ -3319,6 +3329,10 @@
 bool TWPartition::Flash_Sparse_Image(const string& Filename) {
 	string Command;
 
+#ifdef TW_ENABLE_BLKDISCARD
+	BlkDiscard();
+#endif
+
 	gui_msg(Msg("flashing=Flashing {1}...")(Display_Name));
 
 	Command = "simg2img '" + Filename + "' '" + Actual_Block_Device + "'";
diff --git a/partitions.hpp b/partitions.hpp
index 713337b..73a87d4 100755
--- a/partitions.hpp
+++ b/partitions.hpp
@@ -127,6 +127,7 @@
 	bool ReMount(bool Display_Error);                                         // Remounts the partition
 	bool ReMount_RW(bool Display_Error);                                      // Remounts the partition with read/write access
 	bool Bind_Mount(bool Display_Error);                                      // Bind mount partition if symlink mountpoint is populated
+	bool BlkDiscard();                                                        // Clear the partition using BLKDISCARD ioctl
 	bool Wipe(string New_File_System);                                        // Wipes the partition
 	bool Wipe();                                                              // Wipes the partition
 	bool Wipe_AndSec();                                                       // Wipes android secure