memory-reducer.cc 8.34 KB
Newer Older
1 2 3 4 5 6 7
// Copyright 2015 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.

#include "src/heap/memory-reducer.h"

#include "src/flags.h"
8
#include "src/heap/gc-tracer.h"
9
#include "src/heap/heap-inl.h"
10
#include "src/heap/incremental-marking.h"
11 12 13 14 15 16
#include "src/utils.h"
#include "src/v8.h"

namespace v8 {
namespace internal {

17
const int MemoryReducer::kLongDelayMs = 8000;
18
const int MemoryReducer::kShortDelayMs = 500;
19
const int MemoryReducer::kWatchdogDelayMs = 100000;
20
const int MemoryReducer::kMaxNumberOfGCs = 3;
21 22
const double MemoryReducer::kCommittedMemoryFactor = 1.1;
const size_t MemoryReducer::kCommittedMemoryDelta = 10 * MB;
23

24 25 26 27 28 29 30 31
MemoryReducer::MemoryReducer(Heap* heap)
    : heap_(heap),
      taskrunner_(V8::GetCurrentPlatform()->GetForegroundTaskRunner(
          reinterpret_cast<v8::Isolate*>(heap->isolate()))),
      state_(kDone, 0, 0.0, 0.0, 0),
      js_calls_counter_(0),
      js_calls_sample_time_ms_(0.0) {}

32 33 34
MemoryReducer::TimerTask::TimerTask(MemoryReducer* memory_reducer)
    : CancelableTask(memory_reducer->heap()->isolate()),
      memory_reducer_(memory_reducer) {}
35

36 37

void MemoryReducer::TimerTask::RunInternal() {
38 39
  Heap* heap = memory_reducer_->heap();
  Event event;
40 41 42
  double time_ms = heap->MonotonicallyIncreasingTimeInMs();
  heap->tracer()->SampleAllocation(time_ms, heap->NewSpaceAllocationCounter(),
                                   heap->OldGenerationAllocationCounter());
43 44 45
  bool low_allocation_rate = heap->HasLowAllocationRate();
  bool optimize_for_memory = heap->ShouldOptimizeForMemoryUsage();
  if (FLAG_trace_gc_verbose) {
46
    heap->isolate()->PrintWithTimestamp(
47
        "Memory reducer: %s, %s\n",
48 49
        low_allocation_rate ? "low alloc" : "high alloc",
        optimize_for_memory ? "background" : "foreground");
50
  }
51
  event.type = kTimer;
52
  event.time_ms = time_ms;
53 54 55
  // The memory reducer will start incremental markig if
  // 1) mutator is likely idle: js call rate is low and allocation rate is low.
  // 2) mutator is in background: optimize for memory flag is set.
56 57
  event.should_start_incremental_gc =
      low_allocation_rate || optimize_for_memory;
58 59
  event.can_start_incremental_gc =
      heap->incremental_marking()->IsStopped() &&
60
      (heap->incremental_marking()->CanBeActivated() || optimize_for_memory);
61
  event.committed_memory = heap->CommittedOldGenerationMemory();
62 63 64 65 66 67 68 69 70 71 72 73
  memory_reducer_->NotifyTimer(event);
}


void MemoryReducer::NotifyTimer(const Event& event) {
  DCHECK_EQ(kTimer, event.type);
  DCHECK_EQ(kWait, state_.action);
  state_ = Step(state_, event);
  if (state_.action == kRun) {
    DCHECK(heap()->incremental_marking()->IsStopped());
    DCHECK(FLAG_incremental_marking);
    if (FLAG_trace_gc_verbose) {
74 75
      heap()->isolate()->PrintWithTimestamp("Memory reducer: started GC #%d\n",
                                            state_.started_gcs);
76
    }
77
    heap()->StartIdleIncrementalMarking(
78 79
        GarbageCollectionReason::kMemoryReducer,
        kGCCallbackFlagCollectAllExternalMemory);
80
  } else if (state_.action == kWait) {
81 82 83 84 85 86 87 88
    if (!heap()->incremental_marking()->IsStopped() &&
        heap()->ShouldOptimizeForMemoryUsage()) {
      // Make progress with pending incremental marking if memory usage has
      // higher priority than latency. This is important for background tabs
      // that do not send idle notifications.
      const int kIncrementalMarkingDelayMs = 500;
      double deadline = heap()->MonotonicallyIncreasingTimeInMs() +
                        kIncrementalMarkingDelayMs;
89
      heap()->incremental_marking()->AdvanceWithDeadline(
90
          deadline, IncrementalMarking::NO_GC_VIA_STACK_GUARD,
91
          StepOrigin::kTask);
92
      heap()->FinalizeIncrementalMarkingIfComplete(
93
          GarbageCollectionReason::kFinalizeMarkingViaTask);
94
    }
95
    // Re-schedule the timer.
96
    ScheduleTimer(state_.next_gc_start_ms - event.time_ms);
97
    if (FLAG_trace_gc_verbose) {
98 99 100
      heap()->isolate()->PrintWithTimestamp(
          "Memory reducer: waiting for %.f ms\n",
          state_.next_gc_start_ms - event.time_ms);
101 102 103 104 105 106 107 108 109 110 111
    }
  }
}


void MemoryReducer::NotifyMarkCompact(const Event& event) {
  DCHECK_EQ(kMarkCompact, event.type);
  Action old_action = state_.action;
  state_ = Step(state_, event);
  if (old_action != kWait && state_.action == kWait) {
    // If we are transitioning to the WAIT state, start the timer.
112
    ScheduleTimer(state_.next_gc_start_ms - event.time_ms);
113 114 115
  }
  if (old_action == kRun) {
    if (FLAG_trace_gc_verbose) {
116 117 118
      heap()->isolate()->PrintWithTimestamp(
          "Memory reducer: finished GC #%d (%s)\n", state_.started_gcs,
          state_.action == kWait ? "will do more" : "done");
119 120 121 122
    }
  }
}

123 124
void MemoryReducer::NotifyPossibleGarbage(const Event& event) {
  DCHECK_EQ(kPossibleGarbage, event.type);
125 126 127 128
  Action old_action = state_.action;
  state_ = Step(state_, event);
  if (old_action != kWait && state_.action == kWait) {
    // If we are transitioning to the WAIT state, start the timer.
129
    ScheduleTimer(state_.next_gc_start_ms - event.time_ms);
130 131 132 133
  }
}


134 135 136 137 138 139
bool MemoryReducer::WatchdogGC(const State& state, const Event& event) {
  return state.last_gc_time_ms != 0 &&
         event.time_ms > state.last_gc_time_ms + kWatchdogDelayMs;
}


140 141 142
// For specification of this function see the comment for MemoryReducer class.
MemoryReducer::State MemoryReducer::Step(const State& state,
                                         const Event& event) {
ulan's avatar
ulan committed
143
  if (!FLAG_incremental_marking || !FLAG_memory_reducer) {
144
    return State(kDone, 0, 0, state.last_gc_time_ms, 0);
145 146 147
  }
  switch (state.action) {
    case kDone:
148
      if (event.type == kTimer) {
149
        return state;
150 151 152 153 154 155 156 157 158 159 160 161
      } else if (event.type == kMarkCompact) {
        if (event.committed_memory <
            Max(static_cast<size_t>(state.committed_memory_at_last_run *
                                    kCommittedMemoryFactor),
                state.committed_memory_at_last_run + kCommittedMemoryDelta)) {
          return state;
        } else {
          return State(kWait, 0, event.time_ms + kLongDelayMs,
                       event.type == kMarkCompact ? event.time_ms
                                                  : state.last_gc_time_ms,
                       0);
        }
162
      } else {
163
        DCHECK_EQ(kPossibleGarbage, event.type);
164 165
        return State(
            kWait, 0, event.time_ms + kLongDelayMs,
166 167
            event.type == kMarkCompact ? event.time_ms : state.last_gc_time_ms,
            0);
168 169
      }
    case kWait:
170
      switch (event.type) {
171
        case kPossibleGarbage:
172
          return state;
173 174
        case kTimer:
          if (state.started_gcs >= kMaxNumberOfGCs) {
175 176
            return State(kDone, kMaxNumberOfGCs, 0.0, state.last_gc_time_ms,
                         event.committed_memory);
177
          } else if (event.can_start_incremental_gc &&
178 179
                     (event.should_start_incremental_gc ||
                      WatchdogGC(state, event))) {
180
            if (state.next_gc_start_ms <= event.time_ms) {
181
              return State(kRun, state.started_gcs + 1, 0.0,
182
                           state.last_gc_time_ms, 0);
183 184 185 186
            } else {
              return state;
            }
          } else {
187
            return State(kWait, state.started_gcs, event.time_ms + kLongDelayMs,
188
                         state.last_gc_time_ms, 0);
189 190
          }
        case kMarkCompact:
191
          return State(kWait, state.started_gcs, event.time_ms + kLongDelayMs,
192
                       event.time_ms, 0);
193 194 195 196 197 198 199
      }
    case kRun:
      if (event.type != kMarkCompact) {
        return state;
      } else {
        if (state.started_gcs < kMaxNumberOfGCs &&
            (event.next_gc_likely_to_collect_more || state.started_gcs == 1)) {
200
          return State(kWait, state.started_gcs, event.time_ms + kShortDelayMs,
201
                       event.time_ms, 0);
202
        } else {
203 204
          return State(kDone, kMaxNumberOfGCs, 0.0, event.time_ms,
                       event.committed_memory);
205 206 207 208 209 210
        }
      }
  }
  UNREACHABLE();
}

211
void MemoryReducer::ScheduleTimer(double delay_ms) {
212
  DCHECK_LT(0, delay_ms);
213
  if (heap()->IsTearingDown()) return;
214 215
  // Leave some room for precision error in task scheduler.
  const double kSlackMs = 100;
216 217 218
  taskrunner_->PostDelayedTask(
      base::make_unique<MemoryReducer::TimerTask>(this),
      (delay_ms + kSlackMs) / 1000.0);
219 220
}

221
void MemoryReducer::TearDown() { state_ = State(kDone, 0, 0, 0.0, 0); }
222

223 224
}  // namespace internal
}  // namespace v8