memory-reducer.cc 8.16 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 11 12 13 14 15
#include "src/utils.h"
#include "src/v8.h"

namespace v8 {
namespace internal {

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

23 24 25
MemoryReducer::TimerTask::TimerTask(MemoryReducer* memory_reducer)
    : CancelableTask(memory_reducer->heap()->isolate()),
      memory_reducer_(memory_reducer) {}
26

27 28

void MemoryReducer::TimerTask::RunInternal() {
29 30
  Heap* heap = memory_reducer_->heap();
  Event event;
31 32 33
  double time_ms = heap->MonotonicallyIncreasingTimeInMs();
  heap->tracer()->SampleAllocation(time_ms, heap->NewSpaceAllocationCounter(),
                                   heap->OldGenerationAllocationCounter());
34 35 36
  bool low_allocation_rate = heap->HasLowAllocationRate();
  bool optimize_for_memory = heap->ShouldOptimizeForMemoryUsage();
  if (FLAG_trace_gc_verbose) {
37
    heap->isolate()->PrintWithTimestamp(
38
        "Memory reducer: %s, %s\n",
39 40
        low_allocation_rate ? "low alloc" : "high alloc",
        optimize_for_memory ? "background" : "foreground");
41
  }
42
  event.type = kTimer;
43
  event.time_ms = time_ms;
44 45 46
  // 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.
47 48
  event.should_start_incremental_gc =
      low_allocation_rate || optimize_for_memory;
49 50
  event.can_start_incremental_gc =
      heap->incremental_marking()->IsStopped() &&
51
      (heap->incremental_marking()->CanBeActivated() || optimize_for_memory);
52
  event.committed_memory = heap->CommittedOldGenerationMemory();
53 54 55 56 57 58 59 60 61 62 63 64
  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) {
65 66
      heap()->isolate()->PrintWithTimestamp("Memory reducer: started GC #%d\n",
                                            state_.started_gcs);
67
    }
68
    heap()->StartIdleIncrementalMarking(
69 70
        GarbageCollectionReason::kMemoryReducer,
        kGCCallbackFlagCollectAllExternalMemory);
71
  } else if (state_.action == kWait) {
72 73 74 75 76 77 78 79
    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;
80
      heap()->incremental_marking()->AdvanceIncrementalMarking(
81
          deadline, IncrementalMarking::NO_GC_VIA_STACK_GUARD,
82
          StepOrigin::kTask);
83
      heap()->FinalizeIncrementalMarkingIfComplete(
84
          GarbageCollectionReason::kFinalizeMarkingViaTask);
85
    }
86
    // Re-schedule the timer.
87
    ScheduleTimer(event.time_ms, state_.next_gc_start_ms - event.time_ms);
88
    if (FLAG_trace_gc_verbose) {
89 90 91
      heap()->isolate()->PrintWithTimestamp(
          "Memory reducer: waiting for %.f ms\n",
          state_.next_gc_start_ms - event.time_ms);
92 93 94 95 96 97 98 99 100 101 102
    }
  }
}


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.
103
    ScheduleTimer(event.time_ms, state_.next_gc_start_ms - event.time_ms);
104 105 106
  }
  if (old_action == kRun) {
    if (FLAG_trace_gc_verbose) {
107 108 109
      heap()->isolate()->PrintWithTimestamp(
          "Memory reducer: finished GC #%d (%s)\n", state_.started_gcs,
          state_.action == kWait ? "will do more" : "done");
110 111 112 113
    }
  }
}

114 115
void MemoryReducer::NotifyPossibleGarbage(const Event& event) {
  DCHECK_EQ(kPossibleGarbage, event.type);
116 117 118 119
  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.
120
    ScheduleTimer(event.time_ms, state_.next_gc_start_ms - event.time_ms);
121 122 123 124
  }
}


125 126 127 128 129 130
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;
}


131 132 133
// 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
134
  if (!FLAG_incremental_marking || !FLAG_memory_reducer) {
135
    return State(kDone, 0, 0, state.last_gc_time_ms, 0);
136 137 138
  }
  switch (state.action) {
    case kDone:
139
      if (event.type == kTimer) {
140
        return state;
141 142 143 144 145 146 147 148 149 150 151 152
      } 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);
        }
153
      } else {
154
        DCHECK_EQ(kPossibleGarbage, event.type);
155 156
        return State(
            kWait, 0, event.time_ms + kLongDelayMs,
157 158
            event.type == kMarkCompact ? event.time_ms : state.last_gc_time_ms,
            0);
159 160
      }
    case kWait:
161
      switch (event.type) {
162
        case kPossibleGarbage:
163
          return state;
164 165
        case kTimer:
          if (state.started_gcs >= kMaxNumberOfGCs) {
166 167
            return State(kDone, kMaxNumberOfGCs, 0.0, state.last_gc_time_ms,
                         event.committed_memory);
168
          } else if (event.can_start_incremental_gc &&
169 170
                     (event.should_start_incremental_gc ||
                      WatchdogGC(state, event))) {
171
            if (state.next_gc_start_ms <= event.time_ms) {
172
              return State(kRun, state.started_gcs + 1, 0.0,
173
                           state.last_gc_time_ms, 0);
174 175 176 177
            } else {
              return state;
            }
          } else {
178
            return State(kWait, state.started_gcs, event.time_ms + kLongDelayMs,
179
                         state.last_gc_time_ms, 0);
180 181
          }
        case kMarkCompact:
182
          return State(kWait, state.started_gcs, event.time_ms + kLongDelayMs,
183
                       event.time_ms, 0);
184 185 186 187 188 189 190
      }
    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)) {
191
          return State(kWait, state.started_gcs, event.time_ms + kShortDelayMs,
192
                       event.time_ms, 0);
193
        } else {
194 195
          return State(kDone, kMaxNumberOfGCs, 0.0, event.time_ms,
                       event.committed_memory);
196 197 198 199 200 201 202
        }
      }
  }
  UNREACHABLE();
}


203
void MemoryReducer::ScheduleTimer(double time_ms, double delay_ms) {
204
  DCHECK_LT(0, delay_ms);
205 206 207
  // Leave some room for precision error in task scheduler.
  const double kSlackMs = 100;
  v8::Isolate* isolate = reinterpret_cast<v8::Isolate*>(heap()->isolate());
208
  auto timer_task = new MemoryReducer::TimerTask(this);
209
  V8::GetCurrentPlatform()->CallDelayedOnForegroundThread(
210
      isolate, timer_task, (delay_ms + kSlackMs) / 1000.0);
211 212
}

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

215 216
}  // namespace internal
}  // namespace v8