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