Android About China cpu/cpuset/schedtune All applications are based on process priority , Process types are divided according to different priorities .AMS(ActivityManagerService) and PMS(PackageManagerService) Etc class Process Set process priority 、 Scheduling strategy, etc ;android/osProcess JNI By calling libcutils.so/libutils.so perform getpriority/setpriority/sched_setscheduler/sched_getschedler System call or direct operation CGroup File nodes to achieve set priority , Restrict process CPU Purpose of resources .

By priority , By setting CGroup Of cpu/cpuset/stune Control process acquisition CPU execution time 、 Schedulable CPU Scope, etc , In order to achieve the control of different priority processes .

Android About cpu/cpuset/schedtune Frame structure

Process priority and scheduling strategy run through it from top to bottom , But there are some changes in the names at different levels . Let's go through each of these .

class Process as well as android/os/Process JNI

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

Other services through class Process To set process priority 、 Dispatching side rate, etc .

class Process Medium priority :

public static final int THREAD_PRIORITY_DEFAULT = 0;  The default priority of the application

/*
* ***************************************
* ** Keep in sync with utils/threads.h **
* ***************************************
*/

public static final int THREAD_PRIORITY_LOWEST = 19;  The lowest priority of a thread

public static final int THREAD_PRIORITY_BACKGROUND = 10;  Default priority of background thread

public static final int THREAD_PRIORITY_FOREGROUND = -2;  The standard priority of the foreground process

public static final int THREAD_PRIORITY_DISPLAY = -4;  The system is used to display the priority of the function

public static final int THREAD_PRIORITY_URGENT_DISPLAY = -8;  The priority that the system uses for important display functions

public static final int THREAD_PRIORITY_AUDIO = -16;  Audio thread default priority

public static final int THREAD_PRIORITY_URGENT_AUDIO = -19;  Important audio thread default priority

Scheduling strategy partition :

public static final int SCHED_OTHER = 0; Default scheduling policy , Corresponding CFS Scheduling class

public static final int SCHED_FIFO = 1;  FIFO Scheduling strategy , Corresponding RT Scheduling class

public static final int SCHED_RR = 2;  RR Scheduling strategy , Corresponding RT Scheduling class

public static final int SCHED_BATCH = 3;  Batch scheduling strategy , Corresponding CFS Scheduling class

public static final int SCHED_IDLE = 5;  idle Scheduling strategy

class Process relevant API, It is mainly used for :

public static final native void setThreadPriority(int tid, int priority)
        throws IllegalArgumentException, SecurityException;

public static final native void setThreadScheduler(int tid, int policy, int priority)
        throws IllegalArgumentException;

public static final native void setThreadPriority(int tid, int priority)
        throws IllegalArgumentException, SecurityException;

public static final native int getThreadPriority(int tid)
        throws IllegalArgumentException;

public static final native int getThreadScheduler(int tid)
        throws IllegalArgumentException;

public static final native void setThreadGroup(int tid, int group)
        throws IllegalArgumentException, SecurityException;

public static final native void setProcessGroup(int pid, int group)
        throws IllegalArgumentException, SecurityException;

frameworks/base/core/jni/android_util_Process.cpp

Corresponding JNINativeMethod as follows :

static const JNINativeMethod methods[] = {

    {"setThreadPriority",   "(II)V", (void*)android_os_Process_setThreadPriority},
    {"setThreadScheduler",  "(III)V", (void*)android_os_Process_setThreadScheduler},
    {"setCanSelfBackground", "(Z)V", (void*)android_os_Process_setCanSelfBackground},
    {"setThreadPriority",   "(I)V", (void*)android_os_Process_setCallingThreadPriority},
    {"getThreadPriority",   "(I)I", (void*)android_os_Process_getThreadPriority},
    {"getThreadScheduler",   "(I)I", (void*)android_os_Process_getThreadScheduler},
    {"setThreadGroup",      "(II)V", (void*)android_os_Process_setThreadGroup},
    {"setProcessGroup",     "(II)V", (void*)android_os_Process_setProcessGroup},
    {"getProcessGroup",     "(I)I", (void*)android_os_Process_getProcessGroup},

};

scheduler relevant API Call directly sched_setscheduler/sched_getscheduler.

libcutils.so/libutils.so

Before introducing this function, let's first introduce the priority definition used here , It can be seen that and class Process It is a complete correspondence :

ANDROID_PRIORITY_LOWEST         =  19,

/* use for background tasks */
ANDROID_PRIORITY_BACKGROUND     =  10,

/* most threads run at normal priority */
ANDROID_PRIORITY_NORMAL         =   0,

/* threads currently running a UI that the user is interacting with */
ANDROID_PRIORITY_FOREGROUND     =  -2,

/* the main UI thread has a slightly more favorable priority */
ANDROID_PRIORITY_DISPLAY        =  -4,

/* ui service treads might want to run at a urgent display (uncommon) */
ANDROID_PRIORITY_URGENT_DISPLAY =  HAL_PRIORITY_URGENT_DISPLAY,

/* all normal audio threads */
ANDROID_PRIORITY_AUDIO          = -16,

/* service audio threads (uncommon) */
ANDROID_PRIORITY_URGENT_AUDIO   = -19,

/* should never be used in practice. regular process might not
* be allowed to use this level */
ANDROID_PRIORITY_HIGHEST        = -20,

ANDROID_PRIORITY_DEFAULT        = ANDROID_PRIORITY_NORMAL,

We still need to study ,Sched Policy Priority mapping relationships used in :

/* Keep in sync with THREAD_GROUP_* in frameworks/base/core/java/android/os/Process.java */
typedef enum {
    SP_DEFAULT    = -1,
    SP_BACKGROUND = 0,
    SP_FOREGROUND = 1,
    SP_SYSTEM     = 2,  // can't be used with set_sched_policy()
    SP_AUDIO_APP  = 3,
    SP_AUDIO_SYS  = 4,
    SP_TOP_APP    = 5,
    SP_CNT,
    SP_MAX        = SP_CNT - 1,
    SP_SYSTEM_DEFAULT = SP_FOREGROUND,
} SchedPolicy;

Threads.cpp It defines androidSetThreadPriority Used to set the priority of a thread .

int androidSetThreadPriority(pid_t tid, int pri)
{
    int rc = 0;
    int lasterr = 0;

if (pri >= ANDROID_PRIORITY_BACKGROUND) {  If priority Greater than or equal to BACKGROUND, Is set to BACKGROUND Type of scheduling policy .
        rc = set_sched_policy(tid, SP_BACKGROUND);
    } else if (getpriority(PRIO_PROCESS, tid) >= ANDROID_PRIORITY_BACKGROUND) {  If priority Less than BACKGROUND, And when the thread is BACKGROUND type , Is set to FOREGROUND type .
        rc = set_sched_policy(tid, SP_FOREGROUND);
    }

if (rc) {
        lasterr = errno;
    }

if (setpriority(PRIO_PROCESS, tid, pri) < 0) {  set priority
        rc = INVALID_OPERATION;
    } else {
        errno = lasterr;
    }

return rc;
}

set_cpuset_policy according to SchedPolicy Type will tid write in cpuset and schedtune In the subsystem .

We have the following function to get cpuset、schedtune And different types of SchedPolicy The correspondence between :

/dev/cpuset/foreground/tasks  SP_FOREGROUND SP_AUDIO_APP SP_AUDIO_SYS
/dev/cpuset/background/tasks  SP_BACKGROUND
/dev/cpuset/system-background/tasks  SP_SYSTEM
/dev/cpuset/top-app/tasks  SP_TOP_APP

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

int set_cpuset_policy(int tid, SchedPolicy policy)
{
    // in the absence of cpusets, use the old sched policy
#ifndef USE_CPUSETS
    return set_sched_policy(tid, policy);
#else
    if (tid == 0) {
        tid = gettid();
    }
    policy = _policy(policy);
    pthread_once(&the_once, __initialize);

int fd = -1;
    int boost_fd = -1;
    switch (policy) {
    case SP_BACKGROUND:
        fd = bg_cpuset_fd;
        boost_fd = bg_schedboost_fd;
        break;
    case SP_FOREGROUND:
    case SP_AUDIO_APP:
    case SP_AUDIO_SYS:
        fd = fg_cpuset_fd;
        boost_fd = fg_schedboost_fd;
        break;
    case SP_TOP_APP :
        fd = ta_cpuset_fd;
        boost_fd = ta_schedboost_fd;
        break;
    case SP_SYSTEM:
        fd = system_bg_cpuset_fd;
        break;
    default:
        boost_fd = fd = -1;
        break;
    }

if (add_tid_to_cgroup(tid, fd) != 0) {
        if (errno != ESRCH && errno != ENOENT)
            return -errno;
    }

#ifdef USE_SCHEDBOOST
    if (boost_fd > 0 && add_tid_to_cgroup(tid, boost_fd) != 0) {
        if (errno != ESRCH && errno != ENOENT)
            return -errno;
    }
#endif

return 0;
#endif
}

set_sched_policy Set up cpu/schedtune Two subsystems , Subsystem nodes and SchedPolicy The corresponding types are as follows :

/dev/cpuctl/tasks  SP_FOREGROUND SP_AUDIO_APP SP_AUDIO_SYS
/dev/cpuctl/bg_non_interactive/tasks  SP_BACKGROUND

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

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 (__sys_supports_schedgroups) {  Whether to enable schedtune CGroup
        int fd = -1;
        int boost_fd = -1;
        switch (policy) {
        case SP_BACKGROUND:
            fd = bg_cgroup_fd;
            boost_fd = bg_schedboost_fd;
            break;
        case SP_FOREGROUND:
        case SP_AUDIO_APP:
        case SP_AUDIO_SYS:
            fd = fg_cgroup_fd;
            boost_fd = fg_schedboost_fd;
            break;
        case SP_TOP_APP:
            fd = fg_cgroup_fd;
            boost_fd = ta_schedboost_fd;
            break;
        default:
            fd = -1;
            boost_fd = -1;
            break;
        }

if (add_tid_to_cgroup(tid, fd) != 0) {
    
      if (errno != ESRCH && errno != ENOENT)
                return -errno;
        }

#ifdef USE_SCHEDBOOST
        if (boost_fd > 0 && add_tid_to_cgroup(tid, boost_fd) != 0) {
            if (errno != ESRCH && errno != ENOENT)
                return -errno;
        }
#endif
    } else {  If not enabled schedtune CGroup, The system call is used sched_setscheduler Set to SCHED_BATCH perhaps SCHED_NORMAL
        struct sched_param param;

param.sched_priority = 0;
        sched_setscheduler(tid,
                           (policy == SP_BACKGROUND) ?
                           SCHED_BATCH : SCHED_NORMAL,
                           &param);
    }

if (__sys_supports_timerslack) {
        set_timerslack_ns(tid, policy == SP_BACKGROUND ?
                               TIMER_SLACK_BG : TIMER_SLACK_FG);
    }

return 0;
}

The above series of transformations can be shown in the figure below :

system\core\libcutils\Sched_policy.c in , Yes SP_* series SchedPolicy Convert to using different cpuctl、cpuset、stune Handle , The corresponding pid、tid write in tasks in .
SP_BACKGROUND Corresponding SCHED_BACH Scheduling strategy , Other correspondence SCHED_NORMAL.
SCHED_NORMAL: Default scheduling policy , In the old version it was SCHED_OTHER.SCHED_BATCH: For batch processes .SCHED_IDLE: The process using this schedule side rate has the lowest priority .
SCHED_NORMAL and SCHED_BATCH The difference is just when you wake up again , Waking up more frequent processes is not suitable for SCHED_BATCH.
If enabled __sys_supports_schedgroups, Will not call sched_setscheduler To set up SchedulePolicy.

SCHED_NORMAL and SCHED_BACH difference

SP_BACKGROUND Corresponding SCHED_BACH Scheduling strategy , Other correspondence SCHED_NORMAL.

SCHED_NORMAL: Default scheduling policy , In the old version it was SCHED_OTHER.SCHED_BATCH: For batch processes .SCHED_IDLE: The process using this schedule side rate has the lowest priority .

SCHED_NORMAL and SCHED_BATCH The difference is just when you wake up again , Waking up more frequent processes is not suitable for SCHED_BATCH.

If enabled __sys_supports_schedgroups, Will not call sched_setscheduler To set up SchedulePolicy.

Android One of the applications in

cpu Subsystem :

# Create cgroup mount points for process groups

mkdir /dev/cpuctl

mount cgroup none /dev/cpuctl cpu

chown system system /dev/cpuctl

chown system system /dev/cpuctl/tasks

chmod 0666 /dev/cpuctl/tasks

write /dev/cpuctl/cpu.shares 1024

write /dev/cpuctl/cpu.rt_runtime_us 800000

write /dev/cpuctl/cpu.rt_period_us 1000000

mkdir /dev/cpuctl/bg_non_interactive

chown system system /dev/cpuctl/bg_non_interactive/tasks

chmod 0666 /dev/cpuctl/bg_non_interactive/tasks

# 5.0 %

write /dev/cpuctl/bg_non_interactive/cpu.shares 52

write /dev/cpuctl/bg_non_interactive/cpu.rt_runtime_us 700000

write /dev/cpuctl/bg_non_interactive/cpu.rt_period_us 1000000

cpuset Subsystem :

# sets up initial cpusets for ActivityManager

mkdir /dev/cpuset

mount cpuset none /dev/cpuset

# this ensures that the cpusets are present and usable, but the device's

# init.rc must actually set the correct cpus

mkdir /dev/cpuset/foreground

write /dev/cpuset/foreground/cpus 0

write /dev/cpuset/foreground/mems 0

mkdir /dev/cpuset/foreground/boost

write /dev/cpuset/foreground/boost/cpus 0

write /dev/cpuset/foreground/boost/mems 0

mkdir /dev/cpuset/background

write /dev/cpuset/background/cpus 0

write /dev/cpuset/background/mems 0

# system-background is for system tasks that should only run on

# little cores, not on bigs

# to be used only by init, so don't change system-bg permissions

mkdir /dev/cpuset/system-background

write /dev/cpuset/system-background/cpus 0

write /dev/cpuset/system-background/mems 0

mkdir /dev/cpuset/top-app

write /dev/cpuset/top-app/cpus 0

write /dev/cpuset/top-app/mems 0

# change permissions for all cpusets we'll touch at runtime

chown system system /dev/cpuset

chown system system /dev/cpuset/foreground

chown system system /dev/cpuset/foreground/boost

chown system system /dev/cpuset/background

chown system system /dev/cpuset/system-background

chown system system /dev/cpuset/top-app

chown system system /dev/cpuset/tasks

chown system system /dev/cpuset/foreground/tasks

chown system system /dev/cpuset/foreground/boost/tasks

chown system system /dev/cpuset/background/tasks

chown system system /dev/cpuset/system-background/tasks

chown system system /dev/cpuset/top-app/tasks

# set system-background to 0775 so SurfaceFlinger can touch it

chmod 0775 /dev/cpuset/system-background

chmod 0664 /dev/cpuset/foreground/tasks

chmod 0664 /dev/cpuset/foreground/boost/tasks

chmod 0664 /dev/cpuset/background/tasks

chmod 0664 /dev/cpuset/system-background/tasks

chmod 0664 /dev/cpuset/top-app/tasks

chmod 0664 /dev/cpuset/tasks

schedtune Subsystem :

# Create energy-aware scheduler tuning nodes

mkdir /dev/stune

mount cgroup none /dev/stune schedtune

mkdir /dev/stune/foreground

chown system system /dev/stune

chown system system /dev/stune/foreground

chown system system /dev/stune/tasks

chown system system /dev/stune/foreground/tasks

chmod 0664 /dev/stune/tasks

chmod 0664 /dev/stune/foreground/tasks

Android About China cpu/cpuset/schedtune More articles on the application of

  1. 【 monthly income 41 ten thousand 】Mono For Android Use Baidu map in SDK

    With the help of Mono For Android technology ,.Net Developers can also use their own familiar C# Language and .Net To develop Android application . because Mono For Android hold Android SDK Most of the class libraries in are ...

  2. Android About China static The use of

    Reprint please indicate the source :http://www.cnblogs.com/Joanna-Yan/p/5251564.html In the project , Receiving serial data for a long time ( Few hours ) after , Will accidentally report errors . Preliminary exclusion of oom ...

  3. android Thread pool learning notes in

    Reading books : Android Exploration of development Art Android Advanced development from small workers to experts A simple understanding of thread pooling principles : Create multiple threads and manage them , The submitted tasks are assigned to the threads in the thread pool for execution , Through the unified scheduling and management of thread pool ...

  4. About Android in ArrayMap/SparseArray Than HashMap Deep research with good performance

    Because there are friends on the Internet who have made a very detailed study on this issue , So I don't want to be a teacher : Reproduced in :http://android-performance.com/android/2014/02/10/android-sp ...

  5. Android in Activity Life cycle of

    brief introduction : This is basically a must ask question , Say you are right Activity Life cycle understanding , ha-ha … onCreate, onStart, onResume, onPause, onStop, onDestroy, on ...

  6. Android in Handler 、Thread and Runnable The relationship between

    In multithreading programming , We often use Handler,Thread and Runnable These three categories , Let's take a look at the relationship between these three classes ? First of all Android Of CPU The smallest unit allocated is a thread ,Handler commonly ...

  7. Android Chinese vs Log Log file analysis [ turn ]

    One ,Bug There is , need “ kill ” it bug It's scary , But as long as you understand ,android Inside bug It's a good solution , because android We have LOG Mechanism , Specific underlying code , I'll analyze it later , As long as you can see bug, a ...

  8. Android in Service( service ) Detailed explanation

    http://blog.csdn.net/ryantang03/article/details/7770939 Android in Service( service ) Detailed explanation label : serviceandroidappl ...

  9. Android Medium Service Comprehensive summary ( Reprint )

    Reprinted address :http://www.cnblogs.com/newcj/archive/2011/05/30/2061370.html Thanks to the author Android Medium Service Comprehensive summary 1.Ser ...

Random recommendation

  1. git Development based on publishing branches

    Create a publication branch : (1) Software hello-world Of 1.0 There is a corresponding mileage in the release repository . /home/jackluo/workspace/user1/workspace/hello-worldgit ...

  2. POJ 2488-A Knight&amp;#39;s Journey(DFS)

    A Knight's Journey Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 31702   Accepted: 10 ...

  3. Python obtain Facebook User Friends In my hobby Top10

    CODE; #!/usr/bin/python # -*- coding: utf-8 -*- ''' Created on 2014-8-12 @author: guaguastd @name: f ...

  4. [jquery] The image hot area is free to scale with the image size

    Draw hot zone elements with hyperlinks directly on the image map and area I believe you are not new ,Dreamweaver And other web production software have a hot spot tool to draw hyperlinks directly on the picture , But the hot area drawn directly can't be enlarged and shrunk adaptively with the picture , present ...

  5. caffe Source code analysis --data_layer.cpp

    dataLayer As the input layer of the whole network , Data from leveldb To take . leveldb The data is converted from pictures . When the network was set up . datalayer Mainly responsible for setting some parameters , example batchsize.c ...

  6. Chinese subtitles in the machine age (Automata.2014.720p.WEB-DL.DD5.1.H264-RARBG.srt)

    Subtitles . I can't watch it any more . My translation position The discussion of evaluation 1 00:01:58,452 --> 00:02:02,088 precipitation enhancement For the period 32 minute 16 second 2 00:02:02,089 --> 00 ...

  7. Eclipse Next Maven newly build Web project index.jsp Error reporting is a perfect solution (war package )

    Eclipse Next Maven newly build Web Project steps 1. 2. 3. 4. 5. Problem description Recently, with eclipse I've created a new one maven project , It just finished index.jsp The page is wrong , Post the error message first ...

  8. LeetCode Algorithm problem -Two Sum II - Input array is sorted

    This is the number one of Yuele book 179 Secondary update , The first 181 Original article 01 Reading and preparation Today's presentation is LeetCode Algorithm problem Easy Rank No. 38 topic ( Sequence question no 167). Given an array of integers sorted in ascending order , Find two numbers , Add them to a specific ...

  9. Restrictions Query usage

    HQL Operator QBC Operator meaning = Restrictions.eq() be equal to equal <>  Restrictions.ne() It's not equal to not equal >  Restrict ...

  10. Test coverage tools :EclEmma

    Test coverage tools :EclEmma 2016-08-26 Catalog 1 Test coverage implementation technology 2 EclEmma Introduce 3 EclEmma Test coverage index 4 EclEmma install 5 Sample project introduction   5.1 Create project   5 ...