summaryrefslogtreecommitdiffstats
path: root/js/src/vm/InternalThreadPool.cpp
blob: c6cdac1d4447ec563cf06cbc33767e2d18fa5dee (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
 * vim: set ts=8 sts=2 et sw=2 tw=80:
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "vm/InternalThreadPool.h"

#include "mozilla/TimeStamp.h"

#include "js/ProfilingCategory.h"
#include "js/ProfilingStack.h"
#include "threading/Thread.h"
#include "util/NativeStack.h"
#include "vm/HelperThreadState.h"
#include "vm/JSContext.h"

// We want our default stack size limit to be approximately 2MB, to be safe, but
// expect most threads to use much less. On Linux, however, requesting a stack
// of 2MB or larger risks the kernel allocating an entire 2MB huge page for it
// on first access, which we do not want. To avoid this possibility, we subtract
// 2 standard VM page sizes from our default.
static const uint32_t kDefaultHelperStackSize = 2048 * 1024 - 2 * 4096;

// TSan enforces a minimum stack size that's just slightly larger than our
// default helper stack size.  It does this to store blobs of TSan-specific
// data on each thread's stack.  Unfortunately, that means that even though
// we'll actually receive a larger stack than we requested, the effective
// usable space of that stack is significantly less than what we expect.
// To offset TSan stealing our stack space from underneath us, double the
// default.
//
// Note that we don't need this for ASan/MOZ_ASAN because ASan doesn't
// require all the thread-specific state that TSan does.
#if defined(MOZ_TSAN)
static const uint32_t HELPER_STACK_SIZE = 2 * kDefaultHelperStackSize;
#else
static const uint32_t HELPER_STACK_SIZE = kDefaultHelperStackSize;
#endif

// These macros are identical in function to the same-named ones in
// GeckoProfiler.h, but they are defined separately because SpiderMonkey can't
// use GeckoProfiler.h.
#define PROFILER_RAII_PASTE(id, line) id##line
#define PROFILER_RAII_EXPAND(id, line) PROFILER_RAII_PASTE(id, line)
#define PROFILER_RAII PROFILER_RAII_EXPAND(raiiObject, __LINE__)
#define AUTO_PROFILER_LABEL(label, categoryPair) \
  HelperThread::AutoProfilerLabel PROFILER_RAII( \
      this, label, JS::ProfilingCategoryPair::categoryPair)

using namespace js;

namespace js {

class HelperThread {
  Thread thread;

  /*
   * The profiling thread for this helper thread, which can be used to push
   * and pop label frames.
   * This field being non-null indicates that this thread has been registered
   * and needs to be unregistered at shutdown.
   */
  ProfilingStack* profilingStack = nullptr;

 public:
  HelperThread();
  [[nodiscard]] bool init(InternalThreadPool* pool);

  ThreadId threadId() { return thread.get_id(); }

  void join();

  static void ThreadMain(InternalThreadPool* pool, HelperThread* helper);
  void threadLoop(InternalThreadPool* pool);

  void ensureRegisteredWithProfiler();
  void unregisterWithProfilerIfNeeded();

 private:
  struct AutoProfilerLabel {
    AutoProfilerLabel(HelperThread* helperThread, const char* label,
                      JS::ProfilingCategoryPair categoryPair);
    ~AutoProfilerLabel();

   private:
    ProfilingStack* profilingStack;
  };
};

}  // namespace js

InternalThreadPool* InternalThreadPool::Instance = nullptr;

/* static */ InternalThreadPool& InternalThreadPool::Get() {
  MOZ_ASSERT(IsInitialized());
  return *Instance;
}

/* static */
bool InternalThreadPool::Initialize(size_t threadCount,
                                    AutoLockHelperThreadState& lock) {
  if (IsInitialized()) {
    return true;
  }

  auto instance = MakeUnique<InternalThreadPool>();
  if (!instance) {
    return false;
  }

  if (!instance->ensureThreadCount(threadCount, lock)) {
    instance->shutDown(lock);
    return false;
  }

  Instance = instance.release();
  HelperThreadState().setDispatchTaskCallback(DispatchTask, threadCount,
                                              HELPER_STACK_SIZE, lock);
  return true;
}

bool InternalThreadPool::ensureThreadCount(size_t threadCount,
                                           AutoLockHelperThreadState& lock) {
  MOZ_ASSERT(threads(lock).length() < threadCount);

  if (!threads(lock).reserve(threadCount)) {
    return false;
  }

  while (threads(lock).length() < threadCount) {
    auto thread = js::MakeUnique<HelperThread>();
    if (!thread || !thread->init(this)) {
      return false;
    }

    threads(lock).infallibleEmplaceBack(std::move(thread));
  }

  return true;
}

size_t InternalThreadPool::threadCount(const AutoLockHelperThreadState& lock) {
  return threads(lock).length();
}

/* static */
void InternalThreadPool::ShutDown(AutoLockHelperThreadState& lock) {
  MOZ_ASSERT(HelperThreadState().isTerminating(lock));

  Get().shutDown(lock);
  js_delete(Instance);
  Instance = nullptr;
}

void InternalThreadPool::shutDown(AutoLockHelperThreadState& lock) {
  MOZ_ASSERT(!terminating);
  terminating = true;

  notifyAll(lock);

  for (auto& thread : threads(lock)) {
    AutoUnlockHelperThreadState unlock(lock);
    thread->join();
  }
}

inline HelperThreadVector& InternalThreadPool::threads(
    const AutoLockHelperThreadState& lock) {
  return threads_.ref();
}
inline const HelperThreadVector& InternalThreadPool::threads(
    const AutoLockHelperThreadState& lock) const {
  return threads_.ref();
}

size_t InternalThreadPool::sizeOfIncludingThis(
    mozilla::MallocSizeOf mallocSizeOf,
    const AutoLockHelperThreadState& lock) const {
  return sizeof(InternalThreadPool) +
         threads(lock).sizeOfExcludingThis(mallocSizeOf);
}

/* static */
void InternalThreadPool::DispatchTask(JS::DispatchReason reason) {
  Get().dispatchTask(reason);
}

void InternalThreadPool::dispatchTask(JS::DispatchReason reason) {
  // This could now use a separate mutex like TaskController, but continues to
  // use the helper thread state lock for convenience.
  AutoLockHelperThreadState lock;

  queuedTasks++;
  if (reason == JS::DispatchReason::NewTask) {
    wakeup.notify_one();
  } else {
    // We're called from a helper thread right before returning to
    // HelperThread::threadLoop. There we will check queuedTasks so there's no
    // need to wake up any threads.
    MOZ_ASSERT(reason == JS::DispatchReason::FinishedTask);
    MOZ_ASSERT(!TlsContext.get(), "we should be on a helper thread");
  }
}

void InternalThreadPool::notifyAll(const AutoLockHelperThreadState& lock) {
  wakeup.notify_all();
}

void InternalThreadPool::wait(AutoLockHelperThreadState& lock) {
  wakeup.wait_for(lock, mozilla::TimeDuration::Forever());
}

HelperThread::HelperThread()
    : thread(Thread::Options().setStackSize(HELPER_STACK_SIZE)) {}

bool HelperThread::init(InternalThreadPool* pool) {
  return thread.init(HelperThread::ThreadMain, pool, this);
}

void HelperThread::join() { thread.join(); }

/* static */
void HelperThread::ThreadMain(InternalThreadPool* pool, HelperThread* helper) {
  ThisThread::SetName("JS Helper");

  helper->ensureRegisteredWithProfiler();
  helper->threadLoop(pool);
  helper->unregisterWithProfilerIfNeeded();
}

void HelperThread::ensureRegisteredWithProfiler() {
  if (profilingStack) {
    return;
  }

  // Note: To avoid dead locks, we should not hold on the helper thread lock
  // while calling this function. This is safe because the registerThread field
  // is a WriteOnceData<> type stored on the global helper tread state.
  JS::RegisterThreadCallback callback = HelperThreadState().registerThread;
  if (callback) {
    profilingStack =
        callback("JS Helper", reinterpret_cast<void*>(GetNativeStackBase()));
  }
}

void HelperThread::unregisterWithProfilerIfNeeded() {
  if (!profilingStack) {
    return;
  }

  // Note: To avoid dead locks, we should not hold on the helper thread lock
  // while calling this function. This is safe because the unregisterThread
  // field is a WriteOnceData<> type stored on the global helper tread state.
  JS::UnregisterThreadCallback callback = HelperThreadState().unregisterThread;
  if (callback) {
    callback();
    profilingStack = nullptr;
  }
}

HelperThread::AutoProfilerLabel::AutoProfilerLabel(
    HelperThread* helperThread, const char* label,
    JS::ProfilingCategoryPair categoryPair)
    : profilingStack(helperThread->profilingStack) {
  if (profilingStack) {
    profilingStack->pushLabelFrame(label, nullptr, this, categoryPair);
  }
}

HelperThread::AutoProfilerLabel::~AutoProfilerLabel() {
  if (profilingStack) {
    profilingStack->pop();
  }
}

void HelperThread::threadLoop(InternalThreadPool* pool) {
  MOZ_ASSERT(CanUseExtraThreads());

  AutoLockHelperThreadState lock;

  while (!pool->terminating) {
    if (pool->queuedTasks != 0) {
      pool->queuedTasks--;

      AutoUnlockHelperThreadState unlock(lock);
      JS::RunHelperThreadTask();
      continue;
    }

    AUTO_PROFILER_LABEL("HelperThread::threadLoop::wait", IDLE);
    pool->wait(lock);
  }
}