Update V8 to version 4.7.24.
[chromium-blink-merge.git] / cc / raster / one_copy_tile_task_worker_pool.cc
blobb2f8c11309d118863c4e384f951a9ed8eb486899
1 // Copyright 2014 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 "cc/raster/one_copy_tile_task_worker_pool.h"
7 #include <algorithm>
8 #include <limits>
10 #include "base/strings/stringprintf.h"
11 #include "base/thread_task_runner_handle.h"
12 #include "base/trace_event/memory_dump_manager.h"
13 #include "base/trace_event/trace_event.h"
14 #include "base/trace_event/trace_event_argument.h"
15 #include "cc/base/math_util.h"
16 #include "cc/debug/traced_value.h"
17 #include "cc/raster/raster_buffer.h"
18 #include "cc/resources/platform_color.h"
19 #include "cc/resources/resource_format.h"
20 #include "cc/resources/resource_util.h"
21 #include "cc/resources/scoped_resource.h"
22 #include "gpu/GLES2/gl2extchromium.h"
23 #include "gpu/command_buffer/client/gles2_interface.h"
24 #include "gpu/command_buffer/client/gpu_memory_buffer_manager.h"
25 #include "ui/gfx/buffer_format_util.h"
27 namespace cc {
28 namespace {
30 class RasterBufferImpl : public RasterBuffer {
31 public:
32 RasterBufferImpl(OneCopyTileTaskWorkerPool* worker_pool,
33 ResourceProvider* resource_provider,
34 ResourceFormat resource_format,
35 const Resource* resource,
36 uint64_t previous_content_id)
37 : worker_pool_(worker_pool),
38 resource_(resource),
39 lock_(resource_provider, resource->id()),
40 previous_content_id_(previous_content_id) {}
42 ~RasterBufferImpl() override {}
44 // Overridden from RasterBuffer:
45 void Playback(const RasterSource* raster_source,
46 const gfx::Rect& raster_full_rect,
47 const gfx::Rect& raster_dirty_rect,
48 uint64_t new_content_id,
49 float scale,
50 bool include_images) override {
51 worker_pool_->PlaybackAndCopyOnWorkerThread(
52 resource_, &lock_, raster_source, raster_full_rect, raster_dirty_rect,
53 scale, include_images, previous_content_id_, new_content_id);
56 private:
57 OneCopyTileTaskWorkerPool* worker_pool_;
58 const Resource* resource_;
59 ResourceProvider::ScopedWriteLockGL lock_;
60 uint64_t previous_content_id_;
62 DISALLOW_COPY_AND_ASSIGN(RasterBufferImpl);
65 // Delay between checking for query result to be available.
66 const int kCheckForQueryResultAvailableTickRateMs = 1;
68 // Number of attempts to allow before we perform a check that will wait for
69 // query to complete.
70 const int kMaxCheckForQueryResultAvailableAttempts = 256;
72 // 4MiB is the size of 4 512x512 tiles, which has proven to be a good
73 // default batch size for copy operations.
74 const int kMaxBytesPerCopyOperation = 1024 * 1024 * 4;
76 // Delay before a staging buffer might be released.
77 const int kStagingBufferExpirationDelayMs = 1000;
79 bool CheckForQueryResult(gpu::gles2::GLES2Interface* gl, unsigned query_id) {
80 unsigned complete = 1;
81 gl->GetQueryObjectuivEXT(query_id, GL_QUERY_RESULT_AVAILABLE_EXT, &complete);
82 return !!complete;
85 void WaitForQueryResult(gpu::gles2::GLES2Interface* gl, unsigned query_id) {
86 TRACE_EVENT0("cc", "WaitForQueryResult");
88 int attempts_left = kMaxCheckForQueryResultAvailableAttempts;
89 while (attempts_left--) {
90 if (CheckForQueryResult(gl, query_id))
91 break;
93 base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(
94 kCheckForQueryResultAvailableTickRateMs));
97 unsigned result = 0;
98 gl->GetQueryObjectuivEXT(query_id, GL_QUERY_RESULT_EXT, &result);
101 } // namespace
103 OneCopyTileTaskWorkerPool::StagingBuffer::StagingBuffer(const gfx::Size& size)
104 : size(size), texture_id(0), image_id(0), query_id(0), content_id(0) {}
106 OneCopyTileTaskWorkerPool::StagingBuffer::~StagingBuffer() {
107 DCHECK_EQ(texture_id, 0u);
108 DCHECK_EQ(image_id, 0u);
109 DCHECK_EQ(query_id, 0u);
112 void OneCopyTileTaskWorkerPool::StagingBuffer::DestroyGLResources(
113 gpu::gles2::GLES2Interface* gl) {
114 if (query_id) {
115 gl->DeleteQueriesEXT(1, &query_id);
116 query_id = 0;
118 if (image_id) {
119 gl->DestroyImageCHROMIUM(image_id);
120 image_id = 0;
122 if (texture_id) {
123 gl->DeleteTextures(1, &texture_id);
124 texture_id = 0;
128 void OneCopyTileTaskWorkerPool::StagingBuffer::OnMemoryDump(
129 base::trace_event::ProcessMemoryDump* pmd,
130 ResourceFormat format,
131 bool in_free_list) const {
132 if (!gpu_memory_buffer)
133 return;
135 gfx::GpuMemoryBufferId buffer_id = gpu_memory_buffer->GetId();
136 std::string buffer_dump_name =
137 base::StringPrintf("cc/one_copy/staging_memory/buffer_%d", buffer_id.id);
138 base::trace_event::MemoryAllocatorDump* buffer_dump =
139 pmd->CreateAllocatorDump(buffer_dump_name);
141 uint64_t buffer_size_in_bytes =
142 ResourceUtil::UncheckedSizeInBytes<uint64_t>(size, format);
143 buffer_dump->AddScalar(base::trace_event::MemoryAllocatorDump::kNameSize,
144 base::trace_event::MemoryAllocatorDump::kUnitsBytes,
145 buffer_size_in_bytes);
146 buffer_dump->AddScalar("free_size",
147 base::trace_event::MemoryAllocatorDump::kUnitsBytes,
148 in_free_list ? buffer_size_in_bytes : 0);
150 // Emit an ownership edge towards a global allocator dump node.
151 const uint64 tracing_process_id =
152 base::trace_event::MemoryDumpManager::GetInstance()
153 ->GetTracingProcessId();
154 base::trace_event::MemoryAllocatorDumpGuid shared_buffer_guid =
155 gfx::GetGpuMemoryBufferGUIDForTracing(tracing_process_id, buffer_id);
156 pmd->CreateSharedGlobalAllocatorDump(shared_buffer_guid);
158 // By creating an edge with a higher |importance| (w.r.t. browser-side dumps)
159 // the tracing UI will account the effective size of the buffer to the child.
160 const int kImportance = 2;
161 pmd->AddOwnershipEdge(buffer_dump->guid(), shared_buffer_guid, kImportance);
164 // static
165 scoped_ptr<TileTaskWorkerPool> OneCopyTileTaskWorkerPool::Create(
166 base::SequencedTaskRunner* task_runner,
167 TaskGraphRunner* task_graph_runner,
168 ContextProvider* context_provider,
169 ResourceProvider* resource_provider,
170 int max_copy_texture_chromium_size,
171 bool use_persistent_gpu_memory_buffers,
172 int max_staging_buffers) {
173 return make_scoped_ptr<TileTaskWorkerPool>(new OneCopyTileTaskWorkerPool(
174 task_runner, task_graph_runner, resource_provider,
175 max_copy_texture_chromium_size, use_persistent_gpu_memory_buffers,
176 max_staging_buffers));
179 OneCopyTileTaskWorkerPool::OneCopyTileTaskWorkerPool(
180 base::SequencedTaskRunner* task_runner,
181 TaskGraphRunner* task_graph_runner,
182 ResourceProvider* resource_provider,
183 int max_copy_texture_chromium_size,
184 bool use_persistent_gpu_memory_buffers,
185 int max_staging_buffers)
186 : task_runner_(task_runner),
187 task_graph_runner_(task_graph_runner),
188 namespace_token_(task_graph_runner->GetNamespaceToken()),
189 resource_provider_(resource_provider),
190 max_bytes_per_copy_operation_(
191 max_copy_texture_chromium_size
192 ? std::min(kMaxBytesPerCopyOperation,
193 max_copy_texture_chromium_size)
194 : kMaxBytesPerCopyOperation),
195 use_persistent_gpu_memory_buffers_(use_persistent_gpu_memory_buffers),
196 bytes_scheduled_since_last_flush_(0),
197 max_staging_buffers_(max_staging_buffers),
198 staging_buffer_expiration_delay_(
199 base::TimeDelta::FromMilliseconds(kStagingBufferExpirationDelayMs)),
200 reduce_memory_usage_pending_(false),
201 weak_ptr_factory_(this),
202 task_set_finished_weak_ptr_factory_(this) {
203 base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
204 this, base::ThreadTaskRunnerHandle::Get());
205 reduce_memory_usage_callback_ =
206 base::Bind(&OneCopyTileTaskWorkerPool::ReduceMemoryUsage,
207 weak_ptr_factory_.GetWeakPtr());
210 OneCopyTileTaskWorkerPool::~OneCopyTileTaskWorkerPool() {
211 base::trace_event::MemoryDumpManager::GetInstance()->UnregisterDumpProvider(
212 this);
215 TileTaskRunner* OneCopyTileTaskWorkerPool::AsTileTaskRunner() {
216 return this;
219 void OneCopyTileTaskWorkerPool::SetClient(TileTaskRunnerClient* client) {
220 client_ = client;
223 void OneCopyTileTaskWorkerPool::Shutdown() {
224 TRACE_EVENT0("cc", "OneCopyTileTaskWorkerPool::Shutdown");
226 TaskGraph empty;
227 task_graph_runner_->ScheduleTasks(namespace_token_, &empty);
228 task_graph_runner_->WaitForTasksToFinishRunning(namespace_token_);
230 base::AutoLock lock(lock_);
232 if (buffers_.empty())
233 return;
235 ReleaseBuffersNotUsedSince(base::TimeTicks() + base::TimeDelta::Max());
238 void OneCopyTileTaskWorkerPool::ScheduleTasks(TileTaskQueue* queue) {
239 TRACE_EVENT0("cc", "OneCopyTileTaskWorkerPool::ScheduleTasks");
241 if (tasks_pending_.none())
242 TRACE_EVENT_ASYNC_BEGIN0("cc", "ScheduledTasks", this);
244 // Mark all task sets as pending.
245 tasks_pending_.set();
247 size_t priority = kTileTaskPriorityBase;
249 graph_.Reset();
251 // Cancel existing OnTaskSetFinished callbacks.
252 task_set_finished_weak_ptr_factory_.InvalidateWeakPtrs();
254 scoped_refptr<TileTask> new_task_set_finished_tasks[kNumberOfTaskSets];
256 size_t task_count[kNumberOfTaskSets] = {0};
258 for (TaskSet task_set = 0; task_set < kNumberOfTaskSets; ++task_set) {
259 new_task_set_finished_tasks[task_set] = CreateTaskSetFinishedTask(
260 task_runner_.get(),
261 base::Bind(&OneCopyTileTaskWorkerPool::OnTaskSetFinished,
262 task_set_finished_weak_ptr_factory_.GetWeakPtr(), task_set));
265 for (TileTaskQueue::Item::Vector::const_iterator it = queue->items.begin();
266 it != queue->items.end(); ++it) {
267 const TileTaskQueue::Item& item = *it;
268 RasterTask* task = item.task;
269 DCHECK(!task->HasCompleted());
271 for (TaskSet task_set = 0; task_set < kNumberOfTaskSets; ++task_set) {
272 if (!item.task_sets[task_set])
273 continue;
275 ++task_count[task_set];
277 graph_.edges.push_back(
278 TaskGraph::Edge(task, new_task_set_finished_tasks[task_set].get()));
281 InsertNodesForRasterTask(&graph_, task, task->dependencies(), priority++);
284 for (TaskSet task_set = 0; task_set < kNumberOfTaskSets; ++task_set) {
285 InsertNodeForTask(&graph_, new_task_set_finished_tasks[task_set].get(),
286 kTaskSetFinishedTaskPriorityBase + task_set,
287 task_count[task_set]);
290 ScheduleTasksOnOriginThread(this, &graph_);
292 // Barrier to sync any new resources to the worker context.
293 resource_provider_->output_surface()
294 ->context_provider()
295 ->ContextGL()
296 ->OrderingBarrierCHROMIUM();
298 task_graph_runner_->ScheduleTasks(namespace_token_, &graph_);
300 std::copy(new_task_set_finished_tasks,
301 new_task_set_finished_tasks + kNumberOfTaskSets,
302 task_set_finished_tasks_);
304 TRACE_EVENT_ASYNC_STEP_INTO1("cc", "ScheduledTasks", this, "running", "state",
305 StateAsValue());
308 void OneCopyTileTaskWorkerPool::CheckForCompletedTasks() {
309 TRACE_EVENT0("cc", "OneCopyTileTaskWorkerPool::CheckForCompletedTasks");
311 task_graph_runner_->CollectCompletedTasks(namespace_token_,
312 &completed_tasks_);
314 for (Task::Vector::const_iterator it = completed_tasks_.begin();
315 it != completed_tasks_.end(); ++it) {
316 TileTask* task = static_cast<TileTask*>(it->get());
318 task->WillComplete();
319 task->CompleteOnOriginThread(this);
320 task->DidComplete();
322 completed_tasks_.clear();
325 ResourceFormat OneCopyTileTaskWorkerPool::GetResourceFormat() const {
326 return resource_provider_->memory_efficient_texture_format();
329 bool OneCopyTileTaskWorkerPool::GetResourceRequiresSwizzle() const {
330 return !PlatformColor::SameComponentOrder(GetResourceFormat());
333 scoped_ptr<RasterBuffer> OneCopyTileTaskWorkerPool::AcquireBufferForRaster(
334 const Resource* resource,
335 uint64_t resource_content_id,
336 uint64_t previous_content_id) {
337 // TODO(danakj): If resource_content_id != 0, we only need to copy/upload
338 // the dirty rect.
339 DCHECK_EQ(resource->format(),
340 resource_provider_->memory_efficient_texture_format());
341 return make_scoped_ptr<RasterBuffer>(new RasterBufferImpl(
342 this, resource_provider_,
343 resource_provider_->memory_efficient_texture_format(), resource,
344 previous_content_id));
347 void OneCopyTileTaskWorkerPool::ReleaseBufferForRaster(
348 scoped_ptr<RasterBuffer> buffer) {
349 // Nothing to do here. RasterBufferImpl destructor cleans up after itself.
352 void OneCopyTileTaskWorkerPool::PlaybackAndCopyOnWorkerThread(
353 const Resource* resource,
354 const ResourceProvider::ScopedWriteLockGL* resource_lock,
355 const RasterSource* raster_source,
356 const gfx::Rect& raster_full_rect,
357 const gfx::Rect& raster_dirty_rect,
358 float scale,
359 bool include_images,
360 uint64_t previous_content_id,
361 uint64_t new_content_id) {
362 base::AutoLock lock(lock_);
364 scoped_ptr<StagingBuffer> staging_buffer =
365 AcquireStagingBuffer(resource, previous_content_id);
366 DCHECK(staging_buffer);
369 base::AutoUnlock unlock(lock_);
371 // Allocate GpuMemoryBuffer if necessary.
372 if (!staging_buffer->gpu_memory_buffer) {
373 staging_buffer->gpu_memory_buffer =
374 resource_provider_->gpu_memory_buffer_manager()
375 ->AllocateGpuMemoryBuffer(
376 staging_buffer->size,
377 BufferFormat(
378 resource_provider_->memory_efficient_texture_format()),
379 use_persistent_gpu_memory_buffers_
380 ? gfx::BufferUsage::PERSISTENT_MAP
381 : gfx::BufferUsage::MAP);
382 DCHECK_EQ(gfx::NumberOfPlanesForBufferFormat(
383 staging_buffer->gpu_memory_buffer->GetFormat()),
384 1u);
387 gfx::Rect playback_rect = raster_full_rect;
388 if (use_persistent_gpu_memory_buffers_ && previous_content_id) {
389 // Reduce playback rect to dirty region if the content id of the staging
390 // buffer matches the prevous content id.
391 if (previous_content_id == staging_buffer->content_id)
392 playback_rect.Intersect(raster_dirty_rect);
395 if (staging_buffer->gpu_memory_buffer) {
396 void* data = nullptr;
397 bool rv = staging_buffer->gpu_memory_buffer->Map(&data);
398 DCHECK(rv);
399 int stride;
400 staging_buffer->gpu_memory_buffer->GetStride(&stride);
401 // TileTaskWorkerPool::PlaybackToMemory only supports unsigned strides.
402 DCHECK_GE(stride, 0);
404 DCHECK(!playback_rect.IsEmpty())
405 << "Why are we rastering a tile that's not dirty?";
406 TileTaskWorkerPool::PlaybackToMemory(
407 data, resource_provider_->memory_efficient_texture_format(),
408 staging_buffer->size, static_cast<size_t>(stride), raster_source,
409 raster_full_rect, playback_rect, scale, include_images);
410 staging_buffer->gpu_memory_buffer->Unmap();
411 staging_buffer->content_id = new_content_id;
415 ContextProvider* context_provider =
416 resource_provider_->output_surface()->worker_context_provider();
417 DCHECK(context_provider);
420 ContextProvider::ScopedContextLock scoped_context(context_provider);
422 gpu::gles2::GLES2Interface* gl = scoped_context.ContextGL();
423 DCHECK(gl);
425 unsigned image_target = resource_provider_->GetImageTextureTarget(
426 resource_provider_->memory_efficient_texture_format());
428 // Create and bind staging texture.
429 if (!staging_buffer->texture_id) {
430 gl->GenTextures(1, &staging_buffer->texture_id);
431 gl->BindTexture(image_target, staging_buffer->texture_id);
432 gl->TexParameteri(image_target, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
433 gl->TexParameteri(image_target, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
434 gl->TexParameteri(image_target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
435 gl->TexParameteri(image_target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
436 } else {
437 gl->BindTexture(image_target, staging_buffer->texture_id);
440 // Create and bind image.
441 if (!staging_buffer->image_id) {
442 if (staging_buffer->gpu_memory_buffer) {
443 staging_buffer->image_id = gl->CreateImageCHROMIUM(
444 staging_buffer->gpu_memory_buffer->AsClientBuffer(),
445 staging_buffer->size.width(), staging_buffer->size.height(),
446 GLInternalFormat(
447 resource_provider_->memory_efficient_texture_format()));
448 gl->BindTexImage2DCHROMIUM(image_target, staging_buffer->image_id);
450 } else {
451 gl->ReleaseTexImage2DCHROMIUM(image_target, staging_buffer->image_id);
452 gl->BindTexImage2DCHROMIUM(image_target, staging_buffer->image_id);
455 // Unbind staging texture.
456 gl->BindTexture(image_target, 0);
458 if (resource_provider_->use_sync_query()) {
459 if (!staging_buffer->query_id)
460 gl->GenQueriesEXT(1, &staging_buffer->query_id);
462 #if defined(OS_CHROMEOS)
463 // TODO(reveman): This avoids a performance problem on some ChromeOS
464 // devices. This needs to be removed to support native GpuMemoryBuffer
465 // implementations. crbug.com/436314
466 gl->BeginQueryEXT(GL_COMMANDS_ISSUED_CHROMIUM, staging_buffer->query_id);
467 #else
468 gl->BeginQueryEXT(GL_COMMANDS_COMPLETED_CHROMIUM,
469 staging_buffer->query_id);
470 #endif
473 int bytes_per_row =
474 (BitsPerPixel(resource_provider_->memory_efficient_texture_format()) *
475 resource->size().width()) /
477 int chunk_size_in_rows =
478 std::max(1, max_bytes_per_copy_operation_ / bytes_per_row);
479 // Align chunk size to 4. Required to support compressed texture formats.
480 chunk_size_in_rows = MathUtil::UncheckedRoundUp(chunk_size_in_rows, 4);
481 int y = 0;
482 int height = resource->size().height();
483 while (y < height) {
484 // Copy at most |chunk_size_in_rows|.
485 int rows_to_copy = std::min(chunk_size_in_rows, height - y);
486 DCHECK_GT(rows_to_copy, 0);
488 gl->CopySubTextureCHROMIUM(GL_TEXTURE_2D, staging_buffer->texture_id,
489 resource_lock->texture_id(), 0, y, 0, y,
490 resource->size().width(), rows_to_copy, false,
491 false, false);
492 y += rows_to_copy;
494 // Increment |bytes_scheduled_since_last_flush_| by the amount of memory
495 // used for this copy operation.
496 bytes_scheduled_since_last_flush_ += rows_to_copy * bytes_per_row;
498 if (bytes_scheduled_since_last_flush_ >= max_bytes_per_copy_operation_) {
499 gl->ShallowFlushCHROMIUM();
500 bytes_scheduled_since_last_flush_ = 0;
504 if (resource_provider_->use_sync_query()) {
505 #if defined(OS_CHROMEOS)
506 gl->EndQueryEXT(GL_COMMANDS_ISSUED_CHROMIUM);
507 #else
508 gl->EndQueryEXT(GL_COMMANDS_COMPLETED_CHROMIUM);
509 #endif
512 // Barrier to sync worker context output to cc context.
513 gl->OrderingBarrierCHROMIUM();
516 staging_buffer->last_usage = base::TimeTicks::Now();
517 busy_buffers_.push_back(staging_buffer.Pass());
519 ScheduleReduceMemoryUsage();
522 bool OneCopyTileTaskWorkerPool::OnMemoryDump(
523 const base::trace_event::MemoryDumpArgs& args,
524 base::trace_event::ProcessMemoryDump* pmd) {
525 base::AutoLock lock(lock_);
527 for (const auto& buffer : buffers_) {
528 buffer->OnMemoryDump(pmd,
529 resource_provider_->memory_efficient_texture_format(),
530 std::find(free_buffers_.begin(), free_buffers_.end(),
531 buffer) != free_buffers_.end());
534 return true;
537 scoped_ptr<OneCopyTileTaskWorkerPool::StagingBuffer>
538 OneCopyTileTaskWorkerPool::AcquireStagingBuffer(const Resource* resource,
539 uint64_t previous_content_id) {
540 lock_.AssertAcquired();
542 scoped_ptr<StagingBuffer> staging_buffer;
544 ContextProvider* context_provider =
545 resource_provider_->output_surface()->worker_context_provider();
546 DCHECK(context_provider);
548 ContextProvider::ScopedContextLock scoped_context(context_provider);
550 gpu::gles2::GLES2Interface* gl = scoped_context.ContextGL();
551 DCHECK(gl);
553 // Check if any busy buffers have become available.
554 if (resource_provider_->use_sync_query()) {
555 while (!busy_buffers_.empty()) {
556 if (!CheckForQueryResult(gl, busy_buffers_.front()->query_id))
557 break;
559 free_buffers_.push_back(busy_buffers_.take_front());
563 // Wait for number of non-free buffers to become less than the limit.
564 while ((buffers_.size() - free_buffers_.size()) >= max_staging_buffers_) {
565 // Stop when there are no more busy buffers to wait for.
566 if (busy_buffers_.empty())
567 break;
569 if (resource_provider_->use_sync_query()) {
570 WaitForQueryResult(gl, busy_buffers_.front()->query_id);
571 free_buffers_.push_back(busy_buffers_.take_front());
572 } else {
573 // Fall-back to glFinish if CHROMIUM_sync_query is not available.
574 gl->Finish();
575 while (!busy_buffers_.empty())
576 free_buffers_.push_back(busy_buffers_.take_front());
580 // Find a staging buffer that allows us to perform partial raster when
581 // using persistent GpuMemoryBuffers.
582 if (use_persistent_gpu_memory_buffers_ && previous_content_id) {
583 StagingBufferDeque::iterator it =
584 std::find_if(free_buffers_.begin(), free_buffers_.end(),
585 [previous_content_id](const StagingBuffer* buffer) {
586 return buffer->content_id == previous_content_id;
588 if (it != free_buffers_.end())
589 staging_buffer = free_buffers_.take(it);
592 // Find staging buffer of correct size.
593 if (!staging_buffer) {
594 StagingBufferDeque::iterator it =
595 std::find_if(free_buffers_.begin(), free_buffers_.end(),
596 [resource](const StagingBuffer* buffer) {
597 return buffer->size == resource->size();
599 if (it != free_buffers_.end())
600 staging_buffer = free_buffers_.take(it);
603 // Create new staging buffer if necessary.
604 if (!staging_buffer) {
605 staging_buffer = make_scoped_ptr(new StagingBuffer(resource->size()));
606 buffers_.insert(staging_buffer.get());
609 // Release enough free buffers to stay within the limit.
610 while (buffers_.size() > max_staging_buffers_) {
611 if (free_buffers_.empty())
612 break;
614 free_buffers_.front()->DestroyGLResources(gl);
615 buffers_.erase(free_buffers_.front());
616 free_buffers_.take_front();
619 return staging_buffer.Pass();
622 base::TimeTicks OneCopyTileTaskWorkerPool::GetUsageTimeForLRUBuffer() {
623 lock_.AssertAcquired();
625 if (!free_buffers_.empty())
626 return free_buffers_.front()->last_usage;
628 if (!busy_buffers_.empty())
629 return busy_buffers_.front()->last_usage;
631 return base::TimeTicks();
634 void OneCopyTileTaskWorkerPool::ScheduleReduceMemoryUsage() {
635 lock_.AssertAcquired();
637 if (reduce_memory_usage_pending_)
638 return;
640 reduce_memory_usage_pending_ = true;
642 // Schedule a call to ReduceMemoryUsage at the time when the LRU buffer
643 // should be released.
644 base::TimeTicks reduce_memory_usage_time =
645 GetUsageTimeForLRUBuffer() + staging_buffer_expiration_delay_;
646 task_runner_->PostDelayedTask(
647 FROM_HERE, reduce_memory_usage_callback_,
648 reduce_memory_usage_time - base::TimeTicks::Now());
651 void OneCopyTileTaskWorkerPool::ReduceMemoryUsage() {
652 base::AutoLock lock(lock_);
654 reduce_memory_usage_pending_ = false;
656 if (free_buffers_.empty() && busy_buffers_.empty())
657 return;
659 base::TimeTicks current_time = base::TimeTicks::Now();
660 ReleaseBuffersNotUsedSince(current_time - staging_buffer_expiration_delay_);
662 if (free_buffers_.empty() && busy_buffers_.empty())
663 return;
665 reduce_memory_usage_pending_ = true;
667 // Schedule another call to ReduceMemoryUsage at the time when the next
668 // buffer should be released.
669 base::TimeTicks reduce_memory_usage_time =
670 GetUsageTimeForLRUBuffer() + staging_buffer_expiration_delay_;
671 task_runner_->PostDelayedTask(FROM_HERE, reduce_memory_usage_callback_,
672 reduce_memory_usage_time - current_time);
675 void OneCopyTileTaskWorkerPool::ReleaseBuffersNotUsedSince(
676 base::TimeTicks time) {
677 lock_.AssertAcquired();
679 ContextProvider* context_provider =
680 resource_provider_->output_surface()->worker_context_provider();
681 DCHECK(context_provider);
684 ContextProvider::ScopedContextLock scoped_context(context_provider);
686 gpu::gles2::GLES2Interface* gl = scoped_context.ContextGL();
687 DCHECK(gl);
689 // Note: Front buffer is guaranteed to be LRU so we can stop releasing
690 // buffers as soon as we find a buffer that has been used since |time|.
691 while (!free_buffers_.empty()) {
692 if (free_buffers_.front()->last_usage > time)
693 return;
695 free_buffers_.front()->DestroyGLResources(gl);
696 buffers_.erase(free_buffers_.front());
697 free_buffers_.take_front();
700 while (!busy_buffers_.empty()) {
701 if (busy_buffers_.front()->last_usage > time)
702 return;
704 busy_buffers_.front()->DestroyGLResources(gl);
705 buffers_.erase(busy_buffers_.front());
706 busy_buffers_.take_front();
711 void OneCopyTileTaskWorkerPool::OnTaskSetFinished(TaskSet task_set) {
712 TRACE_EVENT1("cc", "OneCopyTileTaskWorkerPool::OnTaskSetFinished", "task_set",
713 task_set);
715 DCHECK(tasks_pending_[task_set]);
716 tasks_pending_[task_set] = false;
717 if (tasks_pending_.any()) {
718 TRACE_EVENT_ASYNC_STEP_INTO1("cc", "ScheduledTasks", this, "running",
719 "state", StateAsValue());
720 } else {
721 TRACE_EVENT_ASYNC_END0("cc", "ScheduledTasks", this);
723 client_->DidFinishRunningTileTasks(task_set);
726 scoped_refptr<base::trace_event::ConvertableToTraceFormat>
727 OneCopyTileTaskWorkerPool::StateAsValue() const {
728 scoped_refptr<base::trace_event::TracedValue> state =
729 new base::trace_event::TracedValue();
731 state->BeginArray("tasks_pending");
732 for (TaskSet task_set = 0; task_set < kNumberOfTaskSets; ++task_set)
733 state->AppendBoolean(tasks_pending_[task_set]);
734 state->EndArray();
735 state->BeginDictionary("staging_state");
736 StagingStateAsValueInto(state.get());
737 state->EndDictionary();
739 return state;
742 void OneCopyTileTaskWorkerPool::StagingStateAsValueInto(
743 base::trace_event::TracedValue* staging_state) const {
744 base::AutoLock lock(lock_);
746 staging_state->SetInteger("staging_buffer_count",
747 static_cast<int>(buffers_.size()));
748 staging_state->SetInteger("busy_count",
749 static_cast<int>(busy_buffers_.size()));
750 staging_state->SetInteger("free_count",
751 static_cast<int>(free_buffers_.size()));
754 } // namespace cc