blob: 84fcca245898e008db6c909ca15164f919216078 [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);
285 ALOGD("Destruction - bufferpool %p "
286 "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);
311 if (it == mAcks.end() || isMessageLater(msgId, it->second)) {
312 mAcks[conId] = msgId;
313 }
314}
315
316void Accessor::Impl::BufferPool::Invalidation::onBufferInvalidated(
317 BufferId bufferId,
318 BufferInvalidationChannel &channel) {
319 for (auto it = mPendings.begin(); it != mPendings.end();) {
Sungtak Leed3128382018-11-07 17:30:37 -0800320 if (it->isInvalidated(bufferId)) {
Sungtak Leec7f9e2c2018-09-14 16:23:40 -0700321 uint32_t msgId = 0;
322 if (it->mNeedsAck) {
323 msgId = ++mInvalidationId;
324 if (msgId == 0) {
325 // wrap happens
326 msgId = ++mInvalidationId;
327 }
328 }
329 channel.postInvalidation(msgId, it->mFrom, it->mTo);
Sungtak Leed3128382018-11-07 17:30:37 -0800330 sInvalidator->addAccessor(mId, it->mImpl);
331 it = mPendings.erase(it);
Sungtak Leec7f9e2c2018-09-14 16:23:40 -0700332 continue;
333 }
334 ++it;
335 }
336}
337
338void Accessor::Impl::BufferPool::Invalidation::onInvalidationRequest(
339 bool needsAck,
340 uint32_t from,
341 uint32_t to,
342 size_t left,
343 BufferInvalidationChannel &channel,
344 const std::shared_ptr<Accessor::Impl> &impl) {
345 if (left == 0) {
346 uint32_t msgId = 0;
347 if (needsAck) {
348 msgId = ++mInvalidationId;
349 if (msgId == 0) {
350 // wrap happens
351 msgId = ++mInvalidationId;
352 }
353 }
Sungtak Leed3128382018-11-07 17:30:37 -0800354 ALOGV("bufferpool invalidation requested and queued");
Sungtak Leec7f9e2c2018-09-14 16:23:40 -0700355 channel.postInvalidation(msgId, from, to);
Sungtak Leed3128382018-11-07 17:30:37 -0800356 sInvalidator->addAccessor(mId, impl);
Sungtak Leec7f9e2c2018-09-14 16:23:40 -0700357 } else {
358 // TODO: sending hint message?
Sungtak Leed3128382018-11-07 17:30:37 -0800359 ALOGV("bufferpool invalidation requested and pending");
Sungtak Leec7f9e2c2018-09-14 16:23:40 -0700360 Pending pending(needsAck, from, to, left, impl);
361 mPendings.push_back(pending);
362 }
363}
364
365void Accessor::Impl::BufferPool::Invalidation::onHandleAck() {
366 if (mInvalidationId != 0) {
367 std::set<int> deads;
368 for (auto it = mAcks.begin(); it != mAcks.end(); ++it) {
369 if (it->second != mInvalidationId) {
Sungtak Leed3128382018-11-07 17:30:37 -0800370 const sp<IObserver> observer = mObservers[it->first];
Sungtak Leec7f9e2c2018-09-14 16:23:40 -0700371 if (observer) {
Sungtak Leed3128382018-11-07 17:30:37 -0800372 ALOGV("connection %lld call observer (%u: %u)",
373 (long long)it->first, it->second, mInvalidationId);
374 Return<void> transResult = observer->onMessage(it->first, mInvalidationId);
375 (void) transResult;
Sungtak Leec7f9e2c2018-09-14 16:23:40 -0700376 } else {
Sungtak Leed3128382018-11-07 17:30:37 -0800377 ALOGV("bufferpool observer died %lld", (long long)it->first);
Sungtak Leec7f9e2c2018-09-14 16:23:40 -0700378 deads.insert(it->first);
379 }
380 }
381 }
382 if (deads.size() > 0) {
383 for (auto it = deads.begin(); it != deads.end(); ++it) {
384 onClose(*it);
385 }
386 }
387 }
388 // All invalidation Ids are synced.
Sungtak Leed3128382018-11-07 17:30:37 -0800389 sInvalidator->delAccessor(mId);
Sungtak Leec7f9e2c2018-09-14 16:23:40 -0700390}
391
Sungtak Leebbe37b62018-08-29 15:15:48 -0700392bool Accessor::Impl::BufferPool::handleOwnBuffer(
393 ConnectionId connectionId, BufferId bufferId) {
394
395 bool added = insert(&mUsingBuffers, connectionId, bufferId);
396 if (added) {
397 auto iter = mBuffers.find(bufferId);
398 iter->second->mOwnerCount++;
399 }
400 insert(&mUsingConnections, bufferId, connectionId);
401 return added;
402}
403
404bool Accessor::Impl::BufferPool::handleReleaseBuffer(
405 ConnectionId connectionId, BufferId bufferId) {
406 bool deleted = erase(&mUsingBuffers, connectionId, bufferId);
407 if (deleted) {
408 auto iter = mBuffers.find(bufferId);
409 iter->second->mOwnerCount--;
410 if (iter->second->mOwnerCount == 0 &&
411 iter->second->mTransactionCount == 0) {
Sungtak Leec7f9e2c2018-09-14 16:23:40 -0700412 if (!iter->second->mInvalidated) {
413 mStats.onBufferUnused(iter->second->mAllocSize);
414 mFreeBuffers.insert(bufferId);
415 } else {
416 mStats.onBufferUnused(iter->second->mAllocSize);
417 mStats.onBufferEvicted(iter->second->mAllocSize);
418 mBuffers.erase(iter);
419 mInvalidation.onBufferInvalidated(bufferId, mInvalidationChannel);
420 }
Sungtak Leebbe37b62018-08-29 15:15:48 -0700421 }
422 }
423 erase(&mUsingConnections, bufferId, connectionId);
424 ALOGV("release buffer %u : %d", bufferId, deleted);
425 return deleted;
426}
427
428bool Accessor::Impl::BufferPool::handleTransferTo(const BufferStatusMessage &message) {
429 auto completed = mCompletedTransactions.find(
430 message.transactionId);
431 if (completed != mCompletedTransactions.end()) {
432 // already completed
433 mCompletedTransactions.erase(completed);
434 return true;
435 }
436 // the buffer should exist and be owned.
437 auto bufferIter = mBuffers.find(message.bufferId);
438 if (bufferIter == mBuffers.end() ||
439 !contains(&mUsingBuffers, message.connectionId, message.bufferId)) {
440 return false;
441 }
442 auto found = mTransactions.find(message.transactionId);
443 if (found != mTransactions.end()) {
444 // transfer_from was received earlier.
445 found->second->mSender = message.connectionId;
446 found->second->mSenderValidated = true;
447 return true;
448 }
449 // TODO: verify there is target connection Id
450 mStats.onBufferSent();
451 mTransactions.insert(std::make_pair(
452 message.transactionId,
453 std::make_unique<TransactionStatus>(message, mTimestampUs)));
454 insert(&mPendingTransactions, message.targetConnectionId,
455 message.transactionId);
456 bufferIter->second->mTransactionCount++;
457 return true;
458}
459
460bool Accessor::Impl::BufferPool::handleTransferFrom(const BufferStatusMessage &message) {
461 auto found = mTransactions.find(message.transactionId);
462 if (found == mTransactions.end()) {
463 // TODO: is it feasible to check ownership here?
464 mStats.onBufferSent();
465 mTransactions.insert(std::make_pair(
466 message.transactionId,
467 std::make_unique<TransactionStatus>(message, mTimestampUs)));
468 insert(&mPendingTransactions, message.connectionId,
469 message.transactionId);
470 auto bufferIter = mBuffers.find(message.bufferId);
471 bufferIter->second->mTransactionCount++;
472 } else {
473 if (message.connectionId == found->second->mReceiver) {
474 found->second->mStatus = BufferStatus::TRANSFER_FROM;
475 }
476 }
477 return true;
478}
479
480bool Accessor::Impl::BufferPool::handleTransferResult(const BufferStatusMessage &message) {
481 auto found = mTransactions.find(message.transactionId);
482 if (found != mTransactions.end()) {
483 bool deleted = erase(&mPendingTransactions, message.connectionId,
484 message.transactionId);
485 if (deleted) {
486 if (!found->second->mSenderValidated) {
487 mCompletedTransactions.insert(message.transactionId);
488 }
489 auto bufferIter = mBuffers.find(message.bufferId);
490 if (message.newStatus == BufferStatus::TRANSFER_OK) {
491 handleOwnBuffer(message.connectionId, message.bufferId);
492 }
493 bufferIter->second->mTransactionCount--;
494 if (bufferIter->second->mOwnerCount == 0
495 && bufferIter->second->mTransactionCount == 0) {
Sungtak Leec7f9e2c2018-09-14 16:23:40 -0700496 if (!bufferIter->second->mInvalidated) {
497 mStats.onBufferUnused(bufferIter->second->mAllocSize);
498 mFreeBuffers.insert(message.bufferId);
499 } else {
500 mStats.onBufferUnused(bufferIter->second->mAllocSize);
501 mStats.onBufferEvicted(bufferIter->second->mAllocSize);
502 mBuffers.erase(bufferIter);
503 mInvalidation.onBufferInvalidated(message.bufferId, mInvalidationChannel);
504 }
Sungtak Leebbe37b62018-08-29 15:15:48 -0700505 }
506 mTransactions.erase(found);
507 }
508 ALOGV("transfer finished %llu %u - %d", (unsigned long long)message.transactionId,
509 message.bufferId, deleted);
510 return deleted;
511 }
512 ALOGV("transfer not found %llu %u", (unsigned long long)message.transactionId,
513 message.bufferId);
514 return false;
515}
516
517void Accessor::Impl::BufferPool::processStatusMessages() {
518 std::vector<BufferStatusMessage> messages;
519 mObserver.getBufferStatusChanges(messages);
520 mTimestampUs = getTimestampNow();
521 for (BufferStatusMessage& message: messages) {
522 bool ret = false;
523 switch (message.newStatus) {
524 case BufferStatus::NOT_USED:
525 ret = handleReleaseBuffer(
526 message.connectionId, message.bufferId);
527 break;
528 case BufferStatus::USED:
529 // not happening
530 break;
531 case BufferStatus::TRANSFER_TO:
532 ret = handleTransferTo(message);
533 break;
534 case BufferStatus::TRANSFER_FROM:
535 ret = handleTransferFrom(message);
536 break;
537 case BufferStatus::TRANSFER_TIMEOUT:
538 // TODO
539 break;
540 case BufferStatus::TRANSFER_LOST:
541 // TODO
542 break;
543 case BufferStatus::TRANSFER_FETCH:
544 // not happening
545 break;
546 case BufferStatus::TRANSFER_OK:
547 case BufferStatus::TRANSFER_ERROR:
548 ret = handleTransferResult(message);
549 break;
Sungtak Leed491f1f2018-10-05 15:56:56 -0700550 case BufferStatus::INVALIDATION_ACK:
Sungtak Leec7f9e2c2018-09-14 16:23:40 -0700551 mInvalidation.onAck(message.connectionId, message.bufferId);
Sungtak Leed3128382018-11-07 17:30:37 -0800552 ret = true;
Sungtak Leed491f1f2018-10-05 15:56:56 -0700553 break;
Sungtak Leebbe37b62018-08-29 15:15:48 -0700554 }
555 if (ret == false) {
556 ALOGW("buffer status message processing failure - message : %d connection : %lld",
557 message.newStatus, (long long)message.connectionId);
558 }
559 }
560 messages.clear();
561}
562
563bool Accessor::Impl::BufferPool::handleClose(ConnectionId connectionId) {
564 // Cleaning buffers
565 auto buffers = mUsingBuffers.find(connectionId);
566 if (buffers != mUsingBuffers.end()) {
567 for (const BufferId& bufferId : buffers->second) {
568 bool deleted = erase(&mUsingConnections, bufferId, connectionId);
569 if (deleted) {
570 auto bufferIter = mBuffers.find(bufferId);
571 bufferIter->second->mOwnerCount--;
572 if (bufferIter->second->mOwnerCount == 0 &&
573 bufferIter->second->mTransactionCount == 0) {
574 // TODO: handle freebuffer insert fail
Sungtak Leec7f9e2c2018-09-14 16:23:40 -0700575 if (!bufferIter->second->mInvalidated) {
576 mStats.onBufferUnused(bufferIter->second->mAllocSize);
577 mFreeBuffers.insert(bufferId);
578 } else {
579 mStats.onBufferUnused(bufferIter->second->mAllocSize);
580 mStats.onBufferEvicted(bufferIter->second->mAllocSize);
581 mBuffers.erase(bufferIter);
582 mInvalidation.onBufferInvalidated(bufferId, mInvalidationChannel);
583 }
Sungtak Leebbe37b62018-08-29 15:15:48 -0700584 }
585 }
586 }
587 mUsingBuffers.erase(buffers);
588 }
589
590 // Cleaning transactions
591 auto pending = mPendingTransactions.find(connectionId);
592 if (pending != mPendingTransactions.end()) {
593 for (const TransactionId& transactionId : pending->second) {
594 auto iter = mTransactions.find(transactionId);
595 if (iter != mTransactions.end()) {
596 if (!iter->second->mSenderValidated) {
597 mCompletedTransactions.insert(transactionId);
598 }
599 BufferId bufferId = iter->second->mBufferId;
600 auto bufferIter = mBuffers.find(bufferId);
601 bufferIter->second->mTransactionCount--;
602 if (bufferIter->second->mOwnerCount == 0 &&
603 bufferIter->second->mTransactionCount == 0) {
604 // TODO: handle freebuffer insert fail
Sungtak Leec7f9e2c2018-09-14 16:23:40 -0700605 if (!bufferIter->second->mInvalidated) {
606 mStats.onBufferUnused(bufferIter->second->mAllocSize);
607 mFreeBuffers.insert(bufferId);
608 } else {
609 mStats.onBufferUnused(bufferIter->second->mAllocSize);
610 mStats.onBufferEvicted(bufferIter->second->mAllocSize);
611 mBuffers.erase(bufferIter);
612 mInvalidation.onBufferInvalidated(bufferId, mInvalidationChannel);
613 }
Sungtak Leebbe37b62018-08-29 15:15:48 -0700614 }
615 mTransactions.erase(iter);
616 }
617 }
618 }
619 return true;
620}
621
622bool Accessor::Impl::BufferPool::getFreeBuffer(
623 const std::shared_ptr<BufferPoolAllocator> &allocator,
624 const std::vector<uint8_t> &params, BufferId *pId,
625 const native_handle_t** handle) {
626 auto bufferIt = mFreeBuffers.begin();
627 for (;bufferIt != mFreeBuffers.end(); ++bufferIt) {
628 BufferId bufferId = *bufferIt;
629 if (allocator->compatible(params, mBuffers[bufferId]->mConfig)) {
630 break;
631 }
632 }
633 if (bufferIt != mFreeBuffers.end()) {
634 BufferId id = *bufferIt;
635 mFreeBuffers.erase(bufferIt);
636 mStats.onBufferRecycled(mBuffers[id]->mAllocSize);
637 *handle = mBuffers[id]->handle();
638 *pId = id;
639 ALOGV("recycle a buffer %u %p", id, *handle);
640 return true;
641 }
642 return false;
643}
644
645ResultStatus Accessor::Impl::BufferPool::addNewBuffer(
646 const std::shared_ptr<BufferPoolAllocation> &alloc,
647 const size_t allocSize,
648 const std::vector<uint8_t> &params,
649 BufferId *pId,
650 const native_handle_t** handle) {
651
652 BufferId bufferId = mSeq++;
653 if (mSeq == Connection::SYNC_BUFFERID) {
654 mSeq = 0;
655 }
656 std::unique_ptr<InternalBuffer> buffer =
657 std::make_unique<InternalBuffer>(
658 bufferId, alloc, allocSize, params);
659 if (buffer) {
660 auto res = mBuffers.insert(std::make_pair(
661 bufferId, std::move(buffer)));
662 if (res.second) {
663 mStats.onBufferAllocated(allocSize);
664 *handle = alloc->handle();
665 *pId = bufferId;
666 return ResultStatus::OK;
667 }
668 }
669 return ResultStatus::NO_MEMORY;
670}
671
672void Accessor::Impl::BufferPool::cleanUp(bool clearCache) {
673 if (clearCache || mTimestampUs > mLastCleanUpUs + kCleanUpDurationUs) {
674 mLastCleanUpUs = mTimestampUs;
675 if (mTimestampUs > mLastLogUs + kLogDurationUs) {
676 mLastLogUs = mTimestampUs;
677 ALOGD("bufferpool %p : %zu(%zu size) total buffers - "
678 "%zu(%zu size) used buffers - %zu/%zu (recycle/alloc) - "
679 "%zu/%zu (fetch/transfer)",
680 this, mStats.mBuffersCached, mStats.mSizeCached,
681 mStats.mBuffersInUse, mStats.mSizeInUse,
682 mStats.mTotalRecycles, mStats.mTotalAllocations,
683 mStats.mTotalFetches, mStats.mTotalTransfers);
684 }
685 for (auto freeIt = mFreeBuffers.begin(); freeIt != mFreeBuffers.end();) {
686 if (!clearCache && mStats.mSizeCached < kMinAllocBytesForEviction
687 && mBuffers.size() < kMinBufferCountForEviction) {
688 break;
689 }
690 auto it = mBuffers.find(*freeIt);
691 if (it != mBuffers.end() &&
692 it->second->mOwnerCount == 0 && it->second->mTransactionCount == 0) {
693 mStats.onBufferEvicted(it->second->mAllocSize);
694 mBuffers.erase(it);
695 freeIt = mFreeBuffers.erase(freeIt);
696 } else {
697 ++freeIt;
698 ALOGW("bufferpool inconsistent!");
699 }
700 }
701 }
702}
703
Sungtak Leec7f9e2c2018-09-14 16:23:40 -0700704void Accessor::Impl::BufferPool::invalidate(
705 bool needsAck, BufferId from, BufferId to,
706 const std::shared_ptr<Accessor::Impl> &impl) {
707 for (auto freeIt = mFreeBuffers.begin(); freeIt != mFreeBuffers.end();) {
708 if (isBufferInRange(from, to, *freeIt)) {
709 auto it = mBuffers.find(*freeIt);
710 if (it != mBuffers.end() &&
711 it->second->mOwnerCount == 0 && it->second->mTransactionCount == 0) {
712 mStats.onBufferEvicted(it->second->mAllocSize);
713 mBuffers.erase(it);
714 freeIt = mFreeBuffers.erase(freeIt);
715 continue;
716 } else {
717 ALOGW("bufferpool inconsistent!");
718 }
719 }
720 ++freeIt;
721 }
722
723 size_t left = 0;
724 for (auto it = mBuffers.begin(); it != mBuffers.end(); ++it) {
725 if (isBufferInRange(from, to, it->first)) {
726 it->second->invalidate();
727 ++left;
728 }
729 }
730 mInvalidation.onInvalidationRequest(needsAck, from, to, left, mInvalidationChannel, impl);
731}
732
733void Accessor::Impl::BufferPool::flush(const std::shared_ptr<Accessor::Impl> &impl) {
734 BufferId from = mStartSeq;
735 BufferId to = mSeq;
736 mStartSeq = mSeq;
737 // TODO: needsAck params
Sungtak Leed3128382018-11-07 17:30:37 -0800738 ALOGV("buffer invalidation request bp:%u %u %u", mInvalidation.mId, from, to);
Sungtak Leec7f9e2c2018-09-14 16:23:40 -0700739 if (from != to) {
740 invalidate(true, from, to, impl);
741 }
742}
743
744void Accessor::Impl::invalidatorThread(
745 std::map<uint32_t, const std::weak_ptr<Accessor::Impl>> &accessors,
746 std::mutex &mutex,
747 std::condition_variable &cv,
748 bool &ready) {
749 while(true) {
750 std::map<uint32_t, const std::weak_ptr<Accessor::Impl>> copied;
751 {
752 std::unique_lock<std::mutex> lock(mutex);
753 if (!ready) {
754 cv.wait(lock);
755 }
756 copied.insert(accessors.begin(), accessors.end());
757 }
758 std::list<ConnectionId> erased;
759 for (auto it = copied.begin(); it != copied.end(); ++it) {
760 const std::shared_ptr<Accessor::Impl> impl = it->second.lock();
761 if (!impl) {
762 erased.push_back(it->first);
763 } else {
764 impl->handleInvalidateAck();
765 }
766 }
767 {
768 std::unique_lock<std::mutex> lock(mutex);
769 for (auto it = erased.begin(); it != erased.end(); ++it) {
770 accessors.erase(*it);
771 }
772 if (accessors.size() == 0) {
773 ready = false;
774 } else {
775 // prevent draining cpu.
776 lock.unlock();
777 std::this_thread::yield();
778 }
779 }
780 }
781}
782
783Accessor::Impl::AccessorInvalidator::AccessorInvalidator() : mReady(false) {
784 std::thread invalidator(
785 invalidatorThread,
786 std::ref(mAccessors),
787 std::ref(mMutex),
788 std::ref(mCv),
789 std::ref(mReady));
790 invalidator.detach();
791}
792
793void Accessor::Impl::AccessorInvalidator::addAccessor(
794 uint32_t accessorId, const std::weak_ptr<Accessor::Impl> &impl) {
795 bool notify = false;
796 std::unique_lock<std::mutex> lock(mMutex);
797 if (mAccessors.find(accessorId) == mAccessors.end()) {
798 if (!mReady) {
799 mReady = true;
800 notify = true;
801 }
802 mAccessors.insert(std::make_pair(accessorId, impl));
Sungtak Leed3128382018-11-07 17:30:37 -0800803 ALOGV("buffer invalidation added bp:%u %d", accessorId, notify);
Sungtak Leec7f9e2c2018-09-14 16:23:40 -0700804 }
805 lock.unlock();
806 if (notify) {
807 mCv.notify_one();
808 }
809}
810
811void Accessor::Impl::AccessorInvalidator::delAccessor(uint32_t accessorId) {
812 std::lock_guard<std::mutex> lock(mMutex);
813 mAccessors.erase(accessorId);
Sungtak Leed3128382018-11-07 17:30:37 -0800814 ALOGV("buffer invalidation deleted bp:%u", accessorId);
Sungtak Leec7f9e2c2018-09-14 16:23:40 -0700815 if (mAccessors.size() == 0) {
816 mReady = false;
817 }
818}
819
Sungtak Leed3128382018-11-07 17:30:37 -0800820std::unique_ptr<Accessor::Impl::AccessorInvalidator> Accessor::Impl::sInvalidator;
821
822void Accessor::Impl::createInvalidator() {
823 if (!sInvalidator) {
824 sInvalidator = std::make_unique<Accessor::Impl::AccessorInvalidator>();
825 }
826}
Sungtak Leec7f9e2c2018-09-14 16:23:40 -0700827
Sungtak Leebbe37b62018-08-29 15:15:48 -0700828} // namespace implementation
829} // namespace V2_0
830} // namespace bufferpool
831} // namespace media
832} // namespace hardware
833} // namespace android