• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2014 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 #include <inttypes.h>
18 #include <pwd.h>
19 #include <sys/types.h>
20 
21 #define LOG_TAG "BufferQueueConsumer"
22 #define ATRACE_TAG ATRACE_TAG_GRAPHICS
23 //#define LOG_NDEBUG 0
24 
25 #if DEBUG_ONLY_CODE
26 #define VALIDATE_CONSISTENCY() do { mCore->validateConsistencyLocked(); } while (0)
27 #else
28 #define VALIDATE_CONSISTENCY()
29 #endif
30 
31 #include <gui/BufferItem.h>
32 #include <gui/BufferQueueConsumer.h>
33 #include <gui/BufferQueueCore.h>
34 #include <gui/IConsumerListener.h>
35 #include <gui/IProducerListener.h>
36 #include <gui/TraceUtils.h>
37 
38 #include <private/gui/BufferQueueThreadState.h>
39 #ifndef __ANDROID_VNDK__
40 #include <binder/PermissionCache.h>
41 #include <vndksupport/linker.h>
42 #endif
43 
44 #include <system/window.h>
45 
46 namespace android {
47 
48 // Macros for include BufferQueueCore information in log messages
49 #define BQ_LOGV(x, ...)                                                                           \
50     ALOGV("[%s](id:%" PRIx64 ",api:%d,p:%d,c:%" PRIu64 ") " x, mConsumerName.string(),            \
51           mCore->mUniqueId, mCore->mConnectedApi, mCore->mConnectedPid, (mCore->mUniqueId) >> 32, \
52           ##__VA_ARGS__)
53 #define BQ_LOGD(x, ...)                                                                           \
54     ALOGD("[%s](id:%" PRIx64 ",api:%d,p:%d,c:%" PRIu64 ") " x, mConsumerName.string(),            \
55           mCore->mUniqueId, mCore->mConnectedApi, mCore->mConnectedPid, (mCore->mUniqueId) >> 32, \
56           ##__VA_ARGS__)
57 #define BQ_LOGI(x, ...)                                                                           \
58     ALOGI("[%s](id:%" PRIx64 ",api:%d,p:%d,c:%" PRIu64 ") " x, mConsumerName.string(),            \
59           mCore->mUniqueId, mCore->mConnectedApi, mCore->mConnectedPid, (mCore->mUniqueId) >> 32, \
60           ##__VA_ARGS__)
61 #define BQ_LOGW(x, ...)                                                                           \
62     ALOGW("[%s](id:%" PRIx64 ",api:%d,p:%d,c:%" PRIu64 ") " x, mConsumerName.string(),            \
63           mCore->mUniqueId, mCore->mConnectedApi, mCore->mConnectedPid, (mCore->mUniqueId) >> 32, \
64           ##__VA_ARGS__)
65 #define BQ_LOGE(x, ...)                                                                           \
66     ALOGE("[%s](id:%" PRIx64 ",api:%d,p:%d,c:%" PRIu64 ") " x, mConsumerName.string(),            \
67           mCore->mUniqueId, mCore->mConnectedApi, mCore->mConnectedPid, (mCore->mUniqueId) >> 32, \
68           ##__VA_ARGS__)
69 
70 ConsumerListener::~ConsumerListener() = default;
71 
BufferQueueConsumer(const sp<BufferQueueCore> & core)72 BufferQueueConsumer::BufferQueueConsumer(const sp<BufferQueueCore>& core) :
73     mCore(core),
74     mSlots(core->mSlots),
75     mConsumerName() {}
76 
~BufferQueueConsumer()77 BufferQueueConsumer::~BufferQueueConsumer() {}
78 
acquireBuffer(BufferItem * outBuffer,nsecs_t expectedPresent,uint64_t maxFrameNumber)79 status_t BufferQueueConsumer::acquireBuffer(BufferItem* outBuffer,
80         nsecs_t expectedPresent, uint64_t maxFrameNumber) {
81     ATRACE_CALL();
82 
83     int numDroppedBuffers = 0;
84     sp<IProducerListener> listener;
85     {
86         std::unique_lock<std::mutex> lock(mCore->mMutex);
87 
88         // Check that the consumer doesn't currently have the maximum number of
89         // buffers acquired. We allow the max buffer count to be exceeded by one
90         // buffer so that the consumer can successfully set up the newly acquired
91         // buffer before releasing the old one.
92         int numAcquiredBuffers = 0;
93         for (int s : mCore->mActiveBuffers) {
94             if (mSlots[s].mBufferState.isAcquired()) {
95                 ++numAcquiredBuffers;
96             }
97         }
98         const bool acquireNonDroppableBuffer = mCore->mAllowExtraAcquire &&
99                 numAcquiredBuffers == mCore->mMaxAcquiredBufferCount + 1;
100         if (numAcquiredBuffers >= mCore->mMaxAcquiredBufferCount + 1 &&
101             !acquireNonDroppableBuffer) {
102             BQ_LOGE("acquireBuffer: max acquired buffer count reached: %d (max %d)",
103                     numAcquiredBuffers, mCore->mMaxAcquiredBufferCount);
104             return INVALID_OPERATION;
105         }
106 
107         bool sharedBufferAvailable = mCore->mSharedBufferMode &&
108                 mCore->mAutoRefresh && mCore->mSharedBufferSlot !=
109                 BufferQueueCore::INVALID_BUFFER_SLOT;
110 
111         // In asynchronous mode the list is guaranteed to be one buffer deep,
112         // while in synchronous mode we use the oldest buffer.
113         if (mCore->mQueue.empty() && !sharedBufferAvailable) {
114             return NO_BUFFER_AVAILABLE;
115         }
116 
117         BufferQueueCore::Fifo::iterator front(mCore->mQueue.begin());
118 
119         // If expectedPresent is specified, we may not want to return a buffer yet.
120         // If it's specified and there's more than one buffer queued, we may want
121         // to drop a buffer.
122         // Skip this if we're in shared buffer mode and the queue is empty,
123         // since in that case we'll just return the shared buffer.
124         if (expectedPresent != 0 && !mCore->mQueue.empty()) {
125             // The 'expectedPresent' argument indicates when the buffer is expected
126             // to be presented on-screen. If the buffer's desired present time is
127             // earlier (less) than expectedPresent -- meaning it will be displayed
128             // on time or possibly late if we show it as soon as possible -- we
129             // acquire and return it. If we don't want to display it until after the
130             // expectedPresent time, we return PRESENT_LATER without acquiring it.
131             //
132             // To be safe, we don't defer acquisition if expectedPresent is more
133             // than one second in the future beyond the desired present time
134             // (i.e., we'd be holding the buffer for a long time).
135             //
136             // NOTE: Code assumes monotonic time values from the system clock
137             // are positive.
138 
139             // Start by checking to see if we can drop frames. We skip this check if
140             // the timestamps are being auto-generated by Surface. If the app isn't
141             // generating timestamps explicitly, it probably doesn't want frames to
142             // be discarded based on them.
143             while (mCore->mQueue.size() > 1 && !mCore->mQueue[0].mIsAutoTimestamp) {
144                 const BufferItem& bufferItem(mCore->mQueue[1]);
145 
146                 // If dropping entry[0] would leave us with a buffer that the
147                 // consumer is not yet ready for, don't drop it.
148                 if (maxFrameNumber && bufferItem.mFrameNumber > maxFrameNumber) {
149                     break;
150                 }
151 
152                 // If entry[1] is timely, drop entry[0] (and repeat). We apply an
153                 // additional criterion here: we only drop the earlier buffer if our
154                 // desiredPresent falls within +/- 1 second of the expected present.
155                 // Otherwise, bogus desiredPresent times (e.g., 0 or a small
156                 // relative timestamp), which normally mean "ignore the timestamp
157                 // and acquire immediately", would cause us to drop frames.
158                 //
159                 // We may want to add an additional criterion: don't drop the
160                 // earlier buffer if entry[1]'s fence hasn't signaled yet.
161                 nsecs_t desiredPresent = bufferItem.mTimestamp;
162                 if (desiredPresent < expectedPresent - MAX_REASONABLE_NSEC ||
163                         desiredPresent > expectedPresent) {
164                     // This buffer is set to display in the near future, or
165                     // desiredPresent is garbage. Either way we don't want to drop
166                     // the previous buffer just to get this on the screen sooner.
167                     BQ_LOGV("acquireBuffer: nodrop desire=%" PRId64 " expect=%"
168                             PRId64 " (%" PRId64 ") now=%" PRId64,
169                             desiredPresent, expectedPresent,
170                             desiredPresent - expectedPresent,
171                             systemTime(CLOCK_MONOTONIC));
172                     break;
173                 }
174 
175                 BQ_LOGV("acquireBuffer: drop desire=%" PRId64 " expect=%" PRId64
176                         " size=%zu",
177                         desiredPresent, expectedPresent, mCore->mQueue.size());
178 
179                 if (!front->mIsStale) {
180                     // Front buffer is still in mSlots, so mark the slot as free
181                     mSlots[front->mSlot].mBufferState.freeQueued();
182 
183                     // After leaving shared buffer mode, the shared buffer will
184                     // still be around. Mark it as no longer shared if this
185                     // operation causes it to be free.
186                     if (!mCore->mSharedBufferMode &&
187                             mSlots[front->mSlot].mBufferState.isFree()) {
188                         mSlots[front->mSlot].mBufferState.mShared = false;
189                     }
190 
191                     // Don't put the shared buffer on the free list
192                     if (!mSlots[front->mSlot].mBufferState.isShared()) {
193                         mCore->mActiveBuffers.erase(front->mSlot);
194                         mCore->mFreeBuffers.push_back(front->mSlot);
195                     }
196 
197                     if (mCore->mBufferReleasedCbEnabled) {
198                         listener = mCore->mConnectedProducerListener;
199                     }
200                     ++numDroppedBuffers;
201                 }
202 
203                 mCore->mQueue.erase(front);
204                 front = mCore->mQueue.begin();
205             }
206 
207             // See if the front buffer is ready to be acquired
208             nsecs_t desiredPresent = front->mTimestamp;
209             bool bufferIsDue = desiredPresent <= expectedPresent ||
210                     desiredPresent > expectedPresent + MAX_REASONABLE_NSEC;
211             bool consumerIsReady = maxFrameNumber > 0 ?
212                     front->mFrameNumber <= maxFrameNumber : true;
213             if (!bufferIsDue || !consumerIsReady) {
214                 BQ_LOGV("acquireBuffer: defer desire=%" PRId64 " expect=%" PRId64
215                         " (%" PRId64 ") now=%" PRId64 " frame=%" PRIu64
216                         " consumer=%" PRIu64,
217                         desiredPresent, expectedPresent,
218                         desiredPresent - expectedPresent,
219                         systemTime(CLOCK_MONOTONIC),
220                         front->mFrameNumber, maxFrameNumber);
221                 ATRACE_NAME("PRESENT_LATER");
222                 return PRESENT_LATER;
223             }
224 
225             BQ_LOGV("acquireBuffer: accept desire=%" PRId64 " expect=%" PRId64 " "
226                     "(%" PRId64 ") now=%" PRId64, desiredPresent, expectedPresent,
227                     desiredPresent - expectedPresent,
228                     systemTime(CLOCK_MONOTONIC));
229         }
230 
231         int slot = BufferQueueCore::INVALID_BUFFER_SLOT;
232 
233         if (sharedBufferAvailable && mCore->mQueue.empty()) {
234             // make sure the buffer has finished allocating before acquiring it
235             mCore->waitWhileAllocatingLocked(lock);
236 
237             slot = mCore->mSharedBufferSlot;
238 
239             // Recreate the BufferItem for the shared buffer from the data that
240             // was cached when it was last queued.
241             outBuffer->mGraphicBuffer = mSlots[slot].mGraphicBuffer;
242             outBuffer->mFence = Fence::NO_FENCE;
243             outBuffer->mFenceTime = FenceTime::NO_FENCE;
244             outBuffer->mCrop = mCore->mSharedBufferCache.crop;
245             outBuffer->mTransform = mCore->mSharedBufferCache.transform &
246                     ~static_cast<uint32_t>(
247                     NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY);
248             outBuffer->mScalingMode = mCore->mSharedBufferCache.scalingMode;
249             outBuffer->mDataSpace = mCore->mSharedBufferCache.dataspace;
250             outBuffer->mFrameNumber = mCore->mFrameCounter;
251             outBuffer->mSlot = slot;
252             outBuffer->mAcquireCalled = mSlots[slot].mAcquireCalled;
253             outBuffer->mTransformToDisplayInverse =
254                     (mCore->mSharedBufferCache.transform &
255                     NATIVE_WINDOW_TRANSFORM_INVERSE_DISPLAY) != 0;
256             outBuffer->mSurfaceDamage = Region::INVALID_REGION;
257             outBuffer->mQueuedBuffer = false;
258             outBuffer->mIsStale = false;
259             outBuffer->mAutoRefresh = mCore->mSharedBufferMode &&
260                     mCore->mAutoRefresh;
261         } else if (acquireNonDroppableBuffer && front->mIsDroppable) {
262             BQ_LOGV("acquireBuffer: front buffer is not droppable");
263             return NO_BUFFER_AVAILABLE;
264         } else {
265             slot = front->mSlot;
266             *outBuffer = *front;
267         }
268 
269         ATRACE_BUFFER_INDEX(slot);
270 
271         BQ_LOGV("acquireBuffer: acquiring { slot=%d/%" PRIu64 " buffer=%p }",
272                 slot, outBuffer->mFrameNumber, outBuffer->mGraphicBuffer->handle);
273 
274         if (!outBuffer->mIsStale) {
275             mSlots[slot].mAcquireCalled = true;
276             // Don't decrease the queue count if the BufferItem wasn't
277             // previously in the queue. This happens in shared buffer mode when
278             // the queue is empty and the BufferItem is created above.
279             if (mCore->mQueue.empty()) {
280                 mSlots[slot].mBufferState.acquireNotInQueue();
281             } else {
282                 mSlots[slot].mBufferState.acquire();
283             }
284             mSlots[slot].mFence = Fence::NO_FENCE;
285         }
286 
287         // If the buffer has previously been acquired by the consumer, set
288         // mGraphicBuffer to NULL to avoid unnecessarily remapping this buffer
289         // on the consumer side
290         if (outBuffer->mAcquireCalled) {
291             outBuffer->mGraphicBuffer = nullptr;
292         }
293 
294         mCore->mQueue.erase(front);
295 
296         // We might have freed a slot while dropping old buffers, or the producer
297         // may be blocked waiting for the number of buffers in the queue to
298         // decrease.
299         mCore->mDequeueCondition.notify_all();
300 
301         ATRACE_INT(mCore->mConsumerName.string(),
302                 static_cast<int32_t>(mCore->mQueue.size()));
303 #ifndef NO_BINDER
304         mCore->mOccupancyTracker.registerOccupancyChange(mCore->mQueue.size());
305 #endif
306         VALIDATE_CONSISTENCY();
307     }
308 
309     if (listener != nullptr) {
310         for (int i = 0; i < numDroppedBuffers; ++i) {
311             listener->onBufferReleased();
312         }
313     }
314 
315     return NO_ERROR;
316 }
317 
detachBuffer(int slot)318 status_t BufferQueueConsumer::detachBuffer(int slot) {
319     ATRACE_CALL();
320     ATRACE_BUFFER_INDEX(slot);
321     BQ_LOGV("detachBuffer: slot %d", slot);
322     std::lock_guard<std::mutex> lock(mCore->mMutex);
323 
324     if (mCore->mIsAbandoned) {
325         BQ_LOGE("detachBuffer: BufferQueue has been abandoned");
326         return NO_INIT;
327     }
328 
329     if (mCore->mSharedBufferMode || slot == mCore->mSharedBufferSlot) {
330         BQ_LOGE("detachBuffer: detachBuffer not allowed in shared buffer mode");
331         return BAD_VALUE;
332     }
333 
334     if (slot < 0 || slot >= BufferQueueDefs::NUM_BUFFER_SLOTS) {
335         BQ_LOGE("detachBuffer: slot index %d out of range [0, %d)",
336                 slot, BufferQueueDefs::NUM_BUFFER_SLOTS);
337         return BAD_VALUE;
338     } else if (!mSlots[slot].mBufferState.isAcquired()) {
339         BQ_LOGE("detachBuffer: slot %d is not owned by the consumer "
340                 "(state = %s)", slot, mSlots[slot].mBufferState.string());
341         return BAD_VALUE;
342     }
343 
344     mSlots[slot].mBufferState.detachConsumer();
345     mCore->mActiveBuffers.erase(slot);
346     mCore->mFreeSlots.insert(slot);
347     mCore->clearBufferSlotLocked(slot);
348     mCore->mDequeueCondition.notify_all();
349     VALIDATE_CONSISTENCY();
350 
351     return NO_ERROR;
352 }
353 
attachBuffer(int * outSlot,const sp<android::GraphicBuffer> & buffer)354 status_t BufferQueueConsumer::attachBuffer(int* outSlot,
355         const sp<android::GraphicBuffer>& buffer) {
356     ATRACE_CALL();
357 
358     if (outSlot == nullptr) {
359         BQ_LOGE("attachBuffer: outSlot must not be NULL");
360         return BAD_VALUE;
361     } else if (buffer == nullptr) {
362         BQ_LOGE("attachBuffer: cannot attach NULL buffer");
363         return BAD_VALUE;
364     }
365 
366     std::lock_guard<std::mutex> lock(mCore->mMutex);
367 
368     if (mCore->mSharedBufferMode) {
369         BQ_LOGE("attachBuffer: cannot attach a buffer in shared buffer mode");
370         return BAD_VALUE;
371     }
372 
373     // Make sure we don't have too many acquired buffers
374     int numAcquiredBuffers = 0;
375     for (int s : mCore->mActiveBuffers) {
376         if (mSlots[s].mBufferState.isAcquired()) {
377             ++numAcquiredBuffers;
378         }
379     }
380 
381     if (numAcquiredBuffers >= mCore->mMaxAcquiredBufferCount + 1) {
382         BQ_LOGE("attachBuffer: max acquired buffer count reached: %d "
383                 "(max %d)", numAcquiredBuffers,
384                 mCore->mMaxAcquiredBufferCount);
385         return INVALID_OPERATION;
386     }
387 
388     if (buffer->getGenerationNumber() != mCore->mGenerationNumber) {
389         BQ_LOGE("attachBuffer: generation number mismatch [buffer %u] "
390                 "[queue %u]", buffer->getGenerationNumber(),
391                 mCore->mGenerationNumber);
392         return BAD_VALUE;
393     }
394 
395     // Find a free slot to put the buffer into
396     int found = BufferQueueCore::INVALID_BUFFER_SLOT;
397     if (!mCore->mFreeSlots.empty()) {
398         auto slot = mCore->mFreeSlots.begin();
399         found = *slot;
400         mCore->mFreeSlots.erase(slot);
401     } else if (!mCore->mFreeBuffers.empty()) {
402         found = mCore->mFreeBuffers.front();
403         mCore->mFreeBuffers.remove(found);
404     }
405     if (found == BufferQueueCore::INVALID_BUFFER_SLOT) {
406         BQ_LOGE("attachBuffer: could not find free buffer slot");
407         return NO_MEMORY;
408     }
409 
410     mCore->mActiveBuffers.insert(found);
411     *outSlot = found;
412     ATRACE_BUFFER_INDEX(*outSlot);
413     BQ_LOGV("attachBuffer: returning slot %d", *outSlot);
414 
415     mSlots[*outSlot].mGraphicBuffer = buffer;
416     mSlots[*outSlot].mBufferState.attachConsumer();
417     mSlots[*outSlot].mNeedsReallocation = true;
418     mSlots[*outSlot].mFence = Fence::NO_FENCE;
419     mSlots[*outSlot].mFrameNumber = 0;
420 
421     // mAcquireCalled tells BufferQueue that it doesn't need to send a valid
422     // GraphicBuffer pointer on the next acquireBuffer call, which decreases
423     // Binder traffic by not un/flattening the GraphicBuffer. However, it
424     // requires that the consumer maintain a cached copy of the slot <--> buffer
425     // mappings, which is why the consumer doesn't need the valid pointer on
426     // acquire.
427     //
428     // The StreamSplitter is one of the primary users of the attach/detach
429     // logic, and while it is running, all buffers it acquires are immediately
430     // detached, and all buffers it eventually releases are ones that were
431     // attached (as opposed to having been obtained from acquireBuffer), so it
432     // doesn't make sense to maintain the slot/buffer mappings, which would
433     // become invalid for every buffer during detach/attach. By setting this to
434     // false, the valid GraphicBuffer pointer will always be sent with acquire
435     // for attached buffers.
436     mSlots[*outSlot].mAcquireCalled = false;
437 
438     VALIDATE_CONSISTENCY();
439 
440     return NO_ERROR;
441 }
442 
releaseBuffer(int slot,uint64_t frameNumber,const sp<Fence> & releaseFence,EGLDisplay eglDisplay,EGLSyncKHR eglFence)443 status_t BufferQueueConsumer::releaseBuffer(int slot, uint64_t frameNumber,
444         const sp<Fence>& releaseFence, EGLDisplay eglDisplay,
445         EGLSyncKHR eglFence) {
446     ATRACE_CALL();
447     ATRACE_BUFFER_INDEX(slot);
448 
449     if (slot < 0 || slot >= BufferQueueDefs::NUM_BUFFER_SLOTS ||
450             releaseFence == nullptr) {
451         BQ_LOGE("releaseBuffer: slot %d out of range or fence %p NULL", slot,
452                 releaseFence.get());
453         return BAD_VALUE;
454     }
455 
456     sp<IProducerListener> listener;
457     { // Autolock scope
458         std::lock_guard<std::mutex> lock(mCore->mMutex);
459 
460         // If the frame number has changed because the buffer has been reallocated,
461         // we can ignore this releaseBuffer for the old buffer.
462         // Ignore this for the shared buffer where the frame number can easily
463         // get out of sync due to the buffer being queued and acquired at the
464         // same time.
465         if (frameNumber != mSlots[slot].mFrameNumber &&
466                 !mSlots[slot].mBufferState.isShared()) {
467             return STALE_BUFFER_SLOT;
468         }
469 
470         if (!mSlots[slot].mBufferState.isAcquired()) {
471             BQ_LOGE("releaseBuffer: attempted to release buffer slot %d "
472                     "but its state was %s", slot,
473                     mSlots[slot].mBufferState.string());
474             return BAD_VALUE;
475         }
476 
477         mSlots[slot].mEglDisplay = eglDisplay;
478         mSlots[slot].mEglFence = eglFence;
479         mSlots[slot].mFence = releaseFence;
480         mSlots[slot].mBufferState.release();
481 
482         // After leaving shared buffer mode, the shared buffer will
483         // still be around. Mark it as no longer shared if this
484         // operation causes it to be free.
485         if (!mCore->mSharedBufferMode && mSlots[slot].mBufferState.isFree()) {
486             mSlots[slot].mBufferState.mShared = false;
487         }
488         // Don't put the shared buffer on the free list.
489         if (!mSlots[slot].mBufferState.isShared()) {
490             mCore->mActiveBuffers.erase(slot);
491             mCore->mFreeBuffers.push_back(slot);
492         }
493 
494         if (mCore->mBufferReleasedCbEnabled) {
495             listener = mCore->mConnectedProducerListener;
496         }
497         BQ_LOGV("releaseBuffer: releasing slot %d", slot);
498 
499         mCore->mDequeueCondition.notify_all();
500         VALIDATE_CONSISTENCY();
501     } // Autolock scope
502 
503     // Call back without lock held
504     if (listener != nullptr) {
505         listener->onBufferReleased();
506     }
507 
508     return NO_ERROR;
509 }
510 
connect(const sp<IConsumerListener> & consumerListener,bool controlledByApp)511 status_t BufferQueueConsumer::connect(
512         const sp<IConsumerListener>& consumerListener, bool controlledByApp) {
513     ATRACE_CALL();
514 
515     if (consumerListener == nullptr) {
516         BQ_LOGE("connect: consumerListener may not be NULL");
517         return BAD_VALUE;
518     }
519 
520     BQ_LOGV("connect: controlledByApp=%s",
521             controlledByApp ? "true" : "false");
522 
523     std::lock_guard<std::mutex> lock(mCore->mMutex);
524 
525     if (mCore->mIsAbandoned) {
526         BQ_LOGE("connect: BufferQueue has been abandoned");
527         return NO_INIT;
528     }
529 
530     mCore->mConsumerListener = consumerListener;
531     mCore->mConsumerControlledByApp = controlledByApp;
532 
533     return NO_ERROR;
534 }
535 
disconnect()536 status_t BufferQueueConsumer::disconnect() {
537     ATRACE_CALL();
538 
539     BQ_LOGV("disconnect");
540 
541     std::lock_guard<std::mutex> lock(mCore->mMutex);
542 
543     if (mCore->mConsumerListener == nullptr) {
544         BQ_LOGE("disconnect: no consumer is connected");
545         return BAD_VALUE;
546     }
547 
548     mCore->mIsAbandoned = true;
549     mCore->mConsumerListener = nullptr;
550     mCore->mQueue.clear();
551     mCore->freeAllBuffersLocked();
552     mCore->mSharedBufferSlot = BufferQueueCore::INVALID_BUFFER_SLOT;
553     mCore->mDequeueCondition.notify_all();
554     return NO_ERROR;
555 }
556 
getReleasedBuffers(uint64_t * outSlotMask)557 status_t BufferQueueConsumer::getReleasedBuffers(uint64_t *outSlotMask) {
558     ATRACE_CALL();
559 
560     if (outSlotMask == nullptr) {
561         BQ_LOGE("getReleasedBuffers: outSlotMask may not be NULL");
562         return BAD_VALUE;
563     }
564 
565     std::lock_guard<std::mutex> lock(mCore->mMutex);
566 
567     if (mCore->mIsAbandoned) {
568         BQ_LOGE("getReleasedBuffers: BufferQueue has been abandoned");
569         return NO_INIT;
570     }
571 
572     uint64_t mask = 0;
573     for (int s = 0; s < BufferQueueDefs::NUM_BUFFER_SLOTS; ++s) {
574         if (!mSlots[s].mAcquireCalled) {
575             mask |= (1ULL << s);
576         }
577     }
578 
579     // Remove from the mask queued buffers for which acquire has been called,
580     // since the consumer will not receive their buffer addresses and so must
581     // retain their cached information
582     BufferQueueCore::Fifo::iterator current(mCore->mQueue.begin());
583     while (current != mCore->mQueue.end()) {
584         if (current->mAcquireCalled) {
585             mask &= ~(1ULL << current->mSlot);
586         }
587         ++current;
588     }
589 
590     BQ_LOGV("getReleasedBuffers: returning mask %#" PRIx64, mask);
591     *outSlotMask = mask;
592     return NO_ERROR;
593 }
594 
setDefaultBufferSize(uint32_t width,uint32_t height)595 status_t BufferQueueConsumer::setDefaultBufferSize(uint32_t width,
596         uint32_t height) {
597     ATRACE_CALL();
598 
599     if (width == 0 || height == 0) {
600         BQ_LOGV("setDefaultBufferSize: dimensions cannot be 0 (width=%u "
601                 "height=%u)", width, height);
602         return BAD_VALUE;
603     }
604 
605     BQ_LOGV("setDefaultBufferSize: width=%u height=%u", width, height);
606 
607     std::lock_guard<std::mutex> lock(mCore->mMutex);
608     mCore->mDefaultWidth = width;
609     mCore->mDefaultHeight = height;
610     return NO_ERROR;
611 }
612 
setMaxBufferCount(int bufferCount)613 status_t BufferQueueConsumer::setMaxBufferCount(int bufferCount) {
614     ATRACE_CALL();
615 
616     if (bufferCount < 1 || bufferCount > BufferQueueDefs::NUM_BUFFER_SLOTS) {
617         BQ_LOGE("setMaxBufferCount: invalid count %d", bufferCount);
618         return BAD_VALUE;
619     }
620 
621     std::lock_guard<std::mutex> lock(mCore->mMutex);
622 
623     if (mCore->mConnectedApi != BufferQueueCore::NO_CONNECTED_API) {
624         BQ_LOGE("setMaxBufferCount: producer is already connected");
625         return INVALID_OPERATION;
626     }
627 
628     if (bufferCount < mCore->mMaxAcquiredBufferCount) {
629         BQ_LOGE("setMaxBufferCount: invalid buffer count (%d) less than"
630                 "mMaxAcquiredBufferCount (%d)", bufferCount,
631                 mCore->mMaxAcquiredBufferCount);
632         return BAD_VALUE;
633     }
634 
635     int delta = mCore->getMaxBufferCountLocked(mCore->mAsyncMode,
636             mCore->mDequeueBufferCannotBlock, bufferCount) -
637             mCore->getMaxBufferCountLocked();
638     if (!mCore->adjustAvailableSlotsLocked(delta)) {
639         BQ_LOGE("setMaxBufferCount: BufferQueue failed to adjust the number of "
640                 "available slots. Delta = %d", delta);
641         return BAD_VALUE;
642     }
643 
644     mCore->mMaxBufferCount = bufferCount;
645     return NO_ERROR;
646 }
647 
setMaxAcquiredBufferCount(int maxAcquiredBuffers)648 status_t BufferQueueConsumer::setMaxAcquiredBufferCount(
649         int maxAcquiredBuffers) {
650     ATRACE_FORMAT("%s(%d)", __func__, maxAcquiredBuffers);
651 
652     if (maxAcquiredBuffers < 1 ||
653             maxAcquiredBuffers > BufferQueueCore::MAX_MAX_ACQUIRED_BUFFERS) {
654         BQ_LOGE("setMaxAcquiredBufferCount: invalid count %d",
655                 maxAcquiredBuffers);
656         return BAD_VALUE;
657     }
658 
659     sp<IConsumerListener> listener;
660     { // Autolock scope
661         std::unique_lock<std::mutex> lock(mCore->mMutex);
662         mCore->waitWhileAllocatingLocked(lock);
663 
664         if (mCore->mIsAbandoned) {
665             BQ_LOGE("setMaxAcquiredBufferCount: consumer is abandoned");
666             return NO_INIT;
667         }
668 
669         if (maxAcquiredBuffers == mCore->mMaxAcquiredBufferCount) {
670             return NO_ERROR;
671         }
672 
673         // The new maxAcquiredBuffers count should not be violated by the number
674         // of currently acquired buffers
675         int acquiredCount = 0;
676         for (int slot : mCore->mActiveBuffers) {
677             if (mSlots[slot].mBufferState.isAcquired()) {
678                 acquiredCount++;
679             }
680         }
681         if (acquiredCount > maxAcquiredBuffers) {
682             BQ_LOGE("setMaxAcquiredBufferCount: the requested maxAcquiredBuffer"
683                     "count (%d) exceeds the current acquired buffer count (%d)",
684                     maxAcquiredBuffers, acquiredCount);
685             return BAD_VALUE;
686         }
687 
688         if ((maxAcquiredBuffers + mCore->mMaxDequeuedBufferCount +
689                 (mCore->mAsyncMode || mCore->mDequeueBufferCannotBlock ? 1 : 0))
690                 > mCore->mMaxBufferCount) {
691             BQ_LOGE("setMaxAcquiredBufferCount: %d acquired buffers would "
692                     "exceed the maxBufferCount (%d) (maxDequeued %d async %d)",
693                     maxAcquiredBuffers, mCore->mMaxBufferCount,
694                     mCore->mMaxDequeuedBufferCount, mCore->mAsyncMode ||
695                     mCore->mDequeueBufferCannotBlock);
696             return BAD_VALUE;
697         }
698 
699         int delta = maxAcquiredBuffers - mCore->mMaxAcquiredBufferCount;
700         if (!mCore->adjustAvailableSlotsLocked(delta)) {
701             return BAD_VALUE;
702         }
703 
704         BQ_LOGV("setMaxAcquiredBufferCount: %d", maxAcquiredBuffers);
705         mCore->mMaxAcquiredBufferCount = maxAcquiredBuffers;
706         VALIDATE_CONSISTENCY();
707         if (delta < 0 && mCore->mBufferReleasedCbEnabled) {
708             listener = mCore->mConsumerListener;
709         }
710     }
711     // Call back without lock held
712     if (listener != nullptr) {
713         listener->onBuffersReleased();
714     }
715 
716     return NO_ERROR;
717 }
718 
setConsumerName(const String8 & name)719 status_t BufferQueueConsumer::setConsumerName(const String8& name) {
720     ATRACE_CALL();
721     BQ_LOGV("setConsumerName: '%s'", name.string());
722     std::lock_guard<std::mutex> lock(mCore->mMutex);
723     mCore->mConsumerName = name;
724     mConsumerName = name;
725     return NO_ERROR;
726 }
727 
setDefaultBufferFormat(PixelFormat defaultFormat)728 status_t BufferQueueConsumer::setDefaultBufferFormat(PixelFormat defaultFormat) {
729     ATRACE_CALL();
730     BQ_LOGV("setDefaultBufferFormat: %u", defaultFormat);
731     std::lock_guard<std::mutex> lock(mCore->mMutex);
732     mCore->mDefaultBufferFormat = defaultFormat;
733     return NO_ERROR;
734 }
735 
setDefaultBufferDataSpace(android_dataspace defaultDataSpace)736 status_t BufferQueueConsumer::setDefaultBufferDataSpace(
737         android_dataspace defaultDataSpace) {
738     ATRACE_CALL();
739     BQ_LOGV("setDefaultBufferDataSpace: %u", defaultDataSpace);
740     std::lock_guard<std::mutex> lock(mCore->mMutex);
741     mCore->mDefaultBufferDataSpace = defaultDataSpace;
742     return NO_ERROR;
743 }
744 
setConsumerUsageBits(uint64_t usage)745 status_t BufferQueueConsumer::setConsumerUsageBits(uint64_t usage) {
746     ATRACE_CALL();
747     BQ_LOGV("setConsumerUsageBits: %#" PRIx64, usage);
748     std::lock_guard<std::mutex> lock(mCore->mMutex);
749     mCore->mConsumerUsageBits = usage;
750     return NO_ERROR;
751 }
752 
setConsumerIsProtected(bool isProtected)753 status_t BufferQueueConsumer::setConsumerIsProtected(bool isProtected) {
754     ATRACE_CALL();
755     BQ_LOGV("setConsumerIsProtected: %s", isProtected ? "true" : "false");
756     std::lock_guard<std::mutex> lock(mCore->mMutex);
757     mCore->mConsumerIsProtected = isProtected;
758     return NO_ERROR;
759 }
760 
setTransformHint(uint32_t hint)761 status_t BufferQueueConsumer::setTransformHint(uint32_t hint) {
762     ATRACE_CALL();
763     BQ_LOGV("setTransformHint: %#x", hint);
764     std::lock_guard<std::mutex> lock(mCore->mMutex);
765     mCore->mTransformHint = hint;
766     return NO_ERROR;
767 }
768 
getSidebandStream(sp<NativeHandle> * outStream) const769 status_t BufferQueueConsumer::getSidebandStream(sp<NativeHandle>* outStream) const {
770     std::lock_guard<std::mutex> lock(mCore->mMutex);
771     *outStream = mCore->mSidebandStream;
772     return NO_ERROR;
773 }
774 
getOccupancyHistory(bool forceFlush,std::vector<OccupancyTracker::Segment> * outHistory)775 status_t BufferQueueConsumer::getOccupancyHistory(bool forceFlush,
776         std::vector<OccupancyTracker::Segment>* outHistory) {
777     std::lock_guard<std::mutex> lock(mCore->mMutex);
778 #ifndef NO_BINDER
779     *outHistory = mCore->mOccupancyTracker.getSegmentHistory(forceFlush);
780 #else
781     (void)forceFlush;
782     outHistory->clear();
783 #endif
784     return NO_ERROR;
785 }
786 
discardFreeBuffers()787 status_t BufferQueueConsumer::discardFreeBuffers() {
788     std::lock_guard<std::mutex> lock(mCore->mMutex);
789     mCore->discardFreeBuffersLocked();
790     return NO_ERROR;
791 }
792 
dumpState(const String8 & prefix,String8 * outResult) const793 status_t BufferQueueConsumer::dumpState(const String8& prefix, String8* outResult) const {
794     struct passwd* pwd = getpwnam("shell");
795     uid_t shellUid = pwd ? pwd->pw_uid : 0;
796     if (!shellUid) {
797         int savedErrno = errno;
798         BQ_LOGE("Cannot get AID_SHELL");
799         return savedErrno ? -savedErrno : UNKNOWN_ERROR;
800     }
801 
802     bool denied = false;
803     const uid_t uid = BufferQueueThreadState::getCallingUid();
804 #if !defined(__ANDROID_VNDK__) && !defined(NO_BINDER)
805     // permission check can't be done for vendors as vendors have no access to
806     // the PermissionController. We need to do a runtime check as well, since
807     // the system variant of libgui can be loaded in a vendor process. For eg:
808     // if a HAL uses an llndk library that depends on libgui (libmediandk etc).
809     if (!android_is_in_vendor_process()) {
810         const pid_t pid = BufferQueueThreadState::getCallingPid();
811         if ((uid != shellUid) &&
812             !PermissionCache::checkPermission(String16("android.permission.DUMP"), pid, uid)) {
813             outResult->appendFormat("Permission Denial: can't dump BufferQueueConsumer "
814                                     "from pid=%d, uid=%d\n",
815                                     pid, uid);
816             denied = true;
817         }
818     }
819 #else
820     if (uid != shellUid) {
821         denied = true;
822     }
823 #endif
824     if (denied) {
825         android_errorWriteWithInfoLog(0x534e4554, "27046057",
826                 static_cast<int32_t>(uid), nullptr, 0);
827         return PERMISSION_DENIED;
828     }
829 
830     mCore->dumpState(prefix, outResult);
831     return NO_ERROR;
832 }
833 
setAllowExtraAcquire(bool allow)834 void BufferQueueConsumer::setAllowExtraAcquire(bool allow) {
835     std::lock_guard<std::mutex> lock(mCore->mMutex);
836     mCore->mAllowExtraAcquire = allow;
837 }
838 
839 } // namespace android
840