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