blob: 295a5092963b4087ca58f84ce3d7f375308d8d9f [file] [log] [blame]
Elliott Hughes8daa0922011-09-11 13:46:25 -07001/*
2 * Copyright (C) 2011 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 "thread.h"
18
19#include <sys/time.h>
20#include <sys/resource.h>
21#include <limits.h>
22#include <errno.h>
23
24#include <cutils/sched_policy.h>
25#include <utils/threads.h>
26
27#include "macros.h"
28
29namespace art {
30
31/*
32 * Conversion map for "nice" values.
33 *
34 * We use Android thread priority constants to be consistent with the rest
35 * of the system. In some cases adjacent entries may overlap.
36 */
37static const int kNiceValues[10] = {
38 ANDROID_PRIORITY_LOWEST, /* 1 (MIN_PRIORITY) */
39 ANDROID_PRIORITY_BACKGROUND + 6,
40 ANDROID_PRIORITY_BACKGROUND + 3,
41 ANDROID_PRIORITY_BACKGROUND,
42 ANDROID_PRIORITY_NORMAL, /* 5 (NORM_PRIORITY) */
43 ANDROID_PRIORITY_NORMAL - 2,
44 ANDROID_PRIORITY_NORMAL - 4,
45 ANDROID_PRIORITY_URGENT_DISPLAY + 3,
46 ANDROID_PRIORITY_URGENT_DISPLAY + 2,
47 ANDROID_PRIORITY_URGENT_DISPLAY /* 10 (MAX_PRIORITY) */
48};
49
50void Thread::SetNativePriority(int newPriority) {
51 if (newPriority < 1 || newPriority > 10) {
52 LOG(WARNING) << "bad priority " << newPriority;
53 newPriority = 5;
54 }
55
56 int newNice = kNiceValues[newPriority-1];
57 pid_t tid = GetTid();
58
59 if (newNice >= ANDROID_PRIORITY_BACKGROUND) {
60 set_sched_policy(tid, SP_BACKGROUND);
61 } else if (getpriority(PRIO_PROCESS, tid) >= ANDROID_PRIORITY_BACKGROUND) {
62 set_sched_policy(tid, SP_FOREGROUND);
63 }
64
65 if (setpriority(PRIO_PROCESS, tid, newNice) != 0) {
66 PLOG(INFO) << *this << " setPriority(PRIO_PROCESS, " << tid << ", " << newNice << ") failed";
67 }
68}
69
70int Thread::GetNativePriority() {
71 errno = 0;
72 int native_priority = getpriority(PRIO_PROCESS, 0);
73 if (native_priority == -1 && errno != 0) {
74 PLOG(WARNING) << "getpriority failed";
75 return Thread::kNormPriority;
76 }
77
78 int managed_priority = Thread::kMinPriority;
79 for (size_t i = 0; i < arraysize(kNiceValues); i++) {
80 if (native_priority >= kNiceValues[i]) {
81 break;
82 }
83 managed_priority++;
84 }
85 if (managed_priority > Thread::kMaxPriority) {
86 managed_priority = Thread::kMaxPriority;
87 }
88 return managed_priority;
89}
90
91} // namespace art