Work on issue #62065889: Assess thresholds and criteria for killing...

...background processes (CPU, etc)

Add full configuration params for adjusting these settings (some were
already there).

Also...  as long as we are doing this...

- Get rid of all of the wakelock stuff.  That is completely pointless
now that we aren't even allowing cached processes to hold wake locks.

- This greatly simplifies the code, since we don't need to deal with
two different policies for how we do checks.  Instead, we just regularly
check for CPU and the CPU check interval.

- And make the CPU check more aggressive and have much more flexibility
for tuning: there are now 4 different maximum CPU use levels, depending
on how long the process has been in the cached state.  This allows us to
be more strict on CPU use the longer it is sitting in the background.

Note that CPU use tracking only happens while the device is not
plugged in to power...  I'll leave this for now, but I think in the
future we should think about applying these limits even when plugged
in, because in either case cached apps should really not be doing
much.

Test: manual
Change-Id: I68f4ab68be5f7d5fc4822005107fb60ef07a374d
diff --git a/core/java/android/os/BatteryStats.java b/core/java/android/os/BatteryStats.java
index b178d81..cf4fd99 100644
--- a/core/java/android/os/BatteryStats.java
+++ b/core/java/android/os/BatteryStats.java
@@ -5160,9 +5160,7 @@
                         Uid.Proc.ExcessivePower ew = ps.getExcessivePower(e);
                         if (ew != null) {
                             pw.print(prefix); pw.print("      * Killed for ");
-                                    if (ew.type == Uid.Proc.ExcessivePower.TYPE_WAKE) {
-                                        pw.print("wake lock");
-                                    } else if (ew.type == Uid.Proc.ExcessivePower.TYPE_CPU) {
+                                    if (ew.type == Uid.Proc.ExcessivePower.TYPE_CPU) {
                                         pw.print("cpu");
                                     } else {
                                         pw.print("unknown");
diff --git a/core/java/android/provider/Settings.java b/core/java/android/provider/Settings.java
index e563360..3b6a11d 100755
--- a/core/java/android/provider/Settings.java
+++ b/core/java/android/provider/Settings.java
@@ -9161,9 +9161,11 @@
          * gc_min_interval                      (long)
          * full_pss_min_interval                (long)
          * full_pss_lowered_interval            (long)
-         * power_check_delay                    (long)
-         * wake_lock_min_check_duration         (long)
-         * cpu_min_check_duration               (long)
+         * power_check_interval                 (long)
+         * power_check_max_cpu_1                (int)
+         * power_check_max_cpu_2                (int)
+         * power_check_max_cpu_3                (int)
+         * power_check_max_cpu_4                (int)
          * service_usage_interaction_time       (long)
          * usage_stats_interaction_interval     (long)
          * service_restart_duration             (long)
diff --git a/core/java/com/android/internal/app/procstats/ProcessState.java b/core/java/com/android/internal/app/procstats/ProcessState.java
index 9470668..e0a4053 100644
--- a/core/java/com/android/internal/app/procstats/ProcessState.java
+++ b/core/java/com/android/internal/app/procstats/ProcessState.java
@@ -196,7 +196,6 @@
         ProcessState pnew = new ProcessState(this, mPackage, mUid, mVersion, mName, now);
         pnew.mDurations.addDurations(mDurations);
         pnew.mPssTable.copyFrom(mPssTable, PSS_COUNT);
-        pnew.mNumExcessiveWake = mNumExcessiveWake;
         pnew.mNumExcessiveCpu = mNumExcessiveCpu;
         pnew.mNumCachedKill = mNumCachedKill;
         pnew.mMinCachedKillPss = mMinCachedKillPss;
@@ -250,7 +249,6 @@
     public void add(ProcessState other) {
         mDurations.addDurations(other.mDurations);
         mPssTable.mergeStats(other.mPssTable);
-        mNumExcessiveWake += other.mNumExcessiveWake;
         mNumExcessiveCpu += other.mNumExcessiveCpu;
         if (other.mNumCachedKill > 0) {
             addCachedKill(other.mNumCachedKill, other.mMinCachedKillPss,
@@ -264,7 +262,6 @@
         mStartTime = now;
         mLastPssState = STATE_NOTHING;
         mLastPssTime = 0;
-        mNumExcessiveWake = 0;
         mNumExcessiveCpu = 0;
         mNumCachedKill = 0;
         mMinCachedKillPss = mAvgCachedKillPss = mMaxCachedKillPss = 0;
@@ -286,7 +283,7 @@
         out.writeInt(mMultiPackage ? 1 : 0);
         mDurations.writeToParcel(out);
         mPssTable.writeToParcel(out);
-        out.writeInt(mNumExcessiveWake);
+        out.writeInt(0);  // was mNumExcessiveWake
         out.writeInt(mNumExcessiveCpu);
         out.writeInt(mNumCachedKill);
         if (mNumCachedKill > 0) {
@@ -309,7 +306,7 @@
         if (!mPssTable.readFromParcel(in)) {
             return false;
         }
-        mNumExcessiveWake = in.readInt();
+        in.readInt(); // was mNumExcessiveWake
         mNumExcessiveCpu = in.readInt();
         mNumCachedKill = in.readInt();
         if (mNumCachedKill > 0) {
@@ -493,18 +490,6 @@
         }
     }
 
-    public void reportExcessiveWake(ArrayMap<String, ProcessStateHolder> pkgList) {
-        ensureNotDead();
-        mCommonProcess.mNumExcessiveWake++;
-        if (!mCommonProcess.mMultiPackage) {
-            return;
-        }
-
-        for (int ip=pkgList.size()-1; ip>=0; ip--) {
-            pullFixedProc(pkgList, ip).mNumExcessiveWake++;
-        }
-    }
-
     public void reportExcessiveCpu(ArrayMap<String, ProcessStateHolder> pkgList) {
         ensureNotDead();
         mCommonProcess.mNumExcessiveCpu++;
@@ -895,10 +880,6 @@
                 }
             }
         }
-        if (mNumExcessiveWake != 0) {
-            pw.print(prefix); pw.print("Killed for excessive wake locks: ");
-                    pw.print(mNumExcessiveWake); pw.println(" times");
-        }
         if (mNumExcessiveCpu != 0) {
             pw.print(prefix); pw.print("Killed for excessive CPU use: ");
                     pw.print(mNumExcessiveCpu); pw.println(" times");
@@ -1072,7 +1053,7 @@
             dumpAllPssCheckin(pw);
             pw.println();
         }
-        if (mNumExcessiveWake > 0 || mNumExcessiveCpu > 0 || mNumCachedKill > 0) {
+        if (mNumExcessiveCpu > 0 || mNumCachedKill > 0) {
             pw.print("pkgkills,");
             pw.print(pkgName);
             pw.print(",");
@@ -1082,7 +1063,7 @@
             pw.print(",");
             pw.print(DumpUtils.collapseString(pkgName, itemName));
             pw.print(",");
-            pw.print(mNumExcessiveWake);
+            pw.print("0"); // was mNumExcessiveWake
             pw.print(",");
             pw.print(mNumExcessiveCpu);
             pw.print(",");
@@ -1114,13 +1095,13 @@
             dumpAllPssCheckin(pw);
             pw.println();
         }
-        if (mNumExcessiveWake > 0 || mNumExcessiveCpu > 0 || mNumCachedKill > 0) {
+        if (mNumExcessiveCpu > 0 || mNumCachedKill > 0) {
             pw.print("kills,");
             pw.print(procName);
             pw.print(",");
             pw.print(uid);
             pw.print(",");
-            pw.print(mNumExcessiveWake);
+            pw.print("0"); // was mNumExcessiveWake
             pw.print(",");
             pw.print(mNumExcessiveCpu);
             pw.print(",");
diff --git a/core/java/com/android/internal/os/BatteryStatsImpl.java b/core/java/com/android/internal/os/BatteryStatsImpl.java
index 696dbda..cb00c5e 100644
--- a/core/java/com/android/internal/os/BatteryStatsImpl.java
+++ b/core/java/com/android/internal/os/BatteryStatsImpl.java
@@ -3987,14 +3987,6 @@
         return 0;
     }
 
-    public void reportExcessiveWakeLocked(int uid, String proc, long overTime, long usedTime) {
-        uid = mapUid(uid);
-        Uid u = mUidStats.get(uid);
-        if (u != null) {
-            u.reportExcessiveWakeLocked(proc, overTime, usedTime);
-        }
-    }
-
     public void reportExcessiveCpuLocked(int uid, String proc, long overTime, long usedTime) {
         uid = mapUid(uid);
         Uid u = mUidStats.get(uid);
@@ -7745,17 +7737,6 @@
                 return null;
             }
 
-            public void addExcessiveWake(long overTime, long usedTime) {
-                if (mExcessivePower == null) {
-                    mExcessivePower = new ArrayList<ExcessivePower>();
-                }
-                ExcessivePower ew = new ExcessivePower();
-                ew.type = ExcessivePower.TYPE_WAKE;
-                ew.overTime = overTime;
-                ew.usedTime = usedTime;
-                mExcessivePower.add(ew);
-            }
-
             public void addExcessiveCpu(long overTime, long usedTime) {
                 if (mExcessivePower == null) {
                     mExcessivePower = new ArrayList<ExcessivePower>();
@@ -8570,13 +8551,6 @@
             }
         }
 
-        public void reportExcessiveWakeLocked(String proc, long overTime, long usedTime) {
-            Proc p = getProcessStatsLocked(proc);
-            if (p != null) {
-                p.addExcessiveWake(overTime, usedTime);
-            }
-        }
-
         public void reportExcessiveCpuLocked(String proc, long overTime, long usedTime) {
             Proc p = getProcessStatsLocked(proc);
             if (p != null) {
diff --git a/services/core/java/com/android/server/am/ActivityManagerConstants.java b/services/core/java/com/android/server/am/ActivityManagerConstants.java
index 6c3fe91..2cd2603 100644
--- a/services/core/java/com/android/server/am/ActivityManagerConstants.java
+++ b/services/core/java/com/android/server/am/ActivityManagerConstants.java
@@ -48,9 +48,11 @@
     private static final String KEY_GC_MIN_INTERVAL = "gc_min_interval";
     private static final String KEY_FULL_PSS_MIN_INTERVAL = "full_pss_min_interval";
     private static final String KEY_FULL_PSS_LOWERED_INTERVAL = "full_pss_lowered_interval";
-    private static final String KEY_POWER_CHECK_DELAY = "power_check_delay";
-    private static final String KEY_WAKE_LOCK_MIN_CHECK_DURATION = "wake_lock_min_check_duration";
-    private static final String KEY_CPU_MIN_CHECK_DURATION = "cpu_min_check_duration";
+    private static final String KEY_POWER_CHECK_INTERVAL = "power_check_interval";
+    private static final String KEY_POWER_CHECK_MAX_CPU_1 = "power_check_max_cpu_1";
+    private static final String KEY_POWER_CHECK_MAX_CPU_2 = "power_check_max_cpu_2";
+    private static final String KEY_POWER_CHECK_MAX_CPU_3 = "power_check_max_cpu_3";
+    private static final String KEY_POWER_CHECK_MAX_CPU_4 = "power_check_max_cpu_4";
     private static final String KEY_SERVICE_USAGE_INTERACTION_TIME
             = "service_usage_interaction_time";
     private static final String KEY_USAGE_STATS_INTERACTION_INTERVAL
@@ -73,11 +75,11 @@
     private static final long DEFAULT_GC_MIN_INTERVAL = 60*1000;
     private static final long DEFAULT_FULL_PSS_MIN_INTERVAL = 10*60*1000;
     private static final long DEFAULT_FULL_PSS_LOWERED_INTERVAL = 2*60*1000;
-    private static final long DEFAULT_POWER_CHECK_DELAY = (DEBUG_POWER_QUICK ? 2 : 15) * 60*1000;
-    private static final long DEFAULT_WAKE_LOCK_MIN_CHECK_DURATION
-            = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
-    private static final long DEFAULT_CPU_MIN_CHECK_DURATION
-            = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
+    private static final long DEFAULT_POWER_CHECK_INTERVAL = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
+    private static final int DEFAULT_POWER_CHECK_MAX_CPU_1 = 25;
+    private static final int DEFAULT_POWER_CHECK_MAX_CPU_2 = 25;
+    private static final int DEFAULT_POWER_CHECK_MAX_CPU_3 = 10;
+    private static final int DEFAULT_POWER_CHECK_MAX_CPU_4 = 2;
     private static final long DEFAULT_SERVICE_USAGE_INTERACTION_TIME = 30*60*1000;
     private static final long DEFAULT_USAGE_STATS_INTERACTION_INTERVAL = 24*60*60*1000L;
     private static final long DEFAULT_SERVICE_RESTART_DURATION = 1*1000;
@@ -133,16 +135,26 @@
     // when the request is due to the memory state being lowered.
     long FULL_PSS_LOWERED_INTERVAL = DEFAULT_FULL_PSS_LOWERED_INTERVAL;
 
-    // The rate at which we check for apps using excessive power -- 15 mins.
-    long POWER_CHECK_DELAY = DEFAULT_POWER_CHECK_DELAY;
-
-    // The minimum sample duration we will allow before deciding we have
-    // enough data on wake locks to start killing things.
-    long WAKE_LOCK_MIN_CHECK_DURATION = DEFAULT_WAKE_LOCK_MIN_CHECK_DURATION;
-
     // The minimum sample duration we will allow before deciding we have
     // enough data on CPU usage to start killing things.
-    long CPU_MIN_CHECK_DURATION = DEFAULT_CPU_MIN_CHECK_DURATION;
+    long POWER_CHECK_INTERVAL = DEFAULT_POWER_CHECK_INTERVAL;
+
+    // The maximum CPU (as a percentage) a process is allowed to use over the first
+    // power check interval that it is cached.
+    int POWER_CHECK_MAX_CPU_1 = DEFAULT_POWER_CHECK_MAX_CPU_1;
+
+    // The maximum CPU (as a percentage) a process is allowed to use over the second
+    // power check interval that it is cached.  The home app will never check for less
+    // CPU than this (it will not test against the 3 or 4 levels).
+    int POWER_CHECK_MAX_CPU_2 = DEFAULT_POWER_CHECK_MAX_CPU_2;
+
+    // The maximum CPU (as a percentage) a process is allowed to use over the third
+    // power check interval that it is cached.
+    int POWER_CHECK_MAX_CPU_3 = DEFAULT_POWER_CHECK_MAX_CPU_3;
+
+    // The maximum CPU (as a percentage) a process is allowed to use over the fourth
+    // power check interval that it is cached.
+    int POWER_CHECK_MAX_CPU_4 = DEFAULT_POWER_CHECK_MAX_CPU_4;
 
     // This is the amount of time an app needs to be running a foreground service before
     // we will consider it to be doing interaction for usage stats.
@@ -270,12 +282,16 @@
                     DEFAULT_FULL_PSS_MIN_INTERVAL);
             FULL_PSS_LOWERED_INTERVAL = mParser.getLong(KEY_FULL_PSS_LOWERED_INTERVAL,
                     DEFAULT_FULL_PSS_LOWERED_INTERVAL);
-            POWER_CHECK_DELAY = mParser.getLong(KEY_POWER_CHECK_DELAY,
-                    DEFAULT_POWER_CHECK_DELAY);
-            WAKE_LOCK_MIN_CHECK_DURATION = mParser.getLong(KEY_WAKE_LOCK_MIN_CHECK_DURATION,
-                    DEFAULT_WAKE_LOCK_MIN_CHECK_DURATION);
-            CPU_MIN_CHECK_DURATION = mParser.getLong(KEY_CPU_MIN_CHECK_DURATION,
-                    DEFAULT_CPU_MIN_CHECK_DURATION);
+            POWER_CHECK_INTERVAL = mParser.getLong(KEY_POWER_CHECK_INTERVAL,
+                    DEFAULT_POWER_CHECK_INTERVAL);
+            POWER_CHECK_MAX_CPU_1 = mParser.getInt(KEY_POWER_CHECK_MAX_CPU_1,
+                    DEFAULT_POWER_CHECK_MAX_CPU_1);
+            POWER_CHECK_MAX_CPU_2 = mParser.getInt(KEY_POWER_CHECK_MAX_CPU_2,
+                    DEFAULT_POWER_CHECK_MAX_CPU_2);
+            POWER_CHECK_MAX_CPU_3 = mParser.getInt(KEY_POWER_CHECK_MAX_CPU_3,
+                    DEFAULT_POWER_CHECK_MAX_CPU_3);
+            POWER_CHECK_MAX_CPU_4 = mParser.getInt(KEY_POWER_CHECK_MAX_CPU_4,
+                    DEFAULT_POWER_CHECK_MAX_CPU_4);
             SERVICE_USAGE_INTERACTION_TIME = mParser.getLong(KEY_SERVICE_USAGE_INTERACTION_TIME,
                     DEFAULT_SERVICE_USAGE_INTERACTION_TIME);
             USAGE_STATS_INTERACTION_INTERVAL = mParser.getLong(KEY_USAGE_STATS_INTERACTION_INTERVAL,
@@ -335,12 +351,16 @@
         pw.println(FULL_PSS_MIN_INTERVAL);
         pw.print("  "); pw.print(KEY_FULL_PSS_LOWERED_INTERVAL); pw.print("=");
         pw.println(FULL_PSS_LOWERED_INTERVAL);
-        pw.print("  "); pw.print(KEY_POWER_CHECK_DELAY); pw.print("=");
-        pw.println(POWER_CHECK_DELAY);
-        pw.print("  "); pw.print(KEY_WAKE_LOCK_MIN_CHECK_DURATION); pw.print("=");
-        pw.println(WAKE_LOCK_MIN_CHECK_DURATION);
-        pw.print("  "); pw.print(KEY_CPU_MIN_CHECK_DURATION); pw.print("=");
-        pw.println(CPU_MIN_CHECK_DURATION);
+        pw.print("  "); pw.print(KEY_POWER_CHECK_INTERVAL); pw.print("=");
+        pw.println(POWER_CHECK_INTERVAL);
+        pw.print("  "); pw.print(KEY_POWER_CHECK_MAX_CPU_1); pw.print("=");
+        pw.println(POWER_CHECK_MAX_CPU_1);
+        pw.print("  "); pw.print(KEY_POWER_CHECK_MAX_CPU_2); pw.print("=");
+        pw.println(POWER_CHECK_MAX_CPU_2);
+        pw.print("  "); pw.print(KEY_POWER_CHECK_MAX_CPU_3); pw.print("=");
+        pw.println(POWER_CHECK_MAX_CPU_3);
+        pw.print("  "); pw.print(KEY_POWER_CHECK_MAX_CPU_4); pw.print("=");
+        pw.println(POWER_CHECK_MAX_CPU_4);
         pw.print("  "); pw.print(KEY_SERVICE_USAGE_INTERACTION_TIME); pw.print("=");
         pw.println(SERVICE_USAGE_INTERACTION_TIME);
         pw.print("  "); pw.print(KEY_USAGE_STATS_INTERACTION_INTERVAL); pw.print("=");
diff --git a/services/core/java/com/android/server/am/ActivityManagerService.java b/services/core/java/com/android/server/am/ActivityManagerService.java
index 3675ecf..94bd6f5 100644
--- a/services/core/java/com/android/server/am/ActivityManagerService.java
+++ b/services/core/java/com/android/server/am/ActivityManagerService.java
@@ -255,7 +255,6 @@
 import android.content.IIntentSender;
 import android.content.Intent;
 import android.content.IntentFilter;
-import android.content.IntentSender;
 import android.content.pm.ActivityInfo;
 import android.content.pm.ApplicationInfo;
 import android.content.pm.ConfigurationInfo;
@@ -1320,11 +1319,6 @@
     boolean mDidAppSwitch;
 
     /**
-     * Last time (in realtime) at which we checked for power usage.
-     */
-    long mLastPowerCheckRealtime;
-
-    /**
      * Last time (in uptime) at which we checked for power usage.
      */
     long mLastPowerCheckUptime;
@@ -1658,7 +1652,7 @@
     static final int POST_HEAVY_NOTIFICATION_MSG = 24;
     static final int CANCEL_HEAVY_NOTIFICATION_MSG = 25;
     static final int SHOW_STRICT_MODE_VIOLATION_UI_MSG = 26;
-    static final int CHECK_EXCESSIVE_WAKE_LOCKS_MSG = 27;
+    static final int CHECK_EXCESSIVE_POWER_USE_MSG = 27;
     static final int CLEAR_DNS_CACHE_MSG = 28;
     static final int UPDATE_HTTP_PROXY_MSG = 29;
     static final int SHOW_COMPAT_MODE_DIALOG_UI_MSG = 30;
@@ -2123,12 +2117,12 @@
                 } catch (RemoteException e) {
                 }
             } break;
-            case CHECK_EXCESSIVE_WAKE_LOCKS_MSG: {
+            case CHECK_EXCESSIVE_POWER_USE_MSG: {
                 synchronized (ActivityManagerService.this) {
-                    checkExcessivePowerUsageLocked(true);
-                    removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
-                    Message nmsg = obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
-                    sendMessageDelayed(nmsg, mConstants.POWER_CHECK_DELAY);
+                    checkExcessivePowerUsageLocked();
+                    removeMessages(CHECK_EXCESSIVE_POWER_USE_MSG);
+                    Message nmsg = obtainMessage(CHECK_EXCESSIVE_POWER_USE_MSG);
+                    sendMessageDelayed(nmsg, mConstants.POWER_CHECK_INTERVAL);
                 }
             } break;
             case REPORT_MEM_USAGE_MSG: {
@@ -3003,6 +2997,9 @@
                                     }
                                     ps.addCpuTimeLocked(st.rel_utime, st.rel_stime);
                                     pr.curCpuTime += st.rel_utime + st.rel_stime;
+                                    if (pr.lastCpuTime == 0) {
+                                        pr.lastCpuTime = pr.curCpuTime;
+                                    }
                                 } else {
                                     BatteryStatsImpl.Uid.Proc ps = st.batteryStats;
                                     if (ps == null || !ps.isActive()) {
@@ -7253,8 +7250,8 @@
 
             if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
                 // Start looking for apps that are abusing wake locks.
-                Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
-                mHandler.sendMessageDelayed(nmsg, mConstants.POWER_CHECK_DELAY);
+                Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_POWER_USE_MSG);
+                mHandler.sendMessageDelayed(nmsg, mConstants.POWER_CHECK_INTERVAL);
                 // Tell anyone interested that we are done booting!
                 SystemProperties.set("sys.boot_completed", "1");
 
@@ -12445,12 +12442,6 @@
             mStackSupervisor.goingToSleepLocked();
             sendNotifyVrManagerOfSleepState(true);
             updateOomAdjLocked();
-
-            // Initialize the wake times of all processes.
-            checkExcessivePowerUsageLocked(false);
-            mHandler.removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
-            Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
-            mHandler.sendMessageDelayed(nmsg, mConstants.POWER_CHECK_DELAY);
         }
 
         // Also update state in a special way for running foreground services UI.
@@ -15951,9 +15942,6 @@
                 pw.println("  mBooting=" + mBooting
                         + " mCallFinishBooting=" + mCallFinishBooting
                         + " mBootAnimationComplete=" + mBootAnimationComplete);
-                pw.print("  mLastPowerCheckRealtime=");
-                        TimeUtils.formatDuration(mLastPowerCheckRealtime, pw);
-                        pw.println("");
                 pw.print("  mLastPowerCheckUptime=");
                         TimeUtils.formatDuration(mLastPowerCheckUptime, pw);
                         pw.println("");
@@ -16608,8 +16596,6 @@
 
         Collections.sort(list, comparator);
 
-        final long curRealtime = SystemClock.elapsedRealtime();
-        final long realtimeSince = curRealtime - service.mLastPowerCheckRealtime;
         final long curUptime = SystemClock.uptimeMillis();
         final long uptimeSince = curUptime - service.mLastPowerCheckUptime;
 
@@ -16706,24 +16692,6 @@
                 pw.print(" hasAboveClient="); pw.println(r.hasAboveClient);
 
                 if (r.setProcState >= ActivityManager.PROCESS_STATE_SERVICE) {
-                    if (r.lastWakeTime != 0) {
-                        long wtime;
-                        BatteryStatsImpl stats = service.mBatteryStatsService.getActiveStatistics();
-                        synchronized (stats) {
-                            wtime = stats.getProcessWakeTime(r.info.uid,
-                                    r.pid, curRealtime);
-                        }
-                        long timeUsed = wtime - r.lastWakeTime;
-                        pw.print(prefix);
-                        pw.print("    ");
-                        pw.print("keep awake over ");
-                        TimeUtils.formatDuration(realtimeSince, pw);
-                        pw.print(" used ");
-                        TimeUtils.formatDuration(timeUsed, pw);
-                        pw.print(" (");
-                        pw.print((timeUsed*100)/realtimeSince);
-                        pw.println("%)");
-                    }
                     if (r.lastCpuTime != 0) {
                         long timeUsed = r.curCpuTime - r.lastCpuTime;
                         pw.print(prefix);
@@ -21862,58 +21830,28 @@
         }
     }
 
-    final void checkExcessivePowerUsageLocked(boolean doKills) {
+    final void checkExcessivePowerUsageLocked() {
         updateCpuStatsNow();
 
         BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
-        boolean doWakeKills = doKills;
-        boolean doCpuKills = doKills;
-        if (mLastPowerCheckRealtime == 0) {
-            doWakeKills = false;
-        }
+        boolean doCpuKills = true;
         if (mLastPowerCheckUptime == 0) {
             doCpuKills = false;
         }
-        if (stats.isScreenOn()) {
-            doWakeKills = false;
-        }
-        final long curRealtime = SystemClock.elapsedRealtime();
-        final long realtimeSince = curRealtime - mLastPowerCheckRealtime;
         final long curUptime = SystemClock.uptimeMillis();
         final long uptimeSince = curUptime - mLastPowerCheckUptime;
-        mLastPowerCheckRealtime = curRealtime;
         mLastPowerCheckUptime = curUptime;
-        if (realtimeSince < mConstants.WAKE_LOCK_MIN_CHECK_DURATION) {
-            doWakeKills = false;
-        }
-        if (uptimeSince < mConstants.CPU_MIN_CHECK_DURATION) {
-            doCpuKills = false;
-        }
         int i = mLruProcesses.size();
         while (i > 0) {
             i--;
             ProcessRecord app = mLruProcesses.get(i);
             if (app.setProcState >= ActivityManager.PROCESS_STATE_HOME) {
-                long wtime;
-                synchronized (stats) {
-                    wtime = stats.getProcessWakeTime(app.info.uid,
-                            app.pid, curRealtime);
+                if (app.lastCpuTime <= 0) {
+                    continue;
                 }
-                long wtimeUsed = wtime - app.lastWakeTime;
                 long cputimeUsed = app.curCpuTime - app.lastCpuTime;
                 if (DEBUG_POWER) {
                     StringBuilder sb = new StringBuilder(128);
-                    sb.append("Wake for ");
-                    app.toShortString(sb);
-                    sb.append(": over ");
-                    TimeUtils.formatDuration(realtimeSince, sb);
-                    sb.append(" used ");
-                    TimeUtils.formatDuration(wtimeUsed, sb);
-                    sb.append(" (");
-                    sb.append((wtimeUsed*100)/realtimeSince);
-                    sb.append("%)");
-                    Slog.i(TAG_POWER, sb.toString());
-                    sb.setLength(0);
                     sb.append("CPU for ");
                     app.toShortString(sb);
                     sb.append(": over ");
@@ -21925,29 +21863,33 @@
                     sb.append("%)");
                     Slog.i(TAG_POWER, sb.toString());
                 }
-                // If a process has held a wake lock for more
-                // than 50% of the time during this period,
-                // that sounds bad.  Kill!
-                if (doWakeKills && realtimeSince > 0
-                        && ((wtimeUsed*100)/realtimeSince) >= 50) {
-                    synchronized (stats) {
-                        stats.reportExcessiveWakeLocked(app.info.uid, app.processName,
-                                realtimeSince, wtimeUsed);
+                // If the process has used too much CPU over the last duration, the
+                // user probably doesn't want this, so kill!
+                if (doCpuKills && uptimeSince > 0) {
+                    // What is the limit for this process?
+                    int cpuLimit;
+                    long checkDur = curUptime - app.whenUnimportant;
+                    if (checkDur <= mConstants.POWER_CHECK_INTERVAL) {
+                        cpuLimit = mConstants.POWER_CHECK_MAX_CPU_1;
+                    } else if (checkDur <= (mConstants.POWER_CHECK_INTERVAL*2)
+                            || app.setProcState <= ActivityManager.PROCESS_STATE_HOME) {
+                        cpuLimit = mConstants.POWER_CHECK_MAX_CPU_2;
+                    } else if (checkDur <= (mConstants.POWER_CHECK_INTERVAL*3)) {
+                        cpuLimit = mConstants.POWER_CHECK_MAX_CPU_3;
+                    } else {
+                        cpuLimit = mConstants.POWER_CHECK_MAX_CPU_4;
                     }
-                    app.kill("excessive wake held " + wtimeUsed + " during " + realtimeSince, true);
-                    app.baseProcessTracker.reportExcessiveWake(app.pkgList);
-                } else if (doCpuKills && uptimeSince > 0
-                        && ((cputimeUsed*100)/uptimeSince) >= 25) {
-                    synchronized (stats) {
-                        stats.reportExcessiveCpuLocked(app.info.uid, app.processName,
-                                uptimeSince, cputimeUsed);
+                    if (((cputimeUsed*100)/uptimeSince) >= cpuLimit) {
+                        synchronized (stats) {
+                            stats.reportExcessiveCpuLocked(app.info.uid, app.processName,
+                                    uptimeSince, cputimeUsed);
+                        }
+                        app.kill("excessive cpu " + cputimeUsed + " during " + uptimeSince
+                                + " dur=" + checkDur + " limit=" + cpuLimit, true);
+                        app.baseProcessTracker.reportExcessiveCpu(app.pkgList);
                     }
-                    app.kill("excessive cpu " + cputimeUsed + " during " + uptimeSince, true);
-                    app.baseProcessTracker.reportExcessiveCpu(app.pkgList);
-                } else {
-                    app.lastWakeTime = wtime;
-                    app.lastCpuTime = app.curCpuTime;
                 }
+                app.lastCpuTime = app.curCpuTime;
             }
         }
     }
@@ -22121,15 +22063,10 @@
             if (setImportant && !curImportant) {
                 // This app is no longer something we consider important enough to allow to
                 // use arbitrary amounts of battery power.  Note
-                // its current wake lock time to later know to kill it if
+                // its current CPU time to later know to kill it if
                 // it is not behaving well.
-                BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
-                synchronized (stats) {
-                    app.lastWakeTime = stats.getProcessWakeTime(app.info.uid,
-                            app.pid, nowElapsed);
-                }
-                app.lastCpuTime = app.curCpuTime;
-
+                app.whenUnimportant = now;
+                app.lastCpuTime = 0;
             }
             // Inform UsageStats of important process state change
             // Must be called before updating setProcState
diff --git a/services/core/java/com/android/server/am/ProcessRecord.java b/services/core/java/com/android/server/am/ProcessRecord.java
index 53c7f84..411e973 100644
--- a/services/core/java/com/android/server/am/ProcessRecord.java
+++ b/services/core/java/com/android/server/am/ProcessRecord.java
@@ -143,7 +143,7 @@
     ActiveInstrumentation instr;// Set to currently active instrumentation running in process
     boolean usingWrapper;       // Set to true when process was launched with a wrapper attached
     final ArraySet<BroadcastRecord> curReceivers = new ArraySet<BroadcastRecord>();// receivers currently running in the app
-    long lastWakeTime;          // How long proc held wake lock at last check
+    long whenUnimportant;       // When (uptime) the process last became unimportant
     long lastCpuTime;           // How long proc has run CPU at last check
     long curCpuTime;            // How long proc has run CPU most recently
     long lastRequestedGc;       // When we last asked the app to do a gc
@@ -204,7 +204,7 @@
     boolean whitelistManager;
 
     void dump(PrintWriter pw, String prefix) {
-        final long now = SystemClock.uptimeMillis();
+        final long nowUptime = SystemClock.uptimeMillis();
 
         pw.print(prefix); pw.print("user #"); pw.print(userId);
                 pw.print(" uid="); pw.print(info.uid);
@@ -254,11 +254,11 @@
         pw.print(prefix); pw.print("pid="); pw.print(pid); pw.print(" starting=");
                 pw.println(starting);
         pw.print(prefix); pw.print("lastActivityTime=");
-                TimeUtils.formatDuration(lastActivityTime, now, pw);
+                TimeUtils.formatDuration(lastActivityTime, nowUptime, pw);
                 pw.print(" lastPssTime=");
-                TimeUtils.formatDuration(lastPssTime, now, pw);
+                TimeUtils.formatDuration(lastPssTime, nowUptime, pw);
                 pw.print(" nextPssTime=");
-                TimeUtils.formatDuration(nextPssTime, now, pw);
+                TimeUtils.formatDuration(nextPssTime, nowUptime, pw);
                 pw.println();
         pw.print(prefix); pw.print("adjSeq="); pw.print(adjSeq);
                 pw.print(" lruSeq="); pw.print(lruSeq);
@@ -294,7 +294,7 @@
                 pw.print(" pssProcState="); pw.print(pssProcState);
                 pw.print(" setProcState="); pw.print(setProcState);
                 pw.print(" lastStateTime=");
-                TimeUtils.formatDuration(lastStateTime, now, pw);
+                TimeUtils.formatDuration(lastStateTime, nowUptime, pw);
                 pw.println();
         if (hasShownUi || pendingUiClean || hasAboveClient || treatLikeActivity) {
             pw.print(prefix); pw.print("hasShownUi="); pw.print(hasShownUi);
@@ -334,29 +334,26 @@
         }
         if (lastProviderTime > 0) {
             pw.print(prefix); pw.print("lastProviderTime=");
-            TimeUtils.formatDuration(lastProviderTime, now, pw);
+            TimeUtils.formatDuration(lastProviderTime, nowUptime, pw);
             pw.println();
         }
         if (hasStartedServices) {
             pw.print(prefix); pw.print("hasStartedServices="); pw.println(hasStartedServices);
         }
-        if (setProcState >= ActivityManager.PROCESS_STATE_SERVICE) {
-            long wtime;
-            synchronized (mBatteryStats) {
-                wtime = mBatteryStats.getProcessWakeTime(info.uid,
-                        pid, SystemClock.elapsedRealtime());
-            }
-            pw.print(prefix); pw.print("lastWakeTime="); pw.print(lastWakeTime);
-                    pw.print(" timeUsed=");
-                    TimeUtils.formatDuration(wtime-lastWakeTime, pw); pw.println("");
+        if (setProcState > ActivityManager.PROCESS_STATE_SERVICE) {
             pw.print(prefix); pw.print("lastCpuTime="); pw.print(lastCpuTime);
-                    pw.print(" timeUsed=");
-                    TimeUtils.formatDuration(curCpuTime-lastCpuTime, pw); pw.println("");
+                    if (lastCpuTime > 0) {
+                        pw.print(" timeUsed=");
+                        TimeUtils.formatDuration(curCpuTime - lastCpuTime, pw);
+                    }
+                    pw.print(" whenUnimportant=");
+                    TimeUtils.formatDuration(whenUnimportant - nowUptime, pw);
+                    pw.println();
         }
         pw.print(prefix); pw.print("lastRequestedGc=");
-                TimeUtils.formatDuration(lastRequestedGc, now, pw);
+                TimeUtils.formatDuration(lastRequestedGc, nowUptime, pw);
                 pw.print(" lastLowMemory=");
-                TimeUtils.formatDuration(lastLowMemory, now, pw);
+                TimeUtils.formatDuration(lastLowMemory, nowUptime, pw);
                 pw.print(" reportLowMemory="); pw.println(reportLowMemory);
         if (killed || killedByAm || waitingToKill != null) {
             pw.print(prefix); pw.print("killed="); pw.print(killed);