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