DXR is a code search and navigation tool aimed at making sense of large projects. It supports full-text and regex searches as well as structural queries.

Header

Mercurial (c969a93b0ca7)

VCS Links

Line Code
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 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "TextureSync.h"

#include <unordered_set>

#include "base/process_util.h"
#include "chrome/common/mach_ipc_mac.h"
#include "mozilla/ipc/SharedMemoryBasic.h"
#include "mozilla/layers/CompositorThread.h"
#include "mozilla/StaticMonitor.h"
#include "mozilla/StaticPtr.h"

#ifdef DEBUG
#  define LOG_ERROR(str, args...)                                  \
    PR_BEGIN_MACRO                                                 \
    mozilla::SmprintfPointer msg = mozilla::Smprintf(str, ##args); \
    NS_WARNING(msg.get());                                         \
    PR_END_MACRO
#else
#  define LOG_ERROR(str, args...) \
    do { /* nothing */            \
    } while (0)
#endif

namespace mozilla {

namespace layers {

// Hold raw pointers and trust that TextureSourceProviders will be
// unregistered in their destructors - we don't want to keep these
// alive, and destroying them from the main thread will be an
// error anyway.
StaticAutoPtr<nsTArray<TextureSourceProvider*>> gTextureSourceProviders;

static std::map<pid_t, std::unordered_set<uint64_t>> gProcessTextureIds;
static StaticMonitor gTextureLockMonitor;

const int kSendMessageTimeout = 1000;
const int kTextureLockTimeout = 32;  // We really don't want to wait more than
                                     // two frames for a texture to unlock. This
                                     // will in any case be very uncommon.

struct WaitForTexturesReply {
  bool success;
};

struct WaitForTexturesRequest {
  pid_t pid;
};

static std::unordered_set<uint64_t>* GetLockedTextureIdsForProcess(pid_t pid) {
  gTextureLockMonitor.AssertCurrentThreadOwns();

  if (gProcessTextureIds.find(pid) == gProcessTextureIds.end()) {
    gProcessTextureIds[pid] = std::unordered_set<uint64_t>();
  }

  return &gProcessTextureIds.at(pid);
}

static bool WaitForTextureIdsToUnlock(pid_t pid,
                                      const Span<const uint64_t>& textureIds) {
  {
    StaticMonitorAutoLock lock(gTextureLockMonitor);
    std::unordered_set<uint64_t>* freedTextureIds =
        GetLockedTextureIdsForProcess(pid);

    TimeStamp start = TimeStamp::Now();
    while (true) {
      bool allCleared = true;
      for (uint64_t textureId : textureIds) {
        if (freedTextureIds->find(textureId) != freedTextureIds->end()) {
          allCleared = false;
        }
      }

      if (allCleared) {
        return true;
      }

      if (lock.Wait(TimeDuration::FromMilliseconds(kTextureLockTimeout)) ==
          CVStatus::Timeout) {
        return false;
      }

      // In case the monitor gets signaled multiple times, each less than
      // kTextureLockTimeout.  This ensures that the total time we wait is
      // < 2 * kTextureLockTimeout
      if ((TimeStamp::Now() - start).ToMilliseconds() >
          (double)kTextureLockTimeout) {
        return false;
      }
    }
  }
}

static void CheckTexturesForUnlock() {
  if (gTextureSourceProviders) {
    for (auto it = gTextureSourceProviders->begin();
         it != gTextureSourceProviders->end(); ++it) {
      (*it)->TryUnlockTextures();
    }
  }
}

void TextureSync::DispatchCheckTexturesForUnlock() {
  RefPtr<Runnable> task =
      NS_NewRunnableFunction("CheckTexturesForUnlock", &CheckTexturesForUnlock);
  CompositorThreadHolder::Loop()->PostTask(task.forget());
}

void TextureSync::HandleWaitForTexturesMessage(MachReceiveMessage* rmsg,
                                               ipc::MemoryPorts* ports) {
  WaitForTexturesRequest* req =
      reinterpret_cast<WaitForTexturesRequest*>(rmsg->GetData());
  uint64_t* textureIds = (uint64_t*)(req + 1);
  uint32_t textureIdsLength =
      (rmsg->GetDataLength() - sizeof(WaitForTexturesRequest)) /
      sizeof(uint64_t);

  bool success = WaitForTextureIdsToUnlock(
      req->pid, MakeSpan<uint64_t>(textureIds, textureIdsLength));

  if (!success) {
    LOG_ERROR("Waiting for textures to unlock failed.\n");
  }

  MachSendMessage msg(ipc::kReturnWaitForTexturesMsg);
  WaitForTexturesReply replydata;
  replydata.success = success;
  msg.SetData(&replydata, sizeof(WaitForTexturesReply));
  kern_return_t err = ports->mSender->SendMessage(msg, kSendMessageTimeout);
  if (KERN_SUCCESS != err) {
    LOG_ERROR("SendMessage failed 0x%x %s\n", err, mach_error_string(err));
  }
}

void TextureSync::RegisterTextureSourceProvider(
    TextureSourceProvider* textureSourceProvider) {
  if (!gTextureSourceProviders) {
    gTextureSourceProviders = new nsTArray<TextureSourceProvider*>();
  }
  MOZ_RELEASE_ASSERT(!gTextureSourceProviders->Contains(textureSourceProvider));
  gTextureSourceProviders->AppendElement(textureSourceProvider);
}

void TextureSync::UnregisterTextureSourceProvider(
    TextureSourceProvider* textureSourceProvider) {
  if (gTextureSourceProviders) {
    MOZ_ASSERT(gTextureSourceProviders->Contains(textureSourceProvider));
    gTextureSourceProviders->RemoveElement(textureSourceProvider);
    if (gTextureSourceProviders->Length() == 0) {
      gTextureSourceProviders = nullptr;
    }
  }
}

void TextureSync::SetTexturesLocked(pid_t pid,
                                    const nsTArray<uint64_t>& textureIds) {
  StaticMonitorAutoLock mal(gTextureLockMonitor);
  std::unordered_set<uint64_t>* lockedTextureIds =
      GetLockedTextureIdsForProcess(pid);
  for (uint64_t textureId : textureIds) {
    lockedTextureIds->insert(textureId);
  }
}

void TextureSync::SetTexturesUnlocked(pid_t pid,
                                      const nsTArray<uint64_t>& textureIds) {
  bool oneErased = false;
  {
    StaticMonitorAutoLock mal(gTextureLockMonitor);
    std::unordered_set<uint64_t>* lockedTextureIds =
        GetLockedTextureIdsForProcess(pid);
    for (uint64_t textureId : textureIds) {
      if (lockedTextureIds->erase(textureId)) {
        oneErased = true;
      }
    }
  }
  if (oneErased) {
    gTextureLockMonitor.NotifyAll();
  }
}

void TextureSync::Shutdown() {
  {
    StaticMonitorAutoLock lock(gTextureLockMonitor);

    for (auto& lockedTextureIds : gProcessTextureIds) {
      lockedTextureIds.second.clear();
    }
  }

  gTextureLockMonitor.NotifyAll();

  {
    StaticMonitorAutoLock lock(gTextureLockMonitor);
    gProcessTextureIds.clear();
  }
}

void TextureSync::UpdateTextureLocks(base::ProcessId aProcessId) {
  if (aProcessId == base::GetCurrentProcId()) {
    DispatchCheckTexturesForUnlock();
    return;
  }

  MachSendMessage smsg(ipc::kUpdateTextureLocksMsg);
  smsg.SetData(&aProcessId, sizeof(aProcessId));
  ipc::SharedMemoryBasic::SendMachMessage(aProcessId, smsg, NULL);
}

bool TextureSync::WaitForTextures(base::ProcessId aProcessId,
                                  const nsTArray<uint64_t>& textureIds) {
  if (aProcessId == base::GetCurrentProcId()) {
    bool success =
        WaitForTextureIdsToUnlock(aProcessId, MakeSpan<uint64_t>(textureIds));
    if (!success) {
      LOG_ERROR("Failed waiting for textures to unlock.\n");
    }

    return success;
  }

  MachSendMessage smsg(ipc::kWaitForTexturesMsg);
  size_t messageSize =
      sizeof(WaitForTexturesRequest) + textureIds.Length() * sizeof(uint64_t);
  UniquePtr<uint8_t[]> messageData = MakeUnique<uint8_t[]>(messageSize);
  WaitForTexturesRequest* req = (WaitForTexturesRequest*)messageData.get();
  uint64_t* reqTextureIds = (uint64_t*)(req + 1);

  for (uint32_t i = 0; i < textureIds.Length(); ++i) {
    reqTextureIds[i] = textureIds[i];
  }

  req->pid = base::GetCurrentProcId();
  bool dataWasSet = smsg.SetData(req, messageSize);

  if (!dataWasSet) {
    LOG_ERROR("Data was too large: %zu\n", messageSize);
    return false;
  }

  MachReceiveMessage msg;
  bool success =
      ipc::SharedMemoryBasic::SendMachMessage(aProcessId, smsg, &msg);
  if (!success) {
    return false;
  }

  if (msg.GetDataLength() != sizeof(WaitForTexturesReply)) {
    LOG_ERROR("Improperly formatted reply\n");
    return false;
  }

  WaitForTexturesReply* msg_data =
      reinterpret_cast<WaitForTexturesReply*>(msg.GetData());
  if (!msg_data->success) {
    LOG_ERROR("Failed waiting for textures to unlock.\n");
    return false;
  }

  return true;
}

void TextureSync::CleanupForPid(base::ProcessId aProcessId) {
  {
    StaticMonitorAutoLock lock(gTextureLockMonitor);
    std::unordered_set<uint64_t>* lockedTextureIds =
        GetLockedTextureIdsForProcess(aProcessId);
    lockedTextureIds->clear();
  }
  gTextureLockMonitor.NotifyAll();
}

}  // namespace layers

}  // namespace mozilla