blob: aaad0f87fe672d553b44a41509e03d6527f78213 [file] [log] [blame]
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001/*
2 * Copyright (C) 2007 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#define ATRACE_TAG ATRACE_TAG_GRAPHICS
18
Mark Salyzyn7823e122016-09-29 08:08:05 -070019#include <dlfcn.h>
20#include <errno.h>
21#include <inttypes.h>
22#include <math.h>
23#include <stdatomic.h>
Fabien Sanglard9d96de42016-10-11 00:15:18 +000024#include <stdint.h>
25#include <sys/types.h>
Dan Stoza9e56aa02015-11-02 13:00:03 -080026
Fabien Sanglard9d96de42016-10-11 00:15:18 +000027#include <mutex>
Fabien Sanglard9d96de42016-10-11 00:15:18 +000028
29#include <EGL/egl.h>
30
Fabien Sanglard9d96de42016-10-11 00:15:18 +000031#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070032#include <log/log.h>
Fabien Sanglard9d96de42016-10-11 00:15:18 +000033
34#include <binder/IPCThreadState.h>
35#include <binder/IServiceManager.h>
36#include <binder/MemoryHeapBase.h>
37#include <binder/PermissionCache.h>
38
39#include <ui/DisplayInfo.h>
40#include <ui/DisplayStatInfo.h>
41
42#include <gui/BitTube.h>
43#include <gui/BufferQueue.h>
44#include <gui/GuiConfig.h>
45#include <gui/IDisplayEventConnection.h>
46#include <gui/Surface.h>
47#include <gui/GraphicBufferAlloc.h>
48
49#include <ui/GraphicBufferAllocator.h>
50#include <ui/HdrCapabilities.h>
51#include <ui/PixelFormat.h>
52#include <ui/UiConfig.h>
53
54#include <utils/misc.h>
55#include <utils/String8.h>
56#include <utils/String16.h>
57#include <utils/StopWatch.h>
58#include <utils/Timers.h>
59#include <utils/Trace.h>
60
61#include <private/android_filesystem_config.h>
62#include <private/gui/SyncFeatures.h>
63
64#include <set>
65
66#include "Client.h"
67#include "clz.h"
68#include "Colorizer.h"
69#include "DdmConnection.h"
70#include "DisplayDevice.h"
71#include "DispSync.h"
72#include "EventControlThread.h"
73#include "EventThread.h"
74#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070075#include "LayerVector.h"
Fabien Sanglard9d96de42016-10-11 00:15:18 +000076#include "LayerDim.h"
Robert Carr1db73f62016-12-21 12:58:51 -080077#include "MonitoredProducer.h"
Fabien Sanglard9d96de42016-10-11 00:15:18 +000078#include "SurfaceFlinger.h"
79
80#include "DisplayHardware/FramebufferSurface.h"
81#include "DisplayHardware/HWComposer.h"
82#include "DisplayHardware/VirtualDisplaySurface.h"
83
84#include "Effects/Daltonizer.h"
85
86#include "RenderEngine/RenderEngine.h"
87#include <cutils/compiler.h>
88
89#define DISPLAY_COUNT 1
90
91/*
92 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
93 * black pixels.
94 */
95#define DEBUG_SCREENSHOTS false
96
97EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
98
Fabien Sanglard9d96de42016-10-11 00:15:18 +000099namespace android {
100
101// This is the phase offset in nanoseconds of the software vsync event
102// relative to the vsync event reported by HWComposer. The software vsync
103// event is when SurfaceFlinger and Choreographer-based applications run each
104// frame.
105//
106// This phase offset allows adjustment of the minimum latency from application
107// wake-up (by Choregographer) time to the time at which the resulting window
108// image is displayed. This value may be either positive (after the HW vsync)
109// or negative (before the HW vsync). Setting it to 0 will result in a
110// minimum latency of two vsync periods because the app and SurfaceFlinger
111// will run just after the HW vsync. Setting it to a positive number will
112// result in the minimum latency being:
113//
114// (2 * VSYNC_PERIOD - (vsyncPhaseOffsetNs % VSYNC_PERIOD))
115//
116// Note that reducing this latency makes it more likely for the applications
117// to not have their window content image ready in time. When this happens
118// the latency will end up being an additional vsync period, and animations
119// will hiccup. Therefore, this latency should be tuned somewhat
120// conservatively (or at least with awareness of the trade-off being made).
121static const int64_t vsyncPhaseOffsetNs = VSYNC_EVENT_PHASE_OFFSET_NS;
122
123// This is the phase offset at which SurfaceFlinger's composition runs.
124static const int64_t sfVsyncPhaseOffsetNs = SF_VSYNC_EVENT_PHASE_OFFSET_NS;
125
126// ---------------------------------------------------------------------------
127
128const String16 sHardwareTest("android.permission.HARDWARE_TEST");
129const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
130const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
131const String16 sDump("android.permission.DUMP");
132
133// ---------------------------------------------------------------------------
134
135SurfaceFlinger::SurfaceFlinger()
136 : BnSurfaceComposer(),
137 mTransactionFlags(0),
138 mTransactionPending(false),
139 mAnimTransactionPending(false),
140 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700141 mLayersAdded(false),
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000142 mRepaintEverything(0),
143 mRenderEngine(NULL),
144 mBootTime(systemTime()),
145 mVisibleRegionsDirty(false),
146 mHwWorkListDirty(false),
147 mAnimCompositionPending(false),
148 mDebugRegion(0),
149 mDebugDDMS(0),
150 mDebugDisableHWC(0),
151 mDebugDisableTransformHint(0),
152 mDebugInSwapBuffers(0),
153 mLastSwapBufferTime(0),
154 mDebugInTransaction(0),
155 mLastTransactionTime(0),
156 mBootFinished(false),
157 mForceFullDamage(false),
158 mInterceptor(),
159 mPrimaryDispSync("PrimaryDispSync"),
160 mPrimaryHWVsyncEnabled(false),
161 mHWVsyncAvailable(false),
162 mDaltonize(false),
163 mHasColorMatrix(false),
164 mHasPoweredOff(false),
165 mFrameBuckets(),
166 mTotalTime(0),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700167 mLastSwapTime(0),
168 mNumLayers(0)
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000169{
170 ALOGI("SurfaceFlinger is starting");
171
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000172 char value[PROPERTY_VALUE_MAX];
173
174 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
175 mGpuToCpuSupported = !atoi(value);
176
177 property_get("debug.sf.showupdates", value, "0");
178 mDebugRegion = atoi(value);
179
180 property_get("debug.sf.ddms", value, "0");
181 mDebugDDMS = atoi(value);
182 if (mDebugDDMS) {
183 if (!startDdmConnection()) {
184 // start failed, and DDMS debugging not enabled
185 mDebugDDMS = 0;
186 }
187 }
188 ALOGI_IF(mDebugRegion, "showupdates enabled");
189 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
190
191 property_get("debug.sf.disable_hwc_vds", value, "0");
192 mUseHwcVirtualDisplays = !atoi(value);
193 ALOGI_IF(!mUseHwcVirtualDisplays, "Disabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800194
195 property_get("ro.sf.disable_triple_buffer", value, "0");
196 mLayerTripleBufferingDisabled = !atoi(value);
197 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000198}
199
200void SurfaceFlinger::onFirstRef()
201{
202 mEventQueue.init(this);
203}
204
205SurfaceFlinger::~SurfaceFlinger()
206{
207 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
208 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
209 eglTerminate(display);
210}
211
212void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
213{
214 // the window manager died on us. prepare its eulogy.
215
216 // restore initial conditions (default device unblank, etc)
217 initializeDisplays();
218
219 // restart the boot-animation
220 startBootAnim();
221}
222
Robert Carr1db73f62016-12-21 12:58:51 -0800223static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000224 status_t err = client->initCheck();
225 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800226 return client;
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000227 }
Robert Carr1db73f62016-12-21 12:58:51 -0800228 return nullptr;
229}
230
231sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
232 return initClient(new Client(this));
233}
234
235sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
236 const sp<IGraphicBufferProducer>& gbp) {
237 if (authenticateSurfaceTexture(gbp) == false) {
238 return nullptr;
239 }
240 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
241 if (layer == nullptr) {
242 return nullptr;
243 }
244
245 return initClient(new Client(this, layer));
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000246}
247
248sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
249 bool secure)
250{
251 class DisplayToken : public BBinder {
252 sp<SurfaceFlinger> flinger;
253 virtual ~DisplayToken() {
254 // no more references, this display must be terminated
255 Mutex::Autolock _l(flinger->mStateLock);
256 flinger->mCurrentState.displays.removeItem(this);
257 flinger->setTransactionFlags(eDisplayTransactionNeeded);
258 }
259 public:
260 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
261 : flinger(flinger) {
262 }
263 };
264
265 sp<BBinder> token = new DisplayToken(this);
266
267 Mutex::Autolock _l(mStateLock);
268 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
269 info.displayName = displayName;
270 mCurrentState.displays.add(token, info);
271 mInterceptor.saveDisplayCreation(info);
272 return token;
273}
274
275void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
276 Mutex::Autolock _l(mStateLock);
277
278 ssize_t idx = mCurrentState.displays.indexOfKey(display);
279 if (idx < 0) {
280 ALOGW("destroyDisplay: invalid display token");
281 return;
282 }
283
284 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
285 if (!info.isVirtualDisplay()) {
286 ALOGE("destroyDisplay called for non-virtual display");
287 return;
288 }
289 mInterceptor.saveDisplayDeletion(info.displayId);
290 mCurrentState.displays.removeItemsAt(idx);
291 setTransactionFlags(eDisplayTransactionNeeded);
292}
293
294void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
295 ALOGW_IF(mBuiltinDisplays[type],
296 "Overwriting display token for display type %d", type);
297 mBuiltinDisplays[type] = new BBinder();
298 // All non-virtual displays are currently considered secure.
299 DisplayDeviceState info(type, true);
300 mCurrentState.displays.add(mBuiltinDisplays[type], info);
301 mInterceptor.saveDisplayCreation(info);
302}
303
304sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
305 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
306 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
307 return NULL;
308 }
309 return mBuiltinDisplays[id];
310}
311
312sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc()
313{
314 sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc());
315 return gba;
316}
317
318void SurfaceFlinger::bootFinished()
319{
Wei Wangb254fa32017-01-31 17:43:23 -0800320 if (mStartBootAnimThread->join() != NO_ERROR) {
321 ALOGE("Join StartBootAnimThread failed!");
322 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000323 const nsecs_t now = systemTime();
324 const nsecs_t duration = now - mBootTime;
325 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
326 mBootFinished = true;
327
328 // wait patiently for the window manager death
329 const String16 name("window");
330 sp<IBinder> window(defaultServiceManager()->getService(name));
331 if (window != 0) {
332 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
333 }
334
335 // stop boot animation
336 // formerly we would just kill the process, but we now ask it to exit so it
337 // can choose where to stop the animation.
338 property_set("service.bootanim.exit", "1");
339
340 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
341 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
342 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
343}
344
345void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
346 class MessageDestroyGLTexture : public MessageBase {
347 RenderEngine& engine;
348 uint32_t texture;
349 public:
350 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
351 : engine(engine), texture(texture) {
352 }
353 virtual bool handler() {
354 engine.deleteTextures(1, &texture);
355 return true;
356 }
357 };
358 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
359}
360
361class DispSyncSource : public VSyncSource, private DispSync::Callback {
362public:
363 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
364 const char* name) :
365 mName(name),
366 mValue(0),
367 mTraceVsync(traceVsync),
368 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
369 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
370 mDispSync(dispSync),
371 mCallbackMutex(),
372 mCallback(),
373 mVsyncMutex(),
374 mPhaseOffset(phaseOffset),
375 mEnabled(false) {}
376
377 virtual ~DispSyncSource() {}
378
379 virtual void setVSyncEnabled(bool enable) {
380 Mutex::Autolock lock(mVsyncMutex);
381 if (enable) {
382 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
383 static_cast<DispSync::Callback*>(this));
384 if (err != NO_ERROR) {
385 ALOGE("error registering vsync callback: %s (%d)",
386 strerror(-err), err);
387 }
388 //ATRACE_INT(mVsyncOnLabel.string(), 1);
389 } else {
390 status_t err = mDispSync->removeEventListener(
391 static_cast<DispSync::Callback*>(this));
392 if (err != NO_ERROR) {
393 ALOGE("error unregistering vsync callback: %s (%d)",
394 strerror(-err), err);
395 }
396 //ATRACE_INT(mVsyncOnLabel.string(), 0);
397 }
398 mEnabled = enable;
399 }
400
401 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
402 Mutex::Autolock lock(mCallbackMutex);
403 mCallback = callback;
404 }
405
406 virtual void setPhaseOffset(nsecs_t phaseOffset) {
407 Mutex::Autolock lock(mVsyncMutex);
408
409 // Normalize phaseOffset to [0, period)
410 auto period = mDispSync->getPeriod();
411 phaseOffset %= period;
412 if (phaseOffset < 0) {
413 // If we're here, then phaseOffset is in (-period, 0). After this
414 // operation, it will be in (0, period)
415 phaseOffset += period;
416 }
417 mPhaseOffset = phaseOffset;
418
419 // If we're not enabled, we don't need to mess with the listeners
420 if (!mEnabled) {
421 return;
422 }
423
424 // Remove the listener with the old offset
425 status_t err = mDispSync->removeEventListener(
426 static_cast<DispSync::Callback*>(this));
427 if (err != NO_ERROR) {
428 ALOGE("error unregistering vsync callback: %s (%d)",
429 strerror(-err), err);
430 }
431
432 // Add a listener with the new offset
433 err = mDispSync->addEventListener(mName, mPhaseOffset,
434 static_cast<DispSync::Callback*>(this));
435 if (err != NO_ERROR) {
436 ALOGE("error registering vsync callback: %s (%d)",
437 strerror(-err), err);
438 }
439 }
440
441private:
442 virtual void onDispSyncEvent(nsecs_t when) {
443 sp<VSyncSource::Callback> callback;
444 {
445 Mutex::Autolock lock(mCallbackMutex);
446 callback = mCallback;
447
448 if (mTraceVsync) {
449 mValue = (mValue + 1) % 2;
450 ATRACE_INT(mVsyncEventLabel.string(), mValue);
451 }
452 }
453
454 if (callback != NULL) {
455 callback->onVSyncEvent(when);
456 }
457 }
458
459 const char* const mName;
460
461 int mValue;
462
463 const bool mTraceVsync;
464 const String8 mVsyncOnLabel;
465 const String8 mVsyncEventLabel;
466
467 DispSync* mDispSync;
468
469 Mutex mCallbackMutex; // Protects the following
470 sp<VSyncSource::Callback> mCallback;
471
472 Mutex mVsyncMutex; // Protects the following
473 nsecs_t mPhaseOffset;
474 bool mEnabled;
475};
476
477class InjectVSyncSource : public VSyncSource {
478public:
479 InjectVSyncSource() {}
480
481 virtual ~InjectVSyncSource() {}
482
483 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
484 std::lock_guard<std::mutex> lock(mCallbackMutex);
485 mCallback = callback;
486 }
487
488 virtual void onInjectSyncEvent(nsecs_t when) {
489 std::lock_guard<std::mutex> lock(mCallbackMutex);
490 mCallback->onVSyncEvent(when);
491 }
492
493 virtual void setVSyncEnabled(bool) {}
494 virtual void setPhaseOffset(nsecs_t) {}
495
496private:
497 std::mutex mCallbackMutex; // Protects the following
498 sp<VSyncSource::Callback> mCallback;
499};
500
501void SurfaceFlinger::init() {
502 ALOGI( "SurfaceFlinger's main thread ready to run. "
503 "Initializing graphics H/W...");
504
505 Mutex::Autolock _l(mStateLock);
506
507 // initialize EGL for the default display
508 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
509 eglInitialize(mEGLDisplay, NULL, NULL);
510
511 // start the EventThread
512 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
513 vsyncPhaseOffsetNs, true, "app");
514 mEventThread = new EventThread(vsyncSrc, *this, false);
515 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
516 sfVsyncPhaseOffsetNs, true, "sf");
517 mSFEventThread = new EventThread(sfVsyncSrc, *this, true);
518 mEventQueue.setEventThread(mSFEventThread);
519
520 // set SFEventThread to SCHED_FIFO to minimize jitter
521 struct sched_param param = {0};
522 param.sched_priority = 2;
523 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
524 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
525 }
526
527
528 // Initialize the H/W composer object. There may or may not be an
529 // actual hardware composer underneath.
530 mHwc = new HWComposer(this,
531 *static_cast<HWComposer::EventHandler *>(this));
532
533 // get a RenderEngine for the given display / config (can't fail)
534 mRenderEngine = RenderEngine::create(mEGLDisplay, mHwc->getVisualID());
535
536 // retrieve the EGL context that was selected/created
537 mEGLContext = mRenderEngine->getEGLContext();
538
539 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
540 "couldn't create EGLContext");
541
542 // initialize our non-virtual displays
543 for (size_t i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
544 DisplayDevice::DisplayType type((DisplayDevice::DisplayType)i);
545 // set-up the displays that are already connected
546 if (mHwc->isConnected(i) || type==DisplayDevice::DISPLAY_PRIMARY) {
547 // All non-virtual displays are currently considered secure.
548 bool isSecure = true;
549 createBuiltinDisplayLocked(type);
550 wp<IBinder> token = mBuiltinDisplays[i];
551
552 sp<IGraphicBufferProducer> producer;
553 sp<IGraphicBufferConsumer> consumer;
554 BufferQueue::createBufferQueue(&producer, &consumer,
555 new GraphicBufferAlloc());
556
557 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc, i,
558 consumer);
559 int32_t hwcId = allocateHwcDisplayId(type);
560 sp<DisplayDevice> hw = new DisplayDevice(this,
561 type, hwcId, mHwc->getFormat(hwcId), isSecure, token,
562 fbs, producer,
563 mRenderEngine->getEGLConfig());
564 if (i > DisplayDevice::DISPLAY_PRIMARY) {
565 // FIXME: currently we don't get blank/unblank requests
566 // for displays other than the main display, so we always
567 // assume a connected display is unblanked.
568 ALOGD("marking display %zu as acquired/unblanked", i);
569 hw->setPowerMode(HWC_POWER_MODE_NORMAL);
570 }
571 mDisplays.add(token, hw);
572 }
573 }
574
575 // make the GLContext current so that we can create textures when creating Layers
576 // (which may happens before we render something)
577 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
578
579 mEventControlThread = new EventControlThread(this);
580 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
581
582 // set a fake vsync period if there is no HWComposer
583 if (mHwc->initCheck() != NO_ERROR) {
584 mPrimaryDispSync.setPeriod(16666667);
585 }
586
587 // initialize our drawing state
588 mDrawingState = mCurrentState;
589
590 // set initial conditions (e.g. unblank default device)
591 initializeDisplays();
592
593 mRenderEngine->primeCache();
594
Wei Wangb254fa32017-01-31 17:43:23 -0800595 mStartBootAnimThread = new StartBootAnimThread();
596 if (mStartBootAnimThread->Start() != NO_ERROR) {
597 ALOGE("Run StartBootAnimThread failed!");
598 }
599
600 ALOGV("Done initializing");
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000601}
602
603int32_t SurfaceFlinger::allocateHwcDisplayId(DisplayDevice::DisplayType type) {
604 return (uint32_t(type) < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) ?
605 type : mHwc->allocateDisplayId();
606}
607
608void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800609 // Start boot animation service by setting a property mailbox
610 // if property setting thread is already running, Start() will be just a NOP
611 mStartBootAnimThread->Start();
612 // Wait until property was set
613 if (mStartBootAnimThread->join() != NO_ERROR) {
614 ALOGE("Join StartBootAnimThread failed!");
615 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000616}
617
618size_t SurfaceFlinger::getMaxTextureSize() const {
619 return mRenderEngine->getMaxTextureSize();
620}
621
622size_t SurfaceFlinger::getMaxViewportDims() const {
623 return mRenderEngine->getMaxViewportDims();
624}
625
626// ----------------------------------------------------------------------------
627
628bool SurfaceFlinger::authenticateSurfaceTexture(
629 const sp<IGraphicBufferProducer>& bufferProducer) const {
630 Mutex::Autolock _l(mStateLock);
631 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
632 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
633}
634
Brian Anderson069b3652016-07-22 10:32:47 -0700635status_t SurfaceFlinger::getSupportedFrameTimestamps(
Brian Anderson3890c392016-07-25 12:48:08 -0700636 std::vector<FrameEvent>* outSupported) const {
Brian Anderson069b3652016-07-22 10:32:47 -0700637 *outSupported = {
Brian Anderson3890c392016-07-25 12:48:08 -0700638 FrameEvent::REQUESTED_PRESENT,
639 FrameEvent::ACQUIRE,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700640 FrameEvent::LATCH,
Brian Anderson3890c392016-07-25 12:48:08 -0700641 FrameEvent::FIRST_REFRESH_START,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700642 FrameEvent::LAST_REFRESH_START,
Brian Anderson3890c392016-07-25 12:48:08 -0700643 FrameEvent::GL_COMPOSITION_DONE,
644 FrameEvent::DISPLAY_RETIRE,
Brian Andersonf7fd56a2016-09-02 10:10:04 -0700645 FrameEvent::DEQUEUE_READY,
Brian Anderson3890c392016-07-25 12:48:08 -0700646 FrameEvent::RELEASE,
Brian Anderson069b3652016-07-22 10:32:47 -0700647 };
648 return NO_ERROR;
649}
650
Fabien Sanglard9d96de42016-10-11 00:15:18 +0000651status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
652 Vector<DisplayInfo>* configs) {
653 if ((configs == NULL) || (display.get() == NULL)) {
654 return BAD_VALUE;
655 }
656
657 int32_t type = getDisplayType(display);
658 if (type < 0) return type;
659
660 // TODO: Not sure if display density should handled by SF any longer
661 class Density {
662 static int getDensityFromProperty(char const* propName) {
663 char property[PROPERTY_VALUE_MAX];
664 int density = 0;
665 if (property_get(propName, property, NULL) > 0) {
666 density = atoi(property);
667 }
668 return density;
669 }
670 public:
671 static int getEmuDensity() {
672 return getDensityFromProperty("qemu.sf.lcd_density"); }
673 static int getBuildDensity() {
674 return getDensityFromProperty("ro.sf.lcd_density"); }
675 };
676
677 configs->clear();
678
679 const Vector<HWComposer::DisplayConfig>& hwConfigs =
680 getHwComposer().getConfigs(type);
681 for (size_t c = 0; c < hwConfigs.size(); ++c) {
682 const HWComposer::DisplayConfig& hwConfig = hwConfigs[c];
683 DisplayInfo info = DisplayInfo();
684
685 float xdpi = hwConfig.xdpi;
686 float ydpi = hwConfig.ydpi;
687
688 if (type == DisplayDevice::DISPLAY_PRIMARY) {
689 // The density of the device is provided by a build property
690 float density = Density::getBuildDensity() / 160.0f;
691 if (density == 0) {
692 // the build doesn't provide a density -- this is wrong!
693 // use xdpi instead
694 ALOGE("ro.sf.lcd_density must be defined as a build property");
695 density = xdpi / 160.0f;
696 }
697 if (Density::getEmuDensity()) {
698 // if "qemu.sf.lcd_density" is specified, it overrides everything
699 xdpi = ydpi = density = Density::getEmuDensity();
700 density /= 160.0f;
701 }
702 info.density = density;
703
704 // TODO: this needs to go away (currently needed only by webkit)
705 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
706 info.orientation = hw->getOrientation();
707 } else {
708 // TODO: where should this value come from?
709 static const int TV_DENSITY = 213;
710 info.density = TV_DENSITY / 160.0f;
711 info.orientation = 0;
712 }
713
714 info.w = hwConfig.width;
715 info.h = hwConfig.height;
716 info.xdpi = xdpi;
717 info.ydpi = ydpi;
718 info.fps = float(1e9 / hwConfig.refresh);
719 info.appVsyncOffset = VSYNC_EVENT_PHASE_OFFSET_NS;
720
721 // This is how far in advance a buffer must be queued for
722 // presentation at a given time. If you want a buffer to appear
723 // on the screen at time N, you must submit the buffer before
724 // (N - presentationDeadline).
725 //
726 // Normally it's one full refresh period (to give SF a chance to
727 // latch the buffer), but this can be reduced by configuring a
728 // DispSync offset. Any additional delays introduced by the hardware
729 // composer or panel must be accounted for here.
730 //
731 // We add an additional 1ms to allow for processing time and
732 // differences between the ideal and actual refresh rate.
733 info.presentationDeadline =
734 hwConfig.refresh - SF_VSYNC_EVENT_PHASE_OFFSET_NS + 1000000;
735
736 // All non-virtual displays are currently considered secure.
737 info.secure = true;
738
739 configs->push_back(info);
740 }
741
742 return NO_ERROR;
743}
744
745status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
746 DisplayStatInfo* stats) {
747 if (stats == NULL) {
748 return BAD_VALUE;
749 }
750
751 // FIXME for now we always return stats for the primary display
752 memset(stats, 0, sizeof(*stats));
753 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
754 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
755 return NO_ERROR;
756}
757
758int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
759 sp<DisplayDevice> device(getDisplayDevice(display));
760 if (device != NULL) {
761 return device->getActiveConfig();
762 }
763 return BAD_VALUE;
764}
765
766void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
767 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
768 this);
769 int32_t type = hw->getDisplayType();
770 int currentMode = hw->getActiveConfig();
771
772 if (mode == currentMode) {
773 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
774 return;
775 }
776
777 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
778 ALOGW("Trying to set config for virtual display");
779 return;
780 }
781
782 hw->setActiveConfig(mode);
783 getHwComposer().setActiveConfig(type, mode);
784}
785
786status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
787 class MessageSetActiveConfig: public MessageBase {
788 SurfaceFlinger& mFlinger;
789 sp<IBinder> mDisplay;
790 int mMode;
791 public:
792 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
793 int mode) :
794 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
795 virtual bool handler() {
796 Vector<DisplayInfo> configs;
797 mFlinger.getDisplayConfigs(mDisplay, &configs);
798 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
799 ALOGE("Attempt to set active config = %d for display with %zu configs",
800 mMode, configs.size());
801 }
802 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
803 if (hw == NULL) {
804 ALOGE("Attempt to set active config = %d for null display %p",
805 mMode, mDisplay.get());
806 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
807 ALOGW("Attempt to set active config = %d for virtual display",
808 mMode);
809 } else {
810 mFlinger.setActiveConfigInternal(hw, mMode);
811 }
812 return true;
813 }
814 };
815 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
816 postMessageSync(msg);
817 return NO_ERROR;
818}
819
820status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
821 Vector<android_color_mode_t>* outColorModes) {
822 if (outColorModes == nullptr || display.get() == nullptr) {
823 return BAD_VALUE;
824 }
825
826 int32_t type = getDisplayType(display);
827 if (type < 0) return type;
828
829 std::set<android_color_mode_t> colorModes;
830 for (const HWComposer::DisplayConfig& hwConfig : getHwComposer().getConfigs(type)) {
831 colorModes.insert(hwConfig.colorMode);
832 }
833
834 outColorModes->clear();
835 std::copy(colorModes.cbegin(), colorModes.cend(), std::back_inserter(*outColorModes));
836
837 return NO_ERROR;
838}
839
840android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
841 if (display.get() == nullptr) return static_cast<android_color_mode_t>(BAD_VALUE);
842
843 int32_t type = getDisplayType(display);
844 if (type < 0) return static_cast<android_color_mode_t>(type);
845
846 return getHwComposer().getColorMode(type);
847}
848
849status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
850 android_color_mode_t colorMode) {
851 if (display.get() == nullptr || colorMode < 0) {
852 return BAD_VALUE;
853 }
854
855 int32_t type = getDisplayType(display);
856 if (type < 0) return type;
857 const Vector<HWComposer::DisplayConfig>& hwConfigs = getHwComposer().getConfigs(type);
858 HWComposer::DisplayConfig desiredConfig = hwConfigs[getHwComposer().getCurrentConfig(type)];
859 desiredConfig.colorMode = colorMode;
860 for (size_t c = 0; c < hwConfigs.size(); ++c) {
861 const HWComposer::DisplayConfig config = hwConfigs[c];
862 if (config == desiredConfig) {
863 return setActiveConfig(display, c);
864 }
865 }
866 return BAD_VALUE;
867}
868
869status_t SurfaceFlinger::clearAnimationFrameStats() {
870 Mutex::Autolock _l(mStateLock);
871 mAnimFrameTracker.clearStats();
872 return NO_ERROR;
873}
874
875status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
876 Mutex::Autolock _l(mStateLock);
877 mAnimFrameTracker.getStats(outStats);
878 return NO_ERROR;
879}
880
881status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& /*display*/,
882 HdrCapabilities* outCapabilities) const {
883 // HWC1 does not provide HDR capabilities
884 *outCapabilities = HdrCapabilities();
885 return NO_ERROR;
886}
887
888status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
889 if (enable == mInjectVSyncs) {
890 return NO_ERROR;
891 }
892
893 if (enable) {
894 mInjectVSyncs = enable;
895 ALOGV("VSync Injections enabled");
896 if (mVSyncInjector.get() == nullptr) {
897 mVSyncInjector = new InjectVSyncSource();
898 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
899 }
900 mEventQueue.setEventThread(mInjectorEventThread);
901 } else {
902 mInjectVSyncs = enable;
903 ALOGV("VSync Injections disabled");
904 mEventQueue.setEventThread(mSFEventThread);
905 mVSyncInjector.clear();
906 }
907 return NO_ERROR;
908}
909
910status_t SurfaceFlinger::injectVSync(nsecs_t when) {
911 if (!mInjectVSyncs) {
912 ALOGE("VSync Injections not enabled");
913 return BAD_VALUE;
914 }
915 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
916 ALOGV("Injecting VSync inside SurfaceFlinger");
917 mVSyncInjector->onInjectSyncEvent(when);
918 }
919 return NO_ERROR;
920}
921
922// ----------------------------------------------------------------------------
923
924sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
925 return mEventThread->createEventConnection();
926}
927
928// ----------------------------------------------------------------------------
929
930void SurfaceFlinger::waitForEvent() {
931 mEventQueue.waitMessage();
932}
933
934void SurfaceFlinger::signalTransaction() {
935 mEventQueue.invalidate();
936}
937
938void SurfaceFlinger::signalLayerUpdate() {
939 mEventQueue.invalidate();
940}
941
942void SurfaceFlinger::signalRefresh() {
943 mEventQueue.refresh();
944}
945
946status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
947 nsecs_t reltime, uint32_t /* flags */) {
948 return mEventQueue.postMessage(msg, reltime);
949}
950
951status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
952 nsecs_t reltime, uint32_t /* flags */) {
953 status_t res = mEventQueue.postMessage(msg, reltime);
954 if (res == NO_ERROR) {
955 msg->wait();
956 }
957 return res;
958}
959
960void SurfaceFlinger::run() {
961 do {
962 waitForEvent();
963 } while (true);
964}
965
966void SurfaceFlinger::enableHardwareVsync() {
967 Mutex::Autolock _l(mHWVsyncLock);
968 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
969 mPrimaryDispSync.beginResync();
970 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
971 mEventControlThread->setVsyncEnabled(true);
972 mPrimaryHWVsyncEnabled = true;
973 }
974}
975
976void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
977 Mutex::Autolock _l(mHWVsyncLock);
978
979 if (makeAvailable) {
980 mHWVsyncAvailable = true;
981 } else if (!mHWVsyncAvailable) {
982 // Hardware vsync is not currently available, so abort the resync
983 // attempt for now
984 return;
985 }
986
987 const nsecs_t period =
988 getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
989
990 mPrimaryDispSync.reset();
991 mPrimaryDispSync.setPeriod(period);
992
993 if (!mPrimaryHWVsyncEnabled) {
994 mPrimaryDispSync.beginResync();
995 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
996 mEventControlThread->setVsyncEnabled(true);
997 mPrimaryHWVsyncEnabled = true;
998 }
999}
1000
1001void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
1002 Mutex::Autolock _l(mHWVsyncLock);
1003 if (mPrimaryHWVsyncEnabled) {
1004 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1005 mEventControlThread->setVsyncEnabled(false);
1006 mPrimaryDispSync.endResync();
1007 mPrimaryHWVsyncEnabled = false;
1008 }
1009 if (makeUnavailable) {
1010 mHWVsyncAvailable = false;
1011 }
1012}
1013
1014void SurfaceFlinger::resyncWithRateLimit() {
1015 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
1016 if (systemTime() - mLastSwapTime > kIgnoreDelay) {
1017 resyncToHardwareVsync(false);
1018 }
1019}
1020
1021void SurfaceFlinger::onVSyncReceived(int type, nsecs_t timestamp) {
1022 bool needsHwVsync = false;
1023
1024 { // Scope for the lock
1025 Mutex::Autolock _l(mHWVsyncLock);
1026 if (type == 0 && mPrimaryHWVsyncEnabled) {
1027 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
1028 }
1029 }
1030
1031 if (needsHwVsync) {
1032 enableHardwareVsync();
1033 } else {
1034 disableHardwareVsync(false);
1035 }
1036}
1037
1038void SurfaceFlinger::onHotplugReceived(int type, bool connected) {
1039 if (mEventThread == NULL) {
1040 // This is a temporary workaround for b/7145521. A non-null pointer
1041 // does not mean EventThread has finished initializing, so this
1042 // is not a correct fix.
1043 ALOGW("WARNING: EventThread not started, ignoring hotplug");
1044 return;
1045 }
1046
1047 if (uint32_t(type) < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
1048 Mutex::Autolock _l(mStateLock);
1049 if (connected) {
1050 createBuiltinDisplayLocked((DisplayDevice::DisplayType)type);
1051 } else {
1052 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1053 mBuiltinDisplays[type].clear();
1054 }
1055 setTransactionFlags(eDisplayTransactionNeeded);
1056
1057 // Defer EventThread notification until SF has updated mDisplays.
1058 }
1059}
1060
1061void SurfaceFlinger::eventControl(int disp, int event, int enabled) {
1062 ATRACE_CALL();
1063 getHwComposer().eventControl(disp, event, enabled);
1064}
1065
1066void SurfaceFlinger::onMessageReceived(int32_t what) {
1067 ATRACE_CALL();
1068 switch (what) {
1069 case MessageQueue::INVALIDATE: {
1070 bool refreshNeeded = handleMessageTransaction();
1071 refreshNeeded |= handleMessageInvalidate();
1072 refreshNeeded |= mRepaintEverything;
1073 if (refreshNeeded) {
1074 // Signal a refresh if a transaction modified the window state,
1075 // a new buffer was latched, or if HWC has requested a full
1076 // repaint
1077 signalRefresh();
1078 }
1079 break;
1080 }
1081 case MessageQueue::REFRESH: {
1082 handleMessageRefresh();
1083 break;
1084 }
1085 }
1086}
1087
1088bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001089 uint32_t transactionFlags = peekTransactionFlags();
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001090 if (transactionFlags) {
1091 handleTransaction(transactionFlags);
1092 return true;
1093 }
1094 return false;
1095}
1096
1097bool SurfaceFlinger::handleMessageInvalidate() {
1098 ATRACE_CALL();
1099 return handlePageFlip();
1100}
1101
1102void SurfaceFlinger::handleMessageRefresh() {
1103 ATRACE_CALL();
1104
1105 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1106
Brian Andersond6927fb2016-07-23 23:37:30 -07001107 preComposition(refreshStartTime);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001108 rebuildLayerStacks();
1109 setUpHWComposer();
1110 doDebugFlashRegions();
1111 doComposition();
Brian Andersond6927fb2016-07-23 23:37:30 -07001112 postComposition();
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001113}
1114
1115void SurfaceFlinger::doDebugFlashRegions()
1116{
1117 // is debugging enabled
1118 if (CC_LIKELY(!mDebugRegion))
1119 return;
1120
1121 const bool repaintEverything = mRepaintEverything;
1122 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1123 const sp<DisplayDevice>& hw(mDisplays[dpy]);
1124 if (hw->isDisplayOn()) {
1125 // transform the dirty region into this screen's coordinate space
1126 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1127 if (!dirtyRegion.isEmpty()) {
1128 // redraw the whole screen
1129 doComposeSurfaces(hw, Region(hw->bounds()));
1130
1131 // and draw the dirty region
1132 const int32_t height = hw->getHeight();
1133 RenderEngine& engine(getRenderEngine());
1134 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1135
1136 hw->compositionComplete();
1137 hw->swapBuffers(getHwComposer());
1138 }
1139 }
1140 }
1141
1142 postFramebuffer();
1143
1144 if (mDebugRegion > 1) {
1145 usleep(mDebugRegion * 1000);
1146 }
1147
1148 HWComposer& hwc(getHwComposer());
1149 if (hwc.initCheck() == NO_ERROR) {
1150 status_t err = hwc.prepare();
1151 ALOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err));
1152 }
1153}
1154
Brian Andersond6927fb2016-07-23 23:37:30 -07001155void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001156{
1157 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001158 mDrawingState.traverseInZOrder([&](Layer* layer) {
1159 if (layer->onPreComposition(refreshStartTime)) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001160 needExtraInvalidate = true;
1161 }
Robert Carr2047fae2016-11-28 14:09:09 -08001162 });
1163
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001164 if (needExtraInvalidate) {
1165 signalLayerUpdate();
1166 }
1167}
1168
Brian Andersond6927fb2016-07-23 23:37:30 -07001169void SurfaceFlinger::postComposition()
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001170{
Brian Andersond6927fb2016-07-23 23:37:30 -07001171 const HWComposer& hwc = getHwComposer();
1172 const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
1173
Brian Anderson3d4039d2016-09-23 16:31:30 -07001174 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1175 if (getHwComposer().hasGlesComposition(hw->getHwcDisplayId())) {
1176 glCompositionDoneFenceTime =
1177 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1178 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1179 } else {
1180 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1181 }
1182 mGlCompositionDoneTimeline.updateSignalTimes();
1183
1184 sp<Fence> displayFence = mHwc->getDisplayFence(HWC_DISPLAY_PRIMARY);
1185 const std::shared_ptr<FenceTime>& presentFenceTime = FenceTime::NO_FENCE;
1186 auto retireFenceTime = std::make_shared<FenceTime>(displayFence);
1187 mDisplayTimeline.push(retireFenceTime);
1188 mDisplayTimeline.updateSignalTimes();
Brian Andersond6927fb2016-07-23 23:37:30 -07001189
Robert Carr2047fae2016-11-28 14:09:09 -08001190 mDrawingState.traverseInZOrder([&](Layer* layer) {
1191 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
1192 presentFenceTime, retireFenceTime);
1193
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001194 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001195 recordBufferingStats(layer->getName().string(),
1196 layer->getOccupancyHistory(false));
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001197 }
Robert Carr2047fae2016-11-28 14:09:09 -08001198 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001199
Brian Anderson3d4039d2016-09-23 16:31:30 -07001200 if (displayFence->isValid()) {
1201 if (mPrimaryDispSync.addPresentFence(displayFence)) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001202 enableHardwareVsync();
1203 } else {
1204 disableHardwareVsync(false);
1205 }
1206 }
1207
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001208 if (kIgnorePresentFences) {
1209 if (hw->isDisplayOn()) {
1210 enableHardwareVsync();
1211 }
1212 }
1213
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001214 if (mAnimCompositionPending) {
1215 mAnimCompositionPending = false;
1216
Brian Anderson3d4039d2016-09-23 16:31:30 -07001217 if (retireFenceTime->isValid()) {
1218 mAnimFrameTracker.setActualPresentFence(std::move(retireFenceTime));
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001219 } else {
1220 // The HWC doesn't support present fences, so use the refresh
1221 // timestamp instead.
1222 nsecs_t presentTime = hwc.getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
1223 mAnimFrameTracker.setActualPresentTime(presentTime);
1224 }
1225 mAnimFrameTracker.advanceFrame();
1226 }
1227
1228 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1229 return;
1230 }
1231
1232 nsecs_t currentTime = systemTime();
1233 if (mHasPoweredOff) {
1234 mHasPoweredOff = false;
1235 } else {
1236 nsecs_t period = mPrimaryDispSync.getPeriod();
1237 nsecs_t elapsedTime = currentTime - mLastSwapTime;
1238 size_t numPeriods = static_cast<size_t>(elapsedTime / period);
1239 if (numPeriods < NUM_BUCKETS - 1) {
1240 mFrameBuckets[numPeriods] += elapsedTime;
1241 } else {
1242 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1243 }
1244 mTotalTime += elapsedTime;
1245 }
1246 mLastSwapTime = currentTime;
1247}
1248
1249void SurfaceFlinger::rebuildLayerStacks() {
1250 // rebuild the visible layer list per screen
1251 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
1252 ATRACE_CALL();
1253 mVisibleRegionsDirty = false;
1254 invalidateHwcGeometry();
1255
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001256 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1257 Region opaqueRegion;
1258 Region dirtyRegion;
1259 Vector< sp<Layer> > layersSortedByZ;
1260 const sp<DisplayDevice>& hw(mDisplays[dpy]);
1261 const Transform& tr(hw->getTransform());
1262 const Rect bounds(hw->getBounds());
1263 if (hw->isDisplayOn()) {
Robert Carr2047fae2016-11-28 14:09:09 -08001264 computeVisibleRegions(hw->getLayerStack(), dirtyRegion,
1265 opaqueRegion);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001266
Robert Carr2047fae2016-11-28 14:09:09 -08001267 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001268 if (layer->getLayerStack() == hw->getLayerStack()) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001269 Region drawRegion(tr.transform(
1270 layer->visibleNonTransparentRegion));
1271 drawRegion.andSelf(bounds);
1272 if (!drawRegion.isEmpty()) {
1273 layersSortedByZ.add(layer);
1274 }
1275 }
Robert Carr2047fae2016-11-28 14:09:09 -08001276 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001277 }
1278 hw->setVisibleLayersSortedByZ(layersSortedByZ);
1279 hw->undefinedRegion.set(bounds);
1280 hw->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
1281 hw->dirtyRegion.orSelf(dirtyRegion);
1282 }
1283 }
1284}
1285
1286void SurfaceFlinger::setUpHWComposer() {
1287 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1288 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1289 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1290 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1291
1292 // If nothing has changed (!dirty), don't recompose.
1293 // If something changed, but we don't currently have any visible layers,
1294 // and didn't when we last did a composition, then skip it this time.
1295 // The second rule does two things:
1296 // - When all layers are removed from a display, we'll emit one black
1297 // frame, then nothing more until we get new layers.
1298 // - When a display is created with a private layer stack, we won't
1299 // emit any black frames until a layer is added to the layer stack.
1300 bool mustRecompose = dirty && !(empty && wasEmpty);
1301
1302 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1303 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1304 mustRecompose ? "doing" : "skipping",
1305 dirty ? "+" : "-",
1306 empty ? "+" : "-",
1307 wasEmpty ? "+" : "-");
1308
1309 mDisplays[dpy]->beginFrame(mustRecompose);
1310
1311 if (mustRecompose) {
1312 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1313 }
1314 }
1315
1316 HWComposer& hwc(getHwComposer());
1317 if (hwc.initCheck() == NO_ERROR) {
1318 // build the h/w work list
1319 if (CC_UNLIKELY(mHwWorkListDirty)) {
1320 mHwWorkListDirty = false;
1321 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1322 sp<const DisplayDevice> hw(mDisplays[dpy]);
1323 const int32_t id = hw->getHwcDisplayId();
1324 if (id >= 0) {
1325 const Vector< sp<Layer> >& currentLayers(
1326 hw->getVisibleLayersSortedByZ());
1327 const size_t count = currentLayers.size();
1328 if (hwc.createWorkList(id, count) == NO_ERROR) {
1329 HWComposer::LayerListIterator cur = hwc.begin(id);
1330 const HWComposer::LayerListIterator end = hwc.end(id);
1331 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1332 const sp<Layer>& layer(currentLayers[i]);
1333 layer->setGeometry(hw, *cur);
1334 if (mDebugDisableHWC || mDebugRegion || mDaltonize || mHasColorMatrix) {
1335 cur->setSkip(true);
1336 }
1337 }
1338 }
1339 }
1340 }
1341 }
1342
1343 // set the per-frame data
1344 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1345 sp<const DisplayDevice> hw(mDisplays[dpy]);
1346 const int32_t id = hw->getHwcDisplayId();
1347 if (id >= 0) {
1348 const Vector< sp<Layer> >& currentLayers(
1349 hw->getVisibleLayersSortedByZ());
1350 const size_t count = currentLayers.size();
1351 HWComposer::LayerListIterator cur = hwc.begin(id);
1352 const HWComposer::LayerListIterator end = hwc.end(id);
1353 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1354 /*
1355 * update the per-frame h/w composer data for each layer
1356 * and build the transparent region of the FB
1357 */
1358 const sp<Layer>& layer(currentLayers[i]);
1359 layer->setPerFrameData(hw, *cur);
1360 }
1361 }
1362 }
1363
1364 // If possible, attempt to use the cursor overlay on each display.
1365 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1366 sp<const DisplayDevice> hw(mDisplays[dpy]);
1367 const int32_t id = hw->getHwcDisplayId();
1368 if (id >= 0) {
1369 const Vector< sp<Layer> >& currentLayers(
1370 hw->getVisibleLayersSortedByZ());
1371 const size_t count = currentLayers.size();
1372 HWComposer::LayerListIterator cur = hwc.begin(id);
1373 const HWComposer::LayerListIterator end = hwc.end(id);
1374 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1375 const sp<Layer>& layer(currentLayers[i]);
1376 if (layer->isPotentialCursor()) {
1377 cur->setIsCursorLayerHint();
1378 break;
1379 }
1380 }
1381 }
1382 }
1383
1384 status_t err = hwc.prepare();
1385 ALOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err));
1386
1387 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1388 sp<const DisplayDevice> hw(mDisplays[dpy]);
1389 hw->prepareFrame(hwc);
1390 }
1391 }
1392}
1393
1394void SurfaceFlinger::doComposition() {
1395 ATRACE_CALL();
1396 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
1397 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1398 const sp<DisplayDevice>& hw(mDisplays[dpy]);
1399 if (hw->isDisplayOn()) {
1400 // transform the dirty region into this screen's coordinate space
1401 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1402
1403 // repaint the framebuffer (if needed)
1404 doDisplayComposition(hw, dirtyRegion);
1405
1406 hw->dirtyRegion.clear();
1407 hw->flip(hw->swapRegion);
1408 hw->swapRegion.clear();
1409 }
1410 // inform the h/w that we're done compositing
1411 hw->compositionComplete();
1412 }
1413 postFramebuffer();
1414}
1415
1416void SurfaceFlinger::postFramebuffer()
1417{
1418 ATRACE_CALL();
1419
1420 const nsecs_t now = systemTime();
1421 mDebugInSwapBuffers = now;
1422
1423 HWComposer& hwc(getHwComposer());
1424 if (hwc.initCheck() == NO_ERROR) {
1425 if (!hwc.supportsFramebufferTarget()) {
1426 // EGL spec says:
1427 // "surface must be bound to the calling thread's current context,
1428 // for the current rendering API."
1429 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
1430 }
1431 hwc.commit();
1432 }
1433
1434 // make the default display current because the VirtualDisplayDevice code cannot
1435 // deal with dequeueBuffer() being called outside of the composition loop; however
1436 // the code below can call glFlush() which is allowed (and does in some case) call
1437 // dequeueBuffer().
1438 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
1439
1440 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1441 sp<const DisplayDevice> hw(mDisplays[dpy]);
1442 const Vector< sp<Layer> >& currentLayers(hw->getVisibleLayersSortedByZ());
1443 hw->onSwapBuffersCompleted(hwc);
1444 const size_t count = currentLayers.size();
1445 int32_t id = hw->getHwcDisplayId();
1446 if (id >=0 && hwc.initCheck() == NO_ERROR) {
1447 HWComposer::LayerListIterator cur = hwc.begin(id);
1448 const HWComposer::LayerListIterator end = hwc.end(id);
1449 for (size_t i = 0; cur != end && i < count; ++i, ++cur) {
1450 currentLayers[i]->onLayerDisplayed(hw, &*cur);
1451 }
1452 } else {
1453 for (size_t i = 0; i < count; i++) {
1454 currentLayers[i]->onLayerDisplayed(hw, NULL);
1455 }
1456 }
1457 }
1458
1459 mLastSwapBufferTime = systemTime() - now;
1460 mDebugInSwapBuffers = 0;
1461
1462 uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
1463 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1464 logFrameStats();
1465 }
1466}
1467
1468void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
1469{
1470 ATRACE_CALL();
1471
1472 // here we keep a copy of the drawing state (that is the state that's
1473 // going to be overwritten by handleTransactionLocked()) outside of
1474 // mStateLock so that the side-effects of the State assignment
1475 // don't happen with mStateLock held (which can cause deadlocks).
1476 State drawingState(mDrawingState);
1477
1478 Mutex::Autolock _l(mStateLock);
1479 const nsecs_t now = systemTime();
1480 mDebugInTransaction = now;
1481
1482 // Here we're guaranteed that some transaction flags are set
1483 // so we can call handleTransactionLocked() unconditionally.
1484 // We call getTransactionFlags(), which will also clear the flags,
1485 // with mStateLock held to guarantee that mCurrentState won't change
1486 // until the transaction is committed.
1487
1488 transactionFlags = getTransactionFlags(eTransactionMask);
1489 handleTransactionLocked(transactionFlags);
1490
1491 mLastTransactionTime = systemTime() - now;
1492 mDebugInTransaction = 0;
1493 invalidateHwcGeometry();
1494 // here the transaction has been committed
1495}
1496
1497void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
1498{
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001499 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08001500 mCurrentState.traverseInZOrder([](Layer* layer) {
1501 layer->notifyAvailableFrames();
1502 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001503
1504 /*
1505 * Traversal of the children
1506 * (perform the transaction for each of them if needed)
1507 */
1508
1509 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08001510 mCurrentState.traverseInZOrder([&](Layer* layer) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001511 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08001512 if (!trFlags) return;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001513
1514 const uint32_t flags = layer->doTransaction(0);
1515 if (flags & Layer::eVisibleRegion)
1516 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08001517 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001518 }
1519
1520 /*
1521 * Perform display own transactions if needed
1522 */
1523
1524 if (transactionFlags & eDisplayTransactionNeeded) {
1525 // here we take advantage of Vector's copy-on-write semantics to
1526 // improve performance by skipping the transaction entirely when
1527 // know that the lists are identical
1528 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1529 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
1530 if (!curr.isIdenticalTo(draw)) {
1531 mVisibleRegionsDirty = true;
1532 const size_t cc = curr.size();
1533 size_t dc = draw.size();
1534
1535 // find the displays that were removed
1536 // (ie: in drawing state but not in current state)
1537 // also handle displays that changed
1538 // (ie: displays that are in both lists)
1539 for (size_t i=0 ; i<dc ; i++) {
1540 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1541 if (j < 0) {
1542 // in drawing state but not in current state
1543 if (!draw[i].isMainDisplay()) {
1544 // Call makeCurrent() on the primary display so we can
1545 // be sure that nothing associated with this display
1546 // is current.
1547 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
1548 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
1549 sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1550 if (hw != NULL)
1551 hw->disconnect(getHwComposer());
1552 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
1553 mEventThread->onHotplugReceived(draw[i].type, false);
1554 mDisplays.removeItem(draw.keyAt(i));
1555 } else {
1556 ALOGW("trying to remove the main display");
1557 }
1558 } else {
1559 // this display is in both lists. see if something changed.
1560 const DisplayDeviceState& state(curr[j]);
1561 const wp<IBinder>& display(curr.keyAt(j));
1562 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
1563 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
1564 if (state_binder != draw_binder) {
1565 // changing the surface is like destroying and
1566 // recreating the DisplayDevice, so we just remove it
1567 // from the drawing state, so that it get re-added
1568 // below.
1569 sp<DisplayDevice> hw(getDisplayDevice(display));
1570 if (hw != NULL)
1571 hw->disconnect(getHwComposer());
1572 mDisplays.removeItem(display);
1573 mDrawingState.displays.removeItemsAt(i);
1574 dc--; i--;
1575 // at this point we must loop to the next item
1576 continue;
1577 }
1578
1579 const sp<DisplayDevice> disp(getDisplayDevice(display));
1580 if (disp != NULL) {
1581 if (state.layerStack != draw[i].layerStack) {
1582 disp->setLayerStack(state.layerStack);
1583 }
1584 if ((state.orientation != draw[i].orientation)
1585 || (state.viewport != draw[i].viewport)
1586 || (state.frame != draw[i].frame))
1587 {
1588 disp->setProjection(state.orientation,
1589 state.viewport, state.frame);
1590 }
1591 if (state.width != draw[i].width || state.height != draw[i].height) {
1592 disp->setDisplaySize(state.width, state.height);
1593 }
1594 }
1595 }
1596 }
1597
1598 // find displays that were added
1599 // (ie: in current state but not in drawing state)
1600 for (size_t i=0 ; i<cc ; i++) {
1601 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
1602 const DisplayDeviceState& state(curr[i]);
1603
1604 sp<DisplaySurface> dispSurface;
1605 sp<IGraphicBufferProducer> producer;
1606 sp<IGraphicBufferProducer> bqProducer;
1607 sp<IGraphicBufferConsumer> bqConsumer;
1608 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer,
1609 new GraphicBufferAlloc());
1610
1611 int32_t hwcDisplayId = -1;
1612 if (state.isVirtualDisplay()) {
1613 // Virtual displays without a surface are dormant:
1614 // they have external state (layer stack, projection,
1615 // etc.) but no internal state (i.e. a DisplayDevice).
1616 if (state.surface != NULL) {
1617
1618 int width = 0;
1619 int status = state.surface->query(
1620 NATIVE_WINDOW_WIDTH, &width);
1621 ALOGE_IF(status != NO_ERROR,
1622 "Unable to query width (%d)", status);
1623 int height = 0;
1624 status = state.surface->query(
1625 NATIVE_WINDOW_HEIGHT, &height);
1626 ALOGE_IF(status != NO_ERROR,
1627 "Unable to query height (%d)", status);
1628 if (mUseHwcVirtualDisplays &&
1629 (MAX_VIRTUAL_DISPLAY_DIMENSION == 0 ||
1630 (width <= MAX_VIRTUAL_DISPLAY_DIMENSION &&
1631 height <= MAX_VIRTUAL_DISPLAY_DIMENSION))) {
1632 hwcDisplayId = allocateHwcDisplayId(state.type);
1633 }
1634
1635 sp<VirtualDisplaySurface> vds = new VirtualDisplaySurface(
1636 *mHwc, hwcDisplayId, state.surface,
1637 bqProducer, bqConsumer, state.displayName);
1638
1639 dispSurface = vds;
1640 producer = vds;
1641 }
1642 } else {
1643 ALOGE_IF(state.surface!=NULL,
1644 "adding a supported display, but rendering "
1645 "surface is provided (%p), ignoring it",
1646 state.surface.get());
1647 hwcDisplayId = allocateHwcDisplayId(state.type);
1648 // for supported (by hwc) displays we provide our
1649 // own rendering surface
1650 dispSurface = new FramebufferSurface(*mHwc, state.type,
1651 bqConsumer);
1652 producer = bqProducer;
1653 }
1654
1655 const wp<IBinder>& display(curr.keyAt(i));
1656 if (dispSurface != NULL) {
1657 sp<DisplayDevice> hw = new DisplayDevice(this,
1658 state.type, hwcDisplayId,
1659 mHwc->getFormat(hwcDisplayId), state.isSecure,
1660 display, dispSurface, producer,
1661 mRenderEngine->getEGLConfig());
1662 hw->setLayerStack(state.layerStack);
1663 hw->setProjection(state.orientation,
1664 state.viewport, state.frame);
1665 hw->setDisplayName(state.displayName);
1666 mDisplays.add(display, hw);
1667 if (state.isVirtualDisplay()) {
1668 if (hwcDisplayId >= 0) {
1669 mHwc->setVirtualDisplayProperties(hwcDisplayId,
1670 hw->getWidth(), hw->getHeight(),
1671 hw->getFormat());
1672 }
1673 } else {
1674 mEventThread->onHotplugReceived(state.type, true);
1675 }
1676 }
1677 }
1678 }
1679 }
1680 }
1681
1682 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
1683 // The transform hint might have changed for some layers
1684 // (either because a display has changed, or because a layer
1685 // as changed).
1686 //
1687 // Walk through all the layers in currentLayers,
1688 // and update their transform hint.
1689 //
1690 // If a layer is visible only on a single display, then that
1691 // display is used to calculate the hint, otherwise we use the
1692 // default display.
1693 //
1694 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
1695 // the hint is set before we acquire a buffer from the surface texture.
1696 //
1697 // NOTE: layer transactions have taken place already, so we use their
1698 // drawing state. However, SurfaceFlinger's own transaction has not
1699 // happened yet, so we must use the current state layer list
1700 // (soon to become the drawing state list).
1701 //
1702 sp<const DisplayDevice> disp;
1703 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08001704 bool first = true;
1705 mCurrentState.traverseInZOrder([&](Layer* layer) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001706 // NOTE: we rely on the fact that layers are sorted by
1707 // layerStack first (so we don't have to traverse the list
1708 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07001709 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08001710 if (first || currentlayerStack != layerStack) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001711 currentlayerStack = layerStack;
1712 // figure out if this layerstack is mirrored
1713 // (more than one display) if so, pick the default display,
1714 // if not, pick the only display it's on.
1715 disp.clear();
1716 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1717 sp<const DisplayDevice> hw(mDisplays[dpy]);
1718 if (hw->getLayerStack() == currentlayerStack) {
1719 if (disp == NULL) {
1720 disp = hw;
1721 } else {
1722 disp = NULL;
1723 break;
1724 }
1725 }
1726 }
1727 }
1728 if (disp == NULL) {
1729 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
1730 // redraw after transform hint changes. See bug 8508397.
1731
1732 // could be null when this layer is using a layerStack
1733 // that is not visible on any display. Also can occur at
1734 // screen off/on times.
1735 disp = getDefaultDisplayDevice();
1736 }
1737 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08001738
1739 first = false;
1740 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001741 }
1742
1743
1744 /*
1745 * Perform our own transaction if needed
1746 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07001747
1748 if (mLayersAdded) {
1749 mLayersAdded = false;
1750 // Layers have been added.
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001751 mVisibleRegionsDirty = true;
1752 }
1753
1754 // some layers might have been removed, so
1755 // we need to update the regions they're exposing.
1756 if (mLayersRemoved) {
1757 mLayersRemoved = false;
1758 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08001759 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001760 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001761 // this layer is not visible anymore
1762 // TODO: we could traverse the tree from front to back and
1763 // compute the actual visible region
1764 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07001765 Region visibleReg;
1766 visibleReg.set(layer->computeScreenBounds());
1767 invalidateLayerStack(layer->getLayerStack(), visibleReg);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001768 }
Robert Carr2047fae2016-11-28 14:09:09 -08001769 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001770 }
1771
1772 commitTransaction();
1773
1774 updateCursorAsync();
1775}
1776
1777void SurfaceFlinger::updateCursorAsync()
1778{
1779 HWComposer& hwc(getHwComposer());
1780 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1781 sp<const DisplayDevice> hw(mDisplays[dpy]);
1782 const int32_t id = hw->getHwcDisplayId();
1783 if (id < 0) {
1784 continue;
1785 }
1786 const Vector< sp<Layer> >& currentLayers(
1787 hw->getVisibleLayersSortedByZ());
1788 const size_t count = currentLayers.size();
1789 HWComposer::LayerListIterator cur = hwc.begin(id);
1790 const HWComposer::LayerListIterator end = hwc.end(id);
1791 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1792 if (cur->getCompositionType() != HWC_CURSOR_OVERLAY) {
1793 continue;
1794 }
1795 const sp<Layer>& layer(currentLayers[i]);
1796 Rect cursorPos = layer->getPosition(hw);
1797 hwc.setCursorPositionAsync(id, cursorPos);
1798 break;
1799 }
1800 }
1801}
1802
1803void SurfaceFlinger::commitTransaction()
1804{
1805 if (!mLayersPendingRemoval.isEmpty()) {
1806 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07001807 for (const auto& l : mLayersPendingRemoval) {
1808 recordBufferingStats(l->getName().string(),
1809 l->getOccupancyHistory(true));
1810 l->onRemoved();
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001811 }
1812 mLayersPendingRemoval.clear();
1813 }
1814
1815 // If this transaction is part of a window animation then the next frame
1816 // we composite should be considered an animation as well.
1817 mAnimCompositionPending = mAnimTransactionPending;
1818
1819 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001820 mDrawingState.traverseInZOrder([](Layer* layer) {
1821 layer->commitChildList();
1822 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001823 mTransactionPending = false;
1824 mAnimTransactionPending = false;
1825 mTransactionCV.broadcast();
1826}
1827
Robert Carr2047fae2016-11-28 14:09:09 -08001828void SurfaceFlinger::computeVisibleRegions(uint32_t layerStack,
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001829 Region& outDirtyRegion, Region& outOpaqueRegion)
1830{
1831 ATRACE_CALL();
1832
1833 Region aboveOpaqueLayers;
1834 Region aboveCoveredLayers;
1835 Region dirty;
1836
1837 outDirtyRegion.clear();
1838
Robert Carr2047fae2016-11-28 14:09:09 -08001839 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001840 // start with the whole surface at its current location
1841 const Layer::State& s(layer->getDrawingState());
1842
1843 // only consider the layers on the given layer stack
Robert Carr1f0a16a2016-10-24 16:27:39 -07001844 if (layer->getLayerStack() != layerStack)
Robert Carr2047fae2016-11-28 14:09:09 -08001845 return;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001846
1847 /*
1848 * opaqueRegion: area of a surface that is fully opaque.
1849 */
1850 Region opaqueRegion;
1851
1852 /*
1853 * visibleRegion: area of a surface that is visible on screen
1854 * and not fully transparent. This is essentially the layer's
1855 * footprint minus the opaque regions above it.
1856 * Areas covered by a translucent surface are considered visible.
1857 */
1858 Region visibleRegion;
1859
1860 /*
1861 * coveredRegion: area of a surface that is covered by all
1862 * visible regions above it (which includes the translucent areas).
1863 */
1864 Region coveredRegion;
1865
1866 /*
1867 * transparentRegion: area of a surface that is hinted to be completely
1868 * transparent. This is only used to tell when the layer has no visible
1869 * non-transparent regions and can be removed from the layer list. It
1870 * does not affect the visibleRegion of this layer or any layers
1871 * beneath it. The hint may not be correct if apps don't respect the
1872 * SurfaceView restrictions (which, sadly, some don't).
1873 */
1874 Region transparentRegion;
1875
1876
1877 // handle hidden surfaces by setting the visible region to empty
1878 if (CC_LIKELY(layer->isVisible())) {
1879 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001880 Rect bounds(layer->computeScreenBounds());
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001881 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001882 Transform tr = layer->getTransform();
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001883 if (!visibleRegion.isEmpty()) {
1884 // Remove the transparent area from the visible region
1885 if (translucent) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001886 if (tr.preserveRects()) {
1887 // transform the transparent region
1888 transparentRegion = tr.transform(s.activeTransparentRegion);
1889 } else {
1890 // transformation too complex, can't do the
1891 // transparent region optimization.
1892 transparentRegion.clear();
1893 }
1894 }
1895
1896 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07001897 const int32_t layerOrientation = tr.getOrientation();
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001898 if (s.alpha==255 && !translucent &&
1899 ((layerOrientation & Transform::ROT_INVALID) == false)) {
1900 // the opaque region is the layer's footprint
1901 opaqueRegion = visibleRegion;
1902 }
1903 }
1904 }
1905
1906 // Clip the covered region to the visible region
1907 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
1908
1909 // Update aboveCoveredLayers for next (lower) layer
1910 aboveCoveredLayers.orSelf(visibleRegion);
1911
1912 // subtract the opaque region covered by the layers above us
1913 visibleRegion.subtractSelf(aboveOpaqueLayers);
1914
1915 // compute this layer's dirty region
1916 if (layer->contentDirty) {
1917 // we need to invalidate the whole region
1918 dirty = visibleRegion;
1919 // as well, as the old visible region
1920 dirty.orSelf(layer->visibleRegion);
1921 layer->contentDirty = false;
1922 } else {
1923 /* compute the exposed region:
1924 * the exposed region consists of two components:
1925 * 1) what's VISIBLE now and was COVERED before
1926 * 2) what's EXPOSED now less what was EXPOSED before
1927 *
1928 * note that (1) is conservative, we start with the whole
1929 * visible region but only keep what used to be covered by
1930 * something -- which mean it may have been exposed.
1931 *
1932 * (2) handles areas that were not covered by anything but got
1933 * exposed because of a resize.
1934 */
1935 const Region newExposed = visibleRegion - coveredRegion;
1936 const Region oldVisibleRegion = layer->visibleRegion;
1937 const Region oldCoveredRegion = layer->coveredRegion;
1938 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
1939 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
1940 }
1941 dirty.subtractSelf(aboveOpaqueLayers);
1942
1943 // accumulate to the screen dirty region
1944 outDirtyRegion.orSelf(dirty);
1945
1946 // Update aboveOpaqueLayers for next (lower) layer
1947 aboveOpaqueLayers.orSelf(opaqueRegion);
1948
1949 // Store the visible region in screen space
1950 layer->setVisibleRegion(visibleRegion);
1951 layer->setCoveredRegion(coveredRegion);
1952 layer->setVisibleNonTransparentRegion(
1953 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08001954 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001955
1956 outOpaqueRegion = aboveOpaqueLayers;
1957}
1958
1959void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
1960 const Region& dirty) {
1961 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1962 const sp<DisplayDevice>& hw(mDisplays[dpy]);
1963 if (hw->getLayerStack() == layerStack) {
1964 hw->dirtyRegion.orSelf(dirty);
1965 }
1966 }
1967}
1968
1969bool SurfaceFlinger::handlePageFlip()
1970{
Brian Andersond6927fb2016-07-23 23:37:30 -07001971 nsecs_t latchTime = systemTime();
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001972 Region dirtyRegion;
1973
1974 bool visibleRegions = false;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001975 bool frameQueued = false;
1976
1977 // Store the set of layers that need updates. This set must not change as
1978 // buffers are being latched, as this could result in a deadlock.
1979 // Example: Two producers share the same command stream and:
1980 // 1.) Layer 0 is latched
1981 // 2.) Layer 0 gets a new frame
1982 // 2.) Layer 1 gets a new frame
1983 // 3.) Layer 1 is latched.
1984 // Display is now waiting on Layer 1's frame, which is behind layer 0's
1985 // second frame. But layer 0's second frame could be waiting on display.
1986 Vector<Layer*> layersWithQueuedFrames;
Robert Carr2047fae2016-11-28 14:09:09 -08001987 mDrawingState.traverseInZOrder([&](Layer* layer) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001988 if (layer->hasQueuedFrame()) {
1989 frameQueued = true;
1990 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08001991 layersWithQueuedFrames.push_back(layer);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001992 } else {
1993 layer->useEmptyDamage();
1994 }
1995 } else {
1996 layer->useEmptyDamage();
1997 }
Robert Carr2047fae2016-11-28 14:09:09 -08001998 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001999 for (size_t i = 0, count = layersWithQueuedFrames.size() ; i<count ; i++) {
2000 Layer* layer = layersWithQueuedFrames[i];
Brian Andersond6927fb2016-07-23 23:37:30 -07002001 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002002 layer->useSurfaceDamage();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002003 invalidateLayerStack(layer->getLayerStack(), dirty);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002004 }
2005
2006 mVisibleRegionsDirty |= visibleRegions;
2007
2008 // If we will need to wake up at some time in the future to deal with a
2009 // queued frame that shouldn't be displayed during this vsync period, wake
2010 // up during the next vsync period to check again.
2011 if (frameQueued && layersWithQueuedFrames.empty()) {
2012 signalLayerUpdate();
2013 }
2014
2015 // Only continue with the refresh if there is actually new work to do
2016 return !layersWithQueuedFrames.empty();
2017}
2018
2019void SurfaceFlinger::invalidateHwcGeometry()
2020{
2021 mHwWorkListDirty = true;
2022}
2023
2024
2025void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& hw,
2026 const Region& inDirtyRegion)
2027{
2028 // We only need to actually compose the display if:
2029 // 1) It is being handled by hardware composer, which may need this to
2030 // keep its virtual display state machine in sync, or
2031 // 2) There is work to be done (the dirty region isn't empty)
2032 bool isHwcDisplay = hw->getHwcDisplayId() >= 0;
2033 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
2034 return;
2035 }
2036
2037 Region dirtyRegion(inDirtyRegion);
2038
2039 // compute the invalid region
2040 hw->swapRegion.orSelf(dirtyRegion);
2041
2042 uint32_t flags = hw->getFlags();
2043 if (flags & DisplayDevice::SWAP_RECTANGLE) {
2044 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2045 // takes a rectangle, we must make sure to update that whole
2046 // rectangle in that case
2047 dirtyRegion.set(hw->swapRegion.bounds());
2048 } else {
2049 if (flags & DisplayDevice::PARTIAL_UPDATES) {
2050 // We need to redraw the rectangle that will be updated
2051 // (pushed to the framebuffer).
2052 // This is needed because PARTIAL_UPDATES only takes one
2053 // rectangle instead of a region (see DisplayDevice::flip())
2054 dirtyRegion.set(hw->swapRegion.bounds());
2055 } else {
2056 // we need to redraw everything (the whole screen)
2057 dirtyRegion.set(hw->bounds());
2058 hw->swapRegion = dirtyRegion;
2059 }
2060 }
2061
2062 if (CC_LIKELY(!mDaltonize && !mHasColorMatrix)) {
2063 if (!doComposeSurfaces(hw, dirtyRegion)) return;
2064 } else {
2065 RenderEngine& engine(getRenderEngine());
2066 mat4 colorMatrix = mColorMatrix;
2067 if (mDaltonize) {
2068 colorMatrix = colorMatrix * mDaltonizer();
2069 }
2070 mat4 oldMatrix = engine.setupColorTransform(colorMatrix);
2071 doComposeSurfaces(hw, dirtyRegion);
2072 engine.setupColorTransform(oldMatrix);
2073 }
2074
2075 // update the swap region and clear the dirty region
2076 hw->swapRegion.orSelf(dirtyRegion);
2077
2078 // swap buffers (presentation)
2079 hw->swapBuffers(getHwComposer());
2080}
2081
2082bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& hw, const Region& dirty)
2083{
2084 RenderEngine& engine(getRenderEngine());
2085 const int32_t id = hw->getHwcDisplayId();
2086 HWComposer& hwc(getHwComposer());
2087 HWComposer::LayerListIterator cur = hwc.begin(id);
2088 const HWComposer::LayerListIterator end = hwc.end(id);
2089
2090 bool hasGlesComposition = hwc.hasGlesComposition(id);
2091 if (hasGlesComposition) {
2092 if (!hw->makeCurrent(mEGLDisplay, mEGLContext)) {
2093 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
2094 hw->getDisplayName().string());
2095 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
2096 if(!getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext)) {
2097 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2098 }
2099 return false;
2100 }
2101
2102 // Never touch the framebuffer if we don't have any framebuffer layers
2103 const bool hasHwcComposition = hwc.hasHwcComposition(id);
2104 if (hasHwcComposition) {
2105 // when using overlays, we assume a fully transparent framebuffer
2106 // NOTE: we could reduce how much we need to clear, for instance
2107 // remove where there are opaque FB layers. however, on some
2108 // GPUs doing a "clean slate" clear might be more efficient.
2109 // We'll revisit later if needed.
2110 engine.clearWithColor(0, 0, 0, 0);
2111 } else {
2112 // we start with the whole screen area
2113 const Region bounds(hw->getBounds());
2114
2115 // we remove the scissor part
2116 // we're left with the letterbox region
2117 // (common case is that letterbox ends-up being empty)
2118 const Region letterbox(bounds.subtract(hw->getScissor()));
2119
2120 // compute the area to clear
2121 Region region(hw->undefinedRegion.merge(letterbox));
2122
2123 // but limit it to the dirty region
2124 region.andSelf(dirty);
2125
2126 // screen is already cleared here
2127 if (!region.isEmpty()) {
2128 // can happen with SurfaceView
2129 drawWormhole(hw, region);
2130 }
2131 }
2132
2133 if (hw->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
2134 // just to be on the safe side, we don't set the
2135 // scissor on the main display. It should never be needed
2136 // anyways (though in theory it could since the API allows it).
2137 const Rect& bounds(hw->getBounds());
2138 const Rect& scissor(hw->getScissor());
2139 if (scissor != bounds) {
2140 // scissor doesn't match the screen's dimensions, so we
2141 // need to clear everything outside of it and enable
2142 // the GL scissor so we don't draw anything where we shouldn't
2143
2144 // enable scissor for this frame
2145 const uint32_t height = hw->getHeight();
2146 engine.setScissor(scissor.left, height - scissor.bottom,
2147 scissor.getWidth(), scissor.getHeight());
2148 }
2149 }
2150 }
2151
2152 /*
2153 * and then, render the layers targeted at the framebuffer
2154 */
2155
2156 const Vector< sp<Layer> >& layers(hw->getVisibleLayersSortedByZ());
2157 const size_t count = layers.size();
2158 const Transform& tr = hw->getTransform();
2159 if (cur != end) {
2160 // we're using h/w composer
2161 for (size_t i=0 ; i<count && cur!=end ; ++i, ++cur) {
2162 const sp<Layer>& layer(layers[i]);
2163 const Region clip(dirty.intersect(tr.transform(layer->visibleRegion)));
2164 if (!clip.isEmpty()) {
2165 switch (cur->getCompositionType()) {
2166 case HWC_CURSOR_OVERLAY:
2167 case HWC_OVERLAY: {
2168 const Layer::State& state(layer->getDrawingState());
2169 if ((cur->getHints() & HWC_HINT_CLEAR_FB)
2170 && i
2171 && layer->isOpaque(state) && (state.alpha == 0xFF)
2172 && hasGlesComposition) {
2173 // never clear the very first layer since we're
2174 // guaranteed the FB is already cleared
Fabien Sanglard17487192016-12-07 13:03:32 -08002175 layer->clearWithOpenGL(hw);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002176 }
2177 break;
2178 }
2179 case HWC_FRAMEBUFFER: {
2180 layer->draw(hw, clip);
2181 break;
2182 }
2183 case HWC_FRAMEBUFFER_TARGET: {
2184 // this should not happen as the iterator shouldn't
2185 // let us get there.
2186 ALOGW("HWC_FRAMEBUFFER_TARGET found in hwc list (index=%zu)", i);
2187 break;
2188 }
2189 }
2190 }
2191 layer->setAcquireFence(hw, *cur);
2192 }
2193 } else {
2194 // we're not using h/w composer
2195 for (size_t i=0 ; i<count ; ++i) {
2196 const sp<Layer>& layer(layers[i]);
2197 const Region clip(dirty.intersect(
2198 tr.transform(layer->visibleRegion)));
2199 if (!clip.isEmpty()) {
2200 layer->draw(hw, clip);
2201 }
2202 }
2203 }
2204
2205 // disable scissor at the end of the frame
2206 engine.disableScissor();
2207 return true;
2208}
2209
2210void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& hw, const Region& region) const {
2211 const int32_t height = hw->getHeight();
2212 RenderEngine& engine(getRenderEngine());
2213 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
2214}
2215
2216status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
2217 const sp<IBinder>& handle,
2218 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002219 const sp<Layer>& lbc,
2220 const sp<Layer>& parent)
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002221{
2222 // add this layer to the current state list
2223 {
2224 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002225 if (mNumLayers >= MAX_LAYERS) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002226 return NO_MEMORY;
2227 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002228 if (parent == nullptr) {
2229 mCurrentState.layersSortedByZ.add(lbc);
2230 } else {
2231 parent->addChild(lbc);
2232 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002233 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002234 mLayersAdded = true;
2235 mNumLayers++;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002236 }
2237
2238 // attach this layer to the client
2239 client->attachLayer(handle, lbc);
2240
2241 return NO_ERROR;
2242}
2243
2244status_t SurfaceFlinger::removeLayer(const wp<Layer>& weakLayer) {
2245 Mutex::Autolock _l(mStateLock);
2246 sp<Layer> layer = weakLayer.promote();
2247 if (layer == nullptr) {
2248 // The layer has already been removed, carry on
2249 return NO_ERROR;
2250 }
2251
Robert Carr1f0a16a2016-10-24 16:27:39 -07002252 const auto& p = layer->getParent();
2253 const ssize_t index = (p != nullptr) ? p->removeChild(layer) :
2254 mCurrentState.layersSortedByZ.remove(layer);
2255
2256 if (index < 0) {
2257 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2258 layer->getName().string(),
2259 (p != nullptr) ? p->getName().string() : "no-parent");
2260 return BAD_VALUE;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002261 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002262
2263 mLayersPendingRemoval.add(layer);
2264 mLayersRemoved = true;
2265 mNumLayers--;
2266 setTransactionFlags(eTransactionNeeded);
2267 return NO_ERROR;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002268}
2269
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002270uint32_t SurfaceFlinger::peekTransactionFlags() {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002271 return android_atomic_release_load(&mTransactionFlags);
2272}
2273
2274uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
2275 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2276}
2277
2278uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
2279 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2280 if ((old & flags)==0) { // wake the server up
2281 signalTransaction();
2282 }
2283 return old;
2284}
2285
2286void SurfaceFlinger::setTransactionState(
2287 const Vector<ComposerState>& state,
2288 const Vector<DisplayState>& displays,
2289 uint32_t flags)
2290{
2291 ATRACE_CALL();
2292 Mutex::Autolock _l(mStateLock);
2293 uint32_t transactionFlags = 0;
2294
2295 if (flags & eAnimation) {
2296 // For window updates that are part of an animation we must wait for
2297 // previous animation "frames" to be handled.
2298 while (mAnimTransactionPending) {
2299 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2300 if (CC_UNLIKELY(err != NO_ERROR)) {
2301 // just in case something goes wrong in SF, return to the
2302 // caller after a few seconds.
2303 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2304 "waiting for previous animation frame");
2305 mAnimTransactionPending = false;
2306 break;
2307 }
2308 }
2309 }
2310
2311 size_t count = displays.size();
2312 for (size_t i=0 ; i<count ; i++) {
2313 const DisplayState& s(displays[i]);
2314 transactionFlags |= setDisplayStateLocked(s);
2315 }
2316
2317 count = state.size();
2318 for (size_t i=0 ; i<count ; i++) {
2319 const ComposerState& s(state[i]);
2320 // Here we need to check that the interface we're given is indeed
2321 // one of our own. A malicious client could give us a NULL
2322 // IInterface, or one of its own or even one of our own but a
2323 // different type. All these situations would cause us to crash.
2324 //
2325 // NOTE: it would be better to use RTTI as we could directly check
2326 // that we have a Client*. however, RTTI is disabled in Android.
2327 if (s.client != NULL) {
2328 sp<IBinder> binder = IInterface::asBinder(s.client);
2329 if (binder != NULL) {
2330 String16 desc(binder->getInterfaceDescriptor());
2331 if (desc == ISurfaceComposerClient::descriptor) {
2332 sp<Client> client( static_cast<Client *>(s.client.get()) );
2333 transactionFlags |= setClientStateLocked(client, s.state);
2334 }
2335 }
2336 }
2337 }
2338
2339 // If a synchronous transaction is explicitly requested without any changes,
2340 // force a transaction anyway. This can be used as a flush mechanism for
2341 // previous async transactions.
2342 if (transactionFlags == 0 && (flags & eSynchronous)) {
2343 transactionFlags = eTransactionNeeded;
2344 }
2345
2346 if (transactionFlags) {
2347 if (mInterceptor.isEnabled()) {
2348 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2349 }
2350
2351 // this triggers the transaction
2352 setTransactionFlags(transactionFlags);
2353
2354 // if this is a synchronous transaction, wait for it to take effect
2355 // before returning.
2356 if (flags & eSynchronous) {
2357 mTransactionPending = true;
2358 }
2359 if (flags & eAnimation) {
2360 mAnimTransactionPending = true;
2361 }
2362 while (mTransactionPending) {
2363 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2364 if (CC_UNLIKELY(err != NO_ERROR)) {
2365 // just in case something goes wrong in SF, return to the
2366 // called after a few seconds.
2367 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2368 mTransactionPending = false;
2369 break;
2370 }
2371 }
2372 }
2373}
2374
2375uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2376{
2377 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2378 if (dpyIdx < 0)
2379 return 0;
2380
2381 uint32_t flags = 0;
2382 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
2383 if (disp.isValid()) {
2384 const uint32_t what = s.what;
2385 if (what & DisplayState::eSurfaceChanged) {
2386 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
2387 disp.surface = s.surface;
2388 flags |= eDisplayTransactionNeeded;
2389 }
2390 }
2391 if (what & DisplayState::eLayerStackChanged) {
2392 if (disp.layerStack != s.layerStack) {
2393 disp.layerStack = s.layerStack;
2394 flags |= eDisplayTransactionNeeded;
2395 }
2396 }
2397 if (what & DisplayState::eDisplayProjectionChanged) {
2398 if (disp.orientation != s.orientation) {
2399 disp.orientation = s.orientation;
2400 flags |= eDisplayTransactionNeeded;
2401 }
2402 if (disp.frame != s.frame) {
2403 disp.frame = s.frame;
2404 flags |= eDisplayTransactionNeeded;
2405 }
2406 if (disp.viewport != s.viewport) {
2407 disp.viewport = s.viewport;
2408 flags |= eDisplayTransactionNeeded;
2409 }
2410 }
2411 if (what & DisplayState::eDisplaySizeChanged) {
2412 if (disp.width != s.width) {
2413 disp.width = s.width;
2414 flags |= eDisplayTransactionNeeded;
2415 }
2416 if (disp.height != s.height) {
2417 disp.height = s.height;
2418 flags |= eDisplayTransactionNeeded;
2419 }
2420 }
2421 }
2422 return flags;
2423}
2424
2425uint32_t SurfaceFlinger::setClientStateLocked(
2426 const sp<Client>& client,
2427 const layer_state_t& s)
2428{
2429 uint32_t flags = 0;
2430 sp<Layer> layer(client->getLayerUser(s.surface));
2431 if (layer != 0) {
2432 const uint32_t what = s.what;
2433 bool geometryAppliesWithResize =
2434 what & layer_state_t::eGeometryAppliesWithResize;
2435 if (what & layer_state_t::ePositionChanged) {
2436 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
2437 flags |= eTraversalNeeded;
2438 }
2439 }
2440 if (what & layer_state_t::eLayerChanged) {
2441 // NOTE: index needs to be calculated before we update the state
Robert Carr1f0a16a2016-10-24 16:27:39 -07002442 const auto& p = layer->getParent();
2443 if (p == nullptr) {
2444 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2445 if (layer->setLayer(s.z) && idx >= 0) {
2446 mCurrentState.layersSortedByZ.removeAt(idx);
2447 mCurrentState.layersSortedByZ.add(layer);
2448 // we need traversal (state changed)
2449 // AND transaction (list changed)
2450 flags |= eTransactionNeeded|eTraversalNeeded;
2451 }
2452 } else {
2453 if (p->setChildLayer(layer, s.z)) {
2454 flags |= eTransactionNeeded|eTraversalNeeded;
2455 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002456 }
2457 }
2458 if (what & layer_state_t::eSizeChanged) {
2459 if (layer->setSize(s.w, s.h)) {
2460 flags |= eTraversalNeeded;
2461 }
2462 }
2463 if (what & layer_state_t::eAlphaChanged) {
2464 if (layer->setAlpha(uint8_t(255.0f*s.alpha+0.5f)))
2465 flags |= eTraversalNeeded;
2466 }
2467 if (what & layer_state_t::eMatrixChanged) {
2468 if (layer->setMatrix(s.matrix))
2469 flags |= eTraversalNeeded;
2470 }
2471 if (what & layer_state_t::eTransparentRegionChanged) {
2472 if (layer->setTransparentRegionHint(s.transparentRegion))
2473 flags |= eTraversalNeeded;
2474 }
2475 if (what & layer_state_t::eFlagsChanged) {
2476 if (layer->setFlags(s.flags, s.mask))
2477 flags |= eTraversalNeeded;
2478 }
2479 if (what & layer_state_t::eCropChanged) {
2480 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
2481 flags |= eTraversalNeeded;
2482 }
2483 if (what & layer_state_t::eFinalCropChanged) {
2484 if (layer->setFinalCrop(s.finalCrop))
2485 flags |= eTraversalNeeded;
2486 }
2487 if (what & layer_state_t::eLayerStackChanged) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002488 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002489 // We only allow setting layer stacks for top level layers,
2490 // everything else inherits layer stack from its parent.
2491 if (layer->hasParent()) {
2492 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
2493 layer->getName().string());
2494 } else if (idx < 0) {
2495 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
2496 "that also does not appear in the top level layer list. Something"
2497 " has gone wrong.", layer->getName().string());
2498 } else if (layer->setLayerStack(s.layerStack)) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002499 mCurrentState.layersSortedByZ.removeAt(idx);
2500 mCurrentState.layersSortedByZ.add(layer);
2501 // we need traversal (state changed)
2502 // AND transaction (list changed)
2503 flags |= eTransactionNeeded|eTraversalNeeded;
2504 }
2505 }
2506 if (what & layer_state_t::eDeferTransaction) {
2507 layer->deferTransactionUntil(s.handle, s.frameNumber);
2508 // We don't trigger a traversal here because if no other state is
2509 // changed, we don't want this to cause any more work
2510 }
Robert Carr1db73f62016-12-21 12:58:51 -08002511 if (what & layer_state_t::eReparentChildren) {
2512 if (layer->reparentChildren(s.reparentHandle)) {
2513 flags |= eTransactionNeeded|eTraversalNeeded;
2514 }
2515 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002516 if (what & layer_state_t::eOverrideScalingModeChanged) {
2517 layer->setOverrideScalingMode(s.overrideScalingMode);
2518 // We don't trigger a traversal here because if no other state is
2519 // changed, we don't want this to cause any more work
2520 }
2521 }
2522 return flags;
2523}
2524
2525status_t SurfaceFlinger::createLayer(
2526 const String8& name,
2527 const sp<Client>& client,
2528 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05002529 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
2530 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002531{
2532 if (int32_t(w|h) < 0) {
2533 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
2534 int(w), int(h));
2535 return BAD_VALUE;
2536 }
2537
2538 status_t result = NO_ERROR;
2539
2540 sp<Layer> layer;
2541
2542 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2543 case ISurfaceComposerClient::eFXSurfaceNormal:
2544 result = createNormalLayer(client,
2545 name, w, h, flags, format,
2546 handle, gbp, &layer);
2547 break;
2548 case ISurfaceComposerClient::eFXSurfaceDim:
2549 result = createDimLayer(client,
2550 name, w, h, flags,
2551 handle, gbp, &layer);
2552 break;
2553 default:
2554 result = BAD_VALUE;
2555 break;
2556 }
2557
2558 if (result != NO_ERROR) {
2559 return result;
2560 }
2561
Albert Chaulk479c60c2017-01-27 14:21:34 -05002562 layer->setInfo(windowType, ownerUid);
2563
Robert Carr1f0a16a2016-10-24 16:27:39 -07002564 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002565 if (result != NO_ERROR) {
2566 return result;
2567 }
2568 mInterceptor.saveSurfaceCreation(layer);
2569
2570 setTransactionFlags(eTransactionNeeded);
2571 return result;
2572}
2573
2574status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
2575 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
2576 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
2577{
2578 // initialize the surfaces
2579 switch (format) {
2580 case PIXEL_FORMAT_TRANSPARENT:
2581 case PIXEL_FORMAT_TRANSLUCENT:
2582 format = PIXEL_FORMAT_RGBA_8888;
2583 break;
2584 case PIXEL_FORMAT_OPAQUE:
2585 format = PIXEL_FORMAT_RGBX_8888;
2586 break;
2587 }
2588
2589 *outLayer = new Layer(this, client, name, w, h, flags);
2590 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
2591 if (err == NO_ERROR) {
2592 *handle = (*outLayer)->getHandle();
2593 *gbp = (*outLayer)->getProducer();
2594 }
2595
2596 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
2597 return err;
2598}
2599
2600status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
2601 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2602 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
2603{
2604 *outLayer = new LayerDim(this, client, name, w, h, flags);
2605 *handle = (*outLayer)->getHandle();
2606 *gbp = (*outLayer)->getProducer();
2607 return NO_ERROR;
2608}
2609
2610status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
2611{
2612 // called by the window manager when it wants to remove a Layer
2613 status_t err = NO_ERROR;
2614 sp<Layer> l(client->getLayerUser(handle));
2615 if (l != NULL) {
2616 mInterceptor.saveSurfaceDeletion(l);
2617 err = removeLayer(l);
2618 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2619 "error removing layer=%p (%s)", l.get(), strerror(-err));
2620 }
2621 return err;
2622}
2623
2624status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
2625{
2626 // called by ~LayerCleaner() when all references to the IBinder (handle)
2627 // are gone
2628 return removeLayer(layer);
2629}
2630
2631// ---------------------------------------------------------------------------
2632
2633void SurfaceFlinger::onInitializeDisplays() {
2634 // reset screen orientation and use primary layer stack
2635 Vector<ComposerState> state;
2636 Vector<DisplayState> displays;
2637 DisplayState d;
2638 d.what = DisplayState::eDisplayProjectionChanged |
2639 DisplayState::eLayerStackChanged;
2640 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
2641 d.layerStack = 0;
2642 d.orientation = DisplayState::eOrientationDefault;
2643 d.frame.makeInvalid();
2644 d.viewport.makeInvalid();
2645 d.width = 0;
2646 d.height = 0;
2647 displays.add(d);
2648 setTransactionState(state, displays, 0);
2649 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
2650
2651 const nsecs_t period =
2652 getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
2653 mAnimFrameTracker.setDisplayRefreshPeriod(period);
2654}
2655
2656void SurfaceFlinger::initializeDisplays() {
2657 class MessageScreenInitialized : public MessageBase {
2658 SurfaceFlinger* flinger;
2659 public:
2660 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
2661 virtual bool handler() {
2662 flinger->onInitializeDisplays();
2663 return true;
2664 }
2665 };
2666 sp<MessageBase> msg = new MessageScreenInitialized(this);
2667 postMessageAsync(msg); // we may be called from main thread, use async message
2668}
2669
2670void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
2671 int mode) {
2672 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
2673 this);
2674 int32_t type = hw->getDisplayType();
2675 int currentMode = hw->getPowerMode();
2676
2677 if (mode == currentMode) {
2678 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
2679 return;
2680 }
2681
2682 hw->setPowerMode(mode);
2683 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
2684 ALOGW("Trying to set power mode for virtual display");
2685 return;
2686 }
2687
2688 if (mInterceptor.isEnabled()) {
2689 Mutex::Autolock _l(mStateLock);
2690 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
2691 if (idx < 0) {
2692 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
2693 return;
2694 }
2695 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
2696 }
2697
2698 if (currentMode == HWC_POWER_MODE_OFF) {
2699 // Turn on the display
2700 getHwComposer().setPowerMode(type, mode);
2701 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2702 // FIXME: eventthread only knows about the main display right now
2703 mEventThread->onScreenAcquired();
2704 resyncToHardwareVsync(true);
2705 }
2706
2707 mVisibleRegionsDirty = true;
2708 mHasPoweredOff = true;
2709 repaintEverything();
2710
2711 struct sched_param param = {0};
2712 param.sched_priority = 1;
2713 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
2714 ALOGW("Couldn't set SCHED_FIFO on display on");
2715 }
2716 } else if (mode == HWC_POWER_MODE_OFF) {
2717 // Turn off the display
2718 struct sched_param param = {0};
2719 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
2720 ALOGW("Couldn't set SCHED_OTHER on display off");
2721 }
2722
2723 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2724 disableHardwareVsync(true); // also cancels any in-progress resync
2725
2726 // FIXME: eventthread only knows about the main display right now
2727 mEventThread->onScreenReleased();
2728 }
2729
2730 getHwComposer().setPowerMode(type, mode);
2731 mVisibleRegionsDirty = true;
2732 // from this point on, SF will stop drawing on this display
2733 } else {
2734 getHwComposer().setPowerMode(type, mode);
2735 }
2736}
2737
2738void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
2739 class MessageSetPowerMode: public MessageBase {
2740 SurfaceFlinger& mFlinger;
2741 sp<IBinder> mDisplay;
2742 int mMode;
2743 public:
2744 MessageSetPowerMode(SurfaceFlinger& flinger,
2745 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
2746 mDisplay(disp) { mMode = mode; }
2747 virtual bool handler() {
2748 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
2749 if (hw == NULL) {
2750 ALOGE("Attempt to set power mode = %d for null display %p",
2751 mMode, mDisplay.get());
2752 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
2753 ALOGW("Attempt to set power mode = %d for virtual display",
2754 mMode);
2755 } else {
2756 mFlinger.setPowerModeInternal(hw, mMode);
2757 }
2758 return true;
2759 }
2760 };
2761 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
2762 postMessageSync(msg);
2763}
2764
2765// ---------------------------------------------------------------------------
2766
2767status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
2768{
2769 String8 result;
2770
2771 IPCThreadState* ipc = IPCThreadState::self();
2772 const int pid = ipc->getCallingPid();
2773 const int uid = ipc->getCallingUid();
2774 if ((uid != AID_SHELL) &&
2775 !PermissionCache::checkPermission(sDump, pid, uid)) {
2776 result.appendFormat("Permission Denial: "
2777 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
2778 } else {
2779 // Try to get the main lock, but give up after one second
2780 // (this would indicate SF is stuck, but we want to be able to
2781 // print something in dumpsys).
2782 status_t err = mStateLock.timedLock(s2ns(1));
2783 bool locked = (err == NO_ERROR);
2784 if (!locked) {
2785 result.appendFormat(
2786 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
2787 "dumping anyways (no locks held)\n", strerror(-err), err);
2788 }
2789
2790 bool dumpAll = true;
2791 size_t index = 0;
2792 size_t numArgs = args.size();
2793 if (numArgs) {
2794 if ((index < numArgs) &&
2795 (args[index] == String16("--list"))) {
2796 index++;
2797 listLayersLocked(args, index, result);
2798 dumpAll = false;
2799 }
2800
2801 if ((index < numArgs) &&
2802 (args[index] == String16("--latency"))) {
2803 index++;
2804 dumpStatsLocked(args, index, result);
2805 dumpAll = false;
2806 }
2807
2808 if ((index < numArgs) &&
2809 (args[index] == String16("--latency-clear"))) {
2810 index++;
2811 clearStatsLocked(args, index, result);
2812 dumpAll = false;
2813 }
2814
2815 if ((index < numArgs) &&
2816 (args[index] == String16("--dispsync"))) {
2817 index++;
2818 mPrimaryDispSync.dump(result);
2819 dumpAll = false;
2820 }
2821
2822 if ((index < numArgs) &&
2823 (args[index] == String16("--static-screen"))) {
2824 index++;
2825 dumpStaticScreenStats(result);
2826 dumpAll = false;
2827 }
2828
2829 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07002830 (args[index] == String16("--frame-events"))) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002831 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07002832 dumpFrameEventsLocked(result);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002833 dumpAll = false;
2834 }
2835 }
2836
2837 if (dumpAll) {
2838 dumpAllLocked(args, index, result);
2839 }
2840
2841 if (locked) {
2842 mStateLock.unlock();
2843 }
2844 }
2845 write(fd, result.string(), result.size());
2846 return NO_ERROR;
2847}
2848
2849void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
2850 size_t& /* index */, String8& result) const
2851{
Robert Carr2047fae2016-11-28 14:09:09 -08002852 mCurrentState.traverseInZOrder([&](Layer* layer) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002853 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08002854 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002855}
2856
2857void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
2858 String8& result) const
2859{
2860 String8 name;
2861 if (index < args.size()) {
2862 name = String8(args[index]);
2863 index++;
2864 }
2865
2866 const nsecs_t period =
2867 getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
2868 result.appendFormat("%" PRId64 "\n", period);
2869
2870 if (name.isEmpty()) {
2871 mAnimFrameTracker.dumpStats(result);
2872 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08002873 mCurrentState.traverseInZOrder([&](Layer* layer) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002874 if (name == layer->getName()) {
2875 layer->dumpFrameStats(result);
2876 }
Robert Carr2047fae2016-11-28 14:09:09 -08002877 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002878 }
2879}
2880
2881void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
2882 String8& /* result */)
2883{
2884 String8 name;
2885 if (index < args.size()) {
2886 name = String8(args[index]);
2887 index++;
2888 }
2889
Robert Carr2047fae2016-11-28 14:09:09 -08002890 mCurrentState.traverseInZOrder([&](Layer* layer) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002891 if (name.isEmpty() || (name == layer->getName())) {
2892 layer->clearFrameStats();
2893 }
Robert Carr2047fae2016-11-28 14:09:09 -08002894 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002895
2896 mAnimFrameTracker.clearStats();
2897}
2898
2899// This should only be called from the main thread. Otherwise it would need
2900// the lock and should use mCurrentState rather than mDrawingState.
2901void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08002902 mDrawingState.traverseInZOrder([&](Layer* layer) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002903 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08002904 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002905
2906 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
2907}
2908
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08002909void SurfaceFlinger::appendSfConfigString(String8& result) const
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002910{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08002911 result.append(" [sf");
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002912#ifdef HAS_CONTEXT_PRIORITY
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08002913 result.append(" HAS_CONTEXT_PRIORITY");
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002914#endif
2915#ifdef NEVER_DEFAULT_TO_ASYNC_MODE
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08002916 result.append(" NEVER_DEFAULT_TO_ASYNC_MODE");
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002917#endif
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08002918 if (isLayerTripleBufferingDisabled())
2919 result.append(" DISABLE_TRIPLE_BUFFERING");
2920 result.append("]");
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002921}
2922
2923void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
2924{
2925 result.appendFormat("Static screen stats:\n");
2926 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
2927 float bucketTimeSec = mFrameBuckets[b] / 1e9;
2928 float percent = 100.0f *
2929 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
2930 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
2931 b + 1, bucketTimeSec, percent);
2932 }
2933 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
2934 float percent = 100.0f *
2935 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
2936 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
2937 NUM_BUCKETS - 1, bucketTimeSec, percent);
2938}
2939
Brian Andersond6927fb2016-07-23 23:37:30 -07002940void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
2941 result.appendFormat("Layer frame timestamps:\n");
2942
2943 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2944 const size_t count = currentLayers.size();
2945 for (size_t i=0 ; i<count ; i++) {
2946 currentLayers[i]->dumpFrameEvents(result);
2947 }
2948}
2949
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002950void SurfaceFlinger::recordBufferingStats(const char* layerName,
2951 std::vector<OccupancyTracker::Segment>&& history) {
2952 Mutex::Autolock lock(mBufferingStatsMutex);
2953 auto& stats = mBufferingStats[layerName];
2954 for (const auto& segment : history) {
2955 if (!segment.usedThirdBuffer) {
2956 stats.twoBufferTime += segment.totalTime;
2957 }
2958 if (segment.occupancyAverage < 1.0f) {
2959 stats.doubleBufferedTime += segment.totalTime;
2960 } else if (segment.occupancyAverage < 2.0f) {
2961 stats.tripleBufferedTime += segment.totalTime;
2962 }
2963 ++stats.numSegments;
2964 stats.totalTime += segment.totalTime;
2965 }
2966}
2967
2968void SurfaceFlinger::dumpBufferingStats(String8& result) const {
2969 result.append("Buffering stats:\n");
2970 result.append(" [Layer name] <Active time> <Two buffer> "
2971 "<Double buffered> <Triple buffered>\n");
2972 Mutex::Autolock lock(mBufferingStatsMutex);
2973 typedef std::tuple<std::string, float, float, float> BufferTuple;
2974 std::map<float, BufferTuple, std::greater<float>> sorted;
2975 for (const auto& statsPair : mBufferingStats) {
2976 const char* name = statsPair.first.c_str();
2977 const BufferingStats& stats = statsPair.second;
2978 if (stats.numSegments == 0) {
2979 continue;
2980 }
2981 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
2982 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
2983 stats.totalTime;
2984 float doubleBufferRatio = static_cast<float>(
2985 stats.doubleBufferedTime) / stats.totalTime;
2986 float tripleBufferRatio = static_cast<float>(
2987 stats.tripleBufferedTime) / stats.totalTime;
2988 sorted.insert({activeTime, {name, twoBufferRatio,
2989 doubleBufferRatio, tripleBufferRatio}});
2990 }
2991 for (const auto& sortedPair : sorted) {
2992 float activeTime = sortedPair.first;
2993 const BufferTuple& values = sortedPair.second;
2994 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
2995 std::get<0>(values).c_str(), activeTime,
2996 std::get<1>(values), std::get<2>(values),
2997 std::get<3>(values));
2998 }
2999 result.append("\n");
3000}
3001
3002void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3003 String8& result) const
3004{
3005 bool colorize = false;
3006 if (index < args.size()
3007 && (args[index] == String16("--color"))) {
3008 colorize = true;
3009 index++;
3010 }
3011
3012 Colorizer colorizer(colorize);
3013
3014 // figure out if we're stuck somewhere
3015 const nsecs_t now = systemTime();
3016 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3017 const nsecs_t inTransaction(mDebugInTransaction);
3018 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3019 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3020
3021 /*
3022 * Dump library configuration.
3023 */
3024
3025 colorizer.bold(result);
3026 result.append("Build configuration:");
3027 colorizer.reset(result);
3028 appendSfConfigString(result);
3029 appendUiConfigString(result);
3030 appendGuiConfigString(result);
3031 result.append("\n");
3032
3033 colorizer.bold(result);
3034 result.append("Sync configuration: ");
3035 colorizer.reset(result);
3036 result.append(SyncFeatures::getInstance().toString());
3037 result.append("\n");
3038
3039 colorizer.bold(result);
3040 result.append("DispSync configuration: ");
3041 colorizer.reset(result);
3042 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
3043 "present offset %d ns (refresh %" PRId64 " ns)",
3044 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs, PRESENT_TIME_OFFSET_FROM_VSYNC_NS,
3045 mHwc->getRefreshPeriod(HWC_DISPLAY_PRIMARY));
3046 result.append("\n");
3047
3048 // Dump static screen stats
3049 result.append("\n");
3050 dumpStaticScreenStats(result);
3051 result.append("\n");
3052
3053 dumpBufferingStats(result);
3054
3055 /*
3056 * Dump the visible layer list
3057 */
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003058 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003059 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003060 colorizer.reset(result);
Robert Carr2047fae2016-11-28 14:09:09 -08003061 mCurrentState.traverseInZOrder([&](Layer* layer) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003062 layer->dump(result, colorizer);
Robert Carr2047fae2016-11-28 14:09:09 -08003063 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003064
3065 /*
3066 * Dump Display state
3067 */
3068
3069 colorizer.bold(result);
3070 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
3071 colorizer.reset(result);
3072 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3073 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
3074 hw->dump(result);
3075 }
3076
3077 /*
3078 * Dump SurfaceFlinger global state
3079 */
3080
3081 colorizer.bold(result);
3082 result.append("SurfaceFlinger global state:\n");
3083 colorizer.reset(result);
3084
3085 HWComposer& hwc(getHwComposer());
3086 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
3087
3088 colorizer.bold(result);
3089 result.appendFormat("EGL implementation : %s\n",
3090 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3091 colorizer.reset(result);
3092 result.appendFormat("%s\n",
3093 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
3094
3095 mRenderEngine->dump(result);
3096
3097 hw->undefinedRegion.dump(result, "undefinedRegion");
3098 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3099 hw->getOrientation(), hw->isDisplayOn());
3100 result.appendFormat(
3101 " last eglSwapBuffers() time: %f us\n"
3102 " last transaction time : %f us\n"
3103 " transaction-flags : %08x\n"
3104 " refresh-rate : %f fps\n"
3105 " x-dpi : %f\n"
3106 " y-dpi : %f\n"
3107 " gpu_to_cpu_unsupported : %d\n"
3108 ,
3109 mLastSwapBufferTime/1000.0,
3110 mLastTransactionTime/1000.0,
3111 mTransactionFlags,
3112 1e9 / hwc.getRefreshPeriod(HWC_DISPLAY_PRIMARY),
3113 hwc.getDpiX(HWC_DISPLAY_PRIMARY),
3114 hwc.getDpiY(HWC_DISPLAY_PRIMARY),
3115 !mGpuToCpuSupported);
3116
3117 result.appendFormat(" eglSwapBuffers time: %f us\n",
3118 inSwapBuffersDuration/1000.0);
3119
3120 result.appendFormat(" transaction time: %f us\n",
3121 inTransactionDuration/1000.0);
3122
3123 /*
3124 * VSYNC state
3125 */
3126 mEventThread->dump(result);
3127
3128 /*
3129 * Dump HWComposer state
3130 */
3131 colorizer.bold(result);
3132 result.append("h/w composer state:\n");
3133 colorizer.reset(result);
3134 result.appendFormat(" h/w composer %s and %s\n",
3135 hwc.initCheck()==NO_ERROR ? "present" : "not present",
3136 (mDebugDisableHWC || mDebugRegion || mDaltonize
3137 || mHasColorMatrix) ? "disabled" : "enabled");
3138 hwc.dump(result);
3139
3140 /*
3141 * Dump gralloc state
3142 */
3143 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3144 alloc.dump(result);
3145}
3146
3147const Vector< sp<Layer> >&
3148SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
3149 // Note: mStateLock is held here
3150 wp<IBinder> dpy;
3151 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3152 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3153 dpy = mDisplays.keyAt(i);
3154 break;
3155 }
3156 }
3157 if (dpy == NULL) {
3158 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3159 // Just use the primary display so we have something to return
3160 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3161 }
3162 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
3163}
3164
3165bool SurfaceFlinger::startDdmConnection()
3166{
3167 void* libddmconnection_dso =
3168 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3169 if (!libddmconnection_dso) {
3170 return false;
3171 }
3172 void (*DdmConnection_start)(const char* name);
3173 DdmConnection_start =
3174 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
3175 if (!DdmConnection_start) {
3176 dlclose(libddmconnection_dso);
3177 return false;
3178 }
3179 (*DdmConnection_start)(getServiceName());
3180 return true;
3181}
3182
3183status_t SurfaceFlinger::onTransact(
3184 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3185{
3186 switch (code) {
3187 case CREATE_CONNECTION:
3188 case CREATE_DISPLAY:
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003189 case BOOT_FINISHED:
3190 case CLEAR_ANIMATION_FRAME_STATS:
3191 case GET_ANIMATION_FRAME_STATS:
3192 case SET_POWER_MODE:
3193 case GET_HDR_CAPABILITIES:
3194 {
3195 // codes that require permission check
3196 IPCThreadState* ipc = IPCThreadState::self();
3197 const int pid = ipc->getCallingPid();
3198 const int uid = ipc->getCallingUid();
3199 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
3200 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
3201 ALOGE("Permission Denial: "
3202 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
3203 return PERMISSION_DENIED;
3204 }
3205 break;
3206 }
Robert Carr1db73f62016-12-21 12:58:51 -08003207 /*
3208 * Calling setTransactionState is safe, because you need to have been
3209 * granted a reference to Client* and Handle* to do anything with it.
3210 *
3211 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
3212 */
3213 case SET_TRANSACTION_STATE:
3214 case CREATE_SCOPED_CONNECTION:
3215 {
3216 break;
3217 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003218 case CAPTURE_SCREEN:
3219 {
3220 // codes that require permission check
3221 IPCThreadState* ipc = IPCThreadState::self();
3222 const int pid = ipc->getCallingPid();
3223 const int uid = ipc->getCallingUid();
3224 if ((uid != AID_GRAPHICS) &&
3225 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
3226 ALOGE("Permission Denial: "
3227 "can't read framebuffer pid=%d, uid=%d", pid, uid);
3228 return PERMISSION_DENIED;
3229 }
3230 break;
3231 }
3232 }
3233
3234 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3235 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
3236 CHECK_INTERFACE(ISurfaceComposer, data, reply);
3237 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
3238 IPCThreadState* ipc = IPCThreadState::self();
3239 const int pid = ipc->getCallingPid();
3240 const int uid = ipc->getCallingUid();
3241 ALOGE("Permission Denial: "
3242 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
3243 return PERMISSION_DENIED;
3244 }
3245 int n;
3246 switch (code) {
3247 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
3248 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
3249 return NO_ERROR;
3250 case 1002: // SHOW_UPDATES
3251 n = data.readInt32();
3252 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
3253 invalidateHwcGeometry();
3254 repaintEverything();
3255 return NO_ERROR;
3256 case 1004:{ // repaint everything
3257 repaintEverything();
3258 return NO_ERROR;
3259 }
3260 case 1005:{ // force transaction
3261 setTransactionFlags(
3262 eTransactionNeeded|
3263 eDisplayTransactionNeeded|
3264 eTraversalNeeded);
3265 return NO_ERROR;
3266 }
3267 case 1006:{ // send empty update
3268 signalRefresh();
3269 return NO_ERROR;
3270 }
3271 case 1008: // toggle use of hw composer
3272 n = data.readInt32();
3273 mDebugDisableHWC = n ? 1 : 0;
3274 invalidateHwcGeometry();
3275 repaintEverything();
3276 return NO_ERROR;
3277 case 1009: // toggle use of transform hint
3278 n = data.readInt32();
3279 mDebugDisableTransformHint = n ? 1 : 0;
3280 invalidateHwcGeometry();
3281 repaintEverything();
3282 return NO_ERROR;
3283 case 1010: // interrogate.
3284 reply->writeInt32(0);
3285 reply->writeInt32(0);
3286 reply->writeInt32(mDebugRegion);
3287 reply->writeInt32(0);
3288 reply->writeInt32(mDebugDisableHWC);
3289 return NO_ERROR;
3290 case 1013: {
3291 Mutex::Autolock _l(mStateLock);
3292 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
3293 reply->writeInt32(hw->getPageFlipCount());
3294 return NO_ERROR;
3295 }
3296 case 1014: {
3297 // daltonize
3298 n = data.readInt32();
3299 switch (n % 10) {
3300 case 1:
3301 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3302 break;
3303 case 2:
3304 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
3305 break;
3306 case 3:
3307 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
3308 break;
3309 }
3310 if (n >= 10) {
3311 mDaltonizer.setMode(ColorBlindnessMode::Correction);
3312 } else {
3313 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
3314 }
3315 mDaltonize = n > 0;
3316 invalidateHwcGeometry();
3317 repaintEverything();
3318 return NO_ERROR;
3319 }
3320 case 1015: {
3321 // apply a color matrix
3322 n = data.readInt32();
3323 mHasColorMatrix = n ? 1 : 0;
3324 if (n) {
3325 // color matrix is sent as mat3 matrix followed by vec3
3326 // offset, then packed into a mat4 where the last row is
3327 // the offset and extra values are 0
3328 for (size_t i = 0 ; i < 4; i++) {
3329 for (size_t j = 0; j < 4; j++) {
3330 mColorMatrix[i][j] = data.readFloat();
3331 }
3332 }
3333 } else {
3334 mColorMatrix = mat4();
3335 }
3336 invalidateHwcGeometry();
3337 repaintEverything();
3338 return NO_ERROR;
3339 }
3340 // This is an experimental interface
3341 // Needs to be shifted to proper binder interface when we productize
3342 case 1016: {
3343 n = data.readInt32();
3344 mPrimaryDispSync.setRefreshSkipCount(n);
3345 return NO_ERROR;
3346 }
3347 case 1017: {
3348 n = data.readInt32();
3349 mForceFullDamage = static_cast<bool>(n);
3350 return NO_ERROR;
3351 }
3352 case 1018: { // Modify Choreographer's phase offset
3353 n = data.readInt32();
3354 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3355 return NO_ERROR;
3356 }
3357 case 1019: { // Modify SurfaceFlinger's phase offset
3358 n = data.readInt32();
3359 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3360 return NO_ERROR;
3361 }
3362 case 1020: { // Layer updates interceptor
3363 n = data.readInt32();
3364 if (n) {
3365 ALOGV("Interceptor enabled");
3366 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
3367 }
3368 else{
3369 ALOGV("Interceptor disabled");
3370 mInterceptor.disable();
3371 }
3372 return NO_ERROR;
3373 }
3374 case 1021: { // Disable HWC virtual displays
3375 n = data.readInt32();
3376 mUseHwcVirtualDisplays = !n;
3377 return NO_ERROR;
3378 }
3379 }
3380 }
3381 return err;
3382}
3383
3384void SurfaceFlinger::repaintEverything() {
3385 android_atomic_or(1, &mRepaintEverything);
3386 signalTransaction();
3387}
3388
3389// ---------------------------------------------------------------------------
3390// Capture screen into an IGraphiBufferProducer
3391// ---------------------------------------------------------------------------
3392
3393/* The code below is here to handle b/8734824
3394 *
3395 * We create a IGraphicBufferProducer wrapper that forwards all calls
3396 * from the surfaceflinger thread to the calling binder thread, where they
3397 * are executed. This allows the calling thread in the calling process to be
3398 * reused and not depend on having "enough" binder threads to handle the
3399 * requests.
3400 */
3401class GraphicProducerWrapper : public BBinder, public MessageHandler {
3402 /* Parts of GraphicProducerWrapper are run on two different threads,
3403 * communicating by sending messages via Looper but also by shared member
3404 * data. Coherence maintenance is subtle and in places implicit (ugh).
3405 *
3406 * Don't rely on Looper's sendMessage/handleMessage providing
3407 * release/acquire semantics for any data not actually in the Message.
3408 * Data going from surfaceflinger to binder threads needs to be
3409 * synchronized explicitly.
3410 *
3411 * Barrier open/wait do provide release/acquire semantics. This provides
3412 * implicit synchronization for data coming back from binder to
3413 * surfaceflinger threads.
3414 */
3415
3416 sp<IGraphicBufferProducer> impl;
3417 sp<Looper> looper;
3418 status_t result;
3419 bool exitPending;
3420 bool exitRequested;
3421 Barrier barrier;
3422 uint32_t code;
3423 Parcel const* data;
3424 Parcel* reply;
3425
3426 enum {
3427 MSG_API_CALL,
3428 MSG_EXIT
3429 };
3430
3431 /*
3432 * Called on surfaceflinger thread. This is called by our "fake"
3433 * BpGraphicBufferProducer. We package the data and reply Parcel and
3434 * forward them to the binder thread.
3435 */
3436 virtual status_t transact(uint32_t code,
3437 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
3438 this->code = code;
3439 this->data = &data;
3440 this->reply = reply;
3441 if (exitPending) {
3442 // if we've exited, we run the message synchronously right here.
3443 // note (JH): as far as I can tell from looking at the code, this
3444 // never actually happens. if it does, i'm not sure if it happens
3445 // on the surfaceflinger or binder thread.
3446 handleMessage(Message(MSG_API_CALL));
3447 } else {
3448 barrier.close();
3449 // Prevent stores to this->{code, data, reply} from being
3450 // reordered later than the construction of Message.
3451 atomic_thread_fence(memory_order_release);
3452 looper->sendMessage(this, Message(MSG_API_CALL));
3453 barrier.wait();
3454 }
3455 return result;
3456 }
3457
3458 /*
3459 * here we run on the binder thread. All we've got to do is
3460 * call the real BpGraphicBufferProducer.
3461 */
3462 virtual void handleMessage(const Message& message) {
3463 int what = message.what;
3464 // Prevent reads below from happening before the read from Message
3465 atomic_thread_fence(memory_order_acquire);
3466 if (what == MSG_API_CALL) {
3467 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
3468 barrier.open();
3469 } else if (what == MSG_EXIT) {
3470 exitRequested = true;
3471 }
3472 }
3473
3474public:
3475 explicit GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
3476 : impl(impl),
3477 looper(new Looper(true)),
3478 result(NO_ERROR),
3479 exitPending(false),
3480 exitRequested(false),
3481 code(0),
3482 data(NULL),
3483 reply(NULL)
3484 {}
3485
3486 // Binder thread
3487 status_t waitForResponse() {
3488 do {
3489 looper->pollOnce(-1);
3490 } while (!exitRequested);
3491 return result;
3492 }
3493
3494 // Client thread
3495 void exit(status_t result) {
3496 this->result = result;
3497 exitPending = true;
3498 // Ensure this->result is visible to the binder thread before it
3499 // handles the message.
3500 atomic_thread_fence(memory_order_release);
3501 looper->sendMessage(this, Message(MSG_EXIT));
3502 }
3503};
3504
3505
3506status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
3507 const sp<IGraphicBufferProducer>& producer,
3508 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003509 int32_t minLayerZ, int32_t maxLayerZ,
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003510 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
3511
3512 if (CC_UNLIKELY(display == 0))
3513 return BAD_VALUE;
3514
3515 if (CC_UNLIKELY(producer == 0))
3516 return BAD_VALUE;
3517
3518 // if we have secure windows on this display, never allow the screen capture
3519 // unless the producer interface is local (i.e.: we can take a screenshot for
3520 // ourselves).
3521 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
3522
3523 // Convert to surfaceflinger's internal rotation type.
3524 Transform::orientation_flags rotationFlags;
3525 switch (rotation) {
3526 case ISurfaceComposer::eRotateNone:
3527 rotationFlags = Transform::ROT_0;
3528 break;
3529 case ISurfaceComposer::eRotate90:
3530 rotationFlags = Transform::ROT_90;
3531 break;
3532 case ISurfaceComposer::eRotate180:
3533 rotationFlags = Transform::ROT_180;
3534 break;
3535 case ISurfaceComposer::eRotate270:
3536 rotationFlags = Transform::ROT_270;
3537 break;
3538 default:
3539 rotationFlags = Transform::ROT_0;
3540 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
3541 break;
3542 }
3543
3544 class MessageCaptureScreen : public MessageBase {
3545 SurfaceFlinger* flinger;
3546 sp<IBinder> display;
3547 sp<IGraphicBufferProducer> producer;
3548 Rect sourceCrop;
3549 uint32_t reqWidth, reqHeight;
Robert Carrae060832016-11-28 10:51:00 -08003550 int32_t minLayerZ,maxLayerZ;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003551 bool useIdentityTransform;
3552 Transform::orientation_flags rotation;
3553 status_t result;
3554 bool isLocalScreenshot;
3555 public:
3556 MessageCaptureScreen(SurfaceFlinger* flinger,
3557 const sp<IBinder>& display,
3558 const sp<IGraphicBufferProducer>& producer,
3559 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003560 int32_t minLayerZ, int32_t maxLayerZ,
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003561 bool useIdentityTransform,
3562 Transform::orientation_flags rotation,
3563 bool isLocalScreenshot)
3564 : flinger(flinger), display(display), producer(producer),
3565 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
3566 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
3567 useIdentityTransform(useIdentityTransform),
3568 rotation(rotation), result(PERMISSION_DENIED),
3569 isLocalScreenshot(isLocalScreenshot)
3570 {
3571 }
3572 status_t getResult() const {
3573 return result;
3574 }
3575 virtual bool handler() {
3576 Mutex::Autolock _l(flinger->mStateLock);
3577 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
3578 result = flinger->captureScreenImplLocked(hw, producer,
3579 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
3580 useIdentityTransform, rotation, isLocalScreenshot);
3581 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
3582 return true;
3583 }
3584 };
3585
3586 // this creates a "fake" BBinder which will serve as a "fake" remote
3587 // binder to receive the marshaled calls and forward them to the
3588 // real remote (a BpGraphicBufferProducer)
3589 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
3590
3591 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
3592 // which does the marshaling work forwards to our "fake remote" above.
3593 sp<MessageBase> msg = new MessageCaptureScreen(this,
3594 display, IGraphicBufferProducer::asInterface( wrapper ),
3595 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
3596 useIdentityTransform, rotationFlags, isLocalScreenshot);
3597
3598 status_t res = postMessageAsync(msg);
3599 if (res == NO_ERROR) {
3600 res = wrapper->waitForResponse();
3601 }
3602 return res;
3603}
3604
3605
3606void SurfaceFlinger::renderScreenImplLocked(
3607 const sp<const DisplayDevice>& hw,
3608 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003609 int32_t minLayerZ, int32_t maxLayerZ,
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003610 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
3611{
3612 ATRACE_CALL();
3613 RenderEngine& engine(getRenderEngine());
3614
3615 // get screen geometry
3616 const int32_t hw_w = hw->getWidth();
3617 const int32_t hw_h = hw->getHeight();
3618 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
3619 static_cast<int32_t>(reqHeight) != hw_h;
3620
3621 // if a default or invalid sourceCrop is passed in, set reasonable values
3622 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
3623 !sourceCrop.isValid()) {
3624 sourceCrop.setLeftTop(Point(0, 0));
3625 sourceCrop.setRightBottom(Point(hw_w, hw_h));
3626 }
3627
3628 // ensure that sourceCrop is inside screen
3629 if (sourceCrop.left < 0) {
3630 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
3631 }
3632 if (sourceCrop.right > hw_w) {
3633 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
3634 }
3635 if (sourceCrop.top < 0) {
3636 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
3637 }
3638 if (sourceCrop.bottom > hw_h) {
3639 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
3640 }
3641
3642 // make sure to clear all GL error flags
3643 engine.checkErrors();
3644
3645 // set-up our viewport
3646 engine.setViewportAndProjection(
3647 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
3648 engine.disableTexturing();
3649
3650 // redraw the screen entirely...
3651 engine.clearWithColor(0, 0, 0, 1);
3652
Robert Carr1f0a16a2016-10-24 16:27:39 -07003653 // We loop through the first level of layers without traversing,
3654 // as we need to interpret min/max layer Z in the top level Z space.
3655 for (const auto& layer : mDrawingState.layersSortedByZ) {
3656 if (layer->getLayerStack() != hw->getLayerStack()) {
3657 continue;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003658 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003659 const Layer::State& state(layer->getDrawingState());
3660 if (state.z < minLayerZ || state.z > maxLayerZ) {
3661 continue;
3662 }
3663 layer->traverseInZOrder([&](Layer* layer) {
3664 if (!layer->isVisible()) {
3665 return;
3666 }
3667 if (filtering) layer->setFiltering(true);
3668 layer->draw(hw, useIdentityTransform);
3669 if (filtering) layer->setFiltering(false);
3670 });
3671 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003672
3673 // compositionComplete is needed for older driver
3674 hw->compositionComplete();
3675 hw->setViewportAndProjection();
3676}
3677
3678
3679status_t SurfaceFlinger::captureScreenImplLocked(
3680 const sp<const DisplayDevice>& hw,
3681 const sp<IGraphicBufferProducer>& producer,
3682 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003683 int32_t minLayerZ, int32_t maxLayerZ,
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003684 bool useIdentityTransform, Transform::orientation_flags rotation,
3685 bool isLocalScreenshot)
3686{
3687 ATRACE_CALL();
3688
3689 // get screen geometry
3690 uint32_t hw_w = hw->getWidth();
3691 uint32_t hw_h = hw->getHeight();
3692
3693 if (rotation & Transform::ROT_90) {
3694 std::swap(hw_w, hw_h);
3695 }
3696
3697 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
3698 ALOGE("size mismatch (%d, %d) > (%d, %d)",
3699 reqWidth, reqHeight, hw_w, hw_h);
3700 return BAD_VALUE;
3701 }
3702
3703 reqWidth = (!reqWidth) ? hw_w : reqWidth;
3704 reqHeight = (!reqHeight) ? hw_h : reqHeight;
3705
3706 bool secureLayerIsVisible = false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07003707 for (const auto& layer : mDrawingState.layersSortedByZ) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003708 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07003709 if ((layer->getLayerStack() != hw->getLayerStack()) ||
3710 (state.z < minLayerZ || state.z > maxLayerZ)) {
3711 continue;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003712 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003713 layer->traverseInZOrder([&](Layer *layer) {
3714 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
3715 layer->isSecure());
3716 });
3717 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003718
3719 if (!isLocalScreenshot && secureLayerIsVisible) {
3720 ALOGW("FB is protected: PERMISSION_DENIED");
3721 return PERMISSION_DENIED;
3722 }
3723
3724 // create a surface (because we're a producer, and we need to
3725 // dequeue/queue a buffer)
3726 sp<Surface> sur = new Surface(producer, false);
3727 ANativeWindow* window = sur.get();
3728
3729 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
3730 if (result == NO_ERROR) {
3731 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
3732 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
3733
3734 int err = 0;
3735 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
3736 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
3737 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
3738 err |= native_window_set_usage(window, usage);
3739
3740 if (err == NO_ERROR) {
3741 ANativeWindowBuffer* buffer;
3742 /* TODO: Once we have the sync framework everywhere this can use
3743 * server-side waits on the fence that dequeueBuffer returns.
3744 */
3745 result = native_window_dequeue_buffer_and_wait(window, &buffer);
3746 if (result == NO_ERROR) {
3747 int syncFd = -1;
3748 // create an EGLImage from the buffer so we can later
3749 // turn it into a texture
3750 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
3751 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
3752 if (image != EGL_NO_IMAGE_KHR) {
3753 // this binds the given EGLImage as a framebuffer for the
3754 // duration of this scope.
3755 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
3756 if (imageBond.getStatus() == NO_ERROR) {
3757 // this will in fact render into our dequeued buffer
3758 // via an FBO, which means we didn't have to create
3759 // an EGLSurface and therefore we're not
3760 // dependent on the context's EGLConfig.
3761 renderScreenImplLocked(
3762 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
3763 useIdentityTransform, rotation);
3764
3765 // Attempt to create a sync khr object that can produce a sync point. If that
3766 // isn't available, create a non-dupable sync object in the fallback path and
3767 // wait on it directly.
3768 EGLSyncKHR sync;
3769 if (!DEBUG_SCREENSHOTS) {
3770 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
3771 // native fence fd will not be populated until flush() is done.
3772 getRenderEngine().flush();
3773 } else {
3774 sync = EGL_NO_SYNC_KHR;
3775 }
3776 if (sync != EGL_NO_SYNC_KHR) {
3777 // get the sync fd
3778 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
3779 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
3780 ALOGW("captureScreen: failed to dup sync khr object");
3781 syncFd = -1;
3782 }
3783 eglDestroySyncKHR(mEGLDisplay, sync);
3784 } else {
3785 // fallback path
3786 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
3787 if (sync != EGL_NO_SYNC_KHR) {
3788 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
3789 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
3790 EGLint eglErr = eglGetError();
3791 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
3792 ALOGW("captureScreen: fence wait timed out");
3793 } else {
3794 ALOGW_IF(eglErr != EGL_SUCCESS,
3795 "captureScreen: error waiting on EGL fence: %#x", eglErr);
3796 }
3797 eglDestroySyncKHR(mEGLDisplay, sync);
3798 } else {
3799 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
3800 }
3801 }
3802 if (DEBUG_SCREENSHOTS) {
3803 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
3804 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
3805 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
3806 hw, minLayerZ, maxLayerZ);
3807 delete [] pixels;
3808 }
3809
3810 } else {
3811 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
3812 result = INVALID_OPERATION;
3813 window->cancelBuffer(window, buffer, syncFd);
3814 buffer = NULL;
3815 }
3816 // destroy our image
3817 eglDestroyImageKHR(mEGLDisplay, image);
3818 } else {
3819 result = BAD_VALUE;
3820 }
3821 if (buffer) {
3822 // queueBuffer takes ownership of syncFd
3823 result = window->queueBuffer(window, buffer, syncFd);
3824 }
3825 }
3826 } else {
3827 result = BAD_VALUE;
3828 }
3829 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
3830 }
3831
3832 return result;
3833}
3834
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003835void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
Robert Carrae060832016-11-28 10:51:00 -08003836 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003837 if (DEBUG_SCREENSHOTS) {
3838 for (size_t y=0 ; y<h ; y++) {
3839 uint32_t const * p = (uint32_t const *)vaddr + y*s;
3840 for (size_t x=0 ; x<w ; x++) {
3841 if (p[x] != 0xFF000000) return;
3842 }
3843 }
3844 ALOGE("*** we just took a black screenshot ***\n"
3845 "requested minz=%d, maxz=%d, layerStack=%d",
3846 minLayerZ, maxLayerZ, hw->getLayerStack());
Robert Carr2047fae2016-11-28 14:09:09 -08003847 size_t i = 0;
Robert Carr1f0a16a2016-10-24 16:27:39 -07003848 for (const auto& layer : mDrawingState.layersSortedByZ) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003849 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07003850 if (layer->getLayerStack() == hw->getLayerStack() && state.z >= minLayerZ &&
3851 state.z <= maxLayerZ) {
3852 layer->traverseInZOrder([&](Layer* layer) {
3853 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%x",
3854 layer->isVisible() ? '+' : '-',
3855 i, layer->getName().string(), layer->getLayerStack(), state.z,
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003856 layer->isVisible(), state.flags, state.alpha);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003857 i++;
3858 });
3859 }
3860 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003861 }
3862}
3863
3864// ---------------------------------------------------------------------------
3865
Robert Carr2047fae2016-11-28 14:09:09 -08003866void SurfaceFlinger::State::traverseInZOrder(const std::function<void(Layer*)>& consume) const {
3867 layersSortedByZ.traverseInZOrder(consume);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003868}
3869
Robert Carr2047fae2016-11-28 14:09:09 -08003870void SurfaceFlinger::State::traverseInReverseZOrder(const std::function<void(Layer*)>& consume) const {
3871 layersSortedByZ.traverseInReverseZOrder(consume);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003872}
3873
3874}; // namespace android
3875
3876
3877#if defined(__gl_h_)
3878#error "don't include gl/gl.h in this file"
3879#endif
3880
3881#if defined(__gl2_h_)
3882#error "don't include gl2/gl2.h in this file"
3883#endif