v8threads.cc 14.6 KB
Newer Older
1
// Copyright 2008 the V8 project authors. All rights reserved.
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
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
//       copyright notice, this list of conditions and the following
//       disclaimer in the documentation and/or other materials provided
//       with the distribution.
//     * Neither the name of Google Inc. nor the names of its
//       contributors may be used to endorse or promote products derived
//       from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include "v8.h"

#include "api.h"
31
#include "bootstrapper.h"
32 33 34
#include "debug.h"
#include "execution.h"
#include "v8threads.h"
35
#include "regexp-stack.h"
36 37 38

namespace v8 {

39 40 41 42 43 44

// Track whether this V8 instance has ever called v8::Locker. This allows the
// API code to verify that the lock is always held when V8 is being entered.
bool Locker::active_ = false;


45
// Constructor for the Locker object.  Once the Locker is constructed the
46 47 48 49 50 51 52 53
// current thread will be guaranteed to have the lock for a given isolate.
Locker::Locker(v8::Isolate* isolate)
  : has_lock_(false),
    top_level_(false),
    isolate_(reinterpret_cast<i::Isolate*>(isolate)) {
  if (isolate_ == NULL) {
    isolate_ = i::Isolate::GetDefaultIsolateForLocking();
  }
54 55
  // Record that the Locker has been used at least once.
  active_ = true;
56
  // Get the big lock if necessary.
57 58
  if (!isolate_->thread_manager()->IsLockedByCurrentThread()) {
    isolate_->thread_manager()->Lock();
59
    has_lock_ = true;
60

61 62 63
    // Make sure that V8 is initialized.  Archiving of threads interferes
    // with deserialization by adding additional root pointers, so we must
    // initialize here, before anyone can call ~Locker() or Unlocker().
64 65
    if (!isolate_->IsInitialized()) {
      isolate_->Enter();
66
      V8::Initialize();
67
      isolate_->Exit();
68
    }
69

70 71
    // This may be a locker within an unlocker in which case we have to
    // get the saved state for this thread and restore it.
72
    if (isolate_->thread_manager()->RestoreThread()) {
73
      top_level_ = false;
74
    } else {
75 76 77 78 79 80 81
      internal::ExecutionAccess access(isolate_);
      isolate_->stack_guard()->ClearThread(access);
      isolate_->stack_guard()->InitThread(access);
    }
    if (isolate_->IsDefaultIsolate()) {
      // This only enters if not yet entered.
      internal::Isolate::EnterDefaultIsolate();
82 83
    }
  }
84
  ASSERT(isolate_->thread_manager()->IsLockedByCurrentThread());
85 86 87
}


88 89 90 91 92 93
bool Locker::IsLocked(v8::Isolate* isolate) {
  i::Isolate* internal_isolate = reinterpret_cast<i::Isolate*>(isolate);
  if (internal_isolate == NULL) {
    internal_isolate = i::Isolate::GetDefaultIsolateForLocking();
  }
  return internal_isolate->thread_manager()->IsLockedByCurrentThread();
94 95 96 97
}


Locker::~Locker() {
98
  ASSERT(isolate_->thread_manager()->IsLockedByCurrentThread());
99
  if (has_lock_) {
100 101 102
    if (isolate_->IsDefaultIsolate()) {
      isolate_->Exit();
    }
103
    if (top_level_) {
104
      isolate_->thread_manager()->FreeThreadResources();
105
    } else {
106
      isolate_->thread_manager()->ArchiveThread();
107
    }
108
    isolate_->thread_manager()->Unlock();
109 110 111 112
  }
}


113 114 115 116 117 118 119 120 121 122 123
Unlocker::Unlocker(v8::Isolate* isolate)
  : isolate_(reinterpret_cast<i::Isolate*>(isolate)) {
  if (isolate_ == NULL) {
    isolate_ = i::Isolate::GetDefaultIsolateForLocking();
  }
  ASSERT(isolate_->thread_manager()->IsLockedByCurrentThread());
  if (isolate_->IsDefaultIsolate()) {
    isolate_->Exit();
  }
  isolate_->thread_manager()->ArchiveThread();
  isolate_->thread_manager()->Unlock();
124 125 126 127
}


Unlocker::~Unlocker() {
128 129 130 131 132 133
  ASSERT(!isolate_->thread_manager()->IsLockedByCurrentThread());
  isolate_->thread_manager()->Lock();
  isolate_->thread_manager()->RestoreThread();
  if (isolate_->IsDefaultIsolate()) {
    isolate_->Enter();
  }
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
}


void Locker::StartPreemption(int every_n_ms) {
  v8::internal::ContextSwitcher::StartPreemption(every_n_ms);
}


void Locker::StopPreemption() {
  v8::internal::ContextSwitcher::StopPreemption();
}


namespace internal {


bool ThreadManager::RestoreThread() {
151
  ASSERT(IsLockedByCurrentThread());
152 153 154
  // First check whether the current thread has been 'lazily archived', ie
  // not archived at all.  If that is the case we put the state storage we
  // had prepared back in the free list, since we didn't need it after all.
155 156
  if (lazily_archived_thread_.Equals(ThreadId::Current())) {
    lazily_archived_thread_ = ThreadId::Invalid();
157 158 159 160
    Isolate::PerIsolateThreadData* per_thread =
        isolate_->FindPerThreadDataForThisThread();
    ASSERT(per_thread != NULL);
    ASSERT(per_thread->thread_state() == lazily_archived_thread_state_);
161
    lazily_archived_thread_state_->set_id(ThreadId::Invalid());
162 163
    lazily_archived_thread_state_->LinkInto(ThreadState::FREE_LIST);
    lazily_archived_thread_state_ = NULL;
164
    per_thread->set_thread_state(NULL);
165 166
    return true;
  }
167

168 169
  // Make sure that the preemption thread cannot modify the thread state while
  // it is being archived or restored.
170
  ExecutionAccess access(isolate_);
171

172 173 174 175 176
  // If there is another thread that was lazily archived then we have to really
  // archive it now.
  if (lazily_archived_thread_.IsValid()) {
    EagerlyArchiveThread();
  }
177
  Isolate::PerIsolateThreadData* per_thread =
178
      isolate_->FindPerThreadDataForThisThread();
179
  if (per_thread == NULL || per_thread->thread_state() == NULL) {
180
    // This is a new thread.
181
    isolate_->stack_guard()->InitThread(access);
182 183
    return false;
  }
184
  ThreadState* state = per_thread->thread_state();
185
  char* from = state->data();
186 187
  from = isolate_->handle_scope_implementer()->RestoreThread(from);
  from = isolate_->RestoreThread(from);
188
  from = Relocatable::RestoreState(isolate_, from);
189
#ifdef ENABLE_DEBUGGER_SUPPORT
190
  from = isolate_->debug()->RestoreDebug(from);
191
#endif
192 193 194 195
  from = isolate_->stack_guard()->RestoreStackGuard(from);
  from = isolate_->regexp_stack()->RestoreStack(from);
  from = isolate_->bootstrapper()->RestoreState(from);
  per_thread->set_thread_state(NULL);
196
  if (state->terminate_on_restore()) {
197
    isolate_->stack_guard()->TerminateExecution();
198 199
    state->set_terminate_on_restore(false);
  }
200
  state->set_id(ThreadId::Invalid());
201 202 203 204 205 206 207 208
  state->Unlink();
  state->LinkInto(ThreadState::FREE_LIST);
  return true;
}


void ThreadManager::Lock() {
  mutex_->Lock();
209
  mutex_owner_ = ThreadId::Current();
210 211 212 213 214
  ASSERT(IsLockedByCurrentThread());
}


void ThreadManager::Unlock() {
215
  mutex_owner_ = ThreadId::Invalid();
216 217 218 219 220 221
  mutex_->Unlock();
}


static int ArchiveSpacePerThread() {
  return HandleScopeImplementer::ArchiveSpacePerThread() +
222
                        Isolate::ArchiveSpacePerThread() +
223
#ifdef ENABLE_DEBUGGER_SUPPORT
224
                          Debug::ArchiveSpacePerThread() +
225
#endif
226
                     StackGuard::ArchiveSpacePerThread() +
227
                    RegExpStack::ArchiveSpacePerThread() +
228 229
                   Bootstrapper::ArchiveSpacePerThread() +
                    Relocatable::ArchiveSpacePerThread();
230 231 232
}


233
ThreadState::ThreadState(ThreadManager* thread_manager)
234
    : id_(ThreadId::Invalid()),
235 236 237 238
      terminate_on_restore_(false),
      next_(this),
      previous_(this),
      thread_manager_(thread_manager) {
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
}


void ThreadState::AllocateSpace() {
  data_ = NewArray<char>(ArchiveSpacePerThread());
}


void ThreadState::Unlink() {
  next_->previous_ = previous_;
  previous_->next_ = next_;
}


void ThreadState::LinkInto(List list) {
  ThreadState* flying_anchor =
255 256
      list == FREE_LIST ? thread_manager_->free_anchor_
                        : thread_manager_->in_use_anchor_;
257 258 259 260 261 262 263
  next_ = flying_anchor->next_;
  previous_ = flying_anchor;
  flying_anchor->next_ = this;
  next_->previous_ = this;
}


264
ThreadState* ThreadManager::GetFreeThreadState() {
265 266
  ThreadState* gotten = free_anchor_->next_;
  if (gotten == free_anchor_) {
267
    ThreadState* new_thread_state = new ThreadState(this);
268 269 270 271 272 273 274 275
    new_thread_state->AllocateSpace();
    return new_thread_state;
  }
  return gotten;
}


// Gets the first in the list of archived threads.
276
ThreadState* ThreadManager::FirstThreadStateInUse() {
277 278 279 280 281
  return in_use_anchor_->Next();
}


ThreadState* ThreadState::Next() {
282
  if (next_ == thread_manager_->in_use_anchor_) return NULL;
283 284 285 286
  return next_;
}


287 288 289
// Thread ids must start with 1, because in TLS having thread id 0 can't
// be distinguished from not having a thread id at all (since NULL is
// defined as 0.)
290 291
ThreadManager::ThreadManager()
    : mutex_(OS::CreateMutex()),
292 293
      mutex_owner_(ThreadId::Invalid()),
      lazily_archived_thread_(ThreadId::Invalid()),
294 295 296 297 298 299 300 301 302 303 304
      lazily_archived_thread_state_(NULL),
      free_anchor_(NULL),
      in_use_anchor_(NULL) {
  free_anchor_ = new ThreadState(this);
  in_use_anchor_ = new ThreadState(this);
}


ThreadManager::~ThreadManager() {
  // TODO(isolates): Destroy mutexes.
}
305 306 307


void ThreadManager::ArchiveThread() {
308
  ASSERT(lazily_archived_thread_.Equals(ThreadId::Invalid()));
309
  ASSERT(!IsArchived());
310
  ASSERT(IsLockedByCurrentThread());
311
  ThreadState* state = GetFreeThreadState();
312
  state->Unlink();
313 314 315
  Isolate::PerIsolateThreadData* per_thread =
      isolate_->FindOrAllocatePerThreadDataForThisThread();
  per_thread->set_thread_state(state);
316
  lazily_archived_thread_ = ThreadId::Current();
317
  lazily_archived_thread_state_ = state;
318
  ASSERT(state->id().Equals(ThreadId::Invalid()));
319
  state->set_id(CurrentId());
320
  ASSERT(!state->id().Equals(ThreadId::Invalid()));
321 322 323 324
}


void ThreadManager::EagerlyArchiveThread() {
325
  ASSERT(IsLockedByCurrentThread());
326 327 328
  ThreadState* state = lazily_archived_thread_state_;
  state->LinkInto(ThreadState::IN_USE_LIST);
  char* to = state->data();
329 330
  // Ensure that data containing GC roots are archived first, and handle them
  // in ThreadManager::Iterate(ObjectVisitor*).
331 332
  to = isolate_->handle_scope_implementer()->ArchiveThread(to);
  to = isolate_->ArchiveThread(to);
333
  to = Relocatable::ArchiveState(isolate_, to);
334
#ifdef ENABLE_DEBUGGER_SUPPORT
335
  to = isolate_->debug()->ArchiveDebug(to);
336
#endif
337 338 339
  to = isolate_->stack_guard()->ArchiveStackGuard(to);
  to = isolate_->regexp_stack()->ArchiveStack(to);
  to = isolate_->bootstrapper()->ArchiveState(to);
340
  lazily_archived_thread_ = ThreadId::Invalid();
341 342 343 344
  lazily_archived_thread_state_ = NULL;
}


345
void ThreadManager::FreeThreadResources() {
346 347
  isolate_->handle_scope_implementer()->FreeThreadResources();
  isolate_->FreeThreadResources();
348
#ifdef ENABLE_DEBUGGER_SUPPORT
349
  isolate_->debug()->FreeThreadResources();
350
#endif
351 352 353
  isolate_->stack_guard()->FreeThreadResources();
  isolate_->regexp_stack()->FreeThreadResources();
  isolate_->bootstrapper()->FreeThreadResources();
354 355 356
}


357
bool ThreadManager::IsArchived() {
358 359
  Isolate::PerIsolateThreadData* data =
      isolate_->FindPerThreadDataForThisThread();
360
  return data != NULL && data->thread_state() != NULL;
361 362
}

363 364
void ThreadManager::Iterate(ObjectVisitor* v) {
  // Expecting no threads during serialization/deserialization
365
  for (ThreadState* state = FirstThreadStateInUse();
366 367 368 369
       state != NULL;
       state = state->Next()) {
    char* data = state->data();
    data = HandleScopeImplementer::Iterate(v, data);
370
    data = isolate_->Iterate(v, data);
371
    data = Relocatable::Iterate(v, data);
372 373 374 375
  }
}


376
void ThreadManager::IterateArchivedThreads(ThreadVisitor* v) {
377
  for (ThreadState* state = FirstThreadStateInUse();
378 379 380 381
       state != NULL;
       state = state->Next()) {
    char* data = state->data();
    data += HandleScopeImplementer::ArchiveSpacePerThread();
382
    isolate_->IterateThread(v, data);
383 384 385 386
  }
}


387 388
ThreadId ThreadManager::CurrentId() {
  return ThreadId::Current();
389 390 391
}


392
void ThreadManager::TerminateExecution(ThreadId thread_id) {
393
  for (ThreadState* state = FirstThreadStateInUse();
394 395
       state != NULL;
       state = state->Next()) {
396
    if (thread_id.Equals(state->id())) {
397 398
      state->set_terminate_on_restore(true);
    }
399 400 401 402
  }
}


403
ContextSwitcher::ContextSwitcher(Isolate* isolate, int every_n_ms)
404
  : Thread("v8:CtxtSwitcher"),
405
    keep_going_(true),
406 407
    sleep_ms_(every_n_ms),
    isolate_(isolate) {
408 409 410
}


iposva@chromium.org's avatar
iposva@chromium.org committed
411 412
// Set the scheduling interval of V8 threads. This function starts the
// ContextSwitcher thread if needed.
413
void ContextSwitcher::StartPreemption(int every_n_ms) {
414
  Isolate* isolate = Isolate::Current();
415
  ASSERT(Locker::IsLocked(reinterpret_cast<v8::Isolate*>(isolate)));
416
  if (isolate->context_switcher() == NULL) {
iposva@chromium.org's avatar
iposva@chromium.org committed
417
    // If the ContextSwitcher thread is not running at the moment start it now.
418 419
    isolate->set_context_switcher(new ContextSwitcher(isolate, every_n_ms));
    isolate->context_switcher()->Start();
420
  } else {
iposva@chromium.org's avatar
iposva@chromium.org committed
421 422
    // ContextSwitcher thread is already running, so we just change the
    // scheduling interval.
423
    isolate->context_switcher()->sleep_ms_ = every_n_ms;
424 425 426 427
  }
}


iposva@chromium.org's avatar
iposva@chromium.org committed
428 429
// Disable preemption of V8 threads. If multiple threads want to use V8 they
// must cooperatively schedule amongst them from this point on.
430
void ContextSwitcher::StopPreemption() {
431
  Isolate* isolate = Isolate::Current();
432
  ASSERT(Locker::IsLocked(reinterpret_cast<v8::Isolate*>(isolate)));
433
  if (isolate->context_switcher() != NULL) {
iposva@chromium.org's avatar
iposva@chromium.org committed
434 435
    // The ContextSwitcher thread is running. We need to stop it and release
    // its resources.
436 437 438
    isolate->context_switcher()->keep_going_ = false;
    // Wait for the ContextSwitcher thread to exit.
    isolate->context_switcher()->Join();
iposva@chromium.org's avatar
iposva@chromium.org committed
439
    // Thread has exited, now we can delete it.
440 441
    delete(isolate->context_switcher());
    isolate->set_context_switcher(NULL);
442 443 444 445
  }
}


iposva@chromium.org's avatar
iposva@chromium.org committed
446 447
// Main loop of the ContextSwitcher thread: Preempt the currently running V8
// thread at regular intervals.
448 449 450
void ContextSwitcher::Run() {
  while (keep_going_) {
    OS::Sleep(sleep_ms_);
451
    isolate()->stack_guard()->Preempt();
452 453 454 455
  }
}


iposva@chromium.org's avatar
iposva@chromium.org committed
456
// Acknowledge the preemption by the receiving thread.
457
void ContextSwitcher::PreemptionReceived() {
458
  ASSERT(Locker::IsLocked());
iposva@chromium.org's avatar
iposva@chromium.org committed
459 460
  // There is currently no accounting being done for this. But could be in the
  // future, which is why we leave this in.
461 462 463 464 465
}


}  // namespace internal
}  // namespace v8