summaryrefslogtreecommitdiffstats
path: root/content/renderer/shared_memory_seqlock_reader.cc
blob: 2727aa52f99fd015c5c9d51a9cf026c8040d4d9b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// Copyright 2013 The Chromium 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 "content/renderer/shared_memory_seqlock_reader.h"

namespace content {
namespace internal {

SharedMemorySeqLockReaderBase::SharedMemorySeqLockReaderBase() { }

SharedMemorySeqLockReaderBase::~SharedMemorySeqLockReaderBase() { }

void*
SharedMemorySeqLockReaderBase::InitializeSharedMemory(
    base::SharedMemoryHandle shared_memory_handle, size_t buffer_size) {
  renderer_shared_memory_handle_ = shared_memory_handle;
  if (!base::SharedMemory::IsHandleValid(renderer_shared_memory_handle_))
    return 0;
  renderer_shared_memory_.reset(new base::SharedMemory(
      renderer_shared_memory_handle_, true));

  return (renderer_shared_memory_->Map(buffer_size))
      ? renderer_shared_memory_->memory()
      : 0;
}

bool SharedMemorySeqLockReaderBase::FetchFromBuffer(
    content::OneWriterSeqLock* seqlock, void* final, void* temp, void* from,
    size_t size) {

  if (!base::SharedMemory::IsHandleValid(renderer_shared_memory_handle_))
    return false;

  // Only try to read this many times before failing to avoid waiting here
  // very long in case of contention with the writer.
  int contention_count = -1;
  base::subtle::Atomic32 version;
  do {
    version = seqlock->ReadBegin();
    memcpy(temp, from, size);
    ++contention_count;
    if (contention_count == kMaximumContentionCount)
      break;
  } while (seqlock->ReadRetry(version));

  if (contention_count >= kMaximumContentionCount) {
    // We failed to successfully read, presumably because the hardware
    // thread was taking unusually long. Don't copy the data to the output
    // buffer, and simply leave what was there before.
    return false;
  }

  // New data was read successfully, copy it into the output buffer.
  memcpy(final, temp, size);
  return true;
}

}  // namespace internal
}  // namespace content