Android 进程管理篇(五)-调度策略与优先级

2019-08-18  本文已影响0人  Stan_Z

接上篇cpuset,这篇来看看进程优先级与调度策略管理。

一、进程优先级与调度策略

Linux中,优先级号一共有0-139,其中0-99的是RT(实时)进程,100-139的是非实时进程。
数字越低优先级越高。

实时调度:针对0-99的RT进程
分时调度:针对100-139的普通进程,他们按nice值 -20 - 19来算优先级,越nice优先级越低

SCHED_IDLE idle状态低优先级进程调度

二、调度策略与优先级设置
frameworks/base/core/java/android/os/Process.java

public static final int SCHED_OTHER = 0;
public static final int SCHED_FIFO = 1;
public static final int SCHED_RR = 2;
public static final int SCHED_BATCH = 3;
public static final int SCHED_IDLE = 5;

先看Process中调度策略的划分,与上面介绍的一样。

frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java

static boolean scheduleAsRegularPriority(int tid, boolean suppressLogs) {
    try {
        Process.setThreadScheduler(tid, Process.SCHED_OTHER, 0);
        return true;
    } catch (IllegalArgumentException e) {
        if (!suppressLogs) {
            Slog.w(TAG, "Failed to set scheduling policy, thread does not exist:\n" + e);
        }
    }
    return false;
}
static boolean scheduleAsFifoPriority(int tid, boolean suppressLogs) {
    try {
        Process.setThreadScheduler(tid, Process.SCHED_FIFO | Process.SCHED_RESET_ON_FORK, 1);
        return true;
    } catch (IllegalArgumentException e) {
        if (!suppressLogs) {
            Slog.w(TAG, "Failed to set scheduling policy, thread does not exist:\n" + e);
        }
    }
    return false;
}

首先在AMS中封装了FIFO和NORMAL的两个策略,NORMAL好说,看看FIFO在哪用到

private final boolean applyOomAdjLocked(ProcessRecord app, boolean doingAll, long now,
        long nowElapsed) {
…
setProcessGroup(app.pid, processGroup); //这里上篇文章已经讲过了
if (app.curSchedGroup == ProcessList.SCHED_GROUP_TOP_APP) {
    // do nothing if we already switched to RT
    if (oldSchedGroup != ProcessList.SCHED_GROUP_TOP_APP) {
        mVrController.onTopProcChangedLocked(app);
//UI渲染使用的fifo,但是mUseFifoUiScheduling条件需要打开:
//if (SystemProperties.getInt("sys.use_fifo_ui", 0) != 0) {
//    mUseFifoUiScheduling = true;
// }
但是getprop看了下,压根就没有设置,那就是并没有使用到fifo策略,可能也并没有什么优化效果吧。
        if (mUseFifoUiScheduling) {
            // Switch UI pipeline for app to SCHED_FIFO
            app.savedPriority = Process.getThreadPriority(app.pid);
            scheduleAsFifoPriority(app.pid, /* suppressLogs */true);
            if (app.renderThreadTid != 0) {
                scheduleAsFifoPriority(app.renderThreadTid,
                    /* suppressLogs */true);
                if (DEBUG_OOM_ADJ) {
                    Slog.d("UI_FIFO", "Set RenderThread (TID " +
                        app.renderThreadTid + ") to FIFO");
                }
            } else {
                if (DEBUG_OOM_ADJ) {
                    Slog.d("UI_FIFO", "Not setting RenderThread TID");
                }
            }
        } else {//如果不调整,那么直接就设置优先级。
            // Boost priority for top app UI and render threads
            setThreadPriority(app.pid, TOP_APP_PRIORITY_BOOST);
            if (app.renderThreadTid != 0) {
                try {
                    setThreadPriority(app.renderThreadTid,
                            TOP_APP_PRIORITY_BOOST);
                } catch (IllegalArgumentException e) {
                    // thread died, ignore
                }
            }
        }
    }
}
...
}

这里Process.setThreadScheduler并没有太多的应用,我们直接来看优先级设置吧。else中将top app的UI线程与render线程都设置为TOP_APP_PRIORITY_BOOST优先级,nice值为-10,非常高。

frameworks/base/core/java/android/os/Process.java

public static final int THREAD_PRIORITY_DEFAULT = 0;
public static final int THREAD_PRIORITY_LOWEST = 19;
public static final int THREAD_PRIORITY_BACKGROUND = 10;
public static final int THREAD_PRIORITY_FOREGROUND = -2;
public static final int THREAD_PRIORITY_DISPLAY = -4;
public static final int THREAD_PRIORITY_URGENT_DISPLAY = -8;
public static final int THREAD_PRIORITY_AUDIO = -16;
public static final int THREAD_PRIORITY_URGENT_AUDIO = -19;
public static final int THREAD_PRIORITY_MORE_FAVORABLE = -1;
public static final int THREAD_PRIORITY_LESS_FAVORABLE = +1;
而TOP_APP_PRIORITY_BOOST=-10 定义在AMS中。
public static final native void setThreadPriority(int priority)
        throws IllegalArgumentException, SecurityException;
setThreadPriority在Process中是native方法,那直接jni进去
frameworks/base/core/jni/android_util_Process.cpp
void android_os_Process_setThreadPriority(JNIEnv* env, jobject clazz,
                                              jint pid, jint pri)
{
#if GUARD_THREAD_PRIORITY
    // if we're putting the current thread into the background, check the TLS
    // to make sure this thread isn't guarded.  If it is, raise an exception.
    if (pri >= ANDROID_PRIORITY_BACKGROUND) {
        if (pid == gettid()) {
            void* bgOk = pthread_getspecific(gBgKey);
            if (bgOk == ((void*)0xbaad)) {
                ALOGE("Thread marked fg-only put self in background!");
                jniThrowException(env, "java/lang/SecurityException", "May not put this thread into background");
                return;
            }
        }
    }
#endif
    int rc = androidSetThreadPriority(pid, pri);//设置thread优先级
    if (rc != 0) {
        if (rc == INVALID_OPERATION) {
            signalExceptionForPriorityError(env, errno, pid);
        } else {
            signalExceptionForGroupError(env, errno, pid);
        }
    }
    //ALOGI("Setting priority of %" PRId32 ": %" PRId32 ", getpriority returns %d\n",
    //     pid, pri, getpriority(PRIO_PROCESS, pid));
}

这里主要调用androidSetThreadPriority方法

system/core/libutils/Threads.cpp

int androidSetThreadPriority(pid_t tid, int pri)
{
    int rc = 0;
    int lasterr = 0;
    //如果priority大于等于BACKGROUND,则设置为BACKGROUND类型的调度策略
    if (pri >= ANDROID_PRIORITY_BACKGROUND) {
        rc = set_sched_policy(tid, SP_BACKGROUND);
    //如果priority小于BACKGROUND,且当线程为BACKGROUND类型,则设置为FOREGROUND类型。
    } else if (getpriority(PRIO_PROCESS, tid) >= ANDROID_PRIORITY_BACKGROUND) {
        rc = set_sched_policy(tid, SP_FOREGROUND);
    }
    if (rc) {
        lasterr = errno;
    }
    if (setpriority(PRIO_PROCESS, tid, pri) < 0) {//这里最终设置优先级
        rc = INVALID_OPERATION;
    } else {
        errno = lasterr;
    }
    return rc;
}

这里通过set_sched_policy来调整调度策略,并通过setpriority设置进程优先级。这里不特意区分进程与线程了,反正在linux中都是进程。

system/core/libcutils/sched_policy.cpp

int set_sched_policy(int tid, SchedPolicy policy)
{
    if (tid == 0) {
        tid = gettid();
    }
    policy = _policy(policy);
    pthread_once(&the_once, __initialize);
#if POLICY_DEBUG
    char statfile[64];
    char statline[1024];
    char thread_name[255];
    snprintf(statfile, sizeof(statfile), "/proc/%d/stat", tid);
    memset(thread_name, 0, sizeof(thread_name));
    int fd = open(statfile, O_RDONLY | O_CLOEXEC);
    if (fd >= 0) {
        int rc = read(fd, statline, 1023);
        close(fd);
        statline[rc] = 0;
        char *p = statline;
        char *q;
        for (p = statline; *p != '('; p++);
        p++;
        for (q = p; *q != ')'; q++);
        strncpy(thread_name, p, (q-p));
    }
    switch (policy) {
    case SP_BACKGROUND:
        SLOGD("vvv tid %d (%s)", tid, thread_name);
        break;
    case SP_FOREGROUND:
    case SP_AUDIO_APP:
    case SP_AUDIO_SYS:
    case SP_TOP_APP:
        SLOGD("^^^ tid %d (%s)", tid, thread_name);
        break;
    case SP_SYSTEM:
        SLOGD("/// tid %d (%s)", tid, thread_name);
        break;
    default:
        SLOGD("??? tid %d (%s)", tid, thread_name);
        break;
    }
#endif
    if (schedboost_enabled()) {
        int boost_fd = -1;
        switch (policy) {
        case SP_BACKGROUND:
            boost_fd = bg_schedboost_fd;
            break;
        case SP_FOREGROUND:
        case SP_AUDIO_APP:
        case SP_AUDIO_SYS:
            boost_fd = fg_schedboost_fd;
            break;
        case SP_TOP_APP:
            boost_fd = ta_schedboost_fd;
            break;
        default:
            boost_fd = -1;
            break;
        }
        //add_tid_to_cgroup又继续写节点
        if (boost_fd > 0 && add_tid_to_cgroup(tid, boost_fd) != 0) {
            if (errno != ESRCH && errno != ENOENT)
                return -errno;
        }
    }
    //timerslack是个睡眠策略,就是至少要睡这么长时间才能醒来,属于省电方面的优化策略
    if (__sys_supports_timerslack) {
        set_timerslack_ns(tid, policy == SP_BACKGROUND ?
                               TIMER_SLACK_BG : TIMER_SLACK_FG);
    }
    return 0;
}

这里与前面的cpuset非常相似,依然是写节点,节点前面也提了就是:

            if (schedboost_enabled()) {//这里对应的是sched路径
                filename = "/dev/stune/top-app/tasks";
                ta_schedboost_fd = open(filename, O_WRONLY | O_CLOEXEC);
                filename = "/dev/stune/foreground/tasks";
                fg_schedboost_fd = open(filename, O_WRONLY | O_CLOEXEC);
                filename = "/dev/stune/background/tasks";
                bg_schedboost_fd = open(filename, O_WRONLY | O_CLOEXEC);
            }

那么这里又引入了一个schedtune子系统,简单介绍下:
schedtune是ARM/Linaro为了EAS新增的一个子系统,主要用来控制进程调度选择CPU以及boost触发。通过权重来分配CPU负载能力来实现快速运行。高权重意味着会享受到更好的cpu负载来处理对应的任务,换句话说你能享受相对更好的cpu运行性能。

简单梳理下schedtune和不同类型SchedPolicy之间的对应关系:

/dev/stune/top-app/tasks  SP_TOP_APP
/dev/stune/foreground/tasks  SP_FOREGROUND 
/dev/stune/background/tasks  SP_BACKGROUND

看下具体文件夹内容:

/dev/stune/top-app # ls -al
total 0
drwxr-xr-x 2 system system 0 1970-05-22 03:35 .
dr-xr-xr-x 7 system system 0 1970-05-22 03:35 ..
-rw-r--r-- 1 root   root   0 2019-08-17 18:06 cgroup.clone_children
-rw-r--r-- 1 root   root   0 2019-08-17 18:06 cgroup.procs
-rw-r--r-- 1 root   root   0 2019-08-17 18:06 notify_on_release
-rw-r--r-- 1 root   root   0 2019-08-12 13:41 schedtune.boost
-rw-r--r-- 1 root   root   0 1970-05-22 03:35 schedtune.colocate
-rw-r--r-- 1 root   root   0 2019-08-12 13:41 schedtune.prefer_idle
-rw-r--r-- 1 root   root   0 1970-05-22 03:35 schedtune.sched_boost_no_override
-rw-rw-r-- 1 system system 0 1970-05-22 03:35 tasks

系统配置:
这里/dev/stune相关配置只做了这么一个

 # choose idle CPU for top app tasks
echo 1 > /dev/stune/top-app/schedtune.prefer_idle
上一篇下一篇

猜你喜欢

热点阅读