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