• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "base/threading/platform_thread.h"
6 
7 #include <errno.h>
8 #include <sched.h>
9 #include <stddef.h>
10 
11 #include "base/files/file_util.h"
12 #include "base/lazy_instance.h"
13 #include "base/logging.h"
14 #include "base/strings/string_number_conversions.h"
15 #include "base/threading/platform_thread_internal_posix.h"
16 #include "base/threading/thread_id_name_manager.h"
17 #include "base/tracked_objects.h"
18 #include "build/build_config.h"
19 
20 #if !defined(OS_NACL)
21 #include <pthread.h>
22 #include <sys/prctl.h>
23 #include <sys/resource.h>
24 #include <sys/time.h>
25 #include <sys/types.h>
26 #include <unistd.h>
27 #endif
28 
29 namespace base {
30 namespace {
31 #if !defined(OS_NACL)
32 const FilePath::CharType kCgroupDirectory[] =
33     FILE_PATH_LITERAL("/sys/fs/cgroup");
34 
ThreadPriorityToCgroupDirectory(const FilePath & cgroup_filepath,ThreadPriority priority)35 FilePath ThreadPriorityToCgroupDirectory(const FilePath& cgroup_filepath,
36                                          ThreadPriority priority) {
37   switch (priority) {
38     case ThreadPriority::NORMAL:
39       return cgroup_filepath;
40     case ThreadPriority::BACKGROUND:
41       return cgroup_filepath.Append(FILE_PATH_LITERAL("non-urgent"));
42     case ThreadPriority::DISPLAY:
43     case ThreadPriority::REALTIME_AUDIO:
44       return cgroup_filepath.Append(FILE_PATH_LITERAL("urgent"));
45   }
46   NOTREACHED();
47   return FilePath();
48 }
49 
SetThreadCgroup(PlatformThreadId thread_id,const FilePath & cgroup_directory)50 void SetThreadCgroup(PlatformThreadId thread_id,
51                      const FilePath& cgroup_directory) {
52   FilePath tasks_filepath = cgroup_directory.Append(FILE_PATH_LITERAL("tasks"));
53   std::string tid = IntToString(thread_id);
54   int bytes_written = WriteFile(tasks_filepath, tid.c_str(), tid.size());
55   if (bytes_written != static_cast<int>(tid.size())) {
56     DVLOG(1) << "Failed to add " << tid << " to " << tasks_filepath.value();
57   }
58 }
59 
SetThreadCgroupForThreadPriority(PlatformThreadId thread_id,const FilePath & cgroup_filepath,ThreadPriority priority)60 void SetThreadCgroupForThreadPriority(PlatformThreadId thread_id,
61                                       const FilePath& cgroup_filepath,
62                                       ThreadPriority priority) {
63   // Append "chrome" suffix.
64   FilePath cgroup_directory = ThreadPriorityToCgroupDirectory(
65       cgroup_filepath.Append(FILE_PATH_LITERAL("chrome")), priority);
66 
67   // Silently ignore request if cgroup directory doesn't exist.
68   if (!DirectoryExists(cgroup_directory))
69     return;
70 
71   SetThreadCgroup(thread_id, cgroup_directory);
72 }
73 
SetThreadCgroupsForThreadPriority(PlatformThreadId thread_id,ThreadPriority priority)74 void SetThreadCgroupsForThreadPriority(PlatformThreadId thread_id,
75                                        ThreadPriority priority) {
76   FilePath cgroup_filepath(kCgroupDirectory);
77   SetThreadCgroupForThreadPriority(
78       thread_id, cgroup_filepath.Append(FILE_PATH_LITERAL("cpuset")), priority);
79   SetThreadCgroupForThreadPriority(
80       thread_id, cgroup_filepath.Append(FILE_PATH_LITERAL("schedtune")),
81       priority);
82 }
83 #endif
84 }  // namespace
85 
86 namespace internal {
87 
88 namespace {
89 #if !defined(OS_NACL)
90 const struct sched_param kRealTimePrio = {8};
91 #endif
92 }  // namespace
93 
94 const ThreadPriorityToNiceValuePair kThreadPriorityToNiceValueMap[4] = {
95     {ThreadPriority::BACKGROUND, 10},
96     {ThreadPriority::NORMAL, 0},
97     {ThreadPriority::DISPLAY, -8},
98     {ThreadPriority::REALTIME_AUDIO, -10},
99 };
100 
SetCurrentThreadPriorityForPlatform(ThreadPriority priority)101 bool SetCurrentThreadPriorityForPlatform(ThreadPriority priority) {
102 #if !defined(OS_NACL)
103   SetThreadCgroupsForThreadPriority(PlatformThread::CurrentId(), priority);
104   return priority == ThreadPriority::REALTIME_AUDIO &&
105          pthread_setschedparam(pthread_self(), SCHED_RR, &kRealTimePrio) == 0;
106 #else
107   return false;
108 #endif
109 }
110 
GetCurrentThreadPriorityForPlatform(ThreadPriority * priority)111 bool GetCurrentThreadPriorityForPlatform(ThreadPriority* priority) {
112 #if !defined(OS_NACL)
113   int maybe_sched_rr = 0;
114   struct sched_param maybe_realtime_prio = {0};
115   if (pthread_getschedparam(pthread_self(), &maybe_sched_rr,
116                             &maybe_realtime_prio) == 0 &&
117       maybe_sched_rr == SCHED_RR &&
118       maybe_realtime_prio.sched_priority == kRealTimePrio.sched_priority) {
119     *priority = ThreadPriority::REALTIME_AUDIO;
120     return true;
121   }
122 #endif
123   return false;
124 }
125 
126 }  // namespace internal
127 
128 // static
SetName(const std::string & name)129 void PlatformThread::SetName(const std::string& name) {
130   ThreadIdNameManager::GetInstance()->SetName(CurrentId(), name);
131   tracked_objects::ThreadData::InitializeThreadContext(name);
132 
133 #if !defined(OS_NACL)
134   // On linux we can get the thread names to show up in the debugger by setting
135   // the process name for the LWP.  We don't want to do this for the main
136   // thread because that would rename the process, causing tools like killall
137   // to stop working.
138   if (PlatformThread::CurrentId() == getpid())
139     return;
140 
141   // http://0pointer.de/blog/projects/name-your-threads.html
142   // Set the name for the LWP (which gets truncated to 15 characters).
143   // Note that glibc also has a 'pthread_setname_np' api, but it may not be
144   // available everywhere and it's only benefit over using prctl directly is
145   // that it can set the name of threads other than the current thread.
146   int err = prctl(PR_SET_NAME, name.c_str());
147   // We expect EPERM failures in sandboxed processes, just ignore those.
148   if (err < 0 && errno != EPERM)
149     DPLOG(ERROR) << "prctl(PR_SET_NAME)";
150 #endif  //  !defined(OS_NACL)
151 }
152 
153 #if !defined(OS_NACL)
154 // static
SetThreadPriority(PlatformThreadId thread_id,ThreadPriority priority)155 void PlatformThread::SetThreadPriority(PlatformThreadId thread_id,
156                                        ThreadPriority priority) {
157   // Changing current main threads' priority is not permitted in favor of
158   // security, this interface is restricted to change only non-main thread
159   // priority.
160   CHECK_NE(thread_id, getpid());
161 
162   SetThreadCgroupsForThreadPriority(thread_id, priority);
163 
164   const int nice_setting = internal::ThreadPriorityToNiceValue(priority);
165   if (setpriority(PRIO_PROCESS, thread_id, nice_setting)) {
166     DVPLOG(1) << "Failed to set nice value of thread (" << thread_id << ") to "
167               << nice_setting;
168   }
169 }
170 #endif  //  !defined(OS_NACL)
171 
InitThreading()172 void InitThreading() {}
173 
TerminateOnThread()174 void TerminateOnThread() {}
175 
GetDefaultThreadStackSize(const pthread_attr_t & attributes)176 size_t GetDefaultThreadStackSize(const pthread_attr_t& attributes) {
177 #if !defined(THREAD_SANITIZER)
178   return 0;
179 #else
180   // ThreadSanitizer bloats the stack heavily. Evidence has been that the
181   // default stack size isn't enough for some browser tests.
182   return 2 * (1 << 23);  // 2 times 8192K (the default stack size on Linux).
183 #endif
184 }
185 
186 }  // namespace base
187