Initialize Tizen 2.3
[external/chromium.git] / base / threading / platform_thread_posix.cc
1 // Copyright (c) 2011 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
10 #include "base/logging.h"
11 #include "base/memory/scoped_ptr.h"
12 #include "base/safe_strerror_posix.h"
13 #include "base/threading/thread_local.h"
14 #include "base/threading/thread_restrictions.h"
15
16 #if defined(OS_MACOSX)
17 #include <mach/mach.h>
18 #include <sys/resource.h>
19 #include <algorithm>
20 #endif
21
22 #if defined(OS_LINUX)
23 #include <dlfcn.h>
24 #include <sys/prctl.h>
25 #include <sys/syscall.h>
26 #include <unistd.h>
27 #endif
28
29 #if defined(OS_ANDROID)
30 #include "base/android/jni_android.h"
31 #endif
32
33 #if defined(OS_NACL)
34 #include <sys/nacl_syscalls.h>
35 #endif
36
37 namespace base {
38
39 #if defined(OS_MACOSX)
40 void InitThreading();
41 #endif
42
43 namespace {
44
45 static ThreadLocalPointer<char> current_thread_name;
46
47 struct ThreadParams {
48   PlatformThread::Delegate* delegate;
49   bool joinable;
50 };
51
52 void* ThreadFunc(void* params) {
53   ThreadParams* thread_params = static_cast<ThreadParams*>(params);
54   PlatformThread::Delegate* delegate = thread_params->delegate;
55   if (!thread_params->joinable)
56     base::ThreadRestrictions::SetSingletonAllowed(false);
57   delete thread_params;
58   delegate->ThreadMain();
59 #if defined(OS_ANDROID)
60   base::android::DetachFromVM();
61 #endif
62   return NULL;
63 }
64
65 bool CreateThread(size_t stack_size, bool joinable,
66                   PlatformThread::Delegate* delegate,
67                   PlatformThreadHandle* thread_handle) {
68 #if defined(OS_MACOSX)
69   base::InitThreading();
70 #endif  // OS_MACOSX
71
72   bool success = false;
73   pthread_attr_t attributes;
74   pthread_attr_init(&attributes);
75
76   // Pthreads are joinable by default, so only specify the detached attribute if
77   // the thread should be non-joinable.
78   if (!joinable) {
79     pthread_attr_setdetachstate(&attributes, PTHREAD_CREATE_DETACHED);
80   }
81
82 #if defined(OS_MACOSX)
83   // The Mac OS X default for a pthread stack size is 512kB.
84   // Libc-594.1.4/pthreads/pthread.c's pthread_attr_init uses
85   // DEFAULT_STACK_SIZE for this purpose.
86   //
87   // 512kB isn't quite generous enough for some deeply recursive threads that
88   // otherwise request the default stack size by specifying 0. Here, adopt
89   // glibc's behavior as on Linux, which is to use the current stack size
90   // limit (ulimit -s) as the default stack size. See
91   // glibc-2.11.1/nptl/nptl-init.c's __pthread_initialize_minimal_internal. To
92   // avoid setting the limit below the Mac OS X default or the minimum usable
93   // stack size, these values are also considered. If any of these values
94   // can't be determined, or if stack size is unlimited (ulimit -s unlimited),
95   // stack_size is left at 0 to get the system default.
96   //
97   // Mac OS X normally only applies ulimit -s to the main thread stack. On
98   // contemporary OS X and Linux systems alike, this value is generally 8MB
99   // or in that neighborhood.
100   if (stack_size == 0) {
101     size_t default_stack_size;
102     struct rlimit stack_rlimit;
103     if (pthread_attr_getstacksize(&attributes, &default_stack_size) == 0 &&
104         getrlimit(RLIMIT_STACK, &stack_rlimit) == 0 &&
105         stack_rlimit.rlim_cur != RLIM_INFINITY) {
106       stack_size = std::max(std::max(default_stack_size,
107                                      static_cast<size_t>(PTHREAD_STACK_MIN)),
108                             static_cast<size_t>(stack_rlimit.rlim_cur));
109     }
110   }
111 #endif  // OS_MACOSX
112
113   if (stack_size > 0)
114     pthread_attr_setstacksize(&attributes, stack_size);
115
116   ThreadParams* params = new ThreadParams;
117   params->delegate = delegate;
118   params->joinable = joinable;
119   success = !pthread_create(thread_handle, &attributes, ThreadFunc, params);
120
121   pthread_attr_destroy(&attributes);
122   if (!success)
123     delete params;
124   return success;
125 }
126
127 }  // namespace
128
129 // static
130 PlatformThreadId PlatformThread::CurrentId() {
131   // Pthreads doesn't have the concept of a thread ID, so we have to reach down
132   // into the kernel.
133 #if defined(OS_MACOSX)
134   return mach_thread_self();
135 #elif defined(OS_LINUX)
136   return syscall(__NR_gettid);
137 #elif defined(OS_ANDROID)
138   return gettid();
139 #elif defined(OS_FREEBSD)
140   // TODO(BSD): find a better thread ID
141   return reinterpret_cast<int64>(pthread_self());
142 #elif defined(OS_NACL) || defined(OS_SOLARIS)
143   return pthread_self();
144 #endif
145 }
146
147 // static
148 void PlatformThread::YieldCurrentThread() {
149   sched_yield();
150 }
151
152 // static
153 void PlatformThread::Sleep(int duration_ms) {
154   struct timespec sleep_time, remaining;
155
156   // Contains the portion of duration_ms >= 1 sec.
157   sleep_time.tv_sec = duration_ms / 1000;
158   duration_ms -= sleep_time.tv_sec * 1000;
159
160   // Contains the portion of duration_ms < 1 sec.
161   sleep_time.tv_nsec = duration_ms * 1000 * 1000;  // nanoseconds.
162
163   while (nanosleep(&sleep_time, &remaining) == -1 && errno == EINTR)
164     sleep_time = remaining;
165 }
166
167 // Linux SetName is currently disabled, as we need to distinguish between
168 // helper threads (where it's ok to make this call) and the main thread
169 // (where making this call renames our process, causing tools like killall
170 // to stop working).
171 #if 0 && defined(OS_LINUX)
172 // static
173 void PlatformThread::SetName(const char* name) {
174   // have to cast away const because ThreadLocalPointer does not support const
175   // void*
176   current_thread_name.Set(const_cast<char*>(name));
177
178   // http://0pointer.de/blog/projects/name-your-threads.html
179
180   // glibc recently added support for pthread_setname_np, but it's not
181   // commonly available yet.  So test for it at runtime.
182   int (*dynamic_pthread_setname_np)(pthread_t, const char*);
183   *reinterpret_cast<void**>(&dynamic_pthread_setname_np) =
184       dlsym(RTLD_DEFAULT, "pthread_setname_np");
185
186   if (dynamic_pthread_setname_np) {
187     // This limit comes from glibc, which gets it from the kernel
188     // (TASK_COMM_LEN).
189     const int kMaxNameLength = 15;
190     std::string shortened_name = std::string(name).substr(0, kMaxNameLength);
191     int err = dynamic_pthread_setname_np(pthread_self(),
192                                          shortened_name.c_str());
193     if (err < 0)
194       LOG(ERROR) << "pthread_setname_np: " << safe_strerror(err);
195   } else {
196     // Implementing this function without glibc is simple enough.  (We
197     // don't do the name length clipping as above because it will be
198     // truncated by the callee (see TASK_COMM_LEN above).)
199     int err = prctl(PR_SET_NAME, name);
200     if (err < 0)
201       PLOG(ERROR) << "prctl(PR_SET_NAME)";
202   }
203 }
204 #elif defined(OS_MACOSX)
205 // Mac is implemented in platform_thread_mac.mm.
206 #else
207 // static
208 void PlatformThread::SetName(const char* name) {
209   // have to cast away const because ThreadLocalPointer does not support const
210   // void*
211   current_thread_name.Set(const_cast<char*>(name));
212
213   // (This should be relatively simple to implement for the BSDs; I
214   // just don't have one handy to test the code on.)
215 }
216 #endif  // defined(OS_LINUX)
217
218
219 #if !defined(OS_MACOSX)
220 // Mac is implemented in platform_thread_mac.mm.
221 // static
222 const char* PlatformThread::GetName() {
223   return current_thread_name.Get();
224 }
225 #endif
226
227 // static
228 bool PlatformThread::Create(size_t stack_size, Delegate* delegate,
229                             PlatformThreadHandle* thread_handle) {
230   return CreateThread(stack_size, true /* joinable thread */,
231                       delegate, thread_handle);
232 }
233
234 // static
235 bool PlatformThread::CreateNonJoinable(size_t stack_size, Delegate* delegate) {
236   PlatformThreadHandle unused;
237
238   bool result = CreateThread(stack_size, false /* non-joinable thread */,
239                              delegate, &unused);
240   return result;
241 }
242
243 // static
244 void PlatformThread::Join(PlatformThreadHandle thread_handle) {
245   // Joining another thread may block the current thread for a long time, since
246   // the thread referred to by |thread_handle| may still be running long-lived /
247   // blocking tasks.
248   base::ThreadRestrictions::AssertIOAllowed();
249   pthread_join(thread_handle, NULL);
250 }
251
252 #if !defined(OS_MACOSX)
253 // Mac OS X uses lower-level mach APIs
254
255 // static
256 void PlatformThread::SetThreadPriority(PlatformThreadHandle, ThreadPriority) {
257   // TODO(crogers): implement
258   NOTIMPLEMENTED();
259 }
260 #endif
261
262 }  // namespace base