• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2021 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 
17 #include <stdlib.h>
18 #include <sys/syscall.h>
19 #include <unistd.h>
20 
21 #include <iostream>
22 
usage(int exit_status)23 [[noreturn]] static void usage(int exit_status) {
24     std::cerr << "Usage: " << getprogname() << " <tid> <uclamp_min> <uclamp_max>" << std::endl
25               << "    tid      Thread ID to apply the uclamp setting." << std::endl
26               << "    uclamp_min  uclamp.min value range from [0, 1024]." << std::endl
27               << "    uclamp_max  uclamp.max value range from [0, 1024]." << std::endl;
28     exit(exit_status);
29 }
30 
31 struct sched_attr {
32     __u32 size;
33     __u32 sched_policy;
34     __u64 sched_flags;
35     __s32 sched_nice;
36     __u32 sched_priority;
37     __u64 sched_runtime;
38     __u64 sched_deadline;
39     __u64 sched_period;
40     __u32 sched_util_min;
41     __u32 sched_util_max;
42 };
43 
sched_setattr(int pid,struct sched_attr * attr,unsigned int flags)44 static int sched_setattr(int pid, struct sched_attr* attr, unsigned int flags) {
45     return syscall(__NR_sched_setattr, pid, attr, flags);
46 }
47 
set_uclamp(int32_t min,int32_t max,int tid)48 static int set_uclamp(int32_t min, int32_t max, int tid) {
49     sched_attr attr = {};
50     attr.size = sizeof(attr);
51 
52     attr.sched_flags = (SCHED_FLAG_KEEP_ALL | SCHED_FLAG_UTIL_CLAMP);
53     attr.sched_util_min = min;
54     attr.sched_util_max = max;
55 
56     int ret = sched_setattr(tid, &attr, 0);
57     if (ret) {
58         int err = errno;
59         std::cerr << "sched_setattr failed for thread " << tid << " err=" << err << std::endl;
60     }
61 
62     return ret;
63 }
64 
main(int argc,char * argv[])65 int main(int argc, char* argv[]) {
66     if (argc != 4) {
67         usage(EXIT_FAILURE);
68     }
69 
70     int tid = atoi(argv[1]);
71     int uclamp_min = atoi(argv[2]);
72     int uclamp_max = atoi(argv[3]);
73 
74     return set_uclamp(uclamp_min, uclamp_max, tid);
75 }
76