Merge CM's bootable/recovery... I'll fork it later.

Change-Id: Ic3e72090a34aef2827c60cb6c0428b4fae129a65
diff --git a/Android.mk b/Android.mk
index 3f9f1e8..a3012aa 100644
--- a/Android.mk
+++ b/Android.mk
@@ -16,8 +16,8 @@
     verifier.c \
     encryptedfs_provisioning.c \
     mounts.c \
-	extendedcommands.c \
-	nandroid.c \
+    extendedcommands.c \
+    nandroid.c \
     reboot.c \
     edifyscripting.c \
     setprop.c
@@ -26,12 +26,12 @@
 
 LOCAL_FORCE_STATIC_EXECUTABLE := true
 
-RECOVERY_VERSION := ClockworkMod Recovery v3.0.2.4
+RECOVERY_VERSION := ClockworkMod Recovery v3.1.0.1
 LOCAL_CFLAGS += -DRECOVERY_VERSION="$(RECOVERY_VERSION)"
 RECOVERY_API_VERSION := 2
 LOCAL_CFLAGS += -DRECOVERY_API_VERSION=$(RECOVERY_API_VERSION)
 
-BOARD_RECOVERY_DEFINES := BOARD_HAS_NO_SELECT_BUTTON BOARD_HAS_SMALL_RECOVERY BOARD_LDPI_RECOVERY BOARD_UMS_LUNFILE
+BOARD_RECOVERY_DEFINES := BOARD_HAS_NO_SELECT_BUTTON BOARD_HAS_SMALL_RECOVERY BOARD_LDPI_RECOVERY BOARD_UMS_LUNFILE TARGET_RECOVERY_PRE_COMMAND
 
 $(foreach board_define,$(BOARD_RECOVERY_DEFINES), \
   $(if $($(board_define)), \
@@ -57,7 +57,12 @@
 LOCAL_STATIC_LIBRARIES += libminzip libunz libmincrypt
 
 LOCAL_STATIC_LIBRARIES += libedify libbusybox libclearsilverregex libmkyaffs2image libunyaffs liberase_image libdump_image libflash_image
-LOCAL_STATIC_LIBRARIES += libflashutils libmtdutils libmmcutils libbmlutils
+
+LOCAL_STATIC_LIBRARIES += libflashutils libmtdutils libmmcutils libbmlutils 
+
+ifeq ($(BOARD_USES_BML_OVER_MTD),true)
+LOCAL_STATIC_LIBRARIES += libbml_over_mtd
+endif
 
 LOCAL_STATIC_LIBRARIES += libminui libpixelflinger_static libpng libcutils
 LOCAL_STATIC_LIBRARIES += libstdc++ libc
diff --git a/edifyscripting.c b/edifyscripting.c
index 83f089f..89554d7 100644
--- a/edifyscripting.c
+++ b/edifyscripting.c
@@ -141,6 +141,10 @@
             free(path);
             return StringValue(strdup(""));
         }
+        if (0 != format_volume("/sdcard/.android_secure")) {
+            free(path);
+            return StringValue(strdup(""));
+        }
     }
 
 done:
diff --git a/etc/init.htc.rc b/etc/init.htc.rc
new file mode 100644
index 0000000..360b3af
--- /dev/null
+++ b/etc/init.htc.rc
@@ -0,0 +1,54 @@
+on early-init
+    start ueventd
+
+on init
+    export PATH /sbin
+    export ANDROID_ROOT /system
+    export ANDROID_DATA /data
+    export EXTERNAL_STORAGE /sdcard
+
+    symlink /system/etc /etc
+
+    mkdir /boot
+    mkdir /sdcard
+    mkdir /sd-ext
+    mkdir /datadata
+    mkdir /emmc
+    mkdir /system
+    mkdir /data
+    mkdir /cache
+    mount /tmp /tmp tmpfs
+
+on boot
+
+    ifup lo
+    hostname localhost
+    domainname localdomain
+
+    class_start default
+
+service ueventd /sbin/ueventd
+    critical
+
+service choice_fn /sbin/choice_fn
+    oneshot
+
+service recovery /sbin/recovery
+    disabled
+
+service power_test /sbin/power_test
+    disabled
+    oneshot
+
+service offmode_charging /sbin/offmode_charging
+
+service detect_key /sbin/detect_key
+
+service adbd /sbin/adbd recovery
+    disabled
+
+on property:persist.service.adb.enable=1
+    start adbd
+
+on property:persist.service.adb.enable=0
+    stop adbd
diff --git a/extendedcommands.c b/extendedcommands.c
index 717d8d2..2e3fa51 100644
--- a/extendedcommands.c
+++ b/extendedcommands.c
@@ -353,7 +353,8 @@
         return -1;
     }
 
-    if (write(fd, vol->device, strlen(vol->device)) < 0) {
+    if ((write(fd, vol->device, strlen(vol->device)) < 0) &&
+        (!vol->device2 || (write(fd, vol->device, strlen(vol->device2)) < 0))) {
         LOGE("Unable to write to ums lunfile (%s)", strerror(errno));
         close(fd);
         return -1;
@@ -487,6 +488,23 @@
     Volume* v;
 } FormatMenuEntry;
 
+int is_safe_to_format(char* name)
+{
+    char str[255];
+    char* partition;
+    property_get("ro.recovery.format_ignore_partitions", str, "/misc,/radio,/bootloader,/recovery");
+
+    partition = strtok(str, ", ");
+    while (partition != NULL) {
+        if (strcmp(name, partition) == 0) {
+            return 0;
+        }
+        partition = strtok(NULL, ", ");
+    }
+
+    return 1;
+}
+
 void show_partition_menu()
 {
     static char* headers[] = {  "Mounts and Storage Menu",
@@ -525,11 +543,13 @@
 				sprintf(&mount_menue[mountable_volumes].unmount, "unmount %s", v->mount_point);
 				mount_menue[mountable_volumes].v = &device_volumes[i];
 				++mountable_volumes;
-				sprintf(&format_menue[formatable_volumes].txt, "format %s", v->mount_point);
-				format_menue[formatable_volumes].v = &device_volumes[i];
-				++formatable_volumes;
+				if (is_safe_to_format(v->mount_point)) {
+					sprintf(&format_menue[formatable_volumes].txt, "format %s", v->mount_point);
+					format_menue[formatable_volumes].v = &device_volumes[i];
+					++formatable_volumes;
+				}
 		    }
-		    else if (strcmp("ramdisk", v->fs_type) != 0 && strcmp("misc", v->mount_point) != 0 && strcmp("mtd", v->fs_type) == 0)
+		    else if (strcmp("ramdisk", v->fs_type) != 0 && strcmp("mtd", v->fs_type) == 0 && is_safe_to_format(v->mount_point))
 		    {
 				sprintf(&format_menue[formatable_volumes].txt, "format %s", v->mount_point);
 				format_menue[formatable_volumes].v = &device_volumes[i];
@@ -540,6 +560,7 @@
 
     static char* confirm_format  = "Confirm format?";
     static char* confirm = "Yes - Format";
+    char confirm_string[255];
 
     for (;;)
     {
@@ -593,7 +614,9 @@
             FormatMenuEntry* e = &format_menue[chosen_item];
             Volume* v = e->v;
 
-            if (!confirm_selection(confirm_format, confirm))
+            sprintf(confirm_string, "%s - %s", v->mount_point, confirm_format);
+
+            if (!confirm_selection(confirm_string, confirm))
                 continue;
             ui_print("Formatting %s...\n", v->mount_point);
             if (0 != format_volume(v->mount_point))
@@ -863,6 +886,9 @@
         switch (chosen_item)
         {
             case 0:
+#ifdef TARGET_RECOVERY_PRE_COMMAND
+                __system( TARGET_RECOVERY_PRE_COMMAND );
+#endif
                 __reboot(LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2, LINUX_REBOOT_CMD_RESTART2, "recovery");
                 break;
             case 1:
@@ -1157,23 +1183,3 @@
     load_volume_table();
     return 0;
 }
-
-void handle_chargemode() {
-    const char* filename = "/proc/cmdline";
-    struct stat file_info;
-    if (0 != stat(filename, &file_info))
-        return;
-
-    int file_len = file_info.st_size;
-    char* file_data = (char*)malloc(file_len + 1);
-    FILE *file = fopen(filename, "rb");
-    if (file == NULL)
-        return;
-    fread(file_data, file_len, 1, file);
-    // supposedly not necessary, but let's be safe.
-    file_data[file_len] = '\0';
-    fclose(file);
-    
-    if (strstr(file_data, "androidboot.mode=offmode_charging") != NULL)
-        reboot(RB_POWER_OFF);
- }
diff --git a/flashutils/Android.mk b/flashutils/Android.mk
index 324480a..d503ce7 100644
--- a/flashutils/Android.mk
+++ b/flashutils/Android.mk
@@ -57,7 +57,6 @@
 LOCAL_CFLAGS += -Dmain=erase_image_main
 include $(BUILD_STATIC_LIBRARY)
 
-
 include $(CLEAR_VARS)
 LOCAL_SRC_FILES := dump_image.c
 LOCAL_MODULE := utility_dump_image
diff --git a/flashutils/flashutils.c b/flashutils/flashutils.c
index 0b1467e..7504e4a 100644
--- a/flashutils/flashutils.c
+++ b/flashutils/flashutils.c
@@ -10,7 +10,7 @@
 int device_flash_type()
 {
     if (the_flash_type == UNKNOWN) {
-        if (access("/dev/block/bml1", F_OK) == 0) {
+        if (access("/dev/block/bml7", F_OK) == 0) {
             the_flash_type = BML;
         } else if (access("/proc/emmc", F_OK) == 0) {
             the_flash_type = MMC;
@@ -78,7 +78,7 @@
         type = MMC;
     else if (strstr(partition, "/dev/block/bml") != NULL)
         type = BML;
-        
+    
     return type;
 }
 int restore_raw_partition(const char *partition, const char *filename)
@@ -107,6 +107,7 @@
         case BML:
             return cmd_bml_backup_raw_partition(partition, filename);
         default:
+            printf("unable to detect device type");
             return -1;
     }
 }
diff --git a/htc/res/offmode_charging_images/battery_error.png b/htc/res/offmode_charging_images/battery_error.png
new file mode 100644
index 0000000..fdc837e
--- /dev/null
+++ b/htc/res/offmode_charging_images/battery_error.png
Binary files differ
diff --git a/htc/res/offmode_charging_images/battery_left_0.png b/htc/res/offmode_charging_images/battery_left_0.png
new file mode 100644
index 0000000..86a57db
--- /dev/null
+++ b/htc/res/offmode_charging_images/battery_left_0.png
Binary files differ
diff --git a/htc/res/offmode_charging_images/battery_left_100.png b/htc/res/offmode_charging_images/battery_left_100.png
new file mode 100644
index 0000000..aa6a234
--- /dev/null
+++ b/htc/res/offmode_charging_images/battery_left_100.png
Binary files differ
diff --git a/htc/res/offmode_charging_images/battery_left_20.png b/htc/res/offmode_charging_images/battery_left_20.png
new file mode 100644
index 0000000..86d9568
--- /dev/null
+++ b/htc/res/offmode_charging_images/battery_left_20.png
Binary files differ
diff --git a/htc/res/offmode_charging_images/battery_left_40.png b/htc/res/offmode_charging_images/battery_left_40.png
new file mode 100644
index 0000000..d524f93
--- /dev/null
+++ b/htc/res/offmode_charging_images/battery_left_40.png
Binary files differ
diff --git a/htc/res/offmode_charging_images/battery_left_60.png b/htc/res/offmode_charging_images/battery_left_60.png
new file mode 100644
index 0000000..d1de603
--- /dev/null
+++ b/htc/res/offmode_charging_images/battery_left_60.png
Binary files differ
diff --git a/htc/res/offmode_charging_images/battery_left_80.png b/htc/res/offmode_charging_images/battery_left_80.png
new file mode 100644
index 0000000..f79dd30
--- /dev/null
+++ b/htc/res/offmode_charging_images/battery_left_80.png
Binary files differ
diff --git a/htc/res/offmode_charging_images/battery_right_0.png b/htc/res/offmode_charging_images/battery_right_0.png
new file mode 100644
index 0000000..00394a9
--- /dev/null
+++ b/htc/res/offmode_charging_images/battery_right_0.png
Binary files differ
diff --git a/htc/res/offmode_charging_images/battery_right_100.png b/htc/res/offmode_charging_images/battery_right_100.png
new file mode 100644
index 0000000..deace01
--- /dev/null
+++ b/htc/res/offmode_charging_images/battery_right_100.png
Binary files differ
diff --git a/htc/res/offmode_charging_images/battery_right_20.png b/htc/res/offmode_charging_images/battery_right_20.png
new file mode 100644
index 0000000..01cf0d3
--- /dev/null
+++ b/htc/res/offmode_charging_images/battery_right_20.png
Binary files differ
diff --git a/htc/res/offmode_charging_images/battery_right_40.png b/htc/res/offmode_charging_images/battery_right_40.png
new file mode 100644
index 0000000..f9f1a51
--- /dev/null
+++ b/htc/res/offmode_charging_images/battery_right_40.png
Binary files differ
diff --git a/htc/res/offmode_charging_images/battery_right_60.png b/htc/res/offmode_charging_images/battery_right_60.png
new file mode 100644
index 0000000..efdefd1
--- /dev/null
+++ b/htc/res/offmode_charging_images/battery_right_60.png
Binary files differ
diff --git a/htc/res/offmode_charging_images/battery_right_80.png b/htc/res/offmode_charging_images/battery_right_80.png
new file mode 100644
index 0000000..9de0462
--- /dev/null
+++ b/htc/res/offmode_charging_images/battery_right_80.png
Binary files differ
diff --git a/htc/res/offmode_charging_images/battery_shell.png b/htc/res/offmode_charging_images/battery_shell.png
new file mode 100644
index 0000000..befc6bf
--- /dev/null
+++ b/htc/res/offmode_charging_images/battery_shell.png
Binary files differ
diff --git a/htc/res/offmode_charging_images/charging_full_00031.png b/htc/res/offmode_charging_images/charging_full_00031.png
new file mode 100644
index 0000000..5bb3bfa
--- /dev/null
+++ b/htc/res/offmode_charging_images/charging_full_00031.png
Binary files differ
diff --git a/htc/res/offmode_charging_images/charging_full_00035.png b/htc/res/offmode_charging_images/charging_full_00035.png
new file mode 100644
index 0000000..cfd2e21
--- /dev/null
+++ b/htc/res/offmode_charging_images/charging_full_00035.png
Binary files differ
diff --git a/htc/res/offmode_charging_images/charging_full_00041.png b/htc/res/offmode_charging_images/charging_full_00041.png
new file mode 100644
index 0000000..b0b39af
--- /dev/null
+++ b/htc/res/offmode_charging_images/charging_full_00041.png
Binary files differ
diff --git a/htc/res/offmode_charging_images/charging_full_00043.png b/htc/res/offmode_charging_images/charging_full_00043.png
new file mode 100644
index 0000000..5ad3d1d
--- /dev/null
+++ b/htc/res/offmode_charging_images/charging_full_00043.png
Binary files differ
diff --git a/htc/res/offmode_charging_images/charging_full_00047.png b/htc/res/offmode_charging_images/charging_full_00047.png
new file mode 100644
index 0000000..54387dd
--- /dev/null
+++ b/htc/res/offmode_charging_images/charging_full_00047.png
Binary files differ
diff --git a/htc/res/offmode_charging_images/charging_full_00049.png b/htc/res/offmode_charging_images/charging_full_00049.png
new file mode 100644
index 0000000..9d201ed
--- /dev/null
+++ b/htc/res/offmode_charging_images/charging_full_00049.png
Binary files differ
diff --git a/htc/res/offmode_charging_images/charging_full_00053.png b/htc/res/offmode_charging_images/charging_full_00053.png
new file mode 100644
index 0000000..4ece618
--- /dev/null
+++ b/htc/res/offmode_charging_images/charging_full_00053.png
Binary files differ
diff --git a/htc/res/offmode_charging_images/charging_full_00055.png b/htc/res/offmode_charging_images/charging_full_00055.png
new file mode 100644
index 0000000..f66e4bc
--- /dev/null
+++ b/htc/res/offmode_charging_images/charging_full_00055.png
Binary files differ
diff --git a/htc/res/offmode_charging_images/charging_full_00059.png b/htc/res/offmode_charging_images/charging_full_00059.png
new file mode 100644
index 0000000..f2a4502
--- /dev/null
+++ b/htc/res/offmode_charging_images/charging_full_00059.png
Binary files differ
diff --git a/htc/res/offmode_charging_images/charging_full_00061.png b/htc/res/offmode_charging_images/charging_full_00061.png
new file mode 100644
index 0000000..6945438
--- /dev/null
+++ b/htc/res/offmode_charging_images/charging_full_00061.png
Binary files differ
diff --git a/htc/res/offmode_charging_images/charging_full_00065.png b/htc/res/offmode_charging_images/charging_full_00065.png
new file mode 100644
index 0000000..b17d986
--- /dev/null
+++ b/htc/res/offmode_charging_images/charging_full_00065.png
Binary files differ
diff --git a/htc/res/offmode_charging_images/charging_full_00067.png b/htc/res/offmode_charging_images/charging_full_00067.png
new file mode 100644
index 0000000..429abf2
--- /dev/null
+++ b/htc/res/offmode_charging_images/charging_full_00067.png
Binary files differ
diff --git a/htc/res/offmode_charging_images/charging_full_00071.png b/htc/res/offmode_charging_images/charging_full_00071.png
new file mode 100644
index 0000000..651e373
--- /dev/null
+++ b/htc/res/offmode_charging_images/charging_full_00071.png
Binary files differ
diff --git a/htc/res/offmode_charging_images/charging_full_00073.png b/htc/res/offmode_charging_images/charging_full_00073.png
new file mode 100644
index 0000000..7913713
--- /dev/null
+++ b/htc/res/offmode_charging_images/charging_full_00073.png
Binary files differ
diff --git a/htc/res/offmode_charging_images/charging_full_00077.png b/htc/res/offmode_charging_images/charging_full_00077.png
new file mode 100644
index 0000000..bb81c6c
--- /dev/null
+++ b/htc/res/offmode_charging_images/charging_full_00077.png
Binary files differ
diff --git a/htc/res/offmode_charging_images/charging_full_00079.png b/htc/res/offmode_charging_images/charging_full_00079.png
new file mode 100644
index 0000000..1eddfc2
--- /dev/null
+++ b/htc/res/offmode_charging_images/charging_full_00079.png
Binary files differ
diff --git a/htc/res/offmode_charging_images/charging_full_00083.png b/htc/res/offmode_charging_images/charging_full_00083.png
new file mode 100644
index 0000000..9a3544c
--- /dev/null
+++ b/htc/res/offmode_charging_images/charging_full_00083.png
Binary files differ
diff --git a/htc/res/offmode_charging_images/charging_full_00085.png b/htc/res/offmode_charging_images/charging_full_00085.png
new file mode 100644
index 0000000..b899e77
--- /dev/null
+++ b/htc/res/offmode_charging_images/charging_full_00085.png
Binary files differ
diff --git a/htc/res/offmode_charging_images/charging_full_00089.png b/htc/res/offmode_charging_images/charging_full_00089.png
new file mode 100644
index 0000000..fd72420
--- /dev/null
+++ b/htc/res/offmode_charging_images/charging_full_00089.png
Binary files differ
diff --git a/htc/res/offmode_charging_images/charging_full_00091.png b/htc/res/offmode_charging_images/charging_full_00091.png
new file mode 100644
index 0000000..5599a2d
--- /dev/null
+++ b/htc/res/offmode_charging_images/charging_full_00091.png
Binary files differ
diff --git a/htc/res/offmode_charging_images/charging_full_00095.png b/htc/res/offmode_charging_images/charging_full_00095.png
new file mode 100644
index 0000000..c69b754
--- /dev/null
+++ b/htc/res/offmode_charging_images/charging_full_00095.png
Binary files differ
diff --git a/htc/res/offmode_charging_images/charging_full_00099.png b/htc/res/offmode_charging_images/charging_full_00099.png
new file mode 100644
index 0000000..9c98cbc
--- /dev/null
+++ b/htc/res/offmode_charging_images/charging_full_00099.png
Binary files differ
diff --git a/install.c b/install.c
index ad2c21d..7ad1b2d 100644
--- a/install.c
+++ b/install.c
@@ -127,10 +127,10 @@
     }
     bool ok = mzExtractZipEntryToFile(zip, binary_entry, fd);
     close(fd);
-    mzCloseZipArchive(zip);
 
     if (!ok) {
         LOGE("Can't copy %s\n", ASSUMED_UPDATE_BINARY_NAME);
+        mzCloseZipArchive(zip);
         return 1;
     }
 
@@ -181,6 +181,7 @@
 
     pid_t pid = fork();
     if (pid == 0) {
+        setenv("UPDATE_PACKAGE", path, 1);
         close(pipefd[0]);
         execv(binary, args);
         fprintf(stdout, "E:Can't run %s (%s)\n", binary, strerror(errno));
@@ -239,13 +240,13 @@
     waitpid(pid, &status, 0);
     if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
         LOGE("Error in %s\n(Status %d)\n", path, WEXITSTATUS(status));
+        mzCloseZipArchive(zip);
         return INSTALL_ERROR;
     }
 
     if (firmware_type != NULL) {
+        mzCloseZipArchive(zip);
         return handle_firmware_update(firmware_type, firmware_filename, zip);
-    } else {
-        return INSTALL_SUCCESS;
     }
     return INSTALL_SUCCESS;
 }
diff --git a/mtdutils/Android.mk b/mtdutils/Android.mk
index 90e97fd..82284ba 100644
--- a/mtdutils/Android.mk
+++ b/mtdutils/Android.mk
@@ -2,15 +2,34 @@
 ifeq ($(TARGET_ARCH),arm)
 
 LOCAL_PATH := $(call my-dir)
+
 include $(CLEAR_VARS)
-
-LOCAL_SRC_FILES := \
-	mtdutils.c
-
+LOCAL_SRC_FILES := mtdutils.c
 LOCAL_MODULE := libmtdutils
-
 include $(BUILD_STATIC_LIBRARY)
 
+ifeq ($(BOARD_USES_BML_OVER_MTD),true)
+include $(CLEAR_VARS)
+LOCAL_SRC_FILES := bml_over_mtd.c
+LOCAL_C_INCLUDES += bootable/recovery/mtdutils
+LOCAL_MODULE := libbml_over_mtd
+LOCAL_MODULE_TAGS := eng
+LOCAL_CFLAGS += -Dmain=bml_over_mtd_main
+include $(BUILD_STATIC_LIBRARY)
+
+include $(CLEAR_VARS)
+LOCAL_SRC_FILES := bml_over_mtd.c
+LOCAL_MODULE := bml_over_mtd
+LOCAL_MODULE_TAGS := eng
+LOCAL_MODULE_CLASS := UTILITY_EXECUTABLES
+LOCAL_MODULE_PATH := $(PRODUCT_OUT)/utilities
+LOCAL_UNSTRIPPED_PATH := $(PRODUCT_OUT)/symbols/utilities
+LOCAL_MODULE_STEM := bml_over_mtd
+LOCAL_C_INCLUDES += bootable/recovery/mtdutils
+LOCAL_STATIC_LIBRARIES := libmtdutils libcutils libc
+LOCAL_FORCE_STATIC_EXECUTABLE := true
+include $(BUILD_EXECUTABLE)
+endif
 
 endif	# TARGET_ARCH == arm
 endif	# !TARGET_SIMULATOR
diff --git a/mtdutils/bml_over_mtd.c b/mtdutils/bml_over_mtd.c
new file mode 100644
index 0000000..c401792
--- /dev/null
+++ b/mtdutils/bml_over_mtd.c
@@ -0,0 +1,798 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <errno.h>
+#include <fcntl.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <sys/ioctl.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <limits.h>
+
+#include "cutils/log.h"
+
+#include <mtd/mtd-user.h>
+
+#include "mtdutils.h"
+
+typedef struct BmlOverMtdReadContext {
+	const MtdPartition *partition;
+	char *buffer;
+	size_t consumed;
+	int fd;
+} BmlOverMtdReadContext;
+
+typedef struct BmlOverMtdWriteContext {
+	const MtdPartition *partition;
+	char *buffer;
+	size_t stored;
+	int fd;
+
+	off_t* bad_block_offsets;
+	int bad_block_alloc;
+	int bad_block_count;
+} BmlOverMtdWriteContext;
+
+
+static BmlOverMtdReadContext *bml_over_mtd_read_partition(const MtdPartition *partition)
+{
+	BmlOverMtdReadContext *ctx = (BmlOverMtdReadContext*) malloc(sizeof(BmlOverMtdReadContext));
+	if (ctx == NULL) return NULL;
+
+	ctx->buffer = malloc(partition->erase_size);
+	if (ctx->buffer == NULL) {
+		free(ctx);
+		return NULL;
+	}
+
+	char mtddevname[32];
+	sprintf(mtddevname, "/dev/mtd/mtd%d", partition->device_index);
+	ctx->fd = open(mtddevname, O_RDONLY);
+	if (ctx->fd < 0) {
+		free(ctx);
+		free(ctx->buffer);
+		return NULL;
+	}
+
+	ctx->partition = partition;
+	ctx->consumed = partition->erase_size;
+	return ctx;
+}
+
+static void bml_over_mtd_read_close(BmlOverMtdReadContext *ctx)
+{
+	close(ctx->fd);
+	free(ctx->buffer);
+	free(ctx);
+}
+
+static BmlOverMtdWriteContext *bml_over_mtd_write_partition(const MtdPartition *partition)
+{
+	BmlOverMtdWriteContext *ctx = (BmlOverMtdWriteContext*) malloc(sizeof(BmlOverMtdWriteContext));
+	if (ctx == NULL) return NULL;
+
+	ctx->bad_block_offsets = NULL;
+	ctx->bad_block_alloc = 0;
+	ctx->bad_block_count = 0;
+
+	ctx->buffer = malloc(partition->erase_size);
+	if (ctx->buffer == NULL) {
+		free(ctx);
+		return NULL;
+	}
+
+	char mtddevname[32];
+	sprintf(mtddevname, "/dev/mtd/mtd%d", partition->device_index);
+	ctx->fd = open(mtddevname, O_RDWR);
+	if (ctx->fd < 0) {
+		free(ctx->buffer);
+		free(ctx);
+		return NULL;
+	}
+
+	ctx->partition = partition;
+	ctx->stored = 0;
+	return ctx;
+}
+
+static int bml_over_mtd_write_close(BmlOverMtdWriteContext *ctx)
+{
+	int r = 0;
+	if (close(ctx->fd)) r = -1;
+	free(ctx->bad_block_offsets);
+	free(ctx->buffer);
+	free(ctx);
+	return r;
+}
+
+
+#ifdef LOG_TAG
+#undef LOG_TAG
+#endif
+
+#define LOG_TAG "bml_over_mtd"
+
+#define BLOCK_SIZE    2048
+#define SPARE_SIZE    (BLOCK_SIZE >> 5)
+
+#define EXIT_CODE_BAD_BLOCKS 15
+
+static int die(const char *msg, ...) {
+	int err = errno;
+	va_list args;
+	va_start(args, msg);
+	char buf[1024];
+	vsnprintf(buf, sizeof(buf), msg, args);
+	va_end(args);
+
+	if (err != 0) {
+		strlcat(buf, ": ", sizeof(buf));
+		strlcat(buf, strerror(err), sizeof(buf));
+	}
+
+	fprintf(stderr, "%s\n", buf);
+	return 1;
+}
+
+static unsigned short* CreateEmptyBlockMapping(const MtdPartition* pSrcPart)
+{
+	size_t srcTotal, srcErase, srcWrite;
+	if (mtd_partition_info(pSrcPart, &srcTotal, &srcErase, &srcWrite) != 0)
+	{
+		fprintf(stderr, "Failed to access partition.\n");
+		return NULL;
+	}
+
+	int numSrcBlocks = srcTotal/srcErase;
+
+	unsigned short* pMapping = malloc(numSrcBlocks * sizeof(unsigned short));
+	if (pMapping == NULL)
+	{
+		fprintf(stderr, "Failed to allocate block mapping memory.\n");
+		return NULL;
+	}
+	memset(pMapping, 0xFF, numSrcBlocks * sizeof(unsigned short));
+	return pMapping;
+}
+
+static const unsigned short* CreateBlockMapping(const MtdPartition* pSrcPart, int srcPartStartBlock,
+		const MtdPartition *pReservoirPart, int reservoirPartStartBlock)
+{
+	size_t srcTotal, srcErase, srcWrite;
+	if (mtd_partition_info(pSrcPart, &srcTotal, &srcErase, &srcWrite) != 0)
+	{
+		fprintf(stderr, "Failed to access partition.\n");
+		return NULL;
+	}
+
+	int numSrcBlocks = srcTotal/srcErase;
+
+	unsigned short* pMapping = malloc(numSrcBlocks * sizeof(unsigned short));
+	if (pMapping == NULL)
+	{
+		fprintf(stderr, "Failed to allocate block mapping memory.\n");
+		return NULL;
+	}
+	memset(pMapping, 0xFF, numSrcBlocks * sizeof(unsigned short));
+
+	size_t total, erase, write;
+	if (mtd_partition_info(pReservoirPart, &total, &erase, &write) != 0)
+	{
+		fprintf(stderr, "Failed to access reservoir partition.\n");
+		free(pMapping);
+		return NULL;
+	}
+
+	if (erase != srcErase || write != srcWrite)
+	{
+		fprintf(stderr, "Source partition and reservoir partition differ in size properties.\n");
+		free(pMapping);
+		return NULL;
+	}
+
+	printf("Partition info: Total %d, Erase %d, write %d\n", total, erase, write);
+
+	BmlOverMtdReadContext *readctx = bml_over_mtd_read_partition(pReservoirPart);
+	if (readctx == NULL)
+	{
+		fprintf(stderr, "Failed to open reservoir partition for reading.\n");
+		free(pMapping);
+		return NULL;
+	}
+
+	if (total < erase || total > INT_MAX)
+	{
+		fprintf(stderr, "Unsuitable reservoir partition properties.\n");
+		free(pMapping);
+		bml_over_mtd_read_close(readctx);
+		return NULL;
+	}
+
+	int foundMappingTable = 0;
+
+	int currOffset = total; //Offset *behind* the last byte
+	while (currOffset > 0)
+	{
+		currOffset -= erase;
+		loff_t pos = lseek64(readctx->fd, currOffset, SEEK_SET);
+		int mgbb = ioctl(readctx->fd, MEMGETBADBLOCK, &pos);
+		if (mgbb != 0)
+		{
+			printf("Bad block %d in reservoir area, skipping.\n", currOffset/erase);
+			continue;
+		}
+		ssize_t readBytes = read(readctx->fd, readctx->buffer, erase);
+		if (readBytes != (ssize_t)erase)
+		{
+			fprintf(stderr, "Failed to read good block in reservoir area (%s).\n",
+					strerror(errno));
+			free(pMapping);
+			bml_over_mtd_read_close(readctx);
+			return NULL;
+		}
+		if (readBytes >= 0x2000)
+		{
+			char* buf = readctx->buffer;
+			if (buf[0]=='U' && buf[1]=='P' && buf[2]=='C' && buf[3]=='H')
+			{
+				printf ("Found mapping block mark at 0x%x (block %d).\n", currOffset, currOffset/erase);
+
+				unsigned short* mappings = (unsigned short*) &buf[0x1000];
+				if (mappings[0]==0 && mappings[1]==0xffff)
+				{
+					printf("Found start of mapping table.\n");
+					foundMappingTable = 1;
+					//Skip first entry (dummy)
+					unsigned short* mappingEntry = mappings + 2;
+					while (mappingEntry - mappings < 100
+							&& mappingEntry[0] != 0xffff)
+					{
+						unsigned short rawSrcBlk = mappingEntry[0];
+						unsigned short rawDstBlk = mappingEntry[1];
+
+						printf("Found raw block mapping %d -> %d\n", rawSrcBlk,
+								rawDstBlk);
+
+						unsigned int srcAbsoluteStartAddress = srcPartStartBlock * erase;
+						unsigned int resAbsoluteStartAddress = reservoirPartStartBlock * erase;
+
+						int reservoirLastBlock = reservoirPartStartBlock + numSrcBlocks - 1;
+						if (rawDstBlk < reservoirPartStartBlock
+								|| rawDstBlk*erase >= resAbsoluteStartAddress+currOffset)
+						{
+							fprintf(stderr, "Mapped block not within reasonable reservoir area.\n");
+							foundMappingTable = 0;
+							break;
+						}
+
+						int srcLastBlock = srcPartStartBlock + numSrcBlocks - 1;
+						if (rawSrcBlk >= srcPartStartBlock && rawSrcBlk <= srcLastBlock)
+						{
+
+							unsigned short relSrcBlk = rawSrcBlk - srcPartStartBlock;
+							unsigned short relDstBlk = rawDstBlk - reservoirPartStartBlock;
+							printf("Partition relative block mapping %d -> %d\n",relSrcBlk, relDstBlk);
+
+							printf("Absolute mapped start addresses 0x%x -> 0x%x\n",
+									srcAbsoluteStartAddress+relSrcBlk*erase,
+									resAbsoluteStartAddress+relDstBlk*erase);
+							printf("Partition relative mapped start addresses 0x%x -> 0x%x\n",
+									relSrcBlk*erase, relDstBlk*erase);
+
+							//Set mapping entry. For duplicate entries, later entries replace former ones.
+							//*Assumption*: Bad blocks in reservoir area will not be mapped themselves in
+							//the mapping table. User partition blocks will not be mapped to bad blocks
+							//(only) in the reservoir area. This has to be confirmed on a wider range of
+							//devices.
+							pMapping[relSrcBlk] = relDstBlk;
+
+						}
+						mappingEntry+=2;
+					}
+					break; //We found the mapping table, no need to search further
+				}
+
+
+			}
+		}
+
+	}
+	bml_over_mtd_read_close(readctx);
+
+	if (foundMappingTable == 0)
+	{
+		fprintf(stderr, "Cannot find mapping table in reservoir partition.\n");
+		free(pMapping);
+		return NULL;
+	}
+
+	//Consistency and validity check
+	int mappingValid = 1;
+	readctx = bml_over_mtd_read_partition(pSrcPart);
+	if (readctx == NULL)
+	{
+		fprintf(stderr, "Cannot open source partition for reading.\n");
+		free(pMapping);
+		return NULL;
+	}
+	int currBlock = 0;
+	for (;currBlock < numSrcBlocks; ++currBlock)
+	{
+		loff_t pos = lseek64(readctx->fd, currBlock*erase, SEEK_SET);
+		int mgbb = ioctl(readctx->fd, MEMGETBADBLOCK, &pos);
+		if (mgbb == 0)
+		{
+			if (pMapping[currBlock]!=0xffff)
+			{
+				fprintf(stderr, "Consistency error: Good block has mapping entry %d -> %d\n", currBlock, pMapping[currBlock]);
+				mappingValid = 0;
+			}
+		} else
+		{
+			//Bad block!
+			if (pMapping[currBlock]==0xffff)
+			{
+				fprintf(stderr, "Consistency error: Bad block has no mapping entry \n");
+				mappingValid = 0;
+			} else
+			{
+				BmlOverMtdReadContext* reservoirReadCtx = bml_over_mtd_read_partition(pReservoirPart);
+				if (reservoirReadCtx == 0)
+				{
+					fprintf(stderr, "Reservoir partition cannot be opened for reading in consistency check.\n");
+					mappingValid = 0;
+				} else
+				{
+					pos = lseek64(reservoirReadCtx->fd, pMapping[currBlock]*erase, SEEK_SET);
+					mgbb = ioctl(reservoirReadCtx->fd, MEMGETBADBLOCK, &pos);
+					if (mgbb == 0)
+					{
+						printf("Bad block has properly mapped reservoir block %d -> %d\n",currBlock, pMapping[currBlock]);
+					}
+					else
+					{
+						fprintf(stderr, "Consistency error: Mapped block is bad, too. (%d -> %d)\n",currBlock, pMapping[currBlock]);
+						mappingValid = 0;
+					}
+
+				}
+				bml_over_mtd_read_close(reservoirReadCtx);
+			}
+
+		}
+
+	}
+	bml_over_mtd_read_close(readctx);
+
+
+	if (!mappingValid)
+	{
+		free(pMapping);
+		return NULL;
+	}
+
+	return pMapping;
+}
+
+static void ReleaseBlockMapping(const unsigned short* blockMapping)
+{
+	free((void*)blockMapping);
+}
+
+static int dump_bml_partition(const MtdPartition* pSrcPart, const MtdPartition* pReservoirPart,
+		const unsigned short* blockMapping, const char* filename)
+{
+	int fd = open(filename, O_WRONLY|O_CREAT|O_TRUNC, 0666);
+	if (fd < 0)
+	{
+		fprintf(stderr, "error opening %s", filename);
+		return -1;
+	}
+	BmlOverMtdReadContext* pSrcRead = bml_over_mtd_read_partition(pSrcPart);
+	if (pSrcRead == NULL)
+	{
+		close(fd);
+		fprintf(stderr, "dump_bml_partition: Error opening src part for reading.\n");
+		return -1;
+	}
+
+	BmlOverMtdReadContext* pResRead = bml_over_mtd_read_partition(pReservoirPart);
+	if (pResRead == NULL)
+	{
+		close(fd);
+		bml_over_mtd_read_close(pSrcRead);
+		fprintf(stderr, "dump_bml_partition: Error opening reservoir part for reading.\n");
+		return -1;
+	}
+
+
+	int numBlocks = pSrcPart->size / pSrcPart->erase_size;
+	int currblock = 0;
+	for (;currblock < numBlocks; ++currblock)
+	{
+		int srcFd = -1;
+		if (blockMapping[currblock] == 0xffff)
+		{
+			//Good block, use src partition
+			srcFd = pSrcRead->fd;
+			if (lseek64(pSrcRead->fd, currblock*pSrcPart->erase_size, SEEK_SET)==-1)
+			{
+				close(fd);
+				bml_over_mtd_read_close(pSrcRead);
+				bml_over_mtd_read_close(pResRead);
+				fprintf(stderr, "dump_bml_partition: lseek in src partition failed\n");
+				return -1;
+			}
+		} else
+		{
+			//Bad block, use mapped block in reservoir partition
+			srcFd = pResRead->fd;
+			if (lseek64(pResRead->fd, blockMapping[currblock]*pSrcPart->erase_size, SEEK_SET)==-1)
+			{
+				close(fd);
+				bml_over_mtd_read_close(pSrcRead);
+				bml_over_mtd_read_close(pResRead);
+				fprintf(stderr, "dump_bml_partition: lseek in reservoir partition failed\n");
+				return -1;
+			}
+		}
+		size_t blockBytesRead = 0;
+		while (blockBytesRead < pSrcPart->erase_size)
+		{
+			ssize_t len = read(srcFd, pSrcRead->buffer + blockBytesRead,
+					pSrcPart->erase_size - blockBytesRead);
+			if (len <= 0)
+			{
+				close(fd);
+				bml_over_mtd_read_close(pSrcRead);
+				bml_over_mtd_read_close(pResRead);
+				fprintf(stderr, "dump_bml_partition: reading partition failed\n");
+				return -1;
+			}
+			blockBytesRead += len;
+		}
+
+		size_t blockBytesWritten = 0;
+		while (blockBytesWritten < pSrcPart->erase_size)
+		{
+			ssize_t len = write(fd, pSrcRead->buffer + blockBytesWritten,
+					pSrcPart->erase_size - blockBytesWritten);
+			if (len <= 0)
+			{
+				close(fd);
+				bml_over_mtd_read_close(pSrcRead);
+				bml_over_mtd_read_close(pResRead);
+				fprintf(stderr, "dump_bml_partition: writing partition dump file failed\n");
+				return -1;
+			}
+			blockBytesWritten += len;
+		}
+
+	}
+
+	bml_over_mtd_read_close(pSrcRead);
+	bml_over_mtd_read_close(pResRead);
+
+	if (close(fd)) {
+		unlink(filename);
+		printf("error closing %s", filename);
+		return -1;
+	}
+
+	return 0;
+}
+
+static ssize_t bml_over_mtd_write_block(int fd, ssize_t erase_size, char* data)
+{
+	off_t pos = lseek(fd, 0, SEEK_CUR);
+	if (pos == (off_t) -1) return -1;
+
+	ssize_t size = erase_size;
+	loff_t bpos = pos;
+	int ret = ioctl(fd, MEMGETBADBLOCK, &bpos);
+	if (ret != 0 && !(ret == -1 && errno == EOPNOTSUPP)) {
+		fprintf(stderr,
+				"Mapping failure: Trying to write bad block at 0x%08lx (ret %d errno %d)\n",
+				pos, ret, errno);
+		return -1;
+	}
+
+	struct erase_info_user erase_info;
+	erase_info.start = pos;
+	erase_info.length = size;
+	int retry;
+	for (retry = 0; retry < 2; ++retry) {
+		if (ioctl(fd, MEMERASE, &erase_info) < 0) {
+			fprintf(stderr, "mtd: erase failure at 0x%08lx (%s)\n",
+					pos, strerror(errno));
+			continue;
+		}
+		if (lseek(fd, pos, SEEK_SET) != pos ||
+				write(fd, data, size) != size) {
+			fprintf(stderr, "mtd: write error at 0x%08lx (%s)\n",
+					pos, strerror(errno));
+		}
+
+		char verify[size];
+		if (lseek(fd, pos, SEEK_SET) != pos ||
+				read(fd, verify, size) != size) {
+			fprintf(stderr, "mtd: re-read error at 0x%08lx (%s)\n",
+					pos, strerror(errno));
+			continue;
+		}
+		if (memcmp(data, verify, size) != 0) {
+			fprintf(stderr, "mtd: verification error at 0x%08lx (%s)\n",
+					pos, strerror(errno));
+			continue;
+		}
+
+		if (retry > 0) {
+			fprintf(stderr, "mtd: wrote block after %d retries\n", retry);
+		}
+		fprintf(stderr, "mtd: successfully wrote block at %llx\n", pos);
+		return size;  // Success!
+	}
+
+
+	fprintf(stderr, "mtd: Block at %llx could not be properly written.\n", pos);
+	// Ran out of space on the device
+	errno = ENOSPC;
+	return -1;
+}
+
+static int flash_bml_partition(const MtdPartition* pSrcPart, const MtdPartition* pReservoirPart,
+		const unsigned short* blockMapping, const char* filename)
+{
+	int fd = open(filename, O_RDONLY);
+	if (fd < 0)
+	{
+		fprintf(stderr, "error opening %s", filename);
+		return -1;
+	}
+	BmlOverMtdWriteContext* pSrcWrite = bml_over_mtd_write_partition(pSrcPart);
+	if (pSrcWrite == NULL)
+	{
+		close(fd);
+		fprintf(stderr, "flash_bml_partition: Error opening src part for writing.\n");
+		return -1;
+	}
+
+#ifdef DUMMY_WRITING
+	close(pSrcWrite->fd);
+	pSrcWrite->fd = open("/sdcard/srcPartWriteDummy.bin", O_WRONLY|O_CREAT|O_TRUNC, 0666);
+#endif
+
+	BmlOverMtdWriteContext* pResWrite = bml_over_mtd_write_partition(pReservoirPart);
+	if (pResWrite == NULL)
+	{
+		close(fd);
+		bml_over_mtd_write_close(pSrcWrite);
+		fprintf(stderr, "flash_bml_partition: Error opening reservoir part for writing.\n");
+		return -1;
+	}
+#ifdef DUMMY_WRITING
+	close(pResWrite->fd);
+	pResWrite->fd = open("/sdcard/resPartWriteDummy.bin", O_WRONLY|O_CREAT|O_TRUNC, 0666);
+#endif
+
+	struct stat fileStat;
+	if (fstat(fd, &fileStat) != 0)
+	{
+		close(fd);
+		bml_over_mtd_write_close(pSrcWrite);
+		bml_over_mtd_write_close(pResWrite);
+		fprintf(stderr, "flash_bml_partition: Failed to stat source file.\n");
+		return -1;
+
+	}
+	if (fileStat.st_size > pSrcPart->size)
+	{
+		close(fd);
+		bml_over_mtd_write_close(pSrcWrite);
+		bml_over_mtd_write_close(pResWrite);
+		fprintf(stderr, "flash_bml_partition: Source file too large for target partition.\n");
+		return -1;
+	}
+
+	int numBlocks = (fileStat.st_size +  pSrcPart->erase_size - 1) / pSrcPart->erase_size;
+	int currblock;
+	for (currblock = 0 ;currblock < numBlocks; ++currblock)
+	{
+		memset(pSrcWrite->buffer, 0xFF, pSrcPart->erase_size);
+		size_t blockBytesRead = 0;
+		while (blockBytesRead < pSrcPart->erase_size)
+		{
+			ssize_t len = read(fd, pSrcWrite->buffer + blockBytesRead,
+					pSrcPart->erase_size - blockBytesRead);
+			if (len < 0)
+			{
+				close(fd);
+				bml_over_mtd_write_close(pSrcWrite);
+				bml_over_mtd_write_close(pResWrite);
+				fprintf(stderr, "flash_bml_partition: read source file failed\n");
+				return -1;
+			}
+			if (len == 0)
+			{
+				//End of file
+				break;
+			}
+
+			blockBytesRead += len;
+		}
+
+
+
+		int srcFd = -1;
+		if (blockMapping[currblock] == 0xffff)
+		{
+			//Good block, use src partition
+			srcFd = pSrcWrite->fd;
+			if (lseek64(pSrcWrite->fd, currblock*pSrcPart->erase_size, SEEK_SET)==-1)
+			{
+				close(fd);
+				bml_over_mtd_write_close(pSrcWrite);
+				bml_over_mtd_write_close(pResWrite);
+				fprintf(stderr, "flash_bml_partition: lseek in src partition failed\n");
+				return -1;
+			}
+		} else
+		{
+			//Bad block, use mapped block in reservoir partition
+			srcFd = pResWrite->fd;
+			if (lseek64(pResWrite->fd, blockMapping[currblock]*pSrcPart->erase_size, SEEK_SET)==-1)
+			{
+				close(fd);
+				bml_over_mtd_write_close(pSrcWrite);
+				bml_over_mtd_write_close(pResWrite);
+				fprintf(stderr, "flash_bml_partition: lseek in reservoir partition failed\n");
+				return -1;
+			}
+		}
+		size_t blockBytesWritten = 0;
+		while (blockBytesWritten < pSrcPart->erase_size)
+		{
+#ifdef DUMMY_WRITING
+			ssize_t len = write(srcFd, pSrcWrite->buffer + blockBytesWritten,
+					pSrcPart->erase_size - blockBytesWritten);
+#else
+			ssize_t len = bml_over_mtd_write_block(srcFd, pSrcPart->erase_size, pSrcWrite->buffer);
+#endif
+			if (len <= 0)
+			{
+				close(fd);
+				bml_over_mtd_write_close(pSrcWrite);
+				bml_over_mtd_write_close(pResWrite);
+				fprintf(stderr, "flash_bml_partition: writing to partition failed\n");
+				return -1;
+			}
+			blockBytesWritten += len;
+		}
+
+
+	}
+
+	bml_over_mtd_write_close(pSrcWrite);
+	bml_over_mtd_write_close(pResWrite);
+
+	if (close(fd)) {
+		printf("error closing %s", filename);
+		return -1;
+	}
+
+	return 0;
+}
+
+static int scan_partition(const MtdPartition* pPart)
+{
+	BmlOverMtdReadContext* readCtx = bml_over_mtd_read_partition(pPart);
+	if (readCtx == NULL)
+	{
+		fprintf(stderr, "Failed to open partition for reading.\n");
+		return -1;
+	}
+
+	int numBadBlocks = 0;
+	size_t numBlocks = pPart->size / pPart->erase_size;
+	size_t currBlock;
+	for (currBlock = 0; currBlock < numBlocks; ++currBlock)
+	{
+
+		loff_t pos = currBlock * pPart->erase_size;
+		int mgbb = ioctl(readCtx->fd, MEMGETBADBLOCK, &pos);
+		if (mgbb != 0)
+		{
+			printf("Bad block %d at 0x%x.\n", currBlock, (unsigned int)pos);
+			numBadBlocks++;
+		}
+	}
+
+	bml_over_mtd_read_close(readCtx);
+	if (numBadBlocks == 0)
+	{
+		printf("No bad blocks.\n");
+		return 0;
+	}
+	return -1 ;
+}
+
+int main(int argc, char **argv)
+{
+	if (argc != 7 && (argc != 3 || (argc == 3 && strcmp(argv[1],"scan"))!=0)
+			&& (argc != 6 || (argc == 6 && strcmp(argv[1],"scan"))!=0))
+		return die("Usage: %s dump|flash <partition> <partition_start_block> <reservoirpartition> <reservoir_start_block> <file>\n"
+				"E.g. %s dump boot 72 reservoir 2004 file.bin\n"
+				"Usage: %s scan <partition> [<partition_start_block> <reservoirpartition> <reservoir_start_block>]\n"
+				,argv[0], argv[0], argv[0]);
+	int num_partitions = mtd_scan_partitions();
+	const MtdPartition *pSrcPart = mtd_find_partition_by_name(argv[2]);
+	if (pSrcPart == NULL)
+		return die("Cannot find partition %s", argv[2]);
+
+	int scanResult = scan_partition(pSrcPart);
+
+	if (argc == 3 && strcmp(argv[1],"scan")==0)
+	{
+		return (scanResult == 0 ? 0 : EXIT_CODE_BAD_BLOCKS);
+	}
+
+	int retVal = 0;
+	const MtdPartition* pReservoirPart = mtd_find_partition_by_name(argv[4]);
+	if (pReservoirPart == NULL)
+		return die("Cannot find partition %s", argv[4]);
+
+	int srcPartStartBlock = atoi(argv[3]);
+	int reservoirPartStartBlock = atoi(argv[5]);
+	const unsigned short* pMapping = CreateBlockMapping(pSrcPart, srcPartStartBlock,
+			pReservoirPart, reservoirPartStartBlock);
+
+	if (pMapping == NULL && scanResult == 0)
+	{
+		printf("Generating empty block mapping table for error-free partition.\n");
+		pMapping = CreateEmptyBlockMapping(pSrcPart);
+	}
+
+	if (argc == 6 && strcmp(argv[1],"scan")==0)
+	{
+		retVal = (scanResult == 0 ? 0 : EXIT_CODE_BAD_BLOCKS);
+	}
+
+	if (pMapping == NULL)
+		return die("Failed to create block mapping table");
+
+	if (strcmp(argv[1],"dump")==0)
+	{
+		retVal = dump_bml_partition(pSrcPart, pReservoirPart, pMapping, argv[6]);
+		if (retVal == 0)
+			printf("Successfully dumped partition to %s\n", argv[6]);
+	}
+
+	if (strcmp(argv[1],"flash")==0)
+	{
+		retVal = flash_bml_partition(pSrcPart, pReservoirPart, pMapping, argv[6]);
+		if (retVal == 0)
+			printf("Successfully wrote %s to partition\n", argv[6]);
+
+	}
+
+
+	ReleaseBlockMapping(pMapping);
+	return retVal;
+}
+
diff --git a/reboot.c b/reboot.c
index 04aa9ae..6af84da 100644
--- a/reboot.c
+++ b/reboot.c
@@ -49,9 +49,13 @@
     if(force || argc > optind) {
         if(poweroff)
             ret = __reboot(LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2, LINUX_REBOOT_CMD_POWER_OFF, NULL);
-        else if(argc > optind)
-            ret = __reboot(LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2, LINUX_REBOOT_CMD_RESTART2, argv[optind]);
-        else
+        else if(argc > optind) {
+#ifdef TARGET_RECOVERY_PRE_COMMAND
+            if (!strncmp(argv[optind],"recovery",8))
+                system( TARGET_RECOVERY_PRE_COMMAND );
+#endif 
+           ret = __reboot(LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2, LINUX_REBOOT_CMD_RESTART2, argv[optind]);
+        } else
             ret = reboot(RB_AUTOBOOT);
     } else {
         if(poweroff) {
diff --git a/recovery.c b/recovery.c
index 963c724..09a7b7f 100644
--- a/recovery.c
+++ b/recovery.c
@@ -794,7 +794,6 @@
             return setprop_main(argc, argv);
 		return busybox_driver(argc, argv);
 	}
-    handle_chargemode();
     __system("/sbin/postrecoveryboot.sh");
     
     int is_user_initiated_recovery = 0;
diff --git a/res/images/icon_clockwork.png b/res/images/icon_clockwork.png
old mode 100755
new mode 100644
index b05951d..e696bc5
--- a/res/images/icon_clockwork.png
+++ b/res/images/icon_clockwork.png
Binary files differ
diff --git a/roots.c b/roots.c
index a3c4677..a33190a 100644
--- a/roots.c
+++ b/roots.c
@@ -153,7 +153,6 @@
     else {
         char mount_cmd[PATH_MAX];
         sprintf(mount_cmd, "mount -t %s -o%s %s %s", fs_type, fs_options, device, mount_point);
-        LOGE("%s\n", mount_cmd);
         ret = __system(mount_cmd);
     }
     if (ret == 0)
diff --git a/updater/updater.c b/updater/updater.c
index aa626d2..6bc4f40 100644
--- a/updater/updater.c
+++ b/updater/updater.c
@@ -63,6 +63,7 @@
     // Extract the script from the package.
 
     char* package_data = argv[3];
+    setenv("UPDATE_PACKAGE", package_data, 1);
     ZipArchive za;
     int err;
     err = mzOpenZipArchive(package_data, &za);
diff --git a/utilities/Android.mk b/utilities/Android.mk
old mode 100644
new mode 100755
index 251c9e6..79201a3
--- a/utilities/Android.mk
+++ b/utilities/Android.mk
@@ -42,7 +42,7 @@
 LOCAL_SRC_FILES := $(LOCAL_MODULE)
 include $(BUILD_PREBUILT)
 
-ifeq ($BOARD_HAS_LARGE_FILESYSTEM,true)
+ifeq ($(BOARD_HAS_LARGE_FILESYSTEM),true)
 include $(CLEAR_VARS)
 LOCAL_MODULE := mke2fs
 LOCAL_MODULE_TAGS := eng
@@ -52,4 +52,38 @@
 include $(BUILD_PREBUILT)
 endif
 
+ifeq ($(BOARD_USES_RECOVERY_CHARGEMODE),true)
+include $(CLEAR_VARS)
+LOCAL_MODULE := choice_fn
+LOCAL_MODULE_TAGS := eng
+LOCAL_MODULE_CLASS := RECOVERY_EXECUTABLES
+LOCAL_MODULE_PATH := $(TARGET_RECOVERY_ROOT_OUT)/sbin
+LOCAL_SRC_FILES := $(LOCAL_MODULE)
+include $(BUILD_PREBUILT)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := power_test
+LOCAL_MODULE_TAGS := eng
+LOCAL_MODULE_CLASS := RECOVERY_EXECUTABLES
+LOCAL_MODULE_PATH := $(TARGET_RECOVERY_ROOT_OUT)/sbin
+LOCAL_SRC_FILES := $(LOCAL_MODULE)
+include $(BUILD_PREBUILT)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := offmode_charging
+LOCAL_MODULE_TAGS := eng
+LOCAL_MODULE_CLASS := RECOVERY_EXECUTABLES
+LOCAL_MODULE_PATH := $(TARGET_RECOVERY_ROOT_OUT)/sbin
+LOCAL_SRC_FILES := $(LOCAL_MODULE)
+include $(BUILD_PREBUILT)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := detect_key
+LOCAL_MODULE_TAGS := eng
+LOCAL_MODULE_CLASS := RECOVERY_EXECUTABLES
+LOCAL_MODULE_PATH := $(TARGET_RECOVERY_ROOT_OUT)/sbin
+LOCAL_SRC_FILES := $(LOCAL_MODULE)
+include $(BUILD_PREBUILT)
+endif
+
 endif
diff --git a/utilities/choice_fn b/utilities/choice_fn
new file mode 100755
index 0000000..9af6061
--- /dev/null
+++ b/utilities/choice_fn
Binary files differ
diff --git a/utilities/detect_key b/utilities/detect_key
new file mode 100755
index 0000000..ebf5ec2
--- /dev/null
+++ b/utilities/detect_key
Binary files differ
diff --git a/utilities/fix_permissions b/utilities/fix_permissions
old mode 100644
new mode 100755
diff --git a/utilities/mke2fs b/utilities/mke2fs
old mode 100644
new mode 100755
Binary files differ
diff --git a/utilities/offmode_charging b/utilities/offmode_charging
new file mode 100755
index 0000000..48da64c
--- /dev/null
+++ b/utilities/offmode_charging
Binary files differ
diff --git a/utilities/parted b/utilities/parted
old mode 100644
new mode 100755
Binary files differ
diff --git a/utilities/power_test b/utilities/power_test
new file mode 100755
index 0000000..7cbb171
--- /dev/null
+++ b/utilities/power_test
Binary files differ
diff --git a/utilities/sdparted b/utilities/sdparted
old mode 100644
new mode 100755
index 13e62f4..74e24a6
--- a/utilities/sdparted
+++ b/utilities/sdparted
@@ -546,12 +546,29 @@
 
 SDSIZE=
 SDSIZEMB=
-if [ -z "$SDPATH" ]
+SDINFO=$(cat /etc/fstab | grep /sdcard | awk '{print $1}')
+if [ -L "$SDINFO" ]
 then
-    SDPATH="/dev/block/mmcblk0"
+	SDPATH=$(ls -l $SDINFO | awk '{print $11}')
 else
-    echo Found SDPATH=$SDPATH
+	SDPATH=$SDINFO
 fi
+# we may now have an SDPATH, let's make sure its on mmcblkX or mmcblkXp1
+CHECK_SDPATH1=$(echo $SDPATH | grep mmcblk.$)
+CHECK_SDPATH2=$(echo $SDPATH | grep mmcblk.p1$)
+if [ -z "$CHECK_SDPATH1" ]
+then
+	if [ -z "$CHECK_SDPATH2" ]
+	then
+		echo fail1
+		unset SDPATH
+	else
+		LEN=${#SDPATH}
+		BLKLEN=$(expr $LEN - 2)
+		SDPATH=${SDPATH:0:$BLKLEN}
+	fi
+fi
+
 
 FATSIZE=
 FATTYPE="fat32"