Merge Chromium + Blink git repositories
[chromium-blink-merge.git] / content / common / gpu / gpu_memory_manager.cc
blob6cae8e032579d4e0f93b576504dec56a3107f4c5
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "content/common/gpu/gpu_memory_manager.h"
7 #include <algorithm>
9 #include "base/bind.h"
10 #include "base/command_line.h"
11 #include "base/message_loop/message_loop.h"
12 #include "base/process/process_handle.h"
13 #include "base/strings/string_number_conversions.h"
14 #include "base/trace_event/trace_event.h"
15 #include "content/common/gpu/gpu_channel_manager.h"
16 #include "content/common/gpu/gpu_memory_manager_client.h"
17 #include "content/common/gpu/gpu_memory_tracking.h"
18 #include "content/common/gpu/gpu_memory_uma_stats.h"
19 #include "content/common/gpu/gpu_messages.h"
20 #include "gpu/command_buffer/common/gpu_memory_allocation.h"
21 #include "gpu/command_buffer/service/gpu_switches.h"
23 using gpu::MemoryAllocation;
25 namespace content {
26 namespace {
28 const int kDelayedScheduleManageTimeoutMs = 67;
30 const uint64 kBytesAllocatedUnmanagedStep = 16 * 1024 * 1024;
32 void TrackValueChanged(uint64 old_size, uint64 new_size, uint64* total_size) {
33 DCHECK(new_size > old_size || *total_size >= (old_size - new_size));
34 *total_size += (new_size - old_size);
39 GpuMemoryManager::GpuMemoryManager(
40 GpuChannelManager* channel_manager,
41 uint64 max_surfaces_with_frontbuffer_soft_limit)
42 : channel_manager_(channel_manager),
43 manage_immediate_scheduled_(false),
44 disable_schedule_manage_(false),
45 max_surfaces_with_frontbuffer_soft_limit_(
46 max_surfaces_with_frontbuffer_soft_limit),
47 client_hard_limit_bytes_(0),
48 bytes_allocated_managed_current_(0),
49 bytes_allocated_unmanaged_current_(0),
50 bytes_allocated_historical_max_(0)
51 { }
53 GpuMemoryManager::~GpuMemoryManager() {
54 DCHECK(tracking_groups_.empty());
55 DCHECK(clients_visible_mru_.empty());
56 DCHECK(clients_nonvisible_mru_.empty());
57 DCHECK(clients_nonsurface_.empty());
58 DCHECK(!bytes_allocated_managed_current_);
59 DCHECK(!bytes_allocated_unmanaged_current_);
62 void GpuMemoryManager::UpdateAvailableGpuMemory() {
63 // If the value was overridden on the command line, use the specified value.
64 static bool client_hard_limit_bytes_overridden =
65 base::CommandLine::ForCurrentProcess()->HasSwitch(
66 switches::kForceGpuMemAvailableMb);
67 if (client_hard_limit_bytes_overridden) {
68 base::StringToUint64(
69 base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
70 switches::kForceGpuMemAvailableMb),
71 &client_hard_limit_bytes_);
72 client_hard_limit_bytes_ *= 1024 * 1024;
73 return;
76 #if defined(OS_ANDROID)
77 // On non-Android, we use an operating system query when possible.
78 // We do not have a reliable concept of multiple GPUs existing in
79 // a system, so just be safe and go with the minimum encountered.
80 uint64 bytes_min = 0;
82 // Only use the clients that are visible, because otherwise the set of clients
83 // we are querying could become extremely large.
84 for (ClientStateList::const_iterator it = clients_visible_mru_.begin();
85 it != clients_visible_mru_.end();
86 ++it) {
87 const GpuMemoryManagerClientState* client_state = *it;
88 if (!client_state->has_surface_)
89 continue;
90 if (!client_state->visible_)
91 continue;
93 uint64 bytes = 0;
94 if (client_state->client_->GetTotalGpuMemory(&bytes)) {
95 if (!bytes_min || bytes < bytes_min)
96 bytes_min = bytes;
100 client_hard_limit_bytes_ = bytes_min;
101 // Clamp the observed value to a specific range on Android.
102 client_hard_limit_bytes_ = std::max(client_hard_limit_bytes_,
103 static_cast<uint64>(8 * 1024 * 1024));
104 client_hard_limit_bytes_ = std::min(client_hard_limit_bytes_,
105 static_cast<uint64>(256 * 1024 * 1024));
106 #else
107 // Ignore what the system said and give all clients the same maximum
108 // allocation on desktop platforms.
109 client_hard_limit_bytes_ = 512 * 1024 * 1024;
110 #endif
113 void GpuMemoryManager::ScheduleManage(
114 ScheduleManageTime schedule_manage_time) {
115 if (disable_schedule_manage_)
116 return;
117 if (manage_immediate_scheduled_)
118 return;
119 if (schedule_manage_time == kScheduleManageNow) {
120 base::ThreadTaskRunnerHandle::Get()->PostTask(
121 FROM_HERE, base::Bind(&GpuMemoryManager::Manage, AsWeakPtr()));
122 manage_immediate_scheduled_ = true;
123 if (!delayed_manage_callback_.IsCancelled())
124 delayed_manage_callback_.Cancel();
125 } else {
126 if (!delayed_manage_callback_.IsCancelled())
127 return;
128 delayed_manage_callback_.Reset(base::Bind(&GpuMemoryManager::Manage,
129 AsWeakPtr()));
130 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
131 FROM_HERE, delayed_manage_callback_.callback(),
132 base::TimeDelta::FromMilliseconds(kDelayedScheduleManageTimeoutMs));
136 void GpuMemoryManager::TrackMemoryAllocatedChange(
137 GpuMemoryTrackingGroup* tracking_group,
138 uint64 old_size,
139 uint64 new_size,
140 gpu::gles2::MemoryTracker::Pool tracking_pool) {
141 TrackValueChanged(old_size, new_size, &tracking_group->size_);
142 switch (tracking_pool) {
143 case gpu::gles2::MemoryTracker::kManaged:
144 TrackValueChanged(old_size, new_size, &bytes_allocated_managed_current_);
145 break;
146 case gpu::gles2::MemoryTracker::kUnmanaged:
147 TrackValueChanged(old_size,
148 new_size,
149 &bytes_allocated_unmanaged_current_);
150 break;
151 default:
152 NOTREACHED();
153 break;
156 if (GetCurrentUsage() > bytes_allocated_historical_max_ +
157 kBytesAllocatedUnmanagedStep) {
158 bytes_allocated_historical_max_ = GetCurrentUsage();
159 // If we're blowing into new memory usage territory, spam the browser
160 // process with the most up-to-date information about our memory usage.
161 SendUmaStatsToBrowser();
165 bool GpuMemoryManager::EnsureGPUMemoryAvailable(uint64 /* size_needed */) {
166 // TODO: Check if there is enough space. Lose contexts until there is.
167 return true;
170 GpuMemoryManagerClientState* GpuMemoryManager::CreateClientState(
171 GpuMemoryManagerClient* client,
172 bool has_surface,
173 bool visible) {
174 TrackingGroupMap::iterator tracking_group_it =
175 tracking_groups_.find(client->GetMemoryTracker());
176 DCHECK(tracking_group_it != tracking_groups_.end());
177 GpuMemoryTrackingGroup* tracking_group = tracking_group_it->second;
179 GpuMemoryManagerClientState* client_state = new GpuMemoryManagerClientState(
180 this, client, tracking_group, has_surface, visible);
181 AddClientToList(client_state);
182 ScheduleManage(kScheduleManageNow);
183 return client_state;
186 void GpuMemoryManager::OnDestroyClientState(
187 GpuMemoryManagerClientState* client_state) {
188 RemoveClientFromList(client_state);
189 ScheduleManage(kScheduleManageLater);
192 void GpuMemoryManager::SetClientStateVisible(
193 GpuMemoryManagerClientState* client_state, bool visible) {
194 DCHECK(client_state->has_surface_);
195 if (client_state->visible_ == visible)
196 return;
198 RemoveClientFromList(client_state);
199 client_state->visible_ = visible;
200 AddClientToList(client_state);
201 ScheduleManage(visible ? kScheduleManageNow : kScheduleManageLater);
204 uint64 GpuMemoryManager::GetTrackerMemoryUsage(
205 gpu::gles2::MemoryTracker* tracker) const {
206 TrackingGroupMap::const_iterator tracking_group_it =
207 tracking_groups_.find(tracker);
208 DCHECK(tracking_group_it != tracking_groups_.end());
209 return tracking_group_it->second->GetSize();
212 GpuMemoryTrackingGroup* GpuMemoryManager::CreateTrackingGroup(
213 base::ProcessId pid, gpu::gles2::MemoryTracker* memory_tracker) {
214 GpuMemoryTrackingGroup* tracking_group = new GpuMemoryTrackingGroup(
215 pid, memory_tracker, this);
216 DCHECK(!tracking_groups_.count(tracking_group->GetMemoryTracker()));
217 tracking_groups_.insert(std::make_pair(tracking_group->GetMemoryTracker(),
218 tracking_group));
219 return tracking_group;
222 void GpuMemoryManager::OnDestroyTrackingGroup(
223 GpuMemoryTrackingGroup* tracking_group) {
224 DCHECK(tracking_groups_.count(tracking_group->GetMemoryTracker()));
225 tracking_groups_.erase(tracking_group->GetMemoryTracker());
228 void GpuMemoryManager::GetVideoMemoryUsageStats(
229 GPUVideoMemoryUsageStats* video_memory_usage_stats) const {
230 // For each context group, assign its memory usage to its PID
231 video_memory_usage_stats->process_map.clear();
232 for (TrackingGroupMap::const_iterator i =
233 tracking_groups_.begin(); i != tracking_groups_.end(); ++i) {
234 const GpuMemoryTrackingGroup* tracking_group = i->second;
235 video_memory_usage_stats->process_map[
236 tracking_group->GetPid()].video_memory += tracking_group->GetSize();
239 // Assign the total across all processes in the GPU process
240 video_memory_usage_stats->process_map[
241 base::GetCurrentProcId()].video_memory = GetCurrentUsage();
242 video_memory_usage_stats->process_map[
243 base::GetCurrentProcId()].has_duplicates = true;
245 video_memory_usage_stats->bytes_allocated = GetCurrentUsage();
246 video_memory_usage_stats->bytes_allocated_historical_max =
247 bytes_allocated_historical_max_;
250 void GpuMemoryManager::Manage() {
251 manage_immediate_scheduled_ = false;
252 delayed_manage_callback_.Cancel();
254 // Update the amount of GPU memory available on the system.
255 UpdateAvailableGpuMemory();
257 // Determine which clients are "hibernated" (which determines the
258 // distribution of frontbuffers and memory among clients that don't have
259 // surfaces).
260 SetClientsHibernatedState();
262 // Assign memory allocations to clients that have surfaces.
263 AssignSurfacesAllocations();
265 // Assign memory allocations to clients that don't have surfaces.
266 AssignNonSurfacesAllocations();
268 SendUmaStatsToBrowser();
271 void GpuMemoryManager::AssignSurfacesAllocations() {
272 // Send that allocation to the clients.
273 ClientStateList clients = clients_visible_mru_;
274 clients.insert(clients.end(),
275 clients_nonvisible_mru_.begin(),
276 clients_nonvisible_mru_.end());
277 for (ClientStateList::const_iterator it = clients.begin();
278 it != clients.end();
279 ++it) {
280 GpuMemoryManagerClientState* client_state = *it;
282 // Populate and send the allocation to the client
283 MemoryAllocation allocation;
284 allocation.bytes_limit_when_visible = client_hard_limit_bytes_;
285 #if defined(OS_ANDROID)
286 // On Android, because there is only one visible tab at any time, allow
287 // that renderer to cache as much as it can.
288 allocation.priority_cutoff_when_visible =
289 MemoryAllocation::CUTOFF_ALLOW_EVERYTHING;
290 #else
291 // On desktop platforms, instruct the renderers to cache only a smaller
292 // set, to play nice with other renderers and other applications. If this
293 // if not done, then the system can become unstable.
294 // http://crbug.com/145600 (Linux)
295 // http://crbug.com/141377 (Mac)
296 allocation.priority_cutoff_when_visible =
297 MemoryAllocation::CUTOFF_ALLOW_NICE_TO_HAVE;
298 #endif
300 client_state->client_->SetMemoryAllocation(allocation);
301 client_state->client_->SuggestHaveFrontBuffer(!client_state->hibernated_);
305 void GpuMemoryManager::AssignNonSurfacesAllocations() {
306 for (ClientStateList::const_iterator it = clients_nonsurface_.begin();
307 it != clients_nonsurface_.end();
308 ++it) {
309 GpuMemoryManagerClientState* client_state = *it;
310 MemoryAllocation allocation;
312 if (!client_state->hibernated_) {
313 allocation.bytes_limit_when_visible = client_hard_limit_bytes_;
314 allocation.priority_cutoff_when_visible =
315 MemoryAllocation::CUTOFF_ALLOW_EVERYTHING;
318 client_state->client_->SetMemoryAllocation(allocation);
322 void GpuMemoryManager::SetClientsHibernatedState() const {
323 // Re-set all tracking groups as being hibernated.
324 for (TrackingGroupMap::const_iterator it = tracking_groups_.begin();
325 it != tracking_groups_.end();
326 ++it) {
327 GpuMemoryTrackingGroup* tracking_group = it->second;
328 tracking_group->hibernated_ = true;
330 // All clients with surfaces that are visible are non-hibernated.
331 uint64 non_hibernated_clients = 0;
332 for (ClientStateList::const_iterator it = clients_visible_mru_.begin();
333 it != clients_visible_mru_.end();
334 ++it) {
335 GpuMemoryManagerClientState* client_state = *it;
336 client_state->hibernated_ = false;
337 client_state->tracking_group_->hibernated_ = false;
338 non_hibernated_clients++;
340 // Then an additional few clients with surfaces are non-hibernated too, up to
341 // a fixed limit.
342 for (ClientStateList::const_iterator it = clients_nonvisible_mru_.begin();
343 it != clients_nonvisible_mru_.end();
344 ++it) {
345 GpuMemoryManagerClientState* client_state = *it;
346 if (non_hibernated_clients < max_surfaces_with_frontbuffer_soft_limit_) {
347 client_state->hibernated_ = false;
348 client_state->tracking_group_->hibernated_ = false;
349 non_hibernated_clients++;
350 } else {
351 client_state->hibernated_ = true;
354 // Clients that don't have surfaces are non-hibernated if they are
355 // in a GL share group with a non-hibernated surface.
356 for (ClientStateList::const_iterator it = clients_nonsurface_.begin();
357 it != clients_nonsurface_.end();
358 ++it) {
359 GpuMemoryManagerClientState* client_state = *it;
360 client_state->hibernated_ = client_state->tracking_group_->hibernated_;
364 void GpuMemoryManager::SendUmaStatsToBrowser() {
365 if (!channel_manager_)
366 return;
367 GPUMemoryUmaStats params;
368 params.bytes_allocated_current = GetCurrentUsage();
369 params.bytes_allocated_max = bytes_allocated_historical_max_;
370 params.bytes_limit = client_hard_limit_bytes_;
371 params.client_count = clients_visible_mru_.size() +
372 clients_nonvisible_mru_.size() +
373 clients_nonsurface_.size();
374 params.context_group_count = tracking_groups_.size();
375 channel_manager_->Send(new GpuHostMsg_GpuMemoryUmaStats(params));
378 GpuMemoryManager::ClientStateList* GpuMemoryManager::GetClientList(
379 GpuMemoryManagerClientState* client_state) {
380 if (client_state->has_surface_) {
381 if (client_state->visible_)
382 return &clients_visible_mru_;
383 else
384 return &clients_nonvisible_mru_;
386 return &clients_nonsurface_;
389 void GpuMemoryManager::AddClientToList(
390 GpuMemoryManagerClientState* client_state) {
391 DCHECK(!client_state->list_iterator_valid_);
392 ClientStateList* client_list = GetClientList(client_state);
393 client_state->list_iterator_ = client_list->insert(
394 client_list->begin(), client_state);
395 client_state->list_iterator_valid_ = true;
398 void GpuMemoryManager::RemoveClientFromList(
399 GpuMemoryManagerClientState* client_state) {
400 DCHECK(client_state->list_iterator_valid_);
401 ClientStateList* client_list = GetClientList(client_state);
402 client_list->erase(client_state->list_iterator_);
403 client_state->list_iterator_valid_ = false;
406 } // namespace content