blob: 84cb6854b0d750e5abe0cd0e081efcfca7bdae5f [file] [log] [blame]
Sungtak Leed79b6da2018-11-12 17:52:17 -08001/*
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_V1_0_ACCESSORIMPL_H
18#define ANDROID_HARDWARE_MEDIA_BUFFERPOOL_V1_0_ACCESSORIMPL_H
19
20#include <map>
21#include <set>
22#include "Accessor.h"
23
24namespace android {
25namespace hardware {
26namespace media {
27namespace bufferpool {
28namespace V1_0 {
29namespace implementation {
30
31struct InternalBuffer;
32struct TransactionStatus;
33
34/**
35 * An implementation of a buffer pool accessor(or a buffer pool implementation.) */
36class Accessor::Impl {
37public:
38 Impl(const std::shared_ptr<BufferPoolAllocator> &allocator);
39
40 ~Impl();
41
42 ResultStatus connect(
43 const sp<Accessor> &accessor, sp<Connection> *connection,
44 ConnectionId *pConnectionId, const QueueDescriptor** fmqDescPtr);
45
46 ResultStatus close(ConnectionId connectionId);
47
48 ResultStatus allocate(ConnectionId connectionId,
49 const std::vector<uint8_t>& params,
50 BufferId *bufferId,
51 const native_handle_t** handle);
52
53 ResultStatus fetch(ConnectionId connectionId,
54 TransactionId transactionId,
55 BufferId bufferId,
56 const native_handle_t** handle);
57
58 void cleanUp(bool clearCache);
59
60private:
61 // ConnectionId = pid : (timestamp_created + seqId)
62 // in order to guarantee uniqueness for each connection
63 static uint32_t sSeqId;
64 static int32_t sPid;
65
66 const std::shared_ptr<BufferPoolAllocator> mAllocator;
67
68 /**
69 * Buffer pool implementation.
70 *
71 * Handles buffer status messages. Handles buffer allocation/recycling.
72 * Handles buffer transfer between buffer pool clients.
73 */
74 struct BufferPool {
75 private:
76 std::mutex mMutex;
77 int64_t mTimestampUs;
78 int64_t mLastCleanUpUs;
79 int64_t mLastLogUs;
80 BufferId mSeq;
81 BufferStatusObserver mObserver;
82
83 std::map<ConnectionId, std::set<BufferId>> mUsingBuffers;
84 std::map<BufferId, std::set<ConnectionId>> mUsingConnections;
85
86 std::map<ConnectionId, std::set<TransactionId>> mPendingTransactions;
87 // Transactions completed before TRANSFER_TO message arrival.
88 // Fetch does not occur for the transactions.
89 // Only transaction id is kept for the transactions in short duration.
90 std::set<TransactionId> mCompletedTransactions;
91 // Currently active(pending) transations' status & information.
92 std::map<TransactionId, std::unique_ptr<TransactionStatus>>
93 mTransactions;
94
95 std::map<BufferId, std::unique_ptr<InternalBuffer>> mBuffers;
96 std::set<BufferId> mFreeBuffers;
Sungtak Leeccc32cb2019-08-20 18:07:54 -070097 std::set<ConnectionId> mConnectionIds;
Sungtak Leed79b6da2018-11-12 17:52:17 -080098
99 /// Buffer pool statistics which tracks allocation and transfer statistics.
100 struct Stats {
101 /// Total size of allocations which are used or available to use.
102 /// (bytes or pixels)
103 size_t mSizeCached;
104 /// # of cached buffers which are used or available to use.
105 size_t mBuffersCached;
106 /// Total size of allocations which are currently used. (bytes or pixels)
107 size_t mSizeInUse;
108 /// # of currently used buffers
109 size_t mBuffersInUse;
110
111 /// # of allocations called on bufferpool. (# of fetched from BlockPool)
112 size_t mTotalAllocations;
113 /// # of allocations that were served from the cache.
114 /// (# of allocator alloc prevented)
115 size_t mTotalRecycles;
116 /// # of buffer transfers initiated.
117 size_t mTotalTransfers;
118 /// # of transfers that had to be fetched.
119 size_t mTotalFetches;
120
121 Stats()
122 : mSizeCached(0), mBuffersCached(0), mSizeInUse(0), mBuffersInUse(0),
123 mTotalAllocations(0), mTotalRecycles(0), mTotalTransfers(0), mTotalFetches(0) {}
124
125 /// A new buffer is allocated on an allocation request.
126 void onBufferAllocated(size_t allocSize) {
127 mSizeCached += allocSize;
128 mBuffersCached++;
129
130 mSizeInUse += allocSize;
131 mBuffersInUse++;
132
133 mTotalAllocations++;
134 }
135
136 /// A buffer is evicted and destroyed.
137 void onBufferEvicted(size_t allocSize) {
138 mSizeCached -= allocSize;
139 mBuffersCached--;
140 }
141
142 /// A buffer is recycled on an allocation request.
143 void onBufferRecycled(size_t allocSize) {
144 mSizeInUse += allocSize;
145 mBuffersInUse++;
146
147 mTotalAllocations++;
148 mTotalRecycles++;
149 }
150
151 /// A buffer is available to be recycled.
152 void onBufferUnused(size_t allocSize) {
153 mSizeInUse -= allocSize;
154 mBuffersInUse--;
155 }
156
157 /// A buffer transfer is initiated.
158 void onBufferSent() {
159 mTotalTransfers++;
160 }
161
162 /// A buffer fetch is invoked by a buffer transfer.
163 void onBufferFetched() {
164 mTotalFetches++;
165 }
166 } mStats;
167
168 public:
169 /** Creates a buffer pool. */
170 BufferPool();
171
172 /** Destroys a buffer pool. */
173 ~BufferPool();
174
175 /**
176 * Processes all pending buffer status messages, and returns the result.
177 * Each status message is handled by methods with 'handle' prefix.
178 */
179 void processStatusMessages();
180
181 /**
182 * Handles a buffer being owned by a connection.
183 *
184 * @param connectionId the id of the buffer owning connection.
185 * @param bufferId the id of the buffer.
186 *
187 * @return {@code true} when the buffer is owned,
188 * {@code false} otherwise.
189 */
190 bool handleOwnBuffer(ConnectionId connectionId, BufferId bufferId);
191
192 /**
193 * Handles a buffer being released by a connection.
194 *
195 * @param connectionId the id of the buffer owning connection.
196 * @param bufferId the id of the buffer.
197 *
198 * @return {@code true} when the buffer ownership is released,
199 * {@code false} otherwise.
200 */
201 bool handleReleaseBuffer(ConnectionId connectionId, BufferId bufferId);
202
203 /**
204 * Handles a transfer transaction start message from the sender.
205 *
206 * @param message a buffer status message for the transaction.
207 *
208 * @result {@code true} when transfer_to message is acknowledged,
209 * {@code false} otherwise.
210 */
211 bool handleTransferTo(const BufferStatusMessage &message);
212
213 /**
214 * Handles a transfer transaction being acked by the receiver.
215 *
216 * @param message a buffer status message for the transaction.
217 *
218 * @result {@code true} when transfer_from message is acknowledged,
219 * {@code false} otherwise.
220 */
221 bool handleTransferFrom(const BufferStatusMessage &message);
222
223 /**
224 * Handles a transfer transaction result message from the receiver.
225 *
226 * @param message a buffer status message for the transaction.
227 *
228 * @result {@code true} when the exisitng transaction is finished,
229 * {@code false} otherwise.
230 */
231 bool handleTransferResult(const BufferStatusMessage &message);
232
233 /**
234 * Handles a connection being closed, and returns the result. All the
235 * buffers and transactions owned by the connection will be cleaned up.
236 * The related FMQ will be cleaned up too.
237 *
238 * @param connectionId the id of the connection.
239 *
240 * @result {@code true} when the connection existed,
241 * {@code false} otherwise.
242 */
243 bool handleClose(ConnectionId connectionId);
244
245 /**
246 * Recycles a existing free buffer if it is possible.
247 *
248 * @param allocator the buffer allocator
249 * @param params the allocation parameters.
250 * @param pId the id of the recycled buffer.
251 * @param handle the native handle of the recycled buffer.
252 *
253 * @return {@code true} when a buffer is recycled, {@code false}
254 * otherwise.
255 */
256 bool getFreeBuffer(
257 const std::shared_ptr<BufferPoolAllocator> &allocator,
258 const std::vector<uint8_t> &params,
259 BufferId *pId, const native_handle_t **handle);
260
261 /**
262 * Adds a newly allocated buffer to bufferpool.
263 *
264 * @param alloc the newly allocated buffer.
265 * @param allocSize the size of the newly allocated buffer.
266 * @param params the allocation parameters.
267 * @param pId the buffer id for the newly allocated buffer.
268 * @param handle the native handle for the newly allocated buffer.
269 *
270 * @return OK when an allocation is successfully allocated.
271 * NO_MEMORY when there is no memory.
272 * CRITICAL_ERROR otherwise.
273 */
274 ResultStatus addNewBuffer(
275 const std::shared_ptr<BufferPoolAllocation> &alloc,
276 const size_t allocSize,
277 const std::vector<uint8_t> &params,
278 BufferId *pId,
279 const native_handle_t **handle);
280
281 /**
282 * Processes pending buffer status messages and performs periodic cache
283 * cleaning.
284 *
285 * @param clearCache if clearCache is true, it frees all buffers
286 * waiting to be recycled.
287 */
288 void cleanUp(bool clearCache = false);
289
290 friend class Accessor::Impl;
291 } mBufferPool;
292};
293
294} // namespace implementation
295} // namespace V1_0
296} // namespace ufferpool
297} // namespace media
298} // namespace hardware
299} // namespace android
300
301#endif // ANDROID_HARDWARE_MEDIA_BUFFERPOOL_V1_0_ACCESSORIMPL_H