Merge "Allow dismissing Keyguard from TrustAgentService"
diff --git a/core/java/android/os/BatteryStats.java b/core/java/android/os/BatteryStats.java
index 22e7952..4dfe0de 100644
--- a/core/java/android/os/BatteryStats.java
+++ b/core/java/android/os/BatteryStats.java
@@ -183,7 +183,9 @@
     private static final String BATTERY_DATA = "bt";
     private static final String BATTERY_DISCHARGE_DATA = "dc";
     private static final String BATTERY_LEVEL_DATA = "lv";
+    private static final String GLOBAL_WIFI_DATA = "gwfl";
     private static final String WIFI_DATA = "wfl";
+    private static final String GLOBAL_BLUETOOTH_DATA = "gble";
     private static final String MISC_DATA = "m";
     private static final String GLOBAL_NETWORK_DATA = "gn";
     private static final String HISTORY_STRING_POOL = "hsp";
@@ -200,8 +202,6 @@
     private static final String WIFI_SUPPL_STATE_COUNT_DATA = "wssc";
     private static final String WIFI_SIGNAL_STRENGTH_TIME_DATA = "wsgt";
     private static final String WIFI_SIGNAL_STRENGTH_COUNT_DATA = "wsgc";
-    private static final String BLUETOOTH_STATE_TIME_DATA = "bst";
-    private static final String BLUETOOTH_STATE_COUNT_DATA = "bsc";
     private static final String POWER_USE_SUMMARY_DATA = "pws";
     private static final String POWER_USE_ITEM_DATA = "pwi";
     private static final String DISCHARGE_STEP_DATA = "dsd";
@@ -1898,43 +1898,6 @@
     public abstract int getWifiSignalStrengthCount(int strengthBin, int which);
 
     /**
-     * Returns the time in microseconds that bluetooth has been on while the device was
-     * running on battery.
-     * 
-     * {@hide}
-     */
-    public abstract long getBluetoothOnTime(long elapsedRealtimeUs, int which);
-    
-    public abstract int getBluetoothPingCount();
-
-    public static final int BLUETOOTH_STATE_INACTIVE = 0;
-    public static final int BLUETOOTH_STATE_LOW = 1;
-    public static final int BLUETOOTH_STATE_MEDIUM = 2;
-    public static final int BLUETOOTH_STATE_HIGH = 3;
-
-    static final String[] BLUETOOTH_STATE_NAMES = {
-        "inactive", "low", "med", "high"
-    };
-
-    public static final int NUM_BLUETOOTH_STATES = BLUETOOTH_STATE_HIGH +1;
-
-    /**
-     * Returns the time in microseconds that Bluetooth has been running in the
-     * given active state.
-     *
-     * {@hide}
-     */
-    public abstract long getBluetoothStateTime(int bluetoothState,
-            long elapsedRealtimeUs, int which);
-
-    /**
-     * Returns the number of times that Bluetooth has entered the given active state.
-     *
-     * {@hide}
-     */
-    public abstract int getBluetoothStateCount(int bluetoothState, int which);
-
-    /**
      * Returns the time in microseconds that the flashlight has been on while the device was
      * running on battery.
      *
@@ -2446,9 +2409,6 @@
         final long deviceIdlingTime = getDeviceIdlingTime(rawRealtime, which);
         final int connChanges = getNumConnectivityChange(which);
         final long phoneOnTime = getPhoneOnTime(rawRealtime, which);
-        final long wifiOnTime = getWifiOnTime(rawRealtime, which);
-        final long wifiRunningTime = getGlobalWifiRunningTime(rawRealtime, which);
-        final long bluetoothOnTime = getBluetoothOnTime(rawRealtime, which);
 
         final StringBuilder sb = new StringBuilder(128);
         
@@ -2490,7 +2450,8 @@
                 }
             }
         }
-        
+
+        // Dump network stats
         final long mobileRxTotalBytes = getNetworkActivityBytes(NETWORK_MOBILE_RX_DATA, which);
         final long mobileTxTotalBytes = getNetworkActivityBytes(NETWORK_MOBILE_TX_DATA, which);
         final long wifiRxTotalBytes = getNetworkActivityBytes(NETWORK_WIFI_RX_DATA, which);
@@ -2499,19 +2460,34 @@
         final long mobileTxTotalPackets = getNetworkActivityPackets(NETWORK_MOBILE_TX_DATA, which);
         final long wifiRxTotalPackets = getNetworkActivityPackets(NETWORK_WIFI_RX_DATA, which);
         final long wifiTxTotalPackets = getNetworkActivityPackets(NETWORK_WIFI_TX_DATA, which);
-
-        // Dump network stats
         dumpLine(pw, 0 /* uid */, category, GLOBAL_NETWORK_DATA,
                 mobileRxTotalBytes, mobileTxTotalBytes, wifiRxTotalBytes, wifiTxTotalBytes,
                 mobileRxTotalPackets, mobileTxTotalPackets, wifiRxTotalPackets, wifiTxTotalPackets);
 
+        // Dump Wifi controller stats
+        final long wifiOnTime = getWifiOnTime(rawRealtime, which);
+        final long wifiRunningTime = getGlobalWifiRunningTime(rawRealtime, which);
+        final long wifiIdleTimeMs = getWifiControllerActivity(CONTROLLER_IDLE_TIME, which);
+        final long wifiRxTimeMs = getWifiControllerActivity(CONTROLLER_RX_TIME, which);
+        final long wifiTxTimeMs = getWifiControllerActivity(CONTROLLER_TX_TIME, which);
+        final long wifiPowerMaMs = getWifiControllerActivity(CONTROLLER_POWER_DRAIN, which);
+        dumpLine(pw, 0 /* uid */, category, GLOBAL_WIFI_DATA,
+                wifiOnTime / 1000, wifiRunningTime / 1000,
+                wifiIdleTimeMs, wifiRxTimeMs, wifiTxTimeMs, wifiPowerMaMs / (1000*60*60));
+
+        // Dump Bluetooth controller stats
+        final long btIdleTimeMs = getBluetoothControllerActivity(CONTROLLER_IDLE_TIME, which);
+        final long btRxTimeMs = getBluetoothControllerActivity(CONTROLLER_RX_TIME, which);
+        final long btTxTimeMs = getBluetoothControllerActivity(CONTROLLER_TX_TIME, which);
+        final long btPowerMaMs = getBluetoothControllerActivity(CONTROLLER_POWER_DRAIN, which);
+        dumpLine(pw, 0 /* uid */, category, GLOBAL_BLUETOOTH_DATA,
+                btIdleTimeMs, btRxTimeMs, btTxTimeMs, btPowerMaMs / (1000*60*60));
+
         // Dump misc stats
         dumpLine(pw, 0 /* uid */, category, MISC_DATA,
-                screenOnTime / 1000, phoneOnTime / 1000, wifiOnTime / 1000,
-                wifiRunningTime / 1000, bluetoothOnTime / 1000,
-                mobileRxTotalBytes, mobileTxTotalBytes, wifiRxTotalBytes, wifiTxTotalBytes,
+                screenOnTime / 1000, phoneOnTime / 1000,
                 fullWakeLockTimeTotal / 1000, partialWakeLockTimeTotal / 1000,
-                0 /*legacy input event count*/, getMobileRadioActiveTime(rawRealtime, which) / 1000,
+                getMobileRadioActiveTime(rawRealtime, which) / 1000,
                 getMobileRadioActiveAdjustedTime(which) / 1000, interactiveTime / 1000,
                 powerSaveModeEnabledTime / 1000, connChanges, deviceIdleModeEnabledTime / 1000,
                 getDeviceIdleModeEnabledCount(which), deviceIdlingTime / 1000,
@@ -2581,17 +2557,6 @@
         }
         dumpLine(pw, 0 /* uid */, category, WIFI_SIGNAL_STRENGTH_COUNT_DATA, args);
 
-        // Dump bluetooth state stats
-        args = new Object[NUM_BLUETOOTH_STATES];
-        for (int i=0; i<NUM_BLUETOOTH_STATES; i++) {
-            args[i] = getBluetoothStateTime(i, rawRealtime, which) / 1000;
-        }
-        dumpLine(pw, 0 /* uid */, category, BLUETOOTH_STATE_TIME_DATA, args);
-        for (int i=0; i<NUM_BLUETOOTH_STATES; i++) {
-            args[i] = getBluetoothStateCount(i, which);
-        }
-        dumpLine(pw, 0 /* uid */, category, BLUETOOTH_STATE_COUNT_DATA, args);
-
         if (which == STATS_SINCE_UNPLUGGED) {
             dumpLine(pw, 0 /* uid */, category, BATTERY_LEVEL_DATA, getDischargeStartLevel(),
                     getDischargeCurrentLevel());
@@ -2696,6 +2661,7 @@
                 continue;
             }
             final Uid u = uidStats.valueAt(iu);
+
             // Dump Network stats per uid, if any
             final long mobileBytesRx = u.getNetworkActivityBytes(NETWORK_MOBILE_RX_DATA, which);
             final long mobileBytesTx = u.getNetworkActivityBytes(NETWORK_MOBILE_TX_DATA, which);
@@ -2707,11 +2673,6 @@
             final int mobileActiveCount = u.getMobileRadioActiveCount(which);
             final long wifiPacketsRx = u.getNetworkActivityPackets(NETWORK_WIFI_RX_DATA, which);
             final long wifiPacketsTx = u.getNetworkActivityPackets(NETWORK_WIFI_TX_DATA, which);
-            final long fullWifiLockOnTime = u.getFullWifiLockTime(rawRealtime, which);
-            final long wifiScanTime = u.getWifiScanTime(rawRealtime, which);
-            final int wifiScanCount = u.getWifiScanCount(which);
-            final long uidWifiRunningTime = u.getWifiRunningTime(rawRealtime, which);
-
             if (mobileBytesRx > 0 || mobileBytesTx > 0 || wifiBytesRx > 0 || wifiBytesTx > 0
                     || mobilePacketsRx > 0 || mobilePacketsTx > 0 || wifiPacketsRx > 0
                     || wifiPacketsTx > 0 || mobileActiveTime > 0 || mobileActiveCount > 0) {
@@ -2722,10 +2683,19 @@
                         mobileActiveTime, mobileActiveCount);
             }
 
+            final long fullWifiLockOnTime = u.getFullWifiLockTime(rawRealtime, which);
+            final long wifiScanTime = u.getWifiScanTime(rawRealtime, which);
+            final int wifiScanCount = u.getWifiScanCount(which);
+            final long uidWifiRunningTime = u.getWifiRunningTime(rawRealtime, which);
+            final long uidWifiIdleTimeMs = u.getWifiControllerActivity(CONTROLLER_IDLE_TIME, which);
+            final long uidWifiRxTimeMs = u.getWifiControllerActivity(CONTROLLER_RX_TIME, which);
+            final long uidWifiTxTimeMs = u.getWifiControllerActivity(CONTROLLER_TX_TIME, which);
             if (fullWifiLockOnTime != 0 || wifiScanTime != 0 || wifiScanCount != 0
-                    || uidWifiRunningTime != 0) {
+                    || uidWifiRunningTime != 0 || uidWifiIdleTimeMs != 0 || uidWifiRxTimeMs != 0
+                    || uidWifiTxTimeMs != 0) {
                 dumpLine(pw, uid, category, WIFI_DATA,
-                        fullWifiLockOnTime, wifiScanTime, uidWifiRunningTime, wifiScanCount);
+                        fullWifiLockOnTime, wifiScanTime, uidWifiRunningTime, wifiScanCount,
+                        uidWifiIdleTimeMs, uidWifiRxTimeMs, uidWifiTxTimeMs);
             }
 
             if (u.hasUserActivity()) {
@@ -2983,7 +2953,6 @@
         final long phoneOnTime = getPhoneOnTime(rawRealtime, which);
         final long wifiRunningTime = getGlobalWifiRunningTime(rawRealtime, which);
         final long wifiOnTime = getWifiOnTime(rawRealtime, which);
-        final long bluetoothOnTime = getBluetoothOnTime(rawRealtime, which);
         sb.setLength(0);
         sb.append(prefix);
                 sb.append("  Screen on: "); formatTimeMs(sb, screenOnTime / 1000);
@@ -3332,42 +3301,11 @@
 
         sb.setLength(0);
         sb.append(prefix);
-        sb.append("  WiFi Energy use: ").append(BatteryStatsHelper.makemAh(
+        sb.append("  WiFi Power drain: ").append(BatteryStatsHelper.makemAh(
                 getWifiControllerActivity(CONTROLLER_POWER_DRAIN, which) / (double)(1000*60*60)));
         sb.append(" mAh");
         pw.println(sb.toString());
 
-        sb.setLength(0);
-        sb.append(prefix);
-                sb.append("  Bluetooth on: "); formatTimeMs(sb, bluetoothOnTime / 1000);
-                sb.append("("); sb.append(formatRatioLocked(bluetoothOnTime, whichBatteryRealtime));
-                sb.append(")");
-        pw.println(sb.toString());
-
-        sb.setLength(0);
-        sb.append(prefix);
-        sb.append("  Bluetooth states:");
-        didOne = false;
-        for (int i=0; i<NUM_BLUETOOTH_STATES; i++) {
-            final long time = getBluetoothStateTime(i, rawRealtime, which);
-            if (time == 0) {
-                continue;
-            }
-            sb.append("\n    ");
-            didOne = true;
-            sb.append(BLUETOOTH_STATE_NAMES[i]);
-            sb.append(" ");
-            formatTimeMs(sb, time/1000);
-            sb.append("(");
-            sb.append(formatRatioLocked(time, whichBatteryRealtime));
-            sb.append(") ");
-            sb.append(getPhoneDataConnectionCount(i, which));
-            sb.append("x");
-        }
-
-        if (!didOne) sb.append(" (no activity)");
-        pw.println(sb.toString());
-
         final long bluetoothIdleTimeMs =
                 getBluetoothControllerActivity(CONTROLLER_IDLE_TIME, which);
         final long bluetoothRxTimeMs = getBluetoothControllerActivity(CONTROLLER_RX_TIME, which);
@@ -3399,6 +3337,14 @@
         sb.append(")");
         pw.println(sb.toString());
 
+        sb.setLength(0);
+        sb.append(prefix);
+        sb.append("  Bluetooth Power drain: ").append(BatteryStatsHelper.makemAh(
+                getBluetoothControllerActivity(CONTROLLER_POWER_DRAIN, which) /
+                        (double)(1000*60*60)));
+        sb.append(" mAh");
+        pw.println(sb.toString());
+
         pw.println();
 
         if (which == STATS_SINCE_UNPLUGGED) {
diff --git a/core/java/android/service/gatekeeper/IGateKeeperService.aidl b/core/java/android/service/gatekeeper/IGateKeeperService.aidl
index 9edd04d..4f46701 100644
--- a/core/java/android/service/gatekeeper/IGateKeeperService.aidl
+++ b/core/java/android/service/gatekeeper/IGateKeeperService.aidl
@@ -69,4 +69,11 @@
      * @param uid the Android user id
      */
     long getSecureUserId(int uid);
+
+    /**
+     * Clears secure user id associated with the provided Android ID.
+     * Must be called when password is set to NONE.
+     * @param uid the Android user id.
+     */
+    void clearSecureUserId(int uid);
 }
diff --git a/core/java/android/service/wallpaper/WallpaperService.java b/core/java/android/service/wallpaper/WallpaperService.java
index 1674950..016541f 100644
--- a/core/java/android/service/wallpaper/WallpaperService.java
+++ b/core/java/android/service/wallpaper/WallpaperService.java
@@ -17,6 +17,7 @@
 package android.service.wallpaper;
 
 import android.content.res.TypedArray;
+import android.graphics.Canvas;
 import android.os.SystemProperties;
 import android.view.WindowInsets;
 
@@ -185,6 +186,7 @@
 
         DisplayManager mDisplayManager;
         Display mDisplay;
+        private int mDisplayState;
 
         final BaseSurfaceHolder mSurfaceHolder = new BaseSurfaceHolder() {
             {
@@ -228,7 +230,19 @@
                 throw new UnsupportedOperationException(
                         "Wallpapers do not support keep screen on");
             }
-            
+
+            @Override
+            public Canvas lockCanvas() {
+                if (mDisplayState == Display.STATE_DOZE
+                        || mDisplayState == Display.STATE_DOZE_SUSPEND) {
+                    try {
+                        mSession.pokeDrawLock(mWindow);
+                    } catch (RemoteException e) {
+                        // System server died, can be ignored.
+                    }
+                }
+                return super.lockCanvas();
+            }
         };
 
         final class WallpaperInputEventReceiver extends InputEventReceiver {
@@ -831,9 +845,12 @@
             
             mWindow.setSession(mSession);
 
+            mLayout.packageName = getPackageName();
+
             mDisplayManager = (DisplayManager)getSystemService(Context.DISPLAY_SERVICE);
             mDisplayManager.registerDisplayListener(mDisplayListener, mCaller.getHandler());
             mDisplay = mDisplayManager.getDisplay(Display.DEFAULT_DISPLAY);
+            mDisplayState = mDisplay.getState();
 
             if (DEBUG) Log.v(TAG, "onCreate(): " + this);
             onCreate(mSurfaceHolder);
@@ -873,8 +890,8 @@
 
         void reportVisibility() {
             if (!mDestroyed) {
-                boolean visible = mVisible
-                        & mDisplay != null && mDisplay.getState() != Display.STATE_OFF;
+                mDisplayState = mDisplay == null ? Display.STATE_UNKNOWN : mDisplay.getState();
+                boolean visible = mVisible && mDisplayState != Display.STATE_OFF;
                 if (mReportedVisible != visible) {
                     mReportedVisible = visible;
                     if (DEBUG) Log.v(TAG, "onVisibilityChanged(" + visible
diff --git a/core/java/com/android/internal/app/IBatteryStats.aidl b/core/java/com/android/internal/app/IBatteryStats.aidl
index 4f0e29e..7c5c565 100644
--- a/core/java/com/android/internal/app/IBatteryStats.aidl
+++ b/core/java/com/android/internal/app/IBatteryStats.aidl
@@ -95,9 +95,6 @@
     void noteWifiState(int wifiState, String accessPoint);
     void noteWifiSupplicantStateChanged(int supplState, boolean failedAuth);
     void noteWifiRssiChanged(int newRssi);
-    void noteBluetoothOn();
-    void noteBluetoothOff();
-    void noteBluetoothState(int bluetoothState);
     void noteFullWifiLockAcquired(int uid);
     void noteFullWifiLockReleased(int uid);
     void noteWifiScanStarted(int uid);
diff --git a/core/java/com/android/internal/os/BatteryStatsHelper.java b/core/java/com/android/internal/os/BatteryStatsHelper.java
index 59dbec6..a53d46c 100644
--- a/core/java/com/android/internal/os/BatteryStatsHelper.java
+++ b/core/java/com/android/internal/os/BatteryStatsHelper.java
@@ -136,6 +136,14 @@
                 profile.getAveragePower(PowerProfile.POWER_WIFI_CONTROLLER_TX) != 0;
     }
 
+    public static boolean checkHasBluetoothPowerReporting(BatteryStats stats,
+                                                          PowerProfile profile) {
+        return stats.hasBluetoothActivityReporting() &&
+                profile.getAveragePower(PowerProfile.POWER_BLUETOOTH_CONTROLLER_IDLE) != 0 &&
+                profile.getAveragePower(PowerProfile.POWER_BLUETOOTH_CONTROLLER_RX) != 0 &&
+                profile.getAveragePower(PowerProfile.POWER_BLUETOOTH_CONTROLLER_TX) != 0;
+    }
+
     public BatteryStatsHelper(Context context) {
         this(context, true);
     }
@@ -256,7 +264,8 @@
     }
 
     public static String makemAh(double power) {
-        if (power < .00001) return String.format("%.8f", power);
+        if (power == 0) return "0";
+        else if (power < .00001) return String.format("%.8f", power);
         else if (power < .0001) return String.format("%.7f", power);
         else if (power < .001) return String.format("%.6f", power);
         else if (power < .01) return String.format("%.5f", power);
@@ -342,7 +351,11 @@
         mWifiPowerCalculator.reset();
 
         if (mBluetoothPowerCalculator == null) {
-            mBluetoothPowerCalculator = new BluetoothPowerCalculator();
+            if (checkHasBluetoothPowerReporting(mStats, mPowerProfile)) {
+                mBluetoothPowerCalculator = new BluetoothPowerCalculator();
+            } else {
+                mBluetoothPowerCalculator = new BluetoothPowerCalculator();
+            }
         }
         mBluetoothPowerCalculator.reset();
 
diff --git a/core/java/com/android/internal/os/BatteryStatsImpl.java b/core/java/com/android/internal/os/BatteryStatsImpl.java
index 9e5a54d..405c861 100644
--- a/core/java/com/android/internal/os/BatteryStatsImpl.java
+++ b/core/java/com/android/internal/os/BatteryStatsImpl.java
@@ -19,8 +19,6 @@
 import android.annotation.Nullable;
 import android.app.ActivityManager;
 import android.bluetooth.BluetoothActivityEnergyInfo;
-import android.bluetooth.BluetoothDevice;
-import android.bluetooth.BluetoothHeadset;
 import android.content.Context;
 import android.content.Intent;
 import android.net.ConnectivityManager;
@@ -84,7 +82,6 @@
 import java.util.Calendar;
 import java.util.HashMap;
 import java.util.Iterator;
-import java.util.List;
 import java.util.Map;
 import java.util.concurrent.atomic.AtomicInteger;
 import java.util.concurrent.locks.ReentrantLock;
@@ -107,7 +104,7 @@
     private static final int MAGIC = 0xBA757475; // 'BATSTATS'
 
     // Current on-disk Parcel version
-    private static final int VERSION = 124 + (USE_OLD_HISTORY ? 1000 : 0);
+    private static final int VERSION = 125 + (USE_OLD_HISTORY ? 1000 : 0);
 
     // Maximum number of items we will record in the history.
     private static final int MAX_HISTORY_ITEMS = 2000;
@@ -386,12 +383,6 @@
     final StopwatchTimer[] mWifiSignalStrengthsTimer =
             new StopwatchTimer[NUM_WIFI_SIGNAL_STRENGTH_BINS];
 
-    boolean mBluetoothOn;
-    StopwatchTimer mBluetoothOnTimer;
-
-    int mBluetoothState = -1;
-    final StopwatchTimer[] mBluetoothStateTimer = new StopwatchTimer[NUM_BLUETOOTH_STATES];
-
     int mMobileRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
     long mMobileRadioActiveStartTime;
     StopwatchTimer mMobileRadioActiveTimer;
@@ -402,9 +393,6 @@
 
     int mWifiRadioPowerState = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
 
-    /** Bluetooth headset object */
-    BluetoothHeadset mBtHeadset;
-
     /**
      * These provide time bases that discount the time the device is plugged
      * in to power.
@@ -462,9 +450,6 @@
 
     long mLastWriteTime = 0; // Milliseconds
 
-    private int mBluetoothPingCount;
-    private int mBluetoothPingStart = -1;
-
     private int mPhoneServiceState = -1;
     private int mPhoneServiceStateRaw = -1;
     private int mPhoneSimStateRaw = -1;
@@ -1807,32 +1792,6 @@
         return kwlt;
     }
 
-    private int getCurrentBluetoothPingCount() {
-        if (mBtHeadset != null) {
-            List<BluetoothDevice> deviceList = mBtHeadset.getConnectedDevices();
-            if (deviceList.size() > 0) {
-                return mBtHeadset.getBatteryUsageHint(deviceList.get(0));
-            }
-        }
-        return -1;
-    }
-
-    public int getBluetoothPingCount() {
-        if (mBluetoothPingStart == -1) {
-            return mBluetoothPingCount;
-        } else if (mBtHeadset != null) {
-            return getCurrentBluetoothPingCount() - mBluetoothPingStart;
-        }
-        return 0;
-    }
-
-    public void setBtHeadset(BluetoothHeadset headset) {
-        if (headset != null && mBtHeadset == null && isOnBattery() && mBluetoothPingStart == -1) {
-            mBluetoothPingStart = getCurrentBluetoothPingCount();
-        }
-        mBtHeadset = headset;
-    }
-
     private int writeHistoryTag(HistoryTag tag) {
         Integer idxObj = mHistoryTagPool.get(tag);
         int idx;
@@ -2550,17 +2509,7 @@
 
     public void updateTimeBasesLocked(boolean unplugged, boolean screenOff, long uptime,
             long realtime) {
-        if (mOnBatteryTimeBase.setRunning(unplugged, uptime, realtime)) {
-            if (unplugged) {
-                // Track bt headset ping count
-                mBluetoothPingStart = getCurrentBluetoothPingCount();
-                mBluetoothPingCount = 0;
-            } else {
-                // Track bt headset ping count
-                mBluetoothPingCount = getBluetoothPingCount();
-                mBluetoothPingStart = -1;
-            }
-        }
+        mOnBatteryTimeBase.setRunning(unplugged, uptime, realtime);
 
         boolean unpluggedScreenOff = unplugged && screenOff;
         if (unpluggedScreenOff != mOnBatteryScreenOffTimeBase.isRunning()) {
@@ -3967,46 +3916,6 @@
         }
     }
 
-    public void noteBluetoothOnLocked() {
-        if (!mBluetoothOn) {
-            final long elapsedRealtime = SystemClock.elapsedRealtime();
-            final long uptime = SystemClock.uptimeMillis();
-            mHistoryCur.states2 |= HistoryItem.STATE2_BLUETOOTH_ON_FLAG;
-            if (DEBUG_HISTORY) Slog.v(TAG, "Bluetooth on to: "
-                    + Integer.toHexString(mHistoryCur.states));
-            addHistoryRecordLocked(elapsedRealtime, uptime);
-            mBluetoothOn = true;
-            mBluetoothOnTimer.startRunningLocked(elapsedRealtime);
-            scheduleSyncExternalStatsLocked("bluetooth-on");
-        }
-    }
-
-    public void noteBluetoothOffLocked() {
-        if (mBluetoothOn) {
-            final long elapsedRealtime = SystemClock.elapsedRealtime();
-            final long uptime = SystemClock.uptimeMillis();
-            mHistoryCur.states2 &= ~HistoryItem.STATE2_BLUETOOTH_ON_FLAG;
-            if (DEBUG_HISTORY) Slog.v(TAG, "Bluetooth off to: "
-                    + Integer.toHexString(mHistoryCur.states));
-            addHistoryRecordLocked(elapsedRealtime, uptime);
-            mBluetoothOn = false;
-            mBluetoothOnTimer.stopRunningLocked(elapsedRealtime);
-            scheduleSyncExternalStatsLocked("bluetooth-off");
-        }
-    }
-
-    public void noteBluetoothStateLocked(int bluetoothState) {
-        if (DEBUG) Log.i(TAG, "Bluetooth state -> " + bluetoothState);
-        if (mBluetoothState != bluetoothState) {
-            final long elapsedRealtime = SystemClock.elapsedRealtime();
-            if (mBluetoothState >= 0) {
-                mBluetoothStateTimer[mBluetoothState].stopRunningLocked(elapsedRealtime);
-            }
-            mBluetoothState = bluetoothState;
-            mBluetoothStateTimer[bluetoothState].startRunningLocked(elapsedRealtime);
-        }
-    }
-
     int mWifiFullLockNesting = 0;
 
     public void noteFullWifiLockAcquiredLocked(int uid) {
@@ -4361,20 +4270,6 @@
         return mWifiSignalStrengthsTimer[strengthBin].getCountLocked(which);
     }
 
-    @Override public long getBluetoothOnTime(long elapsedRealtimeUs, int which) {
-        return mBluetoothOnTimer.getTotalTimeLocked(elapsedRealtimeUs, which);
-    }
-
-    @Override public long getBluetoothStateTime(int bluetoothState,
-            long elapsedRealtimeUs, int which) {
-        return mBluetoothStateTimer[bluetoothState].getTotalTimeLocked(
-                elapsedRealtimeUs, which);
-    }
-
-    @Override public int getBluetoothStateCount(int bluetoothState, int which) {
-        return mBluetoothStateTimer[bluetoothState].getCountLocked(which);
-    }
-
     @Override public boolean hasBluetoothActivityReporting() {
         return mHasBluetoothEnergyReporting;
     }
@@ -6828,10 +6723,6 @@
             mWifiSignalStrengthsTimer[i] = new StopwatchTimer(null, -800-i, null,
                     mOnBatteryTimeBase);
         }
-        mBluetoothOnTimer = new StopwatchTimer(null, -6, null, mOnBatteryTimeBase);
-        for (int i=0; i< NUM_BLUETOOTH_STATES; i++) {
-            mBluetoothStateTimer[i] = new StopwatchTimer(null, -500-i, null, mOnBatteryTimeBase);
-        }
         mAudioOnTimer = new StopwatchTimer(null, -7, null, mOnBatteryTimeBase);
         mVideoOnTimer = new StopwatchTimer(null, -8, null, mOnBatteryTimeBase);
         mFlashlightOnTimer = new StopwatchTimer(null, -9, null, mOnBatteryTimeBase);
@@ -7447,10 +7338,6 @@
         for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
             mWifiSignalStrengthsTimer[i].reset(false);
         }
-        mBluetoothOnTimer.reset(false);
-        for (int i=0; i< NUM_BLUETOOTH_STATES; i++) {
-            mBluetoothStateTimer[i].reset(false);
-        }
         for (int i=0; i< NUM_CONTROLLER_ACTIVITY_TYPES; i++) {
             mBluetoothActivityCounters[i].reset(false);
             mWifiActivityCounters[i].reset(false);
@@ -7775,16 +7662,12 @@
             mWifiActivityCounters[CONTROLLER_IDLE_TIME].addCountLocked(
                     info.getControllerIdleTimeMillis());
 
-            final double powerDrainMaMs;
-            if (mPowerProfile.getAveragePower(
-                    PowerProfile.POWER_WIFI_CONTROLLER_OPERATING_VOLTAGE) == 0) {
-                powerDrainMaMs = 0.0;
-            } else {
-                powerDrainMaMs = info.getControllerEnergyUsed()
-                        / mPowerProfile.getAveragePower(
-                        PowerProfile.POWER_WIFI_CONTROLLER_OPERATING_VOLTAGE);
+            final double opVoltage = mPowerProfile.getAveragePower(
+                    PowerProfile.POWER_WIFI_CONTROLLER_OPERATING_VOLTAGE);
+            if (opVoltage != 0) {
+                mWifiActivityCounters[CONTROLLER_POWER_DRAIN].addCountLocked(
+                        (long)(info.getControllerEnergyUsed() / opVoltage));
             }
-            mWifiActivityCounters[CONTROLLER_POWER_DRAIN].addCountLocked((long) powerDrainMaMs);
         }
     }
 
@@ -7872,8 +7755,13 @@
                     info.getControllerTxTimeMillis());
             mBluetoothActivityCounters[CONTROLLER_IDLE_TIME].addCountLocked(
                     info.getControllerIdleTimeMillis());
-            mBluetoothActivityCounters[CONTROLLER_POWER_DRAIN].addCountLocked(
-                    info.getControllerEnergyUsed());
+
+            final double opVoltage = mPowerProfile.getAveragePower(
+                    PowerProfile.POWER_BLUETOOTH_CONTROLLER_OPERATING_VOLTAGE);
+            if (opVoltage != 0) {
+                mBluetoothActivityCounters[CONTROLLER_POWER_DRAIN].addCountLocked(
+                        (long) (info.getControllerEnergyUsed() / opVoltage));
+            }
         }
     }
 
@@ -8972,16 +8860,9 @@
         for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
             mWifiSignalStrengthsTimer[i].readSummaryFromParcelLocked(in);
         }
-        mBluetoothOn = false;
-        mBluetoothOnTimer.readSummaryFromParcelLocked(in);
-        for (int i=0; i< NUM_BLUETOOTH_STATES; i++) {
-            mBluetoothStateTimer[i].readSummaryFromParcelLocked(in);
-        }
-
         for (int i = 0; i < NUM_CONTROLLER_ACTIVITY_TYPES; i++) {
             mBluetoothActivityCounters[i].readSummaryFromParcelLocked(in);
         }
-
         for (int i = 0; i < NUM_CONTROLLER_ACTIVITY_TYPES; i++) {
             mWifiActivityCounters[i].readSummaryFromParcelLocked(in);
         }
@@ -9295,10 +9176,6 @@
         for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
             mWifiSignalStrengthsTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
         }
-        mBluetoothOnTimer.writeSummaryFromParcelLocked(out, NOWREAL_SYS);
-        for (int i=0; i< NUM_BLUETOOTH_STATES; i++) {
-            mBluetoothStateTimer[i].writeSummaryFromParcelLocked(out, NOWREAL_SYS);
-        }
         for (int i=0; i< NUM_CONTROLLER_ACTIVITY_TYPES; i++) {
             mBluetoothActivityCounters[i].writeSummaryFromParcelLocked(out);
         }
@@ -9608,17 +9485,9 @@
             mWifiSignalStrengthsTimer[i] = new StopwatchTimer(null, -800-i,
                     null, mOnBatteryTimeBase, in);
         }
-        mBluetoothOn = false;
-        mBluetoothOnTimer = new StopwatchTimer(null, -6, null, mOnBatteryTimeBase, in);
-        for (int i=0; i< NUM_BLUETOOTH_STATES; i++) {
-            mBluetoothStateTimer[i] = new StopwatchTimer(null, -500-i,
-                    null, mOnBatteryTimeBase, in);
-        }
-
         for (int i = 0; i < NUM_CONTROLLER_ACTIVITY_TYPES; i++) {
             mBluetoothActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase, in);
         }
-
         for (int i = 0; i < NUM_CONTROLLER_ACTIVITY_TYPES; i++) {
             mWifiActivityCounters[i] = new LongSamplingCounter(mOnBatteryTimeBase, in);
         }
@@ -9648,9 +9517,6 @@
         mChargeStepTracker.readFromParcel(in);
         mLastWriteTime = in.readLong();
 
-        mBluetoothPingCount = in.readInt();
-        mBluetoothPingStart = -1;
-
         mKernelWakelockStats.clear();
         int NKW = in.readInt();
         for (int ikw = 0; ikw < NKW; ikw++) {
@@ -9768,10 +9634,6 @@
         for (int i=0; i<NUM_WIFI_SIGNAL_STRENGTH_BINS; i++) {
             mWifiSignalStrengthsTimer[i].writeToParcel(out, uSecRealtime);
         }
-        mBluetoothOnTimer.writeToParcel(out, uSecRealtime);
-        for (int i=0; i< NUM_BLUETOOTH_STATES; i++) {
-            mBluetoothStateTimer[i].writeToParcel(out, uSecRealtime);
-        }
         for (int i=0; i< NUM_CONTROLLER_ACTIVITY_TYPES; i++) {
             mBluetoothActivityCounters[i].writeToParcel(out);
         }
@@ -9798,8 +9660,6 @@
         mChargeStepTracker.writeToParcel(out);
         out.writeLong(mLastWriteTime);
 
-        out.writeInt(getBluetoothPingCount());
-
         if (inclUids) {
             out.writeInt(mKernelWakelockStats.size());
             for (Map.Entry<String, SamplingTimer> ent : mKernelWakelockStats.entrySet()) {
@@ -9918,12 +9778,6 @@
                 pr.println("*** Wifi signal strength #" + i + ":");
                 mWifiSignalStrengthsTimer[i].logState(pr, "  ");
             }
-            pr.println("*** Bluetooth timer:");
-            mBluetoothOnTimer.logState(pr, "  ");
-            for (int i=0; i< NUM_BLUETOOTH_STATES; i++) {
-                pr.println("*** Bluetooth active type #" + i + ":");
-                mBluetoothStateTimer[i].logState(pr, "  ");
-            }
             pr.println("*** Flashlight timer:");
             mFlashlightOnTimer.logState(pr, "  ");
         }
diff --git a/core/java/com/android/internal/os/WifiPowerCalculator.java b/core/java/com/android/internal/os/WifiPowerCalculator.java
index 4fb8b55..961b0df 100644
--- a/core/java/com/android/internal/os/WifiPowerCalculator.java
+++ b/core/java/com/android/internal/os/WifiPowerCalculator.java
@@ -71,7 +71,7 @@
         app.wifiRunningTimeMs = idleTimeMs + rxTimeMs + txTimeMs;
 
         double powerDrain = stats.getWifiControllerActivity(BatteryStats.CONTROLLER_POWER_DRAIN,
-                statsType) / (1000*60*60);
+                statsType) / (double)(1000*60*60);
         if (powerDrain == 0) {
             // Some controllers do not report power drain, so we can calculate it here.
             powerDrain = ((idleTimeMs * mIdleCurrentMa) + (txTimeMs * mTxCurrentMa)
diff --git a/core/java/com/android/internal/os/WifiPowerEstimator.java b/core/java/com/android/internal/os/WifiPowerEstimator.java
index 0172367..c4e2ef6 100644
--- a/core/java/com/android/internal/os/WifiPowerEstimator.java
+++ b/core/java/com/android/internal/os/WifiPowerEstimator.java
@@ -63,7 +63,7 @@
         mTotalAppWifiRunningTimeMs += app.wifiRunningTimeMs;
         final double wifiLockPower = (app.wifiRunningTimeMs * mWifiPowerOn) / (1000*60*60);
 
-        final long wifiScanTimeMs = u.getWifiScanTime(rawRealtimeUs, statsType);
+        final long wifiScanTimeMs = u.getWifiScanTime(rawRealtimeUs, statsType) / 1000;
         final double wifiScanPower = (wifiScanTimeMs * mWifiPowerScan) / (1000*60*60);
 
         double wifiBatchScanPower = 0;
diff --git a/services/core/java/com/android/server/LockSettingsService.java b/services/core/java/com/android/server/LockSettingsService.java
index ee73b1a..16689ee 100644
--- a/services/core/java/com/android/server/LockSettingsService.java
+++ b/services/core/java/com/android/server/LockSettingsService.java
@@ -388,7 +388,9 @@
         byte[] currentHandle = getCurrentHandle(userId);
 
         if (pattern == null) {
+            getGateKeeperService().clearSecureUserId(userId);
             mStorage.writePatternHash(null, userId);
+            maybeUpdateKeystore(null, userId);
             return;
         }
 
@@ -414,7 +416,9 @@
         byte[] currentHandle = getCurrentHandle(userId);
 
         if (password == null) {
+            getGateKeeperService().clearSecureUserId(userId);
             mStorage.writePasswordHash(null, userId);
+            maybeUpdateKeystore(null, userId);
             return;
         }
 
diff --git a/services/core/java/com/android/server/am/BatteryStatsService.java b/services/core/java/com/android/server/am/BatteryStatsService.java
index 6dbe869..905adc0 100644
--- a/services/core/java/com/android/server/am/BatteryStatsService.java
+++ b/services/core/java/com/android/server/am/BatteryStatsService.java
@@ -18,8 +18,6 @@
 
 import android.bluetooth.BluetoothActivityEnergyInfo;
 import android.bluetooth.BluetoothAdapter;
-import android.bluetooth.BluetoothHeadset;
-import android.bluetooth.BluetoothProfile;
 import android.content.Context;
 import android.content.pm.ApplicationInfo;
 import android.content.pm.PackageManager;
@@ -40,7 +38,6 @@
 import android.os.SystemClock;
 import android.os.UserHandle;
 import android.os.WorkSource;
-import android.telephony.DataConnectionRealTimeInfo;
 import android.telephony.SignalStrength;
 import android.telephony.TelephonyManager;
 import android.util.Slog;
@@ -71,8 +68,6 @@
     final BatteryStatsImpl mStats;
     final BatteryStatsHandler mHandler;
     Context mContext;
-    private boolean mBluetoothPendingStats;
-    private BluetoothHeadset mBluetoothHeadset;
     PowerManagerInternal mPowerManagerInternal;
 
     class BatteryStatsHandler extends Handler implements BatteryStatsImpl.ExternalStatsSync {
@@ -618,56 +613,6 @@
         }
     }
 
-    public void noteBluetoothOn() {
-        enforceCallingPermission();
-        BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
-        if (adapter != null) {
-            adapter.getProfileProxy(mContext, mBluetoothProfileServiceListener,
-                                    BluetoothProfile.HEADSET);
-        }
-        synchronized (mStats) {
-            if (mBluetoothHeadset != null) {
-                mStats.noteBluetoothOnLocked();
-                mStats.setBtHeadset(mBluetoothHeadset);
-            } else {
-                mBluetoothPendingStats = true;
-            }
-        }
-    }
-
-    private BluetoothProfile.ServiceListener mBluetoothProfileServiceListener =
-        new BluetoothProfile.ServiceListener() {
-        public void onServiceConnected(int profile, BluetoothProfile proxy) {
-            mBluetoothHeadset = (BluetoothHeadset) proxy;
-            synchronized (mStats) {
-                if (mBluetoothPendingStats) {
-                    mStats.noteBluetoothOnLocked();
-                    mStats.setBtHeadset(mBluetoothHeadset);
-                    mBluetoothPendingStats = false;
-                }
-            }
-        }
-
-        public void onServiceDisconnected(int profile) {
-            mBluetoothHeadset = null;
-        }
-    };
-
-    public void noteBluetoothOff() {
-        enforceCallingPermission();
-        synchronized (mStats) {
-            mBluetoothPendingStats = false;
-            mStats.noteBluetoothOffLocked();
-        }
-    }
-    
-    public void noteBluetoothState(int bluetoothState) {
-        enforceCallingPermission();
-        synchronized (mStats) {
-            mStats.noteBluetoothStateLocked(bluetoothState);
-        }
-    }
-
     public void noteFullWifiLockAcquired(int uid) {
         enforceCallingPermission();
         synchronized (mStats) {