blob: 6b034946214305681a6aaee03d17829e93feed89 [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#ifndef ANDROID_HARDWARE_MEDIA_BUFFERPOOL_V2_0_ACCESSORIMPL_H
18#define ANDROID_HARDWARE_MEDIA_BUFFERPOOL_V2_0_ACCESSORIMPL_H
19
20#include <map>
21#include <set>
Sungtak Leec7f9e2c2018-09-14 16:23:40 -070022#include <condition_variable>
Sungtak Leebbe37b62018-08-29 15:15:48 -070023#include "Accessor.h"
24
25namespace android {
26namespace hardware {
27namespace media {
28namespace bufferpool {
29namespace V2_0 {
30namespace implementation {
31
32struct InternalBuffer;
33struct TransactionStatus;
34
35/**
36 * An implementation of a buffer pool accessor(or a buffer pool implementation.) */
Sungtak Leec7f9e2c2018-09-14 16:23:40 -070037class Accessor::Impl
38 : public std::enable_shared_from_this<Accessor::Impl> {
Sungtak Leebbe37b62018-08-29 15:15:48 -070039public:
40 Impl(const std::shared_ptr<BufferPoolAllocator> &allocator);
41
42 ~Impl();
43
44 ResultStatus connect(
Sungtak Leec7f9e2c2018-09-14 16:23:40 -070045 const sp<Accessor> &accessor, const sp<IObserver> &observer,
46 sp<Connection> *connection,
47 ConnectionId *pConnectionId,
48 uint32_t *pMsgId,
49 const StatusDescriptor** statusDescPtr,
50 const InvalidationDescriptor** invDescPtr);
Sungtak Leebbe37b62018-08-29 15:15:48 -070051
52 ResultStatus close(ConnectionId connectionId);
53
54 ResultStatus allocate(ConnectionId connectionId,
55 const std::vector<uint8_t>& params,
56 BufferId *bufferId,
57 const native_handle_t** handle);
58
59 ResultStatus fetch(ConnectionId connectionId,
60 TransactionId transactionId,
61 BufferId bufferId,
62 const native_handle_t** handle);
63
Sungtak Leec7f9e2c2018-09-14 16:23:40 -070064 void flush();
65
Sungtak Leebbe37b62018-08-29 15:15:48 -070066 void cleanUp(bool clearCache);
67
Sungtak Leec7f9e2c2018-09-14 16:23:40 -070068 bool isValid();
69
70 void handleInvalidateAck();
71
Sungtak Leebbe37b62018-08-29 15:15:48 -070072private:
73 // ConnectionId = pid : (timestamp_created + seqId)
74 // in order to guarantee uniqueness for each connection
75 static uint32_t sSeqId;
76 static int32_t sPid;
77
78 const std::shared_ptr<BufferPoolAllocator> mAllocator;
79
80 /**
81 * Buffer pool implementation.
82 *
83 * Handles buffer status messages. Handles buffer allocation/recycling.
84 * Handles buffer transfer between buffer pool clients.
85 */
86 struct BufferPool {
87 private:
88 std::mutex mMutex;
89 int64_t mTimestampUs;
90 int64_t mLastCleanUpUs;
91 int64_t mLastLogUs;
92 BufferId mSeq;
Sungtak Leec7f9e2c2018-09-14 16:23:40 -070093 BufferId mStartSeq;
94 bool mValid;
Sungtak Leebbe37b62018-08-29 15:15:48 -070095 BufferStatusObserver mObserver;
Sungtak Leec7f9e2c2018-09-14 16:23:40 -070096 BufferInvalidationChannel mInvalidationChannel;
Sungtak Leebbe37b62018-08-29 15:15:48 -070097
98 std::map<ConnectionId, std::set<BufferId>> mUsingBuffers;
99 std::map<BufferId, std::set<ConnectionId>> mUsingConnections;
100
101 std::map<ConnectionId, std::set<TransactionId>> mPendingTransactions;
102 // Transactions completed before TRANSFER_TO message arrival.
103 // Fetch does not occur for the transactions.
104 // Only transaction id is kept for the transactions in short duration.
105 std::set<TransactionId> mCompletedTransactions;
106 // Currently active(pending) transations' status & information.
107 std::map<TransactionId, std::unique_ptr<TransactionStatus>>
108 mTransactions;
109
110 std::map<BufferId, std::unique_ptr<InternalBuffer>> mBuffers;
111 std::set<BufferId> mFreeBuffers;
112
Sungtak Leec7f9e2c2018-09-14 16:23:40 -0700113 struct Invalidation {
114 static std::atomic<std::uint32_t> sSeqId;
115
116 struct Pending {
117 bool mNeedsAck;
118 uint32_t mFrom;
119 uint32_t mTo;
120 size_t mLeft;
121 const std::weak_ptr<Accessor::Impl> mImpl;
122 Pending(bool needsAck, uint32_t from, uint32_t to, size_t left,
123 const std::shared_ptr<Accessor::Impl> &impl)
124 : mNeedsAck(needsAck),
125 mFrom(from),
126 mTo(to),
127 mLeft(left),
128 mImpl(impl)
129 {}
130
131 bool invalidate(uint32_t bufferId) {
132 return isBufferInRange(mFrom, mTo, bufferId) && --mLeft == 0;
133 }
134 };
135
136 std::list<Pending> mPendings;
137 std::map<ConnectionId, uint32_t> mAcks;
138 std::map<ConnectionId, const wp<IObserver>> mObservers;
139 uint32_t mInvalidationId;
140 uint32_t mId;
141
142 Invalidation() : mInvalidationId(0), mId(sSeqId.fetch_add(1)) {}
143
144 void onConnect(ConnectionId conId, const sp<IObserver> &observer);
145
146 void onClose(ConnectionId conId);
147
148 void onAck(ConnectionId conId, uint32_t msgId);
149
150 void onBufferInvalidated(
151 BufferId bufferId,
152 BufferInvalidationChannel &channel);
153
154 void onInvalidationRequest(
155 bool needsAck, uint32_t from, uint32_t to, size_t left,
156 BufferInvalidationChannel &channel,
157 const std::shared_ptr<Accessor::Impl> &impl);
158
159 void onHandleAck();
160 } mInvalidation;
Sungtak Leebbe37b62018-08-29 15:15:48 -0700161 /// Buffer pool statistics which tracks allocation and transfer statistics.
162 struct Stats {
163 /// Total size of allocations which are used or available to use.
164 /// (bytes or pixels)
165 size_t mSizeCached;
166 /// # of cached buffers which are used or available to use.
167 size_t mBuffersCached;
168 /// Total size of allocations which are currently used. (bytes or pixels)
169 size_t mSizeInUse;
170 /// # of currently used buffers
171 size_t mBuffersInUse;
172
173 /// # of allocations called on bufferpool. (# of fetched from BlockPool)
174 size_t mTotalAllocations;
175 /// # of allocations that were served from the cache.
176 /// (# of allocator alloc prevented)
177 size_t mTotalRecycles;
178 /// # of buffer transfers initiated.
179 size_t mTotalTransfers;
180 /// # of transfers that had to be fetched.
181 size_t mTotalFetches;
182
183 Stats()
184 : mSizeCached(0), mBuffersCached(0), mSizeInUse(0), mBuffersInUse(0),
185 mTotalAllocations(0), mTotalRecycles(0), mTotalTransfers(0), mTotalFetches(0) {}
186
187 /// A new buffer is allocated on an allocation request.
188 void onBufferAllocated(size_t allocSize) {
189 mSizeCached += allocSize;
190 mBuffersCached++;
191
192 mSizeInUse += allocSize;
193 mBuffersInUse++;
194
195 mTotalAllocations++;
196 }
197
198 /// A buffer is evicted and destroyed.
199 void onBufferEvicted(size_t allocSize) {
200 mSizeCached -= allocSize;
201 mBuffersCached--;
202 }
203
204 /// A buffer is recycled on an allocation request.
205 void onBufferRecycled(size_t allocSize) {
206 mSizeInUse += allocSize;
207 mBuffersInUse++;
208
209 mTotalAllocations++;
210 mTotalRecycles++;
211 }
212
213 /// A buffer is available to be recycled.
214 void onBufferUnused(size_t allocSize) {
215 mSizeInUse -= allocSize;
216 mBuffersInUse--;
217 }
218
219 /// A buffer transfer is initiated.
220 void onBufferSent() {
221 mTotalTransfers++;
222 }
223
224 /// A buffer fetch is invoked by a buffer transfer.
225 void onBufferFetched() {
226 mTotalFetches++;
227 }
228 } mStats;
229
Sungtak Leec7f9e2c2018-09-14 16:23:40 -0700230 bool isValid() {
231 return mValid;
232 }
233
234 void invalidate(bool needsAck, BufferId from, BufferId to,
235 const std::shared_ptr<Accessor::Impl> &impl);
236
Sungtak Leebbe37b62018-08-29 15:15:48 -0700237 public:
238 /** Creates a buffer pool. */
239 BufferPool();
240
241 /** Destroys a buffer pool. */
242 ~BufferPool();
243
244 /**
245 * Processes all pending buffer status messages, and returns the result.
246 * Each status message is handled by methods with 'handle' prefix.
247 */
248 void processStatusMessages();
249
250 /**
251 * Handles a buffer being owned by a connection.
252 *
253 * @param connectionId the id of the buffer owning connection.
254 * @param bufferId the id of the buffer.
255 *
256 * @return {@code true} when the buffer is owned,
257 * {@code false} otherwise.
258 */
259 bool handleOwnBuffer(ConnectionId connectionId, BufferId bufferId);
260
261 /**
262 * Handles a buffer being released by a connection.
263 *
264 * @param connectionId the id of the buffer owning connection.
265 * @param bufferId the id of the buffer.
266 *
267 * @return {@code true} when the buffer ownership is released,
268 * {@code false} otherwise.
269 */
270 bool handleReleaseBuffer(ConnectionId connectionId, BufferId bufferId);
271
272 /**
273 * Handles a transfer transaction start message from the sender.
274 *
275 * @param message a buffer status message for the transaction.
276 *
277 * @result {@code true} when transfer_to message is acknowledged,
278 * {@code false} otherwise.
279 */
280 bool handleTransferTo(const BufferStatusMessage &message);
281
282 /**
283 * Handles a transfer transaction being acked by the receiver.
284 *
285 * @param message a buffer status message for the transaction.
286 *
287 * @result {@code true} when transfer_from message is acknowledged,
288 * {@code false} otherwise.
289 */
290 bool handleTransferFrom(const BufferStatusMessage &message);
291
292 /**
293 * Handles a transfer transaction result message from the receiver.
294 *
295 * @param message a buffer status message for the transaction.
296 *
297 * @result {@code true} when the exisitng transaction is finished,
298 * {@code false} otherwise.
299 */
300 bool handleTransferResult(const BufferStatusMessage &message);
301
302 /**
303 * Handles a connection being closed, and returns the result. All the
304 * buffers and transactions owned by the connection will be cleaned up.
305 * The related FMQ will be cleaned up too.
306 *
307 * @param connectionId the id of the connection.
308 *
309 * @result {@code true} when the connection existed,
310 * {@code false} otherwise.
311 */
312 bool handleClose(ConnectionId connectionId);
313
314 /**
315 * Recycles a existing free buffer if it is possible.
316 *
317 * @param allocator the buffer allocator
318 * @param params the allocation parameters.
319 * @param pId the id of the recycled buffer.
320 * @param handle the native handle of the recycled buffer.
321 *
322 * @return {@code true} when a buffer is recycled, {@code false}
323 * otherwise.
324 */
325 bool getFreeBuffer(
326 const std::shared_ptr<BufferPoolAllocator> &allocator,
327 const std::vector<uint8_t> &params,
328 BufferId *pId, const native_handle_t **handle);
329
330 /**
331 * Adds a newly allocated buffer to bufferpool.
332 *
333 * @param alloc the newly allocated buffer.
334 * @param allocSize the size of the newly allocated buffer.
335 * @param params the allocation parameters.
336 * @param pId the buffer id for the newly allocated buffer.
337 * @param handle the native handle for the newly allocated buffer.
338 *
339 * @return OK when an allocation is successfully allocated.
340 * NO_MEMORY when there is no memory.
341 * CRITICAL_ERROR otherwise.
342 */
343 ResultStatus addNewBuffer(
344 const std::shared_ptr<BufferPoolAllocation> &alloc,
345 const size_t allocSize,
346 const std::vector<uint8_t> &params,
347 BufferId *pId,
348 const native_handle_t **handle);
349
350 /**
351 * Processes pending buffer status messages and performs periodic cache
352 * cleaning.
353 *
354 * @param clearCache if clearCache is true, it frees all buffers
355 * waiting to be recycled.
356 */
357 void cleanUp(bool clearCache = false);
358
Sungtak Leec7f9e2c2018-09-14 16:23:40 -0700359 /**
360 * Processes pending buffer status messages and invalidate all current
361 * free buffers. Active buffers are invalidated after being inactive.
362 */
363 void flush(const std::shared_ptr<Accessor::Impl> &impl);
364
Sungtak Leebbe37b62018-08-29 15:15:48 -0700365 friend class Accessor::Impl;
366 } mBufferPool;
Sungtak Leec7f9e2c2018-09-14 16:23:40 -0700367
368 struct AccessorInvalidator {
369 std::map<uint32_t, const std::weak_ptr<Accessor::Impl>> mAccessors;
370 std::mutex mMutex;
371 std::condition_variable mCv;
372 bool mReady;
373
374 AccessorInvalidator();
375 void addAccessor(uint32_t accessorId, const std::weak_ptr<Accessor::Impl> &impl);
376 void delAccessor(uint32_t accessorId);
377 };
378
379 static AccessorInvalidator sInvalidator;
380
381 static void invalidatorThread(
382 std::map<uint32_t, const std::weak_ptr<Accessor::Impl>> &accessors,
383 std::mutex &mutex,
384 std::condition_variable &cv,
385 bool &ready);
Sungtak Leebbe37b62018-08-29 15:15:48 -0700386};
387
388} // namespace implementation
389} // namespace V2_0
390} // namespace ufferpool
391} // namespace media
392} // namespace hardware
393} // namespace android
394
395#endif // ANDROID_HARDWARE_MEDIA_BUFFERPOOL_V2_0_ACCESSORIMPL_H