sched_policy.c revision 493dad966305a7fb555addd367532dd2af275a27
1/* libs/cutils/sched_policy.c
2**
3** Copyright 2007, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9**     http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18#include <stdio.h>
19#include <stdlib.h>
20#include <unistd.h>
21#include <string.h>
22#include <errno.h>
23#include <fcntl.h>
24#include <sched.h>
25#include <linux/sched.h>
26
27#include <cutils/sched_policy.h>
28
29static int add_tid_to_cgroup(int tid, const char *grp_name)
30{
31    int fd;
32    char path[255];
33    char text[64];
34
35    sprintf(path, "/dev/cpuctl/%s/tasks", grp_name);
36
37    if ((fd = open(path, O_WRONLY)) < 0)
38        return -1;
39
40    sprintf(text, "%d", tid);
41    if (write(fd, text, strlen(text)) < 0) {
42        close(fd);
43        return -1;
44    }
45
46    close(fd);
47    return 0;
48}
49
50int set_sched_policy(int tid, SchedPolicy policy)
51{
52    static int __sys_supports_schedgroups = -1;
53
54    if (__sys_supports_schedgroups < 0) {
55        if (!access("/dev/cpuctl/tasks", F_OK)) {
56            __sys_supports_schedgroups = 1;
57        } else {
58            __sys_supports_schedgroups = 0;
59        }
60    }
61
62    if (__sys_supports_schedgroups) {
63        const char *grp = NULL;
64
65        if (policy == SP_BACKGROUND) {
66            grp = "bg_non_interactive";
67        }
68
69        if (add_tid_to_cgroup(tid, grp)) {
70            if (errno != ESRCH && errno != ENOENT)
71                return -errno;
72        }
73    } else {
74        struct sched_param param;
75
76        param.sched_priority = 0;
77        sched_setscheduler(tid,
78                           (policy == SP_BACKGROUND) ?
79                            SCHED_BATCH : SCHED_NORMAL,
80                           &param);
81    }
82
83    return 0;
84}
85