local-heap.h 10.6 KB
Newer Older
1 2 3 4 5 6 7 8
// Copyright 2020 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef V8_HEAP_LOCAL_HEAP_H_
#define V8_HEAP_LOCAL_HEAP_H_

#include <atomic>
9
#include <memory>
10

11
#include "src/base/logging.h"
12
#include "src/base/macros.h"
13 14
#include "src/base/platform/condition-variable.h"
#include "src/base/platform/mutex.h"
15
#include "src/common/assert-scope.h"
16
#include "src/execution/isolate.h"
17
#include "src/handles/persistent-handles.h"
18
#include "src/heap/concurrent-allocator.h"
19 20 21 22 23

namespace v8 {
namespace internal {

class Heap;
24
class LocalHandles;
25 26
class MemoryChunk;
class Safepoint;
27

28 29 30 31 32 33 34 35 36
// LocalHeap is used by the GC to track all threads with heap access in order to
// stop them before performing a collection. LocalHeaps can be either Parked or
// Running and are in Parked mode when initialized.
//   Running: Thread is allowed to access the heap but needs to give the GC the
//            chance to run regularly by manually invoking Safepoint(). The
//            thread can be parked using ParkedScope.
//   Parked:  Heap access is not allowed, so the GC will not stop this thread
//            for a collection. Useful when threads do not need heap access for
//            some time or for blocking operations like locking a mutex.
37
class V8_EXPORT_PRIVATE LocalHeap {
38
 public:
39 40
  using GCEpilogueCallback = void(void* data);

41
  explicit LocalHeap(
42
      Heap* heap, ThreadKind kind,
43
      std::unique_ptr<PersistentHandles> persistent_handles = nullptr);
44
  ~LocalHeap();
45 46 47

  // Frequently invoked by local thread to check whether safepoint was requested
  // from the main thread.
48
  void Safepoint() {
49
    DCHECK(AllowSafepoints::IsAllowed());
50
    ThreadState current = state_.load_relaxed();
51

52
    if (V8_UNLIKELY(current.IsRunningWithSlowPathFlag())) {
53
      SafepointSlowPath();
54 55
    }
  }
56

57 58
  LocalHandles* handles() { return handles_.get(); }

59
  template <typename T>
60 61 62 63 64 65 66
  Handle<T> NewPersistentHandle(T object) {
    if (!persistent_handles_) {
      EnsurePersistentHandles();
    }
    return persistent_handles_->NewHandle(object);
  }

67
  template <typename T>
68 69 70 71
  Handle<T> NewPersistentHandle(Handle<T> object) {
    return NewPersistentHandle(*object);
  }

72 73 74 75 76 77 78 79 80
  template <typename T>
  MaybeHandle<T> NewPersistentMaybeHandle(MaybeHandle<T> maybe_handle) {
    Handle<T> handle;
    if (maybe_handle.ToHandle(&handle)) {
      return NewPersistentHandle(handle);
    }
    return kNullMaybeHandle;
  }

81 82
  void AttachPersistentHandles(
      std::unique_ptr<PersistentHandles> persistent_handles);
83
  std::unique_ptr<PersistentHandles> DetachPersistentHandles();
84
#ifdef DEBUG
85
  bool HasPersistentHandles() { return !!persistent_handles_; }
86
  bool ContainsPersistentHandle(Address* location);
87
  bool ContainsLocalHandle(Address* location);
88
  bool IsHandleDereferenceAllowed();
89
#endif
90 91

  bool IsParked();
92
  bool IsRunning();
93

94
  Heap* heap() { return heap_; }
95
  Heap* AsHeap() { return heap(); }
96

97
  MarkingBarrier* marking_barrier() { return marking_barrier_.get(); }
98 99 100 101 102 103
  ConcurrentAllocator* old_space_allocator() {
    return old_space_allocator_.get();
  }
  ConcurrentAllocator* code_space_allocator() {
    return code_space_allocator_.get();
  }
104 105 106
  ConcurrentAllocator* shared_old_space_allocator() {
    return shared_old_space_allocator_.get();
  }
107

108 109 110 111
  void RegisterCodeObject(Handle<Code> code) {
    heap()->RegisterCodeObject(code);
  }

112 113 114 115 116 117 118
  // Mark/Unmark linear allocation areas black. Used for black allocation.
  void MarkLinearAllocationAreaBlack();
  void UnmarkLinearAllocationArea();

  // Give up linear allocation areas. Used for mark-compact GC.
  void FreeLinearAllocationArea();

119 120 121
  // Free all shared LABs. Used by the shared mark-compact GC.
  void FreeSharedLinearAllocationArea();

122 123 124 125
  // Create filler object in linear allocation areas. Verifying requires
  // iterable heap.
  void MakeLinearAllocationAreaIterable();

126 127 128 129 130 131 132
  // Fetches a pointer to the local heap from the thread local storage.
  // It is intended to be used in handle and write barrier code where it is
  // difficult to get a pointer to the current instance of local heap otherwise.
  // The result may be a nullptr if there is no local heap instance associated
  // with the current thread.
  static LocalHeap* Current();

133 134 135 136
#ifdef DEBUG
  void VerifyCurrent();
#endif

137 138 139 140
  // Allocate an uninitialized object.
  V8_WARN_UNUSED_RESULT inline AllocationResult AllocateRaw(
      int size_in_bytes, AllocationType allocation,
      AllocationOrigin origin = AllocationOrigin::kRuntime,
141
      AllocationAlignment alignment = kTaggedAligned);
142 143 144 145 146 147

  // Allocates an uninitialized object and crashes when object
  // cannot be allocated.
  V8_WARN_UNUSED_RESULT inline Address AllocateRawOrFail(
      int size_in_bytes, AllocationType allocation,
      AllocationOrigin origin = AllocationOrigin::kRuntime,
148
      AllocationAlignment alignment = kTaggedAligned);
149

150 151
  void NotifyObjectSizeChange(HeapObject object, int old_size, int new_size,
                              ClearRecordedSlots clear_recorded_slots);
152

153
  bool is_main_thread() const { return is_main_thread_; }
154 155 156 157
  bool deserialization_complete() const {
    return heap_->deserialization_complete();
  }
  ReadOnlySpace* read_only_space() { return heap_->read_only_space(); }
158

159
  // Requests GC and blocks until the collection finishes.
160
  bool TryPerformCollection();
161

162 163 164 165 166 167 168
  // Adds a callback that is invoked with the given |data| after each GC.
  // The callback is invoked on the main thread before any background thread
  // resumes. The callback must not allocate or make any other calls that
  // can trigger GC.
  void AddGCEpilogueCallback(GCEpilogueCallback* callback, void* data);
  void RemoveGCEpilogueCallback(GCEpilogueCallback* callback, void* data);

169 170 171
  // Used to make SetupMainThread() available to unit tests.
  void SetUpMainThreadForTesting();

172
 private:
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
  using ParkedBit = base::BitField8<bool, 0, 1>;
  using SafepointRequestedBit = ParkedBit::Next<bool, 1>;
  using CollectionRequestedBit = SafepointRequestedBit::Next<bool, 1>;

  class ThreadState final {
   public:
    static constexpr ThreadState Parked() {
      return ThreadState(ParkedBit::kMask);
    }
    static constexpr ThreadState Running() { return ThreadState(0); }

    constexpr bool IsRunning() const { return !ParkedBit::decode(raw_state_); }

    constexpr ThreadState SetRunning() const V8_WARN_UNUSED_RESULT {
      return ThreadState(raw_state_ & ~ParkedBit::kMask);
    }

    constexpr bool IsParked() const { return ParkedBit::decode(raw_state_); }

    constexpr ThreadState SetParked() const V8_WARN_UNUSED_RESULT {
      return ThreadState(ParkedBit::kMask | raw_state_);
    }

    constexpr bool IsSafepointRequested() const {
      return SafepointRequestedBit::decode(raw_state_);
    }

    constexpr bool IsCollectionRequested() const {
      return CollectionRequestedBit::decode(raw_state_);
    }

    constexpr bool IsRunningWithSlowPathFlag() const {
      return IsRunning() && (raw_state_ & (SafepointRequestedBit::kMask |
                                           CollectionRequestedBit::kMask));
    }

   private:
    constexpr explicit ThreadState(uint8_t value) : raw_state_(value) {}

212
    constexpr uint8_t raw() const { return raw_state_; }
213 214 215 216

    uint8_t raw_state_;

    friend class LocalHeap;
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
  class AtomicThreadState final {
   public:
    constexpr explicit AtomicThreadState(ThreadState state)
        : raw_state_(state.raw()) {}

    bool CompareExchangeStrong(ThreadState& expected, ThreadState updated) {
      return raw_state_.compare_exchange_strong(expected.raw_state_,
                                                updated.raw());
    }

    bool CompareExchangeWeak(ThreadState& expected, ThreadState updated) {
      return raw_state_.compare_exchange_weak(expected.raw_state_,
                                              updated.raw());
    }

    ThreadState SetParked() {
      return ThreadState(raw_state_.fetch_or(ParkedBit::kMask));
    }

    ThreadState SetSafepointRequested() {
      return ThreadState(raw_state_.fetch_or(SafepointRequestedBit::kMask));
    }

    ThreadState ClearSafepointRequested() {
      return ThreadState(raw_state_.fetch_and(~SafepointRequestedBit::kMask));
    }

    ThreadState SetCollectionRequested() {
      return ThreadState(raw_state_.fetch_or(CollectionRequestedBit::kMask));
    }

    ThreadState ClearCollectionRequested() {
      return ThreadState(raw_state_.fetch_and(~CollectionRequestedBit::kMask));
    }

    ThreadState load_relaxed() const {
      return ThreadState(raw_state_.load(std::memory_order_relaxed));
    }

   private:
    std::atomic<uint8_t> raw_state_;
  };
261

262 263 264 265 266 267 268
  // Slow path of allocation that performs GC and then retries allocation in
  // loop.
  Address PerformCollectionAndAllocateAgain(int object_size,
                                            AllocationType type,
                                            AllocationOrigin origin,
                                            AllocationAlignment alignment);

269
  void Park() {
270
    DCHECK(AllowSafepoints::IsAllowed());
271 272 273
    ThreadState expected = ThreadState::Running();
    if (!state_.CompareExchangeWeak(expected, ThreadState::Parked())) {
      ParkSlowPath();
274 275 276 277
    }
  }

  void Unpark() {
278
    DCHECK(AllowSafepoints::IsAllowed());
279 280
    ThreadState expected = ThreadState::Parked();
    if (!state_.CompareExchangeWeak(expected, ThreadState::Running())) {
281 282 283 284
      UnparkSlowPath();
    }
  }

285
  void ParkSlowPath();
286
  void UnparkSlowPath();
287
  void EnsureParkedBeforeDestruction();
288
  void SafepointSlowPath();
289 290
  void SleepInSafepoint();
  void SleepInUnpark();
291

292 293
  void EnsurePersistentHandles();

294 295
  void InvokeGCEpilogueCallbacksInSafepoint();

296 297 298
  void SetUpMainThread();
  void SetUp();

299
  Heap* heap_;
300
  bool is_main_thread_;
301

302
  AtomicThreadState state_;
303

304
  bool allocation_failed_;
305
  bool main_thread_parked_;
306

307 308 309
  LocalHeap* prev_;
  LocalHeap* next_;

310 311 312
  std::unordered_set<MemoryChunk*> unprotected_memory_chunks_;
  uintptr_t code_page_collection_memory_modification_scope_depth_{0};

313
  std::unique_ptr<LocalHandles> handles_;
314
  std::unique_ptr<PersistentHandles> persistent_handles_;
315
  std::unique_ptr<MarkingBarrier> marking_barrier_;
316

317 318
  std::vector<std::pair<GCEpilogueCallback*, void*>> gc_epilogue_callbacks_;

319 320
  std::unique_ptr<ConcurrentAllocator> old_space_allocator_;
  std::unique_ptr<ConcurrentAllocator> code_space_allocator_;
321
  std::unique_ptr<ConcurrentAllocator> shared_old_space_allocator_;
322

323 324
  friend class CollectionBarrier;
  friend class ConcurrentAllocator;
325
  friend class GlobalSafepoint;
326
  friend class IsolateSafepoint;
327 328
  friend class Heap;
  friend class Isolate;
329
  friend class ParkedScope;
330
  friend class SafepointScope;
331
  friend class UnparkedScope;
332 333
};

334 335 336 337
}  // namespace internal
}  // namespace v8

#endif  // V8_HEAP_LOCAL_HEAP_H_