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 #if !defined(__ANDROID_VNDK__) && !defined(NO_BINDER)
40 #include <binder/PermissionCache.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.c_str(),             \
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.c_str(),             \
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.c_str(),             \
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.c_str(),             \
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.c_str(),             \
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.c_str(), static_cast<int32_t>(mCore->mQueue.size()));
301 #ifndef NO_BINDER
302         mCore->mOccupancyTracker.registerOccupancyChange(mCore->mQueue.size());
303 #endif
304         VALIDATE_CONSISTENCY();
305     }
306 
307     if (listener != nullptr) {
308         for (int i = 0; i < numDroppedBuffers; ++i) {
309             listener->onBufferReleased();
310         }
311     }
312 
313     return NO_ERROR;
314 }
315 
detachBuffer(int slot)316 status_t BufferQueueConsumer::detachBuffer(int slot) {
317     ATRACE_CALL();
318     ATRACE_BUFFER_INDEX(slot);
319     BQ_LOGV("detachBuffer: slot %d", slot);
320     sp<IProducerListener> listener;
321     {
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         if (mCore->mBufferReleasedCbEnabled) {
344             listener = mCore->mConnectedProducerListener;
345         }
346 
347         mSlots[slot].mBufferState.detachConsumer();
348         mCore->mActiveBuffers.erase(slot);
349         mCore->mFreeSlots.insert(slot);
350         mCore->clearBufferSlotLocked(slot);
351         mCore->mDequeueCondition.notify_all();
352         VALIDATE_CONSISTENCY();
353     }
354 
355     if (listener) {
356         listener->onBufferDetached(slot);
357     }
358     return NO_ERROR;
359 }
360 
attachBuffer(int * outSlot,const sp<android::GraphicBuffer> & buffer)361 status_t BufferQueueConsumer::attachBuffer(int* outSlot,
362         const sp<android::GraphicBuffer>& buffer) {
363     ATRACE_CALL();
364 
365     if (outSlot == nullptr) {
366         BQ_LOGE("attachBuffer: outSlot must not be NULL");
367         return BAD_VALUE;
368     } else if (buffer == nullptr) {
369         BQ_LOGE("attachBuffer: cannot attach NULL buffer");
370         return BAD_VALUE;
371     }
372 
373     std::lock_guard<std::mutex> lock(mCore->mMutex);
374 
375     if (mCore->mSharedBufferMode) {
376         BQ_LOGE("attachBuffer: cannot attach a buffer in shared buffer mode");
377         return BAD_VALUE;
378     }
379 
380     // Make sure we don't have too many acquired buffers
381     int numAcquiredBuffers = 0;
382     for (int s : mCore->mActiveBuffers) {
383         if (mSlots[s].mBufferState.isAcquired()) {
384             ++numAcquiredBuffers;
385         }
386     }
387 
388     if (numAcquiredBuffers >= mCore->mMaxAcquiredBufferCount + 1) {
389         BQ_LOGE("attachBuffer: max acquired buffer count reached: %d "
390                 "(max %d)", numAcquiredBuffers,
391                 mCore->mMaxAcquiredBufferCount);
392         return INVALID_OPERATION;
393     }
394 
395     if (buffer->getGenerationNumber() != mCore->mGenerationNumber) {
396         BQ_LOGE("attachBuffer: generation number mismatch [buffer %u] "
397                 "[queue %u]", buffer->getGenerationNumber(),
398                 mCore->mGenerationNumber);
399         return BAD_VALUE;
400     }
401 
402     // Find a free slot to put the buffer into
403     int found = BufferQueueCore::INVALID_BUFFER_SLOT;
404     if (!mCore->mFreeSlots.empty()) {
405         auto slot = mCore->mFreeSlots.begin();
406         found = *slot;
407         mCore->mFreeSlots.erase(slot);
408     } else if (!mCore->mFreeBuffers.empty()) {
409         found = mCore->mFreeBuffers.front();
410         mCore->mFreeBuffers.remove(found);
411     }
412     if (found == BufferQueueCore::INVALID_BUFFER_SLOT) {
413         BQ_LOGE("attachBuffer: could not find free buffer slot");
414         return NO_MEMORY;
415     }
416 
417     mCore->mActiveBuffers.insert(found);
418     *outSlot = found;
419     ATRACE_BUFFER_INDEX(*outSlot);
420     BQ_LOGV("attachBuffer: returning slot %d", *outSlot);
421 
422     mSlots[*outSlot].mGraphicBuffer = buffer;
423     mSlots[*outSlot].mBufferState.attachConsumer();
424     mSlots[*outSlot].mNeedsReallocation = true;
425     mSlots[*outSlot].mFence = Fence::NO_FENCE;
426     mSlots[*outSlot].mFrameNumber = 0;
427 
428     // mAcquireCalled tells BufferQueue that it doesn't need to send a valid
429     // GraphicBuffer pointer on the next acquireBuffer call, which decreases
430     // Binder traffic by not un/flattening the GraphicBuffer. However, it
431     // requires that the consumer maintain a cached copy of the slot <--> buffer
432     // mappings, which is why the consumer doesn't need the valid pointer on
433     // acquire.
434     //
435     // The StreamSplitter is one of the primary users of the attach/detach
436     // logic, and while it is running, all buffers it acquires are immediately
437     // detached, and all buffers it eventually releases are ones that were
438     // attached (as opposed to having been obtained from acquireBuffer), so it
439     // doesn't make sense to maintain the slot/buffer mappings, which would
440     // become invalid for every buffer during detach/attach. By setting this to
441     // false, the valid GraphicBuffer pointer will always be sent with acquire
442     // for attached buffers.
443     mSlots[*outSlot].mAcquireCalled = false;
444 
445     VALIDATE_CONSISTENCY();
446 
447     return NO_ERROR;
448 }
449 
releaseBuffer(int slot,uint64_t frameNumber,const sp<Fence> & releaseFence,EGLDisplay eglDisplay,EGLSyncKHR eglFence)450 status_t BufferQueueConsumer::releaseBuffer(int slot, uint64_t frameNumber,
451         const sp<Fence>& releaseFence, EGLDisplay eglDisplay,
452         EGLSyncKHR eglFence) {
453     ATRACE_CALL();
454     ATRACE_BUFFER_INDEX(slot);
455 
456     if (slot < 0 || slot >= BufferQueueDefs::NUM_BUFFER_SLOTS ||
457             releaseFence == nullptr) {
458         BQ_LOGE("releaseBuffer: slot %d out of range or fence %p NULL", slot,
459                 releaseFence.get());
460         return BAD_VALUE;
461     }
462 
463     sp<IProducerListener> listener;
464     { // Autolock scope
465         std::lock_guard<std::mutex> lock(mCore->mMutex);
466 
467         // If the frame number has changed because the buffer has been reallocated,
468         // we can ignore this releaseBuffer for the old buffer.
469         // Ignore this for the shared buffer where the frame number can easily
470         // get out of sync due to the buffer being queued and acquired at the
471         // same time.
472         if (frameNumber != mSlots[slot].mFrameNumber &&
473                 !mSlots[slot].mBufferState.isShared()) {
474             return STALE_BUFFER_SLOT;
475         }
476 
477         if (!mSlots[slot].mBufferState.isAcquired()) {
478             BQ_LOGE("releaseBuffer: attempted to release buffer slot %d "
479                     "but its state was %s", slot,
480                     mSlots[slot].mBufferState.string());
481             return BAD_VALUE;
482         }
483 
484         mSlots[slot].mEglDisplay = eglDisplay;
485         mSlots[slot].mEglFence = eglFence;
486         mSlots[slot].mFence = releaseFence;
487         mSlots[slot].mBufferState.release();
488 
489         // After leaving shared buffer mode, the shared buffer will
490         // still be around. Mark it as no longer shared if this
491         // operation causes it to be free.
492         if (!mCore->mSharedBufferMode && mSlots[slot].mBufferState.isFree()) {
493             mSlots[slot].mBufferState.mShared = false;
494         }
495         // Don't put the shared buffer on the free list.
496         if (!mSlots[slot].mBufferState.isShared()) {
497             mCore->mActiveBuffers.erase(slot);
498             mCore->mFreeBuffers.push_back(slot);
499         }
500 
501         if (mCore->mBufferReleasedCbEnabled) {
502             listener = mCore->mConnectedProducerListener;
503         }
504         BQ_LOGV("releaseBuffer: releasing slot %d", slot);
505 
506         mCore->mDequeueCondition.notify_all();
507         VALIDATE_CONSISTENCY();
508     } // Autolock scope
509 
510     // Call back without lock held
511     if (listener != nullptr) {
512         listener->onBufferReleased();
513     }
514 
515     return NO_ERROR;
516 }
517 
connect(const sp<IConsumerListener> & consumerListener,bool controlledByApp)518 status_t BufferQueueConsumer::connect(
519         const sp<IConsumerListener>& consumerListener, bool controlledByApp) {
520     ATRACE_CALL();
521 
522     if (consumerListener == nullptr) {
523         BQ_LOGE("connect: consumerListener may not be NULL");
524         return BAD_VALUE;
525     }
526 
527     BQ_LOGV("connect: controlledByApp=%s",
528             controlledByApp ? "true" : "false");
529 
530     std::lock_guard<std::mutex> lock(mCore->mMutex);
531 
532     if (mCore->mIsAbandoned) {
533         BQ_LOGE("connect: BufferQueue has been abandoned");
534         return NO_INIT;
535     }
536 
537     mCore->mConsumerListener = consumerListener;
538     mCore->mConsumerControlledByApp = controlledByApp;
539 
540     return NO_ERROR;
541 }
542 
disconnect()543 status_t BufferQueueConsumer::disconnect() {
544     ATRACE_CALL();
545 
546     BQ_LOGV("disconnect");
547 
548     std::lock_guard<std::mutex> lock(mCore->mMutex);
549 
550     if (mCore->mConsumerListener == nullptr) {
551         BQ_LOGE("disconnect: no consumer is connected");
552         return BAD_VALUE;
553     }
554 
555     mCore->mIsAbandoned = true;
556     mCore->mConsumerListener = nullptr;
557     mCore->mQueue.clear();
558     mCore->freeAllBuffersLocked();
559     mCore->mSharedBufferSlot = BufferQueueCore::INVALID_BUFFER_SLOT;
560     mCore->mDequeueCondition.notify_all();
561     return NO_ERROR;
562 }
563 
getReleasedBuffers(uint64_t * outSlotMask)564 status_t BufferQueueConsumer::getReleasedBuffers(uint64_t *outSlotMask) {
565     ATRACE_CALL();
566 
567     if (outSlotMask == nullptr) {
568         BQ_LOGE("getReleasedBuffers: outSlotMask may not be NULL");
569         return BAD_VALUE;
570     }
571 
572     std::lock_guard<std::mutex> lock(mCore->mMutex);
573 
574     if (mCore->mIsAbandoned) {
575         BQ_LOGE("getReleasedBuffers: BufferQueue has been abandoned");
576         return NO_INIT;
577     }
578 
579     uint64_t mask = 0;
580     for (int s = 0; s < BufferQueueDefs::NUM_BUFFER_SLOTS; ++s) {
581         if (!mSlots[s].mAcquireCalled) {
582             mask |= (1ULL << s);
583         }
584     }
585 
586     // Remove from the mask queued buffers for which acquire has been called,
587     // since the consumer will not receive their buffer addresses and so must
588     // retain their cached information
589     BufferQueueCore::Fifo::iterator current(mCore->mQueue.begin());
590     while (current != mCore->mQueue.end()) {
591         if (current->mAcquireCalled) {
592             mask &= ~(1ULL << current->mSlot);
593         }
594         ++current;
595     }
596 
597     BQ_LOGV("getReleasedBuffers: returning mask %#" PRIx64, mask);
598     *outSlotMask = mask;
599     return NO_ERROR;
600 }
601 
setDefaultBufferSize(uint32_t width,uint32_t height)602 status_t BufferQueueConsumer::setDefaultBufferSize(uint32_t width,
603         uint32_t height) {
604     ATRACE_CALL();
605 
606     if (width == 0 || height == 0) {
607         BQ_LOGV("setDefaultBufferSize: dimensions cannot be 0 (width=%u "
608                 "height=%u)", width, height);
609         return BAD_VALUE;
610     }
611 
612     BQ_LOGV("setDefaultBufferSize: width=%u height=%u", width, height);
613 
614     std::lock_guard<std::mutex> lock(mCore->mMutex);
615     mCore->mDefaultWidth = width;
616     mCore->mDefaultHeight = height;
617     return NO_ERROR;
618 }
619 
setMaxBufferCount(int bufferCount)620 status_t BufferQueueConsumer::setMaxBufferCount(int bufferCount) {
621     ATRACE_CALL();
622 
623     if (bufferCount < 1 || bufferCount > BufferQueueDefs::NUM_BUFFER_SLOTS) {
624         BQ_LOGE("setMaxBufferCount: invalid count %d", bufferCount);
625         return BAD_VALUE;
626     }
627 
628     std::lock_guard<std::mutex> lock(mCore->mMutex);
629 
630     if (mCore->mConnectedApi != BufferQueueCore::NO_CONNECTED_API) {
631         BQ_LOGE("setMaxBufferCount: producer is already connected");
632         return INVALID_OPERATION;
633     }
634 
635     if (bufferCount < mCore->mMaxAcquiredBufferCount) {
636         BQ_LOGE("setMaxBufferCount: invalid buffer count (%d) less than"
637                 "mMaxAcquiredBufferCount (%d)", bufferCount,
638                 mCore->mMaxAcquiredBufferCount);
639         return BAD_VALUE;
640     }
641 
642     int delta = mCore->getMaxBufferCountLocked(mCore->mAsyncMode,
643             mCore->mDequeueBufferCannotBlock, bufferCount) -
644             mCore->getMaxBufferCountLocked();
645     if (!mCore->adjustAvailableSlotsLocked(delta)) {
646         BQ_LOGE("setMaxBufferCount: BufferQueue failed to adjust the number of "
647                 "available slots. Delta = %d", delta);
648         return BAD_VALUE;
649     }
650 
651     mCore->mMaxBufferCount = bufferCount;
652     return NO_ERROR;
653 }
654 
setMaxAcquiredBufferCount(int maxAcquiredBuffers)655 status_t BufferQueueConsumer::setMaxAcquiredBufferCount(
656         int maxAcquiredBuffers) {
657     ATRACE_FORMAT("%s(%d)", __func__, maxAcquiredBuffers);
658 
659     if (maxAcquiredBuffers < 1 ||
660             maxAcquiredBuffers > BufferQueueCore::MAX_MAX_ACQUIRED_BUFFERS) {
661         BQ_LOGE("setMaxAcquiredBufferCount: invalid count %d",
662                 maxAcquiredBuffers);
663         return BAD_VALUE;
664     }
665 
666     sp<IConsumerListener> listener;
667     { // Autolock scope
668         std::unique_lock<std::mutex> lock(mCore->mMutex);
669         mCore->waitWhileAllocatingLocked(lock);
670 
671         if (mCore->mIsAbandoned) {
672             BQ_LOGE("setMaxAcquiredBufferCount: consumer is abandoned");
673             return NO_INIT;
674         }
675 
676         if (maxAcquiredBuffers == mCore->mMaxAcquiredBufferCount) {
677             return NO_ERROR;
678         }
679 
680         // The new maxAcquiredBuffers count should not be violated by the number
681         // of currently acquired buffers
682         int acquiredCount = 0;
683         for (int slot : mCore->mActiveBuffers) {
684             if (mSlots[slot].mBufferState.isAcquired()) {
685                 acquiredCount++;
686             }
687         }
688         if (acquiredCount > maxAcquiredBuffers) {
689             BQ_LOGE("setMaxAcquiredBufferCount: the requested maxAcquiredBuffer"
690                     "count (%d) exceeds the current acquired buffer count (%d)",
691                     maxAcquiredBuffers, acquiredCount);
692             return BAD_VALUE;
693         }
694 
695         if ((maxAcquiredBuffers + mCore->mMaxDequeuedBufferCount +
696                 (mCore->mAsyncMode || mCore->mDequeueBufferCannotBlock ? 1 : 0))
697                 > mCore->mMaxBufferCount) {
698             BQ_LOGE("setMaxAcquiredBufferCount: %d acquired buffers would "
699                     "exceed the maxBufferCount (%d) (maxDequeued %d async %d)",
700                     maxAcquiredBuffers, mCore->mMaxBufferCount,
701                     mCore->mMaxDequeuedBufferCount, mCore->mAsyncMode ||
702                     mCore->mDequeueBufferCannotBlock);
703             return BAD_VALUE;
704         }
705 
706         int delta = maxAcquiredBuffers - mCore->mMaxAcquiredBufferCount;
707         if (!mCore->adjustAvailableSlotsLocked(delta)) {
708             return BAD_VALUE;
709         }
710 
711         BQ_LOGV("setMaxAcquiredBufferCount: %d", maxAcquiredBuffers);
712         mCore->mMaxAcquiredBufferCount = maxAcquiredBuffers;
713         VALIDATE_CONSISTENCY();
714         if (delta < 0 && mCore->mBufferReleasedCbEnabled) {
715             listener = mCore->mConsumerListener;
716         }
717     }
718     // Call back without lock held
719     if (listener != nullptr) {
720         listener->onBuffersReleased();
721     }
722 
723     return NO_ERROR;
724 }
725 
setConsumerName(const String8 & name)726 status_t BufferQueueConsumer::setConsumerName(const String8& name) {
727     ATRACE_CALL();
728     BQ_LOGV("setConsumerName: '%s'", name.c_str());
729     std::lock_guard<std::mutex> lock(mCore->mMutex);
730     mCore->mConsumerName = name;
731     mConsumerName = name;
732     return NO_ERROR;
733 }
734 
setDefaultBufferFormat(PixelFormat defaultFormat)735 status_t BufferQueueConsumer::setDefaultBufferFormat(PixelFormat defaultFormat) {
736     ATRACE_CALL();
737     BQ_LOGV("setDefaultBufferFormat: %u", defaultFormat);
738     std::lock_guard<std::mutex> lock(mCore->mMutex);
739     mCore->mDefaultBufferFormat = defaultFormat;
740     return NO_ERROR;
741 }
742 
setDefaultBufferDataSpace(android_dataspace defaultDataSpace)743 status_t BufferQueueConsumer::setDefaultBufferDataSpace(
744         android_dataspace defaultDataSpace) {
745     ATRACE_CALL();
746     BQ_LOGV("setDefaultBufferDataSpace: %u", defaultDataSpace);
747     std::lock_guard<std::mutex> lock(mCore->mMutex);
748     mCore->mDefaultBufferDataSpace = defaultDataSpace;
749     return NO_ERROR;
750 }
751 
setConsumerUsageBits(uint64_t usage)752 status_t BufferQueueConsumer::setConsumerUsageBits(uint64_t usage) {
753     ATRACE_CALL();
754     BQ_LOGV("setConsumerUsageBits: %#" PRIx64, usage);
755     std::lock_guard<std::mutex> lock(mCore->mMutex);
756     mCore->mConsumerUsageBits = usage;
757     return NO_ERROR;
758 }
759 
setConsumerIsProtected(bool isProtected)760 status_t BufferQueueConsumer::setConsumerIsProtected(bool isProtected) {
761     ATRACE_CALL();
762     BQ_LOGV("setConsumerIsProtected: %s", isProtected ? "true" : "false");
763     std::lock_guard<std::mutex> lock(mCore->mMutex);
764     mCore->mConsumerIsProtected = isProtected;
765     return NO_ERROR;
766 }
767 
setTransformHint(uint32_t hint)768 status_t BufferQueueConsumer::setTransformHint(uint32_t hint) {
769     ATRACE_CALL();
770     BQ_LOGV("setTransformHint: %#x", hint);
771     std::lock_guard<std::mutex> lock(mCore->mMutex);
772     mCore->mTransformHint = hint;
773     return NO_ERROR;
774 }
775 
getSidebandStream(sp<NativeHandle> * outStream) const776 status_t BufferQueueConsumer::getSidebandStream(sp<NativeHandle>* outStream) const {
777     std::lock_guard<std::mutex> lock(mCore->mMutex);
778     *outStream = mCore->mSidebandStream;
779     return NO_ERROR;
780 }
781 
getOccupancyHistory(bool forceFlush,std::vector<OccupancyTracker::Segment> * outHistory)782 status_t BufferQueueConsumer::getOccupancyHistory(bool forceFlush,
783         std::vector<OccupancyTracker::Segment>* outHistory) {
784     std::lock_guard<std::mutex> lock(mCore->mMutex);
785 #ifndef NO_BINDER
786     *outHistory = mCore->mOccupancyTracker.getSegmentHistory(forceFlush);
787 #else
788     (void)forceFlush;
789     outHistory->clear();
790 #endif
791     return NO_ERROR;
792 }
793 
discardFreeBuffers()794 status_t BufferQueueConsumer::discardFreeBuffers() {
795     std::lock_guard<std::mutex> lock(mCore->mMutex);
796     mCore->discardFreeBuffersLocked();
797     return NO_ERROR;
798 }
799 
dumpState(const String8 & prefix,String8 * outResult) const800 status_t BufferQueueConsumer::dumpState(const String8& prefix, String8* outResult) const {
801     struct passwd* pwd = getpwnam("shell");
802     uid_t shellUid = pwd ? pwd->pw_uid : 0;
803     if (!shellUid) {
804         int savedErrno = errno;
805         BQ_LOGE("Cannot get AID_SHELL");
806         return savedErrno ? -savedErrno : UNKNOWN_ERROR;
807     }
808 
809     bool denied = false;
810     const uid_t uid = BufferQueueThreadState::getCallingUid();
811 #if !defined(__ANDROID_VNDK__) && !defined(NO_BINDER)
812     // permission check can't be done for vendors as vendors have no access to
813     // the PermissionController.
814     const pid_t pid = BufferQueueThreadState::getCallingPid();
815     if ((uid != shellUid) &&
816         !PermissionCache::checkPermission(String16("android.permission.DUMP"), pid, uid)) {
817         outResult->appendFormat("Permission Denial: can't dump BufferQueueConsumer "
818                                 "from pid=%d, uid=%d\n",
819                                 pid, uid);
820         denied = true;
821     }
822 #else
823     if (uid != shellUid) {
824         denied = true;
825     }
826 #endif
827     if (denied) {
828         android_errorWriteWithInfoLog(0x534e4554, "27046057",
829                 static_cast<int32_t>(uid), nullptr, 0);
830         return PERMISSION_DENIED;
831     }
832 
833     mCore->dumpState(prefix, outResult);
834     return NO_ERROR;
835 }
836 
setAllowExtraAcquire(bool allow)837 void BufferQueueConsumer::setAllowExtraAcquire(bool allow) {
838     std::lock_guard<std::mutex> lock(mCore->mMutex);
839     mCore->mAllowExtraAcquire = allow;
840 }
841 
842 } // namespace android
843