xref: /aosp_15_r20/external/cronet/base/threading/platform_thread.h (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright 2012 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 // WARNING: You should *NOT* be using this class directly.  PlatformThread is
6 // the low-level platform-specific abstraction to the OS's threading interface.
7 // You should instead be using a message-loop driven Thread, see thread.h.
8 
9 #ifndef BASE_THREADING_PLATFORM_THREAD_H_
10 #define BASE_THREADING_PLATFORM_THREAD_H_
11 
12 #include <stddef.h>
13 
14 #include <iosfwd>
15 #include <optional>
16 #include <type_traits>
17 
18 #include "base/base_export.h"
19 #include "base/feature_list.h"
20 #include "base/message_loop/message_pump_type.h"
21 #include "base/process/process_handle.h"
22 #include "base/sequence_checker_impl.h"
23 #include "base/threading/platform_thread_ref.h"
24 #include "base/time/time.h"
25 #include "base/types/strong_alias.h"
26 #include "build/build_config.h"
27 #include "build/chromeos_buildflags.h"
28 
29 #if BUILDFLAG(IS_WIN)
30 #include "base/win/windows_types.h"
31 #elif BUILDFLAG(IS_FUCHSIA)
32 #include <zircon/types.h>
33 #elif BUILDFLAG(IS_APPLE)
34 #include <mach/mach_types.h>
35 #elif BUILDFLAG(IS_POSIX)
36 #include <pthread.h>
37 #include <unistd.h>
38 #endif
39 
40 namespace base {
41 
42 // Used for logging. Always an integer value.
43 #if BUILDFLAG(IS_WIN)
44 typedef DWORD PlatformThreadId;
45 #elif BUILDFLAG(IS_FUCHSIA)
46 typedef zx_koid_t PlatformThreadId;
47 #elif BUILDFLAG(IS_APPLE)
48 typedef mach_port_t PlatformThreadId;
49 #elif BUILDFLAG(IS_POSIX)
50 typedef pid_t PlatformThreadId;
51 #endif
52 static_assert(std::is_integral_v<PlatformThreadId>, "Always an integer value.");
53 
54 // Used to operate on threads.
55 class PlatformThreadHandle {
56  public:
57 #if BUILDFLAG(IS_WIN)
58   typedef void* Handle;
59 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
60   typedef pthread_t Handle;
61 #endif
62 
PlatformThreadHandle()63   constexpr PlatformThreadHandle() : handle_(0) {}
64 
PlatformThreadHandle(Handle handle)65   explicit constexpr PlatformThreadHandle(Handle handle) : handle_(handle) {}
66 
is_equal(const PlatformThreadHandle & other)67   bool is_equal(const PlatformThreadHandle& other) const {
68     return handle_ == other.handle_;
69   }
70 
is_null()71   bool is_null() const {
72     return !handle_;
73   }
74 
platform_handle()75   Handle platform_handle() const {
76     return handle_;
77   }
78 
79  private:
80   Handle handle_;
81 };
82 
83 const PlatformThreadId kInvalidThreadId(0);
84 
85 // Valid values for `thread_type` of Thread::Options, SimpleThread::Options,
86 // and SetCurrentThreadType(), listed in increasing order of importance.
87 //
88 // It is up to each platform-specific implementation what these translate to.
89 // Callers should avoid setting different ThreadTypes on different platforms
90 // (ifdefs) at all cost, instead the platform differences should be encoded in
91 // the platform-specific implementations. Some implementations may treat
92 // adjacent ThreadTypes in this enum as equivalent.
93 //
94 // Reach out to //base/task/OWNERS ([email protected]) before changing
95 // thread type assignments in your component, as such decisions affect the whole
96 // of Chrome.
97 //
98 // Refer to PlatformThreadTest.SetCurrentThreadTypeTest in
99 // platform_thread_unittest.cc for the most up-to-date state of each platform's
100 // handling of ThreadType.
101 enum class ThreadType : int {
102   // Suitable for threads that have the least urgency and lowest priority, and
103   // can be interrupted or delayed by other types.
104   kBackground,
105   // Suitable for threads that are less important than normal type, and can be
106   // interrupted or delayed by threads with kDefault type.
107   kUtility,
108   // Suitable for threads that produce user-visible artifacts but aren't
109   // latency sensitive. The underlying platform will try to be economic
110   // in its usage of resources for this thread, if possible.
111   kResourceEfficient,
112   // Default type. The thread priority or quality of service will be set to
113   // platform default. In Chrome, this is suitable for handling user
114   // interactions (input), only display and audio can get a higher priority.
115   kDefault,
116   // Suitable for threads which are critical to compositing the foreground
117   // content.
118   kCompositing,
119   // Suitable for display critical threads.
120   kDisplayCritical,
121   // Suitable for low-latency, glitch-resistant audio.
122   kRealtimeAudio,
123   kMaxValue = kRealtimeAudio,
124 };
125 
126 // Cross-platform mapping of physical thread priorities. Used by tests to verify
127 // the underlying effects of SetCurrentThreadType.
128 enum class ThreadPriorityForTest : int {
129   kBackground,
130   kUtility,
131   kResourceEfficient,
132   kNormal,
133   kCompositing,
134   kDisplay,
135   kRealtimeAudio,
136   kMaxValue = kRealtimeAudio,
137 };
138 
139 // A namespace for low-level thread functions.
140 class BASE_EXPORT PlatformThreadBase {
141  public:
142   // Implement this interface to run code on a background thread.  Your
143   // ThreadMain method will be called on the newly created thread.
144   class BASE_EXPORT Delegate {
145    public:
146     virtual void ThreadMain() = 0;
147 
148 #if BUILDFLAG(IS_APPLE)
149     // TODO: Move this to the PlatformThreadApple class.
150     // The interval at which the thread expects to have work to do. Zero if
151     // unknown. (Example: audio buffer duration for real-time audio.) Is used to
152     // optimize the thread real-time behavior. Is called on the newly created
153     // thread before ThreadMain().
154     virtual TimeDelta GetRealtimePeriod();
155 #endif
156 
157    protected:
158     virtual ~Delegate() = default;
159   };
160 
161   PlatformThreadBase() = delete;
162   PlatformThreadBase(const PlatformThreadBase&) = delete;
163   PlatformThreadBase& operator=(const PlatformThreadBase&) = delete;
164 
165   // Gets the current thread id, which may be useful for logging purposes.
166   static PlatformThreadId CurrentId();
167 
168   // Gets the current thread reference, which can be used to check if
169   // we're on the right thread quickly.
170   static PlatformThreadRef CurrentRef();
171 
172   // Get the handle representing the current thread. On Windows, this is a
173   // pseudo handle constant which will always represent the thread using it and
174   // hence should not be shared with other threads nor be used to differentiate
175   // the current thread from another.
176   static PlatformThreadHandle CurrentHandle();
177 
178   // Yield the current thread so another thread can be scheduled.
179   //
180   // Note: this is likely not the right call to make in most situations. If this
181   // is part of a spin loop, consider base::Lock, which likely has better tail
182   // latency. Yielding the thread has different effects depending on the
183   // platform, system load, etc., and can result in yielding the CPU for less
184   // than 1us, or many tens of ms.
185   static void YieldCurrentThread();
186 
187   // Sleeps for the specified duration (real-time; ignores time overrides).
188   // Note: The sleep duration may be in base::Time or base::TimeTicks, depending
189   // on platform. If you're looking to use this in unit tests testing delayed
190   // tasks, this will be unreliable - instead, use
191   // base::test::TaskEnvironment with MOCK_TIME mode.
192   static void Sleep(base::TimeDelta duration);
193 
194   // Sets the thread name visible to debuggers/tools. This will try to
195   // initialize the context for current thread unless it's a WorkerThread.
196   static void SetName(const std::string& name);
197 
198   // Gets the thread name, if previously set by SetName.
199   static const char* GetName();
200 
201   // Creates a new thread.  The `stack_size` parameter can be 0 to indicate
202   // that the default stack size should be used.  Upon success,
203   // `*thread_handle` will be assigned a handle to the newly created thread,
204   // and `delegate`'s ThreadMain method will be executed on the newly created
205   // thread.
206   // NOTE: When you are done with the thread handle, you must call Join to
207   // release system resources associated with the thread.  You must ensure that
208   // the Delegate object outlives the thread.
Create(size_t stack_size,Delegate * delegate,PlatformThreadHandle * thread_handle)209   static bool Create(size_t stack_size,
210                      Delegate* delegate,
211                      PlatformThreadHandle* thread_handle) {
212     return CreateWithType(stack_size, delegate, thread_handle,
213                           ThreadType::kDefault);
214   }
215 
216   // CreateWithType() does the same thing as Create() except the priority and
217   // possibly the QoS of the thread is set based on `thread_type`.
218   // `pump_type_hint` must be provided if the thread will be using a
219   // MessagePumpForUI or MessagePumpForIO as this affects the application of
220   // `thread_type`.
221   static bool CreateWithType(
222       size_t stack_size,
223       Delegate* delegate,
224       PlatformThreadHandle* thread_handle,
225       ThreadType thread_type,
226       MessagePumpType pump_type_hint = MessagePumpType::DEFAULT);
227 
228   // CreateNonJoinable() does the same thing as Create() except the thread
229   // cannot be Join()'d.  Therefore, it also does not output a
230   // PlatformThreadHandle.
231   static bool CreateNonJoinable(size_t stack_size, Delegate* delegate);
232 
233   // CreateNonJoinableWithType() does the same thing as CreateNonJoinable()
234   // except the type of the thread is set based on `type`. `pump_type_hint` must
235   // be provided if the thread will be using a MessagePumpForUI or
236   // MessagePumpForIO as this affects the application of `thread_type`.
237   static bool CreateNonJoinableWithType(
238       size_t stack_size,
239       Delegate* delegate,
240       ThreadType thread_type,
241       MessagePumpType pump_type_hint = MessagePumpType::DEFAULT);
242 
243   // Joins with a thread created via the Create function.  This function blocks
244   // the caller until the designated thread exits.  This will invalidate
245   // `thread_handle`.
246   static void Join(PlatformThreadHandle thread_handle);
247 
248   // Detaches and releases the thread handle. The thread is no longer joinable
249   // and `thread_handle` is invalidated after this call.
250   static void Detach(PlatformThreadHandle thread_handle);
251 
252   // Returns true if SetCurrentThreadType() should be able to change the type
253   // of a thread in current process from `from` to `to`.
254   static bool CanChangeThreadType(ThreadType from, ThreadType to);
255 
256   // Declares the type of work running on the current thread. This will affect
257   // things like thread priority and thread QoS (Quality of Service) to the best
258   // of the current platform's abilities.
259   static void SetCurrentThreadType(ThreadType thread_type);
260 
261   // Get the last `thread_type` set by SetCurrentThreadType, no matter if the
262   // underlying priority successfully changed or not.
263   static ThreadType GetCurrentThreadType();
264 
265   // Returns a realtime period provided by `delegate`.
266   static TimeDelta GetRealtimePeriod(Delegate* delegate);
267 
268   // Returns the override of task leeway if any.
269   static std::optional<TimeDelta> GetThreadLeewayOverride();
270 
271   // Returns the default thread stack size set by chrome. If we do not
272   // explicitly set default size then returns 0.
273   static size_t GetDefaultThreadStackSize();
274 
275   static ThreadPriorityForTest GetCurrentThreadPriorityForTest();
276 
277   protected:
278   static void SetNameCommon(const std::string& name);
279 };
280 
281 #if BUILDFLAG(IS_APPLE)
282 class BASE_EXPORT PlatformThreadApple : public PlatformThreadBase {
283  public:
284   // Stores the period value in TLS.
285   static void SetCurrentThreadRealtimePeriodValue(TimeDelta realtime_period);
286 
287   static TimeDelta GetCurrentThreadRealtimePeriodForTest();
288 
289   // Initializes features for this class. See `base::features::Init()`.
290   static void InitializeFeatures();
291 };
292 #endif  // BUILDFLAG(IS_APPLE)
293 
294 #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
295 class ThreadTypeDelegate;
296 using IsViaIPC = base::StrongAlias<class IsViaIPCTag, bool>;
297 
298 class BASE_EXPORT PlatformThreadLinux : public PlatformThreadBase {
299  public:
300   static constexpr struct sched_param kRealTimeAudioPrio = {8};
301   static constexpr struct sched_param kRealTimeDisplayPrio = {6};
302 
303   // Sets a delegate which handles thread type changes for this process. This
304   // must be externally synchronized with any call to SetCurrentThreadType.
305   static void SetThreadTypeDelegate(ThreadTypeDelegate* delegate);
306 
307   // Toggles a specific thread's type at runtime. This can be used to
308   // change the priority of a thread in a different process and will fail
309   // if the calling process does not have proper permissions. The
310   // SetCurrentThreadType() function above is preferred in favor of
311   // security but on platforms where sandboxed processes are not allowed to
312   // change priority this function exists to allow a non-sandboxed process
313   // to change the priority of sandboxed threads for improved performance.
314   // Warning: Don't use this for a main thread because that will change the
315   // whole thread group's (i.e. process) priority.
316   static void SetThreadType(PlatformThreadId process_id,
317                             PlatformThreadId thread_id,
318                             ThreadType thread_type,
319                             IsViaIPC via_ipc);
320 
321   // Toggles a specific thread's type at runtime. The thread must be of the
322   // current process.
323   static void SetThreadType(PlatformThreadId thread_id, ThreadType thread_type);
324 
325   // For a given thread id and thread type, setup the cpuset and schedtune
326   // CGroups for the thread.
327   static void SetThreadCgroupsForThreadType(PlatformThreadId thread_id,
328                                             ThreadType thread_type);
329 
330   // Determine if thread_id is a background thread by looking up whether
331   // it is in the urgent or non-urgent cpuset
332   static bool IsThreadBackgroundedForTest(PlatformThreadId thread_id);
333 
334  protected:
335   static void SetThreadTypeInternal(PlatformThreadId process_id,
336                                     PlatformThreadId thread_id,
337                                     ThreadType thread_type,
338                                     IsViaIPC via_ipc);
339 };
340 #endif  // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
341 
342 #if BUILDFLAG(IS_CHROMEOS)
343 BASE_EXPORT BASE_DECLARE_FEATURE(kSetRtForDisplayThreads);
344 
345 class CrossProcessPlatformThreadDelegate;
346 
347 class BASE_EXPORT PlatformThreadChromeOS : public PlatformThreadLinux {
348  public:
349   // Sets a delegate which handles thread type changes for threads of another
350   // process. This must be externally synchronized with any call to
351   // SetCurrentThreadType.
352   static void SetCrossProcessPlatformThreadDelegate(
353       CrossProcessPlatformThreadDelegate* delegate);
354 
355   // Initializes features for this class. See `base::features::Init()`.
356   static void InitializeFeatures();
357 
358   // Toggles a specific thread's type at runtime. This is the ChromeOS-specific
359   // version and includes Linux's functionality but does slightly more. See
360   // PlatformThreadLinux's SetThreadType() header comment for Linux details.
361   static void SetThreadType(PlatformThreadId process_id,
362                             PlatformThreadId thread_id,
363                             ThreadType thread_type,
364                             IsViaIPC via_ipc);
365 
366   // Returns true if the feature for backgrounding of threads is enabled.
367   static bool IsThreadsBgFeatureEnabled();
368 
369   // Returns true if the feature for setting display threads to RT is enabled.
370   static bool IsDisplayThreadsRtFeatureEnabled();
371 
372   // Set a specific thread as backgrounded. This is called when the process
373   // moves to and from the background and changes have to be made to each of its
374   // thread's scheduling attributes.
375   static void SetThreadBackgrounded(ProcessId process_id,
376                                     PlatformThreadId thread_id,
377                                     bool backgrounded);
378 
379   // Returns the thread type of a thread given its thread id.
380   static std::optional<ThreadType> GetThreadTypeFromThreadId(
381       ProcessId process_id,
382       PlatformThreadId thread_id);
383 
384   // Returns a SequenceChecker which should be used to verify that all
385   // cross-process priority changes are performed without races.
386   static SequenceCheckerImpl& GetCrossProcessThreadPrioritySequenceChecker();
387 
388  protected:
389   static void SetThreadTypeInternal(PlatformThreadId process_id,
390                                     PlatformThreadId thread_id,
391                                     ThreadType thread_type,
392                                     IsViaIPC via_ipc);
393 };
394 #endif  // BUILDFLAG(IS_CHROMEOS)
395 
396 // Alias to the correct platform-specific class based on preprocessor directives
397 #if BUILDFLAG(IS_APPLE)
398 using PlatformThread = PlatformThreadApple;
399 #elif BUILDFLAG(IS_CHROMEOS)
400 using PlatformThread = PlatformThreadChromeOS;
401 #elif BUILDFLAG(IS_LINUX)
402 using PlatformThread = PlatformThreadLinux;
403 #else
404 using PlatformThread = PlatformThreadBase;
405 #endif
406 
407 namespace internal {
408 
409 void SetCurrentThreadType(ThreadType thread_type,
410                           MessagePumpType pump_type_hint);
411 
412 void SetCurrentThreadTypeImpl(ThreadType thread_type,
413                               MessagePumpType pump_type_hint);
414 
415 }  // namespace internal
416 
417 }  // namespace base
418 
419 #endif  // BASE_THREADING_PLATFORM_THREAD_H_
420