1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 #include "WorkerThread.h"
8
9 #include "mozilla/Assertions.h"
10 #include "mozilla/ipc/BackgroundChild.h"
11 #include "EventQueue.h"
12 #include "mozilla/ThreadEventQueue.h"
13 #include "nsIThreadInternal.h"
14 #include "WorkerPrivate.h"
15 #include "WorkerRunnable.h"
16
17 #ifdef DEBUG
18 #include "nsThreadManager.h"
19 #endif
20
21 namespace mozilla {
22
23 using namespace ipc;
24
25 namespace dom {
26
27 namespace {
28
29 // The C stack size. We use the same stack size on all platforms for
30 // consistency.
31 const uint32_t kWorkerStackSize = 256 * sizeof(size_t) * 1024;
32
33 } // namespace
34
WorkerThreadFriendKey()35 WorkerThreadFriendKey::WorkerThreadFriendKey() {
36 MOZ_COUNT_CTOR(WorkerThreadFriendKey);
37 }
38
~WorkerThreadFriendKey()39 WorkerThreadFriendKey::~WorkerThreadFriendKey() {
40 MOZ_COUNT_DTOR(WorkerThreadFriendKey);
41 }
42
43 class WorkerThread::Observer final : public nsIThreadObserver {
44 WorkerPrivate* mWorkerPrivate;
45
46 public:
Observer(WorkerPrivate * aWorkerPrivate)47 explicit Observer(WorkerPrivate* aWorkerPrivate)
48 : mWorkerPrivate(aWorkerPrivate) {
49 MOZ_ASSERT(aWorkerPrivate);
50 aWorkerPrivate->AssertIsOnWorkerThread();
51 }
52
53 NS_DECL_THREADSAFE_ISUPPORTS
54
55 private:
~Observer()56 ~Observer() { mWorkerPrivate->AssertIsOnWorkerThread(); }
57
58 NS_DECL_NSITHREADOBSERVER
59 };
60
WorkerThread()61 WorkerThread::WorkerThread()
62 : nsThread(MakeNotNull<ThreadEventQueue<mozilla::EventQueue>*>(
63 MakeUnique<mozilla::EventQueue>()),
64 nsThread::NOT_MAIN_THREAD, kWorkerStackSize),
65 mLock("WorkerThread::mLock"),
66 mWorkerPrivateCondVar(mLock, "WorkerThread::mWorkerPrivateCondVar"),
67 mWorkerPrivate(nullptr),
68 mOtherThreadsDispatchingViaEventTarget(0)
69 #ifdef DEBUG
70 ,
71 mAcceptingNonWorkerRunnables(true)
72 #endif
73 {
74 }
75
~WorkerThread()76 WorkerThread::~WorkerThread() {
77 MOZ_ASSERT(!mWorkerPrivate);
78 MOZ_ASSERT(!mOtherThreadsDispatchingViaEventTarget);
79 MOZ_ASSERT(mAcceptingNonWorkerRunnables);
80 }
81
82 // static
Create(const WorkerThreadFriendKey &)83 already_AddRefed<WorkerThread> WorkerThread::Create(
84 const WorkerThreadFriendKey& /* aKey */) {
85 RefPtr<WorkerThread> thread = new WorkerThread();
86 if (NS_FAILED(thread->Init(NS_LITERAL_CSTRING("DOM Worker")))) {
87 NS_WARNING("Failed to create new thread!");
88 return nullptr;
89 }
90
91 return thread.forget();
92 }
93
SetWorker(const WorkerThreadFriendKey &,WorkerPrivate * aWorkerPrivate)94 void WorkerThread::SetWorker(const WorkerThreadFriendKey& /* aKey */,
95 WorkerPrivate* aWorkerPrivate) {
96 MOZ_ASSERT(PR_GetCurrentThread() == mThread);
97
98 if (aWorkerPrivate) {
99 {
100 MutexAutoLock lock(mLock);
101
102 MOZ_ASSERT(!mWorkerPrivate);
103 MOZ_ASSERT(mAcceptingNonWorkerRunnables);
104
105 mWorkerPrivate = aWorkerPrivate;
106 #ifdef DEBUG
107 mAcceptingNonWorkerRunnables = false;
108 #endif
109 }
110
111 mObserver = new Observer(aWorkerPrivate);
112 MOZ_ALWAYS_SUCCEEDS(AddObserver(mObserver));
113 } else {
114 MOZ_ALWAYS_SUCCEEDS(RemoveObserver(mObserver));
115 mObserver = nullptr;
116
117 {
118 MutexAutoLock lock(mLock);
119
120 MOZ_ASSERT(mWorkerPrivate);
121 MOZ_ASSERT(!mAcceptingNonWorkerRunnables);
122 MOZ_ASSERT(!mOtherThreadsDispatchingViaEventTarget,
123 "XPCOM Dispatch hapenning at the same time our thread is "
124 "being unset! This should not be possible!");
125
126 while (mOtherThreadsDispatchingViaEventTarget) {
127 mWorkerPrivateCondVar.Wait();
128 }
129
130 #ifdef DEBUG
131 mAcceptingNonWorkerRunnables = true;
132 #endif
133 mWorkerPrivate = nullptr;
134 }
135 }
136 }
137
DispatchPrimaryRunnable(const WorkerThreadFriendKey &,already_AddRefed<nsIRunnable> aRunnable)138 nsresult WorkerThread::DispatchPrimaryRunnable(
139 const WorkerThreadFriendKey& /* aKey */,
140 already_AddRefed<nsIRunnable> aRunnable) {
141 nsCOMPtr<nsIRunnable> runnable(aRunnable);
142
143 #ifdef DEBUG
144 MOZ_ASSERT(PR_GetCurrentThread() != mThread);
145 MOZ_ASSERT(runnable);
146 {
147 MutexAutoLock lock(mLock);
148
149 MOZ_ASSERT(!mWorkerPrivate);
150 MOZ_ASSERT(mAcceptingNonWorkerRunnables);
151 }
152 #endif
153
154 nsresult rv = nsThread::Dispatch(runnable.forget(), NS_DISPATCH_NORMAL);
155 if (NS_WARN_IF(NS_FAILED(rv))) {
156 return rv;
157 }
158
159 return NS_OK;
160 }
161
DispatchAnyThread(const WorkerThreadFriendKey &,already_AddRefed<WorkerRunnable> aWorkerRunnable)162 nsresult WorkerThread::DispatchAnyThread(
163 const WorkerThreadFriendKey& /* aKey */,
164 already_AddRefed<WorkerRunnable> aWorkerRunnable) {
165 // May be called on any thread!
166
167 #ifdef DEBUG
168 {
169 const bool onWorkerThread = PR_GetCurrentThread() == mThread;
170 {
171 MutexAutoLock lock(mLock);
172
173 MOZ_ASSERT(mWorkerPrivate);
174 MOZ_ASSERT(!mAcceptingNonWorkerRunnables);
175
176 if (onWorkerThread) {
177 mWorkerPrivate->AssertIsOnWorkerThread();
178 }
179 }
180 }
181 #endif
182 nsCOMPtr<nsIRunnable> runnable(aWorkerRunnable);
183
184 nsresult rv = nsThread::Dispatch(runnable.forget(), NS_DISPATCH_NORMAL);
185 if (NS_WARN_IF(NS_FAILED(rv))) {
186 return rv;
187 }
188
189 // We don't need to notify the worker's condition variable here because we're
190 // being called from worker-controlled code and it will make sure to wake up
191 // the worker thread if needed.
192
193 return NS_OK;
194 }
195
196 NS_IMETHODIMP
DispatchFromScript(nsIRunnable * aRunnable,uint32_t aFlags)197 WorkerThread::DispatchFromScript(nsIRunnable* aRunnable, uint32_t aFlags) {
198 nsCOMPtr<nsIRunnable> runnable(aRunnable);
199 return Dispatch(runnable.forget(), aFlags);
200 }
201
202 NS_IMETHODIMP
Dispatch(already_AddRefed<nsIRunnable> aRunnable,uint32_t aFlags)203 WorkerThread::Dispatch(already_AddRefed<nsIRunnable> aRunnable,
204 uint32_t aFlags) {
205 // May be called on any thread!
206 nsCOMPtr<nsIRunnable> runnable(aRunnable); // in case we exit early
207
208 // Workers only support asynchronous dispatch.
209 if (NS_WARN_IF(aFlags != NS_DISPATCH_NORMAL)) {
210 return NS_ERROR_UNEXPECTED;
211 }
212
213 const bool onWorkerThread = PR_GetCurrentThread() == mThread;
214
215 #ifdef DEBUG
216 if (runnable && !onWorkerThread) {
217 nsCOMPtr<nsICancelableRunnable> cancelable = do_QueryInterface(runnable);
218
219 {
220 MutexAutoLock lock(mLock);
221
222 // Only enforce cancelable runnables after we've started the worker loop.
223 if (!mAcceptingNonWorkerRunnables) {
224 MOZ_ASSERT(cancelable,
225 "Only nsICancelableRunnable may be dispatched to a worker!");
226 }
227 }
228 }
229 #endif
230
231 WorkerPrivate* workerPrivate = nullptr;
232 if (onWorkerThread) {
233 // No need to lock here because it is only modified on this thread.
234 MOZ_ASSERT(mWorkerPrivate);
235 mWorkerPrivate->AssertIsOnWorkerThread();
236
237 workerPrivate = mWorkerPrivate;
238 } else {
239 MutexAutoLock lock(mLock);
240
241 MOZ_ASSERT(mOtherThreadsDispatchingViaEventTarget < UINT32_MAX);
242
243 if (mWorkerPrivate) {
244 workerPrivate = mWorkerPrivate;
245
246 // Incrementing this counter will make the worker thread sleep if it
247 // somehow tries to unset mWorkerPrivate while we're using it.
248 mOtherThreadsDispatchingViaEventTarget++;
249 }
250 }
251
252 nsresult rv;
253 if (runnable && onWorkerThread) {
254 RefPtr<WorkerRunnable> workerRunnable =
255 workerPrivate->MaybeWrapAsWorkerRunnable(runnable.forget());
256 rv = nsThread::Dispatch(workerRunnable.forget(), NS_DISPATCH_NORMAL);
257 } else {
258 rv = nsThread::Dispatch(runnable.forget(), NS_DISPATCH_NORMAL);
259 }
260
261 if (!onWorkerThread && workerPrivate) {
262 // We need to wake the worker thread if we're not already on the right
263 // thread and the dispatch succeeded.
264 if (NS_SUCCEEDED(rv)) {
265 MutexAutoLock workerLock(workerPrivate->mMutex);
266
267 workerPrivate->mCondVar.Notify();
268 }
269
270 // Now unset our waiting flag.
271 {
272 MutexAutoLock lock(mLock);
273
274 MOZ_ASSERT(mOtherThreadsDispatchingViaEventTarget);
275
276 if (!--mOtherThreadsDispatchingViaEventTarget) {
277 mWorkerPrivateCondVar.Notify();
278 }
279 }
280 }
281
282 if (NS_WARN_IF(NS_FAILED(rv))) {
283 return rv;
284 }
285
286 return NS_OK;
287 }
288
289 NS_IMETHODIMP
DelayedDispatch(already_AddRefed<nsIRunnable>,uint32_t)290 WorkerThread::DelayedDispatch(already_AddRefed<nsIRunnable>, uint32_t) {
291 return NS_ERROR_NOT_IMPLEMENTED;
292 }
293
RecursionDepth(const WorkerThreadFriendKey &) const294 uint32_t WorkerThread::RecursionDepth(
295 const WorkerThreadFriendKey& /* aKey */) const {
296 MOZ_ASSERT(PR_GetCurrentThread() == mThread);
297
298 return mNestedEventLoopDepth;
299 }
300
NS_IMPL_ISUPPORTS(WorkerThread::Observer,nsIThreadObserver)301 NS_IMPL_ISUPPORTS(WorkerThread::Observer, nsIThreadObserver)
302
303 NS_IMETHODIMP
304 WorkerThread::Observer::OnDispatchedEvent() {
305 MOZ_CRASH("OnDispatchedEvent() should never be called!");
306 }
307
308 NS_IMETHODIMP
OnProcessNextEvent(nsIThreadInternal *,bool aMayWait)309 WorkerThread::Observer::OnProcessNextEvent(nsIThreadInternal* /* aThread */,
310 bool aMayWait) {
311 mWorkerPrivate->AssertIsOnWorkerThread();
312
313 // If the PBackground child is not created yet, then we must permit
314 // blocking event processing to support
315 // BackgroundChild::GetOrCreateCreateForCurrentThread(). If this occurs
316 // then we are spinning on the event queue at the start of
317 // PrimaryWorkerRunnable::Run() and don't want to process the event in
318 // mWorkerPrivate yet.
319 if (aMayWait) {
320 MOZ_ASSERT(CycleCollectedJSContext::Get()->RecursionDepth() == 2);
321 MOZ_ASSERT(!BackgroundChild::GetForCurrentThread());
322 return NS_OK;
323 }
324
325 mWorkerPrivate->OnProcessNextEvent();
326 return NS_OK;
327 }
328
329 NS_IMETHODIMP
AfterProcessNextEvent(nsIThreadInternal *,bool)330 WorkerThread::Observer::AfterProcessNextEvent(nsIThreadInternal* /* aThread */,
331 bool /* aEventWasProcessed */) {
332 mWorkerPrivate->AssertIsOnWorkerThread();
333
334 mWorkerPrivate->AfterProcessNextEvent();
335 return NS_OK;
336 }
337
338 } // namespace dom
339 } // namespace mozilla
340