blob: 40a27e80c0a2ef53979d729f59ded7150da64ec3 [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
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800191 property_get("debug.sf.enable_hwc_vds", value, "0");
192 mUseHwcVirtualDisplays = atoi(value);
193 ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800194
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800195 property_get("ro.sf.disable_triple_buffer", value, "1");
196 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800197 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
Steven Thomas3cfac282017-02-06 12:29:30 -08001021void SurfaceFlinger::onVSyncReceived(HWComposer* /*composer*/, int type,
1022 nsecs_t timestamp) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001023 bool needsHwVsync = false;
1024
1025 { // Scope for the lock
1026 Mutex::Autolock _l(mHWVsyncLock);
1027 if (type == 0 && mPrimaryHWVsyncEnabled) {
1028 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
1029 }
1030 }
1031
1032 if (needsHwVsync) {
1033 enableHardwareVsync();
1034 } else {
1035 disableHardwareVsync(false);
1036 }
1037}
1038
1039void SurfaceFlinger::onHotplugReceived(int type, bool connected) {
1040 if (mEventThread == NULL) {
1041 // This is a temporary workaround for b/7145521. A non-null pointer
1042 // does not mean EventThread has finished initializing, so this
1043 // is not a correct fix.
1044 ALOGW("WARNING: EventThread not started, ignoring hotplug");
1045 return;
1046 }
1047
1048 if (uint32_t(type) < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
1049 Mutex::Autolock _l(mStateLock);
1050 if (connected) {
1051 createBuiltinDisplayLocked((DisplayDevice::DisplayType)type);
1052 } else {
1053 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1054 mBuiltinDisplays[type].clear();
1055 }
1056 setTransactionFlags(eDisplayTransactionNeeded);
1057
1058 // Defer EventThread notification until SF has updated mDisplays.
1059 }
1060}
1061
Steven Thomas3cfac282017-02-06 12:29:30 -08001062void SurfaceFlinger::onInvalidateReceived(HWComposer* /*composer*/) {
1063 repaintEverything();
1064}
1065
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001066void SurfaceFlinger::eventControl(int disp, int event, int enabled) {
1067 ATRACE_CALL();
1068 getHwComposer().eventControl(disp, event, enabled);
1069}
1070
1071void SurfaceFlinger::onMessageReceived(int32_t what) {
1072 ATRACE_CALL();
1073 switch (what) {
1074 case MessageQueue::INVALIDATE: {
1075 bool refreshNeeded = handleMessageTransaction();
1076 refreshNeeded |= handleMessageInvalidate();
1077 refreshNeeded |= mRepaintEverything;
1078 if (refreshNeeded) {
1079 // Signal a refresh if a transaction modified the window state,
1080 // a new buffer was latched, or if HWC has requested a full
1081 // repaint
1082 signalRefresh();
1083 }
1084 break;
1085 }
1086 case MessageQueue::REFRESH: {
1087 handleMessageRefresh();
1088 break;
1089 }
1090 }
1091}
1092
1093bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001094 uint32_t transactionFlags = peekTransactionFlags();
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001095 if (transactionFlags) {
1096 handleTransaction(transactionFlags);
1097 return true;
1098 }
1099 return false;
1100}
1101
1102bool SurfaceFlinger::handleMessageInvalidate() {
1103 ATRACE_CALL();
1104 return handlePageFlip();
1105}
1106
1107void SurfaceFlinger::handleMessageRefresh() {
1108 ATRACE_CALL();
1109
1110 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1111
Brian Andersond6927fb2016-07-23 23:37:30 -07001112 preComposition(refreshStartTime);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001113 rebuildLayerStacks();
1114 setUpHWComposer();
1115 doDebugFlashRegions();
1116 doComposition();
Brian Andersond6927fb2016-07-23 23:37:30 -07001117 postComposition();
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001118}
1119
1120void SurfaceFlinger::doDebugFlashRegions()
1121{
1122 // is debugging enabled
1123 if (CC_LIKELY(!mDebugRegion))
1124 return;
1125
1126 const bool repaintEverything = mRepaintEverything;
1127 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1128 const sp<DisplayDevice>& hw(mDisplays[dpy]);
1129 if (hw->isDisplayOn()) {
1130 // transform the dirty region into this screen's coordinate space
1131 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1132 if (!dirtyRegion.isEmpty()) {
1133 // redraw the whole screen
1134 doComposeSurfaces(hw, Region(hw->bounds()));
1135
1136 // and draw the dirty region
1137 const int32_t height = hw->getHeight();
1138 RenderEngine& engine(getRenderEngine());
1139 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1140
1141 hw->compositionComplete();
1142 hw->swapBuffers(getHwComposer());
1143 }
1144 }
1145 }
1146
1147 postFramebuffer();
1148
1149 if (mDebugRegion > 1) {
1150 usleep(mDebugRegion * 1000);
1151 }
1152
1153 HWComposer& hwc(getHwComposer());
1154 if (hwc.initCheck() == NO_ERROR) {
1155 status_t err = hwc.prepare();
1156 ALOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err));
1157 }
1158}
1159
Brian Andersond6927fb2016-07-23 23:37:30 -07001160void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001161{
1162 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001163 mDrawingState.traverseInZOrder([&](Layer* layer) {
1164 if (layer->onPreComposition(refreshStartTime)) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001165 needExtraInvalidate = true;
1166 }
Robert Carr2047fae2016-11-28 14:09:09 -08001167 });
1168
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001169 if (needExtraInvalidate) {
1170 signalLayerUpdate();
1171 }
1172}
1173
Brian Andersond6927fb2016-07-23 23:37:30 -07001174void SurfaceFlinger::postComposition()
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001175{
Brian Andersond6927fb2016-07-23 23:37:30 -07001176 const HWComposer& hwc = getHwComposer();
1177 const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
1178
Brian Anderson3d4039d2016-09-23 16:31:30 -07001179 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1180 if (getHwComposer().hasGlesComposition(hw->getHwcDisplayId())) {
1181 glCompositionDoneFenceTime =
1182 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1183 mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1184 } else {
1185 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1186 }
1187 mGlCompositionDoneTimeline.updateSignalTimes();
1188
1189 sp<Fence> displayFence = mHwc->getDisplayFence(HWC_DISPLAY_PRIMARY);
1190 const std::shared_ptr<FenceTime>& presentFenceTime = FenceTime::NO_FENCE;
1191 auto retireFenceTime = std::make_shared<FenceTime>(displayFence);
1192 mDisplayTimeline.push(retireFenceTime);
1193 mDisplayTimeline.updateSignalTimes();
Brian Andersond6927fb2016-07-23 23:37:30 -07001194
Robert Carr2047fae2016-11-28 14:09:09 -08001195 mDrawingState.traverseInZOrder([&](Layer* layer) {
1196 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
1197 presentFenceTime, retireFenceTime);
1198
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001199 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001200 recordBufferingStats(layer->getName().string(),
1201 layer->getOccupancyHistory(false));
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001202 }
Robert Carr2047fae2016-11-28 14:09:09 -08001203 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001204
Brian Anderson3d4039d2016-09-23 16:31:30 -07001205 if (displayFence->isValid()) {
1206 if (mPrimaryDispSync.addPresentFence(displayFence)) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001207 enableHardwareVsync();
1208 } else {
1209 disableHardwareVsync(false);
1210 }
1211 }
1212
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001213 if (kIgnorePresentFences) {
1214 if (hw->isDisplayOn()) {
1215 enableHardwareVsync();
1216 }
1217 }
1218
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001219 if (mAnimCompositionPending) {
1220 mAnimCompositionPending = false;
1221
Brian Anderson3d4039d2016-09-23 16:31:30 -07001222 if (retireFenceTime->isValid()) {
1223 mAnimFrameTracker.setActualPresentFence(std::move(retireFenceTime));
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001224 } else {
1225 // The HWC doesn't support present fences, so use the refresh
1226 // timestamp instead.
1227 nsecs_t presentTime = hwc.getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
1228 mAnimFrameTracker.setActualPresentTime(presentTime);
1229 }
1230 mAnimFrameTracker.advanceFrame();
1231 }
1232
1233 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1234 return;
1235 }
1236
1237 nsecs_t currentTime = systemTime();
1238 if (mHasPoweredOff) {
1239 mHasPoweredOff = false;
1240 } else {
1241 nsecs_t period = mPrimaryDispSync.getPeriod();
1242 nsecs_t elapsedTime = currentTime - mLastSwapTime;
1243 size_t numPeriods = static_cast<size_t>(elapsedTime / period);
1244 if (numPeriods < NUM_BUCKETS - 1) {
1245 mFrameBuckets[numPeriods] += elapsedTime;
1246 } else {
1247 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1248 }
1249 mTotalTime += elapsedTime;
1250 }
1251 mLastSwapTime = currentTime;
1252}
1253
1254void SurfaceFlinger::rebuildLayerStacks() {
1255 // rebuild the visible layer list per screen
1256 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
1257 ATRACE_CALL();
1258 mVisibleRegionsDirty = false;
1259 invalidateHwcGeometry();
1260
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001261 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1262 Region opaqueRegion;
1263 Region dirtyRegion;
1264 Vector< sp<Layer> > layersSortedByZ;
1265 const sp<DisplayDevice>& hw(mDisplays[dpy]);
1266 const Transform& tr(hw->getTransform());
1267 const Rect bounds(hw->getBounds());
1268 if (hw->isDisplayOn()) {
Robert Carr2047fae2016-11-28 14:09:09 -08001269 computeVisibleRegions(hw->getLayerStack(), dirtyRegion,
1270 opaqueRegion);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001271
Robert Carr2047fae2016-11-28 14:09:09 -08001272 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001273 if (layer->getLayerStack() == hw->getLayerStack()) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001274 Region drawRegion(tr.transform(
1275 layer->visibleNonTransparentRegion));
1276 drawRegion.andSelf(bounds);
1277 if (!drawRegion.isEmpty()) {
1278 layersSortedByZ.add(layer);
1279 }
1280 }
Robert Carr2047fae2016-11-28 14:09:09 -08001281 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001282 }
1283 hw->setVisibleLayersSortedByZ(layersSortedByZ);
1284 hw->undefinedRegion.set(bounds);
1285 hw->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
1286 hw->dirtyRegion.orSelf(dirtyRegion);
1287 }
1288 }
1289}
1290
1291void SurfaceFlinger::setUpHWComposer() {
1292 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1293 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1294 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1295 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1296
1297 // If nothing has changed (!dirty), don't recompose.
1298 // If something changed, but we don't currently have any visible layers,
1299 // and didn't when we last did a composition, then skip it this time.
1300 // The second rule does two things:
1301 // - When all layers are removed from a display, we'll emit one black
1302 // frame, then nothing more until we get new layers.
1303 // - When a display is created with a private layer stack, we won't
1304 // emit any black frames until a layer is added to the layer stack.
1305 bool mustRecompose = dirty && !(empty && wasEmpty);
1306
1307 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1308 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1309 mustRecompose ? "doing" : "skipping",
1310 dirty ? "+" : "-",
1311 empty ? "+" : "-",
1312 wasEmpty ? "+" : "-");
1313
1314 mDisplays[dpy]->beginFrame(mustRecompose);
1315
1316 if (mustRecompose) {
1317 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1318 }
1319 }
1320
1321 HWComposer& hwc(getHwComposer());
1322 if (hwc.initCheck() == NO_ERROR) {
1323 // build the h/w work list
1324 if (CC_UNLIKELY(mHwWorkListDirty)) {
1325 mHwWorkListDirty = false;
1326 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1327 sp<const DisplayDevice> hw(mDisplays[dpy]);
1328 const int32_t id = hw->getHwcDisplayId();
1329 if (id >= 0) {
1330 const Vector< sp<Layer> >& currentLayers(
1331 hw->getVisibleLayersSortedByZ());
1332 const size_t count = currentLayers.size();
1333 if (hwc.createWorkList(id, count) == NO_ERROR) {
1334 HWComposer::LayerListIterator cur = hwc.begin(id);
1335 const HWComposer::LayerListIterator end = hwc.end(id);
1336 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1337 const sp<Layer>& layer(currentLayers[i]);
1338 layer->setGeometry(hw, *cur);
1339 if (mDebugDisableHWC || mDebugRegion || mDaltonize || mHasColorMatrix) {
1340 cur->setSkip(true);
1341 }
1342 }
1343 }
1344 }
1345 }
1346 }
1347
1348 // set the per-frame data
1349 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1350 sp<const DisplayDevice> hw(mDisplays[dpy]);
1351 const int32_t id = hw->getHwcDisplayId();
1352 if (id >= 0) {
1353 const Vector< sp<Layer> >& currentLayers(
1354 hw->getVisibleLayersSortedByZ());
1355 const size_t count = currentLayers.size();
1356 HWComposer::LayerListIterator cur = hwc.begin(id);
1357 const HWComposer::LayerListIterator end = hwc.end(id);
1358 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1359 /*
1360 * update the per-frame h/w composer data for each layer
1361 * and build the transparent region of the FB
1362 */
1363 const sp<Layer>& layer(currentLayers[i]);
1364 layer->setPerFrameData(hw, *cur);
1365 }
1366 }
1367 }
1368
1369 // If possible, attempt to use the cursor overlay on each display.
1370 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1371 sp<const DisplayDevice> hw(mDisplays[dpy]);
1372 const int32_t id = hw->getHwcDisplayId();
1373 if (id >= 0) {
1374 const Vector< sp<Layer> >& currentLayers(
1375 hw->getVisibleLayersSortedByZ());
1376 const size_t count = currentLayers.size();
1377 HWComposer::LayerListIterator cur = hwc.begin(id);
1378 const HWComposer::LayerListIterator end = hwc.end(id);
1379 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1380 const sp<Layer>& layer(currentLayers[i]);
1381 if (layer->isPotentialCursor()) {
1382 cur->setIsCursorLayerHint();
1383 break;
1384 }
1385 }
1386 }
1387 }
1388
1389 status_t err = hwc.prepare();
1390 ALOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err));
1391
1392 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1393 sp<const DisplayDevice> hw(mDisplays[dpy]);
1394 hw->prepareFrame(hwc);
1395 }
1396 }
1397}
1398
1399void SurfaceFlinger::doComposition() {
1400 ATRACE_CALL();
1401 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
1402 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1403 const sp<DisplayDevice>& hw(mDisplays[dpy]);
1404 if (hw->isDisplayOn()) {
1405 // transform the dirty region into this screen's coordinate space
1406 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1407
1408 // repaint the framebuffer (if needed)
1409 doDisplayComposition(hw, dirtyRegion);
1410
1411 hw->dirtyRegion.clear();
1412 hw->flip(hw->swapRegion);
1413 hw->swapRegion.clear();
1414 }
1415 // inform the h/w that we're done compositing
1416 hw->compositionComplete();
1417 }
1418 postFramebuffer();
1419}
1420
1421void SurfaceFlinger::postFramebuffer()
1422{
1423 ATRACE_CALL();
1424
1425 const nsecs_t now = systemTime();
1426 mDebugInSwapBuffers = now;
1427
1428 HWComposer& hwc(getHwComposer());
1429 if (hwc.initCheck() == NO_ERROR) {
1430 if (!hwc.supportsFramebufferTarget()) {
1431 // EGL spec says:
1432 // "surface must be bound to the calling thread's current context,
1433 // for the current rendering API."
1434 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
1435 }
1436 hwc.commit();
1437 }
1438
1439 // make the default display current because the VirtualDisplayDevice code cannot
1440 // deal with dequeueBuffer() being called outside of the composition loop; however
1441 // the code below can call glFlush() which is allowed (and does in some case) call
1442 // dequeueBuffer().
1443 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
1444
1445 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1446 sp<const DisplayDevice> hw(mDisplays[dpy]);
1447 const Vector< sp<Layer> >& currentLayers(hw->getVisibleLayersSortedByZ());
1448 hw->onSwapBuffersCompleted(hwc);
1449 const size_t count = currentLayers.size();
1450 int32_t id = hw->getHwcDisplayId();
1451 if (id >=0 && hwc.initCheck() == NO_ERROR) {
1452 HWComposer::LayerListIterator cur = hwc.begin(id);
1453 const HWComposer::LayerListIterator end = hwc.end(id);
1454 for (size_t i = 0; cur != end && i < count; ++i, ++cur) {
1455 currentLayers[i]->onLayerDisplayed(hw, &*cur);
1456 }
1457 } else {
1458 for (size_t i = 0; i < count; i++) {
1459 currentLayers[i]->onLayerDisplayed(hw, NULL);
1460 }
1461 }
1462 }
1463
1464 mLastSwapBufferTime = systemTime() - now;
1465 mDebugInSwapBuffers = 0;
1466
1467 uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
1468 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1469 logFrameStats();
1470 }
1471}
1472
1473void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
1474{
1475 ATRACE_CALL();
1476
1477 // here we keep a copy of the drawing state (that is the state that's
1478 // going to be overwritten by handleTransactionLocked()) outside of
1479 // mStateLock so that the side-effects of the State assignment
1480 // don't happen with mStateLock held (which can cause deadlocks).
1481 State drawingState(mDrawingState);
1482
1483 Mutex::Autolock _l(mStateLock);
1484 const nsecs_t now = systemTime();
1485 mDebugInTransaction = now;
1486
1487 // Here we're guaranteed that some transaction flags are set
1488 // so we can call handleTransactionLocked() unconditionally.
1489 // We call getTransactionFlags(), which will also clear the flags,
1490 // with mStateLock held to guarantee that mCurrentState won't change
1491 // until the transaction is committed.
1492
1493 transactionFlags = getTransactionFlags(eTransactionMask);
1494 handleTransactionLocked(transactionFlags);
1495
1496 mLastTransactionTime = systemTime() - now;
1497 mDebugInTransaction = 0;
1498 invalidateHwcGeometry();
1499 // here the transaction has been committed
1500}
1501
1502void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
1503{
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001504 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08001505 mCurrentState.traverseInZOrder([](Layer* layer) {
1506 layer->notifyAvailableFrames();
1507 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001508
1509 /*
1510 * Traversal of the children
1511 * (perform the transaction for each of them if needed)
1512 */
1513
1514 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08001515 mCurrentState.traverseInZOrder([&](Layer* layer) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001516 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08001517 if (!trFlags) return;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001518
1519 const uint32_t flags = layer->doTransaction(0);
1520 if (flags & Layer::eVisibleRegion)
1521 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08001522 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001523 }
1524
1525 /*
1526 * Perform display own transactions if needed
1527 */
1528
1529 if (transactionFlags & eDisplayTransactionNeeded) {
1530 // here we take advantage of Vector's copy-on-write semantics to
1531 // improve performance by skipping the transaction entirely when
1532 // know that the lists are identical
1533 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1534 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
1535 if (!curr.isIdenticalTo(draw)) {
1536 mVisibleRegionsDirty = true;
1537 const size_t cc = curr.size();
1538 size_t dc = draw.size();
1539
1540 // find the displays that were removed
1541 // (ie: in drawing state but not in current state)
1542 // also handle displays that changed
1543 // (ie: displays that are in both lists)
1544 for (size_t i=0 ; i<dc ; i++) {
1545 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1546 if (j < 0) {
1547 // in drawing state but not in current state
1548 if (!draw[i].isMainDisplay()) {
1549 // Call makeCurrent() on the primary display so we can
1550 // be sure that nothing associated with this display
1551 // is current.
1552 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
1553 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
1554 sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1555 if (hw != NULL)
1556 hw->disconnect(getHwComposer());
1557 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
1558 mEventThread->onHotplugReceived(draw[i].type, false);
1559 mDisplays.removeItem(draw.keyAt(i));
1560 } else {
1561 ALOGW("trying to remove the main display");
1562 }
1563 } else {
1564 // this display is in both lists. see if something changed.
1565 const DisplayDeviceState& state(curr[j]);
1566 const wp<IBinder>& display(curr.keyAt(j));
1567 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
1568 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
1569 if (state_binder != draw_binder) {
1570 // changing the surface is like destroying and
1571 // recreating the DisplayDevice, so we just remove it
1572 // from the drawing state, so that it get re-added
1573 // below.
1574 sp<DisplayDevice> hw(getDisplayDevice(display));
1575 if (hw != NULL)
1576 hw->disconnect(getHwComposer());
1577 mDisplays.removeItem(display);
1578 mDrawingState.displays.removeItemsAt(i);
1579 dc--; i--;
1580 // at this point we must loop to the next item
1581 continue;
1582 }
1583
1584 const sp<DisplayDevice> disp(getDisplayDevice(display));
1585 if (disp != NULL) {
1586 if (state.layerStack != draw[i].layerStack) {
1587 disp->setLayerStack(state.layerStack);
1588 }
1589 if ((state.orientation != draw[i].orientation)
1590 || (state.viewport != draw[i].viewport)
1591 || (state.frame != draw[i].frame))
1592 {
1593 disp->setProjection(state.orientation,
1594 state.viewport, state.frame);
1595 }
1596 if (state.width != draw[i].width || state.height != draw[i].height) {
1597 disp->setDisplaySize(state.width, state.height);
1598 }
1599 }
1600 }
1601 }
1602
1603 // find displays that were added
1604 // (ie: in current state but not in drawing state)
1605 for (size_t i=0 ; i<cc ; i++) {
1606 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
1607 const DisplayDeviceState& state(curr[i]);
1608
1609 sp<DisplaySurface> dispSurface;
1610 sp<IGraphicBufferProducer> producer;
1611 sp<IGraphicBufferProducer> bqProducer;
1612 sp<IGraphicBufferConsumer> bqConsumer;
1613 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer,
1614 new GraphicBufferAlloc());
1615
1616 int32_t hwcDisplayId = -1;
1617 if (state.isVirtualDisplay()) {
1618 // Virtual displays without a surface are dormant:
1619 // they have external state (layer stack, projection,
1620 // etc.) but no internal state (i.e. a DisplayDevice).
1621 if (state.surface != NULL) {
1622
1623 int width = 0;
1624 int status = state.surface->query(
1625 NATIVE_WINDOW_WIDTH, &width);
1626 ALOGE_IF(status != NO_ERROR,
1627 "Unable to query width (%d)", status);
1628 int height = 0;
1629 status = state.surface->query(
1630 NATIVE_WINDOW_HEIGHT, &height);
1631 ALOGE_IF(status != NO_ERROR,
1632 "Unable to query height (%d)", status);
1633 if (mUseHwcVirtualDisplays &&
1634 (MAX_VIRTUAL_DISPLAY_DIMENSION == 0 ||
1635 (width <= MAX_VIRTUAL_DISPLAY_DIMENSION &&
1636 height <= MAX_VIRTUAL_DISPLAY_DIMENSION))) {
1637 hwcDisplayId = allocateHwcDisplayId(state.type);
1638 }
1639
1640 sp<VirtualDisplaySurface> vds = new VirtualDisplaySurface(
1641 *mHwc, hwcDisplayId, state.surface,
1642 bqProducer, bqConsumer, state.displayName);
1643
1644 dispSurface = vds;
1645 producer = vds;
1646 }
1647 } else {
1648 ALOGE_IF(state.surface!=NULL,
1649 "adding a supported display, but rendering "
1650 "surface is provided (%p), ignoring it",
1651 state.surface.get());
1652 hwcDisplayId = allocateHwcDisplayId(state.type);
1653 // for supported (by hwc) displays we provide our
1654 // own rendering surface
1655 dispSurface = new FramebufferSurface(*mHwc, state.type,
1656 bqConsumer);
1657 producer = bqProducer;
1658 }
1659
1660 const wp<IBinder>& display(curr.keyAt(i));
1661 if (dispSurface != NULL) {
1662 sp<DisplayDevice> hw = new DisplayDevice(this,
1663 state.type, hwcDisplayId,
1664 mHwc->getFormat(hwcDisplayId), state.isSecure,
1665 display, dispSurface, producer,
1666 mRenderEngine->getEGLConfig());
1667 hw->setLayerStack(state.layerStack);
1668 hw->setProjection(state.orientation,
1669 state.viewport, state.frame);
1670 hw->setDisplayName(state.displayName);
1671 mDisplays.add(display, hw);
1672 if (state.isVirtualDisplay()) {
1673 if (hwcDisplayId >= 0) {
1674 mHwc->setVirtualDisplayProperties(hwcDisplayId,
1675 hw->getWidth(), hw->getHeight(),
1676 hw->getFormat());
1677 }
1678 } else {
1679 mEventThread->onHotplugReceived(state.type, true);
1680 }
1681 }
1682 }
1683 }
1684 }
1685 }
1686
1687 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
1688 // The transform hint might have changed for some layers
1689 // (either because a display has changed, or because a layer
1690 // as changed).
1691 //
1692 // Walk through all the layers in currentLayers,
1693 // and update their transform hint.
1694 //
1695 // If a layer is visible only on a single display, then that
1696 // display is used to calculate the hint, otherwise we use the
1697 // default display.
1698 //
1699 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
1700 // the hint is set before we acquire a buffer from the surface texture.
1701 //
1702 // NOTE: layer transactions have taken place already, so we use their
1703 // drawing state. However, SurfaceFlinger's own transaction has not
1704 // happened yet, so we must use the current state layer list
1705 // (soon to become the drawing state list).
1706 //
1707 sp<const DisplayDevice> disp;
1708 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08001709 bool first = true;
1710 mCurrentState.traverseInZOrder([&](Layer* layer) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001711 // NOTE: we rely on the fact that layers are sorted by
1712 // layerStack first (so we don't have to traverse the list
1713 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07001714 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08001715 if (first || currentlayerStack != layerStack) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001716 currentlayerStack = layerStack;
1717 // figure out if this layerstack is mirrored
1718 // (more than one display) if so, pick the default display,
1719 // if not, pick the only display it's on.
1720 disp.clear();
1721 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1722 sp<const DisplayDevice> hw(mDisplays[dpy]);
1723 if (hw->getLayerStack() == currentlayerStack) {
1724 if (disp == NULL) {
1725 disp = hw;
1726 } else {
1727 disp = NULL;
1728 break;
1729 }
1730 }
1731 }
1732 }
1733 if (disp == NULL) {
1734 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
1735 // redraw after transform hint changes. See bug 8508397.
1736
1737 // could be null when this layer is using a layerStack
1738 // that is not visible on any display. Also can occur at
1739 // screen off/on times.
1740 disp = getDefaultDisplayDevice();
1741 }
1742 layer->updateTransformHint(disp);
Robert Carr2047fae2016-11-28 14:09:09 -08001743
1744 first = false;
1745 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001746 }
1747
1748
1749 /*
1750 * Perform our own transaction if needed
1751 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07001752
1753 if (mLayersAdded) {
1754 mLayersAdded = false;
1755 // Layers have been added.
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001756 mVisibleRegionsDirty = true;
1757 }
1758
1759 // some layers might have been removed, so
1760 // we need to update the regions they're exposing.
1761 if (mLayersRemoved) {
1762 mLayersRemoved = false;
1763 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08001764 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07001765 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001766 // this layer is not visible anymore
1767 // TODO: we could traverse the tree from front to back and
1768 // compute the actual visible region
1769 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07001770 Region visibleReg;
1771 visibleReg.set(layer->computeScreenBounds());
1772 invalidateLayerStack(layer->getLayerStack(), visibleReg);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001773 }
Robert Carr2047fae2016-11-28 14:09:09 -08001774 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001775 }
1776
1777 commitTransaction();
1778
1779 updateCursorAsync();
1780}
1781
1782void SurfaceFlinger::updateCursorAsync()
1783{
1784 HWComposer& hwc(getHwComposer());
1785 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1786 sp<const DisplayDevice> hw(mDisplays[dpy]);
1787 const int32_t id = hw->getHwcDisplayId();
1788 if (id < 0) {
1789 continue;
1790 }
1791 const Vector< sp<Layer> >& currentLayers(
1792 hw->getVisibleLayersSortedByZ());
1793 const size_t count = currentLayers.size();
1794 HWComposer::LayerListIterator cur = hwc.begin(id);
1795 const HWComposer::LayerListIterator end = hwc.end(id);
1796 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1797 if (cur->getCompositionType() != HWC_CURSOR_OVERLAY) {
1798 continue;
1799 }
1800 const sp<Layer>& layer(currentLayers[i]);
1801 Rect cursorPos = layer->getPosition(hw);
1802 hwc.setCursorPositionAsync(id, cursorPos);
1803 break;
1804 }
1805 }
1806}
1807
1808void SurfaceFlinger::commitTransaction()
1809{
1810 if (!mLayersPendingRemoval.isEmpty()) {
1811 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07001812 for (const auto& l : mLayersPendingRemoval) {
1813 recordBufferingStats(l->getName().string(),
1814 l->getOccupancyHistory(true));
1815 l->onRemoved();
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001816 }
1817 mLayersPendingRemoval.clear();
1818 }
1819
1820 // If this transaction is part of a window animation then the next frame
1821 // we composite should be considered an animation as well.
1822 mAnimCompositionPending = mAnimTransactionPending;
1823
1824 mDrawingState = mCurrentState;
Robert Carr1f0a16a2016-10-24 16:27:39 -07001825 mDrawingState.traverseInZOrder([](Layer* layer) {
1826 layer->commitChildList();
1827 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001828 mTransactionPending = false;
1829 mAnimTransactionPending = false;
1830 mTransactionCV.broadcast();
1831}
1832
Robert Carr2047fae2016-11-28 14:09:09 -08001833void SurfaceFlinger::computeVisibleRegions(uint32_t layerStack,
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001834 Region& outDirtyRegion, Region& outOpaqueRegion)
1835{
1836 ATRACE_CALL();
1837
1838 Region aboveOpaqueLayers;
1839 Region aboveCoveredLayers;
1840 Region dirty;
1841
1842 outDirtyRegion.clear();
1843
Robert Carr2047fae2016-11-28 14:09:09 -08001844 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001845 // start with the whole surface at its current location
1846 const Layer::State& s(layer->getDrawingState());
1847
1848 // only consider the layers on the given layer stack
Robert Carr1f0a16a2016-10-24 16:27:39 -07001849 if (layer->getLayerStack() != layerStack)
Robert Carr2047fae2016-11-28 14:09:09 -08001850 return;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001851
1852 /*
1853 * opaqueRegion: area of a surface that is fully opaque.
1854 */
1855 Region opaqueRegion;
1856
1857 /*
1858 * visibleRegion: area of a surface that is visible on screen
1859 * and not fully transparent. This is essentially the layer's
1860 * footprint minus the opaque regions above it.
1861 * Areas covered by a translucent surface are considered visible.
1862 */
1863 Region visibleRegion;
1864
1865 /*
1866 * coveredRegion: area of a surface that is covered by all
1867 * visible regions above it (which includes the translucent areas).
1868 */
1869 Region coveredRegion;
1870
1871 /*
1872 * transparentRegion: area of a surface that is hinted to be completely
1873 * transparent. This is only used to tell when the layer has no visible
1874 * non-transparent regions and can be removed from the layer list. It
1875 * does not affect the visibleRegion of this layer or any layers
1876 * beneath it. The hint may not be correct if apps don't respect the
1877 * SurfaceView restrictions (which, sadly, some don't).
1878 */
1879 Region transparentRegion;
1880
1881
1882 // handle hidden surfaces by setting the visible region to empty
1883 if (CC_LIKELY(layer->isVisible())) {
1884 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001885 Rect bounds(layer->computeScreenBounds());
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001886 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07001887 Transform tr = layer->getTransform();
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001888 if (!visibleRegion.isEmpty()) {
1889 // Remove the transparent area from the visible region
1890 if (translucent) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001891 if (tr.preserveRects()) {
1892 // transform the transparent region
1893 transparentRegion = tr.transform(s.activeTransparentRegion);
1894 } else {
1895 // transformation too complex, can't do the
1896 // transparent region optimization.
1897 transparentRegion.clear();
1898 }
1899 }
1900
1901 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07001902 const int32_t layerOrientation = tr.getOrientation();
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001903 if (s.alpha==255 && !translucent &&
1904 ((layerOrientation & Transform::ROT_INVALID) == false)) {
1905 // the opaque region is the layer's footprint
1906 opaqueRegion = visibleRegion;
1907 }
1908 }
1909 }
1910
1911 // Clip the covered region to the visible region
1912 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
1913
1914 // Update aboveCoveredLayers for next (lower) layer
1915 aboveCoveredLayers.orSelf(visibleRegion);
1916
1917 // subtract the opaque region covered by the layers above us
1918 visibleRegion.subtractSelf(aboveOpaqueLayers);
1919
1920 // compute this layer's dirty region
1921 if (layer->contentDirty) {
1922 // we need to invalidate the whole region
1923 dirty = visibleRegion;
1924 // as well, as the old visible region
1925 dirty.orSelf(layer->visibleRegion);
1926 layer->contentDirty = false;
1927 } else {
1928 /* compute the exposed region:
1929 * the exposed region consists of two components:
1930 * 1) what's VISIBLE now and was COVERED before
1931 * 2) what's EXPOSED now less what was EXPOSED before
1932 *
1933 * note that (1) is conservative, we start with the whole
1934 * visible region but only keep what used to be covered by
1935 * something -- which mean it may have been exposed.
1936 *
1937 * (2) handles areas that were not covered by anything but got
1938 * exposed because of a resize.
1939 */
1940 const Region newExposed = visibleRegion - coveredRegion;
1941 const Region oldVisibleRegion = layer->visibleRegion;
1942 const Region oldCoveredRegion = layer->coveredRegion;
1943 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
1944 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
1945 }
1946 dirty.subtractSelf(aboveOpaqueLayers);
1947
1948 // accumulate to the screen dirty region
1949 outDirtyRegion.orSelf(dirty);
1950
1951 // Update aboveOpaqueLayers for next (lower) layer
1952 aboveOpaqueLayers.orSelf(opaqueRegion);
1953
1954 // Store the visible region in screen space
1955 layer->setVisibleRegion(visibleRegion);
1956 layer->setCoveredRegion(coveredRegion);
1957 layer->setVisibleNonTransparentRegion(
1958 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08001959 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001960
1961 outOpaqueRegion = aboveOpaqueLayers;
1962}
1963
1964void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
1965 const Region& dirty) {
1966 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1967 const sp<DisplayDevice>& hw(mDisplays[dpy]);
1968 if (hw->getLayerStack() == layerStack) {
1969 hw->dirtyRegion.orSelf(dirty);
1970 }
1971 }
1972}
1973
1974bool SurfaceFlinger::handlePageFlip()
1975{
Brian Andersond6927fb2016-07-23 23:37:30 -07001976 nsecs_t latchTime = systemTime();
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001977 Region dirtyRegion;
1978
1979 bool visibleRegions = false;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001980 bool frameQueued = false;
1981
1982 // Store the set of layers that need updates. This set must not change as
1983 // buffers are being latched, as this could result in a deadlock.
1984 // Example: Two producers share the same command stream and:
1985 // 1.) Layer 0 is latched
1986 // 2.) Layer 0 gets a new frame
1987 // 2.) Layer 1 gets a new frame
1988 // 3.) Layer 1 is latched.
1989 // Display is now waiting on Layer 1's frame, which is behind layer 0's
1990 // second frame. But layer 0's second frame could be waiting on display.
1991 Vector<Layer*> layersWithQueuedFrames;
Robert Carr2047fae2016-11-28 14:09:09 -08001992 mDrawingState.traverseInZOrder([&](Layer* layer) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001993 if (layer->hasQueuedFrame()) {
1994 frameQueued = true;
1995 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08001996 layersWithQueuedFrames.push_back(layer);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00001997 } else {
1998 layer->useEmptyDamage();
1999 }
2000 } else {
2001 layer->useEmptyDamage();
2002 }
Robert Carr2047fae2016-11-28 14:09:09 -08002003 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002004 for (size_t i = 0, count = layersWithQueuedFrames.size() ; i<count ; i++) {
2005 Layer* layer = layersWithQueuedFrames[i];
Brian Andersond6927fb2016-07-23 23:37:30 -07002006 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002007 layer->useSurfaceDamage();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002008 invalidateLayerStack(layer->getLayerStack(), dirty);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002009 }
2010
2011 mVisibleRegionsDirty |= visibleRegions;
2012
2013 // If we will need to wake up at some time in the future to deal with a
2014 // queued frame that shouldn't be displayed during this vsync period, wake
2015 // up during the next vsync period to check again.
2016 if (frameQueued && layersWithQueuedFrames.empty()) {
2017 signalLayerUpdate();
2018 }
2019
2020 // Only continue with the refresh if there is actually new work to do
2021 return !layersWithQueuedFrames.empty();
2022}
2023
2024void SurfaceFlinger::invalidateHwcGeometry()
2025{
2026 mHwWorkListDirty = true;
2027}
2028
2029
2030void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& hw,
2031 const Region& inDirtyRegion)
2032{
2033 // We only need to actually compose the display if:
2034 // 1) It is being handled by hardware composer, which may need this to
2035 // keep its virtual display state machine in sync, or
2036 // 2) There is work to be done (the dirty region isn't empty)
2037 bool isHwcDisplay = hw->getHwcDisplayId() >= 0;
2038 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
2039 return;
2040 }
2041
2042 Region dirtyRegion(inDirtyRegion);
2043
2044 // compute the invalid region
2045 hw->swapRegion.orSelf(dirtyRegion);
2046
2047 uint32_t flags = hw->getFlags();
2048 if (flags & DisplayDevice::SWAP_RECTANGLE) {
2049 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2050 // takes a rectangle, we must make sure to update that whole
2051 // rectangle in that case
2052 dirtyRegion.set(hw->swapRegion.bounds());
2053 } else {
2054 if (flags & DisplayDevice::PARTIAL_UPDATES) {
2055 // We need to redraw the rectangle that will be updated
2056 // (pushed to the framebuffer).
2057 // This is needed because PARTIAL_UPDATES only takes one
2058 // rectangle instead of a region (see DisplayDevice::flip())
2059 dirtyRegion.set(hw->swapRegion.bounds());
2060 } else {
2061 // we need to redraw everything (the whole screen)
2062 dirtyRegion.set(hw->bounds());
2063 hw->swapRegion = dirtyRegion;
2064 }
2065 }
2066
2067 if (CC_LIKELY(!mDaltonize && !mHasColorMatrix)) {
2068 if (!doComposeSurfaces(hw, dirtyRegion)) return;
2069 } else {
2070 RenderEngine& engine(getRenderEngine());
2071 mat4 colorMatrix = mColorMatrix;
2072 if (mDaltonize) {
2073 colorMatrix = colorMatrix * mDaltonizer();
2074 }
2075 mat4 oldMatrix = engine.setupColorTransform(colorMatrix);
2076 doComposeSurfaces(hw, dirtyRegion);
2077 engine.setupColorTransform(oldMatrix);
2078 }
2079
2080 // update the swap region and clear the dirty region
2081 hw->swapRegion.orSelf(dirtyRegion);
2082
2083 // swap buffers (presentation)
2084 hw->swapBuffers(getHwComposer());
2085}
2086
2087bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& hw, const Region& dirty)
2088{
2089 RenderEngine& engine(getRenderEngine());
2090 const int32_t id = hw->getHwcDisplayId();
2091 HWComposer& hwc(getHwComposer());
2092 HWComposer::LayerListIterator cur = hwc.begin(id);
2093 const HWComposer::LayerListIterator end = hwc.end(id);
2094
2095 bool hasGlesComposition = hwc.hasGlesComposition(id);
2096 if (hasGlesComposition) {
2097 if (!hw->makeCurrent(mEGLDisplay, mEGLContext)) {
2098 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
2099 hw->getDisplayName().string());
2100 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
2101 if(!getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext)) {
2102 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2103 }
2104 return false;
2105 }
2106
2107 // Never touch the framebuffer if we don't have any framebuffer layers
2108 const bool hasHwcComposition = hwc.hasHwcComposition(id);
2109 if (hasHwcComposition) {
2110 // when using overlays, we assume a fully transparent framebuffer
2111 // NOTE: we could reduce how much we need to clear, for instance
2112 // remove where there are opaque FB layers. however, on some
2113 // GPUs doing a "clean slate" clear might be more efficient.
2114 // We'll revisit later if needed.
2115 engine.clearWithColor(0, 0, 0, 0);
2116 } else {
2117 // we start with the whole screen area
2118 const Region bounds(hw->getBounds());
2119
2120 // we remove the scissor part
2121 // we're left with the letterbox region
2122 // (common case is that letterbox ends-up being empty)
2123 const Region letterbox(bounds.subtract(hw->getScissor()));
2124
2125 // compute the area to clear
2126 Region region(hw->undefinedRegion.merge(letterbox));
2127
2128 // but limit it to the dirty region
2129 region.andSelf(dirty);
2130
2131 // screen is already cleared here
2132 if (!region.isEmpty()) {
2133 // can happen with SurfaceView
2134 drawWormhole(hw, region);
2135 }
2136 }
2137
2138 if (hw->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
2139 // just to be on the safe side, we don't set the
2140 // scissor on the main display. It should never be needed
2141 // anyways (though in theory it could since the API allows it).
2142 const Rect& bounds(hw->getBounds());
2143 const Rect& scissor(hw->getScissor());
2144 if (scissor != bounds) {
2145 // scissor doesn't match the screen's dimensions, so we
2146 // need to clear everything outside of it and enable
2147 // the GL scissor so we don't draw anything where we shouldn't
2148
2149 // enable scissor for this frame
2150 const uint32_t height = hw->getHeight();
2151 engine.setScissor(scissor.left, height - scissor.bottom,
2152 scissor.getWidth(), scissor.getHeight());
2153 }
2154 }
2155 }
2156
2157 /*
2158 * and then, render the layers targeted at the framebuffer
2159 */
2160
2161 const Vector< sp<Layer> >& layers(hw->getVisibleLayersSortedByZ());
2162 const size_t count = layers.size();
2163 const Transform& tr = hw->getTransform();
2164 if (cur != end) {
2165 // we're using h/w composer
2166 for (size_t i=0 ; i<count && cur!=end ; ++i, ++cur) {
2167 const sp<Layer>& layer(layers[i]);
2168 const Region clip(dirty.intersect(tr.transform(layer->visibleRegion)));
2169 if (!clip.isEmpty()) {
2170 switch (cur->getCompositionType()) {
2171 case HWC_CURSOR_OVERLAY:
2172 case HWC_OVERLAY: {
2173 const Layer::State& state(layer->getDrawingState());
2174 if ((cur->getHints() & HWC_HINT_CLEAR_FB)
2175 && i
2176 && layer->isOpaque(state) && (state.alpha == 0xFF)
2177 && hasGlesComposition) {
2178 // never clear the very first layer since we're
2179 // guaranteed the FB is already cleared
Fabien Sanglard17487192016-12-07 13:03:32 -08002180 layer->clearWithOpenGL(hw);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002181 }
2182 break;
2183 }
2184 case HWC_FRAMEBUFFER: {
2185 layer->draw(hw, clip);
2186 break;
2187 }
2188 case HWC_FRAMEBUFFER_TARGET: {
2189 // this should not happen as the iterator shouldn't
2190 // let us get there.
2191 ALOGW("HWC_FRAMEBUFFER_TARGET found in hwc list (index=%zu)", i);
2192 break;
2193 }
2194 }
2195 }
2196 layer->setAcquireFence(hw, *cur);
2197 }
2198 } else {
2199 // we're not using h/w composer
2200 for (size_t i=0 ; i<count ; ++i) {
2201 const sp<Layer>& layer(layers[i]);
2202 const Region clip(dirty.intersect(
2203 tr.transform(layer->visibleRegion)));
2204 if (!clip.isEmpty()) {
2205 layer->draw(hw, clip);
2206 }
2207 }
2208 }
2209
2210 // disable scissor at the end of the frame
2211 engine.disableScissor();
2212 return true;
2213}
2214
2215void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& hw, const Region& region) const {
2216 const int32_t height = hw->getHeight();
2217 RenderEngine& engine(getRenderEngine());
2218 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
2219}
2220
2221status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
2222 const sp<IBinder>& handle,
2223 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07002224 const sp<Layer>& lbc,
2225 const sp<Layer>& parent)
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002226{
2227 // add this layer to the current state list
2228 {
2229 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002230 if (mNumLayers >= MAX_LAYERS) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002231 return NO_MEMORY;
2232 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002233 if (parent == nullptr) {
2234 mCurrentState.layersSortedByZ.add(lbc);
2235 } else {
2236 parent->addChild(lbc);
2237 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002238 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
Robert Carr1f0a16a2016-10-24 16:27:39 -07002239 mLayersAdded = true;
2240 mNumLayers++;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002241 }
2242
2243 // attach this layer to the client
2244 client->attachLayer(handle, lbc);
2245
2246 return NO_ERROR;
2247}
2248
2249status_t SurfaceFlinger::removeLayer(const wp<Layer>& weakLayer) {
2250 Mutex::Autolock _l(mStateLock);
2251 sp<Layer> layer = weakLayer.promote();
2252 if (layer == nullptr) {
2253 // The layer has already been removed, carry on
2254 return NO_ERROR;
2255 }
2256
Robert Carr1f0a16a2016-10-24 16:27:39 -07002257 const auto& p = layer->getParent();
2258 const ssize_t index = (p != nullptr) ? p->removeChild(layer) :
2259 mCurrentState.layersSortedByZ.remove(layer);
2260
2261 if (index < 0) {
2262 ALOGE("Failed to find layer (%s) in layer parent (%s).",
2263 layer->getName().string(),
2264 (p != nullptr) ? p->getName().string() : "no-parent");
2265 return BAD_VALUE;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002266 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002267
2268 mLayersPendingRemoval.add(layer);
2269 mLayersRemoved = true;
2270 mNumLayers--;
2271 setTransactionFlags(eTransactionNeeded);
2272 return NO_ERROR;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002273}
2274
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002275uint32_t SurfaceFlinger::peekTransactionFlags() {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002276 return android_atomic_release_load(&mTransactionFlags);
2277}
2278
2279uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
2280 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2281}
2282
2283uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
2284 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2285 if ((old & flags)==0) { // wake the server up
2286 signalTransaction();
2287 }
2288 return old;
2289}
2290
2291void SurfaceFlinger::setTransactionState(
2292 const Vector<ComposerState>& state,
2293 const Vector<DisplayState>& displays,
2294 uint32_t flags)
2295{
2296 ATRACE_CALL();
2297 Mutex::Autolock _l(mStateLock);
2298 uint32_t transactionFlags = 0;
2299
2300 if (flags & eAnimation) {
2301 // For window updates that are part of an animation we must wait for
2302 // previous animation "frames" to be handled.
2303 while (mAnimTransactionPending) {
2304 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2305 if (CC_UNLIKELY(err != NO_ERROR)) {
2306 // just in case something goes wrong in SF, return to the
2307 // caller after a few seconds.
2308 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2309 "waiting for previous animation frame");
2310 mAnimTransactionPending = false;
2311 break;
2312 }
2313 }
2314 }
2315
2316 size_t count = displays.size();
2317 for (size_t i=0 ; i<count ; i++) {
2318 const DisplayState& s(displays[i]);
2319 transactionFlags |= setDisplayStateLocked(s);
2320 }
2321
2322 count = state.size();
2323 for (size_t i=0 ; i<count ; i++) {
2324 const ComposerState& s(state[i]);
2325 // Here we need to check that the interface we're given is indeed
2326 // one of our own. A malicious client could give us a NULL
2327 // IInterface, or one of its own or even one of our own but a
2328 // different type. All these situations would cause us to crash.
2329 //
2330 // NOTE: it would be better to use RTTI as we could directly check
2331 // that we have a Client*. however, RTTI is disabled in Android.
2332 if (s.client != NULL) {
2333 sp<IBinder> binder = IInterface::asBinder(s.client);
2334 if (binder != NULL) {
Fabien Sanglard45b20252017-01-18 16:43:18 -08002335 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002336 sp<Client> client( static_cast<Client *>(s.client.get()) );
2337 transactionFlags |= setClientStateLocked(client, s.state);
2338 }
2339 }
2340 }
2341 }
2342
2343 // If a synchronous transaction is explicitly requested without any changes,
2344 // force a transaction anyway. This can be used as a flush mechanism for
2345 // previous async transactions.
2346 if (transactionFlags == 0 && (flags & eSynchronous)) {
2347 transactionFlags = eTransactionNeeded;
2348 }
2349
2350 if (transactionFlags) {
2351 if (mInterceptor.isEnabled()) {
2352 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2353 }
2354
2355 // this triggers the transaction
2356 setTransactionFlags(transactionFlags);
2357
2358 // if this is a synchronous transaction, wait for it to take effect
2359 // before returning.
2360 if (flags & eSynchronous) {
2361 mTransactionPending = true;
2362 }
2363 if (flags & eAnimation) {
2364 mAnimTransactionPending = true;
2365 }
2366 while (mTransactionPending) {
2367 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2368 if (CC_UNLIKELY(err != NO_ERROR)) {
2369 // just in case something goes wrong in SF, return to the
2370 // called after a few seconds.
2371 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2372 mTransactionPending = false;
2373 break;
2374 }
2375 }
2376 }
2377}
2378
2379uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2380{
2381 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2382 if (dpyIdx < 0)
2383 return 0;
2384
2385 uint32_t flags = 0;
2386 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
2387 if (disp.isValid()) {
2388 const uint32_t what = s.what;
2389 if (what & DisplayState::eSurfaceChanged) {
2390 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
2391 disp.surface = s.surface;
2392 flags |= eDisplayTransactionNeeded;
2393 }
2394 }
2395 if (what & DisplayState::eLayerStackChanged) {
2396 if (disp.layerStack != s.layerStack) {
2397 disp.layerStack = s.layerStack;
2398 flags |= eDisplayTransactionNeeded;
2399 }
2400 }
2401 if (what & DisplayState::eDisplayProjectionChanged) {
2402 if (disp.orientation != s.orientation) {
2403 disp.orientation = s.orientation;
2404 flags |= eDisplayTransactionNeeded;
2405 }
2406 if (disp.frame != s.frame) {
2407 disp.frame = s.frame;
2408 flags |= eDisplayTransactionNeeded;
2409 }
2410 if (disp.viewport != s.viewport) {
2411 disp.viewport = s.viewport;
2412 flags |= eDisplayTransactionNeeded;
2413 }
2414 }
2415 if (what & DisplayState::eDisplaySizeChanged) {
2416 if (disp.width != s.width) {
2417 disp.width = s.width;
2418 flags |= eDisplayTransactionNeeded;
2419 }
2420 if (disp.height != s.height) {
2421 disp.height = s.height;
2422 flags |= eDisplayTransactionNeeded;
2423 }
2424 }
2425 }
2426 return flags;
2427}
2428
2429uint32_t SurfaceFlinger::setClientStateLocked(
2430 const sp<Client>& client,
2431 const layer_state_t& s)
2432{
2433 uint32_t flags = 0;
2434 sp<Layer> layer(client->getLayerUser(s.surface));
2435 if (layer != 0) {
2436 const uint32_t what = s.what;
2437 bool geometryAppliesWithResize =
2438 what & layer_state_t::eGeometryAppliesWithResize;
2439 if (what & layer_state_t::ePositionChanged) {
2440 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
2441 flags |= eTraversalNeeded;
2442 }
2443 }
2444 if (what & layer_state_t::eLayerChanged) {
2445 // NOTE: index needs to be calculated before we update the state
Robert Carr1f0a16a2016-10-24 16:27:39 -07002446 const auto& p = layer->getParent();
2447 if (p == nullptr) {
2448 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2449 if (layer->setLayer(s.z) && idx >= 0) {
2450 mCurrentState.layersSortedByZ.removeAt(idx);
2451 mCurrentState.layersSortedByZ.add(layer);
2452 // we need traversal (state changed)
2453 // AND transaction (list changed)
2454 flags |= eTransactionNeeded|eTraversalNeeded;
2455 }
2456 } else {
2457 if (p->setChildLayer(layer, s.z)) {
2458 flags |= eTransactionNeeded|eTraversalNeeded;
2459 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002460 }
2461 }
2462 if (what & layer_state_t::eSizeChanged) {
2463 if (layer->setSize(s.w, s.h)) {
2464 flags |= eTraversalNeeded;
2465 }
2466 }
2467 if (what & layer_state_t::eAlphaChanged) {
2468 if (layer->setAlpha(uint8_t(255.0f*s.alpha+0.5f)))
2469 flags |= eTraversalNeeded;
2470 }
2471 if (what & layer_state_t::eMatrixChanged) {
2472 if (layer->setMatrix(s.matrix))
2473 flags |= eTraversalNeeded;
2474 }
2475 if (what & layer_state_t::eTransparentRegionChanged) {
2476 if (layer->setTransparentRegionHint(s.transparentRegion))
2477 flags |= eTraversalNeeded;
2478 }
2479 if (what & layer_state_t::eFlagsChanged) {
2480 if (layer->setFlags(s.flags, s.mask))
2481 flags |= eTraversalNeeded;
2482 }
2483 if (what & layer_state_t::eCropChanged) {
2484 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
2485 flags |= eTraversalNeeded;
2486 }
2487 if (what & layer_state_t::eFinalCropChanged) {
2488 if (layer->setFinalCrop(s.finalCrop))
2489 flags |= eTraversalNeeded;
2490 }
2491 if (what & layer_state_t::eLayerStackChanged) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002492 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002493 // We only allow setting layer stacks for top level layers,
2494 // everything else inherits layer stack from its parent.
2495 if (layer->hasParent()) {
2496 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
2497 layer->getName().string());
2498 } else if (idx < 0) {
2499 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
2500 "that also does not appear in the top level layer list. Something"
2501 " has gone wrong.", layer->getName().string());
2502 } else if (layer->setLayerStack(s.layerStack)) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002503 mCurrentState.layersSortedByZ.removeAt(idx);
2504 mCurrentState.layersSortedByZ.add(layer);
2505 // we need traversal (state changed)
2506 // AND transaction (list changed)
2507 flags |= eTransactionNeeded|eTraversalNeeded;
2508 }
2509 }
2510 if (what & layer_state_t::eDeferTransaction) {
2511 layer->deferTransactionUntil(s.handle, s.frameNumber);
2512 // We don't trigger a traversal here because if no other state is
2513 // changed, we don't want this to cause any more work
2514 }
Robert Carr1db73f62016-12-21 12:58:51 -08002515 if (what & layer_state_t::eReparentChildren) {
2516 if (layer->reparentChildren(s.reparentHandle)) {
2517 flags |= eTransactionNeeded|eTraversalNeeded;
2518 }
2519 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002520 if (what & layer_state_t::eOverrideScalingModeChanged) {
2521 layer->setOverrideScalingMode(s.overrideScalingMode);
2522 // We don't trigger a traversal here because if no other state is
2523 // changed, we don't want this to cause any more work
2524 }
2525 }
2526 return flags;
2527}
2528
2529status_t SurfaceFlinger::createLayer(
2530 const String8& name,
2531 const sp<Client>& client,
2532 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
Albert Chaulk479c60c2017-01-27 14:21:34 -05002533 uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
2534 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002535{
2536 if (int32_t(w|h) < 0) {
2537 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
2538 int(w), int(h));
2539 return BAD_VALUE;
2540 }
2541
2542 status_t result = NO_ERROR;
2543
2544 sp<Layer> layer;
2545
2546 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2547 case ISurfaceComposerClient::eFXSurfaceNormal:
2548 result = createNormalLayer(client,
2549 name, w, h, flags, format,
2550 handle, gbp, &layer);
2551 break;
2552 case ISurfaceComposerClient::eFXSurfaceDim:
2553 result = createDimLayer(client,
2554 name, w, h, flags,
2555 handle, gbp, &layer);
2556 break;
2557 default:
2558 result = BAD_VALUE;
2559 break;
2560 }
2561
2562 if (result != NO_ERROR) {
2563 return result;
2564 }
2565
Albert Chaulk479c60c2017-01-27 14:21:34 -05002566 layer->setInfo(windowType, ownerUid);
2567
Robert Carr1f0a16a2016-10-24 16:27:39 -07002568 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002569 if (result != NO_ERROR) {
2570 return result;
2571 }
2572 mInterceptor.saveSurfaceCreation(layer);
2573
2574 setTransactionFlags(eTransactionNeeded);
2575 return result;
2576}
2577
2578status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
2579 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
2580 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
2581{
2582 // initialize the surfaces
2583 switch (format) {
2584 case PIXEL_FORMAT_TRANSPARENT:
2585 case PIXEL_FORMAT_TRANSLUCENT:
2586 format = PIXEL_FORMAT_RGBA_8888;
2587 break;
2588 case PIXEL_FORMAT_OPAQUE:
2589 format = PIXEL_FORMAT_RGBX_8888;
2590 break;
2591 }
2592
2593 *outLayer = new Layer(this, client, name, w, h, flags);
2594 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
2595 if (err == NO_ERROR) {
2596 *handle = (*outLayer)->getHandle();
2597 *gbp = (*outLayer)->getProducer();
2598 }
2599
2600 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
2601 return err;
2602}
2603
2604status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
2605 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2606 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
2607{
2608 *outLayer = new LayerDim(this, client, name, w, h, flags);
2609 *handle = (*outLayer)->getHandle();
2610 *gbp = (*outLayer)->getProducer();
2611 return NO_ERROR;
2612}
2613
2614status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
2615{
2616 // called by the window manager when it wants to remove a Layer
2617 status_t err = NO_ERROR;
2618 sp<Layer> l(client->getLayerUser(handle));
2619 if (l != NULL) {
2620 mInterceptor.saveSurfaceDeletion(l);
2621 err = removeLayer(l);
2622 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2623 "error removing layer=%p (%s)", l.get(), strerror(-err));
2624 }
2625 return err;
2626}
2627
2628status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
2629{
2630 // called by ~LayerCleaner() when all references to the IBinder (handle)
2631 // are gone
2632 return removeLayer(layer);
2633}
2634
2635// ---------------------------------------------------------------------------
2636
2637void SurfaceFlinger::onInitializeDisplays() {
2638 // reset screen orientation and use primary layer stack
2639 Vector<ComposerState> state;
2640 Vector<DisplayState> displays;
2641 DisplayState d;
2642 d.what = DisplayState::eDisplayProjectionChanged |
2643 DisplayState::eLayerStackChanged;
2644 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
2645 d.layerStack = 0;
2646 d.orientation = DisplayState::eOrientationDefault;
2647 d.frame.makeInvalid();
2648 d.viewport.makeInvalid();
2649 d.width = 0;
2650 d.height = 0;
2651 displays.add(d);
2652 setTransactionState(state, displays, 0);
2653 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
2654
2655 const nsecs_t period =
2656 getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
2657 mAnimFrameTracker.setDisplayRefreshPeriod(period);
2658}
2659
2660void SurfaceFlinger::initializeDisplays() {
2661 class MessageScreenInitialized : public MessageBase {
2662 SurfaceFlinger* flinger;
2663 public:
2664 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
2665 virtual bool handler() {
2666 flinger->onInitializeDisplays();
2667 return true;
2668 }
2669 };
2670 sp<MessageBase> msg = new MessageScreenInitialized(this);
2671 postMessageAsync(msg); // we may be called from main thread, use async message
2672}
2673
2674void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
2675 int mode) {
2676 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
2677 this);
2678 int32_t type = hw->getDisplayType();
2679 int currentMode = hw->getPowerMode();
2680
2681 if (mode == currentMode) {
2682 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
2683 return;
2684 }
2685
2686 hw->setPowerMode(mode);
2687 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
2688 ALOGW("Trying to set power mode for virtual display");
2689 return;
2690 }
2691
2692 if (mInterceptor.isEnabled()) {
2693 Mutex::Autolock _l(mStateLock);
2694 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
2695 if (idx < 0) {
2696 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
2697 return;
2698 }
2699 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
2700 }
2701
2702 if (currentMode == HWC_POWER_MODE_OFF) {
2703 // Turn on the display
2704 getHwComposer().setPowerMode(type, mode);
2705 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2706 // FIXME: eventthread only knows about the main display right now
2707 mEventThread->onScreenAcquired();
2708 resyncToHardwareVsync(true);
2709 }
2710
2711 mVisibleRegionsDirty = true;
2712 mHasPoweredOff = true;
2713 repaintEverything();
2714
2715 struct sched_param param = {0};
2716 param.sched_priority = 1;
2717 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
2718 ALOGW("Couldn't set SCHED_FIFO on display on");
2719 }
2720 } else if (mode == HWC_POWER_MODE_OFF) {
2721 // Turn off the display
2722 struct sched_param param = {0};
2723 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
2724 ALOGW("Couldn't set SCHED_OTHER on display off");
2725 }
2726
2727 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2728 disableHardwareVsync(true); // also cancels any in-progress resync
2729
2730 // FIXME: eventthread only knows about the main display right now
2731 mEventThread->onScreenReleased();
2732 }
2733
2734 getHwComposer().setPowerMode(type, mode);
2735 mVisibleRegionsDirty = true;
2736 // from this point on, SF will stop drawing on this display
2737 } else {
2738 getHwComposer().setPowerMode(type, mode);
2739 }
2740}
2741
2742void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
2743 class MessageSetPowerMode: public MessageBase {
2744 SurfaceFlinger& mFlinger;
2745 sp<IBinder> mDisplay;
2746 int mMode;
2747 public:
2748 MessageSetPowerMode(SurfaceFlinger& flinger,
2749 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
2750 mDisplay(disp) { mMode = mode; }
2751 virtual bool handler() {
2752 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
2753 if (hw == NULL) {
2754 ALOGE("Attempt to set power mode = %d for null display %p",
2755 mMode, mDisplay.get());
2756 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
2757 ALOGW("Attempt to set power mode = %d for virtual display",
2758 mMode);
2759 } else {
2760 mFlinger.setPowerModeInternal(hw, mMode);
2761 }
2762 return true;
2763 }
2764 };
2765 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
2766 postMessageSync(msg);
2767}
2768
2769// ---------------------------------------------------------------------------
2770
2771status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
2772{
2773 String8 result;
2774
2775 IPCThreadState* ipc = IPCThreadState::self();
2776 const int pid = ipc->getCallingPid();
2777 const int uid = ipc->getCallingUid();
2778 if ((uid != AID_SHELL) &&
2779 !PermissionCache::checkPermission(sDump, pid, uid)) {
2780 result.appendFormat("Permission Denial: "
2781 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
2782 } else {
2783 // Try to get the main lock, but give up after one second
2784 // (this would indicate SF is stuck, but we want to be able to
2785 // print something in dumpsys).
2786 status_t err = mStateLock.timedLock(s2ns(1));
2787 bool locked = (err == NO_ERROR);
2788 if (!locked) {
2789 result.appendFormat(
2790 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
2791 "dumping anyways (no locks held)\n", strerror(-err), err);
2792 }
2793
2794 bool dumpAll = true;
2795 size_t index = 0;
2796 size_t numArgs = args.size();
2797 if (numArgs) {
2798 if ((index < numArgs) &&
2799 (args[index] == String16("--list"))) {
2800 index++;
2801 listLayersLocked(args, index, result);
2802 dumpAll = false;
2803 }
2804
2805 if ((index < numArgs) &&
2806 (args[index] == String16("--latency"))) {
2807 index++;
2808 dumpStatsLocked(args, index, result);
2809 dumpAll = false;
2810 }
2811
2812 if ((index < numArgs) &&
2813 (args[index] == String16("--latency-clear"))) {
2814 index++;
2815 clearStatsLocked(args, index, result);
2816 dumpAll = false;
2817 }
2818
2819 if ((index < numArgs) &&
2820 (args[index] == String16("--dispsync"))) {
2821 index++;
2822 mPrimaryDispSync.dump(result);
2823 dumpAll = false;
2824 }
2825
2826 if ((index < numArgs) &&
2827 (args[index] == String16("--static-screen"))) {
2828 index++;
2829 dumpStaticScreenStats(result);
2830 dumpAll = false;
2831 }
2832
2833 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07002834 (args[index] == String16("--frame-events"))) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002835 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07002836 dumpFrameEventsLocked(result);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002837 dumpAll = false;
2838 }
2839 }
2840
2841 if (dumpAll) {
2842 dumpAllLocked(args, index, result);
2843 }
2844
2845 if (locked) {
2846 mStateLock.unlock();
2847 }
2848 }
2849 write(fd, result.string(), result.size());
2850 return NO_ERROR;
2851}
2852
2853void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
2854 size_t& /* index */, String8& result) const
2855{
Robert Carr2047fae2016-11-28 14:09:09 -08002856 mCurrentState.traverseInZOrder([&](Layer* layer) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002857 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08002858 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002859}
2860
2861void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
2862 String8& result) const
2863{
2864 String8 name;
2865 if (index < args.size()) {
2866 name = String8(args[index]);
2867 index++;
2868 }
2869
2870 const nsecs_t period =
2871 getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
2872 result.appendFormat("%" PRId64 "\n", period);
2873
2874 if (name.isEmpty()) {
2875 mAnimFrameTracker.dumpStats(result);
2876 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08002877 mCurrentState.traverseInZOrder([&](Layer* layer) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002878 if (name == layer->getName()) {
2879 layer->dumpFrameStats(result);
2880 }
Robert Carr2047fae2016-11-28 14:09:09 -08002881 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002882 }
2883}
2884
2885void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
2886 String8& /* result */)
2887{
2888 String8 name;
2889 if (index < args.size()) {
2890 name = String8(args[index]);
2891 index++;
2892 }
2893
Robert Carr2047fae2016-11-28 14:09:09 -08002894 mCurrentState.traverseInZOrder([&](Layer* layer) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002895 if (name.isEmpty() || (name == layer->getName())) {
2896 layer->clearFrameStats();
2897 }
Robert Carr2047fae2016-11-28 14:09:09 -08002898 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002899
2900 mAnimFrameTracker.clearStats();
2901}
2902
2903// This should only be called from the main thread. Otherwise it would need
2904// the lock and should use mCurrentState rather than mDrawingState.
2905void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08002906 mDrawingState.traverseInZOrder([&](Layer* layer) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002907 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08002908 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002909
2910 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
2911}
2912
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08002913void SurfaceFlinger::appendSfConfigString(String8& result) const
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002914{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08002915 result.append(" [sf");
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002916#ifdef HAS_CONTEXT_PRIORITY
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08002917 result.append(" HAS_CONTEXT_PRIORITY");
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002918#endif
2919#ifdef NEVER_DEFAULT_TO_ASYNC_MODE
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08002920 result.append(" NEVER_DEFAULT_TO_ASYNC_MODE");
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002921#endif
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08002922 if (isLayerTripleBufferingDisabled())
2923 result.append(" DISABLE_TRIPLE_BUFFERING");
2924 result.append("]");
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002925}
2926
2927void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
2928{
2929 result.appendFormat("Static screen stats:\n");
2930 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
2931 float bucketTimeSec = mFrameBuckets[b] / 1e9;
2932 float percent = 100.0f *
2933 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
2934 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
2935 b + 1, bucketTimeSec, percent);
2936 }
2937 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
2938 float percent = 100.0f *
2939 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
2940 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
2941 NUM_BUCKETS - 1, bucketTimeSec, percent);
2942}
2943
Brian Andersond6927fb2016-07-23 23:37:30 -07002944void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
2945 result.appendFormat("Layer frame timestamps:\n");
2946
2947 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2948 const size_t count = currentLayers.size();
2949 for (size_t i=0 ; i<count ; i++) {
2950 currentLayers[i]->dumpFrameEvents(result);
2951 }
2952}
2953
Fabien Sanglard9d96de42016-10-11 00:15:18 +00002954void SurfaceFlinger::recordBufferingStats(const char* layerName,
2955 std::vector<OccupancyTracker::Segment>&& history) {
2956 Mutex::Autolock lock(mBufferingStatsMutex);
2957 auto& stats = mBufferingStats[layerName];
2958 for (const auto& segment : history) {
2959 if (!segment.usedThirdBuffer) {
2960 stats.twoBufferTime += segment.totalTime;
2961 }
2962 if (segment.occupancyAverage < 1.0f) {
2963 stats.doubleBufferedTime += segment.totalTime;
2964 } else if (segment.occupancyAverage < 2.0f) {
2965 stats.tripleBufferedTime += segment.totalTime;
2966 }
2967 ++stats.numSegments;
2968 stats.totalTime += segment.totalTime;
2969 }
2970}
2971
2972void SurfaceFlinger::dumpBufferingStats(String8& result) const {
2973 result.append("Buffering stats:\n");
2974 result.append(" [Layer name] <Active time> <Two buffer> "
2975 "<Double buffered> <Triple buffered>\n");
2976 Mutex::Autolock lock(mBufferingStatsMutex);
2977 typedef std::tuple<std::string, float, float, float> BufferTuple;
2978 std::map<float, BufferTuple, std::greater<float>> sorted;
2979 for (const auto& statsPair : mBufferingStats) {
2980 const char* name = statsPair.first.c_str();
2981 const BufferingStats& stats = statsPair.second;
2982 if (stats.numSegments == 0) {
2983 continue;
2984 }
2985 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
2986 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
2987 stats.totalTime;
2988 float doubleBufferRatio = static_cast<float>(
2989 stats.doubleBufferedTime) / stats.totalTime;
2990 float tripleBufferRatio = static_cast<float>(
2991 stats.tripleBufferedTime) / stats.totalTime;
2992 sorted.insert({activeTime, {name, twoBufferRatio,
2993 doubleBufferRatio, tripleBufferRatio}});
2994 }
2995 for (const auto& sortedPair : sorted) {
2996 float activeTime = sortedPair.first;
2997 const BufferTuple& values = sortedPair.second;
2998 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
2999 std::get<0>(values).c_str(), activeTime,
3000 std::get<1>(values), std::get<2>(values),
3001 std::get<3>(values));
3002 }
3003 result.append("\n");
3004}
3005
3006void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3007 String8& result) const
3008{
3009 bool colorize = false;
3010 if (index < args.size()
3011 && (args[index] == String16("--color"))) {
3012 colorize = true;
3013 index++;
3014 }
3015
3016 Colorizer colorizer(colorize);
3017
3018 // figure out if we're stuck somewhere
3019 const nsecs_t now = systemTime();
3020 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3021 const nsecs_t inTransaction(mDebugInTransaction);
3022 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3023 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3024
3025 /*
3026 * Dump library configuration.
3027 */
3028
3029 colorizer.bold(result);
3030 result.append("Build configuration:");
3031 colorizer.reset(result);
3032 appendSfConfigString(result);
3033 appendUiConfigString(result);
3034 appendGuiConfigString(result);
3035 result.append("\n");
3036
3037 colorizer.bold(result);
3038 result.append("Sync configuration: ");
3039 colorizer.reset(result);
3040 result.append(SyncFeatures::getInstance().toString());
3041 result.append("\n");
3042
3043 colorizer.bold(result);
3044 result.append("DispSync configuration: ");
3045 colorizer.reset(result);
3046 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
3047 "present offset %d ns (refresh %" PRId64 " ns)",
3048 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs, PRESENT_TIME_OFFSET_FROM_VSYNC_NS,
3049 mHwc->getRefreshPeriod(HWC_DISPLAY_PRIMARY));
3050 result.append("\n");
3051
3052 // Dump static screen stats
3053 result.append("\n");
3054 dumpStaticScreenStats(result);
3055 result.append("\n");
3056
3057 dumpBufferingStats(result);
3058
3059 /*
3060 * Dump the visible layer list
3061 */
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003062 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003063 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003064 colorizer.reset(result);
Robert Carr2047fae2016-11-28 14:09:09 -08003065 mCurrentState.traverseInZOrder([&](Layer* layer) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003066 layer->dump(result, colorizer);
Robert Carr2047fae2016-11-28 14:09:09 -08003067 });
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003068
3069 /*
3070 * Dump Display state
3071 */
3072
3073 colorizer.bold(result);
3074 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
3075 colorizer.reset(result);
3076 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3077 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
3078 hw->dump(result);
3079 }
3080
3081 /*
3082 * Dump SurfaceFlinger global state
3083 */
3084
3085 colorizer.bold(result);
3086 result.append("SurfaceFlinger global state:\n");
3087 colorizer.reset(result);
3088
3089 HWComposer& hwc(getHwComposer());
3090 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
3091
3092 colorizer.bold(result);
3093 result.appendFormat("EGL implementation : %s\n",
3094 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3095 colorizer.reset(result);
3096 result.appendFormat("%s\n",
3097 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
3098
3099 mRenderEngine->dump(result);
3100
3101 hw->undefinedRegion.dump(result, "undefinedRegion");
3102 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3103 hw->getOrientation(), hw->isDisplayOn());
3104 result.appendFormat(
3105 " last eglSwapBuffers() time: %f us\n"
3106 " last transaction time : %f us\n"
3107 " transaction-flags : %08x\n"
3108 " refresh-rate : %f fps\n"
3109 " x-dpi : %f\n"
3110 " y-dpi : %f\n"
3111 " gpu_to_cpu_unsupported : %d\n"
3112 ,
3113 mLastSwapBufferTime/1000.0,
3114 mLastTransactionTime/1000.0,
3115 mTransactionFlags,
3116 1e9 / hwc.getRefreshPeriod(HWC_DISPLAY_PRIMARY),
3117 hwc.getDpiX(HWC_DISPLAY_PRIMARY),
3118 hwc.getDpiY(HWC_DISPLAY_PRIMARY),
3119 !mGpuToCpuSupported);
3120
3121 result.appendFormat(" eglSwapBuffers time: %f us\n",
3122 inSwapBuffersDuration/1000.0);
3123
3124 result.appendFormat(" transaction time: %f us\n",
3125 inTransactionDuration/1000.0);
3126
3127 /*
3128 * VSYNC state
3129 */
3130 mEventThread->dump(result);
3131
3132 /*
3133 * Dump HWComposer state
3134 */
3135 colorizer.bold(result);
3136 result.append("h/w composer state:\n");
3137 colorizer.reset(result);
3138 result.appendFormat(" h/w composer %s and %s\n",
3139 hwc.initCheck()==NO_ERROR ? "present" : "not present",
3140 (mDebugDisableHWC || mDebugRegion || mDaltonize
3141 || mHasColorMatrix) ? "disabled" : "enabled");
3142 hwc.dump(result);
3143
3144 /*
3145 * Dump gralloc state
3146 */
3147 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3148 alloc.dump(result);
3149}
3150
3151const Vector< sp<Layer> >&
3152SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
3153 // Note: mStateLock is held here
3154 wp<IBinder> dpy;
3155 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3156 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3157 dpy = mDisplays.keyAt(i);
3158 break;
3159 }
3160 }
3161 if (dpy == NULL) {
3162 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3163 // Just use the primary display so we have something to return
3164 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3165 }
3166 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
3167}
3168
3169bool SurfaceFlinger::startDdmConnection()
3170{
3171 void* libddmconnection_dso =
3172 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3173 if (!libddmconnection_dso) {
3174 return false;
3175 }
3176 void (*DdmConnection_start)(const char* name);
3177 DdmConnection_start =
3178 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
3179 if (!DdmConnection_start) {
3180 dlclose(libddmconnection_dso);
3181 return false;
3182 }
3183 (*DdmConnection_start)(getServiceName());
3184 return true;
3185}
3186
3187status_t SurfaceFlinger::onTransact(
3188 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3189{
3190 switch (code) {
3191 case CREATE_CONNECTION:
3192 case CREATE_DISPLAY:
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003193 case BOOT_FINISHED:
3194 case CLEAR_ANIMATION_FRAME_STATS:
3195 case GET_ANIMATION_FRAME_STATS:
3196 case SET_POWER_MODE:
3197 case GET_HDR_CAPABILITIES:
3198 {
3199 // codes that require permission check
3200 IPCThreadState* ipc = IPCThreadState::self();
3201 const int pid = ipc->getCallingPid();
3202 const int uid = ipc->getCallingUid();
3203 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
3204 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
3205 ALOGE("Permission Denial: "
3206 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
3207 return PERMISSION_DENIED;
3208 }
3209 break;
3210 }
Robert Carr1db73f62016-12-21 12:58:51 -08003211 /*
3212 * Calling setTransactionState is safe, because you need to have been
3213 * granted a reference to Client* and Handle* to do anything with it.
3214 *
3215 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
3216 */
3217 case SET_TRANSACTION_STATE:
3218 case CREATE_SCOPED_CONNECTION:
3219 {
3220 break;
3221 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003222 case CAPTURE_SCREEN:
3223 {
3224 // codes that require permission check
3225 IPCThreadState* ipc = IPCThreadState::self();
3226 const int pid = ipc->getCallingPid();
3227 const int uid = ipc->getCallingUid();
3228 if ((uid != AID_GRAPHICS) &&
3229 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
3230 ALOGE("Permission Denial: "
3231 "can't read framebuffer pid=%d, uid=%d", pid, uid);
3232 return PERMISSION_DENIED;
3233 }
3234 break;
3235 }
3236 }
3237
3238 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3239 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
3240 CHECK_INTERFACE(ISurfaceComposer, data, reply);
3241 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
3242 IPCThreadState* ipc = IPCThreadState::self();
3243 const int pid = ipc->getCallingPid();
3244 const int uid = ipc->getCallingUid();
3245 ALOGE("Permission Denial: "
3246 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
3247 return PERMISSION_DENIED;
3248 }
3249 int n;
3250 switch (code) {
3251 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
3252 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
3253 return NO_ERROR;
3254 case 1002: // SHOW_UPDATES
3255 n = data.readInt32();
3256 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
3257 invalidateHwcGeometry();
3258 repaintEverything();
3259 return NO_ERROR;
3260 case 1004:{ // repaint everything
3261 repaintEverything();
3262 return NO_ERROR;
3263 }
3264 case 1005:{ // force transaction
3265 setTransactionFlags(
3266 eTransactionNeeded|
3267 eDisplayTransactionNeeded|
3268 eTraversalNeeded);
3269 return NO_ERROR;
3270 }
3271 case 1006:{ // send empty update
3272 signalRefresh();
3273 return NO_ERROR;
3274 }
3275 case 1008: // toggle use of hw composer
3276 n = data.readInt32();
3277 mDebugDisableHWC = n ? 1 : 0;
3278 invalidateHwcGeometry();
3279 repaintEverything();
3280 return NO_ERROR;
3281 case 1009: // toggle use of transform hint
3282 n = data.readInt32();
3283 mDebugDisableTransformHint = n ? 1 : 0;
3284 invalidateHwcGeometry();
3285 repaintEverything();
3286 return NO_ERROR;
3287 case 1010: // interrogate.
3288 reply->writeInt32(0);
3289 reply->writeInt32(0);
3290 reply->writeInt32(mDebugRegion);
3291 reply->writeInt32(0);
3292 reply->writeInt32(mDebugDisableHWC);
3293 return NO_ERROR;
3294 case 1013: {
3295 Mutex::Autolock _l(mStateLock);
3296 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
3297 reply->writeInt32(hw->getPageFlipCount());
3298 return NO_ERROR;
3299 }
3300 case 1014: {
3301 // daltonize
3302 n = data.readInt32();
3303 switch (n % 10) {
3304 case 1:
3305 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3306 break;
3307 case 2:
3308 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
3309 break;
3310 case 3:
3311 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
3312 break;
3313 }
3314 if (n >= 10) {
3315 mDaltonizer.setMode(ColorBlindnessMode::Correction);
3316 } else {
3317 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
3318 }
3319 mDaltonize = n > 0;
3320 invalidateHwcGeometry();
3321 repaintEverything();
3322 return NO_ERROR;
3323 }
3324 case 1015: {
3325 // apply a color matrix
3326 n = data.readInt32();
3327 mHasColorMatrix = n ? 1 : 0;
3328 if (n) {
3329 // color matrix is sent as mat3 matrix followed by vec3
3330 // offset, then packed into a mat4 where the last row is
3331 // the offset and extra values are 0
3332 for (size_t i = 0 ; i < 4; i++) {
3333 for (size_t j = 0; j < 4; j++) {
3334 mColorMatrix[i][j] = data.readFloat();
3335 }
3336 }
3337 } else {
3338 mColorMatrix = mat4();
3339 }
3340 invalidateHwcGeometry();
3341 repaintEverything();
3342 return NO_ERROR;
3343 }
3344 // This is an experimental interface
3345 // Needs to be shifted to proper binder interface when we productize
3346 case 1016: {
3347 n = data.readInt32();
3348 mPrimaryDispSync.setRefreshSkipCount(n);
3349 return NO_ERROR;
3350 }
3351 case 1017: {
3352 n = data.readInt32();
3353 mForceFullDamage = static_cast<bool>(n);
3354 return NO_ERROR;
3355 }
3356 case 1018: { // Modify Choreographer's phase offset
3357 n = data.readInt32();
3358 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3359 return NO_ERROR;
3360 }
3361 case 1019: { // Modify SurfaceFlinger's phase offset
3362 n = data.readInt32();
3363 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3364 return NO_ERROR;
3365 }
3366 case 1020: { // Layer updates interceptor
3367 n = data.readInt32();
3368 if (n) {
3369 ALOGV("Interceptor enabled");
3370 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
3371 }
3372 else{
3373 ALOGV("Interceptor disabled");
3374 mInterceptor.disable();
3375 }
3376 return NO_ERROR;
3377 }
3378 case 1021: { // Disable HWC virtual displays
3379 n = data.readInt32();
3380 mUseHwcVirtualDisplays = !n;
3381 return NO_ERROR;
3382 }
3383 }
3384 }
3385 return err;
3386}
3387
3388void SurfaceFlinger::repaintEverything() {
3389 android_atomic_or(1, &mRepaintEverything);
3390 signalTransaction();
3391}
3392
3393// ---------------------------------------------------------------------------
3394// Capture screen into an IGraphiBufferProducer
3395// ---------------------------------------------------------------------------
3396
3397/* The code below is here to handle b/8734824
3398 *
3399 * We create a IGraphicBufferProducer wrapper that forwards all calls
3400 * from the surfaceflinger thread to the calling binder thread, where they
3401 * are executed. This allows the calling thread in the calling process to be
3402 * reused and not depend on having "enough" binder threads to handle the
3403 * requests.
3404 */
3405class GraphicProducerWrapper : public BBinder, public MessageHandler {
3406 /* Parts of GraphicProducerWrapper are run on two different threads,
3407 * communicating by sending messages via Looper but also by shared member
3408 * data. Coherence maintenance is subtle and in places implicit (ugh).
3409 *
3410 * Don't rely on Looper's sendMessage/handleMessage providing
3411 * release/acquire semantics for any data not actually in the Message.
3412 * Data going from surfaceflinger to binder threads needs to be
3413 * synchronized explicitly.
3414 *
3415 * Barrier open/wait do provide release/acquire semantics. This provides
3416 * implicit synchronization for data coming back from binder to
3417 * surfaceflinger threads.
3418 */
3419
3420 sp<IGraphicBufferProducer> impl;
3421 sp<Looper> looper;
3422 status_t result;
3423 bool exitPending;
3424 bool exitRequested;
3425 Barrier barrier;
3426 uint32_t code;
3427 Parcel const* data;
3428 Parcel* reply;
3429
3430 enum {
3431 MSG_API_CALL,
3432 MSG_EXIT
3433 };
3434
3435 /*
3436 * Called on surfaceflinger thread. This is called by our "fake"
3437 * BpGraphicBufferProducer. We package the data and reply Parcel and
3438 * forward them to the binder thread.
3439 */
3440 virtual status_t transact(uint32_t code,
3441 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
3442 this->code = code;
3443 this->data = &data;
3444 this->reply = reply;
3445 if (exitPending) {
3446 // if we've exited, we run the message synchronously right here.
3447 // note (JH): as far as I can tell from looking at the code, this
3448 // never actually happens. if it does, i'm not sure if it happens
3449 // on the surfaceflinger or binder thread.
3450 handleMessage(Message(MSG_API_CALL));
3451 } else {
3452 barrier.close();
3453 // Prevent stores to this->{code, data, reply} from being
3454 // reordered later than the construction of Message.
3455 atomic_thread_fence(memory_order_release);
3456 looper->sendMessage(this, Message(MSG_API_CALL));
3457 barrier.wait();
3458 }
3459 return result;
3460 }
3461
3462 /*
3463 * here we run on the binder thread. All we've got to do is
3464 * call the real BpGraphicBufferProducer.
3465 */
3466 virtual void handleMessage(const Message& message) {
3467 int what = message.what;
3468 // Prevent reads below from happening before the read from Message
3469 atomic_thread_fence(memory_order_acquire);
3470 if (what == MSG_API_CALL) {
3471 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
3472 barrier.open();
3473 } else if (what == MSG_EXIT) {
3474 exitRequested = true;
3475 }
3476 }
3477
3478public:
3479 explicit GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
3480 : impl(impl),
3481 looper(new Looper(true)),
3482 result(NO_ERROR),
3483 exitPending(false),
3484 exitRequested(false),
3485 code(0),
3486 data(NULL),
3487 reply(NULL)
3488 {}
3489
3490 // Binder thread
3491 status_t waitForResponse() {
3492 do {
3493 looper->pollOnce(-1);
3494 } while (!exitRequested);
3495 return result;
3496 }
3497
3498 // Client thread
3499 void exit(status_t result) {
3500 this->result = result;
3501 exitPending = true;
3502 // Ensure this->result is visible to the binder thread before it
3503 // handles the message.
3504 atomic_thread_fence(memory_order_release);
3505 looper->sendMessage(this, Message(MSG_EXIT));
3506 }
3507};
3508
3509
3510status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
3511 const sp<IGraphicBufferProducer>& producer,
3512 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003513 int32_t minLayerZ, int32_t maxLayerZ,
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003514 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
3515
3516 if (CC_UNLIKELY(display == 0))
3517 return BAD_VALUE;
3518
3519 if (CC_UNLIKELY(producer == 0))
3520 return BAD_VALUE;
3521
3522 // if we have secure windows on this display, never allow the screen capture
3523 // unless the producer interface is local (i.e.: we can take a screenshot for
3524 // ourselves).
3525 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
3526
3527 // Convert to surfaceflinger's internal rotation type.
3528 Transform::orientation_flags rotationFlags;
3529 switch (rotation) {
3530 case ISurfaceComposer::eRotateNone:
3531 rotationFlags = Transform::ROT_0;
3532 break;
3533 case ISurfaceComposer::eRotate90:
3534 rotationFlags = Transform::ROT_90;
3535 break;
3536 case ISurfaceComposer::eRotate180:
3537 rotationFlags = Transform::ROT_180;
3538 break;
3539 case ISurfaceComposer::eRotate270:
3540 rotationFlags = Transform::ROT_270;
3541 break;
3542 default:
3543 rotationFlags = Transform::ROT_0;
3544 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
3545 break;
3546 }
3547
3548 class MessageCaptureScreen : public MessageBase {
3549 SurfaceFlinger* flinger;
3550 sp<IBinder> display;
3551 sp<IGraphicBufferProducer> producer;
3552 Rect sourceCrop;
3553 uint32_t reqWidth, reqHeight;
Robert Carrae060832016-11-28 10:51:00 -08003554 int32_t minLayerZ,maxLayerZ;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003555 bool useIdentityTransform;
3556 Transform::orientation_flags rotation;
3557 status_t result;
3558 bool isLocalScreenshot;
3559 public:
3560 MessageCaptureScreen(SurfaceFlinger* flinger,
3561 const sp<IBinder>& display,
3562 const sp<IGraphicBufferProducer>& producer,
3563 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003564 int32_t minLayerZ, int32_t maxLayerZ,
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003565 bool useIdentityTransform,
3566 Transform::orientation_flags rotation,
3567 bool isLocalScreenshot)
3568 : flinger(flinger), display(display), producer(producer),
3569 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
3570 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
3571 useIdentityTransform(useIdentityTransform),
3572 rotation(rotation), result(PERMISSION_DENIED),
3573 isLocalScreenshot(isLocalScreenshot)
3574 {
3575 }
3576 status_t getResult() const {
3577 return result;
3578 }
3579 virtual bool handler() {
3580 Mutex::Autolock _l(flinger->mStateLock);
3581 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
3582 result = flinger->captureScreenImplLocked(hw, producer,
3583 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
3584 useIdentityTransform, rotation, isLocalScreenshot);
3585 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
3586 return true;
3587 }
3588 };
3589
3590 // this creates a "fake" BBinder which will serve as a "fake" remote
3591 // binder to receive the marshaled calls and forward them to the
3592 // real remote (a BpGraphicBufferProducer)
3593 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
3594
3595 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
3596 // which does the marshaling work forwards to our "fake remote" above.
3597 sp<MessageBase> msg = new MessageCaptureScreen(this,
3598 display, IGraphicBufferProducer::asInterface( wrapper ),
3599 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
3600 useIdentityTransform, rotationFlags, isLocalScreenshot);
3601
3602 status_t res = postMessageAsync(msg);
3603 if (res == NO_ERROR) {
3604 res = wrapper->waitForResponse();
3605 }
3606 return res;
3607}
3608
3609
3610void SurfaceFlinger::renderScreenImplLocked(
3611 const sp<const DisplayDevice>& hw,
3612 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003613 int32_t minLayerZ, int32_t maxLayerZ,
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003614 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
3615{
3616 ATRACE_CALL();
3617 RenderEngine& engine(getRenderEngine());
3618
3619 // get screen geometry
3620 const int32_t hw_w = hw->getWidth();
3621 const int32_t hw_h = hw->getHeight();
3622 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
3623 static_cast<int32_t>(reqHeight) != hw_h;
3624
3625 // if a default or invalid sourceCrop is passed in, set reasonable values
3626 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
3627 !sourceCrop.isValid()) {
3628 sourceCrop.setLeftTop(Point(0, 0));
3629 sourceCrop.setRightBottom(Point(hw_w, hw_h));
3630 }
3631
3632 // ensure that sourceCrop is inside screen
3633 if (sourceCrop.left < 0) {
3634 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
3635 }
3636 if (sourceCrop.right > hw_w) {
3637 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
3638 }
3639 if (sourceCrop.top < 0) {
3640 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
3641 }
3642 if (sourceCrop.bottom > hw_h) {
3643 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
3644 }
3645
3646 // make sure to clear all GL error flags
3647 engine.checkErrors();
3648
3649 // set-up our viewport
3650 engine.setViewportAndProjection(
3651 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
3652 engine.disableTexturing();
3653
3654 // redraw the screen entirely...
3655 engine.clearWithColor(0, 0, 0, 1);
3656
Robert Carr1f0a16a2016-10-24 16:27:39 -07003657 // We loop through the first level of layers without traversing,
3658 // as we need to interpret min/max layer Z in the top level Z space.
3659 for (const auto& layer : mDrawingState.layersSortedByZ) {
3660 if (layer->getLayerStack() != hw->getLayerStack()) {
3661 continue;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003662 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003663 const Layer::State& state(layer->getDrawingState());
3664 if (state.z < minLayerZ || state.z > maxLayerZ) {
3665 continue;
3666 }
3667 layer->traverseInZOrder([&](Layer* layer) {
3668 if (!layer->isVisible()) {
3669 return;
3670 }
3671 if (filtering) layer->setFiltering(true);
3672 layer->draw(hw, useIdentityTransform);
3673 if (filtering) layer->setFiltering(false);
3674 });
3675 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003676
3677 // compositionComplete is needed for older driver
3678 hw->compositionComplete();
3679 hw->setViewportAndProjection();
3680}
3681
3682
3683status_t SurfaceFlinger::captureScreenImplLocked(
3684 const sp<const DisplayDevice>& hw,
3685 const sp<IGraphicBufferProducer>& producer,
3686 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Robert Carrae060832016-11-28 10:51:00 -08003687 int32_t minLayerZ, int32_t maxLayerZ,
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003688 bool useIdentityTransform, Transform::orientation_flags rotation,
3689 bool isLocalScreenshot)
3690{
3691 ATRACE_CALL();
3692
3693 // get screen geometry
3694 uint32_t hw_w = hw->getWidth();
3695 uint32_t hw_h = hw->getHeight();
3696
3697 if (rotation & Transform::ROT_90) {
3698 std::swap(hw_w, hw_h);
3699 }
3700
3701 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
3702 ALOGE("size mismatch (%d, %d) > (%d, %d)",
3703 reqWidth, reqHeight, hw_w, hw_h);
3704 return BAD_VALUE;
3705 }
3706
3707 reqWidth = (!reqWidth) ? hw_w : reqWidth;
3708 reqHeight = (!reqHeight) ? hw_h : reqHeight;
3709
3710 bool secureLayerIsVisible = false;
Robert Carr1f0a16a2016-10-24 16:27:39 -07003711 for (const auto& layer : mDrawingState.layersSortedByZ) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003712 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07003713 if ((layer->getLayerStack() != hw->getLayerStack()) ||
3714 (state.z < minLayerZ || state.z > maxLayerZ)) {
3715 continue;
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003716 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003717 layer->traverseInZOrder([&](Layer *layer) {
3718 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
3719 layer->isSecure());
3720 });
3721 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003722
3723 if (!isLocalScreenshot && secureLayerIsVisible) {
3724 ALOGW("FB is protected: PERMISSION_DENIED");
3725 return PERMISSION_DENIED;
3726 }
3727
3728 // create a surface (because we're a producer, and we need to
3729 // dequeue/queue a buffer)
3730 sp<Surface> sur = new Surface(producer, false);
3731 ANativeWindow* window = sur.get();
3732
3733 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
3734 if (result == NO_ERROR) {
3735 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
3736 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
3737
3738 int err = 0;
3739 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
3740 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
3741 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
3742 err |= native_window_set_usage(window, usage);
3743
3744 if (err == NO_ERROR) {
3745 ANativeWindowBuffer* buffer;
3746 /* TODO: Once we have the sync framework everywhere this can use
3747 * server-side waits on the fence that dequeueBuffer returns.
3748 */
3749 result = native_window_dequeue_buffer_and_wait(window, &buffer);
3750 if (result == NO_ERROR) {
3751 int syncFd = -1;
3752 // create an EGLImage from the buffer so we can later
3753 // turn it into a texture
3754 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
3755 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
3756 if (image != EGL_NO_IMAGE_KHR) {
3757 // this binds the given EGLImage as a framebuffer for the
3758 // duration of this scope.
3759 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
3760 if (imageBond.getStatus() == NO_ERROR) {
3761 // this will in fact render into our dequeued buffer
3762 // via an FBO, which means we didn't have to create
3763 // an EGLSurface and therefore we're not
3764 // dependent on the context's EGLConfig.
3765 renderScreenImplLocked(
3766 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
3767 useIdentityTransform, rotation);
3768
3769 // Attempt to create a sync khr object that can produce a sync point. If that
3770 // isn't available, create a non-dupable sync object in the fallback path and
3771 // wait on it directly.
3772 EGLSyncKHR sync;
3773 if (!DEBUG_SCREENSHOTS) {
3774 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
3775 // native fence fd will not be populated until flush() is done.
3776 getRenderEngine().flush();
3777 } else {
3778 sync = EGL_NO_SYNC_KHR;
3779 }
3780 if (sync != EGL_NO_SYNC_KHR) {
3781 // get the sync fd
3782 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
3783 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
3784 ALOGW("captureScreen: failed to dup sync khr object");
3785 syncFd = -1;
3786 }
3787 eglDestroySyncKHR(mEGLDisplay, sync);
3788 } else {
3789 // fallback path
3790 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
3791 if (sync != EGL_NO_SYNC_KHR) {
3792 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
3793 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
3794 EGLint eglErr = eglGetError();
3795 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
3796 ALOGW("captureScreen: fence wait timed out");
3797 } else {
3798 ALOGW_IF(eglErr != EGL_SUCCESS,
3799 "captureScreen: error waiting on EGL fence: %#x", eglErr);
3800 }
3801 eglDestroySyncKHR(mEGLDisplay, sync);
3802 } else {
3803 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
3804 }
3805 }
3806 if (DEBUG_SCREENSHOTS) {
3807 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
3808 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
3809 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
3810 hw, minLayerZ, maxLayerZ);
3811 delete [] pixels;
3812 }
3813
3814 } else {
3815 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
3816 result = INVALID_OPERATION;
3817 window->cancelBuffer(window, buffer, syncFd);
3818 buffer = NULL;
3819 }
3820 // destroy our image
3821 eglDestroyImageKHR(mEGLDisplay, image);
3822 } else {
3823 result = BAD_VALUE;
3824 }
3825 if (buffer) {
3826 // queueBuffer takes ownership of syncFd
3827 result = window->queueBuffer(window, buffer, syncFd);
3828 }
3829 }
3830 } else {
3831 result = BAD_VALUE;
3832 }
3833 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
3834 }
3835
3836 return result;
3837}
3838
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003839void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
Robert Carrae060832016-11-28 10:51:00 -08003840 const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003841 if (DEBUG_SCREENSHOTS) {
3842 for (size_t y=0 ; y<h ; y++) {
3843 uint32_t const * p = (uint32_t const *)vaddr + y*s;
3844 for (size_t x=0 ; x<w ; x++) {
3845 if (p[x] != 0xFF000000) return;
3846 }
3847 }
3848 ALOGE("*** we just took a black screenshot ***\n"
3849 "requested minz=%d, maxz=%d, layerStack=%d",
3850 minLayerZ, maxLayerZ, hw->getLayerStack());
Robert Carr2047fae2016-11-28 14:09:09 -08003851 size_t i = 0;
Robert Carr1f0a16a2016-10-24 16:27:39 -07003852 for (const auto& layer : mDrawingState.layersSortedByZ) {
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003853 const Layer::State& state(layer->getDrawingState());
Robert Carr1f0a16a2016-10-24 16:27:39 -07003854 if (layer->getLayerStack() == hw->getLayerStack() && state.z >= minLayerZ &&
3855 state.z <= maxLayerZ) {
3856 layer->traverseInZOrder([&](Layer* layer) {
3857 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%x",
3858 layer->isVisible() ? '+' : '-',
3859 i, layer->getName().string(), layer->getLayerStack(), state.z,
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003860 layer->isVisible(), state.flags, state.alpha);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003861 i++;
3862 });
3863 }
3864 }
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003865 }
3866}
3867
3868// ---------------------------------------------------------------------------
3869
Robert Carr2047fae2016-11-28 14:09:09 -08003870void SurfaceFlinger::State::traverseInZOrder(const std::function<void(Layer*)>& consume) const {
3871 layersSortedByZ.traverseInZOrder(consume);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003872}
3873
Robert Carr2047fae2016-11-28 14:09:09 -08003874void SurfaceFlinger::State::traverseInReverseZOrder(const std::function<void(Layer*)>& consume) const {
3875 layersSortedByZ.traverseInReverseZOrder(consume);
Fabien Sanglard9d96de42016-10-11 00:15:18 +00003876}
3877
3878}; // namespace android
3879
3880
3881#if defined(__gl_h_)
3882#error "don't include gl/gl.h in this file"
3883#endif
3884
3885#if defined(__gl2_h_)
3886#error "don't include gl2/gl2.h in this file"
3887#endif