blob: 2c734ac5658b304871db7d62d565b78d358d976f [file] [log] [blame]
Sungtak Leebbe37b62018-08-29 15:15:48 -07001/*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "BufferPoolAccessor"
18//#define LOG_NDEBUG 0
19
20#include <sys/types.h>
21#include <time.h>
22#include <unistd.h>
23#include <utils/Log.h>
Sungtak Leec7f9e2c2018-09-14 16:23:40 -070024#include <thread>
Sungtak Leebbe37b62018-08-29 15:15:48 -070025#include "AccessorImpl.h"
26#include "Connection.h"
27
28namespace android {
29namespace hardware {
30namespace media {
31namespace bufferpool {
32namespace V2_0 {
33namespace implementation {
34
35namespace {
36 static constexpr int64_t kCleanUpDurationUs = 500000; // TODO tune 0.5 sec
37 static constexpr int64_t kLogDurationUs = 5000000; // 5 secs
38
39 static constexpr size_t kMinAllocBytesForEviction = 1024*1024*15;
40 static constexpr size_t kMinBufferCountForEviction = 40;
41}
42
43// Buffer structure in bufferpool process
44struct InternalBuffer {
45 BufferId mId;
46 size_t mOwnerCount;
47 size_t mTransactionCount;
48 const std::shared_ptr<BufferPoolAllocation> mAllocation;
49 const size_t mAllocSize;
50 const std::vector<uint8_t> mConfig;
Sungtak Leec7f9e2c2018-09-14 16:23:40 -070051 bool mInvalidated;
Sungtak Leebbe37b62018-08-29 15:15:48 -070052
53 InternalBuffer(
54 BufferId id,
55 const std::shared_ptr<BufferPoolAllocation> &alloc,
56 const size_t allocSize,
57 const std::vector<uint8_t> &allocConfig)
58 : mId(id), mOwnerCount(0), mTransactionCount(0),
Sungtak Leec7f9e2c2018-09-14 16:23:40 -070059 mAllocation(alloc), mAllocSize(allocSize), mConfig(allocConfig),
60 mInvalidated(false) {}
Sungtak Leebbe37b62018-08-29 15:15:48 -070061
62 const native_handle_t *handle() {
63 return mAllocation->handle();
64 }
Sungtak Leec7f9e2c2018-09-14 16:23:40 -070065
66 void invalidate() {
67 mInvalidated = true;
68 }
Sungtak Leebbe37b62018-08-29 15:15:48 -070069};
70
71struct TransactionStatus {
72 TransactionId mId;
73 BufferId mBufferId;
74 ConnectionId mSender;
75 ConnectionId mReceiver;
76 BufferStatus mStatus;
77 int64_t mTimestampUs;
78 bool mSenderValidated;
79
80 TransactionStatus(const BufferStatusMessage &message, int64_t timestampUs) {
81 mId = message.transactionId;
82 mBufferId = message.bufferId;
83 mStatus = message.newStatus;
84 mTimestampUs = timestampUs;
85 if (mStatus == BufferStatus::TRANSFER_TO) {
86 mSender = message.connectionId;
87 mReceiver = message.targetConnectionId;
88 mSenderValidated = true;
89 } else {
90 mSender = -1LL;
91 mReceiver = message.connectionId;
92 mSenderValidated = false;
93 }
94 }
95};
96
97// Helper template methods for handling map of set.
98template<class T, class U>
99bool insert(std::map<T, std::set<U>> *mapOfSet, T key, U value) {
100 auto iter = mapOfSet->find(key);
101 if (iter == mapOfSet->end()) {
102 std::set<U> valueSet{value};
103 mapOfSet->insert(std::make_pair(key, valueSet));
104 return true;
105 } else if (iter->second.find(value) == iter->second.end()) {
106 iter->second.insert(value);
107 return true;
108 }
109 return false;
110}
111
112template<class T, class U>
113bool erase(std::map<T, std::set<U>> *mapOfSet, T key, U value) {
114 bool ret = false;
115 auto iter = mapOfSet->find(key);
116 if (iter != mapOfSet->end()) {
117 if (iter->second.erase(value) > 0) {
118 ret = true;
119 }
120 if (iter->second.size() == 0) {
121 mapOfSet->erase(iter);
122 }
123 }
124 return ret;
125}
126
127template<class T, class U>
128bool contains(std::map<T, std::set<U>> *mapOfSet, T key, U value) {
129 auto iter = mapOfSet->find(key);
130 if (iter != mapOfSet->end()) {
131 auto setIter = iter->second.find(value);
132 return setIter != iter->second.end();
133 }
134 return false;
135}
136
137int32_t Accessor::Impl::sPid = getpid();
138uint32_t Accessor::Impl::sSeqId = time(nullptr);
139
140Accessor::Impl::Impl(
141 const std::shared_ptr<BufferPoolAllocator> &allocator)
142 : mAllocator(allocator) {}
143
144Accessor::Impl::~Impl() {
145}
146
147ResultStatus Accessor::Impl::connect(
Sungtak Leec7f9e2c2018-09-14 16:23:40 -0700148 const sp<Accessor> &accessor, const sp<IObserver> &observer,
149 sp<Connection> *connection,
150 ConnectionId *pConnectionId,
151 uint32_t *pMsgId,
152 const StatusDescriptor** statusDescPtr,
153 const InvalidationDescriptor** invDescPtr) {
Sungtak Leebbe37b62018-08-29 15:15:48 -0700154 sp<Connection> newConnection = new Connection();
155 ResultStatus status = ResultStatus::CRITICAL_ERROR;
156 {
157 std::lock_guard<std::mutex> lock(mBufferPool.mMutex);
158 if (newConnection) {
159 ConnectionId id = (int64_t)sPid << 32 | sSeqId;
Sungtak Leec7f9e2c2018-09-14 16:23:40 -0700160 status = mBufferPool.mObserver.open(id, statusDescPtr);
Sungtak Leebbe37b62018-08-29 15:15:48 -0700161 if (status == ResultStatus::OK) {
162 newConnection->initialize(accessor, id);
163 *connection = newConnection;
164 *pConnectionId = id;
Sungtak Leec7f9e2c2018-09-14 16:23:40 -0700165 *pMsgId = mBufferPool.mInvalidation.mInvalidationId;
166 mBufferPool.mInvalidationChannel.getDesc(invDescPtr);
167 mBufferPool.mInvalidation.onConnect(id, observer);
Sungtak Leebbe37b62018-08-29 15:15:48 -0700168 ++sSeqId;
169 }
Sungtak Leec7f9e2c2018-09-14 16:23:40 -0700170
Sungtak Leebbe37b62018-08-29 15:15:48 -0700171 }
172 mBufferPool.processStatusMessages();
173 mBufferPool.cleanUp();
174 }
175 return status;
176}
177
178ResultStatus Accessor::Impl::close(ConnectionId connectionId) {
179 std::lock_guard<std::mutex> lock(mBufferPool.mMutex);
Sungtak Leed3128382018-11-07 17:30:37 -0800180 ALOGV("connection close %lld: %u", (long long)connectionId, mBufferPool.mInvalidation.mId);
Sungtak Leebbe37b62018-08-29 15:15:48 -0700181 mBufferPool.processStatusMessages();
182 mBufferPool.handleClose(connectionId);
183 mBufferPool.mObserver.close(connectionId);
Sungtak Leec7f9e2c2018-09-14 16:23:40 -0700184 mBufferPool.mInvalidation.onClose(connectionId);
Sungtak Leebbe37b62018-08-29 15:15:48 -0700185 // Since close# will be called after all works are finished, it is OK to
186 // evict unused buffers.
187 mBufferPool.cleanUp(true);
188 return ResultStatus::OK;
189}
190
191ResultStatus Accessor::Impl::allocate(
192 ConnectionId connectionId, const std::vector<uint8_t>& params,
193 BufferId *bufferId, const native_handle_t** handle) {
194 std::unique_lock<std::mutex> lock(mBufferPool.mMutex);
195 mBufferPool.processStatusMessages();
196 ResultStatus status = ResultStatus::OK;
197 if (!mBufferPool.getFreeBuffer(mAllocator, params, bufferId, handle)) {
198 lock.unlock();
199 std::shared_ptr<BufferPoolAllocation> alloc;
200 size_t allocSize;
201 status = mAllocator->allocate(params, &alloc, &allocSize);
202 lock.lock();
203 if (status == ResultStatus::OK) {
204 status = mBufferPool.addNewBuffer(alloc, allocSize, params, bufferId, handle);
205 }
206 ALOGV("create a buffer %d : %u %p",
207 status == ResultStatus::OK, *bufferId, *handle);
208 }
209 if (status == ResultStatus::OK) {
210 // TODO: handle ownBuffer failure
211 mBufferPool.handleOwnBuffer(connectionId, *bufferId);
212 }
213 mBufferPool.cleanUp();
214 return status;
215}
216
217ResultStatus Accessor::Impl::fetch(
218 ConnectionId connectionId, TransactionId transactionId,
219 BufferId bufferId, const native_handle_t** handle) {
220 std::lock_guard<std::mutex> lock(mBufferPool.mMutex);
221 mBufferPool.processStatusMessages();
222 auto found = mBufferPool.mTransactions.find(transactionId);
223 if (found != mBufferPool.mTransactions.end() &&
224 contains(&mBufferPool.mPendingTransactions,
225 connectionId, transactionId)) {
226 if (found->second->mSenderValidated &&
227 found->second->mStatus == BufferStatus::TRANSFER_FROM &&
228 found->second->mBufferId == bufferId) {
229 found->second->mStatus = BufferStatus::TRANSFER_FETCH;
230 auto bufferIt = mBufferPool.mBuffers.find(bufferId);
231 if (bufferIt != mBufferPool.mBuffers.end()) {
232 mBufferPool.mStats.onBufferFetched();
233 *handle = bufferIt->second->handle();
234 return ResultStatus::OK;
235 }
236 }
237 }
238 mBufferPool.cleanUp();
239 return ResultStatus::CRITICAL_ERROR;
240}
241
242void Accessor::Impl::cleanUp(bool clearCache) {
243 // transaction timeout, buffer cacheing TTL handling
244 std::lock_guard<std::mutex> lock(mBufferPool.mMutex);
245 mBufferPool.processStatusMessages();
246 mBufferPool.cleanUp(clearCache);
247}
248
Sungtak Leec7f9e2c2018-09-14 16:23:40 -0700249void Accessor::Impl::flush() {
250 std::lock_guard<std::mutex> lock(mBufferPool.mMutex);
251 mBufferPool.processStatusMessages();
252 mBufferPool.flush(shared_from_this());
253}
254
255void Accessor::Impl::handleInvalidateAck() {
256 std::lock_guard<std::mutex> lock(mBufferPool.mMutex);
257 mBufferPool.processStatusMessages();
258 mBufferPool.mInvalidation.onHandleAck();
259}
260
261bool Accessor::Impl::isValid() {
262 return mBufferPool.isValid();
263}
264
Sungtak Leebbe37b62018-08-29 15:15:48 -0700265Accessor::Impl::Impl::BufferPool::BufferPool()
266 : mTimestampUs(getTimestampNow()),
267 mLastCleanUpUs(mTimestampUs),
268 mLastLogUs(mTimestampUs),
Sungtak Leec7f9e2c2018-09-14 16:23:40 -0700269 mSeq(0),
270 mStartSeq(0) {
271 mValid = mInvalidationChannel.isValid();
272}
Sungtak Leebbe37b62018-08-29 15:15:48 -0700273
274
275// Statistics helper
276template<typename T, typename S>
277int percentage(T base, S total) {
278 return int(total ? 0.5 + 100. * static_cast<S>(base) / total : 0);
279}
280
Sungtak Leed3128382018-11-07 17:30:37 -0800281std::atomic<std::uint32_t> Accessor::Impl::BufferPool::Invalidation::sInvSeqId(0);
Sungtak Leec7f9e2c2018-09-14 16:23:40 -0700282
Sungtak Leebbe37b62018-08-29 15:15:48 -0700283Accessor::Impl::Impl::BufferPool::~BufferPool() {
284 std::lock_guard<std::mutex> lock(mMutex);
Sungtak Leed3318082018-09-07 15:52:43 -0700285 ALOGD("Destruction - bufferpool2 %p "
Sungtak Leebbe37b62018-08-29 15:15:48 -0700286 "cached: %zu/%zuM, %zu/%d%% in use; "
287 "allocs: %zu, %d%% recycled; "
288 "transfers: %zu, %d%% unfetced",
289 this, mStats.mBuffersCached, mStats.mSizeCached >> 20,
290 mStats.mBuffersInUse, percentage(mStats.mBuffersInUse, mStats.mBuffersCached),
291 mStats.mTotalAllocations, percentage(mStats.mTotalRecycles, mStats.mTotalAllocations),
292 mStats.mTotalTransfers,
293 percentage(mStats.mTotalTransfers - mStats.mTotalFetches, mStats.mTotalTransfers));
294}
295
Sungtak Leec7f9e2c2018-09-14 16:23:40 -0700296void Accessor::Impl::BufferPool::Invalidation::onConnect(
297 ConnectionId conId, const sp<IObserver>& observer) {
298 mAcks[conId] = mInvalidationId; // starts from current invalidationId
299 mObservers.insert(std::make_pair(conId, observer));
300}
301
302void Accessor::Impl::BufferPool::Invalidation::onClose(ConnectionId conId) {
303 mAcks.erase(conId);
304 mObservers.erase(conId);
305}
306
307void Accessor::Impl::BufferPool::Invalidation::onAck(
308 ConnectionId conId,
309 uint32_t msgId) {
310 auto it = mAcks.find(conId);
Sungtak Leeb355f7c2018-11-19 14:49:10 -0800311 if (it == mAcks.end()) {
312 ALOGW("ACK from inconsistent connection! %lld", (long long)conId);
313 return;
314 }
315 if (isMessageLater(msgId, it->second)) {
Sungtak Leec7f9e2c2018-09-14 16:23:40 -0700316 mAcks[conId] = msgId;
317 }
318}
319
320void Accessor::Impl::BufferPool::Invalidation::onBufferInvalidated(
321 BufferId bufferId,
322 BufferInvalidationChannel &channel) {
323 for (auto it = mPendings.begin(); it != mPendings.end();) {
Sungtak Leed3128382018-11-07 17:30:37 -0800324 if (it->isInvalidated(bufferId)) {
Sungtak Leec7f9e2c2018-09-14 16:23:40 -0700325 uint32_t msgId = 0;
326 if (it->mNeedsAck) {
327 msgId = ++mInvalidationId;
328 if (msgId == 0) {
329 // wrap happens
330 msgId = ++mInvalidationId;
331 }
332 }
333 channel.postInvalidation(msgId, it->mFrom, it->mTo);
Sungtak Leed3128382018-11-07 17:30:37 -0800334 it = mPendings.erase(it);
Sungtak Leec7f9e2c2018-09-14 16:23:40 -0700335 continue;
336 }
337 ++it;
338 }
339}
340
341void Accessor::Impl::BufferPool::Invalidation::onInvalidationRequest(
342 bool needsAck,
343 uint32_t from,
344 uint32_t to,
345 size_t left,
346 BufferInvalidationChannel &channel,
347 const std::shared_ptr<Accessor::Impl> &impl) {
Sungtak Leec7f9e2c2018-09-14 16:23:40 -0700348 uint32_t msgId = 0;
Sungtak Leeb355f7c2018-11-19 14:49:10 -0800349 if (needsAck) {
350 msgId = ++mInvalidationId;
351 if (msgId == 0) {
352 // wrap happens
Sungtak Leec7f9e2c2018-09-14 16:23:40 -0700353 msgId = ++mInvalidationId;
Sungtak Leec7f9e2c2018-09-14 16:23:40 -0700354 }
Sungtak Leeb355f7c2018-11-19 14:49:10 -0800355 }
Sungtak Leed3318082018-09-07 15:52:43 -0700356 ALOGV("bufferpool2 invalidation requested and queued");
Sungtak Leeb355f7c2018-11-19 14:49:10 -0800357 if (left == 0) {
Sungtak Leec7f9e2c2018-09-14 16:23:40 -0700358 channel.postInvalidation(msgId, from, to);
Sungtak Leec7f9e2c2018-09-14 16:23:40 -0700359 } else {
360 // TODO: sending hint message?
Sungtak Leed3318082018-09-07 15:52:43 -0700361 ALOGV("bufferpoo2 invalidation requested and pending");
Sungtak Leec7f9e2c2018-09-14 16:23:40 -0700362 Pending pending(needsAck, from, to, left, impl);
363 mPendings.push_back(pending);
364 }
Sungtak Leeb355f7c2018-11-19 14:49:10 -0800365 sInvalidator->addAccessor(mId, impl);
Sungtak Leec7f9e2c2018-09-14 16:23:40 -0700366}
367
368void Accessor::Impl::BufferPool::Invalidation::onHandleAck() {
369 if (mInvalidationId != 0) {
370 std::set<int> deads;
371 for (auto it = mAcks.begin(); it != mAcks.end(); ++it) {
372 if (it->second != mInvalidationId) {
Sungtak Leed3128382018-11-07 17:30:37 -0800373 const sp<IObserver> observer = mObservers[it->first];
Sungtak Leec7f9e2c2018-09-14 16:23:40 -0700374 if (observer) {
Sungtak Leed3128382018-11-07 17:30:37 -0800375 ALOGV("connection %lld call observer (%u: %u)",
376 (long long)it->first, it->second, mInvalidationId);
377 Return<void> transResult = observer->onMessage(it->first, mInvalidationId);
378 (void) transResult;
Sungtak Leeb355f7c2018-11-19 14:49:10 -0800379 // N.B: ignore possibility of onMessage oneway call being
380 // lost.
381 it->second = mInvalidationId;
Sungtak Leec7f9e2c2018-09-14 16:23:40 -0700382 } else {
Sungtak Leed3318082018-09-07 15:52:43 -0700383 ALOGV("bufferpool2 observer died %lld", (long long)it->first);
Sungtak Leec7f9e2c2018-09-14 16:23:40 -0700384 deads.insert(it->first);
385 }
386 }
387 }
388 if (deads.size() > 0) {
389 for (auto it = deads.begin(); it != deads.end(); ++it) {
390 onClose(*it);
391 }
392 }
393 }
Sungtak Leeb355f7c2018-11-19 14:49:10 -0800394 if (mPendings.size() == 0) {
395 // All invalidation Ids are synced and no more pending invalidations.
396 sInvalidator->delAccessor(mId);
397 }
Sungtak Leec7f9e2c2018-09-14 16:23:40 -0700398}
399
Sungtak Leebbe37b62018-08-29 15:15:48 -0700400bool Accessor::Impl::BufferPool::handleOwnBuffer(
401 ConnectionId connectionId, BufferId bufferId) {
402
403 bool added = insert(&mUsingBuffers, connectionId, bufferId);
404 if (added) {
405 auto iter = mBuffers.find(bufferId);
406 iter->second->mOwnerCount++;
407 }
408 insert(&mUsingConnections, bufferId, connectionId);
409 return added;
410}
411
412bool Accessor::Impl::BufferPool::handleReleaseBuffer(
413 ConnectionId connectionId, BufferId bufferId) {
414 bool deleted = erase(&mUsingBuffers, connectionId, bufferId);
415 if (deleted) {
416 auto iter = mBuffers.find(bufferId);
417 iter->second->mOwnerCount--;
418 if (iter->second->mOwnerCount == 0 &&
419 iter->second->mTransactionCount == 0) {
Sungtak Leec7f9e2c2018-09-14 16:23:40 -0700420 if (!iter->second->mInvalidated) {
421 mStats.onBufferUnused(iter->second->mAllocSize);
422 mFreeBuffers.insert(bufferId);
423 } else {
424 mStats.onBufferUnused(iter->second->mAllocSize);
425 mStats.onBufferEvicted(iter->second->mAllocSize);
426 mBuffers.erase(iter);
427 mInvalidation.onBufferInvalidated(bufferId, mInvalidationChannel);
428 }
Sungtak Leebbe37b62018-08-29 15:15:48 -0700429 }
430 }
431 erase(&mUsingConnections, bufferId, connectionId);
432 ALOGV("release buffer %u : %d", bufferId, deleted);
433 return deleted;
434}
435
436bool Accessor::Impl::BufferPool::handleTransferTo(const BufferStatusMessage &message) {
437 auto completed = mCompletedTransactions.find(
438 message.transactionId);
439 if (completed != mCompletedTransactions.end()) {
440 // already completed
441 mCompletedTransactions.erase(completed);
442 return true;
443 }
444 // the buffer should exist and be owned.
445 auto bufferIter = mBuffers.find(message.bufferId);
446 if (bufferIter == mBuffers.end() ||
447 !contains(&mUsingBuffers, message.connectionId, message.bufferId)) {
448 return false;
449 }
450 auto found = mTransactions.find(message.transactionId);
451 if (found != mTransactions.end()) {
452 // transfer_from was received earlier.
453 found->second->mSender = message.connectionId;
454 found->second->mSenderValidated = true;
455 return true;
456 }
457 // TODO: verify there is target connection Id
458 mStats.onBufferSent();
459 mTransactions.insert(std::make_pair(
460 message.transactionId,
461 std::make_unique<TransactionStatus>(message, mTimestampUs)));
462 insert(&mPendingTransactions, message.targetConnectionId,
463 message.transactionId);
464 bufferIter->second->mTransactionCount++;
465 return true;
466}
467
468bool Accessor::Impl::BufferPool::handleTransferFrom(const BufferStatusMessage &message) {
469 auto found = mTransactions.find(message.transactionId);
470 if (found == mTransactions.end()) {
471 // TODO: is it feasible to check ownership here?
472 mStats.onBufferSent();
473 mTransactions.insert(std::make_pair(
474 message.transactionId,
475 std::make_unique<TransactionStatus>(message, mTimestampUs)));
476 insert(&mPendingTransactions, message.connectionId,
477 message.transactionId);
478 auto bufferIter = mBuffers.find(message.bufferId);
479 bufferIter->second->mTransactionCount++;
480 } else {
481 if (message.connectionId == found->second->mReceiver) {
482 found->second->mStatus = BufferStatus::TRANSFER_FROM;
483 }
484 }
485 return true;
486}
487
488bool Accessor::Impl::BufferPool::handleTransferResult(const BufferStatusMessage &message) {
489 auto found = mTransactions.find(message.transactionId);
490 if (found != mTransactions.end()) {
491 bool deleted = erase(&mPendingTransactions, message.connectionId,
492 message.transactionId);
493 if (deleted) {
494 if (!found->second->mSenderValidated) {
495 mCompletedTransactions.insert(message.transactionId);
496 }
497 auto bufferIter = mBuffers.find(message.bufferId);
498 if (message.newStatus == BufferStatus::TRANSFER_OK) {
499 handleOwnBuffer(message.connectionId, message.bufferId);
500 }
501 bufferIter->second->mTransactionCount--;
502 if (bufferIter->second->mOwnerCount == 0
503 && bufferIter->second->mTransactionCount == 0) {
Sungtak Leec7f9e2c2018-09-14 16:23:40 -0700504 if (!bufferIter->second->mInvalidated) {
505 mStats.onBufferUnused(bufferIter->second->mAllocSize);
506 mFreeBuffers.insert(message.bufferId);
507 } else {
508 mStats.onBufferUnused(bufferIter->second->mAllocSize);
509 mStats.onBufferEvicted(bufferIter->second->mAllocSize);
510 mBuffers.erase(bufferIter);
511 mInvalidation.onBufferInvalidated(message.bufferId, mInvalidationChannel);
512 }
Sungtak Leebbe37b62018-08-29 15:15:48 -0700513 }
514 mTransactions.erase(found);
515 }
516 ALOGV("transfer finished %llu %u - %d", (unsigned long long)message.transactionId,
517 message.bufferId, deleted);
518 return deleted;
519 }
520 ALOGV("transfer not found %llu %u", (unsigned long long)message.transactionId,
521 message.bufferId);
522 return false;
523}
524
525void Accessor::Impl::BufferPool::processStatusMessages() {
526 std::vector<BufferStatusMessage> messages;
527 mObserver.getBufferStatusChanges(messages);
528 mTimestampUs = getTimestampNow();
529 for (BufferStatusMessage& message: messages) {
530 bool ret = false;
531 switch (message.newStatus) {
532 case BufferStatus::NOT_USED:
533 ret = handleReleaseBuffer(
534 message.connectionId, message.bufferId);
535 break;
536 case BufferStatus::USED:
537 // not happening
538 break;
539 case BufferStatus::TRANSFER_TO:
540 ret = handleTransferTo(message);
541 break;
542 case BufferStatus::TRANSFER_FROM:
543 ret = handleTransferFrom(message);
544 break;
545 case BufferStatus::TRANSFER_TIMEOUT:
546 // TODO
547 break;
548 case BufferStatus::TRANSFER_LOST:
549 // TODO
550 break;
551 case BufferStatus::TRANSFER_FETCH:
552 // not happening
553 break;
554 case BufferStatus::TRANSFER_OK:
555 case BufferStatus::TRANSFER_ERROR:
556 ret = handleTransferResult(message);
557 break;
Sungtak Leed491f1f2018-10-05 15:56:56 -0700558 case BufferStatus::INVALIDATION_ACK:
Sungtak Leec7f9e2c2018-09-14 16:23:40 -0700559 mInvalidation.onAck(message.connectionId, message.bufferId);
Sungtak Leed3128382018-11-07 17:30:37 -0800560 ret = true;
Sungtak Leed491f1f2018-10-05 15:56:56 -0700561 break;
Sungtak Leebbe37b62018-08-29 15:15:48 -0700562 }
563 if (ret == false) {
564 ALOGW("buffer status message processing failure - message : %d connection : %lld",
565 message.newStatus, (long long)message.connectionId);
566 }
567 }
568 messages.clear();
569}
570
571bool Accessor::Impl::BufferPool::handleClose(ConnectionId connectionId) {
572 // Cleaning buffers
573 auto buffers = mUsingBuffers.find(connectionId);
574 if (buffers != mUsingBuffers.end()) {
575 for (const BufferId& bufferId : buffers->second) {
576 bool deleted = erase(&mUsingConnections, bufferId, connectionId);
577 if (deleted) {
578 auto bufferIter = mBuffers.find(bufferId);
579 bufferIter->second->mOwnerCount--;
580 if (bufferIter->second->mOwnerCount == 0 &&
581 bufferIter->second->mTransactionCount == 0) {
582 // TODO: handle freebuffer insert fail
Sungtak Leec7f9e2c2018-09-14 16:23:40 -0700583 if (!bufferIter->second->mInvalidated) {
584 mStats.onBufferUnused(bufferIter->second->mAllocSize);
585 mFreeBuffers.insert(bufferId);
586 } else {
587 mStats.onBufferUnused(bufferIter->second->mAllocSize);
588 mStats.onBufferEvicted(bufferIter->second->mAllocSize);
589 mBuffers.erase(bufferIter);
590 mInvalidation.onBufferInvalidated(bufferId, mInvalidationChannel);
591 }
Sungtak Leebbe37b62018-08-29 15:15:48 -0700592 }
593 }
594 }
595 mUsingBuffers.erase(buffers);
596 }
597
598 // Cleaning transactions
599 auto pending = mPendingTransactions.find(connectionId);
600 if (pending != mPendingTransactions.end()) {
601 for (const TransactionId& transactionId : pending->second) {
602 auto iter = mTransactions.find(transactionId);
603 if (iter != mTransactions.end()) {
604 if (!iter->second->mSenderValidated) {
605 mCompletedTransactions.insert(transactionId);
606 }
607 BufferId bufferId = iter->second->mBufferId;
608 auto bufferIter = mBuffers.find(bufferId);
609 bufferIter->second->mTransactionCount--;
610 if (bufferIter->second->mOwnerCount == 0 &&
611 bufferIter->second->mTransactionCount == 0) {
612 // TODO: handle freebuffer insert fail
Sungtak Leec7f9e2c2018-09-14 16:23:40 -0700613 if (!bufferIter->second->mInvalidated) {
614 mStats.onBufferUnused(bufferIter->second->mAllocSize);
615 mFreeBuffers.insert(bufferId);
616 } else {
617 mStats.onBufferUnused(bufferIter->second->mAllocSize);
618 mStats.onBufferEvicted(bufferIter->second->mAllocSize);
619 mBuffers.erase(bufferIter);
620 mInvalidation.onBufferInvalidated(bufferId, mInvalidationChannel);
621 }
Sungtak Leebbe37b62018-08-29 15:15:48 -0700622 }
623 mTransactions.erase(iter);
624 }
625 }
626 }
627 return true;
628}
629
630bool Accessor::Impl::BufferPool::getFreeBuffer(
631 const std::shared_ptr<BufferPoolAllocator> &allocator,
632 const std::vector<uint8_t> &params, BufferId *pId,
633 const native_handle_t** handle) {
634 auto bufferIt = mFreeBuffers.begin();
635 for (;bufferIt != mFreeBuffers.end(); ++bufferIt) {
636 BufferId bufferId = *bufferIt;
637 if (allocator->compatible(params, mBuffers[bufferId]->mConfig)) {
638 break;
639 }
640 }
641 if (bufferIt != mFreeBuffers.end()) {
642 BufferId id = *bufferIt;
643 mFreeBuffers.erase(bufferIt);
644 mStats.onBufferRecycled(mBuffers[id]->mAllocSize);
645 *handle = mBuffers[id]->handle();
646 *pId = id;
647 ALOGV("recycle a buffer %u %p", id, *handle);
648 return true;
649 }
650 return false;
651}
652
653ResultStatus Accessor::Impl::BufferPool::addNewBuffer(
654 const std::shared_ptr<BufferPoolAllocation> &alloc,
655 const size_t allocSize,
656 const std::vector<uint8_t> &params,
657 BufferId *pId,
658 const native_handle_t** handle) {
659
660 BufferId bufferId = mSeq++;
661 if (mSeq == Connection::SYNC_BUFFERID) {
662 mSeq = 0;
663 }
664 std::unique_ptr<InternalBuffer> buffer =
665 std::make_unique<InternalBuffer>(
666 bufferId, alloc, allocSize, params);
667 if (buffer) {
668 auto res = mBuffers.insert(std::make_pair(
669 bufferId, std::move(buffer)));
670 if (res.second) {
671 mStats.onBufferAllocated(allocSize);
672 *handle = alloc->handle();
673 *pId = bufferId;
674 return ResultStatus::OK;
675 }
676 }
677 return ResultStatus::NO_MEMORY;
678}
679
680void Accessor::Impl::BufferPool::cleanUp(bool clearCache) {
681 if (clearCache || mTimestampUs > mLastCleanUpUs + kCleanUpDurationUs) {
682 mLastCleanUpUs = mTimestampUs;
683 if (mTimestampUs > mLastLogUs + kLogDurationUs) {
684 mLastLogUs = mTimestampUs;
Sungtak Leed3318082018-09-07 15:52:43 -0700685 ALOGD("bufferpool2 %p : %zu(%zu size) total buffers - "
Sungtak Leebbe37b62018-08-29 15:15:48 -0700686 "%zu(%zu size) used buffers - %zu/%zu (recycle/alloc) - "
687 "%zu/%zu (fetch/transfer)",
688 this, mStats.mBuffersCached, mStats.mSizeCached,
689 mStats.mBuffersInUse, mStats.mSizeInUse,
690 mStats.mTotalRecycles, mStats.mTotalAllocations,
691 mStats.mTotalFetches, mStats.mTotalTransfers);
692 }
693 for (auto freeIt = mFreeBuffers.begin(); freeIt != mFreeBuffers.end();) {
694 if (!clearCache && mStats.mSizeCached < kMinAllocBytesForEviction
695 && mBuffers.size() < kMinBufferCountForEviction) {
696 break;
697 }
698 auto it = mBuffers.find(*freeIt);
699 if (it != mBuffers.end() &&
700 it->second->mOwnerCount == 0 && it->second->mTransactionCount == 0) {
701 mStats.onBufferEvicted(it->second->mAllocSize);
702 mBuffers.erase(it);
703 freeIt = mFreeBuffers.erase(freeIt);
704 } else {
705 ++freeIt;
Sungtak Leed3318082018-09-07 15:52:43 -0700706 ALOGW("bufferpool2 inconsistent!");
Sungtak Leebbe37b62018-08-29 15:15:48 -0700707 }
708 }
709 }
710}
711
Sungtak Leec7f9e2c2018-09-14 16:23:40 -0700712void Accessor::Impl::BufferPool::invalidate(
713 bool needsAck, BufferId from, BufferId to,
714 const std::shared_ptr<Accessor::Impl> &impl) {
715 for (auto freeIt = mFreeBuffers.begin(); freeIt != mFreeBuffers.end();) {
716 if (isBufferInRange(from, to, *freeIt)) {
717 auto it = mBuffers.find(*freeIt);
718 if (it != mBuffers.end() &&
719 it->second->mOwnerCount == 0 && it->second->mTransactionCount == 0) {
720 mStats.onBufferEvicted(it->second->mAllocSize);
721 mBuffers.erase(it);
722 freeIt = mFreeBuffers.erase(freeIt);
723 continue;
724 } else {
Sungtak Leed3318082018-09-07 15:52:43 -0700725 ALOGW("bufferpool2 inconsistent!");
Sungtak Leec7f9e2c2018-09-14 16:23:40 -0700726 }
727 }
728 ++freeIt;
729 }
730
731 size_t left = 0;
732 for (auto it = mBuffers.begin(); it != mBuffers.end(); ++it) {
733 if (isBufferInRange(from, to, it->first)) {
734 it->second->invalidate();
735 ++left;
736 }
737 }
738 mInvalidation.onInvalidationRequest(needsAck, from, to, left, mInvalidationChannel, impl);
739}
740
741void Accessor::Impl::BufferPool::flush(const std::shared_ptr<Accessor::Impl> &impl) {
742 BufferId from = mStartSeq;
743 BufferId to = mSeq;
744 mStartSeq = mSeq;
745 // TODO: needsAck params
Sungtak Leed3128382018-11-07 17:30:37 -0800746 ALOGV("buffer invalidation request bp:%u %u %u", mInvalidation.mId, from, to);
Sungtak Leec7f9e2c2018-09-14 16:23:40 -0700747 if (from != to) {
748 invalidate(true, from, to, impl);
749 }
750}
751
752void Accessor::Impl::invalidatorThread(
753 std::map<uint32_t, const std::weak_ptr<Accessor::Impl>> &accessors,
754 std::mutex &mutex,
755 std::condition_variable &cv,
756 bool &ready) {
757 while(true) {
758 std::map<uint32_t, const std::weak_ptr<Accessor::Impl>> copied;
759 {
760 std::unique_lock<std::mutex> lock(mutex);
761 if (!ready) {
762 cv.wait(lock);
763 }
764 copied.insert(accessors.begin(), accessors.end());
765 }
766 std::list<ConnectionId> erased;
767 for (auto it = copied.begin(); it != copied.end(); ++it) {
768 const std::shared_ptr<Accessor::Impl> impl = it->second.lock();
769 if (!impl) {
770 erased.push_back(it->first);
771 } else {
772 impl->handleInvalidateAck();
773 }
774 }
775 {
776 std::unique_lock<std::mutex> lock(mutex);
777 for (auto it = erased.begin(); it != erased.end(); ++it) {
778 accessors.erase(*it);
779 }
780 if (accessors.size() == 0) {
781 ready = false;
782 } else {
783 // prevent draining cpu.
784 lock.unlock();
785 std::this_thread::yield();
786 }
787 }
788 }
789}
790
791Accessor::Impl::AccessorInvalidator::AccessorInvalidator() : mReady(false) {
792 std::thread invalidator(
793 invalidatorThread,
794 std::ref(mAccessors),
795 std::ref(mMutex),
796 std::ref(mCv),
797 std::ref(mReady));
798 invalidator.detach();
799}
800
801void Accessor::Impl::AccessorInvalidator::addAccessor(
802 uint32_t accessorId, const std::weak_ptr<Accessor::Impl> &impl) {
803 bool notify = false;
804 std::unique_lock<std::mutex> lock(mMutex);
805 if (mAccessors.find(accessorId) == mAccessors.end()) {
806 if (!mReady) {
807 mReady = true;
808 notify = true;
809 }
810 mAccessors.insert(std::make_pair(accessorId, impl));
Sungtak Leed3128382018-11-07 17:30:37 -0800811 ALOGV("buffer invalidation added bp:%u %d", accessorId, notify);
Sungtak Leec7f9e2c2018-09-14 16:23:40 -0700812 }
813 lock.unlock();
814 if (notify) {
815 mCv.notify_one();
816 }
817}
818
819void Accessor::Impl::AccessorInvalidator::delAccessor(uint32_t accessorId) {
820 std::lock_guard<std::mutex> lock(mMutex);
821 mAccessors.erase(accessorId);
Sungtak Leed3128382018-11-07 17:30:37 -0800822 ALOGV("buffer invalidation deleted bp:%u", accessorId);
Sungtak Leec7f9e2c2018-09-14 16:23:40 -0700823 if (mAccessors.size() == 0) {
824 mReady = false;
825 }
826}
827
Sungtak Leed3128382018-11-07 17:30:37 -0800828std::unique_ptr<Accessor::Impl::AccessorInvalidator> Accessor::Impl::sInvalidator;
829
830void Accessor::Impl::createInvalidator() {
831 if (!sInvalidator) {
832 sInvalidator = std::make_unique<Accessor::Impl::AccessorInvalidator>();
833 }
834}
Sungtak Leec7f9e2c2018-09-14 16:23:40 -0700835
Sungtak Leebbe37b62018-08-29 15:15:48 -0700836} // namespace implementation
837} // namespace V2_0
838} // namespace bufferpool
839} // namespace media
840} // namespace hardware
841} // namespace android