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