1 /*
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 LOG_NDEBUG 0
18 #define ATRACE_TAG ATRACE_TAG_GRAPHICS
19 
20 #include <sys/types.h>
21 #include <errno.h>
22 #include <dlfcn.h>
23 
24 #include <algorithm>
25 #include <cinttypes>
26 #include <cmath>
27 #include <cstdint>
28 #include <functional>
29 #include <mutex>
30 #include <optional>
31 #include <unordered_map>
32 
33 #include <cutils/properties.h>
34 #include <log/log.h>
35 
36 #include <binder/IPCThreadState.h>
37 #include <binder/IServiceManager.h>
38 #include <binder/PermissionCache.h>
39 
40 #include <compositionengine/CompositionEngine.h>
41 #include <compositionengine/Display.h>
42 #include <compositionengine/DisplayColorProfile.h>
43 #include <compositionengine/Layer.h>
44 #include <compositionengine/OutputLayer.h>
45 #include <compositionengine/RenderSurface.h>
46 #include <compositionengine/impl/LayerCompositionState.h>
47 #include <compositionengine/impl/OutputCompositionState.h>
48 #include <compositionengine/impl/OutputLayerCompositionState.h>
49 #include <dvr/vr_flinger.h>
50 #include <gui/BufferQueue.h>
51 #include <gui/GuiConfig.h>
52 #include <gui/IDisplayEventConnection.h>
53 #include <gui/IProducerListener.h>
54 #include <gui/LayerDebugInfo.h>
55 #include <gui/Surface.h>
56 #include <input/IInputFlinger.h>
57 #include <renderengine/RenderEngine.h>
58 #include <ui/ColorSpace.h>
59 #include <ui/DebugUtils.h>
60 #include <ui/DisplayInfo.h>
61 #include <ui/DisplayStatInfo.h>
62 #include <ui/GraphicBufferAllocator.h>
63 #include <ui/PixelFormat.h>
64 #include <ui/UiConfig.h>
65 #include <utils/StopWatch.h>
66 #include <utils/String16.h>
67 #include <utils/String8.h>
68 #include <utils/Timers.h>
69 #include <utils/Trace.h>
70 #include <utils/misc.h>
71 
72 #include <private/android_filesystem_config.h>
73 #include <private/gui/SyncFeatures.h>
74 
75 #include "BufferLayer.h"
76 #include "BufferQueueLayer.h"
77 #include "BufferStateLayer.h"
78 #include "Client.h"
79 #include "ColorLayer.h"
80 #include "Colorizer.h"
81 #include "ContainerLayer.h"
82 #include "DisplayDevice.h"
83 #include "Layer.h"
84 #include "LayerVector.h"
85 #include "MonitoredProducer.h"
86 #include "NativeWindowSurface.h"
87 #include "RefreshRateOverlay.h"
88 #include "StartPropertySetThread.h"
89 #include "SurfaceFlinger.h"
90 #include "SurfaceInterceptor.h"
91 
92 #include "DisplayHardware/ComposerHal.h"
93 #include "DisplayHardware/DisplayIdentification.h"
94 #include "DisplayHardware/FramebufferSurface.h"
95 #include "DisplayHardware/HWComposer.h"
96 #include "DisplayHardware/VirtualDisplaySurface.h"
97 #include "Effects/Daltonizer.h"
98 #include "RegionSamplingThread.h"
99 #include "Scheduler/DispSync.h"
100 #include "Scheduler/DispSyncSource.h"
101 #include "Scheduler/EventControlThread.h"
102 #include "Scheduler/EventThread.h"
103 #include "Scheduler/InjectVSyncSource.h"
104 #include "Scheduler/MessageQueue.h"
105 #include "Scheduler/PhaseOffsets.h"
106 #include "Scheduler/Scheduler.h"
107 #include "TimeStats/TimeStats.h"
108 
109 #include <cutils/compiler.h>
110 
111 #include "android-base/stringprintf.h"
112 
113 #include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
114 #include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
115 #include <android/hardware/configstore/1.1/types.h>
116 #include <android/hardware/power/1.0/IPower.h>
117 #include <configstore/Utils.h>
118 
119 #include <layerproto/LayerProtoParser.h>
120 #include "SurfaceFlingerProperties.h"
121 
122 namespace android {
123 
124 using namespace android::hardware::configstore;
125 using namespace android::hardware::configstore::V1_0;
126 using namespace android::sysprop;
127 
128 using android::hardware::power::V1_0::PowerHint;
129 using base::StringAppendF;
130 using ui::ColorMode;
131 using ui::Dataspace;
132 using ui::DisplayPrimaries;
133 using ui::Hdr;
134 using ui::RenderIntent;
135 
136 namespace {
137 
138 #pragma clang diagnostic push
139 #pragma clang diagnostic error "-Wswitch-enum"
140 
isWideColorMode(const ColorMode colorMode)141 bool isWideColorMode(const ColorMode colorMode) {
142     switch (colorMode) {
143         case ColorMode::DISPLAY_P3:
144         case ColorMode::ADOBE_RGB:
145         case ColorMode::DCI_P3:
146         case ColorMode::BT2020:
147         case ColorMode::DISPLAY_BT2020:
148         case ColorMode::BT2100_PQ:
149         case ColorMode::BT2100_HLG:
150             return true;
151         case ColorMode::NATIVE:
152         case ColorMode::STANDARD_BT601_625:
153         case ColorMode::STANDARD_BT601_625_UNADJUSTED:
154         case ColorMode::STANDARD_BT601_525:
155         case ColorMode::STANDARD_BT601_525_UNADJUSTED:
156         case ColorMode::STANDARD_BT709:
157         case ColorMode::SRGB:
158             return false;
159     }
160     return false;
161 }
162 
isHdrColorMode(const ColorMode colorMode)163 bool isHdrColorMode(const ColorMode colorMode) {
164     switch (colorMode) {
165         case ColorMode::BT2100_PQ:
166         case ColorMode::BT2100_HLG:
167             return true;
168         case ColorMode::DISPLAY_P3:
169         case ColorMode::ADOBE_RGB:
170         case ColorMode::DCI_P3:
171         case ColorMode::BT2020:
172         case ColorMode::DISPLAY_BT2020:
173         case ColorMode::NATIVE:
174         case ColorMode::STANDARD_BT601_625:
175         case ColorMode::STANDARD_BT601_625_UNADJUSTED:
176         case ColorMode::STANDARD_BT601_525:
177         case ColorMode::STANDARD_BT601_525_UNADJUSTED:
178         case ColorMode::STANDARD_BT709:
179         case ColorMode::SRGB:
180             return false;
181     }
182     return false;
183 }
184 
fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation)185 ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
186     switch (rotation) {
187         case ISurfaceComposer::eRotateNone:
188             return ui::Transform::ROT_0;
189         case ISurfaceComposer::eRotate90:
190             return ui::Transform::ROT_90;
191         case ISurfaceComposer::eRotate180:
192             return ui::Transform::ROT_180;
193         case ISurfaceComposer::eRotate270:
194             return ui::Transform::ROT_270;
195     }
196     ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
197     return ui::Transform::ROT_0;
198 }
199 
200 #pragma clang diagnostic pop
201 
202 class ConditionalLock {
203 public:
ConditionalLock(Mutex & mutex,bool lock)204     ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
205         if (lock) {
206             mMutex.lock();
207         }
208     }
~ConditionalLock()209     ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
210 private:
211     Mutex& mMutex;
212     bool mLocked;
213 };
214 
215 // Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
validateCompositionDataspace(Dataspace dataspace)216 bool validateCompositionDataspace(Dataspace dataspace) {
217     return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
218 }
219 
220 }  // namespace anonymous
221 
222 // ---------------------------------------------------------------------------
223 
224 const String16 sHardwareTest("android.permission.HARDWARE_TEST");
225 const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
226 const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
227 const String16 sDump("android.permission.DUMP");
228 
229 // ---------------------------------------------------------------------------
230 int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
231 bool SurfaceFlinger::useHwcForRgbToYuv;
232 uint64_t SurfaceFlinger::maxVirtualDisplaySize;
233 bool SurfaceFlinger::hasSyncFramework;
234 bool SurfaceFlinger::useVrFlinger;
235 int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
236 bool SurfaceFlinger::hasWideColorDisplay;
237 int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
238 bool SurfaceFlinger::useColorManagement;
239 bool SurfaceFlinger::useContextPriority;
240 Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
241 ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
242 Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
243 ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
244 
getHwcServiceName()245 std::string getHwcServiceName() {
246     char value[PROPERTY_VALUE_MAX] = {};
247     property_get("debug.sf.hwc_service_name", value, "default");
248     ALOGI("Using HWComposer service: '%s'", value);
249     return std::string(value);
250 }
251 
useTrebleTestingOverride()252 bool useTrebleTestingOverride() {
253     char value[PROPERTY_VALUE_MAX] = {};
254     property_get("debug.sf.treble_testing_override", value, "false");
255     ALOGI("Treble testing override: '%s'", value);
256     return std::string(value) == "true";
257 }
258 
decodeDisplayColorSetting(DisplayColorSetting displayColorSetting)259 std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
260     switch(displayColorSetting) {
261         case DisplayColorSetting::MANAGED:
262             return std::string("Managed");
263         case DisplayColorSetting::UNMANAGED:
264             return std::string("Unmanaged");
265         case DisplayColorSetting::ENHANCED:
266             return std::string("Enhanced");
267         default:
268             return std::string("Unknown ") +
269                 std::to_string(static_cast<int>(displayColorSetting));
270     }
271 }
272 
SurfaceFlingerBE()273 SurfaceFlingerBE::SurfaceFlingerBE() : mHwcServiceName(getHwcServiceName()) {}
274 
SurfaceFlinger(Factory & factory,SkipInitializationTag)275 SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
276       : mFactory(factory),
277         mPhaseOffsets(mFactory.createPhaseOffsets()),
278         mInterceptor(mFactory.createSurfaceInterceptor(this)),
279         mTimeStats(mFactory.createTimeStats()),
280         mEventQueue(mFactory.createMessageQueue()),
281         mCompositionEngine(mFactory.createCompositionEngine()) {}
282 
SurfaceFlinger(Factory & factory)283 SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
284     ALOGI("SurfaceFlinger is starting");
285 
286     hasSyncFramework = running_without_sync_framework(true);
287 
288     dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
289 
290     useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
291 
292     maxVirtualDisplaySize = max_virtual_display_dimension(0);
293 
294     // Vr flinger is only enabled on Daydream ready devices.
295     useVrFlinger = use_vr_flinger(false);
296 
297     maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
298 
299     hasWideColorDisplay = has_wide_color_display(false);
300 
301     useColorManagement = use_color_management(false);
302 
303     mDefaultCompositionDataspace =
304             static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
305     mWideColorGamutCompositionDataspace = static_cast<ui::Dataspace>(wcg_composition_dataspace(
306             hasWideColorDisplay ? Dataspace::DISPLAY_P3 : Dataspace::V0_SRGB));
307     defaultCompositionDataspace = mDefaultCompositionDataspace;
308     wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
309     defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
310             default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
311     wideColorGamutCompositionPixelFormat =
312             static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
313 
314     useContextPriority = use_context_priority(true);
315 
316     auto tmpPrimaryDisplayOrientation = primary_display_orientation(
317             SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_0);
318     switch (tmpPrimaryDisplayOrientation) {
319         case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_90:
320             SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
321             break;
322         case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_180:
323             SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
324             break;
325         case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_270:
326             SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
327             break;
328         default:
329             SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
330             break;
331     }
332     ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
333 
334     mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
335 
336     // debugging stuff...
337     char value[PROPERTY_VALUE_MAX];
338 
339     property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
340     mGpuToCpuSupported = !atoi(value);
341 
342     property_get("debug.sf.showupdates", value, "0");
343     mDebugRegion = atoi(value);
344 
345     ALOGI_IF(mDebugRegion, "showupdates enabled");
346 
347     // DDMS debugging deprecated (b/120782499)
348     property_get("debug.sf.ddms", value, "0");
349     int debugDdms = atoi(value);
350     ALOGI_IF(debugDdms, "DDMS debugging not supported");
351 
352     property_get("debug.sf.disable_backpressure", value, "0");
353     mPropagateBackpressure = !atoi(value);
354     ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
355 
356     property_get("debug.sf.enable_gl_backpressure", value, "0");
357     mPropagateBackpressureClientComposition = atoi(value);
358     ALOGI_IF(mPropagateBackpressureClientComposition,
359              "Enabling backpressure propagation for Client Composition");
360 
361     property_get("debug.sf.enable_hwc_vds", value, "0");
362     mUseHwcVirtualDisplays = atoi(value);
363     ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
364 
365     property_get("ro.sf.disable_triple_buffer", value, "0");
366     mLayerTripleBufferingDisabled = atoi(value);
367     ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
368 
369     const size_t defaultListSize = MAX_LAYERS;
370     auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
371     mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
372 
373     mUseSmart90ForVideo = use_smart_90_for_video(false);
374     property_get("debug.sf.use_smart_90_for_video", value, "0");
375 
376     int int_value = atoi(value);
377     if (int_value) {
378         mUseSmart90ForVideo = true;
379     }
380 
381     property_get("debug.sf.luma_sampling", value, "1");
382     mLumaSampling = atoi(value);
383 
384     const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
385     mVsyncModulator.setPhaseOffsets(early, gl, late);
386 
387     // We should be reading 'persist.sys.sf.color_saturation' here
388     // but since /data may be encrypted, we need to wait until after vold
389     // comes online to attempt to read the property. The property is
390     // instead read after the boot animation
391 
392     if (useTrebleTestingOverride()) {
393         // Without the override SurfaceFlinger cannot connect to HIDL
394         // services that are not listed in the manifests.  Considered
395         // deriving the setting from the set service name, but it
396         // would be brittle if the name that's not 'default' is used
397         // for production purposes later on.
398         setenv("TREBLE_TESTING_OVERRIDE", "true", true);
399     }
400 }
401 
onFirstRef()402 void SurfaceFlinger::onFirstRef()
403 {
404     mEventQueue->init(this);
405 }
406 
407 SurfaceFlinger::~SurfaceFlinger() = default;
408 
binderDied(const wp<IBinder> &)409 void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
410 {
411     // the window manager died on us. prepare its eulogy.
412 
413     // restore initial conditions (default device unblank, etc)
414     initializeDisplays();
415 
416     // restart the boot-animation
417     startBootAnim();
418 }
419 
initClient(const sp<Client> & client)420 static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
421     status_t err = client->initCheck();
422     if (err == NO_ERROR) {
423         return client;
424     }
425     return nullptr;
426 }
427 
createConnection()428 sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
429     return initClient(new Client(this));
430 }
431 
createDisplay(const String8 & displayName,bool secure)432 sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
433         bool secure)
434 {
435     class DisplayToken : public BBinder {
436         sp<SurfaceFlinger> flinger;
437         virtual ~DisplayToken() {
438              // no more references, this display must be terminated
439              Mutex::Autolock _l(flinger->mStateLock);
440              flinger->mCurrentState.displays.removeItem(this);
441              flinger->setTransactionFlags(eDisplayTransactionNeeded);
442          }
443      public:
444         explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
445             : flinger(flinger) {
446         }
447     };
448 
449     sp<BBinder> token = new DisplayToken(this);
450 
451     Mutex::Autolock _l(mStateLock);
452     // Display ID is assigned when virtual display is allocated by HWC.
453     DisplayDeviceState state;
454     state.isSecure = secure;
455     state.displayName = displayName;
456     mCurrentState.displays.add(token, state);
457     mInterceptor->saveDisplayCreation(state);
458     return token;
459 }
460 
destroyDisplay(const sp<IBinder> & displayToken)461 void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
462     Mutex::Autolock _l(mStateLock);
463 
464     ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
465     if (index < 0) {
466         ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
467         return;
468     }
469 
470     const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
471     if (!state.isVirtual()) {
472         ALOGE("destroyDisplay called for non-virtual display");
473         return;
474     }
475     mInterceptor->saveDisplayDeletion(state.sequenceId);
476     mCurrentState.displays.removeItemsAt(index);
477     setTransactionFlags(eDisplayTransactionNeeded);
478 }
479 
getPhysicalDisplayIds() const480 std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
481     Mutex::Autolock lock(mStateLock);
482 
483     const auto internalDisplayId = getInternalDisplayIdLocked();
484     if (!internalDisplayId) {
485         return {};
486     }
487 
488     std::vector<PhysicalDisplayId> displayIds;
489     displayIds.reserve(mPhysicalDisplayTokens.size());
490     displayIds.push_back(internalDisplayId->value);
491 
492     for (const auto& [id, token] : mPhysicalDisplayTokens) {
493         if (id != *internalDisplayId) {
494             displayIds.push_back(id.value);
495         }
496     }
497 
498     return displayIds;
499 }
500 
getPhysicalDisplayToken(PhysicalDisplayId displayId) const501 sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
502     Mutex::Autolock lock(mStateLock);
503     return getPhysicalDisplayTokenLocked(DisplayId{displayId});
504 }
505 
getColorManagement(bool * outGetColorManagement) const506 status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
507     if (!outGetColorManagement) {
508         return BAD_VALUE;
509     }
510     *outGetColorManagement = useColorManagement;
511     return NO_ERROR;
512 }
513 
getHwComposer() const514 HWComposer& SurfaceFlinger::getHwComposer() const {
515     return mCompositionEngine->getHwComposer();
516 }
517 
getRenderEngine() const518 renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
519     return mCompositionEngine->getRenderEngine();
520 }
521 
getCompositionEngine() const522 compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
523     return *mCompositionEngine.get();
524 }
525 
bootFinished()526 void SurfaceFlinger::bootFinished()
527 {
528     if (mStartPropertySetThread->join() != NO_ERROR) {
529         ALOGE("Join StartPropertySetThread failed!");
530     }
531     const nsecs_t now = systemTime();
532     const nsecs_t duration = now - mBootTime;
533     ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
534 
535     // wait patiently for the window manager death
536     const String16 name("window");
537     sp<IBinder> window(defaultServiceManager()->getService(name));
538     if (window != 0) {
539         window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
540     }
541     sp<IBinder> input(defaultServiceManager()->getService(
542             String16("inputflinger")));
543     if (input == nullptr) {
544         ALOGE("Failed to link to input service");
545     } else {
546         mInputFlinger = interface_cast<IInputFlinger>(input);
547     }
548 
549     if (mVrFlinger) {
550       mVrFlinger->OnBootFinished();
551     }
552 
553     // stop boot animation
554     // formerly we would just kill the process, but we now ask it to exit so it
555     // can choose where to stop the animation.
556     property_set("service.bootanim.exit", "1");
557 
558     const int LOGTAG_SF_STOP_BOOTANIM = 60110;
559     LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
560                    ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
561 
562     postMessageAsync(new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS {
563         readPersistentProperties();
564         mBootStage = BootStage::FINISHED;
565 
566         // set the refresh rate according to the policy
567         const auto& performanceRefreshRate =
568                 mRefreshRateConfigs.getRefreshRate(RefreshRateType::PERFORMANCE);
569 
570         if (performanceRefreshRate && isDisplayConfigAllowed(performanceRefreshRate->configId)) {
571             setRefreshRateTo(RefreshRateType::PERFORMANCE, Scheduler::ConfigEvent::None);
572         } else {
573             setRefreshRateTo(RefreshRateType::DEFAULT, Scheduler::ConfigEvent::None);
574         }
575     }));
576 }
577 
getNewTexture()578 uint32_t SurfaceFlinger::getNewTexture() {
579     {
580         std::lock_guard lock(mTexturePoolMutex);
581         if (!mTexturePool.empty()) {
582             uint32_t name = mTexturePool.back();
583             mTexturePool.pop_back();
584             ATRACE_INT("TexturePoolSize", mTexturePool.size());
585             return name;
586         }
587 
588         // The pool was too small, so increase it for the future
589         ++mTexturePoolSize;
590     }
591 
592     // The pool was empty, so we need to get a new texture name directly using a
593     // blocking call to the main thread
594     uint32_t name = 0;
595     postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
596     return name;
597 }
598 
deleteTextureAsync(uint32_t texture)599 void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
600     std::lock_guard lock(mTexturePoolMutex);
601     // We don't change the pool size, so the fix-up logic in postComposition will decide whether
602     // to actually delete this or not based on mTexturePoolSize
603     mTexturePool.push_back(texture);
604     ATRACE_INT("TexturePoolSize", mTexturePool.size());
605 }
606 
607 // Do not call property_set on main thread which will be blocked by init
608 // Use StartPropertySetThread instead.
init()609 void SurfaceFlinger::init() {
610     ALOGI(  "SurfaceFlinger's main thread ready to run. "
611             "Initializing graphics H/W...");
612 
613     ALOGI("Phase offset NS: %" PRId64 "", mPhaseOffsets->getCurrentAppOffset());
614 
615     Mutex::Autolock _l(mStateLock);
616     // start the EventThread
617     mScheduler =
618             getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
619                                          mRefreshRateConfigs);
620     auto resyncCallback =
621             mScheduler->makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
622 
623     mAppConnectionHandle =
624             mScheduler->createConnection("app", mPhaseOffsets->getCurrentAppOffset(),
625                                          resyncCallback,
626                                          impl::EventThread::InterceptVSyncsCallback());
627     mSfConnectionHandle = mScheduler->createConnection("sf", mPhaseOffsets->getCurrentSfOffset(),
628                                                        resyncCallback, [this](nsecs_t timestamp) {
629                                                            mInterceptor->saveVSyncEvent(timestamp);
630                                                        });
631 
632     mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
633     mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
634                                            mSfConnectionHandle.get());
635 
636     mRegionSamplingThread =
637             new RegionSamplingThread(*this, *mScheduler,
638                                      RegionSamplingThread::EnvironmentTimingTunables());
639 
640     // Get a RenderEngine for the given display / config (can't fail)
641     int32_t renderEngineFeature = 0;
642     renderEngineFeature |= (useColorManagement ?
643                             renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
644     renderEngineFeature |= (useContextPriority ?
645                             renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
646     renderEngineFeature |=
647             (enable_protected_contents(false) ? renderengine::RenderEngine::ENABLE_PROTECTED_CONTEXT
648                                               : 0);
649 
650     // TODO(b/77156734): We need to stop casting and use HAL types when possible.
651     // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
652     mCompositionEngine->setRenderEngine(
653             renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
654                                                renderEngineFeature, maxFrameBufferAcquiredBuffers));
655 
656     LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
657             "Starting with vr flinger active is not currently supported.");
658     mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
659     mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
660     // Process any initial hotplug and resulting display changes.
661     processDisplayHotplugEventsLocked();
662     const auto display = getDefaultDisplayDeviceLocked();
663     LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
664     LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
665                         "Internal display is disconnected.");
666 
667     if (useVrFlinger) {
668         auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
669             // This callback is called from the vr flinger dispatch thread. We
670             // need to call signalTransaction(), which requires holding
671             // mStateLock when we're not on the main thread. Acquiring
672             // mStateLock from the vr flinger dispatch thread might trigger a
673             // deadlock in surface flinger (see b/66916578), so post a message
674             // to be handled on the main thread instead.
675             postMessageAsync(new LambdaMessage([=] {
676                 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
677                 mVrFlingerRequestsDisplay = requestDisplay;
678                 signalTransaction();
679             }));
680         };
681         mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
682                                             getHwComposer()
683                                                     .fromPhysicalDisplayId(*display->getId())
684                                                     .value_or(0),
685                                             vrFlingerRequestDisplayCallback);
686         if (!mVrFlinger) {
687             ALOGE("Failed to start vrflinger");
688         }
689     }
690 
691     // initialize our drawing state
692     mDrawingState = mCurrentState;
693 
694     // set initial conditions (e.g. unblank default device)
695     initializeDisplays();
696 
697     getRenderEngine().primeCache();
698 
699     // Inform native graphics APIs whether the present timestamp is supported:
700 
701     const bool presentFenceReliable =
702             !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
703     mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
704 
705     if (mStartPropertySetThread->Start() != NO_ERROR) {
706         ALOGE("Run StartPropertySetThread failed!");
707     }
708 
709     mScheduler->setChangeRefreshRateCallback(
710             [this](RefreshRateType type, Scheduler::ConfigEvent event) {
711                 Mutex::Autolock lock(mStateLock);
712                 setRefreshRateTo(type, event);
713             });
714     mScheduler->setGetVsyncPeriodCallback([this] {
715         Mutex::Autolock lock(mStateLock);
716         return getVsyncPeriod();
717     });
718 
719     mRefreshRateConfigs.populate(getHwComposer().getConfigs(*display->getId()));
720     mRefreshRateStats.setConfigMode(getHwComposer().getActiveConfigIndex(*display->getId()));
721 
722     ALOGV("Done initializing");
723 }
724 
readPersistentProperties()725 void SurfaceFlinger::readPersistentProperties() {
726     Mutex::Autolock _l(mStateLock);
727 
728     char value[PROPERTY_VALUE_MAX];
729 
730     property_get("persist.sys.sf.color_saturation", value, "1.0");
731     mGlobalSaturationFactor = atof(value);
732     updateColorMatrixLocked();
733     ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
734 
735     property_get("persist.sys.sf.native_mode", value, "0");
736     mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
737 
738     property_get("persist.sys.sf.color_mode", value, "0");
739     mForceColorMode = static_cast<ColorMode>(atoi(value));
740 }
741 
startBootAnim()742 void SurfaceFlinger::startBootAnim() {
743     // Start boot animation service by setting a property mailbox
744     // if property setting thread is already running, Start() will be just a NOP
745     mStartPropertySetThread->Start();
746     // Wait until property was set
747     if (mStartPropertySetThread->join() != NO_ERROR) {
748         ALOGE("Join StartPropertySetThread failed!");
749     }
750 }
751 
getMaxTextureSize() const752 size_t SurfaceFlinger::getMaxTextureSize() const {
753     return getRenderEngine().getMaxTextureSize();
754 }
755 
getMaxViewportDims() const756 size_t SurfaceFlinger::getMaxViewportDims() const {
757     return getRenderEngine().getMaxViewportDims();
758 }
759 
760 // ----------------------------------------------------------------------------
761 
authenticateSurfaceTexture(const sp<IGraphicBufferProducer> & bufferProducer) const762 bool SurfaceFlinger::authenticateSurfaceTexture(
763         const sp<IGraphicBufferProducer>& bufferProducer) const {
764     Mutex::Autolock _l(mStateLock);
765     return authenticateSurfaceTextureLocked(bufferProducer);
766 }
767 
authenticateSurfaceTextureLocked(const sp<IGraphicBufferProducer> & bufferProducer) const768 bool SurfaceFlinger::authenticateSurfaceTextureLocked(
769         const sp<IGraphicBufferProducer>& bufferProducer) const {
770     sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
771     return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
772 }
773 
getSupportedFrameTimestamps(std::vector<FrameEvent> * outSupported) const774 status_t SurfaceFlinger::getSupportedFrameTimestamps(
775         std::vector<FrameEvent>* outSupported) const {
776     *outSupported = {
777         FrameEvent::REQUESTED_PRESENT,
778         FrameEvent::ACQUIRE,
779         FrameEvent::LATCH,
780         FrameEvent::FIRST_REFRESH_START,
781         FrameEvent::LAST_REFRESH_START,
782         FrameEvent::GPU_COMPOSITION_DONE,
783         FrameEvent::DEQUEUE_READY,
784         FrameEvent::RELEASE,
785     };
786     ConditionalLock _l(mStateLock,
787             std::this_thread::get_id() != mMainThreadId);
788     if (!getHwComposer().hasCapability(
789             HWC2::Capability::PresentFenceIsNotReliable)) {
790         outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
791     }
792     return NO_ERROR;
793 }
794 
getDisplayConfigs(const sp<IBinder> & displayToken,Vector<DisplayInfo> * configs)795 status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
796                                            Vector<DisplayInfo>* configs) {
797     if (!displayToken || !configs) {
798         return BAD_VALUE;
799     }
800 
801     Mutex::Autolock lock(mStateLock);
802 
803     const auto displayId = getPhysicalDisplayIdLocked(displayToken);
804     if (!displayId) {
805         return NAME_NOT_FOUND;
806     }
807 
808     // TODO: Not sure if display density should handled by SF any longer
809     class Density {
810         static float getDensityFromProperty(char const* propName) {
811             char property[PROPERTY_VALUE_MAX];
812             float density = 0.0f;
813             if (property_get(propName, property, nullptr) > 0) {
814                 density = strtof(property, nullptr);
815             }
816             return density;
817         }
818     public:
819         static float getEmuDensity() {
820             return getDensityFromProperty("qemu.sf.lcd_density"); }
821         static float getBuildDensity()  {
822             return getDensityFromProperty("ro.sf.lcd_density"); }
823     };
824 
825     configs->clear();
826 
827     for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
828         DisplayInfo info = DisplayInfo();
829 
830         float xdpi = hwConfig->getDpiX();
831         float ydpi = hwConfig->getDpiY();
832 
833         info.w = hwConfig->getWidth();
834         info.h = hwConfig->getHeight();
835         // Default display viewport to display width and height
836         info.viewportW = info.w;
837         info.viewportH = info.h;
838 
839         if (displayId == getInternalDisplayIdLocked()) {
840             // The density of the device is provided by a build property
841             float density = Density::getBuildDensity() / 160.0f;
842             if (density == 0) {
843                 // the build doesn't provide a density -- this is wrong!
844                 // use xdpi instead
845                 ALOGE("ro.sf.lcd_density must be defined as a build property");
846                 density = xdpi / 160.0f;
847             }
848             if (Density::getEmuDensity()) {
849                 // if "qemu.sf.lcd_density" is specified, it overrides everything
850                 xdpi = ydpi = density = Density::getEmuDensity();
851                 density /= 160.0f;
852             }
853             info.density = density;
854 
855             // TODO: this needs to go away (currently needed only by webkit)
856             const auto display = getDefaultDisplayDeviceLocked();
857             info.orientation = display ? display->getOrientation() : 0;
858 
859             // This is for screenrecord
860             const Rect viewport = display->getViewport();
861             if (viewport.isValid()) {
862                 info.viewportW = uint32_t(viewport.getWidth());
863                 info.viewportH = uint32_t(viewport.getHeight());
864             }
865         } else {
866             // TODO: where should this value come from?
867             static const int TV_DENSITY = 213;
868             info.density = TV_DENSITY / 160.0f;
869             info.orientation = 0;
870         }
871 
872         info.xdpi = xdpi;
873         info.ydpi = ydpi;
874         info.fps = 1e9 / hwConfig->getVsyncPeriod();
875         const auto refreshRateType = mRefreshRateConfigs.getRefreshRateType(hwConfig->getId());
876         const auto offset = mPhaseOffsets->getOffsetsForRefreshRate(refreshRateType);
877         info.appVsyncOffset = offset.late.app;
878 
879         // This is how far in advance a buffer must be queued for
880         // presentation at a given time.  If you want a buffer to appear
881         // on the screen at time N, you must submit the buffer before
882         // (N - presentationDeadline).
883         //
884         // Normally it's one full refresh period (to give SF a chance to
885         // latch the buffer), but this can be reduced by configuring a
886         // DispSync offset.  Any additional delays introduced by the hardware
887         // composer or panel must be accounted for here.
888         //
889         // We add an additional 1ms to allow for processing time and
890         // differences between the ideal and actual refresh rate.
891         info.presentationDeadline = hwConfig->getVsyncPeriod() - offset.late.sf + 1000000;
892 
893         // All non-virtual displays are currently considered secure.
894         info.secure = true;
895 
896         if (displayId == getInternalDisplayIdLocked() &&
897             primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
898             std::swap(info.w, info.h);
899         }
900 
901         configs->push_back(info);
902     }
903 
904     return NO_ERROR;
905 }
906 
getDisplayStats(const sp<IBinder> &,DisplayStatInfo * stats)907 status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
908     if (!stats) {
909         return BAD_VALUE;
910     }
911 
912     mScheduler->getDisplayStatInfo(stats);
913     return NO_ERROR;
914 }
915 
getActiveConfig(const sp<IBinder> & displayToken)916 int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
917     const auto display = getDisplayDevice(displayToken);
918     if (!display) {
919         ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
920         return BAD_VALUE;
921     }
922 
923     return display->getActiveConfig();
924 }
925 
setDesiredActiveConfig(const ActiveConfigInfo & info)926 void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
927     ATRACE_CALL();
928 
929     // Don't check against the current mode yet. Worst case we set the desired
930     // config twice. However event generation config might have changed so we need to update it
931     // accordingly
932     std::lock_guard<std::mutex> lock(mActiveConfigLock);
933     const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
934     mDesiredActiveConfig = info;
935     mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
936 
937     if (!mDesiredActiveConfigChanged) {
938         // This will trigger HWC refresh without resetting the idle timer.
939         repaintEverythingForHWC();
940         // Start receiving vsync samples now, so that we can detect a period
941         // switch.
942         mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
943         mPhaseOffsets->setRefreshRateType(info.type);
944         const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
945         mVsyncModulator.onRefreshRateChangeInitiated();
946         mVsyncModulator.setPhaseOffsets(early, gl, late);
947     }
948     mDesiredActiveConfigChanged = true;
949     ATRACE_INT("DesiredActiveConfigChanged", mDesiredActiveConfigChanged);
950 
951     if (mRefreshRateOverlay) {
952         mRefreshRateOverlay->changeRefreshRate(mDesiredActiveConfig.type);
953     }
954 }
955 
setActiveConfig(const sp<IBinder> & displayToken,int mode)956 status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
957     ATRACE_CALL();
958 
959     std::vector<int32_t> allowedConfig;
960     allowedConfig.push_back(mode);
961 
962     return setAllowedDisplayConfigs(displayToken, allowedConfig);
963 }
964 
setActiveConfigInternal()965 void SurfaceFlinger::setActiveConfigInternal() {
966     ATRACE_CALL();
967 
968     const auto display = getDefaultDisplayDeviceLocked();
969     if (!display) {
970         return;
971     }
972 
973     std::lock_guard<std::mutex> lock(mActiveConfigLock);
974     mRefreshRateStats.setConfigMode(mUpcomingActiveConfig.configId);
975 
976     display->setActiveConfig(mUpcomingActiveConfig.configId);
977 
978     mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
979     mPhaseOffsets->setRefreshRateType(mUpcomingActiveConfig.type);
980     const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
981     mVsyncModulator.setPhaseOffsets(early, gl, late);
982     ATRACE_INT("ActiveConfigMode", mUpcomingActiveConfig.configId);
983 
984     if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
985         mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
986                                     mUpcomingActiveConfig.configId);
987     }
988 }
989 
performSetActiveConfig()990 bool SurfaceFlinger::performSetActiveConfig() {
991     ATRACE_CALL();
992     if (mCheckPendingFence) {
993         if (previousFrameMissed()) {
994             // fence has not signaled yet. wait for the next invalidate
995             mEventQueue->invalidate();
996             return true;
997         }
998 
999         // We received the present fence from the HWC, so we assume it successfully updated
1000         // the config, hence we update SF.
1001         mCheckPendingFence = false;
1002         setActiveConfigInternal();
1003     }
1004 
1005     // Store the local variable to release the lock.
1006     ActiveConfigInfo desiredActiveConfig;
1007     {
1008         std::lock_guard<std::mutex> lock(mActiveConfigLock);
1009         if (!mDesiredActiveConfigChanged) {
1010             return false;
1011         }
1012         desiredActiveConfig = mDesiredActiveConfig;
1013     }
1014 
1015     const auto display = getDefaultDisplayDeviceLocked();
1016     if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
1017         // display is not valid or we are already in the requested mode
1018         // on both cases there is nothing left to do
1019         std::lock_guard<std::mutex> lock(mActiveConfigLock);
1020         mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
1021         mDesiredActiveConfigChanged = false;
1022         ATRACE_INT("DesiredActiveConfigChanged", mDesiredActiveConfigChanged);
1023         return false;
1024     }
1025 
1026     // Desired active config was set, it is different than the config currently in use, however
1027     // allowed configs might have change by the time we process the refresh.
1028     // Make sure the desired config is still allowed
1029     if (!isDisplayConfigAllowed(desiredActiveConfig.configId)) {
1030         std::lock_guard<std::mutex> lock(mActiveConfigLock);
1031         mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
1032         mDesiredActiveConfig.configId = display->getActiveConfig();
1033         mDesiredActiveConfigChanged = false;
1034         ATRACE_INT("DesiredActiveConfigChanged", mDesiredActiveConfigChanged);
1035         return false;
1036     }
1037     mUpcomingActiveConfig = desiredActiveConfig;
1038     const auto displayId = display->getId();
1039     LOG_ALWAYS_FATAL_IF(!displayId);
1040 
1041     ATRACE_INT("ActiveConfigModeHWC", mUpcomingActiveConfig.configId);
1042     getHwComposer().setActiveConfig(*displayId, mUpcomingActiveConfig.configId);
1043 
1044     // we need to submit an empty frame to HWC to start the process
1045     mCheckPendingFence = true;
1046     mEventQueue->invalidate();
1047     return false;
1048 }
1049 
getDisplayColorModes(const sp<IBinder> & displayToken,Vector<ColorMode> * outColorModes)1050 status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1051                                               Vector<ColorMode>* outColorModes) {
1052     if (!displayToken || !outColorModes) {
1053         return BAD_VALUE;
1054     }
1055 
1056     std::vector<ColorMode> modes;
1057     bool isInternalDisplay = false;
1058     {
1059         ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1060 
1061         const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1062         if (!displayId) {
1063             return NAME_NOT_FOUND;
1064         }
1065 
1066         modes = getHwComposer().getColorModes(*displayId);
1067         isInternalDisplay = displayId == getInternalDisplayIdLocked();
1068     }
1069     outColorModes->clear();
1070 
1071     // If it's built-in display and the configuration claims it's not wide color capable,
1072     // filter out all wide color modes. The typical reason why this happens is that the
1073     // hardware is not good enough to support GPU composition of wide color, and thus the
1074     // OEMs choose to disable this capability.
1075     if (isInternalDisplay && !hasWideColorDisplay) {
1076         std::remove_copy_if(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes),
1077                             isWideColorMode);
1078     } else {
1079         std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1080     }
1081 
1082     return NO_ERROR;
1083 }
1084 
getDisplayNativePrimaries(const sp<IBinder> & displayToken,ui::DisplayPrimaries & primaries)1085 status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1086                                                    ui::DisplayPrimaries &primaries) {
1087     if (!displayToken) {
1088         return BAD_VALUE;
1089     }
1090 
1091     // Currently we only support this API for a single internal display.
1092     if (getInternalDisplayToken() != displayToken) {
1093         return BAD_VALUE;
1094     }
1095 
1096     memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1097     return NO_ERROR;
1098 }
1099 
getActiveColorMode(const sp<IBinder> & displayToken)1100 ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1101     if (const auto display = getDisplayDevice(displayToken)) {
1102         return display->getCompositionDisplay()->getState().colorMode;
1103     }
1104     return static_cast<ColorMode>(BAD_VALUE);
1105 }
1106 
setActiveColorMode(const sp<IBinder> & displayToken,ColorMode mode)1107 status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
1108     postMessageSync(new LambdaMessage([&] {
1109         Vector<ColorMode> modes;
1110         getDisplayColorModes(displayToken, &modes);
1111         bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1112         if (mode < ColorMode::NATIVE || !exists) {
1113             ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1114                   decodeColorMode(mode).c_str(), mode, displayToken.get());
1115             return;
1116         }
1117         const auto display = getDisplayDevice(displayToken);
1118         if (!display) {
1119             ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1120                   decodeColorMode(mode).c_str(), mode, displayToken.get());
1121         } else if (display->isVirtual()) {
1122             ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1123                   decodeColorMode(mode).c_str(), mode);
1124         } else {
1125             display->getCompositionDisplay()->setColorMode(mode, Dataspace::UNKNOWN,
1126                                                            RenderIntent::COLORIMETRIC);
1127         }
1128     }));
1129 
1130     return NO_ERROR;
1131 }
1132 
clearAnimationFrameStats()1133 status_t SurfaceFlinger::clearAnimationFrameStats() {
1134     Mutex::Autolock _l(mStateLock);
1135     mAnimFrameTracker.clearStats();
1136     return NO_ERROR;
1137 }
1138 
getAnimationFrameStats(FrameStats * outStats) const1139 status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1140     Mutex::Autolock _l(mStateLock);
1141     mAnimFrameTracker.getStats(outStats);
1142     return NO_ERROR;
1143 }
1144 
getHdrCapabilities(const sp<IBinder> & displayToken,HdrCapabilities * outCapabilities) const1145 status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1146                                             HdrCapabilities* outCapabilities) const {
1147     Mutex::Autolock _l(mStateLock);
1148 
1149     const auto display = getDisplayDeviceLocked(displayToken);
1150     if (!display) {
1151         ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
1152         return BAD_VALUE;
1153     }
1154 
1155     // At this point the DisplayDeivce should already be set up,
1156     // meaning the luminance information is already queried from
1157     // hardware composer and stored properly.
1158     const HdrCapabilities& capabilities = display->getHdrCapabilities();
1159     *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1160                                        capabilities.getDesiredMaxLuminance(),
1161                                        capabilities.getDesiredMaxAverageLuminance(),
1162                                        capabilities.getDesiredMinLuminance());
1163 
1164     return NO_ERROR;
1165 }
1166 
getDisplayedContentSamplingAttributes(const sp<IBinder> & displayToken,ui::PixelFormat * outFormat,ui::Dataspace * outDataspace,uint8_t * outComponentMask) const1167 status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1168                                                                ui::PixelFormat* outFormat,
1169                                                                ui::Dataspace* outDataspace,
1170                                                                uint8_t* outComponentMask) const {
1171     if (!outFormat || !outDataspace || !outComponentMask) {
1172         return BAD_VALUE;
1173     }
1174     const auto display = getDisplayDevice(displayToken);
1175     if (!display || !display->getId()) {
1176         ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1177         return BAD_VALUE;
1178     }
1179     return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1180                                                                  outDataspace, outComponentMask);
1181 }
1182 
setDisplayContentSamplingEnabled(const sp<IBinder> & displayToken,bool enable,uint8_t componentMask,uint64_t maxFrames) const1183 status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1184                                                           bool enable, uint8_t componentMask,
1185                                                           uint64_t maxFrames) const {
1186     const auto display = getDisplayDevice(displayToken);
1187     if (!display || !display->getId()) {
1188         ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1189         return BAD_VALUE;
1190     }
1191 
1192     return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1193                                                             componentMask, maxFrames);
1194 }
1195 
getDisplayedContentSample(const sp<IBinder> & displayToken,uint64_t maxFrames,uint64_t timestamp,DisplayedFrameStats * outStats) const1196 status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1197                                                    uint64_t maxFrames, uint64_t timestamp,
1198                                                    DisplayedFrameStats* outStats) const {
1199     const auto display = getDisplayDevice(displayToken);
1200     if (!display || !display->getId()) {
1201         ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1202         return BAD_VALUE;
1203     }
1204 
1205     return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1206                                                      outStats);
1207 }
1208 
getProtectedContentSupport(bool * outSupported) const1209 status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1210     if (!outSupported) {
1211         return BAD_VALUE;
1212     }
1213     *outSupported = getRenderEngine().supportsProtectedContent();
1214     return NO_ERROR;
1215 }
1216 
isWideColorDisplay(const sp<IBinder> & displayToken,bool * outIsWideColorDisplay) const1217 status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1218                                             bool* outIsWideColorDisplay) const {
1219     if (!displayToken || !outIsWideColorDisplay) {
1220         return BAD_VALUE;
1221     }
1222     Mutex::Autolock _l(mStateLock);
1223     const auto display = getDisplayDeviceLocked(displayToken);
1224     if (!display) {
1225         return BAD_VALUE;
1226     }
1227 
1228     // Use hasWideColorDisplay to override built-in display.
1229     const auto displayId = display->getId();
1230     if (displayId && displayId == getInternalDisplayIdLocked()) {
1231         *outIsWideColorDisplay = hasWideColorDisplay;
1232         return NO_ERROR;
1233     }
1234     *outIsWideColorDisplay = display->hasWideColorGamut();
1235     return NO_ERROR;
1236 }
1237 
enableVSyncInjections(bool enable)1238 status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
1239     postMessageSync(new LambdaMessage([&] {
1240         Mutex::Autolock _l(mStateLock);
1241 
1242         if (mInjectVSyncs == enable) {
1243             return;
1244         }
1245 
1246         auto resyncCallback =
1247                 mScheduler->makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
1248 
1249         // TODO(b/128863962): Part of the Injector should be refactored, so that it
1250         // can be passed to Scheduler.
1251         if (enable) {
1252             ALOGV("VSync Injections enabled");
1253             if (mVSyncInjector.get() == nullptr) {
1254                 mVSyncInjector = std::make_unique<InjectVSyncSource>();
1255                 mInjectorEventThread = std::make_unique<
1256                         impl::EventThread>(mVSyncInjector.get(),
1257                                            impl::EventThread::InterceptVSyncsCallback(),
1258                                            "injEventThread");
1259             }
1260             mEventQueue->setEventThread(mInjectorEventThread.get(), std::move(resyncCallback));
1261         } else {
1262             ALOGV("VSync Injections disabled");
1263             mEventQueue->setEventThread(mScheduler->getEventThread(mSfConnectionHandle),
1264                                         std::move(resyncCallback));
1265         }
1266 
1267         mInjectVSyncs = enable;
1268     }));
1269 
1270     return NO_ERROR;
1271 }
1272 
injectVSync(nsecs_t when)1273 status_t SurfaceFlinger::injectVSync(nsecs_t when) {
1274     Mutex::Autolock _l(mStateLock);
1275 
1276     if (!mInjectVSyncs) {
1277         ALOGE("VSync Injections not enabled");
1278         return BAD_VALUE;
1279     }
1280     if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1281         ALOGV("Injecting VSync inside SurfaceFlinger");
1282         mVSyncInjector->onInjectSyncEvent(when);
1283     }
1284     return NO_ERROR;
1285 }
1286 
getLayerDebugInfo(std::vector<LayerDebugInfo> * outLayers) const1287 status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1288         NO_THREAD_SAFETY_ANALYSIS {
1289     // Try to acquire a lock for 1s, fail gracefully
1290     const status_t err = mStateLock.timedLock(s2ns(1));
1291     const bool locked = (err == NO_ERROR);
1292     if (!locked) {
1293         ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1294         return TIMED_OUT;
1295     }
1296 
1297     outLayers->clear();
1298     mCurrentState.traverseInZOrder([&](Layer* layer) {
1299         outLayers->push_back(layer->getLayerDebugInfo());
1300     });
1301 
1302     mStateLock.unlock();
1303     return NO_ERROR;
1304 }
1305 
getCompositionPreference(Dataspace * outDataspace,ui::PixelFormat * outPixelFormat,Dataspace * outWideColorGamutDataspace,ui::PixelFormat * outWideColorGamutPixelFormat) const1306 status_t SurfaceFlinger::getCompositionPreference(
1307         Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1308         Dataspace* outWideColorGamutDataspace,
1309         ui::PixelFormat* outWideColorGamutPixelFormat) const {
1310     *outDataspace = mDefaultCompositionDataspace;
1311     *outPixelFormat = defaultCompositionPixelFormat;
1312     *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
1313     *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
1314     return NO_ERROR;
1315 }
1316 
addRegionSamplingListener(const Rect & samplingArea,const sp<IBinder> & stopLayerHandle,const sp<IRegionSamplingListener> & listener)1317 status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1318                                                    const sp<IBinder>& stopLayerHandle,
1319                                                    const sp<IRegionSamplingListener>& listener) {
1320     if (!listener || samplingArea == Rect::INVALID_RECT) {
1321         return BAD_VALUE;
1322     }
1323     mRegionSamplingThread->addListener(samplingArea, stopLayerHandle, listener);
1324     return NO_ERROR;
1325 }
1326 
removeRegionSamplingListener(const sp<IRegionSamplingListener> & listener)1327 status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
1328     if (!listener) {
1329         return BAD_VALUE;
1330     }
1331     mRegionSamplingThread->removeListener(listener);
1332     return NO_ERROR;
1333 }
1334 
getDisplayBrightnessSupport(const sp<IBinder> & displayToken,bool * outSupport) const1335 status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1336                                                      bool* outSupport) const {
1337     if (!displayToken || !outSupport) {
1338         return BAD_VALUE;
1339     }
1340     const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1341     if (!displayId) {
1342         return NAME_NOT_FOUND;
1343     }
1344     *outSupport =
1345             getHwComposer().hasDisplayCapability(displayId, HWC2::DisplayCapability::Brightness);
1346     return NO_ERROR;
1347 }
1348 
setDisplayBrightness(const sp<IBinder> & displayToken,float brightness) const1349 status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1350                                               float brightness) const {
1351     if (!displayToken) {
1352         return BAD_VALUE;
1353     }
1354     const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1355     if (!displayId) {
1356         return NAME_NOT_FOUND;
1357     }
1358     return getHwComposer().setDisplayBrightness(*displayId, brightness);
1359 }
1360 
notifyPowerHint(int32_t hintId)1361 status_t SurfaceFlinger::notifyPowerHint(int32_t hintId) {
1362     PowerHint powerHint = static_cast<PowerHint>(hintId);
1363 
1364     if (powerHint == PowerHint::INTERACTION) {
1365         mScheduler->notifyTouchEvent();
1366     }
1367 
1368     return NO_ERROR;
1369 }
1370 
1371 // ----------------------------------------------------------------------------
1372 
createDisplayEventConnection(ISurfaceComposer::VsyncSource vsyncSource)1373 sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1374         ISurfaceComposer::VsyncSource vsyncSource) {
1375     auto resyncCallback = mScheduler->makeResyncCallback([this] {
1376         Mutex::Autolock lock(mStateLock);
1377         return getVsyncPeriod();
1378     });
1379 
1380     const auto& handle =
1381             vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
1382 
1383     return mScheduler->createDisplayEventConnection(handle, std::move(resyncCallback));
1384 }
1385 
1386 // ----------------------------------------------------------------------------
1387 
waitForEvent()1388 void SurfaceFlinger::waitForEvent() {
1389     mEventQueue->waitMessage();
1390 }
1391 
signalTransaction()1392 void SurfaceFlinger::signalTransaction() {
1393     mScheduler->resetIdleTimer();
1394     mEventQueue->invalidate();
1395 }
1396 
signalLayerUpdate()1397 void SurfaceFlinger::signalLayerUpdate() {
1398     mScheduler->resetIdleTimer();
1399     mEventQueue->invalidate();
1400 }
1401 
signalRefresh()1402 void SurfaceFlinger::signalRefresh() {
1403     mRefreshPending = true;
1404     mEventQueue->refresh();
1405 }
1406 
postMessageAsync(const sp<MessageBase> & msg,nsecs_t reltime,uint32_t)1407 status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
1408         nsecs_t reltime, uint32_t /* flags */) {
1409     return mEventQueue->postMessage(msg, reltime);
1410 }
1411 
postMessageSync(const sp<MessageBase> & msg,nsecs_t reltime,uint32_t)1412 status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
1413         nsecs_t reltime, uint32_t /* flags */) {
1414     status_t res = mEventQueue->postMessage(msg, reltime);
1415     if (res == NO_ERROR) {
1416         msg->wait();
1417     }
1418     return res;
1419 }
1420 
run()1421 void SurfaceFlinger::run() {
1422     do {
1423         waitForEvent();
1424     } while (true);
1425 }
1426 
getVsyncPeriod() const1427 nsecs_t SurfaceFlinger::getVsyncPeriod() const {
1428     const auto displayId = getInternalDisplayIdLocked();
1429     if (!displayId || !getHwComposer().isConnected(*displayId)) {
1430         return 0;
1431     }
1432 
1433     const auto config = getHwComposer().getActiveConfig(*displayId);
1434     return config ? config->getVsyncPeriod() : 0;
1435 }
1436 
onVsyncReceived(int32_t sequenceId,hwc2_display_t hwcDisplayId,int64_t timestamp)1437 void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1438                                      int64_t timestamp) {
1439     ATRACE_NAME("SF onVsync");
1440 
1441     Mutex::Autolock lock(mStateLock);
1442     // Ignore any vsyncs from a previous hardware composer.
1443     if (sequenceId != getBE().mComposerSequenceId) {
1444         return;
1445     }
1446 
1447     if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
1448         return;
1449     }
1450 
1451     if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
1452         // For now, we don't do anything with external display vsyncs.
1453         return;
1454     }
1455 
1456     bool periodChanged = false;
1457     mScheduler->addResyncSample(timestamp, &periodChanged);
1458     if (periodChanged) {
1459         mVsyncModulator.onRefreshRateChangeDetected();
1460     }
1461 }
1462 
getCompositorTiming(CompositorTiming * compositorTiming)1463 void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
1464     std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1465     *compositorTiming = getBE().mCompositorTiming;
1466 }
1467 
isDisplayConfigAllowed(int32_t configId)1468 bool SurfaceFlinger::isDisplayConfigAllowed(int32_t configId) {
1469     return mAllowedDisplayConfigs.empty() || mAllowedDisplayConfigs.count(configId);
1470 }
1471 
setRefreshRateTo(RefreshRateType refreshRate,Scheduler::ConfigEvent event)1472 void SurfaceFlinger::setRefreshRateTo(RefreshRateType refreshRate, Scheduler::ConfigEvent event) {
1473     const auto display = getDefaultDisplayDeviceLocked();
1474     if (!display || mBootStage != BootStage::FINISHED) {
1475         return;
1476     }
1477     ATRACE_CALL();
1478 
1479     // Don't do any updating if the current fps is the same as the new one.
1480     const auto& refreshRateConfig = mRefreshRateConfigs.getRefreshRate(refreshRate);
1481     if (!refreshRateConfig) {
1482         ALOGV("Skipping refresh rate change request for unsupported rate.");
1483         return;
1484     }
1485 
1486     const int desiredConfigId = refreshRateConfig->configId;
1487 
1488     if (!isDisplayConfigAllowed(desiredConfigId)) {
1489         ALOGV("Skipping config %d as it is not part of allowed configs", desiredConfigId);
1490         return;
1491     }
1492 
1493     setDesiredActiveConfig({refreshRate, desiredConfigId, event});
1494 }
1495 
onHotplugReceived(int32_t sequenceId,hwc2_display_t hwcDisplayId,HWC2::Connection connection)1496 void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1497                                        HWC2::Connection connection) {
1498     ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
1499           connection == HWC2::Connection::Connected ? "connected" : "disconnected");
1500 
1501     // Ignore events that do not have the right sequenceId.
1502     if (sequenceId != getBE().mComposerSequenceId) {
1503         return;
1504     }
1505 
1506     // Only lock if we're not on the main thread. This function is normally
1507     // called on a hwbinder thread, but for the primary display it's called on
1508     // the main thread with the state lock already held, so don't attempt to
1509     // acquire it here.
1510     ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1511 
1512     mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
1513 
1514     if (std::this_thread::get_id() == mMainThreadId) {
1515         // Process all pending hot plug events immediately if we are on the main thread.
1516         processDisplayHotplugEventsLocked();
1517     }
1518 
1519     setTransactionFlags(eDisplayTransactionNeeded);
1520 }
1521 
onRefreshReceived(int sequenceId,hwc2_display_t)1522 void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
1523     Mutex::Autolock lock(mStateLock);
1524     if (sequenceId != getBE().mComposerSequenceId) {
1525         return;
1526     }
1527     repaintEverythingForHWC();
1528 }
1529 
setPrimaryVsyncEnabled(bool enabled)1530 void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
1531     ATRACE_CALL();
1532     Mutex::Autolock lock(mStateLock);
1533     if (const auto displayId = getInternalDisplayIdLocked()) {
1534         getHwComposer().setVsyncEnabled(*displayId,
1535                                         enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1536     }
1537 }
1538 
1539 // Note: it is assumed the caller holds |mStateLock| when this is called
resetDisplayState()1540 void SurfaceFlinger::resetDisplayState() {
1541     mScheduler->disableHardwareVsync(true);
1542     // Clear the drawing state so that the logic inside of
1543     // handleTransactionLocked will fire. It will determine the delta between
1544     // mCurrentState and mDrawingState and re-apply all changes when we make the
1545     // transition.
1546     mDrawingState.displays.clear();
1547     mDisplays.clear();
1548 }
1549 
updateVrFlinger()1550 void SurfaceFlinger::updateVrFlinger() {
1551     ATRACE_CALL();
1552     if (!mVrFlinger)
1553         return;
1554     bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
1555     if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
1556         return;
1557     }
1558 
1559     if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
1560         ALOGE("Vr flinger is only supported for remote hardware composer"
1561               " service connections. Ignoring request to transition to vr"
1562               " flinger.");
1563         mVrFlingerRequestsDisplay = false;
1564         return;
1565     }
1566 
1567     Mutex::Autolock _l(mStateLock);
1568 
1569     sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
1570     LOG_ALWAYS_FATAL_IF(!display);
1571 
1572     const int currentDisplayPowerMode = display->getPowerMode();
1573 
1574     // Clear out all the output layers from the composition engine for all
1575     // displays before destroying the hardware composer interface. This ensures
1576     // any HWC layers are destroyed through that interface before it becomes
1577     // invalid.
1578     for (const auto& [token, displayDevice] : mDisplays) {
1579         displayDevice->getCompositionDisplay()->setOutputLayersOrderedByZ(
1580                 compositionengine::Output::OutputLayers());
1581     }
1582 
1583     // This DisplayDevice will no longer be relevant once resetDisplayState() is
1584     // called below. Clear the reference now so we don't accidentally use it
1585     // later.
1586     display.clear();
1587 
1588     if (!vrFlingerRequestsDisplay) {
1589         mVrFlinger->SeizeDisplayOwnership();
1590     }
1591 
1592     resetDisplayState();
1593     // Delete the current instance before creating the new one
1594     mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1595     mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1596             vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1597     getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
1598 
1599     LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
1600                         "Switched to non-remote hardware composer");
1601 
1602     if (vrFlingerRequestsDisplay) {
1603         mVrFlinger->GrantDisplayOwnership();
1604     }
1605 
1606     mVisibleRegionsDirty = true;
1607     invalidateHwcGeometry();
1608 
1609     // Re-enable default display.
1610     display = getDefaultDisplayDeviceLocked();
1611     LOG_ALWAYS_FATAL_IF(!display);
1612     setPowerModeInternal(display, currentDisplayPowerMode);
1613 
1614     // Reset the timing values to account for the period of the swapped in HWC
1615     const nsecs_t vsyncPeriod = getVsyncPeriod();
1616     mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
1617 
1618     // The present fences returned from vr_hwc are not an accurate
1619     // representation of vsync times.
1620     mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
1621 
1622     // Use phase of 0 since phase is not known.
1623     // Use latency of 0, which will snap to the ideal latency.
1624     DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
1625     setCompositorTimingSnapped(stats, 0);
1626 
1627     mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
1628 
1629     mRepaintEverything = true;
1630     setTransactionFlags(eDisplayTransactionNeeded);
1631 }
1632 
previousFrameMissed()1633 bool SurfaceFlinger::previousFrameMissed() NO_THREAD_SAFETY_ANALYSIS {
1634     // We are storing the last 2 present fences. If sf's phase offset is to be
1635     // woken up before the actual vsync but targeting the next vsync, we need to check
1636     // fence N-2
1637     const sp<Fence>& fence =
1638             mVsyncModulator.getOffsets().sf < mPhaseOffsets->getOffsetThresholdForNextVsync()
1639             ? mPreviousPresentFences[0]
1640             : mPreviousPresentFences[1];
1641 
1642     return fence != Fence::NO_FENCE && (fence->getStatus() == Fence::Status::Unsignaled);
1643 }
1644 
onMessageReceived(int32_t what)1645 void SurfaceFlinger::onMessageReceived(int32_t what) NO_THREAD_SAFETY_ANALYSIS {
1646     ATRACE_CALL();
1647     switch (what) {
1648         case MessageQueue::INVALIDATE: {
1649             bool frameMissed = previousFrameMissed();
1650             bool hwcFrameMissed = mHadDeviceComposition && frameMissed;
1651             bool gpuFrameMissed = mHadClientComposition && frameMissed;
1652             ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
1653             ATRACE_INT("HwcFrameMissed", static_cast<int>(hwcFrameMissed));
1654             ATRACE_INT("GpuFrameMissed", static_cast<int>(gpuFrameMissed));
1655             if (frameMissed) {
1656                 mFrameMissedCount++;
1657                 mTimeStats->incrementMissedFrames();
1658             }
1659 
1660             if (hwcFrameMissed) {
1661                 mHwcFrameMissedCount++;
1662             }
1663 
1664             if (gpuFrameMissed) {
1665                 mGpuFrameMissedCount++;
1666             }
1667 
1668             if (mUseSmart90ForVideo) {
1669                 // This call is made each time SF wakes up and creates a new frame. It is part
1670                 // of video detection feature.
1671                 mScheduler->updateFpsBasedOnContent();
1672             }
1673 
1674             if (performSetActiveConfig()) {
1675                 break;
1676             }
1677 
1678             if (frameMissed && mPropagateBackpressure) {
1679                 if ((hwcFrameMissed && !gpuFrameMissed) ||
1680                     mPropagateBackpressureClientComposition) {
1681                     signalLayerUpdate();
1682                     break;
1683                 }
1684             }
1685 
1686             // Now that we're going to make it to the handleMessageTransaction()
1687             // call below it's safe to call updateVrFlinger(), which will
1688             // potentially trigger a display handoff.
1689             updateVrFlinger();
1690 
1691             bool refreshNeeded = handleMessageTransaction();
1692             refreshNeeded |= handleMessageInvalidate();
1693 
1694             updateCursorAsync();
1695             updateInputFlinger();
1696 
1697             refreshNeeded |= mRepaintEverything;
1698             if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
1699                 // Signal a refresh if a transaction modified the window state,
1700                 // a new buffer was latched, or if HWC has requested a full
1701                 // repaint
1702                 signalRefresh();
1703             }
1704             break;
1705         }
1706         case MessageQueue::REFRESH: {
1707             handleMessageRefresh();
1708             break;
1709         }
1710     }
1711 }
1712 
handleMessageTransaction()1713 bool SurfaceFlinger::handleMessageTransaction() {
1714     ATRACE_CALL();
1715     uint32_t transactionFlags = peekTransactionFlags();
1716 
1717     bool flushedATransaction = flushTransactionQueues();
1718 
1719     bool runHandleTransaction = transactionFlags &&
1720             ((transactionFlags != eTransactionFlushNeeded) || flushedATransaction);
1721 
1722     if (runHandleTransaction) {
1723         handleTransaction(eTransactionMask);
1724     } else {
1725         getTransactionFlags(eTransactionFlushNeeded);
1726     }
1727 
1728     if (transactionFlushNeeded()) {
1729         setTransactionFlags(eTransactionFlushNeeded);
1730     }
1731 
1732     return runHandleTransaction;
1733 }
1734 
handleMessageRefresh()1735 void SurfaceFlinger::handleMessageRefresh() {
1736     ATRACE_CALL();
1737 
1738     mRefreshPending = false;
1739 
1740     const bool repaintEverything = mRepaintEverything.exchange(false);
1741     preComposition();
1742     rebuildLayerStacks();
1743     calculateWorkingSet();
1744     for (const auto& [token, display] : mDisplays) {
1745         beginFrame(display);
1746         prepareFrame(display);
1747         doDebugFlashRegions(display, repaintEverything);
1748         doComposition(display, repaintEverything);
1749     }
1750 
1751     logLayerStats();
1752 
1753     postFrame();
1754     postComposition();
1755 
1756     mHadClientComposition = false;
1757     mHadDeviceComposition = false;
1758     for (const auto& [token, displayDevice] : mDisplays) {
1759         auto display = displayDevice->getCompositionDisplay();
1760         const auto displayId = display->getId();
1761         mHadClientComposition =
1762                 mHadClientComposition || getHwComposer().hasClientComposition(displayId);
1763         mHadDeviceComposition =
1764                 mHadDeviceComposition || getHwComposer().hasDeviceComposition(displayId);
1765     }
1766 
1767     mVsyncModulator.onRefreshed(mHadClientComposition);
1768 
1769     mLayersWithQueuedFrames.clear();
1770 }
1771 
1772 
handleMessageInvalidate()1773 bool SurfaceFlinger::handleMessageInvalidate() {
1774     ATRACE_CALL();
1775     bool refreshNeeded = handlePageFlip();
1776 
1777     if (mVisibleRegionsDirty) {
1778         computeLayerBounds();
1779         if (mTracingEnabled) {
1780             mTracing.notify("visibleRegionsDirty");
1781         }
1782     }
1783 
1784     for (auto& layer : mLayersPendingRefresh) {
1785         Region visibleReg;
1786         visibleReg.set(layer->getScreenBounds());
1787         invalidateLayerStack(layer, visibleReg);
1788     }
1789     mLayersPendingRefresh.clear();
1790     return refreshNeeded;
1791 }
1792 
calculateWorkingSet()1793 void SurfaceFlinger::calculateWorkingSet() {
1794     ATRACE_CALL();
1795     ALOGV(__FUNCTION__);
1796 
1797     // build the h/w work list
1798     if (CC_UNLIKELY(mGeometryInvalid)) {
1799         mGeometryInvalid = false;
1800         for (const auto& [token, displayDevice] : mDisplays) {
1801             auto display = displayDevice->getCompositionDisplay();
1802 
1803             uint32_t zOrder = 0;
1804 
1805             for (auto& layer : display->getOutputLayersOrderedByZ()) {
1806                 auto& compositionState = layer->editState();
1807                 compositionState.forceClientComposition = false;
1808                 if (!compositionState.hwc || mDebugDisableHWC || mDebugRegion) {
1809                     compositionState.forceClientComposition = true;
1810                 }
1811 
1812                 // The output Z order is set here based on a simple counter.
1813                 compositionState.z = zOrder++;
1814 
1815                 // Update the display independent composition state. This goes
1816                 // to the general composition layer state structure.
1817                 // TODO: Do this once per compositionengine::CompositionLayer.
1818                 layer->getLayerFE().latchCompositionState(layer->getLayer().editState().frontEnd,
1819                                                           true);
1820 
1821                 // Recalculate the geometry state of the output layer.
1822                 layer->updateCompositionState(true);
1823 
1824                 // Write the updated geometry state to the HWC
1825                 layer->writeStateToHWC(true);
1826             }
1827         }
1828     }
1829 
1830     // Set the per-frame data
1831     for (const auto& [token, displayDevice] : mDisplays) {
1832         auto display = displayDevice->getCompositionDisplay();
1833         const auto displayId = display->getId();
1834         if (!displayId) {
1835             continue;
1836         }
1837         auto* profile = display->getDisplayColorProfile();
1838 
1839         if (mDrawingState.colorMatrixChanged) {
1840             display->setColorTransform(mDrawingState.colorMatrix);
1841         }
1842         Dataspace targetDataspace = Dataspace::UNKNOWN;
1843         if (useColorManagement) {
1844             ColorMode colorMode;
1845             RenderIntent renderIntent;
1846             pickColorMode(displayDevice, &colorMode, &targetDataspace, &renderIntent);
1847             display->setColorMode(colorMode, targetDataspace, renderIntent);
1848         }
1849         for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1850             if (layer->isHdrY410()) {
1851                 layer->forceClientComposition(displayDevice);
1852             } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1853                         layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
1854                        !profile->hasHDR10Support()) {
1855                 layer->forceClientComposition(displayDevice);
1856             } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1857                         layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
1858                        !profile->hasHLGSupport()) {
1859                 layer->forceClientComposition(displayDevice);
1860             }
1861 
1862             if (layer->getRoundedCornerState().radius > 0.0f) {
1863                 layer->forceClientComposition(displayDevice);
1864             }
1865 
1866             if (layer->getForceClientComposition(displayDevice)) {
1867                 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1868                 layer->setCompositionType(displayDevice,
1869                                           Hwc2::IComposerClient::Composition::CLIENT);
1870                 continue;
1871             }
1872 
1873             const auto& displayState = display->getState();
1874             layer->setPerFrameData(displayDevice, displayState.transform, displayState.viewport,
1875                                    displayDevice->getSupportedPerFrameMetadata(),
1876                                    isHdrColorMode(displayState.colorMode) ? Dataspace::UNKNOWN
1877                                                                           : targetDataspace);
1878         }
1879     }
1880 
1881     mDrawingState.colorMatrixChanged = false;
1882 
1883     for (const auto& [token, displayDevice] : mDisplays) {
1884         auto display = displayDevice->getCompositionDisplay();
1885         for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1886             auto& layerState = layer->getCompositionLayer()->editState().frontEnd;
1887             layerState.compositionType = static_cast<Hwc2::IComposerClient::Composition>(
1888                     layer->getCompositionType(displayDevice));
1889         }
1890     }
1891 }
1892 
doDebugFlashRegions(const sp<DisplayDevice> & displayDevice,bool repaintEverything)1893 void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& displayDevice,
1894                                          bool repaintEverything) {
1895     auto display = displayDevice->getCompositionDisplay();
1896     const auto& displayState = display->getState();
1897 
1898     // is debugging enabled
1899     if (CC_LIKELY(!mDebugRegion))
1900         return;
1901 
1902     if (displayState.isEnabled) {
1903         // transform the dirty region into this screen's coordinate space
1904         const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
1905         if (!dirtyRegion.isEmpty()) {
1906             base::unique_fd readyFence;
1907             // redraw the whole screen
1908             doComposeSurfaces(displayDevice, dirtyRegion, &readyFence);
1909 
1910             display->getRenderSurface()->queueBuffer(std::move(readyFence));
1911         }
1912     }
1913 
1914     postFramebuffer(displayDevice);
1915 
1916     if (mDebugRegion > 1) {
1917         usleep(mDebugRegion * 1000);
1918     }
1919 
1920     prepareFrame(displayDevice);
1921 }
1922 
logLayerStats()1923 void SurfaceFlinger::logLayerStats() {
1924     ATRACE_CALL();
1925     if (CC_UNLIKELY(mLayerStats.isEnabled())) {
1926         for (const auto& [token, display] : mDisplays) {
1927             if (display->isPrimary()) {
1928                 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(display));
1929                 return;
1930             }
1931         }
1932 
1933         ALOGE("logLayerStats: no primary display");
1934     }
1935 }
1936 
preComposition()1937 void SurfaceFlinger::preComposition()
1938 {
1939     ATRACE_CALL();
1940     ALOGV("preComposition");
1941 
1942     mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1943 
1944     bool needExtraInvalidate = false;
1945     mDrawingState.traverseInZOrder([&](Layer* layer) {
1946         if (layer->onPreComposition(mRefreshStartTime)) {
1947             needExtraInvalidate = true;
1948         }
1949     });
1950 
1951     if (needExtraInvalidate) {
1952         signalLayerUpdate();
1953     }
1954 }
1955 
updateCompositorTiming(const DisplayStatInfo & stats,nsecs_t compositeTime,std::shared_ptr<FenceTime> & presentFenceTime)1956 void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1957                                             std::shared_ptr<FenceTime>& presentFenceTime) {
1958     // Update queue of past composite+present times and determine the
1959     // most recently known composite to present latency.
1960     getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
1961     nsecs_t compositeToPresentLatency = -1;
1962     while (!getBE().mCompositePresentTimes.empty()) {
1963         SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
1964         // Cached values should have been updated before calling this method,
1965         // which helps avoid duplicate syscalls.
1966         nsecs_t displayTime = cpt.display->getCachedSignalTime();
1967         if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1968             break;
1969         }
1970         compositeToPresentLatency = displayTime - cpt.composite;
1971         getBE().mCompositePresentTimes.pop();
1972     }
1973 
1974     // Don't let mCompositePresentTimes grow unbounded, just in case.
1975     while (getBE().mCompositePresentTimes.size() > 16) {
1976         getBE().mCompositePresentTimes.pop();
1977     }
1978 
1979     setCompositorTimingSnapped(stats, compositeToPresentLatency);
1980 }
1981 
setCompositorTimingSnapped(const DisplayStatInfo & stats,nsecs_t compositeToPresentLatency)1982 void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1983                                                 nsecs_t compositeToPresentLatency) {
1984     // Integer division and modulo round toward 0 not -inf, so we need to
1985     // treat negative and positive offsets differently.
1986     nsecs_t idealLatency = (mPhaseOffsets->getCurrentSfOffset() > 0)
1987             ? (stats.vsyncPeriod - (mPhaseOffsets->getCurrentSfOffset() % stats.vsyncPeriod))
1988             : ((-mPhaseOffsets->getCurrentSfOffset()) % stats.vsyncPeriod);
1989 
1990     // Just in case mPhaseOffsets->getCurrentSfOffset() == -vsyncInterval.
1991     if (idealLatency <= 0) {
1992         idealLatency = stats.vsyncPeriod;
1993     }
1994 
1995     // Snap the latency to a value that removes scheduling jitter from the
1996     // composition and present times, which often have >1ms of jitter.
1997     // Reducing jitter is important if an app attempts to extrapolate
1998     // something (such as user input) to an accurate diasplay time.
1999     // Snapping also allows an app to precisely calculate mPhaseOffsets->getCurrentSfOffset()
2000     // with (presentLatency % interval).
2001     nsecs_t bias = stats.vsyncPeriod / 2;
2002     int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
2003     nsecs_t snappedCompositeToPresentLatency =
2004             (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
2005 
2006     std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2007     getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
2008     getBE().mCompositorTiming.interval = stats.vsyncPeriod;
2009     getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
2010 }
2011 
postComposition()2012 void SurfaceFlinger::postComposition()
2013 {
2014     ATRACE_CALL();
2015     ALOGV("postComposition");
2016 
2017     // Release any buffers which were replaced this frame
2018     nsecs_t dequeueReadyTime = systemTime();
2019     for (auto& layer : mLayersWithQueuedFrames) {
2020         layer->releasePendingBuffer(dequeueReadyTime);
2021     }
2022 
2023     // |mStateLock| not needed as we are on the main thread
2024     const auto displayDevice = getDefaultDisplayDeviceLocked();
2025 
2026     getBE().mGlCompositionDoneTimeline.updateSignalTimes();
2027     std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
2028     if (displayDevice && getHwComposer().hasClientComposition(displayDevice->getId())) {
2029         glCompositionDoneFenceTime =
2030                 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2031                                                     ->getRenderSurface()
2032                                                     ->getClientTargetAcquireFence());
2033         getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
2034     } else {
2035         glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2036     }
2037 
2038     getBE().mDisplayTimeline.updateSignalTimes();
2039     mPreviousPresentFences[1] = mPreviousPresentFences[0];
2040     mPreviousPresentFences[0] = displayDevice
2041             ? getHwComposer().getPresentFence(*displayDevice->getId())
2042             : Fence::NO_FENCE;
2043     auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
2044     getBE().mDisplayTimeline.push(presentFenceTime);
2045 
2046     DisplayStatInfo stats;
2047     mScheduler->getDisplayStatInfo(&stats);
2048 
2049     // We use the mRefreshStartTime which might be sampled a little later than
2050     // when we started doing work for this frame, but that should be okay
2051     // since updateCompositorTiming has snapping logic.
2052     updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
2053     CompositorTiming compositorTiming;
2054     {
2055         std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2056         compositorTiming = getBE().mCompositorTiming;
2057     }
2058 
2059     mDrawingState.traverseInZOrder([&](Layer* layer) {
2060         bool frameLatched =
2061                 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
2062                                          presentFenceTime, compositorTiming);
2063         if (frameLatched) {
2064             recordBufferingStats(layer->getName().string(),
2065                     layer->getOccupancyHistory(false));
2066         }
2067     });
2068 
2069     if (presentFenceTime->isValid()) {
2070         mScheduler->addPresentFence(presentFenceTime);
2071     }
2072 
2073     if (!hasSyncFramework) {
2074         if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2075             displayDevice->isPoweredOn()) {
2076             mScheduler->enableHardwareVsync();
2077         }
2078     }
2079 
2080     if (mAnimCompositionPending) {
2081         mAnimCompositionPending = false;
2082 
2083         if (presentFenceTime->isValid()) {
2084             mAnimFrameTracker.setActualPresentFence(
2085                     std::move(presentFenceTime));
2086         } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
2087             // The HWC doesn't support present fences, so use the refresh
2088             // timestamp instead.
2089             const nsecs_t presentTime =
2090                     getHwComposer().getRefreshTimestamp(*displayDevice->getId());
2091             mAnimFrameTracker.setActualPresentTime(presentTime);
2092         }
2093         mAnimFrameTracker.advanceFrame();
2094     }
2095 
2096     mTimeStats->incrementTotalFrames();
2097     if (mHadClientComposition) {
2098         mTimeStats->incrementClientCompositionFrames();
2099     }
2100 
2101     mTimeStats->setPresentFenceGlobal(presentFenceTime);
2102 
2103     if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2104         !displayDevice->isPoweredOn()) {
2105         return;
2106     }
2107 
2108     nsecs_t currentTime = systemTime();
2109     if (mHasPoweredOff) {
2110         mHasPoweredOff = false;
2111     } else {
2112         nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
2113         size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
2114         if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2115             getBE().mFrameBuckets[numPeriods] += elapsedTime;
2116         } else {
2117             getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
2118         }
2119         getBE().mTotalTime += elapsedTime;
2120     }
2121     getBE().mLastSwapTime = currentTime;
2122 
2123     {
2124         std::lock_guard lock(mTexturePoolMutex);
2125         if (mTexturePool.size() < mTexturePoolSize) {
2126             const size_t refillCount = mTexturePoolSize - mTexturePool.size();
2127             const size_t offset = mTexturePool.size();
2128             mTexturePool.resize(mTexturePoolSize);
2129             getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2130             ATRACE_INT("TexturePoolSize", mTexturePool.size());
2131         } else if (mTexturePool.size() > mTexturePoolSize) {
2132             const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2133             const size_t offset = mTexturePoolSize;
2134             getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2135             mTexturePool.resize(mTexturePoolSize);
2136             ATRACE_INT("TexturePoolSize", mTexturePool.size());
2137         }
2138     }
2139 
2140     mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
2141 
2142     // Lock the mStateLock in case SurfaceFlinger is in the middle of applying a transaction.
2143     // If we do not lock here, a callback could be sent without all of its SurfaceControls and
2144     // metrics.
2145     {
2146         Mutex::Autolock _l(mStateLock);
2147         mTransactionCompletedThread.sendCallbacks();
2148     }
2149 
2150     if (mLumaSampling && mRegionSamplingThread) {
2151         mRegionSamplingThread->notifyNewContent();
2152     }
2153 
2154     // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2155     // side-effect of getTotalSize(), so we check that again here
2156     if (ATRACE_ENABLED()) {
2157         ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2158     }
2159 }
2160 
computeLayerBounds()2161 void SurfaceFlinger::computeLayerBounds() {
2162     for (const auto& pair : mDisplays) {
2163         const auto& displayDevice = pair.second;
2164         const auto display = displayDevice->getCompositionDisplay();
2165         for (const auto& layer : mDrawingState.layersSortedByZ) {
2166             // only consider the layers on the given layer stack
2167             if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
2168                 continue;
2169             }
2170 
2171             layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform());
2172         }
2173     }
2174 }
2175 
rebuildLayerStacks()2176 void SurfaceFlinger::rebuildLayerStacks() {
2177     ATRACE_CALL();
2178     ALOGV("rebuildLayerStacks");
2179 
2180     // rebuild the visible layer list per screen
2181     if (CC_UNLIKELY(mVisibleRegionsDirty)) {
2182         ATRACE_NAME("rebuildLayerStacks VR Dirty");
2183         mVisibleRegionsDirty = false;
2184         invalidateHwcGeometry();
2185 
2186         for (const auto& pair : mDisplays) {
2187             const auto& displayDevice = pair.second;
2188             auto display = displayDevice->getCompositionDisplay();
2189             const auto& displayState = display->getState();
2190             Region opaqueRegion;
2191             Region dirtyRegion;
2192             compositionengine::Output::OutputLayers layersSortedByZ;
2193             Vector<sp<Layer>> deprecated_layersSortedByZ;
2194             Vector<sp<Layer>> layersNeedingFences;
2195             const ui::Transform& tr = displayState.transform;
2196             const Rect bounds = displayState.bounds;
2197             if (displayState.isEnabled) {
2198                 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
2199 
2200                 mDrawingState.traverseInZOrder([&](Layer* layer) {
2201                     auto compositionLayer = layer->getCompositionLayer();
2202                     if (compositionLayer == nullptr) {
2203                         return;
2204                     }
2205 
2206                     const auto displayId = displayDevice->getId();
2207                     sp<compositionengine::LayerFE> layerFE = compositionLayer->getLayerFE();
2208                     LOG_ALWAYS_FATAL_IF(layerFE.get() == nullptr);
2209 
2210                     bool needsOutputLayer = false;
2211 
2212                     if (display->belongsInOutput(layer->getLayerStack(),
2213                                                  layer->getPrimaryDisplayOnly())) {
2214                         Region drawRegion(tr.transform(
2215                                 layer->visibleNonTransparentRegion));
2216                         drawRegion.andSelf(bounds);
2217                         if (!drawRegion.isEmpty()) {
2218                             needsOutputLayer = true;
2219                         }
2220                     }
2221 
2222                     if (needsOutputLayer) {
2223                         layersSortedByZ.emplace_back(
2224                                 display->getOrCreateOutputLayer(displayId, compositionLayer,
2225                                                                 layerFE));
2226                         deprecated_layersSortedByZ.add(layer);
2227 
2228                         auto& outputLayerState = layersSortedByZ.back()->editState();
2229                         outputLayerState.visibleRegion =
2230                                 tr.transform(layer->visibleRegion.intersect(displayState.viewport));
2231                     } else if (displayId) {
2232                         // For layers that are being removed from a HWC display,
2233                         // and that have queued frames, add them to a a list of
2234                         // released layers so we can properly set a fence.
2235                         bool hasExistingOutputLayer =
2236                                 display->getOutputLayerForLayer(compositionLayer.get()) != nullptr;
2237                         bool hasQueuedFrames = std::find(mLayersWithQueuedFrames.cbegin(),
2238                                                          mLayersWithQueuedFrames.cend(),
2239                                                          layer) != mLayersWithQueuedFrames.cend();
2240 
2241                         if (hasExistingOutputLayer && hasQueuedFrames) {
2242                             layersNeedingFences.add(layer);
2243                         }
2244                     }
2245                 });
2246             }
2247 
2248             display->setOutputLayersOrderedByZ(std::move(layersSortedByZ));
2249 
2250             displayDevice->setVisibleLayersSortedByZ(deprecated_layersSortedByZ);
2251             displayDevice->setLayersNeedingFences(layersNeedingFences);
2252 
2253             Region undefinedRegion{bounds};
2254             undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2255 
2256             display->editState().undefinedRegion = undefinedRegion;
2257             display->editState().dirtyRegion.orSelf(dirtyRegion);
2258         }
2259     }
2260 }
2261 
2262 // Returns a data space that fits all visible layers.  The returned data space
2263 // can only be one of
2264 //  - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
2265 //  - Dataspace::DISPLAY_P3
2266 //  - Dataspace::DISPLAY_BT2020
2267 // The returned HDR data space is one of
2268 //  - Dataspace::UNKNOWN
2269 //  - Dataspace::BT2020_HLG
2270 //  - Dataspace::BT2020_PQ
getBestDataspace(const sp<DisplayDevice> & display,Dataspace * outHdrDataSpace,bool * outIsHdrClientComposition) const2271 Dataspace SurfaceFlinger::getBestDataspace(const sp<DisplayDevice>& display,
2272                                            Dataspace* outHdrDataSpace,
2273                                            bool* outIsHdrClientComposition) const {
2274     Dataspace bestDataSpace = Dataspace::V0_SRGB;
2275     *outHdrDataSpace = Dataspace::UNKNOWN;
2276 
2277     for (const auto& layer : display->getVisibleLayersSortedByZ()) {
2278         switch (layer->getDataSpace()) {
2279             case Dataspace::V0_SCRGB:
2280             case Dataspace::V0_SCRGB_LINEAR:
2281             case Dataspace::BT2020:
2282             case Dataspace::BT2020_ITU:
2283             case Dataspace::BT2020_LINEAR:
2284             case Dataspace::DISPLAY_BT2020:
2285                 bestDataSpace = Dataspace::DISPLAY_BT2020;
2286                 break;
2287             case Dataspace::DISPLAY_P3:
2288                 bestDataSpace = Dataspace::DISPLAY_P3;
2289                 break;
2290             case Dataspace::BT2020_PQ:
2291             case Dataspace::BT2020_ITU_PQ:
2292                 bestDataSpace = Dataspace::DISPLAY_P3;
2293                 *outHdrDataSpace = Dataspace::BT2020_PQ;
2294                 *outIsHdrClientComposition = layer->getForceClientComposition(display);
2295                 break;
2296             case Dataspace::BT2020_HLG:
2297             case Dataspace::BT2020_ITU_HLG:
2298                 bestDataSpace = Dataspace::DISPLAY_P3;
2299                 // When there's mixed PQ content and HLG content, we set the HDR
2300                 // data space to be BT2020_PQ and convert HLG to PQ.
2301                 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2302                     *outHdrDataSpace = Dataspace::BT2020_HLG;
2303                 }
2304                 break;
2305             default:
2306                 break;
2307         }
2308     }
2309 
2310     return bestDataSpace;
2311 }
2312 
2313 // Pick the ColorMode / Dataspace for the display device.
pickColorMode(const sp<DisplayDevice> & display,ColorMode * outMode,Dataspace * outDataSpace,RenderIntent * outRenderIntent) const2314 void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2315                                    Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
2316     if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2317         *outMode = ColorMode::NATIVE;
2318         *outDataSpace = Dataspace::UNKNOWN;
2319         *outRenderIntent = RenderIntent::COLORIMETRIC;
2320         return;
2321     }
2322 
2323     Dataspace hdrDataSpace;
2324     bool isHdrClientComposition = false;
2325     Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace, &isHdrClientComposition);
2326 
2327     auto* profile = display->getCompositionDisplay()->getDisplayColorProfile();
2328 
2329     switch (mForceColorMode) {
2330         case ColorMode::SRGB:
2331             bestDataSpace = Dataspace::V0_SRGB;
2332             break;
2333         case ColorMode::DISPLAY_P3:
2334             bestDataSpace = Dataspace::DISPLAY_P3;
2335             break;
2336         default:
2337             break;
2338     }
2339 
2340     // respect hdrDataSpace only when there is no legacy HDR support
2341     const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
2342             !profile->hasLegacyHdrSupport(hdrDataSpace) && !isHdrClientComposition;
2343     if (isHdr) {
2344         bestDataSpace = hdrDataSpace;
2345     }
2346 
2347     RenderIntent intent;
2348     switch (mDisplayColorSetting) {
2349         case DisplayColorSetting::MANAGED:
2350         case DisplayColorSetting::UNMANAGED:
2351             intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
2352             break;
2353         case DisplayColorSetting::ENHANCED:
2354             intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
2355             break;
2356         default: // vendor display color setting
2357             intent = static_cast<RenderIntent>(mDisplayColorSetting);
2358             break;
2359     }
2360 
2361     profile->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
2362 }
2363 
beginFrame(const sp<DisplayDevice> & displayDevice)2364 void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& displayDevice) {
2365     auto display = displayDevice->getCompositionDisplay();
2366     const auto& displayState = display->getState();
2367 
2368     bool dirty = !display->getDirtyRegion(false).isEmpty();
2369     bool empty = displayDevice->getVisibleLayersSortedByZ().size() == 0;
2370     bool wasEmpty = !displayState.lastCompositionHadVisibleLayers;
2371 
2372     // If nothing has changed (!dirty), don't recompose.
2373     // If something changed, but we don't currently have any visible layers,
2374     //   and didn't when we last did a composition, then skip it this time.
2375     // The second rule does two things:
2376     // - When all layers are removed from a display, we'll emit one black
2377     //   frame, then nothing more until we get new layers.
2378     // - When a display is created with a private layer stack, we won't
2379     //   emit any black frames until a layer is added to the layer stack.
2380     bool mustRecompose = dirty && !(empty && wasEmpty);
2381 
2382     const char flagPrefix[] = {'-', '+'};
2383     static_cast<void>(flagPrefix);
2384     ALOGV_IF(displayDevice->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2385              __FUNCTION__, mustRecompose ? "doing" : "skipping",
2386              displayDevice->getDebugName().c_str(), flagPrefix[dirty], flagPrefix[empty],
2387              flagPrefix[wasEmpty]);
2388 
2389     display->getRenderSurface()->beginFrame(mustRecompose);
2390 
2391     if (mustRecompose) {
2392         display->editState().lastCompositionHadVisibleLayers = !empty;
2393     }
2394 }
2395 
prepareFrame(const sp<DisplayDevice> & displayDevice)2396 void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& displayDevice) {
2397     auto display = displayDevice->getCompositionDisplay();
2398     const auto& displayState = display->getState();
2399 
2400     if (!displayState.isEnabled) {
2401         return;
2402     }
2403 
2404     status_t result = display->getRenderSurface()->prepareFrame();
2405     ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
2406              displayDevice->getDebugName().c_str(), result, strerror(-result));
2407 }
2408 
doComposition(const sp<DisplayDevice> & displayDevice,bool repaintEverything)2409 void SurfaceFlinger::doComposition(const sp<DisplayDevice>& displayDevice, bool repaintEverything) {
2410     ATRACE_CALL();
2411     ALOGV("doComposition");
2412 
2413     auto display = displayDevice->getCompositionDisplay();
2414     const auto& displayState = display->getState();
2415 
2416     if (displayState.isEnabled) {
2417         // transform the dirty region into this screen's coordinate space
2418         const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
2419 
2420         // repaint the framebuffer (if needed)
2421         doDisplayComposition(displayDevice, dirtyRegion);
2422 
2423         display->editState().dirtyRegion.clear();
2424         display->getRenderSurface()->flip();
2425     }
2426     postFramebuffer(displayDevice);
2427 }
2428 
postFrame()2429 void SurfaceFlinger::postFrame()
2430 {
2431     // |mStateLock| not needed as we are on the main thread
2432     const auto display = getDefaultDisplayDeviceLocked();
2433     if (display && getHwComposer().isConnected(*display->getId())) {
2434         uint32_t flipCount = display->getPageFlipCount();
2435         if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2436             logFrameStats();
2437         }
2438     }
2439 }
2440 
postFramebuffer(const sp<DisplayDevice> & displayDevice)2441 void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& displayDevice) {
2442     ATRACE_CALL();
2443     ALOGV("postFramebuffer");
2444 
2445     auto display = displayDevice->getCompositionDisplay();
2446     const auto& displayState = display->getState();
2447     const auto displayId = display->getId();
2448 
2449     if (displayState.isEnabled) {
2450         if (displayId) {
2451             getHwComposer().presentAndGetReleaseFences(*displayId);
2452         }
2453         display->getRenderSurface()->onPresentDisplayCompleted();
2454         for (auto& layer : display->getOutputLayersOrderedByZ()) {
2455             sp<Fence> releaseFence = Fence::NO_FENCE;
2456             bool usedClientComposition = true;
2457 
2458             // The layer buffer from the previous frame (if any) is released
2459             // by HWC only when the release fence from this frame (if any) is
2460             // signaled.  Always get the release fence from HWC first.
2461             if (layer->getState().hwc) {
2462                 const auto& hwcState = *layer->getState().hwc;
2463                 releaseFence =
2464                         getHwComposer().getLayerReleaseFence(*displayId, hwcState.hwcLayer.get());
2465                 usedClientComposition =
2466                         hwcState.hwcCompositionType == Hwc2::IComposerClient::Composition::CLIENT;
2467             }
2468 
2469             // If the layer was client composited in the previous frame, we
2470             // need to merge with the previous client target acquire fence.
2471             // Since we do not track that, always merge with the current
2472             // client target acquire fence when it is available, even though
2473             // this is suboptimal.
2474             if (usedClientComposition) {
2475                 releaseFence =
2476                         Fence::merge("LayerRelease", releaseFence,
2477                                      display->getRenderSurface()->getClientTargetAcquireFence());
2478             }
2479 
2480             layer->getLayerFE().onLayerDisplayed(releaseFence);
2481         }
2482 
2483         // We've got a list of layers needing fences, that are disjoint with
2484         // display->getVisibleLayersSortedByZ.  The best we can do is to
2485         // supply them with the present fence.
2486         if (!displayDevice->getLayersNeedingFences().isEmpty()) {
2487             sp<Fence> presentFence =
2488                     displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
2489             for (auto& layer : displayDevice->getLayersNeedingFences()) {
2490                 layer->getCompositionLayer()->getLayerFE()->onLayerDisplayed(presentFence);
2491             }
2492         }
2493 
2494         if (displayId) {
2495             getHwComposer().clearReleaseFences(*displayId);
2496         }
2497     }
2498 }
2499 
handleTransaction(uint32_t transactionFlags)2500 void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
2501 {
2502     ATRACE_CALL();
2503 
2504     // here we keep a copy of the drawing state (that is the state that's
2505     // going to be overwritten by handleTransactionLocked()) outside of
2506     // mStateLock so that the side-effects of the State assignment
2507     // don't happen with mStateLock held (which can cause deadlocks).
2508     State drawingState(mDrawingState);
2509 
2510     Mutex::Autolock _l(mStateLock);
2511     mDebugInTransaction = systemTime();
2512 
2513     // Here we're guaranteed that some transaction flags are set
2514     // so we can call handleTransactionLocked() unconditionally.
2515     // We call getTransactionFlags(), which will also clear the flags,
2516     // with mStateLock held to guarantee that mCurrentState won't change
2517     // until the transaction is committed.
2518 
2519     mVsyncModulator.onTransactionHandled();
2520     transactionFlags = getTransactionFlags(eTransactionMask);
2521     handleTransactionLocked(transactionFlags);
2522 
2523     mDebugInTransaction = 0;
2524     invalidateHwcGeometry();
2525     // here the transaction has been committed
2526 }
2527 
processDisplayHotplugEventsLocked()2528 void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2529     for (const auto& event : mPendingHotplugEvents) {
2530         const std::optional<DisplayIdentificationInfo> info =
2531                 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
2532 
2533         if (!info) {
2534             continue;
2535         }
2536 
2537         if (event.connection == HWC2::Connection::Connected) {
2538             if (!mPhysicalDisplayTokens.count(info->id)) {
2539                 ALOGV("Creating display %s", to_string(info->id).c_str());
2540                 mPhysicalDisplayTokens[info->id] = new BBinder();
2541                 DisplayDeviceState state;
2542                 state.displayId = info->id;
2543                 state.isSecure = true; // All physical displays are currently considered secure.
2544                 state.displayName = info->name;
2545                 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2546                 mInterceptor->saveDisplayCreation(state);
2547             }
2548         } else {
2549             ALOGV("Removing display %s", to_string(info->id).c_str());
2550 
2551             ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2552             if (index >= 0) {
2553                 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2554                 mInterceptor->saveDisplayDeletion(state.sequenceId);
2555                 mCurrentState.displays.removeItemsAt(index);
2556             }
2557             mPhysicalDisplayTokens.erase(info->id);
2558         }
2559 
2560         processDisplayChangesLocked();
2561     }
2562 
2563     mPendingHotplugEvents.clear();
2564 }
2565 
dispatchDisplayHotplugEvent(PhysicalDisplayId displayId,bool connected)2566 void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
2567     mScheduler->hotplugReceived(mAppConnectionHandle, displayId, connected);
2568     mScheduler->hotplugReceived(mSfConnectionHandle, displayId, connected);
2569 }
2570 
setupNewDisplayDeviceInternal(const wp<IBinder> & displayToken,const std::optional<DisplayId> & displayId,const DisplayDeviceState & state,const sp<compositionengine::DisplaySurface> & dispSurface,const sp<IGraphicBufferProducer> & producer)2571 sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
2572         const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
2573         const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
2574         const sp<IGraphicBufferProducer>& producer) {
2575     DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
2576     creationArgs.sequenceId = state.sequenceId;
2577     creationArgs.isVirtual = state.isVirtual();
2578     creationArgs.isSecure = state.isSecure;
2579     creationArgs.displaySurface = dispSurface;
2580     creationArgs.hasWideColorGamut = false;
2581     creationArgs.supportedPerFrameMetadata = 0;
2582 
2583     const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
2584     creationArgs.isPrimary = isInternalDisplay;
2585 
2586     if (useColorManagement && displayId) {
2587         std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
2588         for (ColorMode colorMode : modes) {
2589             if (isWideColorMode(colorMode)) {
2590                 creationArgs.hasWideColorGamut = true;
2591             }
2592 
2593             std::vector<RenderIntent> renderIntents =
2594                     getHwComposer().getRenderIntents(*displayId, colorMode);
2595             creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
2596         }
2597     }
2598 
2599     if (displayId) {
2600         getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
2601         creationArgs.supportedPerFrameMetadata =
2602                 getHwComposer().getSupportedPerFrameMetadata(*displayId);
2603     }
2604 
2605     auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
2606     auto nativeWindow = nativeWindowSurface->getNativeWindow();
2607     creationArgs.nativeWindow = nativeWindow;
2608 
2609     // Make sure that composition can never be stalled by a virtual display
2610     // consumer that isn't processing buffers fast enough. We have to do this
2611     // here, in case the display is composed entirely by HWC.
2612     if (state.isVirtual()) {
2613         nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2614     }
2615 
2616     creationArgs.displayInstallOrientation =
2617             isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
2618 
2619     // virtual displays are always considered enabled
2620     creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
2621 
2622     sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
2623 
2624     if (maxFrameBufferAcquiredBuffers >= 3) {
2625         nativeWindowSurface->preallocateBuffers();
2626     }
2627 
2628     ColorMode defaultColorMode = ColorMode::NATIVE;
2629     Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2630     if (display->hasWideColorGamut()) {
2631         defaultColorMode = ColorMode::SRGB;
2632         defaultDataSpace = Dataspace::V0_SRGB;
2633     }
2634     display->getCompositionDisplay()->setColorMode(defaultColorMode, defaultDataSpace,
2635                                                    RenderIntent::COLORIMETRIC);
2636     if (!state.isVirtual()) {
2637         LOG_ALWAYS_FATAL_IF(!displayId);
2638         display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
2639     }
2640 
2641     display->setLayerStack(state.layerStack);
2642     display->setProjection(state.orientation, state.viewport, state.frame);
2643     display->setDisplayName(state.displayName);
2644 
2645     return display;
2646 }
2647 
processDisplayChangesLocked()2648 void SurfaceFlinger::processDisplayChangesLocked() {
2649     // here we take advantage of Vector's copy-on-write semantics to
2650     // improve performance by skipping the transaction entirely when
2651     // know that the lists are identical
2652     const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2653     const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2654     if (!curr.isIdenticalTo(draw)) {
2655         mVisibleRegionsDirty = true;
2656         const size_t cc = curr.size();
2657         size_t dc = draw.size();
2658 
2659         // find the displays that were removed
2660         // (ie: in drawing state but not in current state)
2661         // also handle displays that changed
2662         // (ie: displays that are in both lists)
2663         for (size_t i = 0; i < dc;) {
2664             const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2665             if (j < 0) {
2666                 // in drawing state but not in current state
2667                 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2668                     // Save display ID before disconnecting.
2669                     const auto displayId = display->getId();
2670                     display->disconnect();
2671 
2672                     if (!display->isVirtual()) {
2673                         LOG_ALWAYS_FATAL_IF(!displayId);
2674                         dispatchDisplayHotplugEvent(displayId->value, false);
2675                     }
2676                 }
2677 
2678                 mDisplays.erase(draw.keyAt(i));
2679             } else {
2680                 // this display is in both lists. see if something changed.
2681                 const DisplayDeviceState& state(curr[j]);
2682                 const wp<IBinder>& displayToken = curr.keyAt(j);
2683                 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2684                 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2685                 if (state_binder != draw_binder) {
2686                     // changing the surface is like destroying and
2687                     // recreating the DisplayDevice, so we just remove it
2688                     // from the drawing state, so that it get re-added
2689                     // below.
2690                     if (const auto display = getDisplayDeviceLocked(displayToken)) {
2691                         display->disconnect();
2692                     }
2693                     mDisplays.erase(displayToken);
2694                     mDrawingState.displays.removeItemsAt(i);
2695                     dc--;
2696                     // at this point we must loop to the next item
2697                     continue;
2698                 }
2699 
2700                 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2701                     if (state.layerStack != draw[i].layerStack) {
2702                         display->setLayerStack(state.layerStack);
2703                     }
2704                     if ((state.orientation != draw[i].orientation) ||
2705                         (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
2706                         display->setProjection(state.orientation, state.viewport, state.frame);
2707                     }
2708                     if (state.width != draw[i].width || state.height != draw[i].height) {
2709                         display->setDisplaySize(state.width, state.height);
2710                     }
2711                 }
2712             }
2713             ++i;
2714         }
2715 
2716         // find displays that were added
2717         // (ie: in current state but not in drawing state)
2718         for (size_t i = 0; i < cc; i++) {
2719             if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2720                 const DisplayDeviceState& state(curr[i]);
2721 
2722                 sp<compositionengine::DisplaySurface> dispSurface;
2723                 sp<IGraphicBufferProducer> producer;
2724                 sp<IGraphicBufferProducer> bqProducer;
2725                 sp<IGraphicBufferConsumer> bqConsumer;
2726                 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
2727 
2728                 std::optional<DisplayId> displayId;
2729                 if (state.isVirtual()) {
2730                     // Virtual displays without a surface are dormant:
2731                     // they have external state (layer stack, projection,
2732                     // etc.) but no internal state (i.e. a DisplayDevice).
2733                     if (state.surface != nullptr) {
2734                         // Allow VR composer to use virtual displays.
2735                         if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
2736                             int width = 0;
2737                             int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2738                             ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2739                             int height = 0;
2740                             status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2741                             ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2742                             int intFormat = 0;
2743                             status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2744                             ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
2745                             auto format = static_cast<ui::PixelFormat>(intFormat);
2746 
2747                             displayId =
2748                                     getHwComposer().allocateVirtualDisplay(width, height, &format);
2749                         }
2750 
2751                         // TODO: Plumb requested format back up to consumer
2752 
2753                         sp<VirtualDisplaySurface> vds =
2754                                 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
2755                                                           bqProducer, bqConsumer,
2756                                                           state.displayName);
2757 
2758                         dispSurface = vds;
2759                         producer = vds;
2760                     }
2761                 } else {
2762                     ALOGE_IF(state.surface != nullptr,
2763                              "adding a supported display, but rendering "
2764                              "surface is provided (%p), ignoring it",
2765                              state.surface.get());
2766 
2767                     displayId = state.displayId;
2768                     LOG_ALWAYS_FATAL_IF(!displayId);
2769                     dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
2770                     producer = bqProducer;
2771                 }
2772 
2773                 const wp<IBinder>& displayToken = curr.keyAt(i);
2774                 if (dispSurface != nullptr) {
2775                     mDisplays.emplace(displayToken,
2776                                       setupNewDisplayDeviceInternal(displayToken, displayId, state,
2777                                                                     dispSurface, producer));
2778                     if (!state.isVirtual()) {
2779                         LOG_ALWAYS_FATAL_IF(!displayId);
2780                         dispatchDisplayHotplugEvent(displayId->value, true);
2781                     }
2782                 }
2783             }
2784         }
2785     }
2786 
2787     mDrawingState.displays = mCurrentState.displays;
2788 }
2789 
handleTransactionLocked(uint32_t transactionFlags)2790 void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
2791 {
2792     // Notify all layers of available frames
2793     mCurrentState.traverseInZOrder([](Layer* layer) {
2794         layer->notifyAvailableFrames();
2795     });
2796 
2797     /*
2798      * Traversal of the children
2799      * (perform the transaction for each of them if needed)
2800      */
2801 
2802     if ((transactionFlags & eTraversalNeeded) || mTraversalNeededMainThread) {
2803         mCurrentState.traverseInZOrder([&](Layer* layer) {
2804             uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
2805             if (!trFlags) return;
2806 
2807             const uint32_t flags = layer->doTransaction(0);
2808             if (flags & Layer::eVisibleRegion)
2809                 mVisibleRegionsDirty = true;
2810 
2811             if (flags & Layer::eInputInfoChanged) {
2812                 mInputInfoChanged = true;
2813             }
2814         });
2815         mTraversalNeededMainThread = false;
2816     }
2817 
2818     /*
2819      * Perform display own transactions if needed
2820      */
2821 
2822     if (transactionFlags & eDisplayTransactionNeeded) {
2823         processDisplayChangesLocked();
2824         processDisplayHotplugEventsLocked();
2825     }
2826 
2827     if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
2828         // The transform hint might have changed for some layers
2829         // (either because a display has changed, or because a layer
2830         // as changed).
2831         //
2832         // Walk through all the layers in currentLayers,
2833         // and update their transform hint.
2834         //
2835         // If a layer is visible only on a single display, then that
2836         // display is used to calculate the hint, otherwise we use the
2837         // default display.
2838         //
2839         // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2840         // the hint is set before we acquire a buffer from the surface texture.
2841         //
2842         // NOTE: layer transactions have taken place already, so we use their
2843         // drawing state. However, SurfaceFlinger's own transaction has not
2844         // happened yet, so we must use the current state layer list
2845         // (soon to become the drawing state list).
2846         //
2847         sp<const DisplayDevice> hintDisplay;
2848         uint32_t currentlayerStack = 0;
2849         bool first = true;
2850         mCurrentState.traverseInZOrder([&](Layer* layer) {
2851             // NOTE: we rely on the fact that layers are sorted by
2852             // layerStack first (so we don't have to traverse the list
2853             // of displays for every layer).
2854             uint32_t layerStack = layer->getLayerStack();
2855             if (first || currentlayerStack != layerStack) {
2856                 currentlayerStack = layerStack;
2857                 // figure out if this layerstack is mirrored
2858                 // (more than one display) if so, pick the default display,
2859                 // if not, pick the only display it's on.
2860                 hintDisplay = nullptr;
2861                 for (const auto& [token, display] : mDisplays) {
2862                     if (display->getCompositionDisplay()
2863                                 ->belongsInOutput(layer->getLayerStack(),
2864                                                   layer->getPrimaryDisplayOnly())) {
2865                         if (hintDisplay) {
2866                             hintDisplay = nullptr;
2867                             break;
2868                         } else {
2869                             hintDisplay = display;
2870                         }
2871                     }
2872                 }
2873             }
2874 
2875             if (!hintDisplay) {
2876                 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2877                 // redraw after transform hint changes. See bug 8508397.
2878 
2879                 // could be null when this layer is using a layerStack
2880                 // that is not visible on any display. Also can occur at
2881                 // screen off/on times.
2882                 hintDisplay = getDefaultDisplayDeviceLocked();
2883             }
2884 
2885             // could be null if there is no display available at all to get
2886             // the transform hint from.
2887             if (hintDisplay) {
2888                 layer->updateTransformHint(hintDisplay);
2889             }
2890 
2891             first = false;
2892         });
2893     }
2894 
2895 
2896     /*
2897      * Perform our own transaction if needed
2898      */
2899 
2900     if (mLayersAdded) {
2901         mLayersAdded = false;
2902         // Layers have been added.
2903         mVisibleRegionsDirty = true;
2904     }
2905 
2906     // some layers might have been removed, so
2907     // we need to update the regions they're exposing.
2908     if (mLayersRemoved) {
2909         mLayersRemoved = false;
2910         mVisibleRegionsDirty = true;
2911         mDrawingState.traverseInZOrder([&](Layer* layer) {
2912             if (mLayersPendingRemoval.indexOf(layer) >= 0) {
2913                 // this layer is not visible anymore
2914                 Region visibleReg;
2915                 visibleReg.set(layer->getScreenBounds());
2916                 invalidateLayerStack(layer, visibleReg);
2917             }
2918         });
2919     }
2920 
2921     commitInputWindowCommands();
2922     commitTransaction();
2923 }
2924 
updateInputFlinger()2925 void SurfaceFlinger::updateInputFlinger() {
2926     ATRACE_CALL();
2927     if (!mInputFlinger) {
2928         return;
2929     }
2930 
2931     if (mVisibleRegionsDirty || mInputInfoChanged) {
2932         mInputInfoChanged = false;
2933         updateInputWindowInfo();
2934     } else if (mInputWindowCommands.syncInputWindows) {
2935         // If the caller requested to sync input windows, but there are no
2936         // changes to input windows, notify immediately.
2937         setInputWindowsFinished();
2938     }
2939 
2940     executeInputWindowCommands();
2941 }
2942 
updateInputWindowInfo()2943 void SurfaceFlinger::updateInputWindowInfo() {
2944     std::vector<InputWindowInfo> inputHandles;
2945 
2946     mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2947         if (layer->hasInput()) {
2948             // When calculating the screen bounds we ignore the transparent region since it may
2949             // result in an unwanted offset.
2950             inputHandles.push_back(layer->fillInputInfo());
2951         }
2952     });
2953 
2954     mInputFlinger->setInputWindows(inputHandles,
2955                                    mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2956                                                                          : nullptr);
2957 }
2958 
commitInputWindowCommands()2959 void SurfaceFlinger::commitInputWindowCommands() {
2960     mInputWindowCommands = mPendingInputWindowCommands;
2961     mPendingInputWindowCommands.clear();
2962 }
2963 
executeInputWindowCommands()2964 void SurfaceFlinger::executeInputWindowCommands() {
2965     for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
2966         if (transferTouchFocusCommand.fromToken != nullptr &&
2967             transferTouchFocusCommand.toToken != nullptr &&
2968             transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
2969             mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
2970                                               transferTouchFocusCommand.toToken);
2971         }
2972     }
2973 
2974     mInputWindowCommands.clear();
2975 }
2976 
updateCursorAsync()2977 void SurfaceFlinger::updateCursorAsync()
2978 {
2979     for (const auto& [token, display] : mDisplays) {
2980         if (!display->getId()) {
2981             continue;
2982         }
2983 
2984         for (auto& layer : display->getVisibleLayersSortedByZ()) {
2985             layer->updateCursorPosition(display);
2986         }
2987     }
2988 }
2989 
latchAndReleaseBuffer(const sp<Layer> & layer)2990 void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
2991     if (layer->hasReadyFrame()) {
2992         bool ignored = false;
2993         layer->latchBuffer(ignored, systemTime());
2994     }
2995     layer->releasePendingBuffer(systemTime());
2996 }
2997 
commitTransaction()2998 void SurfaceFlinger::commitTransaction()
2999 {
3000     if (!mLayersPendingRemoval.isEmpty()) {
3001         // Notify removed layers now that they can't be drawn from
3002         for (const auto& l : mLayersPendingRemoval) {
3003             recordBufferingStats(l->getName().string(),
3004                     l->getOccupancyHistory(true));
3005 
3006             // Ensure any buffers set to display on any children are released.
3007             if (l->isRemovedFromCurrentState()) {
3008                 latchAndReleaseBuffer(l);
3009             }
3010 
3011             // If the layer has been removed and has no parent, then it will not be reachable
3012             // when traversing layers on screen. Add the layer to the offscreenLayers set to
3013             // ensure we can copy its current to drawing state.
3014             if (!l->getParent()) {
3015                 mOffscreenLayers.emplace(l.get());
3016             }
3017         }
3018         mLayersPendingRemoval.clear();
3019     }
3020 
3021     // If this transaction is part of a window animation then the next frame
3022     // we composite should be considered an animation as well.
3023     mAnimCompositionPending = mAnimTransactionPending;
3024 
3025     withTracingLock([&]() {
3026         mDrawingState = mCurrentState;
3027         // clear the "changed" flags in current state
3028         mCurrentState.colorMatrixChanged = false;
3029 
3030         mDrawingState.traverseInZOrder([&](Layer* layer) {
3031             layer->commitChildList();
3032 
3033             // If the layer can be reached when traversing mDrawingState, then the layer is no
3034             // longer offscreen. Remove the layer from the offscreenLayer set.
3035             if (mOffscreenLayers.count(layer)) {
3036                 mOffscreenLayers.erase(layer);
3037             }
3038         });
3039 
3040         commitOffscreenLayers();
3041     });
3042 
3043     mTransactionPending = false;
3044     mAnimTransactionPending = false;
3045     mTransactionCV.broadcast();
3046 }
3047 
withTracingLock(std::function<void ()> lockedOperation)3048 void SurfaceFlinger::withTracingLock(std::function<void()> lockedOperation) {
3049     if (mTracingEnabledChanged) {
3050         mTracingEnabled = mTracing.isEnabled();
3051         mTracingEnabledChanged = false;
3052     }
3053 
3054     // Synchronize with Tracing thread
3055     std::unique_lock<std::mutex> lock;
3056     if (mTracingEnabled) {
3057         lock = std::unique_lock<std::mutex>(mDrawingStateLock);
3058     }
3059 
3060     lockedOperation();
3061 
3062     // Synchronize with Tracing thread
3063     if (mTracingEnabled) {
3064         lock.unlock();
3065     }
3066 }
3067 
commitOffscreenLayers()3068 void SurfaceFlinger::commitOffscreenLayers() {
3069     for (Layer* offscreenLayer : mOffscreenLayers) {
3070         offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing, [](Layer* layer) {
3071             uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
3072             if (!trFlags) return;
3073 
3074             layer->doTransaction(0);
3075             layer->commitChildList();
3076         });
3077     }
3078 }
3079 
computeVisibleRegions(const sp<const DisplayDevice> & displayDevice,Region & outDirtyRegion,Region & outOpaqueRegion)3080 void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
3081                                            Region& outDirtyRegion, Region& outOpaqueRegion) {
3082     ATRACE_CALL();
3083     ALOGV("computeVisibleRegions");
3084 
3085     auto display = displayDevice->getCompositionDisplay();
3086 
3087     Region aboveOpaqueLayers;
3088     Region aboveCoveredLayers;
3089     Region dirty;
3090 
3091     outDirtyRegion.clear();
3092 
3093     mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
3094         // start with the whole surface at its current location
3095         const Layer::State& s(layer->getDrawingState());
3096 
3097         // only consider the layers on the given layer stack
3098         if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
3099             return;
3100         }
3101 
3102         /*
3103          * opaqueRegion: area of a surface that is fully opaque.
3104          */
3105         Region opaqueRegion;
3106 
3107         /*
3108          * visibleRegion: area of a surface that is visible on screen
3109          * and not fully transparent. This is essentially the layer's
3110          * footprint minus the opaque regions above it.
3111          * Areas covered by a translucent surface are considered visible.
3112          */
3113         Region visibleRegion;
3114 
3115         /*
3116          * coveredRegion: area of a surface that is covered by all
3117          * visible regions above it (which includes the translucent areas).
3118          */
3119         Region coveredRegion;
3120 
3121         /*
3122          * transparentRegion: area of a surface that is hinted to be completely
3123          * transparent. This is only used to tell when the layer has no visible
3124          * non-transparent regions and can be removed from the layer list. It
3125          * does not affect the visibleRegion of this layer or any layers
3126          * beneath it. The hint may not be correct if apps don't respect the
3127          * SurfaceView restrictions (which, sadly, some don't).
3128          */
3129         Region transparentRegion;
3130 
3131 
3132         // handle hidden surfaces by setting the visible region to empty
3133         if (CC_LIKELY(layer->isVisible())) {
3134             const bool translucent = !layer->isOpaque(s);
3135             Rect bounds(layer->getScreenBounds());
3136 
3137             visibleRegion.set(bounds);
3138             ui::Transform tr = layer->getTransform();
3139             if (!visibleRegion.isEmpty()) {
3140                 // Remove the transparent area from the visible region
3141                 if (translucent) {
3142                     if (tr.preserveRects()) {
3143                         // transform the transparent region
3144                         transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
3145                     } else {
3146                         // transformation too complex, can't do the
3147                         // transparent region optimization.
3148                         transparentRegion.clear();
3149                     }
3150                 }
3151 
3152                 // compute the opaque region
3153                 const int32_t layerOrientation = tr.getOrientation();
3154                 if (layer->getAlpha() == 1.0f && !translucent &&
3155                         layer->getRoundedCornerState().radius == 0.0f &&
3156                         ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
3157                     // the opaque region is the layer's footprint
3158                     opaqueRegion = visibleRegion;
3159                 }
3160             }
3161         }
3162 
3163         if (visibleRegion.isEmpty()) {
3164             layer->clearVisibilityRegions();
3165             return;
3166         }
3167 
3168         // Clip the covered region to the visible region
3169         coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3170 
3171         // Update aboveCoveredLayers for next (lower) layer
3172         aboveCoveredLayers.orSelf(visibleRegion);
3173 
3174         // subtract the opaque region covered by the layers above us
3175         visibleRegion.subtractSelf(aboveOpaqueLayers);
3176 
3177         // compute this layer's dirty region
3178         if (layer->contentDirty) {
3179             // we need to invalidate the whole region
3180             dirty = visibleRegion;
3181             // as well, as the old visible region
3182             dirty.orSelf(layer->visibleRegion);
3183             layer->contentDirty = false;
3184         } else {
3185             /* compute the exposed region:
3186              *   the exposed region consists of two components:
3187              *   1) what's VISIBLE now and was COVERED before
3188              *   2) what's EXPOSED now less what was EXPOSED before
3189              *
3190              * note that (1) is conservative, we start with the whole
3191              * visible region but only keep what used to be covered by
3192              * something -- which mean it may have been exposed.
3193              *
3194              * (2) handles areas that were not covered by anything but got
3195              * exposed because of a resize.
3196              */
3197             const Region newExposed = visibleRegion - coveredRegion;
3198             const Region oldVisibleRegion = layer->visibleRegion;
3199             const Region oldCoveredRegion = layer->coveredRegion;
3200             const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3201             dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
3202         }
3203         dirty.subtractSelf(aboveOpaqueLayers);
3204 
3205         // accumulate to the screen dirty region
3206         outDirtyRegion.orSelf(dirty);
3207 
3208         // Update aboveOpaqueLayers for next (lower) layer
3209         aboveOpaqueLayers.orSelf(opaqueRegion);
3210 
3211         // Store the visible region in screen space
3212         layer->setVisibleRegion(visibleRegion);
3213         layer->setCoveredRegion(coveredRegion);
3214         layer->setVisibleNonTransparentRegion(
3215                 visibleRegion.subtract(transparentRegion));
3216     });
3217 
3218     outOpaqueRegion = aboveOpaqueLayers;
3219 }
3220 
invalidateLayerStack(const sp<const Layer> & layer,const Region & dirty)3221 void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
3222     for (const auto& [token, displayDevice] : mDisplays) {
3223         auto display = displayDevice->getCompositionDisplay();
3224         if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
3225             display->editState().dirtyRegion.orSelf(dirty);
3226         }
3227     }
3228 }
3229 
handlePageFlip()3230 bool SurfaceFlinger::handlePageFlip()
3231 {
3232     ATRACE_CALL();
3233     ALOGV("handlePageFlip");
3234 
3235     nsecs_t latchTime = systemTime();
3236 
3237     bool visibleRegions = false;
3238     bool frameQueued = false;
3239     bool newDataLatched = false;
3240 
3241     // Store the set of layers that need updates. This set must not change as
3242     // buffers are being latched, as this could result in a deadlock.
3243     // Example: Two producers share the same command stream and:
3244     // 1.) Layer 0 is latched
3245     // 2.) Layer 0 gets a new frame
3246     // 2.) Layer 1 gets a new frame
3247     // 3.) Layer 1 is latched.
3248     // Display is now waiting on Layer 1's frame, which is behind layer 0's
3249     // second frame. But layer 0's second frame could be waiting on display.
3250     mDrawingState.traverseInZOrder([&](Layer* layer) {
3251         if (layer->hasReadyFrame()) {
3252             frameQueued = true;
3253             nsecs_t expectedPresentTime;
3254             expectedPresentTime = mScheduler->expectedPresentTime();
3255             if (layer->shouldPresentNow(expectedPresentTime)) {
3256                 mLayersWithQueuedFrames.push_back(layer);
3257             } else {
3258                 ATRACE_NAME("!layer->shouldPresentNow()");
3259                 layer->useEmptyDamage();
3260             }
3261         } else {
3262             layer->useEmptyDamage();
3263         }
3264     });
3265 
3266     if (!mLayersWithQueuedFrames.empty()) {
3267         // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3268         // writes to Layer current state. See also b/119481871
3269         Mutex::Autolock lock(mStateLock);
3270 
3271         for (auto& layer : mLayersWithQueuedFrames) {
3272             if (layer->latchBuffer(visibleRegions, latchTime)) {
3273                 mLayersPendingRefresh.push_back(layer);
3274             }
3275             layer->useSurfaceDamage();
3276             if (layer->isBufferLatched()) {
3277                 newDataLatched = true;
3278             }
3279         }
3280     }
3281 
3282     mVisibleRegionsDirty |= visibleRegions;
3283 
3284     // If we will need to wake up at some time in the future to deal with a
3285     // queued frame that shouldn't be displayed during this vsync period, wake
3286     // up during the next vsync period to check again.
3287     if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
3288         signalLayerUpdate();
3289     }
3290 
3291     // enter boot animation on first buffer latch
3292     if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3293         ALOGI("Enter boot animation");
3294         mBootStage = BootStage::BOOTANIMATION;
3295     }
3296 
3297     // Only continue with the refresh if there is actually new work to do
3298     return !mLayersWithQueuedFrames.empty() && newDataLatched;
3299 }
3300 
invalidateHwcGeometry()3301 void SurfaceFlinger::invalidateHwcGeometry()
3302 {
3303     mGeometryInvalid = true;
3304 }
3305 
doDisplayComposition(const sp<DisplayDevice> & displayDevice,const Region & inDirtyRegion)3306 void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& displayDevice,
3307                                           const Region& inDirtyRegion) {
3308     auto display = displayDevice->getCompositionDisplay();
3309     // We only need to actually compose the display if:
3310     // 1) It is being handled by hardware composer, which may need this to
3311     //    keep its virtual display state machine in sync, or
3312     // 2) There is work to be done (the dirty region isn't empty)
3313     if (!displayDevice->getId() && inDirtyRegion.isEmpty()) {
3314         ALOGV("Skipping display composition");
3315         return;
3316     }
3317 
3318     ALOGV("doDisplayComposition");
3319     base::unique_fd readyFence;
3320     if (!doComposeSurfaces(displayDevice, Region::INVALID_REGION, &readyFence)) return;
3321 
3322     // swap buffers (presentation)
3323     display->getRenderSurface()->queueBuffer(std::move(readyFence));
3324 }
3325 
doComposeSurfaces(const sp<DisplayDevice> & displayDevice,const Region & debugRegion,base::unique_fd * readyFence)3326 bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& displayDevice,
3327                                        const Region& debugRegion, base::unique_fd* readyFence) {
3328     ATRACE_CALL();
3329     ALOGV("doComposeSurfaces");
3330 
3331     auto display = displayDevice->getCompositionDisplay();
3332     const auto& displayState = display->getState();
3333     const auto displayId = display->getId();
3334     auto& renderEngine = getRenderEngine();
3335     const bool supportProtectedContent = renderEngine.supportsProtectedContent();
3336 
3337     const Region bounds(displayState.bounds);
3338     const DisplayRenderArea renderArea(displayDevice);
3339     const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
3340     ATRACE_INT("hasClientComposition", hasClientComposition);
3341 
3342     bool applyColorMatrix = false;
3343 
3344     renderengine::DisplaySettings clientCompositionDisplay;
3345     std::vector<renderengine::LayerSettings> clientCompositionLayers;
3346     sp<GraphicBuffer> buf;
3347     base::unique_fd fd;
3348 
3349     if (hasClientComposition) {
3350         ALOGV("hasClientComposition");
3351 
3352         if (displayDevice->isPrimary() && supportProtectedContent) {
3353             bool needsProtected = false;
3354             for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
3355                 // If the layer is a protected layer, mark protected context is needed.
3356                 if (layer->isProtected()) {
3357                     needsProtected = true;
3358                     break;
3359                 }
3360             }
3361             if (needsProtected != renderEngine.isProtected()) {
3362                 renderEngine.useProtectedContext(needsProtected);
3363             }
3364             if (needsProtected != display->getRenderSurface()->isProtected() &&
3365                 needsProtected == renderEngine.isProtected()) {
3366                 display->getRenderSurface()->setProtected(needsProtected);
3367             }
3368         }
3369 
3370         buf = display->getRenderSurface()->dequeueBuffer(&fd);
3371 
3372         if (buf == nullptr) {
3373             ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3374                   "client composition for this frame",
3375                   displayDevice->getDisplayName().c_str());
3376             return false;
3377         }
3378 
3379         clientCompositionDisplay.physicalDisplay = displayState.scissor;
3380         clientCompositionDisplay.clip = displayState.scissor;
3381         const ui::Transform& displayTransform = displayState.transform;
3382         clientCompositionDisplay.globalTransform = displayTransform.asMatrix4();
3383         clientCompositionDisplay.orientation = displayState.orientation;
3384 
3385         const auto* profile = display->getDisplayColorProfile();
3386         Dataspace outputDataspace = Dataspace::UNKNOWN;
3387         if (profile->hasWideColorGamut()) {
3388             outputDataspace = displayState.dataspace;
3389         }
3390         clientCompositionDisplay.outputDataspace = outputDataspace;
3391         clientCompositionDisplay.maxLuminance =
3392                 profile->getHdrCapabilities().getDesiredMaxLuminance();
3393 
3394         const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
3395         const bool skipClientColorTransform =
3396                 getHwComposer()
3397                         .hasDisplayCapability(displayId,
3398                                               HWC2::DisplayCapability::SkipClientColorTransform);
3399 
3400         // Compute the global color transform matrix.
3401         applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3402         if (applyColorMatrix) {
3403             clientCompositionDisplay.colorTransform = displayState.colorTransformMat;
3404         }
3405     }
3406 
3407     /*
3408      * and then, render the layers targeted at the framebuffer
3409      */
3410 
3411     ALOGV("Rendering client layers");
3412     bool firstLayer = true;
3413     Region clearRegion = Region::INVALID_REGION;
3414     for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
3415         const Region viewportRegion(displayState.viewport);
3416         const Region clip(viewportRegion.intersect(layer->visibleRegion));
3417         ALOGV("Layer: %s", layer->getName().string());
3418         ALOGV("  Composition type: %s", toString(layer->getCompositionType(displayDevice)).c_str());
3419         if (!clip.isEmpty()) {
3420             switch (layer->getCompositionType(displayDevice)) {
3421                 case Hwc2::IComposerClient::Composition::CURSOR:
3422                 case Hwc2::IComposerClient::Composition::DEVICE:
3423                 case Hwc2::IComposerClient::Composition::SIDEBAND:
3424                 case Hwc2::IComposerClient::Composition::SOLID_COLOR: {
3425                     LOG_ALWAYS_FATAL_IF(!displayId);
3426                     const Layer::State& state(layer->getDrawingState());
3427                     if (layer->getClearClientTarget(displayDevice) && !firstLayer &&
3428                         layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
3429                         layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
3430                         // never clear the very first layer since we're
3431                         // guaranteed the FB is already cleared
3432                         renderengine::LayerSettings layerSettings;
3433                         Region dummyRegion;
3434                         bool prepared =
3435                                 layer->prepareClientLayer(renderArea, clip, dummyRegion,
3436                                                           supportProtectedContent, layerSettings);
3437 
3438                         if (prepared) {
3439                             layerSettings.source.buffer.buffer = nullptr;
3440                             layerSettings.source.solidColor = half3(0.0, 0.0, 0.0);
3441                             layerSettings.alpha = half(0.0);
3442                             layerSettings.disableBlending = true;
3443                             clientCompositionLayers.push_back(layerSettings);
3444                         }
3445                     }
3446                     break;
3447                 }
3448                 case Hwc2::IComposerClient::Composition::CLIENT: {
3449                     renderengine::LayerSettings layerSettings;
3450                     bool prepared =
3451                             layer->prepareClientLayer(renderArea, clip, clearRegion,
3452                                                       supportProtectedContent, layerSettings);
3453                     if (prepared) {
3454                         clientCompositionLayers.push_back(layerSettings);
3455                     }
3456                     break;
3457                 }
3458                 default:
3459                     break;
3460             }
3461         } else {
3462             ALOGV("  Skipping for empty clip");
3463         }
3464         firstLayer = false;
3465     }
3466 
3467     // Perform some cleanup steps if we used client composition.
3468     if (hasClientComposition) {
3469         clientCompositionDisplay.clearRegion = clearRegion;
3470 
3471         // We boost GPU frequency here because there will be color spaces conversion
3472         // and it's expensive. We boost the GPU frequency so that GPU composition can
3473         // finish in time. We must reset GPU frequency afterwards, because high frequency
3474         // consumes extra battery.
3475         const bool expensiveRenderingExpected =
3476                 clientCompositionDisplay.outputDataspace == Dataspace::DISPLAY_P3;
3477         if (expensiveRenderingExpected && displayId) {
3478             mPowerAdvisor.setExpensiveRenderingExpected(*displayId, true);
3479         }
3480         if (!debugRegion.isEmpty()) {
3481             Region::const_iterator it = debugRegion.begin();
3482             Region::const_iterator end = debugRegion.end();
3483             while (it != end) {
3484                 const Rect& rect = *it++;
3485                 renderengine::LayerSettings layerSettings;
3486                 layerSettings.source.buffer.buffer = nullptr;
3487                 layerSettings.source.solidColor = half3(1.0, 0.0, 1.0);
3488                 layerSettings.geometry.boundaries = rect.toFloatRect();
3489                 layerSettings.alpha = half(1.0);
3490                 clientCompositionLayers.push_back(layerSettings);
3491             }
3492         }
3493         renderEngine.drawLayers(clientCompositionDisplay, clientCompositionLayers,
3494                                 buf->getNativeBuffer(), /*useFramebufferCache=*/true, std::move(fd),
3495                                 readyFence);
3496     } else if (displayId) {
3497         mPowerAdvisor.setExpensiveRenderingExpected(*displayId, false);
3498     }
3499     return true;
3500 }
3501 
drawWormhole(const Region & region) const3502 void SurfaceFlinger::drawWormhole(const Region& region) const {
3503     auto& engine(getRenderEngine());
3504     engine.fillRegionWithColor(region, 0, 0, 0, 0);
3505 }
3506 
addClientLayer(const sp<Client> & client,const sp<IBinder> & handle,const sp<IGraphicBufferProducer> & gbc,const sp<Layer> & lbc,const sp<IBinder> & parentHandle,const sp<Layer> & parentLayer,bool addToCurrentState)3507 status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
3508                                         const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
3509                                         const sp<IBinder>& parentHandle,
3510                                         const sp<Layer>& parentLayer, bool addToCurrentState) {
3511     // add this layer to the current state list
3512     {
3513         Mutex::Autolock _l(mStateLock);
3514         sp<Layer> parent;
3515         if (parentHandle != nullptr) {
3516             parent = fromHandle(parentHandle);
3517             if (parent == nullptr) {
3518                 return NAME_NOT_FOUND;
3519             }
3520         } else {
3521             parent = parentLayer;
3522         }
3523 
3524         if (mNumLayers >= MAX_LAYERS) {
3525             ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3526                   MAX_LAYERS);
3527             return NO_MEMORY;
3528         }
3529 
3530         mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
3531 
3532         if (parent == nullptr && addToCurrentState) {
3533             mCurrentState.layersSortedByZ.add(lbc);
3534         } else if (parent == nullptr) {
3535             lbc->onRemovedFromCurrentState();
3536         } else if (parent->isRemovedFromCurrentState()) {
3537             parent->addChild(lbc);
3538             lbc->onRemovedFromCurrentState();
3539         } else {
3540             parent->addChild(lbc);
3541         }
3542 
3543         if (gbc != nullptr) {
3544             mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3545             LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3546                                         mMaxGraphicBufferProducerListSize,
3547                                 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3548                                 mGraphicBufferProducerList.size(),
3549                                 mMaxGraphicBufferProducerListSize, mNumLayers);
3550         }
3551         mLayersAdded = true;
3552     }
3553 
3554     // attach this layer to the client
3555     client->attachLayer(handle, lbc);
3556 
3557     return NO_ERROR;
3558 }
3559 
peekTransactionFlags()3560 uint32_t SurfaceFlinger::peekTransactionFlags() {
3561     return mTransactionFlags;
3562 }
3563 
getTransactionFlags(uint32_t flags)3564 uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
3565     return mTransactionFlags.fetch_and(~flags) & flags;
3566 }
3567 
setTransactionFlags(uint32_t flags)3568 uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
3569     return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
3570 }
3571 
setTransactionFlags(uint32_t flags,Scheduler::TransactionStart transactionStart)3572 uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3573                                              Scheduler::TransactionStart transactionStart) {
3574     uint32_t old = mTransactionFlags.fetch_or(flags);
3575     mVsyncModulator.setTransactionStart(transactionStart);
3576     if ((old & flags)==0) { // wake the server up
3577         signalTransaction();
3578     }
3579     return old;
3580 }
3581 
flushTransactionQueues()3582 bool SurfaceFlinger::flushTransactionQueues() {
3583     // to prevent onHandleDestroyed from being called while the lock is held,
3584     // we must keep a copy of the transactions (specifically the composer
3585     // states) around outside the scope of the lock
3586     std::vector<const TransactionState> transactions;
3587     bool flushedATransaction = false;
3588     {
3589         Mutex::Autolock _l(mStateLock);
3590 
3591         auto it = mTransactionQueues.begin();
3592         while (it != mTransactionQueues.end()) {
3593             auto& [applyToken, transactionQueue] = *it;
3594 
3595             while (!transactionQueue.empty()) {
3596                 const auto& transaction = transactionQueue.front();
3597                 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
3598                                                    transaction.states)) {
3599                     setTransactionFlags(eTransactionFlushNeeded);
3600                     break;
3601                 }
3602                 transactions.push_back(transaction);
3603                 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
3604                                       mPendingInputWindowCommands, transaction.desiredPresentTime,
3605                                       transaction.buffer, transaction.callback,
3606                                       transaction.postTime, transaction.privileged,
3607                                       /*isMainThread*/ true);
3608                 transactionQueue.pop();
3609                 flushedATransaction = true;
3610             }
3611 
3612             if (transactionQueue.empty()) {
3613                 it = mTransactionQueues.erase(it);
3614                 mTransactionCV.broadcast();
3615             } else {
3616                 it = std::next(it, 1);
3617             }
3618         }
3619     }
3620     return flushedATransaction;
3621 }
3622 
transactionFlushNeeded()3623 bool SurfaceFlinger::transactionFlushNeeded() {
3624     return !mTransactionQueues.empty();
3625 }
3626 
containsAnyInvalidClientState(const Vector<ComposerState> & states)3627 bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3628     for (const ComposerState& state : states) {
3629         // Here we need to check that the interface we're given is indeed
3630         // one of our own. A malicious client could give us a nullptr
3631         // IInterface, or one of its own or even one of our own but a
3632         // different type. All these situations would cause us to crash.
3633         if (state.client == nullptr) {
3634             return true;
3635         }
3636 
3637         sp<IBinder> binder = IInterface::asBinder(state.client);
3638         if (binder == nullptr) {
3639             return true;
3640         }
3641 
3642         if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3643             return true;
3644         }
3645     }
3646     return false;
3647 }
3648 
transactionIsReadyToBeApplied(int64_t desiredPresentTime,const Vector<ComposerState> & states)3649 bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3650                                                    const Vector<ComposerState>& states) {
3651     nsecs_t expectedPresentTime = mScheduler->expectedPresentTime();
3652     // Do not present if the desiredPresentTime has not passed unless it is more than one second
3653     // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3654     if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3655         desiredPresentTime < expectedPresentTime + s2ns(1)) {
3656         return false;
3657     }
3658 
3659     for (const ComposerState& state : states) {
3660         const layer_state_t& s = state.state;
3661         if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3662             continue;
3663         }
3664         if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
3665             return false;
3666         }
3667     }
3668     return true;
3669 }
3670 
setTransactionState(const Vector<ComposerState> & states,const Vector<DisplayState> & displays,uint32_t flags,const sp<IBinder> & applyToken,const InputWindowCommands & inputWindowCommands,int64_t desiredPresentTime,const client_cache_t & uncacheBuffer,const std::vector<ListenerCallbacks> & listenerCallbacks)3671 void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3672                                          const Vector<DisplayState>& displays, uint32_t flags,
3673                                          const sp<IBinder>& applyToken,
3674                                          const InputWindowCommands& inputWindowCommands,
3675                                          int64_t desiredPresentTime,
3676                                          const client_cache_t& uncacheBuffer,
3677                                          const std::vector<ListenerCallbacks>& listenerCallbacks) {
3678     ATRACE_CALL();
3679 
3680     const int64_t postTime = systemTime();
3681 
3682     bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3683 
3684     Mutex::Autolock _l(mStateLock);
3685 
3686     if (containsAnyInvalidClientState(states)) {
3687         return;
3688     }
3689 
3690     // If its TransactionQueue already has a pending TransactionState or if it is pending
3691     auto itr = mTransactionQueues.find(applyToken);
3692     // if this is an animation frame, wait until prior animation frame has
3693     // been applied by SF
3694     if (flags & eAnimation) {
3695         while (itr != mTransactionQueues.end()) {
3696             status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3697             if (CC_UNLIKELY(err != NO_ERROR)) {
3698                 ALOGW_IF(err == TIMED_OUT,
3699                          "setTransactionState timed out "
3700                          "waiting for animation frame to apply");
3701                 break;
3702             }
3703             itr = mTransactionQueues.find(applyToken);
3704         }
3705     }
3706     if (itr != mTransactionQueues.end() ||
3707         !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
3708         mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
3709                                                uncacheBuffer, listenerCallbacks, postTime,
3710                                                privileged);
3711         setTransactionFlags(eTransactionFlushNeeded);
3712         return;
3713     }
3714 
3715     applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
3716                           uncacheBuffer, listenerCallbacks, postTime, privileged);
3717 }
3718 
applyTransactionState(const Vector<ComposerState> & states,const Vector<DisplayState> & displays,uint32_t flags,const InputWindowCommands & inputWindowCommands,const int64_t desiredPresentTime,const client_cache_t & uncacheBuffer,const std::vector<ListenerCallbacks> & listenerCallbacks,const int64_t postTime,bool privileged,bool isMainThread)3719 void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
3720                                            const Vector<DisplayState>& displays, uint32_t flags,
3721                                            const InputWindowCommands& inputWindowCommands,
3722                                            const int64_t desiredPresentTime,
3723                                            const client_cache_t& uncacheBuffer,
3724                                            const std::vector<ListenerCallbacks>& listenerCallbacks,
3725                                            const int64_t postTime, bool privileged,
3726                                            bool isMainThread) {
3727     uint32_t transactionFlags = 0;
3728 
3729     if (flags & eAnimation) {
3730         // For window updates that are part of an animation we must wait for
3731         // previous animation "frames" to be handled.
3732         while (!isMainThread && mAnimTransactionPending) {
3733             status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3734             if (CC_UNLIKELY(err != NO_ERROR)) {
3735                 // just in case something goes wrong in SF, return to the
3736                 // caller after a few seconds.
3737                 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3738                         "waiting for previous animation frame");
3739                 mAnimTransactionPending = false;
3740                 break;
3741             }
3742         }
3743     }
3744 
3745     for (const DisplayState& display : displays) {
3746         transactionFlags |= setDisplayStateLocked(display);
3747     }
3748 
3749     // In case the client has sent a Transaction that should receive callbacks but without any
3750     // SurfaceControls that should be included in the callback, send the listener and callbackIds
3751     // to the callback thread so it can send an empty callback
3752     if (!listenerCallbacks.empty()) {
3753         mTransactionCompletedThread.run();
3754     }
3755     for (const auto& [listener, callbackIds] : listenerCallbacks) {
3756         mTransactionCompletedThread.addCallback(listener, callbackIds);
3757     }
3758 
3759     uint32_t clientStateFlags = 0;
3760     for (const ComposerState& state : states) {
3761         clientStateFlags |= setClientStateLocked(state, desiredPresentTime, listenerCallbacks,
3762                                                  postTime, privileged);
3763     }
3764 
3765     // If the state doesn't require a traversal and there are callbacks, send them now
3766     if (!(clientStateFlags & eTraversalNeeded) && !listenerCallbacks.empty()) {
3767         mTransactionCompletedThread.sendCallbacks();
3768     }
3769     transactionFlags |= clientStateFlags;
3770 
3771     transactionFlags |= addInputWindowCommands(inputWindowCommands);
3772 
3773     if (uncacheBuffer.isValid()) {
3774         ClientCache::getInstance().erase(uncacheBuffer);
3775     }
3776 
3777     // If a synchronous transaction is explicitly requested without any changes, force a transaction
3778     // anyway. This can be used as a flush mechanism for previous async transactions.
3779     // Empty animation transaction can be used to simulate back-pressure, so also force a
3780     // transaction for empty animation transactions.
3781     if (transactionFlags == 0 &&
3782             ((flags & eSynchronous) || (flags & eAnimation))) {
3783         transactionFlags = eTransactionNeeded;
3784     }
3785 
3786     // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3787     // so we don't have to wake up again next frame to preform an uneeded traversal.
3788     if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3789         transactionFlags = transactionFlags & (~eTraversalNeeded);
3790         mTraversalNeededMainThread = true;
3791     }
3792 
3793     if (transactionFlags) {
3794         if (mInterceptor->isEnabled()) {
3795             mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
3796         }
3797 
3798         // this triggers the transaction
3799         const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3800                                                   : Scheduler::TransactionStart::NORMAL;
3801         setTransactionFlags(transactionFlags, start);
3802 
3803         // if this is a synchronous transaction, wait for it to take effect
3804         // before returning.
3805         if (flags & eSynchronous) {
3806             mTransactionPending = true;
3807         }
3808         if (flags & eAnimation) {
3809             mAnimTransactionPending = true;
3810         }
3811         if (mPendingInputWindowCommands.syncInputWindows) {
3812             mPendingSyncInputWindows = true;
3813         }
3814 
3815         // applyTransactionState can be called by either the main SF thread or by
3816         // another process through setTransactionState.  While a given process may wish
3817         // to wait on synchronous transactions, the main SF thread should never
3818         // be blocked.  Therefore, we only wait if isMainThread is false.
3819         while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
3820             status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3821             if (CC_UNLIKELY(err != NO_ERROR)) {
3822                 // just in case something goes wrong in SF, return to the
3823                 // called after a few seconds.
3824                 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3825                 mTransactionPending = false;
3826                 mPendingSyncInputWindows = false;
3827                 break;
3828             }
3829         }
3830     }
3831 }
3832 
setDisplayStateLocked(const DisplayState & s)3833 uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3834     const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3835     if (index < 0) return 0;
3836 
3837     uint32_t flags = 0;
3838     DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3839 
3840     const uint32_t what = s.what;
3841     if (what & DisplayState::eSurfaceChanged) {
3842         if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3843             state.surface = s.surface;
3844             flags |= eDisplayTransactionNeeded;
3845         }
3846     }
3847     if (what & DisplayState::eLayerStackChanged) {
3848         if (state.layerStack != s.layerStack) {
3849             state.layerStack = s.layerStack;
3850             flags |= eDisplayTransactionNeeded;
3851         }
3852     }
3853     if (what & DisplayState::eDisplayProjectionChanged) {
3854         if (state.orientation != s.orientation) {
3855             state.orientation = s.orientation;
3856             flags |= eDisplayTransactionNeeded;
3857         }
3858         if (state.frame != s.frame) {
3859             state.frame = s.frame;
3860             flags |= eDisplayTransactionNeeded;
3861         }
3862         if (state.viewport != s.viewport) {
3863             state.viewport = s.viewport;
3864             flags |= eDisplayTransactionNeeded;
3865         }
3866     }
3867     if (what & DisplayState::eDisplaySizeChanged) {
3868         if (state.width != s.width) {
3869             state.width = s.width;
3870             flags |= eDisplayTransactionNeeded;
3871         }
3872         if (state.height != s.height) {
3873             state.height = s.height;
3874             flags |= eDisplayTransactionNeeded;
3875         }
3876     }
3877 
3878     return flags;
3879 }
3880 
callingThreadHasUnscopedSurfaceFlingerAccess()3881 bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
3882     IPCThreadState* ipc = IPCThreadState::self();
3883     const int pid = ipc->getCallingPid();
3884     const int uid = ipc->getCallingUid();
3885     if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
3886         !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
3887         return false;
3888     }
3889     return true;
3890 }
3891 
setClientStateLocked(const ComposerState & composerState,int64_t desiredPresentTime,const std::vector<ListenerCallbacks> & listenerCallbacks,int64_t postTime,bool privileged)3892 uint32_t SurfaceFlinger::setClientStateLocked(
3893         const ComposerState& composerState, int64_t desiredPresentTime,
3894         const std::vector<ListenerCallbacks>& listenerCallbacks, int64_t postTime,
3895         bool privileged) {
3896     const layer_state_t& s = composerState.state;
3897     sp<Client> client(static_cast<Client*>(composerState.client.get()));
3898 
3899     sp<Layer> layer(client->getLayerUser(s.surface));
3900     if (layer == nullptr) {
3901         return 0;
3902     }
3903 
3904     uint32_t flags = 0;
3905 
3906     const uint64_t what = s.what;
3907     bool geometryAppliesWithResize =
3908             what & layer_state_t::eGeometryAppliesWithResize;
3909 
3910     // If we are deferring transaction, make sure to push the pending state, as otherwise the
3911     // pending state will also be deferred.
3912     if (what & layer_state_t::eDeferTransaction_legacy) {
3913         layer->pushPendingState();
3914     }
3915 
3916     if (what & layer_state_t::ePositionChanged) {
3917         if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3918             flags |= eTraversalNeeded;
3919         }
3920     }
3921     if (what & layer_state_t::eLayerChanged) {
3922         // NOTE: index needs to be calculated before we update the state
3923         const auto& p = layer->getParent();
3924         if (p == nullptr) {
3925             ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3926             if (layer->setLayer(s.z) && idx >= 0) {
3927                 mCurrentState.layersSortedByZ.removeAt(idx);
3928                 mCurrentState.layersSortedByZ.add(layer);
3929                 // we need traversal (state changed)
3930                 // AND transaction (list changed)
3931                 flags |= eTransactionNeeded|eTraversalNeeded;
3932             }
3933         } else {
3934             if (p->setChildLayer(layer, s.z)) {
3935                 flags |= eTransactionNeeded|eTraversalNeeded;
3936             }
3937         }
3938     }
3939     if (what & layer_state_t::eRelativeLayerChanged) {
3940         // NOTE: index needs to be calculated before we update the state
3941         const auto& p = layer->getParent();
3942         if (p == nullptr) {
3943             ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3944             if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3945                 mCurrentState.layersSortedByZ.removeAt(idx);
3946                 mCurrentState.layersSortedByZ.add(layer);
3947                 // we need traversal (state changed)
3948                 // AND transaction (list changed)
3949                 flags |= eTransactionNeeded|eTraversalNeeded;
3950             }
3951         } else {
3952             if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3953                 flags |= eTransactionNeeded|eTraversalNeeded;
3954             }
3955         }
3956     }
3957     if (what & layer_state_t::eSizeChanged) {
3958         if (layer->setSize(s.w, s.h)) {
3959             flags |= eTraversalNeeded;
3960         }
3961     }
3962     if (what & layer_state_t::eAlphaChanged) {
3963         if (layer->setAlpha(s.alpha))
3964             flags |= eTraversalNeeded;
3965     }
3966     if (what & layer_state_t::eColorChanged) {
3967         if (layer->setColor(s.color))
3968             flags |= eTraversalNeeded;
3969     }
3970     if (what & layer_state_t::eColorTransformChanged) {
3971         if (layer->setColorTransform(s.colorTransform)) {
3972             flags |= eTraversalNeeded;
3973         }
3974     }
3975     if (what & layer_state_t::eBackgroundColorChanged) {
3976         if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3977             flags |= eTraversalNeeded;
3978         }
3979     }
3980     if (what & layer_state_t::eMatrixChanged) {
3981         // TODO: b/109894387
3982         //
3983         // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3984         // rotation. To see the problem observe that if we have a square parent, and a child
3985         // of the same size, then we rotate the child 45 degrees around it's center, the child
3986         // must now be cropped to a non rectangular 8 sided region.
3987         //
3988         // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3989         // private API, and the WindowManager only uses rotation in one case, which is on a top
3990         // level layer in which cropping is not an issue.
3991         //
3992         // However given that abuse of rotation matrices could lead to surfaces extending outside
3993         // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3994         // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3995         // transformations.
3996         if (layer->setMatrix(s.matrix, privileged))
3997             flags |= eTraversalNeeded;
3998     }
3999     if (what & layer_state_t::eTransparentRegionChanged) {
4000         if (layer->setTransparentRegionHint(s.transparentRegion))
4001             flags |= eTraversalNeeded;
4002     }
4003     if (what & layer_state_t::eFlagsChanged) {
4004         if (layer->setFlags(s.flags, s.mask))
4005             flags |= eTraversalNeeded;
4006     }
4007     if (what & layer_state_t::eCropChanged_legacy) {
4008         if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
4009             flags |= eTraversalNeeded;
4010     }
4011     if (what & layer_state_t::eCornerRadiusChanged) {
4012         if (layer->setCornerRadius(s.cornerRadius))
4013             flags |= eTraversalNeeded;
4014     }
4015     if (what & layer_state_t::eLayerStackChanged) {
4016         ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
4017         // We only allow setting layer stacks for top level layers,
4018         // everything else inherits layer stack from its parent.
4019         if (layer->hasParent()) {
4020             ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
4021                     layer->getName().string());
4022         } else if (idx < 0) {
4023             ALOGE("Attempt to set layer stack on layer without parent (%s) that "
4024                     "that also does not appear in the top level layer list. Something"
4025                     " has gone wrong.", layer->getName().string());
4026         } else if (layer->setLayerStack(s.layerStack)) {
4027             mCurrentState.layersSortedByZ.removeAt(idx);
4028             mCurrentState.layersSortedByZ.add(layer);
4029             // we need traversal (state changed)
4030             // AND transaction (list changed)
4031             flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
4032         }
4033     }
4034     if (what & layer_state_t::eDeferTransaction_legacy) {
4035         if (s.barrierHandle_legacy != nullptr) {
4036             layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
4037         } else if (s.barrierGbp_legacy != nullptr) {
4038             const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
4039             if (authenticateSurfaceTextureLocked(gbp)) {
4040                 const auto& otherLayer =
4041                     (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
4042                 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
4043             } else {
4044                 ALOGE("Attempt to defer transaction to to an"
4045                         " unrecognized GraphicBufferProducer");
4046             }
4047         }
4048         // We don't trigger a traversal here because if no other state is
4049         // changed, we don't want this to cause any more work
4050     }
4051     if (what & layer_state_t::eReparent) {
4052         bool hadParent = layer->hasParent();
4053         if (layer->reparent(s.parentHandleForChild)) {
4054             if (!hadParent) {
4055                 mCurrentState.layersSortedByZ.remove(layer);
4056             }
4057             flags |= eTransactionNeeded|eTraversalNeeded;
4058         }
4059     }
4060     if (what & layer_state_t::eReparentChildren) {
4061         if (layer->reparentChildren(s.reparentHandle)) {
4062             flags |= eTransactionNeeded|eTraversalNeeded;
4063         }
4064     }
4065     if (what & layer_state_t::eDetachChildren) {
4066         layer->detachChildren();
4067     }
4068     if (what & layer_state_t::eOverrideScalingModeChanged) {
4069         layer->setOverrideScalingMode(s.overrideScalingMode);
4070         // We don't trigger a traversal here because if no other state is
4071         // changed, we don't want this to cause any more work
4072     }
4073     if (what & layer_state_t::eTransformChanged) {
4074         if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
4075     }
4076     if (what & layer_state_t::eTransformToDisplayInverseChanged) {
4077         if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
4078             flags |= eTraversalNeeded;
4079     }
4080     if (what & layer_state_t::eCropChanged) {
4081         if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
4082     }
4083     if (what & layer_state_t::eFrameChanged) {
4084         if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
4085     }
4086     if (what & layer_state_t::eAcquireFenceChanged) {
4087         if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
4088     }
4089     if (what & layer_state_t::eDataspaceChanged) {
4090         if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
4091     }
4092     if (what & layer_state_t::eHdrMetadataChanged) {
4093         if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
4094     }
4095     if (what & layer_state_t::eSurfaceDamageRegionChanged) {
4096         if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
4097     }
4098     if (what & layer_state_t::eApiChanged) {
4099         if (layer->setApi(s.api)) flags |= eTraversalNeeded;
4100     }
4101     if (what & layer_state_t::eSidebandStreamChanged) {
4102         if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
4103     }
4104     if (what & layer_state_t::eInputInfoChanged) {
4105         if (privileged) {
4106             layer->setInputInfo(s.inputInfo);
4107             flags |= eTraversalNeeded;
4108         } else {
4109             ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
4110         }
4111     }
4112     if (what & layer_state_t::eMetadataChanged) {
4113         if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
4114     }
4115     if (what & layer_state_t::eColorSpaceAgnosticChanged) {
4116         if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
4117             flags |= eTraversalNeeded;
4118         }
4119     }
4120     std::vector<sp<CallbackHandle>> callbackHandles;
4121     if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!listenerCallbacks.empty())) {
4122         for (const auto& [listener, callbackIds] : listenerCallbacks) {
4123             callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
4124         }
4125     }
4126     bool bufferChanged = what & layer_state_t::eBufferChanged;
4127     bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
4128     sp<GraphicBuffer> buffer;
4129     if (bufferChanged && cacheIdChanged) {
4130         ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
4131         buffer = s.buffer;
4132     } else if (cacheIdChanged) {
4133         buffer = ClientCache::getInstance().get(s.cachedBuffer);
4134     } else if (bufferChanged) {
4135         buffer = s.buffer;
4136     }
4137     if (buffer) {
4138         if (layer->setBuffer(buffer, postTime, desiredPresentTime, s.cachedBuffer)) {
4139             flags |= eTraversalNeeded;
4140         }
4141     }
4142     if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
4143     // Do not put anything that updates layer state or modifies flags after
4144     // setTransactionCompletedListener
4145     return flags;
4146 }
4147 
addInputWindowCommands(const InputWindowCommands & inputWindowCommands)4148 uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
4149     uint32_t flags = 0;
4150     if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
4151         flags |= eTraversalNeeded;
4152     }
4153 
4154     if (inputWindowCommands.syncInputWindows) {
4155         flags |= eTraversalNeeded;
4156     }
4157 
4158     mPendingInputWindowCommands.merge(inputWindowCommands);
4159     return flags;
4160 }
4161 
createLayer(const String8 & name,const sp<Client> & client,uint32_t w,uint32_t h,PixelFormat format,uint32_t flags,LayerMetadata metadata,sp<IBinder> * handle,sp<IGraphicBufferProducer> * gbp,const sp<IBinder> & parentHandle,const sp<Layer> & parentLayer)4162 status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
4163                                      uint32_t h, PixelFormat format, uint32_t flags,
4164                                      LayerMetadata metadata, sp<IBinder>* handle,
4165                                      sp<IGraphicBufferProducer>* gbp,
4166                                      const sp<IBinder>& parentHandle,
4167                                      const sp<Layer>& parentLayer) {
4168     if (int32_t(w|h) < 0) {
4169         ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
4170                 int(w), int(h));
4171         return BAD_VALUE;
4172     }
4173 
4174     ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
4175             "Expected only one of parentLayer or parentHandle to be non-null. "
4176             "Programmer error?");
4177 
4178     status_t result = NO_ERROR;
4179 
4180     sp<Layer> layer;
4181 
4182     String8 uniqueName = getUniqueLayerName(name);
4183 
4184     bool primaryDisplayOnly = false;
4185 
4186     // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
4187     // TODO b/64227542
4188     if (metadata.has(METADATA_WINDOW_TYPE)) {
4189         int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
4190         if (windowType == 441731) {
4191             metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
4192             primaryDisplayOnly = true;
4193         }
4194     }
4195 
4196     switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
4197         case ISurfaceComposerClient::eFXSurfaceBufferQueue:
4198             result = createBufferQueueLayer(client, uniqueName, w, h, flags, std::move(metadata),
4199                                             format, handle, gbp, &layer);
4200 
4201             break;
4202         case ISurfaceComposerClient::eFXSurfaceBufferState:
4203             result = createBufferStateLayer(client, uniqueName, w, h, flags, std::move(metadata),
4204                                             handle, &layer);
4205             break;
4206         case ISurfaceComposerClient::eFXSurfaceColor:
4207             // check if buffer size is set for color layer.
4208             if (w > 0 || h > 0) {
4209                 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
4210                       int(w), int(h));
4211                 return BAD_VALUE;
4212             }
4213 
4214             result = createColorLayer(client, uniqueName, w, h, flags, std::move(metadata), handle,
4215                                       &layer);
4216             break;
4217         case ISurfaceComposerClient::eFXSurfaceContainer:
4218             // check if buffer size is set for container layer.
4219             if (w > 0 || h > 0) {
4220                 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
4221                       int(w), int(h));
4222                 return BAD_VALUE;
4223             }
4224             result = createContainerLayer(client, uniqueName, w, h, flags, std::move(metadata),
4225                                           handle, &layer);
4226             break;
4227         default:
4228             result = BAD_VALUE;
4229             break;
4230     }
4231 
4232     if (result != NO_ERROR) {
4233         return result;
4234     }
4235 
4236     if (primaryDisplayOnly) {
4237         layer->setPrimaryDisplayOnly();
4238     }
4239 
4240     bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
4241     result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
4242                             addToCurrentState);
4243     if (result != NO_ERROR) {
4244         return result;
4245     }
4246     mInterceptor->saveSurfaceCreation(layer);
4247 
4248     setTransactionFlags(eTransactionNeeded);
4249     return result;
4250 }
4251 
getUniqueLayerName(const String8 & name)4252 String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4253 {
4254     bool matchFound = true;
4255     uint32_t dupeCounter = 0;
4256 
4257     // Tack on our counter whether there is a hit or not, so everyone gets a tag
4258     String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4259 
4260     // Grab the state lock since we're accessing mCurrentState
4261     Mutex::Autolock lock(mStateLock);
4262 
4263     // Loop over layers until we're sure there is no matching name
4264     while (matchFound) {
4265         matchFound = false;
4266         mCurrentState.traverseInZOrder([&](Layer* layer) {
4267             if (layer->getName() == uniqueName) {
4268                 matchFound = true;
4269                 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4270             }
4271         });
4272     }
4273 
4274     ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4275              uniqueName.c_str());
4276 
4277     return uniqueName;
4278 }
4279 
createBufferQueueLayer(const sp<Client> & client,const String8 & name,uint32_t w,uint32_t h,uint32_t flags,LayerMetadata metadata,PixelFormat & format,sp<IBinder> * handle,sp<IGraphicBufferProducer> * gbp,sp<Layer> * outLayer)4280 status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4281                                                 uint32_t w, uint32_t h, uint32_t flags,
4282                                                 LayerMetadata metadata, PixelFormat& format,
4283                                                 sp<IBinder>* handle,
4284                                                 sp<IGraphicBufferProducer>* gbp,
4285                                                 sp<Layer>* outLayer) {
4286     // initialize the surfaces
4287     switch (format) {
4288     case PIXEL_FORMAT_TRANSPARENT:
4289     case PIXEL_FORMAT_TRANSLUCENT:
4290         format = PIXEL_FORMAT_RGBA_8888;
4291         break;
4292     case PIXEL_FORMAT_OPAQUE:
4293         format = PIXEL_FORMAT_RGBX_8888;
4294         break;
4295     }
4296 
4297     sp<BufferQueueLayer> layer = getFactory().createBufferQueueLayer(
4298             LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
4299     status_t err = layer->setDefaultBufferProperties(w, h, format);
4300     if (err == NO_ERROR) {
4301         *handle = layer->getHandle();
4302         *gbp = layer->getProducer();
4303         *outLayer = layer;
4304     }
4305 
4306     ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
4307     return err;
4308 }
4309 
createBufferStateLayer(const sp<Client> & client,const String8 & name,uint32_t w,uint32_t h,uint32_t flags,LayerMetadata metadata,sp<IBinder> * handle,sp<Layer> * outLayer)4310 status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4311                                                 uint32_t w, uint32_t h, uint32_t flags,
4312                                                 LayerMetadata metadata, sp<IBinder>* handle,
4313                                                 sp<Layer>* outLayer) {
4314     sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(
4315             LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
4316     *handle = layer->getHandle();
4317     *outLayer = layer;
4318 
4319     return NO_ERROR;
4320 }
4321 
createColorLayer(const sp<Client> & client,const String8 & name,uint32_t w,uint32_t h,uint32_t flags,LayerMetadata metadata,sp<IBinder> * handle,sp<Layer> * outLayer)4322 status_t SurfaceFlinger::createColorLayer(const sp<Client>& client, const String8& name, uint32_t w,
4323                                           uint32_t h, uint32_t flags, LayerMetadata metadata,
4324                                           sp<IBinder>* handle, sp<Layer>* outLayer) {
4325     *outLayer = getFactory().createColorLayer(
4326             LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
4327     *handle = (*outLayer)->getHandle();
4328     return NO_ERROR;
4329 }
4330 
createContainerLayer(const sp<Client> & client,const String8 & name,uint32_t w,uint32_t h,uint32_t flags,LayerMetadata metadata,sp<IBinder> * handle,sp<Layer> * outLayer)4331 status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, const String8& name,
4332                                               uint32_t w, uint32_t h, uint32_t flags,
4333                                               LayerMetadata metadata, sp<IBinder>* handle,
4334                                               sp<Layer>* outLayer) {
4335     *outLayer = getFactory().createContainerLayer(
4336             LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
4337     *handle = (*outLayer)->getHandle();
4338     return NO_ERROR;
4339 }
4340 
4341 
markLayerPendingRemovalLocked(const sp<Layer> & layer)4342 void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
4343     mLayersPendingRemoval.add(layer);
4344     mLayersRemoved = true;
4345     setTransactionFlags(eTransactionNeeded);
4346 }
4347 
onHandleDestroyed(sp<Layer> & layer)4348 void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
4349 {
4350     Mutex::Autolock lock(mStateLock);
4351     // If a layer has a parent, we allow it to out-live it's handle
4352     // with the idea that the parent holds a reference and will eventually
4353     // be cleaned up. However no one cleans up the top-level so we do so
4354     // here.
4355     if (layer->getParent() == nullptr) {
4356         mCurrentState.layersSortedByZ.remove(layer);
4357     }
4358     markLayerPendingRemovalLocked(layer);
4359 
4360     auto it = mLayersByLocalBinderToken.begin();
4361     while (it != mLayersByLocalBinderToken.end()) {
4362         if (it->second == layer) {
4363             it = mLayersByLocalBinderToken.erase(it);
4364         } else {
4365             it++;
4366         }
4367     }
4368 
4369     layer.clear();
4370 }
4371 
4372 // ---------------------------------------------------------------------------
4373 
onInitializeDisplays()4374 void SurfaceFlinger::onInitializeDisplays() {
4375     const auto display = getDefaultDisplayDeviceLocked();
4376     if (!display) return;
4377 
4378     const sp<IBinder> token = display->getDisplayToken().promote();
4379     LOG_ALWAYS_FATAL_IF(token == nullptr);
4380 
4381     // reset screen orientation and use primary layer stack
4382     Vector<ComposerState> state;
4383     Vector<DisplayState> displays;
4384     DisplayState d;
4385     d.what = DisplayState::eDisplayProjectionChanged |
4386              DisplayState::eLayerStackChanged;
4387     d.token = token;
4388     d.layerStack = 0;
4389     d.orientation = DisplayState::eOrientationDefault;
4390     d.frame.makeInvalid();
4391     d.viewport.makeInvalid();
4392     d.width = 0;
4393     d.height = 0;
4394     displays.add(d);
4395     setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, {});
4396 
4397     setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
4398 
4399     const nsecs_t vsyncPeriod = getVsyncPeriod();
4400     mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
4401 
4402     // Use phase of 0 since phase is not known.
4403     // Use latency of 0, which will snap to the ideal latency.
4404     DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
4405     setCompositorTimingSnapped(stats, 0);
4406 }
4407 
initializeDisplays()4408 void SurfaceFlinger::initializeDisplays() {
4409     // Async since we may be called from the main thread.
4410     postMessageAsync(
4411             new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
4412 }
4413 
setPowerModeInternal(const sp<DisplayDevice> & display,int mode)4414 void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
4415     if (display->isVirtual()) {
4416         ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
4417         return;
4418     }
4419 
4420     const auto displayId = display->getId();
4421     LOG_ALWAYS_FATAL_IF(!displayId);
4422 
4423     ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
4424 
4425     int currentMode = display->getPowerMode();
4426     if (mode == currentMode) {
4427         return;
4428     }
4429 
4430     display->setPowerMode(mode);
4431 
4432     if (mInterceptor->isEnabled()) {
4433         mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
4434     }
4435 
4436     if (currentMode == HWC_POWER_MODE_OFF) {
4437         // Turn on the display
4438         getHwComposer().setPowerMode(*displayId, mode);
4439         if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
4440             mScheduler->onScreenAcquired(mAppConnectionHandle);
4441             mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
4442         }
4443 
4444         mVisibleRegionsDirty = true;
4445         mHasPoweredOff = true;
4446         repaintEverything();
4447 
4448         struct sched_param param = {0};
4449         param.sched_priority = 1;
4450         if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4451             ALOGW("Couldn't set SCHED_FIFO on display on");
4452         }
4453     } else if (mode == HWC_POWER_MODE_OFF) {
4454         // Turn off the display
4455         struct sched_param param = {0};
4456         if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4457             ALOGW("Couldn't set SCHED_OTHER on display off");
4458         }
4459 
4460         if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
4461             mScheduler->disableHardwareVsync(true);
4462             mScheduler->onScreenReleased(mAppConnectionHandle);
4463         }
4464 
4465         getHwComposer().setPowerMode(*displayId, mode);
4466         mVisibleRegionsDirty = true;
4467         // from this point on, SF will stop drawing on this display
4468     } else if (mode == HWC_POWER_MODE_DOZE ||
4469                mode == HWC_POWER_MODE_NORMAL) {
4470         // Update display while dozing
4471         getHwComposer().setPowerMode(*displayId, mode);
4472         if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
4473             mScheduler->onScreenAcquired(mAppConnectionHandle);
4474             mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
4475         }
4476     } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4477         // Leave display going to doze
4478         if (display->isPrimary()) {
4479             mScheduler->disableHardwareVsync(true);
4480             mScheduler->onScreenReleased(mAppConnectionHandle);
4481         }
4482         getHwComposer().setPowerMode(*displayId, mode);
4483     } else {
4484         ALOGE("Attempting to set unknown power mode: %d\n", mode);
4485         getHwComposer().setPowerMode(*displayId, mode);
4486     }
4487 
4488     if (display->isPrimary()) {
4489         mTimeStats->setPowerMode(mode);
4490         mRefreshRateStats.setPowerMode(mode);
4491     }
4492 
4493     ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
4494 }
4495 
setPowerMode(const sp<IBinder> & displayToken,int mode)4496 void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
4497     postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
4498         const auto display = getDisplayDevice(displayToken);
4499         if (!display) {
4500             ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4501                   displayToken.get());
4502         } else if (display->isVirtual()) {
4503             ALOGW("Attempt to set power mode %d for virtual display", mode);
4504         } else {
4505             setPowerModeInternal(display, mode);
4506         }
4507     }));
4508 }
4509 
4510 // ---------------------------------------------------------------------------
4511 
doDump(int fd,const DumpArgs & args,bool asProto)4512 status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4513                                 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
4514     std::string result;
4515 
4516     IPCThreadState* ipc = IPCThreadState::self();
4517     const int pid = ipc->getCallingPid();
4518     const int uid = ipc->getCallingUid();
4519 
4520     if ((uid != AID_SHELL) &&
4521             !PermissionCache::checkPermission(sDump, pid, uid)) {
4522         StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4523                       pid, uid);
4524     } else {
4525         // Try to get the main lock, but give up after one second
4526         // (this would indicate SF is stuck, but we want to be able to
4527         // print something in dumpsys).
4528         status_t err = mStateLock.timedLock(s2ns(1));
4529         bool locked = (err == NO_ERROR);
4530         if (!locked) {
4531             StringAppendF(&result,
4532                           "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4533                           "(no locks held)\n",
4534                           strerror(-err), err);
4535         }
4536 
4537         using namespace std::string_literals;
4538 
4539         static const std::unordered_map<std::string, Dumper> dumpers = {
4540                 {"--clear-layer-stats"s, dumper([this](std::string&) { mLayerStats.clear(); })},
4541                 {"--disable-layer-stats"s, dumper([this](std::string&) { mLayerStats.disable(); })},
4542                 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
4543                 {"--dispsync"s, dumper([this](std::string& s) {
4544                          mScheduler->dumpPrimaryDispSync(s);
4545                  })},
4546                 {"--dump-layer-stats"s, dumper([this](std::string& s) { mLayerStats.dump(s); })},
4547                 {"--enable-layer-stats"s, dumper([this](std::string&) { mLayerStats.enable(); })},
4548                 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4549                 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4550                 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4551                 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4552                 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4553                 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
4554                 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
4555                 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4556         };
4557 
4558         const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
4559 
4560         if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4561             (it->second)(args, asProto, result);
4562         } else {
4563             if (asProto) {
4564                 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4565                 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4566             } else {
4567                 dumpAllLocked(args, result);
4568             }
4569         }
4570 
4571         if (locked) {
4572             mStateLock.unlock();
4573         }
4574     }
4575     write(fd, result.c_str(), result.size());
4576     return NO_ERROR;
4577 }
4578 
dumpCritical(int fd,const DumpArgs &,bool asProto)4579 status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4580     if (asProto && mTracing.isEnabled()) {
4581         mTracing.writeToFileAsync();
4582     }
4583 
4584     return doDump(fd, DumpArgs(), asProto);
4585 }
4586 
listLayersLocked(std::string & result) const4587 void SurfaceFlinger::listLayersLocked(std::string& result) const {
4588     mCurrentState.traverseInZOrder(
4589             [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
4590 }
4591 
dumpStatsLocked(const DumpArgs & args,std::string & result) const4592 void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
4593     StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
4594 
4595     if (args.size() > 1) {
4596         const auto name = String8(args[1]);
4597         mCurrentState.traverseInZOrder([&](Layer* layer) {
4598             if (name == layer->getName()) {
4599                 layer->dumpFrameStats(result);
4600             }
4601         });
4602     } else {
4603         mAnimFrameTracker.dumpStats(result);
4604     }
4605 }
4606 
clearStatsLocked(const DumpArgs & args,std::string &)4607 void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
4608     mCurrentState.traverseInZOrder([&](Layer* layer) {
4609         if (args.size() < 2 || String8(args[1]) == layer->getName()) {
4610             layer->clearFrameStats();
4611         }
4612     });
4613 
4614     mAnimFrameTracker.clearStats();
4615 }
4616 
dumpTimeStats(const DumpArgs & args,bool asProto,std::string & result) const4617 void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4618     mTimeStats->parseArgs(asProto, args, result);
4619 }
4620 
4621 // This should only be called from the main thread.  Otherwise it would need
4622 // the lock and should use mCurrentState rather than mDrawingState.
logFrameStats()4623 void SurfaceFlinger::logFrameStats() {
4624     mDrawingState.traverseInZOrder([&](Layer* layer) {
4625         layer->logFrameStats();
4626     });
4627 
4628     mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4629 }
4630 
appendSfConfigString(std::string & result) const4631 void SurfaceFlinger::appendSfConfigString(std::string& result) const {
4632     result.append(" [sf");
4633 
4634     if (isLayerTripleBufferingDisabled())
4635         result.append(" DISABLE_TRIPLE_BUFFERING");
4636 
4637     StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4638     StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4639     StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4640     StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4641     StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4642                   maxFrameBufferAcquiredBuffers);
4643     result.append("]");
4644 }
4645 
dumpVSync(std::string & result) const4646 void SurfaceFlinger::dumpVSync(std::string& result) const {
4647     mPhaseOffsets->dump(result);
4648     StringAppendF(&result,
4649                   "    present offset: %9" PRId64 " ns\t     VSYNC period: %9" PRId64 " ns\n\n",
4650                   dispSyncPresentTimeOffset, getVsyncPeriod());
4651 
4652     StringAppendF(&result, "Scheduler enabled.");
4653     StringAppendF(&result, "+  Smart 90 for video detection: %s\n\n",
4654                   mUseSmart90ForVideo ? "on" : "off");
4655     mScheduler->dump(mAppConnectionHandle, result);
4656 }
4657 
dumpStaticScreenStats(std::string & result) const4658 void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4659     result.append("Static screen stats:\n");
4660     for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4661         float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
4662         float percent = 100.0f *
4663                 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
4664         StringAppendF(&result, "  < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
4665     }
4666     float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
4667     float percent = 100.0f *
4668             static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
4669     StringAppendF(&result, "  %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4670                   bucketTimeSec, percent);
4671 }
4672 
recordBufferingStats(const char * layerName,std::vector<OccupancyTracker::Segment> && history)4673 void SurfaceFlinger::recordBufferingStats(const char* layerName,
4674         std::vector<OccupancyTracker::Segment>&& history) {
4675     Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4676     auto& stats = getBE().mBufferingStats[layerName];
4677     for (const auto& segment : history) {
4678         if (!segment.usedThirdBuffer) {
4679             stats.twoBufferTime += segment.totalTime;
4680         }
4681         if (segment.occupancyAverage < 1.0f) {
4682             stats.doubleBufferedTime += segment.totalTime;
4683         } else if (segment.occupancyAverage < 2.0f) {
4684             stats.tripleBufferedTime += segment.totalTime;
4685         }
4686         ++stats.numSegments;
4687         stats.totalTime += segment.totalTime;
4688     }
4689 }
4690 
dumpFrameEventsLocked(std::string & result)4691 void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4692     result.append("Layer frame timestamps:\n");
4693 
4694     const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4695     const size_t count = currentLayers.size();
4696     for (size_t i=0 ; i<count ; i++) {
4697         currentLayers[i]->dumpFrameEvents(result);
4698     }
4699 }
4700 
dumpBufferingStats(std::string & result) const4701 void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
4702     result.append("Buffering stats:\n");
4703     result.append("  [Layer name] <Active time> <Two buffer> "
4704             "<Double buffered> <Triple buffered>\n");
4705     Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4706     typedef std::tuple<std::string, float, float, float> BufferTuple;
4707     std::map<float, BufferTuple, std::greater<float>> sorted;
4708     for (const auto& statsPair : getBE().mBufferingStats) {
4709         const char* name = statsPair.first.c_str();
4710         const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
4711         if (stats.numSegments == 0) {
4712             continue;
4713         }
4714         float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4715         float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4716                 stats.totalTime;
4717         float doubleBufferRatio = static_cast<float>(
4718                 stats.doubleBufferedTime) / stats.totalTime;
4719         float tripleBufferRatio = static_cast<float>(
4720                 stats.tripleBufferedTime) / stats.totalTime;
4721         sorted.insert({activeTime, {name, twoBufferRatio,
4722                 doubleBufferRatio, tripleBufferRatio}});
4723     }
4724     for (const auto& sortedPair : sorted) {
4725         float activeTime = sortedPair.first;
4726         const BufferTuple& values = sortedPair.second;
4727         StringAppendF(&result, "  [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4728                       activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
4729     }
4730     result.append("\n");
4731 }
4732 
dumpDisplayIdentificationData(std::string & result) const4733 void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
4734     for (const auto& [token, display] : mDisplays) {
4735         const auto displayId = display->getId();
4736         if (!displayId) {
4737             continue;
4738         }
4739         const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
4740         if (!hwcDisplayId) {
4741             continue;
4742         }
4743 
4744         StringAppendF(&result,
4745                       "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4746                       *hwcDisplayId);
4747         uint8_t port;
4748         DisplayIdentificationData data;
4749         if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
4750             result.append("no identification data\n");
4751             continue;
4752         }
4753 
4754         if (!isEdid(data)) {
4755             result.append("unknown identification data: ");
4756             for (uint8_t byte : data) {
4757                 StringAppendF(&result, "%x ", byte);
4758             }
4759             result.append("\n");
4760             continue;
4761         }
4762 
4763         const auto edid = parseEdid(data);
4764         if (!edid) {
4765             result.append("invalid EDID: ");
4766             for (uint8_t byte : data) {
4767                 StringAppendF(&result, "%x ", byte);
4768             }
4769             result.append("\n");
4770             continue;
4771         }
4772 
4773         StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4774         result.append(edid->displayName.data(), edid->displayName.length());
4775         result.append("\"\n");
4776     }
4777 }
4778 
dumpWideColorInfo(std::string & result) const4779 void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
4780     StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
4781     StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4782     StringAppendF(&result, "DisplayColorSetting: %s\n",
4783                   decodeDisplayColorSetting(mDisplayColorSetting).c_str());
4784 
4785     // TODO: print out if wide-color mode is active or not
4786 
4787     for (const auto& [token, display] : mDisplays) {
4788         const auto displayId = display->getId();
4789         if (!displayId) {
4790             continue;
4791         }
4792 
4793         StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
4794         std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
4795         for (auto&& mode : modes) {
4796             StringAppendF(&result, "    %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4797         }
4798 
4799         ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
4800         StringAppendF(&result, "    Current color mode: %s (%d)\n",
4801                       decodeColorMode(currentMode).c_str(), currentMode);
4802     }
4803     result.append("\n");
4804 }
4805 
dumpProtoInfo(LayerVector::StateSet stateSet,uint32_t traceFlags) const4806 LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet,
4807                                           uint32_t traceFlags) const {
4808     LayersProto layersProto;
4809     const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4810     const State& state = useDrawing ? mDrawingState : mCurrentState;
4811     state.traverseInZOrder([&](Layer* layer) {
4812         LayerProto* layerProto = layersProto.add_layers();
4813         layer->writeToProto(layerProto, stateSet, traceFlags);
4814     });
4815 
4816     return layersProto;
4817 }
4818 
dumpVisibleLayersProtoInfo(const sp<DisplayDevice> & displayDevice) const4819 LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(
4820         const sp<DisplayDevice>& displayDevice) const {
4821     LayersProto layersProto;
4822 
4823     SizeProto* resolution = layersProto.mutable_resolution();
4824     resolution->set_w(displayDevice->getWidth());
4825     resolution->set_h(displayDevice->getHeight());
4826 
4827     auto display = displayDevice->getCompositionDisplay();
4828     const auto& displayState = display->getState();
4829 
4830     layersProto.set_color_mode(decodeColorMode(displayState.colorMode));
4831     layersProto.set_color_transform(decodeColorTransform(displayState.colorTransform));
4832     layersProto.set_global_transform(displayState.orientation);
4833 
4834     const auto displayId = displayDevice->getId();
4835     LOG_ALWAYS_FATAL_IF(!displayId);
4836     mDrawingState.traverseInZOrder([&](Layer* layer) {
4837         if (!layer->visibleRegion.isEmpty() && !display->getOutputLayersOrderedByZ().empty()) {
4838             LayerProto* layerProto = layersProto.add_layers();
4839             layer->writeToProto(layerProto, displayDevice);
4840         }
4841     });
4842 
4843     return layersProto;
4844 }
4845 
dumpAllLocked(const DumpArgs & args,std::string & result) const4846 void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4847     const bool colorize = !args.empty() && args[0] == String16("--color");
4848     Colorizer colorizer(colorize);
4849 
4850     // figure out if we're stuck somewhere
4851     const nsecs_t now = systemTime();
4852     const nsecs_t inTransaction(mDebugInTransaction);
4853     nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4854 
4855     /*
4856      * Dump library configuration.
4857      */
4858 
4859     colorizer.bold(result);
4860     result.append("Build configuration:");
4861     colorizer.reset(result);
4862     appendSfConfigString(result);
4863     appendUiConfigString(result);
4864     appendGuiConfigString(result);
4865     result.append("\n");
4866 
4867     result.append("\nDisplay identification data:\n");
4868     dumpDisplayIdentificationData(result);
4869 
4870     result.append("\nWide-Color information:\n");
4871     dumpWideColorInfo(result);
4872 
4873     colorizer.bold(result);
4874     result.append("Sync configuration: ");
4875     colorizer.reset(result);
4876     result.append(SyncFeatures::getInstance().toString());
4877     result.append("\n\n");
4878 
4879     colorizer.bold(result);
4880     result.append("VSYNC configuration:\n");
4881     colorizer.reset(result);
4882     dumpVSync(result);
4883     result.append("\n");
4884 
4885     dumpStaticScreenStats(result);
4886     result.append("\n");
4887 
4888     StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4889     StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4890     StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
4891 
4892     dumpBufferingStats(result);
4893 
4894     /*
4895      * Dump the visible layer list
4896      */
4897     colorizer.bold(result);
4898     StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4899     StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4900                   mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
4901     colorizer.reset(result);
4902 
4903     {
4904         LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4905         auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4906         result.append(LayerProtoParser::layerTreeToString(layerTree));
4907         result.append("\n");
4908     }
4909 
4910     {
4911         StringAppendF(&result, "Composition layers\n");
4912         mDrawingState.traverseInZOrder([&](Layer* layer) {
4913             auto compositionLayer = layer->getCompositionLayer();
4914             if (compositionLayer) compositionLayer->dump(result);
4915         });
4916     }
4917 
4918     /*
4919      * Dump Display state
4920      */
4921 
4922     colorizer.bold(result);
4923     StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
4924     colorizer.reset(result);
4925     for (const auto& [token, display] : mDisplays) {
4926         display->dump(result);
4927     }
4928     result.append("\n");
4929 
4930     /*
4931      * Dump SurfaceFlinger global state
4932      */
4933 
4934     colorizer.bold(result);
4935     result.append("SurfaceFlinger global state:\n");
4936     colorizer.reset(result);
4937 
4938     getRenderEngine().dump(result);
4939 
4940     if (const auto display = getDefaultDisplayDeviceLocked()) {
4941         display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4942                                                                           "undefinedRegion");
4943         StringAppendF(&result, "  orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4944                       display->isPoweredOn());
4945     }
4946     StringAppendF(&result,
4947                   "  transaction-flags         : %08x\n"
4948                   "  gpu_to_cpu_unsupported    : %d\n",
4949                   mTransactionFlags.load(), !mGpuToCpuSupported);
4950 
4951     if (const auto displayId = getInternalDisplayIdLocked();
4952         displayId && getHwComposer().isConnected(*displayId)) {
4953         const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
4954         StringAppendF(&result,
4955                       "  refresh-rate              : %f fps\n"
4956                       "  x-dpi                     : %f\n"
4957                       "  y-dpi                     : %f\n",
4958                       1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4959                       activeConfig->getDpiY());
4960     }
4961 
4962     StringAppendF(&result, "  transaction time: %f us\n", inTransactionDuration / 1000.0);
4963 
4964     /*
4965      * Tracing state
4966      */
4967     mTracing.dump(result);
4968     result.append("\n");
4969 
4970     /*
4971      * HWC layer minidump
4972      */
4973     for (const auto& [token, display] : mDisplays) {
4974         const auto displayId = display->getId();
4975         if (!displayId) {
4976             continue;
4977         }
4978 
4979         StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
4980         Layer::miniDumpHeader(result);
4981         const sp<DisplayDevice> displayDevice = display;
4982         mCurrentState.traverseInZOrder(
4983                 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
4984         result.append("\n");
4985     }
4986 
4987     /*
4988      * Dump HWComposer state
4989      */
4990     colorizer.bold(result);
4991     result.append("h/w composer state:\n");
4992     colorizer.reset(result);
4993     bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
4994     StringAppendF(&result, "  h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
4995     getHwComposer().dump(result);
4996 
4997     /*
4998      * Dump gralloc state
4999      */
5000     const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
5001     alloc.dump(result);
5002 
5003     /*
5004      * Dump VrFlinger state if in use.
5005      */
5006     if (mVrFlingerRequestsDisplay && mVrFlinger) {
5007         result.append("VrFlinger state:\n");
5008         result.append(mVrFlinger->Dump());
5009         result.append("\n");
5010     }
5011 
5012     /**
5013      * Scheduler dump state.
5014      */
5015     result.append("\nScheduler state:\n");
5016     result.append(mScheduler->doDump() + "\n");
5017     StringAppendF(&result, "+  Smart video mode: %s\n\n", mUseSmart90ForVideo ? "on" : "off");
5018     result.append(mRefreshRateStats.doDump() + "\n");
5019 
5020     result.append(mTimeStats->miniDump());
5021     result.append("\n");
5022 }
5023 
getLayerSortedByZForHwcDisplay(DisplayId displayId)5024 const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
5025     // Note: mStateLock is held here
5026     for (const auto& [token, display] : mDisplays) {
5027         if (display->getId() == displayId) {
5028             return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
5029         }
5030     }
5031 
5032     ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
5033     static const Vector<sp<Layer>> empty;
5034     return empty;
5035 }
5036 
updateColorMatrixLocked()5037 void SurfaceFlinger::updateColorMatrixLocked() {
5038     mat4 colorMatrix;
5039     if (mGlobalSaturationFactor != 1.0f) {
5040         // Rec.709 luma coefficients
5041         float3 luminance{0.213f, 0.715f, 0.072f};
5042         luminance *= 1.0f - mGlobalSaturationFactor;
5043         mat4 saturationMatrix = mat4(
5044             vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
5045             vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
5046             vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
5047             vec4{0.0f, 0.0f, 0.0f, 1.0f}
5048         );
5049         colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
5050     } else {
5051         colorMatrix = mClientColorMatrix * mDaltonizer();
5052     }
5053 
5054     if (mCurrentState.colorMatrix != colorMatrix) {
5055         mCurrentState.colorMatrix = colorMatrix;
5056         mCurrentState.colorMatrixChanged = true;
5057         setTransactionFlags(eTransactionNeeded);
5058     }
5059 }
5060 
CheckTransactCodeCredentials(uint32_t code)5061 status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
5062 #pragma clang diagnostic push
5063 #pragma clang diagnostic error "-Wswitch-enum"
5064     switch (static_cast<ISurfaceComposerTag>(code)) {
5065         // These methods should at minimum make sure that the client requested
5066         // access to SF.
5067         case BOOT_FINISHED:
5068         case CLEAR_ANIMATION_FRAME_STATS:
5069         case CREATE_DISPLAY:
5070         case DESTROY_DISPLAY:
5071         case ENABLE_VSYNC_INJECTIONS:
5072         case GET_ANIMATION_FRAME_STATS:
5073         case GET_HDR_CAPABILITIES:
5074         case SET_ACTIVE_CONFIG:
5075         case SET_ALLOWED_DISPLAY_CONFIGS:
5076         case GET_ALLOWED_DISPLAY_CONFIGS:
5077         case SET_ACTIVE_COLOR_MODE:
5078         case INJECT_VSYNC:
5079         case SET_POWER_MODE:
5080         case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
5081         case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
5082         case GET_DISPLAYED_CONTENT_SAMPLE:
5083         case NOTIFY_POWER_HINT: {
5084             if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
5085                 IPCThreadState* ipc = IPCThreadState::self();
5086                 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
5087                         ipc->getCallingPid(), ipc->getCallingUid());
5088                 return PERMISSION_DENIED;
5089             }
5090             return OK;
5091         }
5092         case GET_LAYER_DEBUG_INFO: {
5093             IPCThreadState* ipc = IPCThreadState::self();
5094             const int pid = ipc->getCallingPid();
5095             const int uid = ipc->getCallingUid();
5096             if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
5097                 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
5098                 return PERMISSION_DENIED;
5099             }
5100             return OK;
5101         }
5102         // Used by apps to hook Choreographer to SurfaceFlinger.
5103         case CREATE_DISPLAY_EVENT_CONNECTION:
5104         // The following calls are currently used by clients that do not
5105         // request necessary permissions. However, they do not expose any secret
5106         // information, so it is OK to pass them.
5107         case AUTHENTICATE_SURFACE:
5108         case GET_ACTIVE_COLOR_MODE:
5109         case GET_ACTIVE_CONFIG:
5110         case GET_PHYSICAL_DISPLAY_IDS:
5111         case GET_PHYSICAL_DISPLAY_TOKEN:
5112         case GET_DISPLAY_COLOR_MODES:
5113         case GET_DISPLAY_NATIVE_PRIMARIES:
5114         case GET_DISPLAY_CONFIGS:
5115         case GET_DISPLAY_STATS:
5116         case GET_SUPPORTED_FRAME_TIMESTAMPS:
5117         // Calling setTransactionState is safe, because you need to have been
5118         // granted a reference to Client* and Handle* to do anything with it.
5119         case SET_TRANSACTION_STATE:
5120         case CREATE_CONNECTION:
5121         case GET_COLOR_MANAGEMENT:
5122         case GET_COMPOSITION_PREFERENCE:
5123         case GET_PROTECTED_CONTENT_SUPPORT:
5124         case IS_WIDE_COLOR_DISPLAY:
5125         case GET_DISPLAY_BRIGHTNESS_SUPPORT:
5126         case SET_DISPLAY_BRIGHTNESS: {
5127             return OK;
5128         }
5129         case CAPTURE_LAYERS:
5130         case CAPTURE_SCREEN:
5131         case ADD_REGION_SAMPLING_LISTENER:
5132         case REMOVE_REGION_SAMPLING_LISTENER: {
5133             // codes that require permission check
5134             IPCThreadState* ipc = IPCThreadState::self();
5135             const int pid = ipc->getCallingPid();
5136             const int uid = ipc->getCallingUid();
5137             if ((uid != AID_GRAPHICS) &&
5138                 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
5139                 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
5140                 return PERMISSION_DENIED;
5141             }
5142             return OK;
5143         }
5144         // The following codes are deprecated and should never be allowed to access SF.
5145         case CONNECT_DISPLAY_UNUSED:
5146         case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
5147             ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
5148             return PERMISSION_DENIED;
5149         }
5150         case CAPTURE_SCREEN_BY_ID: {
5151             IPCThreadState* ipc = IPCThreadState::self();
5152             const int uid = ipc->getCallingUid();
5153             if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
5154                 return OK;
5155             }
5156             return PERMISSION_DENIED;
5157         }
5158     }
5159 
5160     // These codes are used for the IBinder protocol to either interrogate the recipient
5161     // side of the transaction for its canonical interface descriptor or to dump its state.
5162     // We let them pass by default.
5163     if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5164         code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5165         code == IBinder::SYSPROPS_TRANSACTION) {
5166         return OK;
5167     }
5168     // Numbers from 1000 to 1034 are currently used for backdoors. The code
5169     // in onTransact verifies that the user is root, and has access to use SF.
5170     if (code >= 1000 && code <= 1035) {
5171         ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5172         return OK;
5173     }
5174     ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5175     return PERMISSION_DENIED;
5176 #pragma clang diagnostic pop
5177 }
5178 
onTransact(uint32_t code,const Parcel & data,Parcel * reply,uint32_t flags)5179 status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5180                                     uint32_t flags) {
5181     status_t credentialCheck = CheckTransactCodeCredentials(code);
5182     if (credentialCheck != OK) {
5183         return credentialCheck;
5184     }
5185 
5186     status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5187     if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
5188         CHECK_INTERFACE(ISurfaceComposer, data, reply);
5189         IPCThreadState* ipc = IPCThreadState::self();
5190         const int uid = ipc->getCallingUid();
5191         if (CC_UNLIKELY(uid != AID_SYSTEM
5192                 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
5193             const int pid = ipc->getCallingPid();
5194             ALOGE("Permission Denial: "
5195                     "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
5196             return PERMISSION_DENIED;
5197         }
5198         int n;
5199         switch (code) {
5200             case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
5201             case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
5202                 return NO_ERROR;
5203             case 1002:  // SHOW_UPDATES
5204                 n = data.readInt32();
5205                 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
5206                 invalidateHwcGeometry();
5207                 repaintEverything();
5208                 return NO_ERROR;
5209             case 1004:{ // repaint everything
5210                 repaintEverything();
5211                 return NO_ERROR;
5212             }
5213             case 1005:{ // force transaction
5214                 Mutex::Autolock _l(mStateLock);
5215                 setTransactionFlags(
5216                         eTransactionNeeded|
5217                         eDisplayTransactionNeeded|
5218                         eTraversalNeeded);
5219                 return NO_ERROR;
5220             }
5221             case 1006:{ // send empty update
5222                 signalRefresh();
5223                 return NO_ERROR;
5224             }
5225             case 1008:  // toggle use of hw composer
5226                 n = data.readInt32();
5227                 mDebugDisableHWC = n != 0;
5228                 invalidateHwcGeometry();
5229                 repaintEverything();
5230                 return NO_ERROR;
5231             case 1009:  // toggle use of transform hint
5232                 n = data.readInt32();
5233                 mDebugDisableTransformHint = n != 0;
5234                 invalidateHwcGeometry();
5235                 repaintEverything();
5236                 return NO_ERROR;
5237             case 1010:  // interrogate.
5238                 reply->writeInt32(0);
5239                 reply->writeInt32(0);
5240                 reply->writeInt32(mDebugRegion);
5241                 reply->writeInt32(0);
5242                 reply->writeInt32(mDebugDisableHWC);
5243                 return NO_ERROR;
5244             case 1013: {
5245                 const auto display = getDefaultDisplayDevice();
5246                 if (!display) {
5247                     return NAME_NOT_FOUND;
5248                 }
5249 
5250                 reply->writeInt32(display->getPageFlipCount());
5251                 return NO_ERROR;
5252             }
5253             case 1014: {
5254                 Mutex::Autolock _l(mStateLock);
5255                 // daltonize
5256                 n = data.readInt32();
5257                 switch (n % 10) {
5258                     case 1:
5259                         mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5260                         break;
5261                     case 2:
5262                         mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5263                         break;
5264                     case 3:
5265                         mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5266                         break;
5267                     default:
5268                         mDaltonizer.setType(ColorBlindnessType::None);
5269                         break;
5270                 }
5271                 if (n >= 10) {
5272                     mDaltonizer.setMode(ColorBlindnessMode::Correction);
5273                 } else {
5274                     mDaltonizer.setMode(ColorBlindnessMode::Simulation);
5275                 }
5276 
5277                 updateColorMatrixLocked();
5278                 return NO_ERROR;
5279             }
5280             case 1015: {
5281                 Mutex::Autolock _l(mStateLock);
5282                 // apply a color matrix
5283                 n = data.readInt32();
5284                 if (n) {
5285                     // color matrix is sent as a column-major mat4 matrix
5286                     for (size_t i = 0 ; i < 4; i++) {
5287                         for (size_t j = 0; j < 4; j++) {
5288                             mClientColorMatrix[i][j] = data.readFloat();
5289                         }
5290                     }
5291                 } else {
5292                     mClientColorMatrix = mat4();
5293                 }
5294 
5295                 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5296                 // the division by w in the fragment shader
5297                 float4 lastRow(transpose(mClientColorMatrix)[3]);
5298                 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5299                     ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5300                 }
5301 
5302                 updateColorMatrixLocked();
5303                 return NO_ERROR;
5304             }
5305             // This is an experimental interface
5306             // Needs to be shifted to proper binder interface when we productize
5307             case 1016: {
5308                 n = data.readInt32();
5309                 // TODO(b/113612090): Evaluate if this can be removed.
5310                 mScheduler->setRefreshSkipCount(n);
5311                 return NO_ERROR;
5312             }
5313             case 1017: {
5314                 n = data.readInt32();
5315                 mForceFullDamage = n != 0;
5316                 return NO_ERROR;
5317             }
5318             case 1018: { // Modify Choreographer's phase offset
5319                 n = data.readInt32();
5320                 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
5321                 return NO_ERROR;
5322             }
5323             case 1019: { // Modify SurfaceFlinger's phase offset
5324                 n = data.readInt32();
5325                 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
5326                 return NO_ERROR;
5327             }
5328             case 1020: { // Layer updates interceptor
5329                 n = data.readInt32();
5330                 if (n) {
5331                     ALOGV("Interceptor enabled");
5332                     mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
5333                 }
5334                 else{
5335                     ALOGV("Interceptor disabled");
5336                     mInterceptor->disable();
5337                 }
5338                 return NO_ERROR;
5339             }
5340             case 1021: { // Disable HWC virtual displays
5341                 n = data.readInt32();
5342                 mUseHwcVirtualDisplays = !n;
5343                 return NO_ERROR;
5344             }
5345             case 1022: { // Set saturation boost
5346                 Mutex::Autolock _l(mStateLock);
5347                 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
5348 
5349                 updateColorMatrixLocked();
5350                 return NO_ERROR;
5351             }
5352             case 1023: { // Set native mode
5353                 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
5354                 invalidateHwcGeometry();
5355                 repaintEverything();
5356                 return NO_ERROR;
5357             }
5358             // Deprecate, use 1030 to check whether the device is color managed.
5359             case 1024: {
5360                 return NAME_NOT_FOUND;
5361             }
5362             case 1025: { // Set layer tracing
5363                 n = data.readInt32();
5364                 if (n) {
5365                     ALOGD("LayerTracing enabled");
5366                     Mutex::Autolock lock(mStateLock);
5367                     mTracingEnabledChanged = true;
5368                     mTracing.enable();
5369                     reply->writeInt32(NO_ERROR);
5370                 } else {
5371                     ALOGD("LayerTracing disabled");
5372                     bool writeFile = false;
5373                     {
5374                         Mutex::Autolock lock(mStateLock);
5375                         mTracingEnabledChanged = true;
5376                         writeFile = mTracing.disable();
5377                     }
5378 
5379                     if (writeFile) {
5380                         reply->writeInt32(mTracing.writeToFile());
5381                     } else {
5382                         reply->writeInt32(NO_ERROR);
5383                     }
5384                 }
5385                 return NO_ERROR;
5386             }
5387             case 1026: { // Get layer tracing status
5388                 reply->writeBool(mTracing.isEnabled());
5389                 return NO_ERROR;
5390             }
5391             // Is a DisplayColorSetting supported?
5392             case 1027: {
5393                 const auto display = getDefaultDisplayDevice();
5394                 if (!display) {
5395                     return NAME_NOT_FOUND;
5396                 }
5397 
5398                 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5399                 switch (setting) {
5400                     case DisplayColorSetting::MANAGED:
5401                         reply->writeBool(useColorManagement);
5402                         break;
5403                     case DisplayColorSetting::UNMANAGED:
5404                         reply->writeBool(true);
5405                         break;
5406                     case DisplayColorSetting::ENHANCED:
5407                         reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
5408                         break;
5409                     default: // vendor display color setting
5410                         reply->writeBool(
5411                                 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
5412                         break;
5413                 }
5414                 return NO_ERROR;
5415             }
5416             // Is VrFlinger active?
5417             case 1028: {
5418                 Mutex::Autolock _l(mStateLock);
5419                 reply->writeBool(getHwComposer().isUsingVrComposer());
5420                 return NO_ERROR;
5421             }
5422             // Set buffer size for SF tracing (value in KB)
5423             case 1029: {
5424                 n = data.readInt32();
5425                 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5426                     ALOGW("Invalid buffer size: %d KB", n);
5427                     reply->writeInt32(BAD_VALUE);
5428                     return BAD_VALUE;
5429                 }
5430 
5431                 ALOGD("Updating trace buffer to %d KB", n);
5432                 mTracing.setBufferSize(n * 1024);
5433                 reply->writeInt32(NO_ERROR);
5434                 return NO_ERROR;
5435             }
5436             // Is device color managed?
5437             case 1030: {
5438                 reply->writeBool(useColorManagement);
5439                 return NO_ERROR;
5440             }
5441             // Override default composition data space
5442             // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5443             // && adb shell stop zygote && adb shell start zygote
5444             // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5445             // adb shell stop zygote && adb shell start zygote
5446             case 1031: {
5447                 Mutex::Autolock _l(mStateLock);
5448                 n = data.readInt32();
5449                 if (n) {
5450                     n = data.readInt32();
5451                     if (n) {
5452                         Dataspace dataspace = static_cast<Dataspace>(n);
5453                         if (!validateCompositionDataspace(dataspace)) {
5454                             return BAD_VALUE;
5455                         }
5456                         mDefaultCompositionDataspace = dataspace;
5457                     }
5458                     n = data.readInt32();
5459                     if (n) {
5460                         Dataspace dataspace = static_cast<Dataspace>(n);
5461                         if (!validateCompositionDataspace(dataspace)) {
5462                             return BAD_VALUE;
5463                         }
5464                         mWideColorGamutCompositionDataspace = dataspace;
5465                     }
5466                 } else {
5467                     // restore composition data space.
5468                     mDefaultCompositionDataspace = defaultCompositionDataspace;
5469                     mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5470                 }
5471                 return NO_ERROR;
5472             }
5473             // Set trace flags
5474             case 1033: {
5475                 n = data.readUint32();
5476                 ALOGD("Updating trace flags to 0x%x", n);
5477                 mTracing.setTraceFlags(n);
5478                 reply->writeInt32(NO_ERROR);
5479                 return NO_ERROR;
5480             }
5481             case 1034: {
5482                 // TODO(b/129297325): expose this via developer menu option
5483                 n = data.readInt32();
5484                 if (n && !mRefreshRateOverlay) {
5485                     RefreshRateType type;
5486                     {
5487                         std::lock_guard<std::mutex> lock(mActiveConfigLock);
5488                         type = mDesiredActiveConfig.type;
5489                     }
5490                     mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
5491                     mRefreshRateOverlay->changeRefreshRate(type);
5492                 } else if (!n) {
5493                     mRefreshRateOverlay.reset();
5494                 }
5495                 return NO_ERROR;
5496             }
5497             case 1035: {
5498                 n = data.readInt32();
5499                 mDebugDisplayConfigSetByBackdoor = false;
5500                 if (n >= 0) {
5501                     const auto displayToken = getInternalDisplayToken();
5502                     status_t result = setAllowedDisplayConfigs(displayToken, {n});
5503                     if (result != NO_ERROR) {
5504                         return result;
5505                     }
5506                     mDebugDisplayConfigSetByBackdoor = true;
5507                 }
5508                 return NO_ERROR;
5509             }
5510         }
5511     }
5512     return err;
5513 }
5514 
repaintEverything()5515 void SurfaceFlinger::repaintEverything() {
5516     mRepaintEverything = true;
5517     signalTransaction();
5518 }
5519 
repaintEverythingForHWC()5520 void SurfaceFlinger::repaintEverythingForHWC() {
5521     mRepaintEverything = true;
5522     mEventQueue->invalidate();
5523 }
5524 
5525 // A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5526 class WindowDisconnector {
5527 public:
WindowDisconnector(ANativeWindow * window,int api)5528     WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
~WindowDisconnector()5529     ~WindowDisconnector() {
5530         native_window_api_disconnect(mWindow, mApi);
5531     }
5532 
5533 private:
5534     ANativeWindow* mWindow;
5535     const int mApi;
5536 };
5537 
captureScreen(const sp<IBinder> & displayToken,sp<GraphicBuffer> * outBuffer,bool & outCapturedSecureLayers,const Dataspace reqDataspace,const ui::PixelFormat reqPixelFormat,Rect sourceCrop,uint32_t reqWidth,uint32_t reqHeight,bool useIdentityTransform,ISurfaceComposer::Rotation rotation,bool captureSecureLayers)5538 status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
5539                                        sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
5540                                        const Dataspace reqDataspace,
5541                                        const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
5542                                        uint32_t reqWidth, uint32_t reqHeight,
5543                                        bool useIdentityTransform,
5544                                        ISurfaceComposer::Rotation rotation,
5545                                        bool captureSecureLayers) {
5546     ATRACE_CALL();
5547 
5548     if (!displayToken) return BAD_VALUE;
5549 
5550     auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5551 
5552     sp<DisplayDevice> display;
5553     {
5554         Mutex::Autolock _l(mStateLock);
5555 
5556         display = getDisplayDeviceLocked(displayToken);
5557         if (!display) return BAD_VALUE;
5558 
5559         // set the requested width/height to the logical display viewport size
5560         // by default
5561         if (reqWidth == 0 || reqHeight == 0) {
5562             reqWidth = uint32_t(display->getViewport().width());
5563             reqHeight = uint32_t(display->getViewport().height());
5564         }
5565     }
5566 
5567     DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5568                                  renderAreaRotation, captureSecureLayers);
5569 
5570     auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5571                                     std::placeholders::_1);
5572     return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5573                                useIdentityTransform, outCapturedSecureLayers);
5574 }
5575 
pickDataspaceFromColorMode(const ColorMode colorMode)5576 static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
5577     switch (colorMode) {
5578         case ColorMode::DISPLAY_P3:
5579         case ColorMode::BT2100_PQ:
5580         case ColorMode::BT2100_HLG:
5581         case ColorMode::DISPLAY_BT2020:
5582             return Dataspace::DISPLAY_P3;
5583         default:
5584             return Dataspace::V0_SRGB;
5585     }
5586 }
5587 
getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack)5588 const sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
5589     const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
5590     if (displayToken) {
5591         return getDisplayDeviceLocked(displayToken);
5592     }
5593     // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
5594     // may not have a displayId.
5595     for (const auto& [token, display] : mDisplays) {
5596         if (display->getLayerStack() == displayOrLayerStack) {
5597             return display;
5598         }
5599     }
5600     return nullptr;
5601 }
5602 
captureScreen(uint64_t displayOrLayerStack,Dataspace * outDataspace,sp<GraphicBuffer> * outBuffer)5603 status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
5604                                        sp<GraphicBuffer>* outBuffer) {
5605     sp<DisplayDevice> display;
5606     uint32_t width;
5607     uint32_t height;
5608     ui::Transform::orientation_flags captureOrientation;
5609     {
5610         Mutex::Autolock _l(mStateLock);
5611         display = getDisplayByIdOrLayerStack(displayOrLayerStack);
5612         if (!display) {
5613             return BAD_VALUE;
5614         }
5615 
5616         width = uint32_t(display->getViewport().width());
5617         height = uint32_t(display->getViewport().height());
5618 
5619         captureOrientation = fromSurfaceComposerRotation(
5620                 static_cast<ISurfaceComposer::Rotation>(display->getOrientation()));
5621         if (captureOrientation == ui::Transform::orientation_flags::ROT_90) {
5622             captureOrientation = ui::Transform::orientation_flags::ROT_270;
5623         } else if (captureOrientation == ui::Transform::orientation_flags::ROT_270) {
5624             captureOrientation = ui::Transform::orientation_flags::ROT_90;
5625         }
5626         *outDataspace =
5627                 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
5628     }
5629 
5630     DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
5631                                  false /* captureSecureLayers */);
5632 
5633     auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5634                                     std::placeholders::_1);
5635     bool ignored = false;
5636     return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
5637                                false /* useIdentityTransform */,
5638                                ignored /* outCapturedSecureLayers */);
5639 }
5640 
captureLayers(const sp<IBinder> & layerHandleBinder,sp<GraphicBuffer> * outBuffer,const Dataspace reqDataspace,const ui::PixelFormat reqPixelFormat,const Rect & sourceCrop,const std::unordered_set<sp<IBinder>,ISurfaceComposer::SpHash<IBinder>> & excludeHandles,float frameScale,bool childrenOnly)5641 status_t SurfaceFlinger::captureLayers(
5642         const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
5643         const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
5644         const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
5645         float frameScale, bool childrenOnly) {
5646     ATRACE_CALL();
5647 
5648     class LayerRenderArea : public RenderArea {
5649     public:
5650         LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
5651                         int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5652                         bool childrenOnly)
5653               : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
5654                 mLayer(layer),
5655                 mCrop(crop),
5656                 mNeedsFiltering(false),
5657                 mFlinger(flinger),
5658                 mChildrenOnly(childrenOnly) {}
5659         const ui::Transform& getTransform() const override { return mTransform; }
5660         Rect getBounds() const override {
5661             const Layer::State& layerState(mLayer->getDrawingState());
5662             return mLayer->getBufferSize(layerState);
5663         }
5664         int getHeight() const override {
5665             return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
5666         }
5667         int getWidth() const override {
5668             return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
5669         }
5670         bool isSecure() const override { return false; }
5671         bool needsFiltering() const override { return mNeedsFiltering; }
5672         const sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
5673         Rect getSourceCrop() const override {
5674             if (mCrop.isEmpty()) {
5675                 return getBounds();
5676             } else {
5677                 return mCrop;
5678             }
5679         }
5680         class ReparentForDrawing {
5681         public:
5682             const sp<Layer>& oldParent;
5683             const sp<Layer>& newParent;
5684 
5685             ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5686                                const Rect& drawingBounds)
5687                   : oldParent(oldParent), newParent(newParent) {
5688                 // Compute and cache the bounds for the new parent layer.
5689                 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform());
5690                 oldParent->setChildrenDrawingParent(newParent);
5691             }
5692             ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
5693         };
5694 
5695         void render(std::function<void()> drawLayers) override {
5696             const Rect sourceCrop = getSourceCrop();
5697             // no need to check rotation because there is none
5698             mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5699                 sourceCrop.height() != getReqHeight();
5700 
5701             if (!mChildrenOnly) {
5702                 mTransform = mLayer->getTransform().inverse();
5703                 drawLayers();
5704             } else {
5705                 Rect bounds = getBounds();
5706                 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
5707                         LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5708                                           bounds.getWidth(), bounds.getHeight(), 0,
5709                                           LayerMetadata()));
5710 
5711                 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
5712                 drawLayers();
5713             }
5714         }
5715 
5716     private:
5717         const sp<Layer> mLayer;
5718         const Rect mCrop;
5719 
5720         // In the "childrenOnly" case we reparent the children to a screenshot
5721         // layer which has no properties set and which does not draw.
5722         sp<ContainerLayer> screenshotParentLayer;
5723         ui::Transform mTransform;
5724         bool mNeedsFiltering;
5725 
5726         SurfaceFlinger* mFlinger;
5727         const bool mChildrenOnly;
5728     };
5729 
5730     int reqWidth = 0;
5731     int reqHeight = 0;
5732     sp<Layer> parent;
5733     Rect crop(sourceCrop);
5734     std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
5735 
5736     {
5737         Mutex::Autolock _l(mStateLock);
5738 
5739         parent = fromHandle(layerHandleBinder);
5740         if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5741             ALOGE("captureLayers called with an invalid or removed parent");
5742             return NAME_NOT_FOUND;
5743         }
5744 
5745         const int uid = IPCThreadState::self()->getCallingUid();
5746         const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5747         if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5748             ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5749             return PERMISSION_DENIED;
5750         }
5751 
5752         if (sourceCrop.width() <= 0) {
5753             crop.left = 0;
5754             crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
5755         }
5756 
5757         if (sourceCrop.height() <= 0) {
5758             crop.top = 0;
5759             crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
5760         }
5761         reqWidth = crop.width() * frameScale;
5762         reqHeight = crop.height() * frameScale;
5763 
5764         for (const auto& handle : excludeHandles) {
5765             sp<Layer> excludeLayer = fromHandle(handle);
5766             if (excludeLayer != nullptr) {
5767                 excludeLayers.emplace(excludeLayer);
5768             } else {
5769                 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5770                 return NAME_NOT_FOUND;
5771             }
5772         }
5773     } // mStateLock
5774 
5775     // really small crop or frameScale
5776     if (reqWidth <= 0) {
5777         reqWidth = 1;
5778     }
5779     if (reqHeight <= 0) {
5780         reqHeight = 1;
5781     }
5782 
5783     LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
5784     auto traverseLayers = [parent, childrenOnly,
5785                            &excludeLayers](const LayerVector::Visitor& visitor) {
5786         parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5787             if (!layer->isVisible()) {
5788                 return;
5789             } else if (childrenOnly && layer == parent.get()) {
5790                 return;
5791             }
5792 
5793             sp<Layer> p = layer;
5794             while (p != nullptr) {
5795                 if (excludeLayers.count(p) != 0) {
5796                     return;
5797                 }
5798                 p = p->getParent();
5799             }
5800 
5801             visitor(layer);
5802         });
5803     };
5804 
5805     bool outCapturedSecureLayers = false;
5806     return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5807                                outCapturedSecureLayers);
5808 }
5809 
captureScreenCommon(RenderArea & renderArea,TraverseLayersFunction traverseLayers,sp<GraphicBuffer> * outBuffer,const ui::PixelFormat reqPixelFormat,bool useIdentityTransform,bool & outCapturedSecureLayers)5810 status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5811                                              TraverseLayersFunction traverseLayers,
5812                                              sp<GraphicBuffer>* outBuffer,
5813                                              const ui::PixelFormat reqPixelFormat,
5814                                              bool useIdentityTransform,
5815                                              bool& outCapturedSecureLayers) {
5816     ATRACE_CALL();
5817 
5818     // TODO(b/116112787) Make buffer usage a parameter.
5819     const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5820             GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
5821     *outBuffer =
5822             getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5823                                              static_cast<android_pixel_format>(reqPixelFormat), 1,
5824                                              usage, "screenshot");
5825 
5826     return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
5827                                outCapturedSecureLayers);
5828 }
5829 
captureScreenCommon(RenderArea & renderArea,TraverseLayersFunction traverseLayers,const sp<GraphicBuffer> & buffer,bool useIdentityTransform,bool & outCapturedSecureLayers)5830 status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5831                                              TraverseLayersFunction traverseLayers,
5832                                              const sp<GraphicBuffer>& buffer,
5833                                              bool useIdentityTransform,
5834                                              bool& outCapturedSecureLayers) {
5835     // This mutex protects syncFd and captureResult for communication of the return values from the
5836     // main thread back to this Binder thread
5837     std::mutex captureMutex;
5838     std::condition_variable captureCondition;
5839     std::unique_lock<std::mutex> captureLock(captureMutex);
5840     int syncFd = -1;
5841     std::optional<status_t> captureResult;
5842 
5843     const int uid = IPCThreadState::self()->getCallingUid();
5844     const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5845 
5846     sp<LambdaMessage> message = new LambdaMessage([&] {
5847         // If there is a refresh pending, bug out early and tell the binder thread to try again
5848         // after the refresh.
5849         if (mRefreshPending) {
5850             ATRACE_NAME("Skipping screenshot for now");
5851             std::unique_lock<std::mutex> captureLock(captureMutex);
5852             captureResult = std::make_optional<status_t>(EAGAIN);
5853             captureCondition.notify_one();
5854             return;
5855         }
5856 
5857         status_t result = NO_ERROR;
5858         int fd = -1;
5859         {
5860             Mutex::Autolock _l(mStateLock);
5861             renderArea.render([&] {
5862                 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
5863                                                  useIdentityTransform, forSystem, &fd,
5864                                                  outCapturedSecureLayers);
5865             });
5866         }
5867 
5868         {
5869             std::unique_lock<std::mutex> captureLock(captureMutex);
5870             syncFd = fd;
5871             captureResult = std::make_optional<status_t>(result);
5872             captureCondition.notify_one();
5873         }
5874     });
5875 
5876     status_t result = postMessageAsync(message);
5877     if (result == NO_ERROR) {
5878         captureCondition.wait(captureLock, [&] { return captureResult; });
5879         while (*captureResult == EAGAIN) {
5880             captureResult.reset();
5881             result = postMessageAsync(message);
5882             if (result != NO_ERROR) {
5883                 return result;
5884             }
5885             captureCondition.wait(captureLock, [&] { return captureResult; });
5886         }
5887         result = *captureResult;
5888     }
5889 
5890     if (result == NO_ERROR) {
5891         sync_wait(syncFd, -1);
5892         close(syncFd);
5893     }
5894 
5895     return result;
5896 }
5897 
renderScreenImplLocked(const RenderArea & renderArea,TraverseLayersFunction traverseLayers,ANativeWindowBuffer * buffer,bool useIdentityTransform,int * outSyncFd)5898 void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
5899                                             TraverseLayersFunction traverseLayers,
5900                                             ANativeWindowBuffer* buffer, bool useIdentityTransform,
5901                                             int* outSyncFd) {
5902     ATRACE_CALL();
5903 
5904     const auto reqWidth = renderArea.getReqWidth();
5905     const auto reqHeight = renderArea.getReqHeight();
5906     const auto rotation = renderArea.getRotationFlags();
5907     const auto transform = renderArea.getTransform();
5908     const auto sourceCrop = renderArea.getSourceCrop();
5909 
5910     renderengine::DisplaySettings clientCompositionDisplay;
5911     std::vector<renderengine::LayerSettings> clientCompositionLayers;
5912 
5913     // assume that bounds are never offset, and that they are the same as the
5914     // buffer bounds.
5915     clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
5916     clientCompositionDisplay.clip = sourceCrop;
5917     clientCompositionDisplay.globalTransform = transform.asMatrix4();
5918 
5919     // Now take into account the rotation flag. We append a transform that
5920     // rotates the layer stack about the origin, then translate by buffer
5921     // boundaries to be in the right quadrant.
5922     mat4 rotMatrix;
5923     int displacementX = 0;
5924     int displacementY = 0;
5925     float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5926     switch (rotation) {
5927         case ui::Transform::ROT_90:
5928             rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
5929             displacementX = renderArea.getBounds().getHeight();
5930             break;
5931         case ui::Transform::ROT_180:
5932             rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
5933             displacementY = renderArea.getBounds().getWidth();
5934             displacementX = renderArea.getBounds().getHeight();
5935             break;
5936         case ui::Transform::ROT_270:
5937             rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
5938             displacementY = renderArea.getBounds().getWidth();
5939             break;
5940         default:
5941             break;
5942     }
5943 
5944     // We need to transform the clipping window into the right spot.
5945     // First, rotate the clipping rectangle by the rotation hint to get the
5946     // right orientation
5947     const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5948     const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5949     const vec4 rotClipTL = rotMatrix * clipTL;
5950     const vec4 rotClipBR = rotMatrix * clipBR;
5951     const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5952     const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5953     const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5954     const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5955 
5956     // Now reposition the clipping rectangle with the displacement vector
5957     // computed above.
5958     const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
5959     clientCompositionDisplay.clip =
5960             Rect(newClipLeft + displacementX, newClipTop + displacementY,
5961                  newClipRight + displacementX, newClipBottom + displacementY);
5962 
5963     mat4 clipTransform = displacementMat * rotMatrix;
5964     clientCompositionDisplay.globalTransform =
5965             clipTransform * clientCompositionDisplay.globalTransform;
5966 
5967     clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5968     clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
5969 
5970     const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
5971 
5972     renderengine::LayerSettings fillLayer;
5973     fillLayer.source.buffer.buffer = nullptr;
5974     fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5975     fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5976     fillLayer.alpha = half(alpha);
5977     clientCompositionLayers.push_back(fillLayer);
5978 
5979     Region clearRegion = Region::INVALID_REGION;
5980     traverseLayers([&](Layer* layer) {
5981         renderengine::LayerSettings layerSettings;
5982         bool prepared = layer->prepareClientLayer(renderArea, useIdentityTransform, clearRegion,
5983                                                   false, layerSettings);
5984         if (prepared) {
5985             clientCompositionLayers.push_back(layerSettings);
5986         }
5987     });
5988 
5989     clientCompositionDisplay.clearRegion = clearRegion;
5990     // Use an empty fence for the buffer fence, since we just created the buffer so
5991     // there is no need for synchronization with the GPU.
5992     base::unique_fd bufferFence;
5993     base::unique_fd drawFence;
5994     getRenderEngine().useProtectedContext(false);
5995     getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers, buffer,
5996                                  /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
5997 
5998     *outSyncFd = drawFence.release();
5999 }
6000 
captureScreenImplLocked(const RenderArea & renderArea,TraverseLayersFunction traverseLayers,ANativeWindowBuffer * buffer,bool useIdentityTransform,bool forSystem,int * outSyncFd,bool & outCapturedSecureLayers)6001 status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
6002                                                  TraverseLayersFunction traverseLayers,
6003                                                  ANativeWindowBuffer* buffer,
6004                                                  bool useIdentityTransform, bool forSystem,
6005                                                  int* outSyncFd, bool& outCapturedSecureLayers) {
6006     ATRACE_CALL();
6007 
6008     traverseLayers([&](Layer* layer) {
6009         outCapturedSecureLayers =
6010                 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
6011     });
6012 
6013     // We allow the system server to take screenshots of secure layers for
6014     // use in situations like the Screen-rotation animation and place
6015     // the impetus on WindowManager to not persist them.
6016     if (outCapturedSecureLayers && !forSystem) {
6017         ALOGW("FB is protected: PERMISSION_DENIED");
6018         return PERMISSION_DENIED;
6019     }
6020     renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
6021     return NO_ERROR;
6022 }
6023 
setInputWindowsFinished()6024 void SurfaceFlinger::setInputWindowsFinished() {
6025     Mutex::Autolock _l(mStateLock);
6026 
6027     mPendingSyncInputWindows = false;
6028     mTransactionCV.broadcast();
6029 }
6030 
6031 // ---------------------------------------------------------------------------
6032 
traverseInZOrder(const LayerVector::Visitor & visitor) const6033 void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
6034     layersSortedByZ.traverseInZOrder(stateSet, visitor);
6035 }
6036 
traverseInReverseZOrder(const LayerVector::Visitor & visitor) const6037 void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
6038     layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
6039 }
6040 
traverseLayersInDisplay(const sp<const DisplayDevice> & display,const LayerVector::Visitor & visitor)6041 void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
6042                                              const LayerVector::Visitor& visitor) {
6043     // We loop through the first level of layers without traversing,
6044     // as we need to determine which layers belong to the requested display.
6045     for (const auto& layer : mDrawingState.layersSortedByZ) {
6046         if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
6047             continue;
6048         }
6049         // relative layers are traversed in Layer::traverseInZOrder
6050         layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
6051             if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
6052                 return;
6053             }
6054             if (!layer->isVisible()) {
6055                 return;
6056             }
6057             visitor(layer);
6058         });
6059     }
6060 }
6061 
setAllowedDisplayConfigsInternal(const sp<DisplayDevice> & display,const std::vector<int32_t> & allowedConfigs)6062 void SurfaceFlinger::setAllowedDisplayConfigsInternal(const sp<DisplayDevice>& display,
6063                                                       const std::vector<int32_t>& allowedConfigs) {
6064     if (!display->isPrimary()) {
6065         return;
6066     }
6067 
6068     ALOGV("Updating allowed configs");
6069     mAllowedDisplayConfigs = DisplayConfigs(allowedConfigs.begin(), allowedConfigs.end());
6070 
6071     // Set the highest allowed config by iterating backwards on available refresh rates
6072     const auto& refreshRates = mRefreshRateConfigs.getRefreshRates();
6073     for (auto iter = refreshRates.crbegin(); iter != refreshRates.crend(); ++iter) {
6074         if (iter->second && isDisplayConfigAllowed(iter->second->configId)) {
6075             ALOGV("switching to config %d", iter->second->configId);
6076             setDesiredActiveConfig(
6077                     {iter->first, iter->second->configId, Scheduler::ConfigEvent::Changed});
6078             break;
6079         }
6080     }
6081 }
6082 
setAllowedDisplayConfigs(const sp<IBinder> & displayToken,const std::vector<int32_t> & allowedConfigs)6083 status_t SurfaceFlinger::setAllowedDisplayConfigs(const sp<IBinder>& displayToken,
6084                                                   const std::vector<int32_t>& allowedConfigs) {
6085     ATRACE_CALL();
6086 
6087     if (!displayToken || allowedConfigs.empty()) {
6088         return BAD_VALUE;
6089     }
6090 
6091     if (mDebugDisplayConfigSetByBackdoor) {
6092         // ignore this request as config is overridden by backdoor
6093         return NO_ERROR;
6094     }
6095 
6096     postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
6097         const auto display = getDisplayDeviceLocked(displayToken);
6098         if (!display) {
6099             ALOGE("Attempt to set allowed display configs for invalid display token %p",
6100                   displayToken.get());
6101         } else if (display->isVirtual()) {
6102             ALOGW("Attempt to set allowed display configs for virtual display");
6103         } else {
6104             setAllowedDisplayConfigsInternal(display, allowedConfigs);
6105         }
6106     }));
6107 
6108     return NO_ERROR;
6109 }
6110 
getAllowedDisplayConfigs(const sp<IBinder> & displayToken,std::vector<int32_t> * outAllowedConfigs)6111 status_t SurfaceFlinger::getAllowedDisplayConfigs(const sp<IBinder>& displayToken,
6112                                                   std::vector<int32_t>* outAllowedConfigs) {
6113     ATRACE_CALL();
6114 
6115     if (!displayToken || !outAllowedConfigs) {
6116         return BAD_VALUE;
6117     }
6118 
6119     Mutex::Autolock lock(mStateLock);
6120 
6121     const auto display = getDisplayDeviceLocked(displayToken);
6122     if (!display) {
6123         return NAME_NOT_FOUND;
6124     }
6125 
6126     if (display->isPrimary()) {
6127         outAllowedConfigs->assign(mAllowedDisplayConfigs.begin(), mAllowedDisplayConfigs.end());
6128     }
6129 
6130     return NO_ERROR;
6131 }
6132 
onSetInputWindowsFinished()6133 void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
6134     mFlinger->setInputWindowsFinished();
6135 }
6136 
fromHandle(const sp<IBinder> & handle)6137 sp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
6138     BBinder *b = handle->localBinder();
6139     if (b == nullptr) {
6140         return nullptr;
6141     }
6142     auto it = mLayersByLocalBinderToken.find(b);
6143     if (it != mLayersByLocalBinderToken.end()) {
6144         return it->second.promote();
6145     }
6146     return nullptr;
6147 }
6148 
6149 } // namespace android
6150 
6151 #if defined(__gl_h_)
6152 #error "don't include gl/gl.h in this file"
6153 #endif
6154 
6155 #if defined(__gl2_h_)
6156 #error "don't include gl2/gl2.h in this file"
6157 #endif
6158