Merge "Update get_sched_policy to return TOP_APP correctly." into nyc-dev
diff --git a/fs_mgr/fs_mgr.c b/fs_mgr/fs_mgr.c
index e92cca5..bc072bc 100644
--- a/fs_mgr/fs_mgr.c
+++ b/fs_mgr/fs_mgr.c
@@ -101,6 +101,7 @@
     char tmpmnt_opts[64] = "errors=remount-ro";
     char *e2fsck_argv[] = {
         E2FSCK_BIN,
+        "-f",
         "-y",
         blk_device
     };
diff --git a/healthd/BatteryMonitor.cpp b/healthd/BatteryMonitor.cpp
index ae84d1e..a8646c5 100644
--- a/healthd/BatteryMonitor.cpp
+++ b/healthd/BatteryMonitor.cpp
@@ -73,6 +73,7 @@
     props->batteryCurrent = 0;
     props->batteryCycleCount = 0;
     props->batteryFullCharge = 0;
+    props->batteryChargeCounter = 0;
     props->batteryTechnology.clear();
 }
 
@@ -230,6 +231,9 @@
     if (!mHealthdConfig->batteryCycleCountPath.isEmpty())
         props.batteryCycleCount = getIntField(mHealthdConfig->batteryCycleCountPath);
 
+    if (!mHealthdConfig->batteryChargeCounterPath.isEmpty())
+        props.batteryChargeCounter = getIntField(mHealthdConfig->batteryChargeCounterPath);
+
     props.batteryTemperature = mBatteryFixedTemperature ?
         mBatteryFixedTemperature :
         getIntField(mHealthdConfig->batteryTemperaturePath);
diff --git a/include/private/canned_fs_config.h b/include/private/canned_fs_config.h
new file mode 100644
index 0000000..d9f51ca
--- /dev/null
+++ b/include/private/canned_fs_config.h
@@ -0,0 +1,26 @@
+/*
+ * Copyright (C) 2014 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.
+ */
+
+#ifndef _CANNED_FS_CONFIG_H
+#define _CANNED_FS_CONFIG_H
+
+#include <inttypes.h>
+
+int load_canned_fs_config(const char* fn);
+void canned_fs_config(const char* path, int dir, const char* target_out_path,
+                      unsigned* uid, unsigned* gid, unsigned* mode, uint64_t* capabilities);
+
+#endif
diff --git a/include/system/graphics.h b/include/system/graphics.h
index eabe18e..a9e451f 100644
--- a/include/system/graphics.h
+++ b/include/system/graphics.h
@@ -1066,6 +1066,20 @@
     HAL_COLOR_TRANSFORM_CORRECT_TRITANOPIA = 6
 } android_color_transform_t;
 
+/*
+ * Supported HDR formats. Must be kept in sync with equivalents in Display.java.
+ */
+typedef enum android_hdr {
+    /* Device supports Dolby Vision HDR */
+    HAL_HDR_DOLBY_VISION = 1,
+
+    /* Device supports HDR10 */
+    HAL_HDR_HDR10 = 2,
+
+    /* Device supports hybrid log-gamma HDR */
+    HAL_HDR_HLG = 3
+} android_hdr_t;
+
 #ifdef __cplusplus
 }
 #endif
diff --git a/include/utils/Mutex.h b/include/utils/Mutex.h
index f027c79..9b0b734 100644
--- a/include/utils/Mutex.h
+++ b/include/utils/Mutex.h
@@ -35,6 +35,10 @@
 class Condition;
 
 /*
+ * NOTE: This class is for code that builds on Win32.  Its usage is
+ * deprecated for code which doesn't build for Win32.  New code which
+ * doesn't build for Win32 should use std::mutex and std::lock_guard instead.
+ *
  * Simple mutex class.  The implementation is system-dependent.
  *
  * The mutex must be unlocked by the thread that locked it.  They are not
diff --git a/init/Android.mk b/init/Android.mk
index d8b574f..4827fa3 100644
--- a/init/Android.mk
+++ b/init/Android.mk
@@ -83,6 +83,7 @@
 
 LOCAL_STATIC_LIBRARIES := \
     libinit \
+    libbootloader_message_writer \
     libfs_mgr \
     libfec \
     libfec_rs \
diff --git a/init/builtins.cpp b/init/builtins.cpp
index 2e72832..c8780bb 100644
--- a/init/builtins.cpp
+++ b/init/builtins.cpp
@@ -16,11 +16,13 @@
 
 #include "builtins.h"
 
+#include <dirent.h>
 #include <errno.h>
 #include <fcntl.h>
 #include <mntent.h>
 #include <net/if.h>
 #include <signal.h>
+#include <sched.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
@@ -39,8 +41,10 @@
 #include <selinux/label.h>
 
 #include <fs_mgr.h>
+#include <android-base/file.h>
 #include <android-base/parseint.h>
 #include <android-base/stringprintf.h>
+#include <bootloader_message_writer.h>
 #include <cutils/partition_utils.h>
 #include <cutils/android_reboot.h>
 #include <logwrap/logwrap.h>
@@ -103,6 +107,32 @@
     return ret;
 }
 
+// Turn off backlight while we are performing power down cleanup activities.
+static void turnOffBacklight() {
+    static const char off[] = "0";
+
+    android::base::WriteStringToFile(off, "/sys/class/leds/lcd-backlight/brightness");
+
+    static const char backlightDir[] = "/sys/class/backlight";
+    std::unique_ptr<DIR, int(*)(DIR*)> dir(opendir(backlightDir), closedir);
+    if (!dir) {
+        return;
+    }
+
+    struct dirent *dp;
+    while ((dp = readdir(dir.get())) != NULL) {
+        if (((dp->d_type != DT_DIR) && (dp->d_type != DT_LNK)) ||
+                (dp->d_name[0] == '.')) {
+            continue;
+        }
+
+        std::string fileName = android::base::StringPrintf("%s/%s/brightness",
+                                                           backlightDir,
+                                                           dp->d_name);
+        android::base::WriteStringToFile(off, fileName);
+    }
+}
+
 static void unmount_and_fsck(const struct mntent *entry) {
     if (strcmp(entry->mnt_type, "f2fs") && strcmp(entry->mnt_type, "ext4"))
         return;
@@ -127,6 +157,18 @@
     ServiceManager::GetInstance().ForEachService([] (Service* s) { s->Stop(); });
     TEMP_FAILURE_RETRY(kill(-1, SIGKILL));
 
+    // Restart Watchdogd to allow us to complete umounting and fsck
+    Service *svc = ServiceManager::GetInstance().FindServiceByName("watchdogd");
+    if (svc) {
+        do {
+            sched_yield(); // do not be so eager, let cleanup have priority
+            ServiceManager::GetInstance().ReapAnyOutstandingChildren();
+        } while (svc->flags() & SVC_RUNNING); // Paranoid Cargo
+        svc->Start();
+    }
+
+    turnOffBacklight();
+
     int count = 0;
     while (count++ < UNMOUNT_CHECK_TIMES) {
         int fd = TEMP_FAILURE_RETRY(open(entry->mnt_fsname, O_RDONLY | O_EXCL));
@@ -147,6 +189,11 @@
         }
     }
 
+    // NB: With watchdog still running, there is no cap on the time it takes
+    // to complete the fsck, from the users perspective the device graphics
+    // and responses are locked-up and they may choose to hold the power
+    // button in frustration if it drags out.
+
     int st;
     if (!strcmp(entry->mnt_type, "f2fs")) {
         const char *f2fs_argv[] = {
@@ -404,14 +451,10 @@
 }
 
 static int wipe_data_via_recovery() {
-    mkdir("/cache/recovery", 0700);
-    int fd = open("/cache/recovery/command", O_RDWR|O_CREAT|O_TRUNC|O_CLOEXEC, 0600);
-    if (fd >= 0) {
-        write(fd, "--wipe_data\n", strlen("--wipe_data\n") + 1);
-        write(fd, "--reason=wipe_data_via_recovery\n", strlen("--reason=wipe_data_via_recovery\n") + 1);
-        close(fd);
-    } else {
-        ERROR("could not open /cache/recovery/command\n");
+    const std::vector<std::string> options = {"--wipe_data", "--reason=wipe_data_via_recovery"};
+    std::string err;
+    if (!write_bootloader_message(options, &err)) {
+        ERROR("failed to set bootloader message: %s", err.c_str());
         return -1;
     }
     android_reboot(ANDROID_RB_RESTART2, 0, "recovery");
diff --git a/libcutils/Android.mk b/libcutils/Android.mk
index c0d4d76..0c6e5a1 100644
--- a/libcutils/Android.mk
+++ b/libcutils/Android.mk
@@ -20,6 +20,7 @@
         atomic.c.arm \
         config_utils.c \
         fs_config.c \
+        canned_fs_config.c \
         hashmap.c \
         iosched_policy.c \
         load_file.c \
diff --git a/libcutils/canned_fs_config.c b/libcutils/canned_fs_config.c
new file mode 100644
index 0000000..5800857
--- /dev/null
+++ b/libcutils/canned_fs_config.c
@@ -0,0 +1,117 @@
+/*
+ * Copyright (C) 2014 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 <inttypes.h>
+#include <stdio.h>
+#include <string.h>
+#include <errno.h>
+#include <limits.h>
+#include <stdlib.h>
+
+#include <private/android_filesystem_config.h>
+#include <private/canned_fs_config.h>
+
+typedef struct {
+	const char* path;
+	unsigned uid;
+	unsigned gid;
+	unsigned mode;
+	uint64_t capabilities;
+} Path;
+
+static Path* canned_data = NULL;
+static int canned_alloc = 0;
+static int canned_used = 0;
+
+static int path_compare(const void* a, const void* b) {
+	return strcmp(((Path*)a)->path, ((Path*)b)->path);
+}
+
+int load_canned_fs_config(const char* fn) {
+	FILE* f = fopen(fn, "r");
+	if (f == NULL) {
+		fprintf(stderr, "failed to open %s: %s\n", fn, strerror(errno));
+		return -1;
+	}
+
+	char line[PATH_MAX + 200];
+	while (fgets(line, sizeof(line), f)) {
+		while (canned_used >= canned_alloc) {
+			canned_alloc = (canned_alloc+1) * 2;
+			canned_data = (Path*) realloc(canned_data, canned_alloc * sizeof(Path));
+		}
+		Path* p = canned_data + canned_used;
+		p->path = strdup(strtok(line, " "));
+		p->uid = atoi(strtok(NULL, " "));
+		p->gid = atoi(strtok(NULL, " "));
+		p->mode = strtol(strtok(NULL, " "), NULL, 8);   // mode is in octal
+		p->capabilities = 0;
+
+		char* token = NULL;
+		do {
+			token = strtok(NULL, " ");
+			if (token && strncmp(token, "capabilities=", 13) == 0) {
+				p->capabilities = strtoll(token+13, NULL, 0);
+				break;
+			}
+		} while (token);
+
+		canned_used++;
+	}
+
+	fclose(f);
+
+	qsort(canned_data, canned_used, sizeof(Path), path_compare);
+	printf("loaded %d fs_config entries\n", canned_used);
+
+	return 0;
+}
+
+static const int kDebugCannedFsConfig = 0;
+
+void canned_fs_config(const char* path, int dir, const char* target_out_path,
+					  unsigned* uid, unsigned* gid, unsigned* mode, uint64_t* capabilities) {
+	Path key;
+    key.path = path;
+    if (path[0] == '/')
+        key.path++;   // canned paths lack the leading '/'
+	Path* p = (Path*) bsearch(&key, canned_data, canned_used, sizeof(Path), path_compare);
+	if (p == NULL) {
+		fprintf(stderr, "failed to find [%s] in canned fs_config\n", path);
+		exit(1);
+	}
+	*uid = p->uid;
+	*gid = p->gid;
+	*mode = p->mode;
+	*capabilities = p->capabilities;
+
+	if (kDebugCannedFsConfig) {
+		// for debugging, run the built-in fs_config and compare the results.
+
+		unsigned c_uid, c_gid, c_mode;
+		uint64_t c_capabilities;
+		fs_config(path, dir, target_out_path, &c_uid, &c_gid, &c_mode, &c_capabilities);
+
+		if (c_uid != *uid) printf("%s uid %d %d\n", path, *uid, c_uid);
+		if (c_gid != *gid) printf("%s gid %d %d\n", path, *gid, c_gid);
+		if (c_mode != *mode) printf("%s mode 0%o 0%o\n", path, *mode, c_mode);
+		if (c_capabilities != *capabilities)
+			printf("%s capabilities %" PRIx64 " %" PRIx64 "\n",
+				path,
+				*capabilities,
+				c_capabilities);
+        }
+}
diff --git a/sdcard/sdcard.c b/sdcard/sdcard.c
index d8fda67..befe38c 100644
--- a/sdcard/sdcard.c
+++ b/sdcard/sdcard.c
@@ -43,6 +43,7 @@
 #include <cutils/hashmap.h>
 #include <cutils/log.h>
 #include <cutils/multiuser.h>
+#include <cutils/properties.h>
 #include <packagelistparser/packagelistparser.h>
 
 #include <private/android_filesystem_config.h>
@@ -89,6 +90,9 @@
 
 #define ERROR(x...) ALOGE(x)
 
+#define PROP_SDCARDFS_DEVICE "ro.sys.sdcardfs"
+#define PROP_SDCARDFS_USER "persist.sys.sdcardfs"
+
 #define FUSE_UNKNOWN_INO 0xffffffff
 
 /* Maximum number of bytes to write in one request. */
@@ -1993,6 +1997,29 @@
     return false;
 }
 
+static bool should_use_sdcardfs(void) {
+    char property[PROPERTY_VALUE_MAX];
+
+    // Allow user to have a strong opinion about state
+    property_get(PROP_SDCARDFS_USER, property, "");
+    if (!strcmp(property, "force_on")) {
+        ALOGW("User explicitly enabled sdcardfs");
+        return supports_sdcardfs();
+    } else if (!strcmp(property, "force_off")) {
+        ALOGW("User explicitly disabled sdcardfs");
+        return false;
+    }
+
+    // Fall back to device opinion about state
+    if (property_get_bool(PROP_SDCARDFS_DEVICE, false)) {
+        ALOGW("Device explicitly enabled sdcardfs");
+        return supports_sdcardfs();
+    } else {
+        ALOGW("Device explicitly disabled sdcardfs");
+        return false;
+    }
+}
+
 int main(int argc, char **argv) {
     const char *source_path = NULL;
     const char *label = NULL;
@@ -2065,7 +2092,7 @@
         sleep(1);
     }
 
-    if (supports_sdcardfs()) {
+    if (should_use_sdcardfs()) {
         run_sdcardfs(source_path, label, uid, gid, userid, multi_user, full_write);
     } else {
         run(source_path, label, uid, gid, userid, multi_user, full_write);