1 /*
2  * Copyright (C) 2011 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.server.am;
18 
19 import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM;
20 import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME;
21 
22 import java.io.IOException;
23 import java.io.OutputStream;
24 import java.nio.ByteBuffer;
25 
26 import android.app.ActivityManager;
27 import android.os.Build;
28 import android.os.SystemClock;
29 import com.android.internal.util.MemInfoReader;
30 import com.android.server.wm.WindowManagerService;
31 
32 import android.content.res.Resources;
33 import android.graphics.Point;
34 import android.os.SystemProperties;
35 import android.net.LocalSocketAddress;
36 import android.net.LocalSocket;
37 import android.util.Slog;
38 import android.view.Display;
39 
40 /**
41  * Activity manager code dealing with processes.
42  */
43 final class ProcessList {
44     private static final String TAG = TAG_WITH_CLASS_NAME ? "ProcessList" : TAG_AM;
45 
46     // The minimum time we allow between crashes, for us to consider this
47     // application to be bad and stop and its services and reject broadcasts.
48     static final int MIN_CRASH_INTERVAL = 60*1000;
49 
50     // OOM adjustments for processes in various states:
51 
52     // Adjustment used in certain places where we don't know it yet.
53     // (Generally this is something that is going to be cached, but we
54     // don't know the exact value in the cached range to assign yet.)
55     static final int UNKNOWN_ADJ = 16;
56 
57     // This is a process only hosting activities that are not visible,
58     // so it can be killed without any disruption.
59     static final int CACHED_APP_MAX_ADJ = 15;
60     static final int CACHED_APP_MIN_ADJ = 9;
61 
62     // The B list of SERVICE_ADJ -- these are the old and decrepit
63     // services that aren't as shiny and interesting as the ones in the A list.
64     static final int SERVICE_B_ADJ = 8;
65 
66     // This is the process of the previous application that the user was in.
67     // This process is kept above other things, because it is very common to
68     // switch back to the previous app.  This is important both for recent
69     // task switch (toggling between the two top recent apps) as well as normal
70     // UI flow such as clicking on a URI in the e-mail app to view in the browser,
71     // and then pressing back to return to e-mail.
72     static final int PREVIOUS_APP_ADJ = 7;
73 
74     // This is a process holding the home application -- we want to try
75     // avoiding killing it, even if it would normally be in the background,
76     // because the user interacts with it so much.
77     static final int HOME_APP_ADJ = 6;
78 
79     // This is a process holding an application service -- killing it will not
80     // have much of an impact as far as the user is concerned.
81     static final int SERVICE_ADJ = 5;
82 
83     // This is a process with a heavy-weight application.  It is in the
84     // background, but we want to try to avoid killing it.  Value set in
85     // system/rootdir/init.rc on startup.
86     static final int HEAVY_WEIGHT_APP_ADJ = 4;
87 
88     // This is a process currently hosting a backup operation.  Killing it
89     // is not entirely fatal but is generally a bad idea.
90     static final int BACKUP_APP_ADJ = 3;
91 
92     // This is a process only hosting components that are perceptible to the
93     // user, and we really want to avoid killing them, but they are not
94     // immediately visible. An example is background music playback.
95     static final int PERCEPTIBLE_APP_ADJ = 2;
96 
97     // This is a process only hosting activities that are visible to the
98     // user, so we'd prefer they don't disappear.
99     static final int VISIBLE_APP_ADJ = 1;
100 
101     // This is the process running the current foreground app.  We'd really
102     // rather not kill it!
103     static final int FOREGROUND_APP_ADJ = 0;
104 
105     // This is a process that the system or a persistent process has bound to,
106     // and indicated it is important.
107     static final int PERSISTENT_SERVICE_ADJ = -11;
108 
109     // This is a system persistent process, such as telephony.  Definitely
110     // don't want to kill it, but doing so is not completely fatal.
111     static final int PERSISTENT_PROC_ADJ = -12;
112 
113     // The system process runs at the default adjustment.
114     static final int SYSTEM_ADJ = -16;
115 
116     // Special code for native processes that are not being managed by the system (so
117     // don't have an oom adj assigned by the system).
118     static final int NATIVE_ADJ = -17;
119 
120     // Memory pages are 4K.
121     static final int PAGE_SIZE = 4*1024;
122 
123     // The minimum number of cached apps we want to be able to keep around,
124     // without empty apps being able to push them out of memory.
125     static final int MIN_CACHED_APPS = 2;
126 
127     // The maximum number of cached processes we will keep around before killing them.
128     // NOTE: this constant is *only* a control to not let us go too crazy with
129     // keeping around processes on devices with large amounts of RAM.  For devices that
130     // are tighter on RAM, the out of memory killer is responsible for killing background
131     // processes as RAM is needed, and we should *never* be relying on this limit to
132     // kill them.  Also note that this limit only applies to cached background processes;
133     // we have no limit on the number of service, visible, foreground, or other such
134     // processes and the number of those processes does not count against the cached
135     // process limit.
136     static final int MAX_CACHED_APPS = 32;
137 
138     // We allow empty processes to stick around for at most 30 minutes.
139     static final long MAX_EMPTY_TIME = 30*60*1000;
140 
141     // The maximum number of empty app processes we will let sit around.
142     private static final int MAX_EMPTY_APPS = computeEmptyProcessLimit(MAX_CACHED_APPS);
143 
144     // The number of empty apps at which we don't consider it necessary to do
145     // memory trimming.
146     static final int TRIM_EMPTY_APPS = MAX_EMPTY_APPS/2;
147 
148     // The number of cached at which we don't consider it necessary to do
149     // memory trimming.
150     static final int TRIM_CACHED_APPS = (MAX_CACHED_APPS-MAX_EMPTY_APPS)/3;
151 
152     // Threshold of number of cached+empty where we consider memory critical.
153     static final int TRIM_CRITICAL_THRESHOLD = 3;
154 
155     // Threshold of number of cached+empty where we consider memory critical.
156     static final int TRIM_LOW_THRESHOLD = 5;
157 
158     // Low Memory Killer Daemon command codes.
159     // These must be kept in sync with the definitions in lmkd.c
160     //
161     // LMK_TARGET <minfree> <minkillprio> ... (up to 6 pairs)
162     // LMK_PROCPRIO <pid> <prio>
163     // LMK_PROCREMOVE <pid>
164     static final byte LMK_TARGET = 0;
165     static final byte LMK_PROCPRIO = 1;
166     static final byte LMK_PROCREMOVE = 2;
167 
168     // These are the various interesting memory levels that we will give to
169     // the OOM killer.  Note that the OOM killer only supports 6 slots, so we
170     // can't give it a different value for every possible kind of process.
171     private final int[] mOomAdj = new int[] {
172             FOREGROUND_APP_ADJ, VISIBLE_APP_ADJ, PERCEPTIBLE_APP_ADJ,
173             BACKUP_APP_ADJ, CACHED_APP_MIN_ADJ, CACHED_APP_MAX_ADJ
174     };
175     // These are the low-end OOM level limits.  This is appropriate for an
176     // HVGA or smaller phone with less than 512MB.  Values are in KB.
177     private final int[] mOomMinFreeLow = new int[] {
178             12288, 18432, 24576,
179             36864, 43008, 49152
180     };
181     // These are the high-end OOM level limits.  This is appropriate for a
182     // 1280x800 or larger screen with around 1GB RAM.  Values are in KB.
183     private final int[] mOomMinFreeHigh = new int[] {
184             73728, 92160, 110592,
185             129024, 147456, 184320
186     };
187     // The actual OOM killer memory levels we are using.
188     private final int[] mOomMinFree = new int[mOomAdj.length];
189 
190     private final long mTotalMemMb;
191 
192     private long mCachedRestoreLevel;
193 
194     private boolean mHaveDisplaySize;
195 
196     private static LocalSocket sLmkdSocket;
197     private static OutputStream sLmkdOutputStream;
198 
ProcessList()199     ProcessList() {
200         MemInfoReader minfo = new MemInfoReader();
201         minfo.readMemInfo();
202         mTotalMemMb = minfo.getTotalSize()/(1024*1024);
203         updateOomLevels(0, 0, false);
204     }
205 
applyDisplaySize(WindowManagerService wm)206     void applyDisplaySize(WindowManagerService wm) {
207         if (!mHaveDisplaySize) {
208             Point p = new Point();
209             wm.getBaseDisplaySize(Display.DEFAULT_DISPLAY, p);
210             if (p.x != 0 && p.y != 0) {
211                 updateOomLevels(p.x, p.y, true);
212                 mHaveDisplaySize = true;
213             }
214         }
215     }
216 
updateOomLevels(int displayWidth, int displayHeight, boolean write)217     private void updateOomLevels(int displayWidth, int displayHeight, boolean write) {
218         // Scale buckets from avail memory: at 300MB we use the lowest values to
219         // 700MB or more for the top values.
220         float scaleMem = ((float)(mTotalMemMb-350))/(700-350);
221 
222         // Scale buckets from screen size.
223         int minSize = 480*800;  //  384000
224         int maxSize = 1280*800; // 1024000  230400 870400  .264
225         float scaleDisp = ((float)(displayWidth*displayHeight)-minSize)/(maxSize-minSize);
226         if (false) {
227             Slog.i("XXXXXX", "scaleMem=" + scaleMem);
228             Slog.i("XXXXXX", "scaleDisp=" + scaleDisp + " dw=" + displayWidth
229                     + " dh=" + displayHeight);
230         }
231 
232         float scale = scaleMem > scaleDisp ? scaleMem : scaleDisp;
233         if (scale < 0) scale = 0;
234         else if (scale > 1) scale = 1;
235         int minfree_adj = Resources.getSystem().getInteger(
236                 com.android.internal.R.integer.config_lowMemoryKillerMinFreeKbytesAdjust);
237         int minfree_abs = Resources.getSystem().getInteger(
238                 com.android.internal.R.integer.config_lowMemoryKillerMinFreeKbytesAbsolute);
239         if (false) {
240             Slog.i("XXXXXX", "minfree_adj=" + minfree_adj + " minfree_abs=" + minfree_abs);
241         }
242 
243         final boolean is64bit = Build.SUPPORTED_64_BIT_ABIS.length > 0;
244 
245         for (int i=0; i<mOomAdj.length; i++) {
246             int low = mOomMinFreeLow[i];
247             int high = mOomMinFreeHigh[i];
248             if (is64bit) {
249                 // Increase the high min-free levels for cached processes for 64-bit
250                 if (i == 4) high = (high*3)/2;
251                 else if (i == 5) high = (high*7)/4;
252             }
253             mOomMinFree[i] = (int)(low + ((high-low)*scale));
254         }
255 
256         if (minfree_abs >= 0) {
257             for (int i=0; i<mOomAdj.length; i++) {
258                 mOomMinFree[i] = (int)((float)minfree_abs * mOomMinFree[i]
259                         / mOomMinFree[mOomAdj.length - 1]);
260             }
261         }
262 
263         if (minfree_adj != 0) {
264             for (int i=0; i<mOomAdj.length; i++) {
265                 mOomMinFree[i] += (int)((float)minfree_adj * mOomMinFree[i]
266                         / mOomMinFree[mOomAdj.length - 1]);
267                 if (mOomMinFree[i] < 0) {
268                     mOomMinFree[i] = 0;
269                 }
270             }
271         }
272 
273         // The maximum size we will restore a process from cached to background, when under
274         // memory duress, is 1/3 the size we have reserved for kernel caches and other overhead
275         // before killing background processes.
276         mCachedRestoreLevel = (getMemLevel(ProcessList.CACHED_APP_MAX_ADJ)/1024) / 3;
277 
278         // Ask the kernel to try to keep enough memory free to allocate 3 full
279         // screen 32bpp buffers without entering direct reclaim.
280         int reserve = displayWidth * displayHeight * 4 * 3 / 1024;
281         int reserve_adj = Resources.getSystem().getInteger(com.android.internal.R.integer.config_extraFreeKbytesAdjust);
282         int reserve_abs = Resources.getSystem().getInteger(com.android.internal.R.integer.config_extraFreeKbytesAbsolute);
283 
284         if (reserve_abs >= 0) {
285             reserve = reserve_abs;
286         }
287 
288         if (reserve_adj != 0) {
289             reserve += reserve_adj;
290             if (reserve < 0) {
291                 reserve = 0;
292             }
293         }
294 
295         if (write) {
296             ByteBuffer buf = ByteBuffer.allocate(4 * (2*mOomAdj.length + 1));
297             buf.putInt(LMK_TARGET);
298             for (int i=0; i<mOomAdj.length; i++) {
299                 buf.putInt((mOomMinFree[i]*1024)/PAGE_SIZE);
300                 buf.putInt(mOomAdj[i]);
301             }
302 
303             writeLmkd(buf);
304             SystemProperties.set("sys.sysctl.extra_free_kbytes", Integer.toString(reserve));
305         }
306         // GB: 2048,3072,4096,6144,7168,8192
307         // HC: 8192,10240,12288,14336,16384,20480
308     }
309 
computeEmptyProcessLimit(int totalProcessLimit)310     public static int computeEmptyProcessLimit(int totalProcessLimit) {
311         return totalProcessLimit/2;
312     }
313 
buildOomTag(String prefix, String space, int val, int base)314     private static String buildOomTag(String prefix, String space, int val, int base) {
315         if (val == base) {
316             if (space == null) return prefix;
317             return prefix + "  ";
318         }
319         return prefix + "+" + Integer.toString(val-base);
320     }
321 
makeOomAdjString(int setAdj)322     public static String makeOomAdjString(int setAdj) {
323         if (setAdj >= ProcessList.CACHED_APP_MIN_ADJ) {
324             return buildOomTag("cch", "  ", setAdj, ProcessList.CACHED_APP_MIN_ADJ);
325         } else if (setAdj >= ProcessList.SERVICE_B_ADJ) {
326             return buildOomTag("svcb ", null, setAdj, ProcessList.SERVICE_B_ADJ);
327         } else if (setAdj >= ProcessList.PREVIOUS_APP_ADJ) {
328             return buildOomTag("prev ", null, setAdj, ProcessList.PREVIOUS_APP_ADJ);
329         } else if (setAdj >= ProcessList.HOME_APP_ADJ) {
330             return buildOomTag("home ", null, setAdj, ProcessList.HOME_APP_ADJ);
331         } else if (setAdj >= ProcessList.SERVICE_ADJ) {
332             return buildOomTag("svc  ", null, setAdj, ProcessList.SERVICE_ADJ);
333         } else if (setAdj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
334             return buildOomTag("hvy  ", null, setAdj, ProcessList.HEAVY_WEIGHT_APP_ADJ);
335         } else if (setAdj >= ProcessList.BACKUP_APP_ADJ) {
336             return buildOomTag("bkup ", null, setAdj, ProcessList.BACKUP_APP_ADJ);
337         } else if (setAdj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
338             return buildOomTag("prcp ", null, setAdj, ProcessList.PERCEPTIBLE_APP_ADJ);
339         } else if (setAdj >= ProcessList.VISIBLE_APP_ADJ) {
340             return buildOomTag("vis  ", null, setAdj, ProcessList.VISIBLE_APP_ADJ);
341         } else if (setAdj >= ProcessList.FOREGROUND_APP_ADJ) {
342             return buildOomTag("fore ", null, setAdj, ProcessList.FOREGROUND_APP_ADJ);
343         } else if (setAdj >= ProcessList.PERSISTENT_SERVICE_ADJ) {
344             return buildOomTag("psvc ", null, setAdj, ProcessList.PERSISTENT_SERVICE_ADJ);
345         } else if (setAdj >= ProcessList.PERSISTENT_PROC_ADJ) {
346             return buildOomTag("pers ", null, setAdj, ProcessList.PERSISTENT_PROC_ADJ);
347         } else if (setAdj >= ProcessList.SYSTEM_ADJ) {
348             return buildOomTag("sys  ", null, setAdj, ProcessList.SYSTEM_ADJ);
349         } else if (setAdj >= ProcessList.NATIVE_ADJ) {
350             return buildOomTag("ntv  ", null, setAdj, ProcessList.NATIVE_ADJ);
351         } else {
352             return Integer.toString(setAdj);
353         }
354     }
355 
makeProcStateString(int curProcState)356     public static String makeProcStateString(int curProcState) {
357         String procState;
358         switch (curProcState) {
359             case -1:
360                 procState = "N ";
361                 break;
362             case ActivityManager.PROCESS_STATE_PERSISTENT:
363                 procState = "P ";
364                 break;
365             case ActivityManager.PROCESS_STATE_PERSISTENT_UI:
366                 procState = "PU";
367                 break;
368             case ActivityManager.PROCESS_STATE_TOP:
369                 procState = "T ";
370                 break;
371             case ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE:
372                 procState = "SB";
373                 break;
374             case ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE:
375                 procState = "SF";
376                 break;
377             case ActivityManager.PROCESS_STATE_TOP_SLEEPING:
378                 procState = "TS";
379                 break;
380             case ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND:
381                 procState = "IF";
382                 break;
383             case ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND:
384                 procState = "IB";
385                 break;
386             case ActivityManager.PROCESS_STATE_BACKUP:
387                 procState = "BU";
388                 break;
389             case ActivityManager.PROCESS_STATE_HEAVY_WEIGHT:
390                 procState = "HW";
391                 break;
392             case ActivityManager.PROCESS_STATE_SERVICE:
393                 procState = "S ";
394                 break;
395             case ActivityManager.PROCESS_STATE_RECEIVER:
396                 procState = "R ";
397                 break;
398             case ActivityManager.PROCESS_STATE_HOME:
399                 procState = "HO";
400                 break;
401             case ActivityManager.PROCESS_STATE_LAST_ACTIVITY:
402                 procState = "LA";
403                 break;
404             case ActivityManager.PROCESS_STATE_CACHED_ACTIVITY:
405                 procState = "CA";
406                 break;
407             case ActivityManager.PROCESS_STATE_CACHED_ACTIVITY_CLIENT:
408                 procState = "Ca";
409                 break;
410             case ActivityManager.PROCESS_STATE_CACHED_EMPTY:
411                 procState = "CE";
412                 break;
413             default:
414                 procState = "??";
415                 break;
416         }
417         return procState;
418     }
419 
appendRamKb(StringBuilder sb, long ramKb)420     public static void appendRamKb(StringBuilder sb, long ramKb) {
421         for (int j=0, fact=10; j<6; j++, fact*=10) {
422             if (ramKb < fact) {
423                 sb.append(' ');
424             }
425         }
426         sb.append(ramKb);
427     }
428 
429     // How long after a state change that it is safe to collect PSS without it being dirty.
430     public static final int PSS_SAFE_TIME_FROM_STATE_CHANGE = 1000;
431 
432     // The minimum time interval after a state change it is safe to collect PSS.
433     public static final int PSS_MIN_TIME_FROM_STATE_CHANGE = 15*1000;
434 
435     // The maximum amount of time we want to go between PSS collections.
436     public static final int PSS_MAX_INTERVAL = 30*60*1000;
437 
438     // The minimum amount of time between successive PSS requests for *all* processes.
439     public static final int PSS_ALL_INTERVAL = 10*60*1000;
440 
441     // The minimum amount of time between successive PSS requests for a process.
442     private static final int PSS_SHORT_INTERVAL = 2*60*1000;
443 
444     // The amount of time until PSS when a process first becomes top.
445     private static final int PSS_FIRST_TOP_INTERVAL = 10*1000;
446 
447     // The amount of time until PSS when a process first goes into the background.
448     private static final int PSS_FIRST_BACKGROUND_INTERVAL = 20*1000;
449 
450     // The amount of time until PSS when a process first becomes cached.
451     private static final int PSS_FIRST_CACHED_INTERVAL = 30*1000;
452 
453     // The amount of time until PSS when an important process stays in the same state.
454     private static final int PSS_SAME_IMPORTANT_INTERVAL = 15*60*1000;
455 
456     // The amount of time until PSS when a service process stays in the same state.
457     private static final int PSS_SAME_SERVICE_INTERVAL = 20*60*1000;
458 
459     // The amount of time until PSS when a cached process stays in the same state.
460     private static final int PSS_SAME_CACHED_INTERVAL = 30*60*1000;
461 
462     // The minimum time interval after a state change it is safe to collect PSS.
463     public static final int PSS_TEST_MIN_TIME_FROM_STATE_CHANGE = 10*1000;
464 
465     // The amount of time during testing until PSS when a process first becomes top.
466     private static final int PSS_TEST_FIRST_TOP_INTERVAL = 3*1000;
467 
468     // The amount of time during testing until PSS when a process first goes into the background.
469     private static final int PSS_TEST_FIRST_BACKGROUND_INTERVAL = 5*1000;
470 
471     // The amount of time during testing until PSS when an important process stays in same state.
472     private static final int PSS_TEST_SAME_IMPORTANT_INTERVAL = 10*1000;
473 
474     // The amount of time during testing until PSS when a background process stays in same state.
475     private static final int PSS_TEST_SAME_BACKGROUND_INTERVAL = 15*1000;
476 
477     public static final int PROC_MEM_PERSISTENT = 0;
478     public static final int PROC_MEM_TOP = 1;
479     public static final int PROC_MEM_IMPORTANT = 2;
480     public static final int PROC_MEM_SERVICE = 3;
481     public static final int PROC_MEM_CACHED = 4;
482 
483     private static final int[] sProcStateToProcMem = new int[] {
484         PROC_MEM_PERSISTENT,            // ActivityManager.PROCESS_STATE_PERSISTENT
485         PROC_MEM_PERSISTENT,            // ActivityManager.PROCESS_STATE_PERSISTENT_UI
486         PROC_MEM_TOP,                   // ActivityManager.PROCESS_STATE_TOP
487         PROC_MEM_IMPORTANT,             // ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE
488         PROC_MEM_IMPORTANT,             // ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE
489         PROC_MEM_TOP,                   // ActivityManager.PROCESS_STATE_TOP_SLEEPING
490         PROC_MEM_IMPORTANT,             // ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND
491         PROC_MEM_IMPORTANT,             // ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND
492         PROC_MEM_IMPORTANT,             // ActivityManager.PROCESS_STATE_BACKUP
493         PROC_MEM_IMPORTANT,             // ActivityManager.PROCESS_STATE_HEAVY_WEIGHT
494         PROC_MEM_SERVICE,               // ActivityManager.PROCESS_STATE_SERVICE
495         PROC_MEM_CACHED,                // ActivityManager.PROCESS_STATE_RECEIVER
496         PROC_MEM_CACHED,                // ActivityManager.PROCESS_STATE_HOME
497         PROC_MEM_CACHED,                // ActivityManager.PROCESS_STATE_LAST_ACTIVITY
498         PROC_MEM_CACHED,                // ActivityManager.PROCESS_STATE_CACHED_ACTIVITY
499         PROC_MEM_CACHED,                // ActivityManager.PROCESS_STATE_CACHED_ACTIVITY_CLIENT
500         PROC_MEM_CACHED,                // ActivityManager.PROCESS_STATE_CACHED_EMPTY
501     };
502 
503     private static final long[] sFirstAwakePssTimes = new long[] {
504         PSS_SHORT_INTERVAL,             // ActivityManager.PROCESS_STATE_PERSISTENT
505         PSS_SHORT_INTERVAL,             // ActivityManager.PROCESS_STATE_PERSISTENT_UI
506         PSS_FIRST_TOP_INTERVAL,         // ActivityManager.PROCESS_STATE_TOP
507         PSS_FIRST_BACKGROUND_INTERVAL,  // ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE
508         PSS_FIRST_BACKGROUND_INTERVAL,  // ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE
509         PSS_FIRST_BACKGROUND_INTERVAL,  // ActivityManager.PROCESS_STATE_TOP_SLEEPING
510         PSS_FIRST_BACKGROUND_INTERVAL,  // ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND
511         PSS_FIRST_BACKGROUND_INTERVAL,  // ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND
512         PSS_FIRST_BACKGROUND_INTERVAL,  // ActivityManager.PROCESS_STATE_BACKUP
513         PSS_FIRST_BACKGROUND_INTERVAL,  // ActivityManager.PROCESS_STATE_HEAVY_WEIGHT
514         PSS_FIRST_BACKGROUND_INTERVAL,  // ActivityManager.PROCESS_STATE_SERVICE
515         PSS_FIRST_CACHED_INTERVAL,      // ActivityManager.PROCESS_STATE_RECEIVER
516         PSS_FIRST_CACHED_INTERVAL,      // ActivityManager.PROCESS_STATE_HOME
517         PSS_FIRST_CACHED_INTERVAL,      // ActivityManager.PROCESS_STATE_LAST_ACTIVITY
518         PSS_FIRST_CACHED_INTERVAL,      // ActivityManager.PROCESS_STATE_CACHED_ACTIVITY
519         PSS_FIRST_CACHED_INTERVAL,      // ActivityManager.PROCESS_STATE_CACHED_ACTIVITY_CLIENT
520         PSS_FIRST_CACHED_INTERVAL,      // ActivityManager.PROCESS_STATE_CACHED_EMPTY
521     };
522 
523     private static final long[] sSameAwakePssTimes = new long[] {
524         PSS_SAME_IMPORTANT_INTERVAL,    // ActivityManager.PROCESS_STATE_PERSISTENT
525         PSS_SAME_IMPORTANT_INTERVAL,    // ActivityManager.PROCESS_STATE_PERSISTENT_UI
526         PSS_SHORT_INTERVAL,             // ActivityManager.PROCESS_STATE_TOP
527         PSS_SAME_IMPORTANT_INTERVAL,    // ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE
528         PSS_SAME_IMPORTANT_INTERVAL,    // ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE
529         PSS_SAME_IMPORTANT_INTERVAL,    // ActivityManager.PROCESS_STATE_TOP_SLEEPING
530         PSS_SAME_IMPORTANT_INTERVAL,    // ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND
531         PSS_SAME_IMPORTANT_INTERVAL,    // ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND
532         PSS_SAME_IMPORTANT_INTERVAL,    // ActivityManager.PROCESS_STATE_BACKUP
533         PSS_SAME_IMPORTANT_INTERVAL,    // ActivityManager.PROCESS_STATE_HEAVY_WEIGHT
534         PSS_SAME_SERVICE_INTERVAL,      // ActivityManager.PROCESS_STATE_SERVICE
535         PSS_SAME_SERVICE_INTERVAL,      // ActivityManager.PROCESS_STATE_RECEIVER
536         PSS_SAME_CACHED_INTERVAL,       // ActivityManager.PROCESS_STATE_HOME
537         PSS_SAME_CACHED_INTERVAL,       // ActivityManager.PROCESS_STATE_LAST_ACTIVITY
538         PSS_SAME_CACHED_INTERVAL,       // ActivityManager.PROCESS_STATE_CACHED_ACTIVITY
539         PSS_SAME_CACHED_INTERVAL,       // ActivityManager.PROCESS_STATE_CACHED_ACTIVITY_CLIENT
540         PSS_SAME_CACHED_INTERVAL,       // ActivityManager.PROCESS_STATE_CACHED_EMPTY
541     };
542 
543     private static final long[] sTestFirstAwakePssTimes = new long[] {
544         PSS_TEST_FIRST_TOP_INTERVAL,        // ActivityManager.PROCESS_STATE_PERSISTENT
545         PSS_TEST_FIRST_TOP_INTERVAL,        // ActivityManager.PROCESS_STATE_PERSISTENT_UI
546         PSS_TEST_FIRST_TOP_INTERVAL,        // ActivityManager.PROCESS_STATE_TOP
547         PSS_FIRST_BACKGROUND_INTERVAL,      // ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE
548         PSS_FIRST_BACKGROUND_INTERVAL,      // ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE
549         PSS_FIRST_BACKGROUND_INTERVAL,      // ActivityManager.PROCESS_STATE_TOP_SLEEPING
550         PSS_TEST_FIRST_BACKGROUND_INTERVAL, // ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND
551         PSS_TEST_FIRST_BACKGROUND_INTERVAL, // ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND
552         PSS_TEST_FIRST_BACKGROUND_INTERVAL, // ActivityManager.PROCESS_STATE_BACKUP
553         PSS_TEST_FIRST_BACKGROUND_INTERVAL, // ActivityManager.PROCESS_STATE_HEAVY_WEIGHT
554         PSS_TEST_FIRST_BACKGROUND_INTERVAL, // ActivityManager.PROCESS_STATE_SERVICE
555         PSS_TEST_FIRST_BACKGROUND_INTERVAL, // ActivityManager.PROCESS_STATE_RECEIVER
556         PSS_TEST_FIRST_BACKGROUND_INTERVAL, // ActivityManager.PROCESS_STATE_HOME
557         PSS_TEST_FIRST_BACKGROUND_INTERVAL, // ActivityManager.PROCESS_STATE_LAST_ACTIVITY
558         PSS_TEST_FIRST_BACKGROUND_INTERVAL, // ActivityManager.PROCESS_STATE_CACHED_ACTIVITY
559         PSS_TEST_FIRST_BACKGROUND_INTERVAL, // ActivityManager.PROCESS_STATE_CACHED_ACTIVITY_CLIENT
560         PSS_TEST_FIRST_BACKGROUND_INTERVAL, // ActivityManager.PROCESS_STATE_CACHED_EMPTY
561     };
562 
563     private static final long[] sTestSameAwakePssTimes = new long[] {
564         PSS_TEST_SAME_BACKGROUND_INTERVAL,  // ActivityManager.PROCESS_STATE_PERSISTENT
565         PSS_TEST_SAME_BACKGROUND_INTERVAL,  // ActivityManager.PROCESS_STATE_PERSISTENT_UI
566         PSS_TEST_SAME_IMPORTANT_INTERVAL,   // ActivityManager.PROCESS_STATE_TOP
567         PSS_TEST_SAME_IMPORTANT_INTERVAL,   // ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE
568         PSS_TEST_SAME_IMPORTANT_INTERVAL,   // ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE
569         PSS_TEST_SAME_IMPORTANT_INTERVAL,   // ActivityManager.PROCESS_STATE_TOP_SLEEPING
570         PSS_TEST_SAME_IMPORTANT_INTERVAL,   // ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND
571         PSS_TEST_SAME_IMPORTANT_INTERVAL,   // ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND
572         PSS_TEST_SAME_IMPORTANT_INTERVAL,   // ActivityManager.PROCESS_STATE_BACKUP
573         PSS_TEST_SAME_IMPORTANT_INTERVAL,   // ActivityManager.PROCESS_STATE_HEAVY_WEIGHT
574         PSS_TEST_SAME_BACKGROUND_INTERVAL,  // ActivityManager.PROCESS_STATE_SERVICE
575         PSS_TEST_SAME_BACKGROUND_INTERVAL,  // ActivityManager.PROCESS_STATE_RECEIVER
576         PSS_TEST_SAME_BACKGROUND_INTERVAL,  // ActivityManager.PROCESS_STATE_HOME
577         PSS_TEST_SAME_BACKGROUND_INTERVAL,  // ActivityManager.PROCESS_STATE_LAST_ACTIVITY
578         PSS_TEST_SAME_BACKGROUND_INTERVAL,  // ActivityManager.PROCESS_STATE_CACHED_ACTIVITY
579         PSS_TEST_SAME_BACKGROUND_INTERVAL,  // ActivityManager.PROCESS_STATE_CACHED_ACTIVITY_CLIENT
580         PSS_TEST_SAME_BACKGROUND_INTERVAL,  // ActivityManager.PROCESS_STATE_CACHED_EMPTY
581     };
582 
procStatesDifferForMem(int procState1, int procState2)583     public static boolean procStatesDifferForMem(int procState1, int procState2) {
584         return sProcStateToProcMem[procState1] != sProcStateToProcMem[procState2];
585     }
586 
minTimeFromStateChange(boolean test)587     public static long minTimeFromStateChange(boolean test) {
588         return test ? PSS_TEST_MIN_TIME_FROM_STATE_CHANGE : PSS_MIN_TIME_FROM_STATE_CHANGE;
589     }
590 
computeNextPssTime(int procState, boolean first, boolean test, boolean sleeping, long now)591     public static long computeNextPssTime(int procState, boolean first, boolean test,
592             boolean sleeping, long now) {
593         final long[] table = test
594                 ? (first
595                         ? sTestFirstAwakePssTimes
596                         : sTestSameAwakePssTimes)
597                 : (first
598                         ? sFirstAwakePssTimes
599                         : sSameAwakePssTimes);
600         return now + table[procState];
601     }
602 
getMemLevel(int adjustment)603     long getMemLevel(int adjustment) {
604         for (int i=0; i<mOomAdj.length; i++) {
605             if (adjustment <= mOomAdj[i]) {
606                 return mOomMinFree[i] * 1024;
607             }
608         }
609         return mOomMinFree[mOomAdj.length-1] * 1024;
610     }
611 
612     /**
613      * Return the maximum pss size in kb that we consider a process acceptable to
614      * restore from its cached state for running in the background when RAM is low.
615      */
getCachedRestoreThresholdKb()616     long getCachedRestoreThresholdKb() {
617         return mCachedRestoreLevel;
618     }
619 
620     /**
621      * Set the out-of-memory badness adjustment for a process.
622      *
623      * @param pid The process identifier to set.
624      * @param uid The uid of the app
625      * @param amt Adjustment value -- lmkd allows -16 to +15.
626      *
627      * {@hide}
628      */
setOomAdj(int pid, int uid, int amt)629     public static final void setOomAdj(int pid, int uid, int amt) {
630         if (amt == UNKNOWN_ADJ)
631             return;
632 
633         long start = SystemClock.elapsedRealtime();
634         ByteBuffer buf = ByteBuffer.allocate(4 * 4);
635         buf.putInt(LMK_PROCPRIO);
636         buf.putInt(pid);
637         buf.putInt(uid);
638         buf.putInt(amt);
639         writeLmkd(buf);
640         long now = SystemClock.elapsedRealtime();
641         if ((now-start) > 250) {
642             Slog.w("ActivityManager", "SLOW OOM ADJ: " + (now-start) + "ms for pid " + pid
643                     + " = " + amt);
644         }
645     }
646 
647     /*
648      * {@hide}
649      */
remove(int pid)650     public static final void remove(int pid) {
651         ByteBuffer buf = ByteBuffer.allocate(4 * 2);
652         buf.putInt(LMK_PROCREMOVE);
653         buf.putInt(pid);
654         writeLmkd(buf);
655     }
656 
openLmkdSocket()657     private static boolean openLmkdSocket() {
658         try {
659             sLmkdSocket = new LocalSocket(LocalSocket.SOCKET_SEQPACKET);
660             sLmkdSocket.connect(
661                 new LocalSocketAddress("lmkd",
662                         LocalSocketAddress.Namespace.RESERVED));
663             sLmkdOutputStream = sLmkdSocket.getOutputStream();
664         } catch (IOException ex) {
665             Slog.w(TAG, "lowmemorykiller daemon socket open failed");
666             sLmkdSocket = null;
667             return false;
668         }
669 
670         return true;
671     }
672 
writeLmkd(ByteBuffer buf)673     private static void writeLmkd(ByteBuffer buf) {
674 
675         for (int i = 0; i < 3; i++) {
676             if (sLmkdSocket == null) {
677                     if (openLmkdSocket() == false) {
678                         try {
679                             Thread.sleep(1000);
680                         } catch (InterruptedException ie) {
681                         }
682                         continue;
683                     }
684             }
685 
686             try {
687                 sLmkdOutputStream.write(buf.array(), 0, buf.position());
688                 return;
689             } catch (IOException ex) {
690                 Slog.w(TAG, "Error writing to lowmemorykiller socket");
691 
692                 try {
693                     sLmkdSocket.close();
694                 } catch (IOException ex2) {
695                 }
696 
697                 sLmkdSocket = null;
698             }
699         }
700     }
701 }
702