• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #pragma clang diagnostic ignored "-Wextra"
21 
22 //#define LOG_NDEBUG 0
23 #define ATRACE_TAG ATRACE_TAG_GRAPHICS
24 
25 #include "SurfaceFlinger.h"
26 
27 #include <android-base/parseint.h>
28 #include <android-base/properties.h>
29 #include <android-base/stringprintf.h>
30 #include <android-base/strings.h>
31 #include <android/configuration.h>
32 #include <android/gui/IDisplayEventConnection.h>
33 #include <android/gui/StaticDisplayInfo.h>
34 #include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
35 #include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
36 #include <android/hardware/configstore/1.1/types.h>
37 #include <android/hardware/power/Boost.h>
38 #include <android/native_window.h>
39 #include <android/os/IInputFlinger.h>
40 #include <binder/IPCThreadState.h>
41 #include <binder/IServiceManager.h>
42 #include <binder/PermissionCache.h>
43 #include <compositionengine/CompositionEngine.h>
44 #include <compositionengine/CompositionRefreshArgs.h>
45 #include <compositionengine/Display.h>
46 #include <compositionengine/DisplayColorProfile.h>
47 #include <compositionengine/DisplayColorProfileCreationArgs.h>
48 #include <compositionengine/DisplayCreationArgs.h>
49 #include <compositionengine/LayerFECompositionState.h>
50 #include <compositionengine/OutputLayer.h>
51 #include <compositionengine/RenderSurface.h>
52 #include <compositionengine/impl/DisplayColorProfile.h>
53 #include <compositionengine/impl/OutputCompositionState.h>
54 #include <compositionengine/impl/OutputLayerCompositionState.h>
55 #include <configstore/Utils.h>
56 #include <cutils/compiler.h>
57 #include <cutils/properties.h>
58 #include <ftl/algorithm.h>
59 #include <ftl/concat.h>
60 #include <ftl/fake_guard.h>
61 #include <ftl/future.h>
62 #include <ftl/unit.h>
63 #include <gui/AidlStatusUtil.h>
64 #include <gui/BufferQueue.h>
65 #include <gui/DebugEGLImageTracker.h>
66 #include <gui/IProducerListener.h>
67 #include <gui/LayerDebugInfo.h>
68 #include <gui/LayerMetadata.h>
69 #include <gui/LayerState.h>
70 #include <gui/Surface.h>
71 #include <gui/TraceUtils.h>
72 #include <hidl/ServiceManagement.h>
73 #include <layerproto/LayerProtoParser.h>
74 #include <log/log.h>
75 #include <private/android_filesystem_config.h>
76 #include <private/gui/SyncFeatures.h>
77 #include <processgroup/processgroup.h>
78 #include <renderengine/RenderEngine.h>
79 #include <renderengine/impl/ExternalTexture.h>
80 #include <scheduler/FrameTargeter.h>
81 #include <sys/types.h>
82 #include <ui/ColorSpace.h>
83 #include <ui/DebugUtils.h>
84 #include <ui/DisplayId.h>
85 #include <ui/DisplayMode.h>
86 #include <ui/DisplayStatInfo.h>
87 #include <ui/DisplayState.h>
88 #include <ui/DynamicDisplayInfo.h>
89 #include <ui/GraphicBufferAllocator.h>
90 #include <ui/HdrRenderTypeUtils.h>
91 #include <ui/LayerStack.h>
92 #include <ui/PixelFormat.h>
93 #include <ui/StaticDisplayInfo.h>
94 #include <utils/StopWatch.h>
95 #include <utils/String16.h>
96 #include <utils/String8.h>
97 #include <utils/Timers.h>
98 #include <utils/misc.h>
99 
100 #include <unistd.h>
101 #include <algorithm>
102 #include <cerrno>
103 #include <cinttypes>
104 #include <cmath>
105 #include <cstdint>
106 #include <functional>
107 #include <memory>
108 #include <mutex>
109 #include <optional>
110 #include <string>
111 #include <type_traits>
112 #include <unordered_map>
113 #include <vector>
114 
115 #include <gui/LayerStatePermissions.h>
116 #include <ui/DisplayIdentification.h>
117 #include "BackgroundExecutor.h"
118 #include "Client.h"
119 #include "ClientCache.h"
120 #include "Colorizer.h"
121 #include "DisplayDevice.h"
122 #include "DisplayHardware/ComposerHal.h"
123 #include "DisplayHardware/FramebufferSurface.h"
124 #include "DisplayHardware/HWComposer.h"
125 #include "DisplayHardware/Hal.h"
126 #include "DisplayHardware/PowerAdvisor.h"
127 #include "DisplayHardware/VirtualDisplaySurface.h"
128 #include "DisplayRenderArea.h"
129 #include "Effects/Daltonizer.h"
130 #include "FlagManager.h"
131 #include "FpsReporter.h"
132 #include "FrameTimeline/FrameTimeline.h"
133 #include "FrameTracer/FrameTracer.h"
134 #include "FrontEnd/LayerCreationArgs.h"
135 #include "FrontEnd/LayerHandle.h"
136 #include "FrontEnd/LayerLifecycleManager.h"
137 #include "FrontEnd/LayerSnapshot.h"
138 #include "HdrLayerInfoReporter.h"
139 #include "Layer.h"
140 #include "LayerProtoHelper.h"
141 #include "LayerRenderArea.h"
142 #include "LayerVector.h"
143 #include "MutexUtils.h"
144 #include "NativeWindowSurface.h"
145 #include "RegionSamplingThread.h"
146 #include "Scheduler/EventThread.h"
147 #include "Scheduler/LayerHistory.h"
148 #include "Scheduler/Scheduler.h"
149 #include "Scheduler/VsyncConfiguration.h"
150 #include "Scheduler/VsyncModulator.h"
151 #include "ScreenCaptureOutput.h"
152 #include "StartPropertySetThread.h"
153 #include "SurfaceFlingerProperties.h"
154 #include "TimeStats/TimeStats.h"
155 #include "TunnelModeEnabledReporter.h"
156 #include "Utils/Dumper.h"
157 #include "WindowInfosListenerInvoker.h"
158 
159 #include <aidl/android/hardware/graphics/common/DisplayDecorationSupport.h>
160 #include <aidl/android/hardware/graphics/composer3/DisplayCapability.h>
161 #include <aidl/android/hardware/graphics/composer3/RenderIntent.h>
162 
163 #undef NO_THREAD_SAFETY_ANALYSIS
164 #define NO_THREAD_SAFETY_ANALYSIS \
165     _Pragma("GCC error \"Prefer <ftl/fake_guard.h> or MutexUtils.h helpers.\"")
166 
167 // To enable layer borders in the system, change the below flag to true.
168 #undef DOES_CONTAIN_BORDER
169 #define DOES_CONTAIN_BORDER false
170 
171 namespace android {
172 
173 using namespace std::chrono_literals;
174 using namespace std::string_literals;
175 using namespace std::string_view_literals;
176 
177 using namespace hardware::configstore;
178 using namespace hardware::configstore::V1_0;
179 using namespace sysprop;
180 using ftl::Flags;
181 using namespace ftl::flag_operators;
182 
183 using aidl::android::hardware::graphics::common::DisplayDecorationSupport;
184 using aidl::android::hardware::graphics::composer3::Capability;
185 using aidl::android::hardware::graphics::composer3::DisplayCapability;
186 using CompositionStrategyPredictionState = android::compositionengine::impl::
187         OutputCompositionState::CompositionStrategyPredictionState;
188 
189 using base::StringAppendF;
190 using display::PhysicalDisplay;
191 using display::PhysicalDisplays;
192 using frontend::TransactionHandler;
193 using gui::DisplayInfo;
194 using gui::GameMode;
195 using gui::IDisplayEventConnection;
196 using gui::IWindowInfosListener;
197 using gui::LayerMetadata;
198 using gui::WindowInfo;
199 using gui::aidl_utils::binderStatusFromStatusT;
200 using scheduler::VsyncModulator;
201 using ui::Dataspace;
202 using ui::DisplayPrimaries;
203 using ui::RenderIntent;
204 
205 using KernelIdleTimerController = scheduler::RefreshRateSelector::KernelIdleTimerController;
206 
207 namespace hal = android::hardware::graphics::composer::hal;
208 
209 namespace {
210 
211 static constexpr int FOUR_K_WIDTH = 3840;
212 static constexpr int FOUR_K_HEIGHT = 2160;
213 
214 // TODO(b/141333600): Consolidate with DisplayMode::Builder::getDefaultDensity.
215 constexpr float FALLBACK_DENSITY = ACONFIGURATION_DENSITY_TV;
216 
getDensityFromProperty(const char * property,bool required)217 float getDensityFromProperty(const char* property, bool required) {
218     char value[PROPERTY_VALUE_MAX];
219     const float density = property_get(property, value, nullptr) > 0 ? std::atof(value) : 0.f;
220     if (!density && required) {
221         ALOGE("%s must be defined as a build property", property);
222         return FALLBACK_DENSITY;
223     }
224     return density;
225 }
226 
227 // Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
validateCompositionDataspace(Dataspace dataspace)228 bool validateCompositionDataspace(Dataspace dataspace) {
229     return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
230 }
231 
getIdleTimerTimeout(DisplayId displayId)232 std::chrono::milliseconds getIdleTimerTimeout(DisplayId displayId) {
233     const auto displayIdleTimerMsKey = [displayId] {
234         std::stringstream ss;
235         ss << "debug.sf.set_idle_timer_ms_" << displayId.value;
236         return ss.str();
237     }();
238 
239     const int32_t displayIdleTimerMs = base::GetIntProperty(displayIdleTimerMsKey, 0);
240     if (displayIdleTimerMs > 0) {
241         return std::chrono::milliseconds(displayIdleTimerMs);
242     }
243 
244     const int32_t setIdleTimerMs = base::GetIntProperty("debug.sf.set_idle_timer_ms", 0);
245     const int32_t millis = setIdleTimerMs ? setIdleTimerMs : sysprop::set_idle_timer_ms(0);
246     return std::chrono::milliseconds(millis);
247 }
248 
getKernelIdleTimerSyspropConfig(DisplayId displayId)249 bool getKernelIdleTimerSyspropConfig(DisplayId displayId) {
250     const auto displaySupportKernelIdleTimerKey = [displayId] {
251         std::stringstream ss;
252         ss << "debug.sf.support_kernel_idle_timer_" << displayId.value;
253         return ss.str();
254     }();
255 
256     const auto displaySupportKernelIdleTimer =
257             base::GetBoolProperty(displaySupportKernelIdleTimerKey, false);
258     return displaySupportKernelIdleTimer || sysprop::support_kernel_idle_timer(false);
259 }
260 
isAbove4k30(const ui::DisplayMode & outMode)261 bool isAbove4k30(const ui::DisplayMode& outMode) {
262     using fps_approx_ops::operator>;
263     Fps refreshRate = Fps::fromValue(outMode.refreshRate);
264     return outMode.resolution.getWidth() >= FOUR_K_WIDTH &&
265             outMode.resolution.getHeight() >= FOUR_K_HEIGHT && refreshRate > 30_Hz;
266 }
267 
excludeDolbyVisionIf4k30Present(const std::vector<ui::Hdr> & displayHdrTypes,ui::DisplayMode & outMode)268 void excludeDolbyVisionIf4k30Present(const std::vector<ui::Hdr>& displayHdrTypes,
269                                      ui::DisplayMode& outMode) {
270     if (isAbove4k30(outMode) &&
271         std::any_of(displayHdrTypes.begin(), displayHdrTypes.end(),
272                     [](ui::Hdr type) { return type == ui::Hdr::DOLBY_VISION_4K30; })) {
273         for (ui::Hdr type : displayHdrTypes) {
274             if (type != ui::Hdr::DOLBY_VISION_4K30 && type != ui::Hdr::DOLBY_VISION) {
275                 outMode.supportedHdrTypes.push_back(type);
276             }
277         }
278     } else {
279         for (ui::Hdr type : displayHdrTypes) {
280             if (type != ui::Hdr::DOLBY_VISION_4K30) {
281                 outMode.supportedHdrTypes.push_back(type);
282             }
283         }
284     }
285 }
286 
filterOut4k30(const HdrCapabilities & displayHdrCapabilities)287 HdrCapabilities filterOut4k30(const HdrCapabilities& displayHdrCapabilities) {
288     std::vector<ui::Hdr> hdrTypes;
289     for (ui::Hdr type : displayHdrCapabilities.getSupportedHdrTypes()) {
290         if (type != ui::Hdr::DOLBY_VISION_4K30) {
291             hdrTypes.push_back(type);
292         }
293     }
294     return {hdrTypes, displayHdrCapabilities.getDesiredMaxLuminance(),
295             displayHdrCapabilities.getDesiredMaxAverageLuminance(),
296             displayHdrCapabilities.getDesiredMinLuminance()};
297 }
298 
getLayerIdFromSurfaceControl(sp<SurfaceControl> surfaceControl)299 uint32_t getLayerIdFromSurfaceControl(sp<SurfaceControl> surfaceControl) {
300     if (!surfaceControl) {
301         return UNASSIGNED_LAYER_ID;
302     }
303     return LayerHandle::getLayerId(surfaceControl->getHandle());
304 }
305 
306 }  // namespace anonymous
307 
308 // ---------------------------------------------------------------------------
309 
310 const String16 sHardwareTest("android.permission.HARDWARE_TEST");
311 const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
312 const String16 sRotateSurfaceFlinger("android.permission.ROTATE_SURFACE_FLINGER");
313 const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
314 const String16 sControlDisplayBrightness("android.permission.CONTROL_DISPLAY_BRIGHTNESS");
315 const String16 sDump("android.permission.DUMP");
316 const String16 sCaptureBlackoutContent("android.permission.CAPTURE_BLACKOUT_CONTENT");
317 const String16 sInternalSystemWindow("android.permission.INTERNAL_SYSTEM_WINDOW");
318 const String16 sWakeupSurfaceFlinger("android.permission.WAKEUP_SURFACE_FLINGER");
319 
320 const char* KERNEL_IDLE_TIMER_PROP = "graphics.display.kernel_idle_timer.enabled";
321 
322 static const int MAX_TRACING_MEMORY = 1024 * 1024 * 1024; // 1GB
323 
324 // ---------------------------------------------------------------------------
325 int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
326 bool SurfaceFlinger::useHwcForRgbToYuv;
327 bool SurfaceFlinger::hasSyncFramework;
328 int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
329 uint32_t SurfaceFlinger::maxGraphicsWidth;
330 uint32_t SurfaceFlinger::maxGraphicsHeight;
331 bool SurfaceFlinger::useContextPriority;
332 Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
333 ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
334 Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
335 ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
336 LatchUnsignaledConfig SurfaceFlinger::enableLatchUnsignaledConfig;
337 
decodeDisplayColorSetting(DisplayColorSetting displayColorSetting)338 std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
339     switch(displayColorSetting) {
340         case DisplayColorSetting::kManaged:
341             return std::string("Managed");
342         case DisplayColorSetting::kUnmanaged:
343             return std::string("Unmanaged");
344         case DisplayColorSetting::kEnhanced:
345             return std::string("Enhanced");
346         default:
347             return std::string("Unknown ") +
348                 std::to_string(static_cast<int>(displayColorSetting));
349     }
350 }
351 
callingThreadHasPermission(const String16 & permission)352 bool callingThreadHasPermission(const String16& permission) {
353     IPCThreadState* ipc = IPCThreadState::self();
354     const int pid = ipc->getCallingPid();
355     const int uid = ipc->getCallingUid();
356     return uid == AID_GRAPHICS || uid == AID_SYSTEM ||
357             PermissionCache::checkPermission(permission, pid, uid);
358 }
359 
360 ui::Transform::RotationFlags SurfaceFlinger::sActiveDisplayRotationFlags = ui::Transform::ROT_0;
361 
SurfaceFlinger(Factory & factory,SkipInitializationTag)362 SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
363       : mFactory(factory),
364         mPid(getpid()),
365         mTimeStats(std::make_shared<impl::TimeStats>()),
366         mFrameTracer(mFactory.createFrameTracer()),
367         mFrameTimeline(mFactory.createFrameTimeline(mTimeStats, mPid)),
368         mCompositionEngine(mFactory.createCompositionEngine()),
369         mHwcServiceName(base::GetProperty("debug.sf.hwc_service_name"s, "default"s)),
370         mTunnelModeEnabledReporter(sp<TunnelModeEnabledReporter>::make()),
371         mEmulatedDisplayDensity(getDensityFromProperty("qemu.sf.lcd_density", false)),
372         mInternalDisplayDensity(
373                 getDensityFromProperty("ro.sf.lcd_density", !mEmulatedDisplayDensity)),
374         mPowerAdvisor(std::make_unique<Hwc2::impl::PowerAdvisor>(*this)),
375         mWindowInfosListenerInvoker(sp<WindowInfosListenerInvoker>::make()) {
376     ALOGI("Using HWComposer service: %s", mHwcServiceName.c_str());
377 }
378 
SurfaceFlinger(Factory & factory)379 SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
380     ALOGI("SurfaceFlinger is starting");
381 
382     hasSyncFramework = running_without_sync_framework(true);
383 
384     dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
385 
386     useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
387 
388     maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
389 
390     maxGraphicsWidth = std::max(max_graphics_width(0), 0);
391     maxGraphicsHeight = std::max(max_graphics_height(0), 0);
392 
393     mSupportsWideColor = has_wide_color_display(false);
394     mDefaultCompositionDataspace =
395             static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
396     mWideColorGamutCompositionDataspace = static_cast<ui::Dataspace>(wcg_composition_dataspace(
397             mSupportsWideColor ? Dataspace::DISPLAY_P3 : Dataspace::V0_SRGB));
398     defaultCompositionDataspace = mDefaultCompositionDataspace;
399     wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
400     defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
401             default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
402     wideColorGamutCompositionPixelFormat =
403             static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
404 
405     mColorSpaceAgnosticDataspace =
406             static_cast<ui::Dataspace>(color_space_agnostic_dataspace(Dataspace::UNKNOWN));
407 
408     mLayerCachingEnabled = [] {
409         const bool enable =
410                 android::sysprop::SurfaceFlingerProperties::enable_layer_caching().value_or(false);
411         return base::GetBoolProperty(std::string("debug.sf.enable_layer_caching"), enable);
412     }();
413 
414     useContextPriority = use_context_priority(true);
415 
416     mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
417 
418     // debugging stuff...
419     char value[PROPERTY_VALUE_MAX];
420 
421     property_get("ro.build.type", value, "user");
422     mIsUserBuild = strcmp(value, "user") == 0;
423 
424     mDebugFlashDelay = base::GetUintProperty("debug.sf.showupdates"s, 0u);
425 
426     mBackpressureGpuComposition = base::GetBoolProperty("debug.sf.enable_gl_backpressure"s, true);
427     ALOGI_IF(mBackpressureGpuComposition, "Enabling backpressure for GPU composition");
428 
429     property_get("ro.surface_flinger.supports_background_blur", value, "0");
430     bool supportsBlurs = atoi(value);
431     mSupportsBlur = supportsBlurs;
432     ALOGI_IF(!mSupportsBlur, "Disabling blur effects, they are not supported.");
433 
434     const size_t defaultListSize = MAX_LAYERS;
435     auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
436     mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
437     mGraphicBufferProducerListSizeLogThreshold =
438             std::max(static_cast<int>(0.95 *
439                                       static_cast<double>(mMaxGraphicBufferProducerListSize)),
440                      1);
441 
442     property_get("debug.sf.luma_sampling", value, "1");
443     mLumaSampling = atoi(value);
444 
445     property_get("debug.sf.disable_client_composition_cache", value, "0");
446     mDisableClientCompositionCache = atoi(value);
447 
448     property_get("debug.sf.predict_hwc_composition_strategy", value, "1");
449     mPredictCompositionStrategy = atoi(value);
450 
451     property_get("debug.sf.treat_170m_as_sRGB", value, "0");
452     mTreat170mAsSrgb = atoi(value);
453 
454     property_get("debug.sf.dim_in_gamma_in_enhanced_screenshots", value, 0);
455     mDimInGammaSpaceForEnhancedScreenshots = atoi(value);
456 
457     mIgnoreHwcPhysicalDisplayOrientation =
458             base::GetBoolProperty("debug.sf.ignore_hwc_physical_display_orientation"s, false);
459 
460     // We should be reading 'persist.sys.sf.color_saturation' here
461     // but since /data may be encrypted, we need to wait until after vold
462     // comes online to attempt to read the property. The property is
463     // instead read after the boot animation
464 
465     if (base::GetBoolProperty("debug.sf.treble_testing_override"s, false)) {
466         // Without the override SurfaceFlinger cannot connect to HIDL
467         // services that are not listed in the manifests.  Considered
468         // deriving the setting from the set service name, but it
469         // would be brittle if the name that's not 'default' is used
470         // for production purposes later on.
471         ALOGI("Enabling Treble testing override");
472         android::hardware::details::setTrebleTestingOverride(true);
473     }
474 
475     // TODO (b/270966065) Update the HWC based refresh rate overlay to support spinner
476     mRefreshRateOverlaySpinner = property_get_bool("debug.sf.show_refresh_rate_overlay_spinner", 0);
477     mRefreshRateOverlayRenderRate =
478             property_get_bool("debug.sf.show_refresh_rate_overlay_render_rate", 0);
479     mRefreshRateOverlayShowInMiddle =
480             property_get_bool("debug.sf.show_refresh_rate_overlay_in_middle", 0);
481 
482     if (!mIsUserBuild && base::GetBoolProperty("debug.sf.enable_transaction_tracing"s, true)) {
483         mTransactionTracing.emplace();
484     }
485 
486     mIgnoreHdrCameraLayers = ignore_hdr_camera_layers(false);
487 
488     mLayerLifecycleManagerEnabled =
489             base::GetBoolProperty("persist.debug.sf.enable_layer_lifecycle_manager"s, false);
490     mLegacyFrontEndEnabled = !mLayerLifecycleManagerEnabled ||
491             base::GetBoolProperty("persist.debug.sf.enable_legacy_frontend"s, false);
492 }
493 
getLatchUnsignaledConfig()494 LatchUnsignaledConfig SurfaceFlinger::getLatchUnsignaledConfig() {
495     if (base::GetBoolProperty("debug.sf.auto_latch_unsignaled"s, true)) {
496         return LatchUnsignaledConfig::AutoSingleLayer;
497     }
498 
499     if (base::GetBoolProperty("debug.sf.latch_unsignaled"s, false)) {
500         return LatchUnsignaledConfig::Always;
501     }
502 
503     return LatchUnsignaledConfig::Disabled;
504 }
505 
506 SurfaceFlinger::~SurfaceFlinger() = default;
507 
binderDied(const wp<IBinder> &)508 void SurfaceFlinger::binderDied(const wp<IBinder>&) {
509     // the window manager died on us. prepare its eulogy.
510     mBootFinished = false;
511 
512     static_cast<void>(mScheduler->schedule([this]() FTL_FAKE_GUARD(kMainThreadContext) {
513         // Sever the link to inputflinger since it's gone as well.
514         mInputFlinger.clear();
515 
516         initializeDisplays();
517     }));
518 
519     startBootAnim();
520 }
521 
run()522 void SurfaceFlinger::run() {
523     mScheduler->run();
524 }
525 
createDisplay(const String8 & displayName,bool secure,float requestedRefreshRate)526 sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName, bool secure,
527                                           float requestedRefreshRate) {
528     // onTransact already checks for some permissions, but adding an additional check here.
529     // This is to ensure that only system and graphics can request to create a secure
530     // display. Secure displays can show secure content so we add an additional restriction on it.
531     const int uid = IPCThreadState::self()->getCallingUid();
532     if (secure && uid != AID_GRAPHICS && uid != AID_SYSTEM) {
533         ALOGE("Only privileged processes can create a secure display");
534         return nullptr;
535     }
536 
537     class DisplayToken : public BBinder {
538         sp<SurfaceFlinger> flinger;
539         virtual ~DisplayToken() {
540              // no more references, this display must be terminated
541              Mutex::Autolock _l(flinger->mStateLock);
542              flinger->mCurrentState.displays.removeItem(wp<IBinder>::fromExisting(this));
543              flinger->setTransactionFlags(eDisplayTransactionNeeded);
544          }
545      public:
546         explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
547             : flinger(flinger) {
548         }
549     };
550 
551     sp<BBinder> token = sp<DisplayToken>::make(sp<SurfaceFlinger>::fromExisting(this));
552 
553     Mutex::Autolock _l(mStateLock);
554     // Display ID is assigned when virtual display is allocated by HWC.
555     DisplayDeviceState state;
556     state.isSecure = secure;
557     state.displayName = displayName;
558     state.requestedRefreshRate = Fps::fromValue(requestedRefreshRate);
559     mCurrentState.displays.add(token, state);
560     return token;
561 }
562 
destroyDisplay(const sp<IBinder> & displayToken)563 void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
564     Mutex::Autolock lock(mStateLock);
565 
566     const ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
567     if (index < 0) {
568         ALOGE("%s: Invalid display token %p", __func__, displayToken.get());
569         return;
570     }
571 
572     const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
573     if (state.physical) {
574         ALOGE("%s: Invalid operation on physical display", __func__);
575         return;
576     }
577     mCurrentState.displays.removeItemsAt(index);
578     setTransactionFlags(eDisplayTransactionNeeded);
579 }
580 
enableHalVirtualDisplays(bool enable)581 void SurfaceFlinger::enableHalVirtualDisplays(bool enable) {
582     auto& generator = mVirtualDisplayIdGenerators.hal;
583     if (!generator && enable) {
584         ALOGI("Enabling HAL virtual displays");
585         generator.emplace(getHwComposer().getMaxVirtualDisplayCount());
586     } else if (generator && !enable) {
587         ALOGW_IF(generator->inUse(), "Disabling HAL virtual displays while in use");
588         generator.reset();
589     }
590 }
591 
acquireVirtualDisplay(ui::Size resolution,ui::PixelFormat format)592 VirtualDisplayId SurfaceFlinger::acquireVirtualDisplay(ui::Size resolution,
593                                                        ui::PixelFormat format) {
594     if (auto& generator = mVirtualDisplayIdGenerators.hal) {
595         if (const auto id = generator->generateId()) {
596             if (getHwComposer().allocateVirtualDisplay(*id, resolution, &format)) {
597                 return *id;
598             }
599 
600             generator->releaseId(*id);
601         } else {
602             ALOGW("%s: Exhausted HAL virtual displays", __func__);
603         }
604 
605         ALOGW("%s: Falling back to GPU virtual display", __func__);
606     }
607 
608     const auto id = mVirtualDisplayIdGenerators.gpu.generateId();
609     LOG_ALWAYS_FATAL_IF(!id, "Failed to generate ID for GPU virtual display");
610     return *id;
611 }
612 
releaseVirtualDisplay(VirtualDisplayId displayId)613 void SurfaceFlinger::releaseVirtualDisplay(VirtualDisplayId displayId) {
614     if (const auto id = HalVirtualDisplayId::tryCast(displayId)) {
615         if (auto& generator = mVirtualDisplayIdGenerators.hal) {
616             generator->releaseId(*id);
617         }
618         return;
619     }
620 
621     const auto id = GpuVirtualDisplayId::tryCast(displayId);
622     LOG_ALWAYS_FATAL_IF(!id);
623     mVirtualDisplayIdGenerators.gpu.releaseId(*id);
624 }
625 
getPhysicalDisplayIdsLocked() const626 std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIdsLocked() const {
627     std::vector<PhysicalDisplayId> displayIds;
628     displayIds.reserve(mPhysicalDisplays.size());
629 
630     const auto defaultDisplayId = getDefaultDisplayDeviceLocked()->getPhysicalId();
631     displayIds.push_back(defaultDisplayId);
632 
633     for (const auto& [id, display] : mPhysicalDisplays) {
634         if (id != defaultDisplayId) {
635             displayIds.push_back(id);
636         }
637     }
638 
639     return displayIds;
640 }
641 
getPhysicalDisplayIdLocked(const sp<display::DisplayToken> & displayToken) const642 std::optional<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIdLocked(
643         const sp<display::DisplayToken>& displayToken) const {
644     return ftl::find_if(mPhysicalDisplays, PhysicalDisplay::hasToken(displayToken))
645             .transform(&ftl::to_key<PhysicalDisplays>);
646 }
647 
getPhysicalDisplayToken(PhysicalDisplayId displayId) const648 sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
649     Mutex::Autolock lock(mStateLock);
650     return getPhysicalDisplayTokenLocked(displayId);
651 }
652 
getColorManagement(bool * outGetColorManagement) const653 status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
654     if (!outGetColorManagement) {
655         return BAD_VALUE;
656     }
657     *outGetColorManagement = useColorManagement;
658     return NO_ERROR;
659 }
660 
getHwComposer() const661 HWComposer& SurfaceFlinger::getHwComposer() const {
662     return mCompositionEngine->getHwComposer();
663 }
664 
getRenderEngine() const665 renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
666     return *mRenderEngine;
667 }
668 
getCompositionEngine() const669 compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
670     return *mCompositionEngine.get();
671 }
672 
bootFinished()673 void SurfaceFlinger::bootFinished() {
674     if (mBootFinished == true) {
675         ALOGE("Extra call to bootFinished");
676         return;
677     }
678     mBootFinished = true;
679     if (mStartPropertySetThread->join() != NO_ERROR) {
680         ALOGE("Join StartPropertySetThread failed!");
681     }
682 
683     if (mRenderEnginePrimeCacheFuture.valid()) {
684         mRenderEnginePrimeCacheFuture.get();
685     }
686     const nsecs_t now = systemTime();
687     const nsecs_t duration = now - mBootTime;
688     ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
689 
690     mFrameTracer->initialize();
691     mFrameTimeline->onBootFinished();
692     getRenderEngine().setEnableTracing(mFlagManager.use_skia_tracing());
693 
694     // wait patiently for the window manager death
695     const String16 name("window");
696     mWindowManager = defaultServiceManager()->getService(name);
697     if (mWindowManager != 0) {
698         mWindowManager->linkToDeath(sp<IBinder::DeathRecipient>::fromExisting(this));
699     }
700 
701     // stop boot animation
702     // formerly we would just kill the process, but we now ask it to exit so it
703     // can choose where to stop the animation.
704     property_set("service.bootanim.exit", "1");
705 
706     const int LOGTAG_SF_STOP_BOOTANIM = 60110;
707     LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
708                    ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
709 
710     sp<IBinder> input(defaultServiceManager()->getService(String16("inputflinger")));
711 
712     static_cast<void>(mScheduler->schedule([=]() FTL_FAKE_GUARD(kMainThreadContext) {
713         if (input == nullptr) {
714             ALOGE("Failed to link to input service");
715         } else {
716             mInputFlinger = interface_cast<os::IInputFlinger>(input);
717         }
718 
719         readPersistentProperties();
720         mPowerAdvisor->onBootFinished();
721         const bool hintSessionEnabled = mFlagManager.use_adpf_cpu_hint();
722         mPowerAdvisor->enablePowerHintSession(hintSessionEnabled);
723         const bool hintSessionUsed = mPowerAdvisor->usePowerHintSession();
724         ALOGD("Power hint is %s",
725               hintSessionUsed ? "supported" : (hintSessionEnabled ? "unsupported" : "disabled"));
726         if (hintSessionUsed) {
727             std::optional<pid_t> renderEngineTid = getRenderEngine().getRenderEngineTid();
728             std::vector<int32_t> tidList;
729             tidList.emplace_back(gettid());
730             if (renderEngineTid.has_value()) {
731                 tidList.emplace_back(*renderEngineTid);
732             }
733             if (!mPowerAdvisor->startPowerHintSession(tidList)) {
734                 ALOGW("Cannot start power hint session");
735             }
736         }
737 
738         mBootStage = BootStage::FINISHED;
739 
740         if (base::GetBoolProperty("sf.debug.show_refresh_rate_overlay"s, false)) {
741             ftl::FakeGuard guard(mStateLock);
742             enableRefreshRateOverlay(true);
743         }
744     }));
745 }
746 
getNewTexture()747 uint32_t SurfaceFlinger::getNewTexture() {
748     {
749         std::lock_guard lock(mTexturePoolMutex);
750         if (!mTexturePool.empty()) {
751             uint32_t name = mTexturePool.back();
752             mTexturePool.pop_back();
753             ATRACE_INT("TexturePoolSize", mTexturePool.size());
754             return name;
755         }
756 
757         // The pool was too small, so increase it for the future
758         ++mTexturePoolSize;
759     }
760 
761     // The pool was empty, so we need to get a new texture name directly using a
762     // blocking call to the main thread
763     auto genTextures = [this] {
764                uint32_t name = 0;
765                getRenderEngine().genTextures(1, &name);
766                return name;
767     };
768     if (std::this_thread::get_id() == mMainThreadId) {
769         return genTextures();
770     } else {
771         return mScheduler->schedule(genTextures).get();
772     }
773 }
774 
deleteTextureAsync(uint32_t texture)775 void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
776     std::lock_guard lock(mTexturePoolMutex);
777     // We don't change the pool size, so the fix-up logic in postComposition will decide whether
778     // to actually delete this or not based on mTexturePoolSize
779     mTexturePool.push_back(texture);
780     ATRACE_INT("TexturePoolSize", mTexturePool.size());
781 }
782 
783 static std::optional<renderengine::RenderEngine::RenderEngineType>
chooseRenderEngineTypeViaSysProp()784 chooseRenderEngineTypeViaSysProp() {
785     char prop[PROPERTY_VALUE_MAX];
786     property_get(PROPERTY_DEBUG_RENDERENGINE_BACKEND, prop, "");
787 
788     if (strcmp(prop, "gles") == 0) {
789         return renderengine::RenderEngine::RenderEngineType::GLES;
790     } else if (strcmp(prop, "threaded") == 0) {
791         return renderengine::RenderEngine::RenderEngineType::THREADED;
792     } else if (strcmp(prop, "skiagl") == 0) {
793         return renderengine::RenderEngine::RenderEngineType::SKIA_GL;
794     } else if (strcmp(prop, "skiaglthreaded") == 0) {
795         return renderengine::RenderEngine::RenderEngineType::SKIA_GL_THREADED;
796     } else if (strcmp(prop, "skiavk") == 0) {
797         return renderengine::RenderEngine::RenderEngineType::SKIA_VK;
798     } else if (strcmp(prop, "skiavkthreaded") == 0) {
799         return renderengine::RenderEngine::RenderEngineType::SKIA_VK_THREADED;
800     } else {
801         ALOGE("Unrecognized RenderEngineType %s; ignoring!", prop);
802         return {};
803     }
804 }
805 
806 // Do not call property_set on main thread which will be blocked by init
807 // Use StartPropertySetThread instead.
init()808 void SurfaceFlinger::init() FTL_FAKE_GUARD(kMainThreadContext) {
809     ALOGI(  "SurfaceFlinger's main thread ready to run. "
810             "Initializing graphics H/W...");
811     addTransactionReadyFilters();
812     Mutex::Autolock lock(mStateLock);
813 
814     // Get a RenderEngine for the given display / config (can't fail)
815     // TODO(b/77156734): We need to stop casting and use HAL types when possible.
816     // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
817     auto builder = renderengine::RenderEngineCreationArgs::Builder()
818                            .setPixelFormat(static_cast<int32_t>(defaultCompositionPixelFormat))
819                            .setImageCacheSize(maxFrameBufferAcquiredBuffers)
820                            .setUseColorManagerment(useColorManagement)
821                            .setEnableProtectedContext(enable_protected_contents(false))
822                            .setPrecacheToneMapperShaderOnly(false)
823                            .setSupportsBackgroundBlur(mSupportsBlur)
824                            .setContextPriority(
825                                    useContextPriority
826                                            ? renderengine::RenderEngine::ContextPriority::REALTIME
827                                            : renderengine::RenderEngine::ContextPriority::MEDIUM);
828     if (auto type = chooseRenderEngineTypeViaSysProp()) {
829         builder.setRenderEngineType(type.value());
830     }
831     mRenderEngine = renderengine::RenderEngine::create(builder.build());
832     mCompositionEngine->setRenderEngine(mRenderEngine.get());
833     mMaxRenderTargetSize =
834             std::min(getRenderEngine().getMaxTextureSize(), getRenderEngine().getMaxViewportDims());
835 
836     // Set SF main policy after initializing RenderEngine which has its own policy.
837     if (!SetTaskProfiles(0, {"SFMainPolicy"})) {
838         ALOGW("Failed to set main task profile");
839     }
840 
841     mCompositionEngine->setTimeStats(mTimeStats);
842     mCompositionEngine->setHwComposer(getFactory().createHWComposer(mHwcServiceName));
843     mCompositionEngine->getHwComposer().setCallback(*this);
844     ClientCache::getInstance().setRenderEngine(&getRenderEngine());
845 
846     enableLatchUnsignaledConfig = getLatchUnsignaledConfig();
847 
848     if (base::GetBoolProperty("debug.sf.enable_hwc_vds"s, false)) {
849         enableHalVirtualDisplays(true);
850     }
851 
852     // Process hotplug for displays connected at boot.
853     LOG_ALWAYS_FATAL_IF(!configureLocked(),
854                         "Initial display configuration failed: HWC did not hotplug");
855 
856     // Commit primary display.
857     sp<const DisplayDevice> display;
858     if (const auto indexOpt = mCurrentState.getDisplayIndex(getPrimaryDisplayIdLocked())) {
859         const auto& displays = mCurrentState.displays;
860 
861         const auto& token = displays.keyAt(*indexOpt);
862         const auto& state = displays.valueAt(*indexOpt);
863 
864         processDisplayAdded(token, state);
865         mDrawingState.displays.add(token, state);
866 
867         display = getDefaultDisplayDeviceLocked();
868     }
869 
870     LOG_ALWAYS_FATAL_IF(!display, "Failed to configure the primary display");
871     LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(display->getPhysicalId()),
872                         "Primary display is disconnected");
873 
874     // TODO(b/241285876): The Scheduler needlessly depends on creating the CompositionEngine part of
875     // the DisplayDevice, hence the above commit of the primary display. Remove that special case by
876     // initializing the Scheduler after configureLocked, once decoupled from DisplayDevice.
877     initScheduler(display);
878     dispatchDisplayHotplugEvent(display->getPhysicalId(), true);
879 
880     // Commit secondary display(s).
881     processDisplayChangesLocked();
882 
883     // initialize our drawing state
884     mDrawingState = mCurrentState;
885 
886     onActiveDisplayChangedLocked(nullptr, *display);
887 
888     static_cast<void>(mScheduler->schedule(
889             [this]() FTL_FAKE_GUARD(kMainThreadContext) { initializeDisplays(); }));
890 
891     mPowerAdvisor->init();
892 
893     char primeShaderCache[PROPERTY_VALUE_MAX];
894     property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
895     if (atoi(primeShaderCache)) {
896         if (setSchedFifo(false) != NO_ERROR) {
897             ALOGW("Can't set SCHED_OTHER for primeCache");
898         }
899 
900         mRenderEnginePrimeCacheFuture = getRenderEngine().primeCache();
901 
902         if (setSchedFifo(true) != NO_ERROR) {
903             ALOGW("Can't set SCHED_OTHER for primeCache");
904         }
905     }
906 
907     // Inform native graphics APIs whether the present timestamp is supported:
908 
909     const bool presentFenceReliable =
910             !getHwComposer().hasCapability(Capability::PRESENT_FENCE_IS_NOT_RELIABLE);
911     mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
912 
913     if (mStartPropertySetThread->Start() != NO_ERROR) {
914         ALOGE("Run StartPropertySetThread failed!");
915     }
916 
917     if (mTransactionTracing) {
918         TransactionTraceWriter::getInstance().setWriterFunction([&](const std::string& prefix,
919                                                                     bool overwrite) {
920             auto writeFn = [&]() {
921                 const std::string filename =
922                         TransactionTracing::DIR_NAME + prefix + TransactionTracing::FILE_NAME;
923                 if (overwrite && access(filename.c_str(), F_OK) == 0) {
924                     ALOGD("TransactionTraceWriter: file=%s already exists", filename.c_str());
925                     return;
926                 }
927                 mTransactionTracing->flush();
928                 mTransactionTracing->writeToFile(filename);
929             };
930             if (std::this_thread::get_id() == mMainThreadId) {
931                 writeFn();
932             } else {
933                 mScheduler->schedule(writeFn).get();
934             }
935         });
936     }
937 
938     ALOGV("Done initializing");
939 }
940 
readPersistentProperties()941 void SurfaceFlinger::readPersistentProperties() {
942     Mutex::Autolock _l(mStateLock);
943 
944     char value[PROPERTY_VALUE_MAX];
945 
946     property_get("persist.sys.sf.color_saturation", value, "1.0");
947     mGlobalSaturationFactor = atof(value);
948     updateColorMatrixLocked();
949     ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
950 
951     property_get("persist.sys.sf.native_mode", value, "0");
952     mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
953 
954     mForceColorMode =
955             static_cast<ui::ColorMode>(base::GetIntProperty("persist.sys.sf.color_mode"s, 0));
956 }
957 
startBootAnim()958 void SurfaceFlinger::startBootAnim() {
959     // Start boot animation service by setting a property mailbox
960     // if property setting thread is already running, Start() will be just a NOP
961     mStartPropertySetThread->Start();
962     // Wait until property was set
963     if (mStartPropertySetThread->join() != NO_ERROR) {
964         ALOGE("Join StartPropertySetThread failed!");
965     }
966 }
967 
968 // ----------------------------------------------------------------------------
969 
getSupportedFrameTimestamps(std::vector<FrameEvent> * outSupported) const970 status_t SurfaceFlinger::getSupportedFrameTimestamps(
971         std::vector<FrameEvent>* outSupported) const {
972     *outSupported = {
973         FrameEvent::REQUESTED_PRESENT,
974         FrameEvent::ACQUIRE,
975         FrameEvent::LATCH,
976         FrameEvent::FIRST_REFRESH_START,
977         FrameEvent::LAST_REFRESH_START,
978         FrameEvent::GPU_COMPOSITION_DONE,
979         FrameEvent::DEQUEUE_READY,
980         FrameEvent::RELEASE,
981     };
982 
983     ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
984 
985     if (!getHwComposer().hasCapability(Capability::PRESENT_FENCE_IS_NOT_RELIABLE)) {
986         outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
987     }
988     return NO_ERROR;
989 }
990 
getDisplayState(const sp<IBinder> & displayToken,ui::DisplayState * state)991 status_t SurfaceFlinger::getDisplayState(const sp<IBinder>& displayToken, ui::DisplayState* state) {
992     if (!displayToken || !state) {
993         return BAD_VALUE;
994     }
995 
996     Mutex::Autolock lock(mStateLock);
997 
998     const auto display = getDisplayDeviceLocked(displayToken);
999     if (!display) {
1000         return NAME_NOT_FOUND;
1001     }
1002 
1003     state->layerStack = display->getLayerStack();
1004     state->orientation = display->getOrientation();
1005 
1006     const Rect layerStackRect = display->getLayerStackSpaceRect();
1007     state->layerStackSpaceRect =
1008             layerStackRect.isValid() ? layerStackRect.getSize() : display->getSize();
1009 
1010     return NO_ERROR;
1011 }
1012 
getStaticDisplayInfo(int64_t displayId,ui::StaticDisplayInfo * info)1013 status_t SurfaceFlinger::getStaticDisplayInfo(int64_t displayId, ui::StaticDisplayInfo* info) {
1014     if (!info) {
1015         return BAD_VALUE;
1016     }
1017 
1018     Mutex::Autolock lock(mStateLock);
1019     const auto id = DisplayId::fromValue<PhysicalDisplayId>(static_cast<uint64_t>(displayId));
1020     const auto displayOpt = mPhysicalDisplays.get(*id).and_then(getDisplayDeviceAndSnapshot());
1021 
1022     if (!displayOpt) {
1023         return NAME_NOT_FOUND;
1024     }
1025 
1026     const auto& [display, snapshotRef] = *displayOpt;
1027     const auto& snapshot = snapshotRef.get();
1028 
1029     info->connectionType = snapshot.connectionType();
1030     info->deviceProductInfo = snapshot.deviceProductInfo();
1031 
1032     if (mEmulatedDisplayDensity) {
1033         info->density = mEmulatedDisplayDensity;
1034     } else {
1035         info->density = info->connectionType == ui::DisplayConnectionType::Internal
1036                 ? mInternalDisplayDensity
1037                 : FALLBACK_DENSITY;
1038     }
1039     info->density /= ACONFIGURATION_DENSITY_MEDIUM;
1040 
1041     info->secure = display->isSecure();
1042     info->installOrientation = display->getPhysicalOrientation();
1043 
1044     return NO_ERROR;
1045 }
1046 
getDynamicDisplayInfoInternal(ui::DynamicDisplayInfo * & info,const sp<DisplayDevice> & display,const display::DisplaySnapshot & snapshot)1047 void SurfaceFlinger::getDynamicDisplayInfoInternal(ui::DynamicDisplayInfo*& info,
1048                                                    const sp<DisplayDevice>& display,
1049                                                    const display::DisplaySnapshot& snapshot) {
1050     const auto& displayModes = snapshot.displayModes();
1051     info->supportedDisplayModes.clear();
1052     info->supportedDisplayModes.reserve(displayModes.size());
1053 
1054     for (const auto& [id, mode] : displayModes) {
1055         ui::DisplayMode outMode;
1056         outMode.id = static_cast<int32_t>(id.value());
1057 
1058         auto [width, height] = mode->getResolution();
1059         auto [xDpi, yDpi] = mode->getDpi();
1060 
1061         if (const auto physicalOrientation = display->getPhysicalOrientation();
1062             physicalOrientation == ui::ROTATION_90 || physicalOrientation == ui::ROTATION_270) {
1063             std::swap(width, height);
1064             std::swap(xDpi, yDpi);
1065         }
1066 
1067         outMode.resolution = ui::Size(width, height);
1068 
1069         outMode.xDpi = xDpi;
1070         outMode.yDpi = yDpi;
1071 
1072         const nsecs_t period = mode->getVsyncPeriod();
1073         outMode.refreshRate = Fps::fromPeriodNsecs(period).getValue();
1074 
1075         const auto vsyncConfigSet =
1076                 mVsyncConfiguration->getConfigsForRefreshRate(Fps::fromValue(outMode.refreshRate));
1077         outMode.appVsyncOffset = vsyncConfigSet.late.appOffset;
1078         outMode.sfVsyncOffset = vsyncConfigSet.late.sfOffset;
1079         outMode.group = mode->getGroup();
1080 
1081         // This is how far in advance a buffer must be queued for
1082         // presentation at a given time.  If you want a buffer to appear
1083         // on the screen at time N, you must submit the buffer before
1084         // (N - presentationDeadline).
1085         //
1086         // Normally it's one full refresh period (to give SF a chance to
1087         // latch the buffer), but this can be reduced by configuring a
1088         // VsyncController offset.  Any additional delays introduced by the hardware
1089         // composer or panel must be accounted for here.
1090         //
1091         // We add an additional 1ms to allow for processing time and
1092         // differences between the ideal and actual refresh rate.
1093         outMode.presentationDeadline = period - outMode.sfVsyncOffset + 1000000;
1094         excludeDolbyVisionIf4k30Present(display->getHdrCapabilities().getSupportedHdrTypes(),
1095                                         outMode);
1096         info->supportedDisplayModes.push_back(outMode);
1097     }
1098 
1099     info->supportedColorModes = snapshot.filterColorModes(mSupportsWideColor);
1100 
1101     const PhysicalDisplayId displayId = snapshot.displayId();
1102 
1103     const auto mode = display->refreshRateSelector().getActiveMode();
1104     info->activeDisplayModeId = mode.modePtr->getId().value();
1105     info->renderFrameRate = mode.fps.getValue();
1106     info->activeColorMode = display->getCompositionDisplay()->getState().colorMode;
1107     info->hdrCapabilities = filterOut4k30(display->getHdrCapabilities());
1108 
1109     info->autoLowLatencyModeSupported =
1110             getHwComposer().hasDisplayCapability(displayId,
1111                                                  DisplayCapability::AUTO_LOW_LATENCY_MODE);
1112     info->gameContentTypeSupported =
1113             getHwComposer().supportsContentType(displayId, hal::ContentType::GAME);
1114 
1115     info->preferredBootDisplayMode = static_cast<ui::DisplayModeId>(-1);
1116 
1117     if (getHwComposer().hasCapability(Capability::BOOT_DISPLAY_CONFIG)) {
1118         if (const auto hwcId = getHwComposer().getPreferredBootDisplayMode(displayId)) {
1119             if (const auto modeId = snapshot.translateModeId(*hwcId)) {
1120                 info->preferredBootDisplayMode = modeId->value();
1121             }
1122         }
1123     }
1124 }
1125 
getDynamicDisplayInfoFromId(int64_t physicalDisplayId,ui::DynamicDisplayInfo * info)1126 status_t SurfaceFlinger::getDynamicDisplayInfoFromId(int64_t physicalDisplayId,
1127                                                      ui::DynamicDisplayInfo* info) {
1128     if (!info) {
1129         return BAD_VALUE;
1130     }
1131 
1132     Mutex::Autolock lock(mStateLock);
1133 
1134     const auto id_ =
1135             DisplayId::fromValue<PhysicalDisplayId>(static_cast<uint64_t>(physicalDisplayId));
1136     const auto displayOpt = mPhysicalDisplays.get(*id_).and_then(getDisplayDeviceAndSnapshot());
1137 
1138     if (!displayOpt) {
1139         return NAME_NOT_FOUND;
1140     }
1141 
1142     const auto& [display, snapshotRef] = *displayOpt;
1143     getDynamicDisplayInfoInternal(info, display, snapshotRef.get());
1144     return NO_ERROR;
1145 }
1146 
getDynamicDisplayInfoFromToken(const sp<IBinder> & displayToken,ui::DynamicDisplayInfo * info)1147 status_t SurfaceFlinger::getDynamicDisplayInfoFromToken(const sp<IBinder>& displayToken,
1148                                                         ui::DynamicDisplayInfo* info) {
1149     if (!displayToken || !info) {
1150         return BAD_VALUE;
1151     }
1152 
1153     Mutex::Autolock lock(mStateLock);
1154 
1155     const auto displayOpt = ftl::find_if(mPhysicalDisplays, PhysicalDisplay::hasToken(displayToken))
1156                                     .transform(&ftl::to_mapped_ref<PhysicalDisplays>)
1157                                     .and_then(getDisplayDeviceAndSnapshot());
1158 
1159     if (!displayOpt) {
1160         return NAME_NOT_FOUND;
1161     }
1162 
1163     const auto& [display, snapshotRef] = *displayOpt;
1164     getDynamicDisplayInfoInternal(info, display, snapshotRef.get());
1165     return NO_ERROR;
1166 }
1167 
getDisplayStats(const sp<IBinder> & displayToken,DisplayStatInfo * outStats)1168 status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& displayToken,
1169                                          DisplayStatInfo* outStats) {
1170     if (!outStats) {
1171         return BAD_VALUE;
1172     }
1173 
1174     std::optional<PhysicalDisplayId> displayIdOpt;
1175     {
1176         Mutex::Autolock lock(mStateLock);
1177         if (displayToken) {
1178             displayIdOpt = getPhysicalDisplayIdLocked(displayToken);
1179             if (!displayIdOpt) {
1180                 ALOGW("%s: Invalid physical display token %p", __func__, displayToken.get());
1181                 return NAME_NOT_FOUND;
1182             }
1183         } else {
1184             // TODO (b/277364366): Clients should be updated to pass in the display they
1185             // want, rather than us picking an arbitrary one (the active display, in this
1186             // case).
1187             displayIdOpt = mActiveDisplayId;
1188         }
1189     }
1190 
1191     const auto schedule = mScheduler->getVsyncSchedule(displayIdOpt);
1192     if (!schedule) {
1193         ALOGE("%s: Missing VSYNC schedule for display %s!", __func__,
1194               to_string(*displayIdOpt).c_str());
1195         return NAME_NOT_FOUND;
1196     }
1197     outStats->vsyncTime = schedule->vsyncDeadlineAfter(TimePoint::now()).ns();
1198     outStats->vsyncPeriod = schedule->period().ns();
1199     return NO_ERROR;
1200 }
1201 
setDesiredActiveMode(display::DisplayModeRequest && request,bool force)1202 void SurfaceFlinger::setDesiredActiveMode(display::DisplayModeRequest&& request, bool force) {
1203     const auto displayId = request.mode.modePtr->getPhysicalDisplayId();
1204     ATRACE_NAME(ftl::Concat(__func__, ' ', displayId.value).c_str());
1205 
1206     const auto display = getDisplayDeviceLocked(displayId);
1207     if (!display) {
1208         ALOGW("%s: display is no longer valid", __func__);
1209         return;
1210     }
1211 
1212     const auto mode = request.mode;
1213     const bool emitEvent = request.emitEvent;
1214 
1215     switch (display->setDesiredActiveMode(DisplayDevice::ActiveModeInfo(std::move(request)),
1216                                           force)) {
1217         case DisplayDevice::DesiredActiveModeAction::InitiateDisplayModeSwitch:
1218             // Set the render rate as setDesiredActiveMode updated it.
1219             mScheduler->setRenderRate(displayId,
1220                                       display->refreshRateSelector().getActiveMode().fps);
1221 
1222             // Schedule a new frame to initiate the display mode switch.
1223             scheduleComposite(FrameHint::kNone);
1224 
1225             // Start receiving vsync samples now, so that we can detect a period
1226             // switch.
1227             mScheduler->resyncToHardwareVsync(displayId, true /* allowToEnable */,
1228                                               mode.modePtr->getFps());
1229 
1230             // As we called to set period, we will call to onRefreshRateChangeCompleted once
1231             // VsyncController model is locked.
1232             mScheduler->modulateVsync(displayId, &VsyncModulator::onRefreshRateChangeInitiated);
1233 
1234             if (displayId == mActiveDisplayId) {
1235                 updatePhaseConfiguration(mode.fps);
1236             }
1237 
1238             mScheduler->setModeChangePending(true);
1239             break;
1240         case DisplayDevice::DesiredActiveModeAction::InitiateRenderRateSwitch:
1241             mScheduler->setRenderRate(displayId, mode.fps);
1242 
1243             if (displayId == mActiveDisplayId) {
1244                 updatePhaseConfiguration(mode.fps);
1245                 mRefreshRateStats->setRefreshRate(mode.fps);
1246             }
1247 
1248             if (emitEvent) {
1249                 dispatchDisplayModeChangeEvent(displayId, mode);
1250             }
1251             break;
1252         case DisplayDevice::DesiredActiveModeAction::None:
1253             break;
1254     }
1255 }
1256 
setActiveModeFromBackdoor(const sp<display::DisplayToken> & displayToken,DisplayModeId modeId)1257 status_t SurfaceFlinger::setActiveModeFromBackdoor(const sp<display::DisplayToken>& displayToken,
1258                                                    DisplayModeId modeId) {
1259     ATRACE_CALL();
1260 
1261     if (!displayToken) {
1262         return BAD_VALUE;
1263     }
1264 
1265     const char* const whence = __func__;
1266     auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(kMainThreadContext) -> status_t {
1267         const auto displayOpt =
1268                 FTL_FAKE_GUARD(mStateLock,
1269                                ftl::find_if(mPhysicalDisplays,
1270                                             PhysicalDisplay::hasToken(displayToken))
1271                                        .transform(&ftl::to_mapped_ref<PhysicalDisplays>)
1272                                        .and_then(getDisplayDeviceAndSnapshot()));
1273         if (!displayOpt) {
1274             ALOGE("%s: Invalid physical display token %p", whence, displayToken.get());
1275             return NAME_NOT_FOUND;
1276         }
1277 
1278         const auto& [display, snapshotRef] = *displayOpt;
1279         const auto& snapshot = snapshotRef.get();
1280 
1281         const auto fpsOpt = snapshot.displayModes().get(modeId).transform(
1282                 [](const DisplayModePtr& mode) { return mode->getFps(); });
1283 
1284         if (!fpsOpt) {
1285             ALOGE("%s: Invalid mode %d for display %s", whence, modeId.value(),
1286                   to_string(snapshot.displayId()).c_str());
1287             return BAD_VALUE;
1288         }
1289 
1290         const Fps fps = *fpsOpt;
1291 
1292         // Keep the old switching type.
1293         const bool allowGroupSwitching =
1294                 display->refreshRateSelector().getCurrentPolicy().allowGroupSwitching;
1295 
1296         const scheduler::RefreshRateSelector::DisplayManagerPolicy policy{modeId,
1297                                                                           {fps, fps},
1298                                                                           allowGroupSwitching};
1299 
1300         return setDesiredDisplayModeSpecsInternal(display, policy);
1301     });
1302 
1303     return future.get();
1304 }
1305 
finalizeDisplayModeChange(DisplayDevice & display)1306 void SurfaceFlinger::finalizeDisplayModeChange(DisplayDevice& display) {
1307     const auto displayId = display.getPhysicalId();
1308     ATRACE_NAME(ftl::Concat(__func__, ' ', displayId.value).c_str());
1309 
1310     const auto upcomingModeInfo = display.getUpcomingActiveMode();
1311     if (!upcomingModeInfo.modeOpt) {
1312         // There is no pending mode change. This can happen if the active
1313         // display changed and the mode change happened on a different display.
1314         return;
1315     }
1316 
1317     if (display.getActiveMode().modePtr->getResolution() !=
1318         upcomingModeInfo.modeOpt->modePtr->getResolution()) {
1319         auto& state = mCurrentState.displays.editValueFor(display.getDisplayToken());
1320         // We need to generate new sequenceId in order to recreate the display (and this
1321         // way the framebuffer).
1322         state.sequenceId = DisplayDeviceState{}.sequenceId;
1323         state.physical->activeMode = upcomingModeInfo.modeOpt->modePtr.get();
1324         processDisplayChangesLocked();
1325 
1326         // processDisplayChangesLocked will update all necessary components so we're done here.
1327         return;
1328     }
1329 
1330     const auto& activeMode = *upcomingModeInfo.modeOpt;
1331     display.finalizeModeChange(activeMode.modePtr->getId(), activeMode.modePtr->getFps(),
1332                                activeMode.fps);
1333 
1334     if (displayId == mActiveDisplayId) {
1335         mRefreshRateStats->setRefreshRate(activeMode.fps);
1336         updatePhaseConfiguration(activeMode.fps);
1337     }
1338 
1339     if (upcomingModeInfo.event != scheduler::DisplayModeEvent::None) {
1340         dispatchDisplayModeChangeEvent(displayId, activeMode);
1341     }
1342 }
1343 
clearDesiredActiveModeState(const sp<DisplayDevice> & display)1344 void SurfaceFlinger::clearDesiredActiveModeState(const sp<DisplayDevice>& display) {
1345     display->clearDesiredActiveModeState();
1346     if (display->getPhysicalId() == mActiveDisplayId) {
1347         // TODO(b/255635711): Check for pending mode changes on other displays.
1348         mScheduler->setModeChangePending(false);
1349     }
1350 }
1351 
desiredActiveModeChangeDone(const sp<DisplayDevice> & display)1352 void SurfaceFlinger::desiredActiveModeChangeDone(const sp<DisplayDevice>& display) {
1353     const auto desiredActiveMode = display->getDesiredActiveMode();
1354     const auto& modeOpt = desiredActiveMode->modeOpt;
1355     const auto displayId = modeOpt->modePtr->getPhysicalDisplayId();
1356     const auto displayFps = modeOpt->modePtr->getFps();
1357     const auto renderFps = modeOpt->fps;
1358     clearDesiredActiveModeState(display);
1359     mScheduler->resyncToHardwareVsync(displayId, true /* allowToEnable */, displayFps);
1360     mScheduler->setRenderRate(displayId, renderFps);
1361 
1362     if (displayId == mActiveDisplayId) {
1363         updatePhaseConfiguration(renderFps);
1364     }
1365 }
1366 
initiateDisplayModeChanges()1367 void SurfaceFlinger::initiateDisplayModeChanges() {
1368     ATRACE_CALL();
1369 
1370     std::optional<PhysicalDisplayId> displayToUpdateImmediately;
1371 
1372     for (const auto& [id, physical] : mPhysicalDisplays) {
1373         const auto display = getDisplayDeviceLocked(id);
1374         if (!display) continue;
1375 
1376         // Store the local variable to release the lock.
1377         const auto desiredActiveMode = display->getDesiredActiveMode();
1378         if (!desiredActiveMode) {
1379             // No desired active mode pending to be applied.
1380             continue;
1381         }
1382 
1383         if (!shouldApplyRefreshRateSelectorPolicy(*display)) {
1384             clearDesiredActiveModeState(display);
1385             continue;
1386         }
1387 
1388         const auto desiredModeId = desiredActiveMode->modeOpt->modePtr->getId();
1389         const auto displayModePtrOpt = physical.snapshot().displayModes().get(desiredModeId);
1390 
1391         if (!displayModePtrOpt) {
1392             ALOGW("Desired display mode is no longer supported. Mode ID = %d",
1393                   desiredModeId.value());
1394             clearDesiredActiveModeState(display);
1395             continue;
1396         }
1397 
1398         ALOGV("%s changing active mode to %d(%s) for display %s", __func__, desiredModeId.value(),
1399               to_string(displayModePtrOpt->get()->getFps()).c_str(),
1400               to_string(display->getId()).c_str());
1401 
1402         if (display->getActiveMode() == desiredActiveMode->modeOpt) {
1403             // we are already in the requested mode, there is nothing left to do
1404             desiredActiveModeChangeDone(display);
1405             continue;
1406         }
1407 
1408         // Desired active mode was set, it is different than the mode currently in use, however
1409         // allowed modes might have changed by the time we process the refresh.
1410         // Make sure the desired mode is still allowed
1411         const auto displayModeAllowed =
1412                 display->refreshRateSelector().isModeAllowed(*desiredActiveMode->modeOpt);
1413         if (!displayModeAllowed) {
1414             clearDesiredActiveModeState(display);
1415             continue;
1416         }
1417 
1418         // TODO(b/142753666) use constrains
1419         hal::VsyncPeriodChangeConstraints constraints;
1420         constraints.desiredTimeNanos = systemTime();
1421         constraints.seamlessRequired = false;
1422         hal::VsyncPeriodChangeTimeline outTimeline;
1423 
1424         const auto status =
1425                 display->initiateModeChange(*desiredActiveMode, constraints, &outTimeline);
1426 
1427         if (status != NO_ERROR) {
1428             // initiateModeChange may fail if a hotplug event is just about
1429             // to be sent. We just log the error in this case.
1430             ALOGW("initiateModeChange failed: %d", status);
1431             continue;
1432         }
1433 
1434         display->refreshRateSelector().onModeChangeInitiated();
1435         mScheduler->onNewVsyncPeriodChangeTimeline(outTimeline);
1436 
1437         if (outTimeline.refreshRequired) {
1438             scheduleComposite(FrameHint::kNone);
1439         } else {
1440             // TODO(b/255635711): Remove `displayToUpdateImmediately` to `finalizeDisplayModeChange`
1441             // for all displays. This was only needed when the loop iterated over `mDisplays` rather
1442             // than `mPhysicalDisplays`.
1443             displayToUpdateImmediately = display->getPhysicalId();
1444         }
1445     }
1446 
1447     if (displayToUpdateImmediately) {
1448         const auto display = getDisplayDeviceLocked(*displayToUpdateImmediately);
1449         finalizeDisplayModeChange(*display);
1450 
1451         const auto desiredActiveMode = display->getDesiredActiveMode();
1452         if (desiredActiveMode && display->getActiveMode() == desiredActiveMode->modeOpt) {
1453             desiredActiveModeChangeDone(display);
1454         }
1455     }
1456 }
1457 
disableExpensiveRendering()1458 void SurfaceFlinger::disableExpensiveRendering() {
1459     const char* const whence = __func__;
1460     auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
1461         ATRACE_NAME(whence);
1462         if (mPowerAdvisor->isUsingExpensiveRendering()) {
1463             for (const auto& [_, display] : mDisplays) {
1464                 constexpr bool kDisable = false;
1465                 mPowerAdvisor->setExpensiveRenderingExpected(display->getId(), kDisable);
1466             }
1467         }
1468     });
1469 
1470     future.wait();
1471 }
1472 
getDisplayNativePrimaries(const sp<IBinder> & displayToken,ui::DisplayPrimaries & primaries)1473 status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1474                                                    ui::DisplayPrimaries& primaries) {
1475     if (!displayToken) {
1476         return BAD_VALUE;
1477     }
1478 
1479     Mutex::Autolock lock(mStateLock);
1480 
1481     const auto display = ftl::find_if(mPhysicalDisplays, PhysicalDisplay::hasToken(displayToken))
1482                                  .transform(&ftl::to_mapped_ref<PhysicalDisplays>);
1483     if (!display) {
1484         return NAME_NOT_FOUND;
1485     }
1486 
1487     if (!display.transform(&PhysicalDisplay::isInternal).value()) {
1488         return INVALID_OPERATION;
1489     }
1490 
1491     // TODO(b/229846990): For now, assume that all internal displays have the same primaries.
1492     primaries = mInternalDisplayPrimaries;
1493     return NO_ERROR;
1494 }
1495 
setActiveColorMode(const sp<IBinder> & displayToken,ui::ColorMode mode)1496 status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ui::ColorMode mode) {
1497     if (!displayToken) {
1498         return BAD_VALUE;
1499     }
1500 
1501     const char* const whence = __func__;
1502     auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) -> status_t {
1503         const auto displayOpt =
1504                 ftl::find_if(mPhysicalDisplays, PhysicalDisplay::hasToken(displayToken))
1505                         .transform(&ftl::to_mapped_ref<PhysicalDisplays>)
1506                         .and_then(getDisplayDeviceAndSnapshot());
1507 
1508         if (!displayOpt) {
1509             ALOGE("%s: Invalid physical display token %p", whence, displayToken.get());
1510             return NAME_NOT_FOUND;
1511         }
1512 
1513         const auto& [display, snapshotRef] = *displayOpt;
1514         const auto& snapshot = snapshotRef.get();
1515 
1516         const auto modes = snapshot.filterColorModes(mSupportsWideColor);
1517         const bool exists = std::find(modes.begin(), modes.end(), mode) != modes.end();
1518 
1519         if (mode < ui::ColorMode::NATIVE || !exists) {
1520             ALOGE("%s: Invalid color mode %s (%d) for display %s", whence,
1521                   decodeColorMode(mode).c_str(), mode, to_string(snapshot.displayId()).c_str());
1522             return BAD_VALUE;
1523         }
1524 
1525         display->getCompositionDisplay()->setColorProfile(
1526                 {mode, Dataspace::UNKNOWN, RenderIntent::COLORIMETRIC, Dataspace::UNKNOWN});
1527 
1528         return NO_ERROR;
1529     });
1530 
1531     // TODO(b/195698395): Propagate error.
1532     future.wait();
1533     return NO_ERROR;
1534 }
1535 
getBootDisplayModeSupport(bool * outSupport) const1536 status_t SurfaceFlinger::getBootDisplayModeSupport(bool* outSupport) const {
1537     auto future = mScheduler->schedule(
1538             [this] { return getHwComposer().hasCapability(Capability::BOOT_DISPLAY_CONFIG); });
1539 
1540     *outSupport = future.get();
1541     return NO_ERROR;
1542 }
1543 
getOverlaySupport(gui::OverlayProperties * outProperties) const1544 status_t SurfaceFlinger::getOverlaySupport(gui::OverlayProperties* outProperties) const {
1545     const auto& aidlProperties = getHwComposer().getOverlaySupport();
1546     // convert aidl OverlayProperties to gui::OverlayProperties
1547     outProperties->combinations.reserve(aidlProperties.combinations.size());
1548     for (const auto& combination : aidlProperties.combinations) {
1549         std::vector<int32_t> pixelFormats;
1550         pixelFormats.reserve(combination.pixelFormats.size());
1551         std::transform(combination.pixelFormats.cbegin(), combination.pixelFormats.cend(),
1552                        std::back_inserter(pixelFormats),
1553                        [](const auto& val) { return static_cast<int32_t>(val); });
1554         std::vector<int32_t> standards;
1555         standards.reserve(combination.standards.size());
1556         std::transform(combination.standards.cbegin(), combination.standards.cend(),
1557                        std::back_inserter(standards),
1558                        [](const auto& val) { return static_cast<int32_t>(val); });
1559         std::vector<int32_t> transfers;
1560         transfers.reserve(combination.transfers.size());
1561         std::transform(combination.transfers.cbegin(), combination.transfers.cend(),
1562                        std::back_inserter(transfers),
1563                        [](const auto& val) { return static_cast<int32_t>(val); });
1564         std::vector<int32_t> ranges;
1565         ranges.reserve(combination.ranges.size());
1566         std::transform(combination.ranges.cbegin(), combination.ranges.cend(),
1567                        std::back_inserter(ranges),
1568                        [](const auto& val) { return static_cast<int32_t>(val); });
1569         gui::OverlayProperties::SupportedBufferCombinations outCombination;
1570         outCombination.pixelFormats = std::move(pixelFormats);
1571         outCombination.standards = std::move(standards);
1572         outCombination.transfers = std::move(transfers);
1573         outCombination.ranges = std::move(ranges);
1574         outProperties->combinations.emplace_back(outCombination);
1575     }
1576     outProperties->supportMixedColorSpaces = aidlProperties.supportMixedColorSpaces;
1577     return NO_ERROR;
1578 }
1579 
setBootDisplayMode(const sp<display::DisplayToken> & displayToken,DisplayModeId modeId)1580 status_t SurfaceFlinger::setBootDisplayMode(const sp<display::DisplayToken>& displayToken,
1581                                             DisplayModeId modeId) {
1582     const char* const whence = __func__;
1583     auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) -> status_t {
1584         const auto snapshotOpt =
1585                 ftl::find_if(mPhysicalDisplays, PhysicalDisplay::hasToken(displayToken))
1586                         .transform(&ftl::to_mapped_ref<PhysicalDisplays>)
1587                         .transform(&PhysicalDisplay::snapshotRef);
1588 
1589         if (!snapshotOpt) {
1590             ALOGE("%s: Invalid physical display token %p", whence, displayToken.get());
1591             return NAME_NOT_FOUND;
1592         }
1593 
1594         const auto& snapshot = snapshotOpt->get();
1595         const auto hwcIdOpt = snapshot.displayModes().get(modeId).transform(
1596                 [](const DisplayModePtr& mode) { return mode->getHwcId(); });
1597 
1598         if (!hwcIdOpt) {
1599             ALOGE("%s: Invalid mode %d for display %s", whence, modeId.value(),
1600                   to_string(snapshot.displayId()).c_str());
1601             return BAD_VALUE;
1602         }
1603 
1604         return getHwComposer().setBootDisplayMode(snapshot.displayId(), *hwcIdOpt);
1605     });
1606     return future.get();
1607 }
1608 
clearBootDisplayMode(const sp<IBinder> & displayToken)1609 status_t SurfaceFlinger::clearBootDisplayMode(const sp<IBinder>& displayToken) {
1610     const char* const whence = __func__;
1611     auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) -> status_t {
1612         if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1613             return getHwComposer().clearBootDisplayMode(*displayId);
1614         } else {
1615             ALOGE("%s: Invalid display token %p", whence, displayToken.get());
1616             return BAD_VALUE;
1617         }
1618     });
1619     return future.get();
1620 }
1621 
getHdrConversionCapabilities(std::vector<gui::HdrConversionCapability> * hdrConversionCapabilities) const1622 status_t SurfaceFlinger::getHdrConversionCapabilities(
1623         std::vector<gui::HdrConversionCapability>* hdrConversionCapabilities) const {
1624     bool hdrOutputConversionSupport;
1625     getHdrOutputConversionSupport(&hdrOutputConversionSupport);
1626     if (hdrOutputConversionSupport == false) {
1627         ALOGE("hdrOutputConversion is not supported by this device.");
1628         return INVALID_OPERATION;
1629     }
1630     const auto aidlConversionCapability = getHwComposer().getHdrConversionCapabilities();
1631     for (auto capability : aidlConversionCapability) {
1632         gui::HdrConversionCapability tempCapability;
1633         tempCapability.sourceType = static_cast<int>(capability.sourceType);
1634         tempCapability.outputType = static_cast<int>(capability.outputType);
1635         tempCapability.addsLatency = capability.addsLatency;
1636         hdrConversionCapabilities->push_back(tempCapability);
1637     }
1638     return NO_ERROR;
1639 }
1640 
setHdrConversionStrategy(const gui::HdrConversionStrategy & hdrConversionStrategy,int32_t * outPreferredHdrOutputType)1641 status_t SurfaceFlinger::setHdrConversionStrategy(
1642         const gui::HdrConversionStrategy& hdrConversionStrategy,
1643         int32_t* outPreferredHdrOutputType) {
1644     bool hdrOutputConversionSupport;
1645     getHdrOutputConversionSupport(&hdrOutputConversionSupport);
1646     if (hdrOutputConversionSupport == false) {
1647         ALOGE("hdrOutputConversion is not supported by this device.");
1648         return INVALID_OPERATION;
1649     }
1650     auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) mutable -> status_t {
1651         using AidlHdrConversionStrategy =
1652                 aidl::android::hardware::graphics::common::HdrConversionStrategy;
1653         using GuiHdrConversionStrategyTag = gui::HdrConversionStrategy::Tag;
1654         AidlHdrConversionStrategy aidlConversionStrategy;
1655         status_t status;
1656         aidl::android::hardware::graphics::common::Hdr aidlPreferredHdrOutputType;
1657         switch (hdrConversionStrategy.getTag()) {
1658             case GuiHdrConversionStrategyTag::passthrough: {
1659                 aidlConversionStrategy.set<AidlHdrConversionStrategy::Tag::passthrough>(
1660                         hdrConversionStrategy.get<GuiHdrConversionStrategyTag::passthrough>());
1661                 status = getHwComposer().setHdrConversionStrategy(aidlConversionStrategy,
1662                                                                   &aidlPreferredHdrOutputType);
1663                 *outPreferredHdrOutputType = static_cast<int32_t>(aidlPreferredHdrOutputType);
1664                 return status;
1665             }
1666             case GuiHdrConversionStrategyTag::autoAllowedHdrTypes: {
1667                 auto autoHdrTypes =
1668                         hdrConversionStrategy
1669                                 .get<GuiHdrConversionStrategyTag::autoAllowedHdrTypes>();
1670                 std::vector<aidl::android::hardware::graphics::common::Hdr> aidlAutoHdrTypes;
1671                 for (auto type : autoHdrTypes) {
1672                     aidlAutoHdrTypes.push_back(
1673                             static_cast<aidl::android::hardware::graphics::common::Hdr>(type));
1674                 }
1675                 aidlConversionStrategy.set<AidlHdrConversionStrategy::Tag::autoAllowedHdrTypes>(
1676                         aidlAutoHdrTypes);
1677                 status = getHwComposer().setHdrConversionStrategy(aidlConversionStrategy,
1678                                                                   &aidlPreferredHdrOutputType);
1679                 *outPreferredHdrOutputType = static_cast<int32_t>(aidlPreferredHdrOutputType);
1680                 return status;
1681             }
1682             case GuiHdrConversionStrategyTag::forceHdrConversion: {
1683                 auto forceHdrConversion =
1684                         hdrConversionStrategy
1685                                 .get<GuiHdrConversionStrategyTag::forceHdrConversion>();
1686                 aidlConversionStrategy.set<AidlHdrConversionStrategy::Tag::forceHdrConversion>(
1687                         static_cast<aidl::android::hardware::graphics::common::Hdr>(
1688                                 forceHdrConversion));
1689                 status = getHwComposer().setHdrConversionStrategy(aidlConversionStrategy,
1690                                                                   &aidlPreferredHdrOutputType);
1691                 *outPreferredHdrOutputType = static_cast<int32_t>(aidlPreferredHdrOutputType);
1692                 return status;
1693             }
1694         }
1695     });
1696     return future.get();
1697 }
1698 
getHdrOutputConversionSupport(bool * outSupport) const1699 status_t SurfaceFlinger::getHdrOutputConversionSupport(bool* outSupport) const {
1700     auto future = mScheduler->schedule([this] {
1701         return getHwComposer().hasCapability(Capability::HDR_OUTPUT_CONVERSION_CONFIG);
1702     });
1703 
1704     *outSupport = future.get();
1705     return NO_ERROR;
1706 }
1707 
setAutoLowLatencyMode(const sp<IBinder> & displayToken,bool on)1708 void SurfaceFlinger::setAutoLowLatencyMode(const sp<IBinder>& displayToken, bool on) {
1709     const char* const whence = __func__;
1710     static_cast<void>(mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
1711         if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1712             getHwComposer().setAutoLowLatencyMode(*displayId, on);
1713         } else {
1714             ALOGE("%s: Invalid display token %p", whence, displayToken.get());
1715         }
1716     }));
1717 }
1718 
setGameContentType(const sp<IBinder> & displayToken,bool on)1719 void SurfaceFlinger::setGameContentType(const sp<IBinder>& displayToken, bool on) {
1720     const char* const whence = __func__;
1721     static_cast<void>(mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
1722         if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1723             const auto type = on ? hal::ContentType::GAME : hal::ContentType::NONE;
1724             getHwComposer().setContentType(*displayId, type);
1725         } else {
1726             ALOGE("%s: Invalid display token %p", whence, displayToken.get());
1727         }
1728     }));
1729 }
1730 
overrideHdrTypes(const sp<IBinder> & displayToken,const std::vector<ui::Hdr> & hdrTypes)1731 status_t SurfaceFlinger::overrideHdrTypes(const sp<IBinder>& displayToken,
1732                                           const std::vector<ui::Hdr>& hdrTypes) {
1733     Mutex::Autolock lock(mStateLock);
1734 
1735     auto display = getDisplayDeviceLocked(displayToken);
1736     if (!display) {
1737         ALOGE("%s: Invalid display token %p", __func__, displayToken.get());
1738         return NAME_NOT_FOUND;
1739     }
1740 
1741     display->overrideHdrTypes(hdrTypes);
1742     dispatchDisplayHotplugEvent(display->getPhysicalId(), true /* connected */);
1743     return NO_ERROR;
1744 }
1745 
onPullAtom(const int32_t atomId,std::vector<uint8_t> * pulledData,bool * success)1746 status_t SurfaceFlinger::onPullAtom(const int32_t atomId, std::vector<uint8_t>* pulledData,
1747                                     bool* success) {
1748     *success = mTimeStats->onPullAtom(atomId, pulledData);
1749     return NO_ERROR;
1750 }
1751 
getDisplayedContentSamplingAttributes(const sp<IBinder> & displayToken,ui::PixelFormat * outFormat,ui::Dataspace * outDataspace,uint8_t * outComponentMask) const1752 status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1753                                                                ui::PixelFormat* outFormat,
1754                                                                ui::Dataspace* outDataspace,
1755                                                                uint8_t* outComponentMask) const {
1756     if (!outFormat || !outDataspace || !outComponentMask) {
1757         return BAD_VALUE;
1758     }
1759 
1760     Mutex::Autolock lock(mStateLock);
1761 
1762     const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1763     if (!displayId) {
1764         return NAME_NOT_FOUND;
1765     }
1766 
1767     return getHwComposer().getDisplayedContentSamplingAttributes(*displayId, outFormat,
1768                                                                  outDataspace, outComponentMask);
1769 }
1770 
setDisplayContentSamplingEnabled(const sp<IBinder> & displayToken,bool enable,uint8_t componentMask,uint64_t maxFrames)1771 status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1772                                                           bool enable, uint8_t componentMask,
1773                                                           uint64_t maxFrames) {
1774     const char* const whence = __func__;
1775     auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) -> status_t {
1776         if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1777             return getHwComposer().setDisplayContentSamplingEnabled(*displayId, enable,
1778                                                                     componentMask, maxFrames);
1779         } else {
1780             ALOGE("%s: Invalid display token %p", whence, displayToken.get());
1781             return NAME_NOT_FOUND;
1782         }
1783     });
1784 
1785     return future.get();
1786 }
1787 
getDisplayedContentSample(const sp<IBinder> & displayToken,uint64_t maxFrames,uint64_t timestamp,DisplayedFrameStats * outStats) const1788 status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1789                                                    uint64_t maxFrames, uint64_t timestamp,
1790                                                    DisplayedFrameStats* outStats) const {
1791     Mutex::Autolock lock(mStateLock);
1792 
1793     const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1794     if (!displayId) {
1795         return NAME_NOT_FOUND;
1796     }
1797 
1798     return getHwComposer().getDisplayedContentSample(*displayId, maxFrames, timestamp, outStats);
1799 }
1800 
getProtectedContentSupport(bool * outSupported) const1801 status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1802     if (!outSupported) {
1803         return BAD_VALUE;
1804     }
1805     *outSupported = getRenderEngine().supportsProtectedContent();
1806     return NO_ERROR;
1807 }
1808 
isWideColorDisplay(const sp<IBinder> & displayToken,bool * outIsWideColorDisplay) const1809 status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1810                                             bool* outIsWideColorDisplay) const {
1811     if (!displayToken || !outIsWideColorDisplay) {
1812         return BAD_VALUE;
1813     }
1814 
1815     Mutex::Autolock lock(mStateLock);
1816     const auto display = getDisplayDeviceLocked(displayToken);
1817     if (!display) {
1818         return NAME_NOT_FOUND;
1819     }
1820 
1821     *outIsWideColorDisplay =
1822             display->isPrimary() ? mSupportsWideColor : display->hasWideColorGamut();
1823     return NO_ERROR;
1824 }
1825 
getLayerDebugInfo(std::vector<gui::LayerDebugInfo> * outLayers)1826 status_t SurfaceFlinger::getLayerDebugInfo(std::vector<gui::LayerDebugInfo>* outLayers) {
1827     outLayers->clear();
1828     auto future = mScheduler->schedule([=] {
1829         const auto display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
1830         mDrawingState.traverseInZOrder([&](Layer* layer) {
1831             outLayers->push_back(layer->getLayerDebugInfo(display.get()));
1832         });
1833     });
1834 
1835     future.wait();
1836     return NO_ERROR;
1837 }
1838 
getCompositionPreference(Dataspace * outDataspace,ui::PixelFormat * outPixelFormat,Dataspace * outWideColorGamutDataspace,ui::PixelFormat * outWideColorGamutPixelFormat) const1839 status_t SurfaceFlinger::getCompositionPreference(
1840         Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1841         Dataspace* outWideColorGamutDataspace,
1842         ui::PixelFormat* outWideColorGamutPixelFormat) const {
1843     *outDataspace = mDefaultCompositionDataspace;
1844     *outPixelFormat = defaultCompositionPixelFormat;
1845     *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
1846     *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
1847     return NO_ERROR;
1848 }
1849 
addRegionSamplingListener(const Rect & samplingArea,const sp<IBinder> & stopLayerHandle,const sp<IRegionSamplingListener> & listener)1850 status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1851                                                    const sp<IBinder>& stopLayerHandle,
1852                                                    const sp<IRegionSamplingListener>& listener) {
1853     if (!listener || samplingArea == Rect::INVALID_RECT || samplingArea.isEmpty()) {
1854         return BAD_VALUE;
1855     }
1856 
1857     // LayerHandle::getLayer promotes the layer object in a binder thread but we will not destroy
1858     // the layer here since the caller has a strong ref to the layer's handle.
1859     const sp<Layer> stopLayer = LayerHandle::getLayer(stopLayerHandle);
1860     mRegionSamplingThread->addListener(samplingArea,
1861                                        stopLayer ? stopLayer->getSequence() : UNASSIGNED_LAYER_ID,
1862                                        listener);
1863     return NO_ERROR;
1864 }
1865 
removeRegionSamplingListener(const sp<IRegionSamplingListener> & listener)1866 status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
1867     if (!listener) {
1868         return BAD_VALUE;
1869     }
1870     mRegionSamplingThread->removeListener(listener);
1871     return NO_ERROR;
1872 }
1873 
addFpsListener(int32_t taskId,const sp<gui::IFpsListener> & listener)1874 status_t SurfaceFlinger::addFpsListener(int32_t taskId, const sp<gui::IFpsListener>& listener) {
1875     if (!listener) {
1876         return BAD_VALUE;
1877     }
1878 
1879     mFpsReporter->addListener(listener, taskId);
1880     return NO_ERROR;
1881 }
1882 
removeFpsListener(const sp<gui::IFpsListener> & listener)1883 status_t SurfaceFlinger::removeFpsListener(const sp<gui::IFpsListener>& listener) {
1884     if (!listener) {
1885         return BAD_VALUE;
1886     }
1887     mFpsReporter->removeListener(listener);
1888     return NO_ERROR;
1889 }
1890 
addTunnelModeEnabledListener(const sp<gui::ITunnelModeEnabledListener> & listener)1891 status_t SurfaceFlinger::addTunnelModeEnabledListener(
1892         const sp<gui::ITunnelModeEnabledListener>& listener) {
1893     if (!listener) {
1894         return BAD_VALUE;
1895     }
1896 
1897     mTunnelModeEnabledReporter->addListener(listener);
1898     return NO_ERROR;
1899 }
1900 
removeTunnelModeEnabledListener(const sp<gui::ITunnelModeEnabledListener> & listener)1901 status_t SurfaceFlinger::removeTunnelModeEnabledListener(
1902         const sp<gui::ITunnelModeEnabledListener>& listener) {
1903     if (!listener) {
1904         return BAD_VALUE;
1905     }
1906 
1907     mTunnelModeEnabledReporter->removeListener(listener);
1908     return NO_ERROR;
1909 }
1910 
getDisplayBrightnessSupport(const sp<IBinder> & displayToken,bool * outSupport) const1911 status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1912                                                      bool* outSupport) const {
1913     if (!displayToken || !outSupport) {
1914         return BAD_VALUE;
1915     }
1916 
1917     Mutex::Autolock lock(mStateLock);
1918 
1919     const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1920     if (!displayId) {
1921         return NAME_NOT_FOUND;
1922     }
1923     *outSupport = getHwComposer().hasDisplayCapability(*displayId, DisplayCapability::BRIGHTNESS);
1924     return NO_ERROR;
1925 }
1926 
setDisplayBrightness(const sp<IBinder> & displayToken,const gui::DisplayBrightness & brightness)1927 status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1928                                               const gui::DisplayBrightness& brightness) {
1929     if (!displayToken) {
1930         return BAD_VALUE;
1931     }
1932 
1933     const char* const whence = __func__;
1934     return ftl::Future(mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
1935                if (const auto display = getDisplayDeviceLocked(displayToken)) {
1936                    const bool supportsDisplayBrightnessCommand =
1937                            getHwComposer().getComposer()->isSupported(
1938                                    Hwc2::Composer::OptionalFeature::DisplayBrightnessCommand);
1939                    // If we support applying display brightness as a command, then we also support
1940                    // dimming SDR layers.
1941                    if (supportsDisplayBrightnessCommand) {
1942                        auto compositionDisplay = display->getCompositionDisplay();
1943                        float currentDimmingRatio =
1944                                compositionDisplay->editState().sdrWhitePointNits /
1945                                compositionDisplay->editState().displayBrightnessNits;
1946                        compositionDisplay->setDisplayBrightness(brightness.sdrWhitePointNits,
1947                                                                 brightness.displayBrightnessNits);
1948                        FTL_FAKE_GUARD(kMainThreadContext,
1949                                       display->stageBrightness(brightness.displayBrightness));
1950 
1951                        if (brightness.sdrWhitePointNits / brightness.displayBrightnessNits !=
1952                            currentDimmingRatio) {
1953                            scheduleComposite(FrameHint::kNone);
1954                        } else {
1955                            scheduleCommit(FrameHint::kNone);
1956                        }
1957                        return ftl::yield<status_t>(OK);
1958                    } else {
1959                        return getHwComposer()
1960                                .setDisplayBrightness(display->getPhysicalId(),
1961                                                      brightness.displayBrightness,
1962                                                      brightness.displayBrightnessNits,
1963                                                      Hwc2::Composer::DisplayBrightnessOptions{
1964                                                              .applyImmediately = true});
1965                    }
1966 
1967                } else {
1968                    ALOGE("%s: Invalid display token %p", whence, displayToken.get());
1969                    return ftl::yield<status_t>(NAME_NOT_FOUND);
1970                }
1971            }))
1972             .then([](ftl::Future<status_t> task) { return task; })
1973             .get();
1974 }
1975 
addHdrLayerInfoListener(const sp<IBinder> & displayToken,const sp<gui::IHdrLayerInfoListener> & listener)1976 status_t SurfaceFlinger::addHdrLayerInfoListener(const sp<IBinder>& displayToken,
1977                                                  const sp<gui::IHdrLayerInfoListener>& listener) {
1978     if (!displayToken) {
1979         return BAD_VALUE;
1980     }
1981 
1982     Mutex::Autolock lock(mStateLock);
1983 
1984     const auto display = getDisplayDeviceLocked(displayToken);
1985     if (!display) {
1986         return NAME_NOT_FOUND;
1987     }
1988     const auto displayId = display->getId();
1989     sp<HdrLayerInfoReporter>& hdrInfoReporter = mHdrLayerInfoListeners[displayId];
1990     if (!hdrInfoReporter) {
1991         hdrInfoReporter = sp<HdrLayerInfoReporter>::make();
1992     }
1993     hdrInfoReporter->addListener(listener);
1994 
1995 
1996     mAddingHDRLayerInfoListener = true;
1997     return OK;
1998 }
1999 
removeHdrLayerInfoListener(const sp<IBinder> & displayToken,const sp<gui::IHdrLayerInfoListener> & listener)2000 status_t SurfaceFlinger::removeHdrLayerInfoListener(
2001         const sp<IBinder>& displayToken, const sp<gui::IHdrLayerInfoListener>& listener) {
2002     if (!displayToken) {
2003         return BAD_VALUE;
2004     }
2005 
2006     Mutex::Autolock lock(mStateLock);
2007 
2008     const auto display = getDisplayDeviceLocked(displayToken);
2009     if (!display) {
2010         return NAME_NOT_FOUND;
2011     }
2012     const auto displayId = display->getId();
2013     sp<HdrLayerInfoReporter>& hdrInfoReporter = mHdrLayerInfoListeners[displayId];
2014     if (hdrInfoReporter) {
2015         hdrInfoReporter->removeListener(listener);
2016     }
2017     return OK;
2018 }
2019 
notifyPowerBoost(int32_t boostId)2020 status_t SurfaceFlinger::notifyPowerBoost(int32_t boostId) {
2021     using hardware::power::Boost;
2022     Boost powerBoost = static_cast<Boost>(boostId);
2023 
2024     if (powerBoost == Boost::INTERACTION) {
2025         mScheduler->onTouchHint();
2026     }
2027 
2028     return NO_ERROR;
2029 }
2030 
getDisplayDecorationSupport(const sp<IBinder> & displayToken,std::optional<DisplayDecorationSupport> * outSupport) const2031 status_t SurfaceFlinger::getDisplayDecorationSupport(
2032         const sp<IBinder>& displayToken,
2033         std::optional<DisplayDecorationSupport>* outSupport) const {
2034     if (!displayToken || !outSupport) {
2035         return BAD_VALUE;
2036     }
2037 
2038     Mutex::Autolock lock(mStateLock);
2039 
2040     const auto displayId = getPhysicalDisplayIdLocked(displayToken);
2041     if (!displayId) {
2042         return NAME_NOT_FOUND;
2043     }
2044     getHwComposer().getDisplayDecorationSupport(*displayId, outSupport);
2045     return NO_ERROR;
2046 }
2047 
2048 // ----------------------------------------------------------------------------
2049 
createDisplayEventConnection(gui::ISurfaceComposer::VsyncSource vsyncSource,EventRegistrationFlags eventRegistration,const sp<IBinder> & layerHandle)2050 sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
2051         gui::ISurfaceComposer::VsyncSource vsyncSource, EventRegistrationFlags eventRegistration,
2052         const sp<IBinder>& layerHandle) {
2053     const auto& handle =
2054             vsyncSource == gui::ISurfaceComposer::VsyncSource::eVsyncSourceSurfaceFlinger
2055             ? mSfConnectionHandle
2056             : mAppConnectionHandle;
2057 
2058     return mScheduler->createDisplayEventConnection(handle, eventRegistration, layerHandle);
2059 }
2060 
scheduleCommit(FrameHint hint)2061 void SurfaceFlinger::scheduleCommit(FrameHint hint) {
2062     if (hint == FrameHint::kActive) {
2063         mScheduler->resetIdleTimer();
2064     }
2065     mPowerAdvisor->notifyDisplayUpdateImminentAndCpuReset();
2066     mScheduler->scheduleFrame();
2067 }
2068 
scheduleComposite(FrameHint hint)2069 void SurfaceFlinger::scheduleComposite(FrameHint hint) {
2070     mMustComposite = true;
2071     scheduleCommit(hint);
2072 }
2073 
scheduleRepaint()2074 void SurfaceFlinger::scheduleRepaint() {
2075     mGeometryDirty = true;
2076     scheduleComposite(FrameHint::kActive);
2077 }
2078 
scheduleSample()2079 void SurfaceFlinger::scheduleSample() {
2080     static_cast<void>(mScheduler->schedule([this] { sample(); }));
2081 }
2082 
getVsyncPeriodFromHWC() const2083 nsecs_t SurfaceFlinger::getVsyncPeriodFromHWC() const {
2084     if (const auto display = getDefaultDisplayDeviceLocked()) {
2085         return display->getVsyncPeriodFromHWC();
2086     }
2087 
2088     return 0;
2089 }
2090 
onComposerHalVsync(hal::HWDisplayId hwcDisplayId,int64_t timestamp,std::optional<hal::VsyncPeriodNanos> vsyncPeriod)2091 void SurfaceFlinger::onComposerHalVsync(hal::HWDisplayId hwcDisplayId, int64_t timestamp,
2092                                         std::optional<hal::VsyncPeriodNanos> vsyncPeriod) {
2093     ATRACE_NAME(vsyncPeriod
2094                         ? ftl::Concat(__func__, ' ', hwcDisplayId, ' ', *vsyncPeriod, "ns").c_str()
2095                         : ftl::Concat(__func__, ' ', hwcDisplayId).c_str());
2096 
2097     Mutex::Autolock lock(mStateLock);
2098     if (const auto displayIdOpt = getHwComposer().onVsync(hwcDisplayId, timestamp)) {
2099         if (mScheduler->addResyncSample(*displayIdOpt, timestamp, vsyncPeriod)) {
2100             // period flushed
2101             mScheduler->modulateVsync(displayIdOpt, &VsyncModulator::onRefreshRateChangeCompleted);
2102         }
2103     }
2104 }
2105 
onComposerHalHotplug(hal::HWDisplayId hwcDisplayId,hal::Connection connection)2106 void SurfaceFlinger::onComposerHalHotplug(hal::HWDisplayId hwcDisplayId,
2107                                           hal::Connection connection) {
2108     {
2109         std::lock_guard<std::mutex> lock(mHotplugMutex);
2110         mPendingHotplugEvents.push_back(HotplugEvent{hwcDisplayId, connection});
2111     }
2112 
2113     if (mScheduler) {
2114         mScheduler->scheduleConfigure();
2115     }
2116 }
2117 
onComposerHalVsyncPeriodTimingChanged(hal::HWDisplayId,const hal::VsyncPeriodChangeTimeline & timeline)2118 void SurfaceFlinger::onComposerHalVsyncPeriodTimingChanged(
2119         hal::HWDisplayId, const hal::VsyncPeriodChangeTimeline& timeline) {
2120     Mutex::Autolock lock(mStateLock);
2121     mScheduler->onNewVsyncPeriodChangeTimeline(timeline);
2122 
2123     if (timeline.refreshRequired) {
2124         scheduleComposite(FrameHint::kNone);
2125     }
2126 }
2127 
onComposerHalSeamlessPossible(hal::HWDisplayId)2128 void SurfaceFlinger::onComposerHalSeamlessPossible(hal::HWDisplayId) {
2129     // TODO(b/142753666): use constraints when calling to setActiveModeWithConstraints and
2130     // use this callback to know when to retry in case of SEAMLESS_NOT_POSSIBLE.
2131 }
2132 
onComposerHalRefresh(hal::HWDisplayId)2133 void SurfaceFlinger::onComposerHalRefresh(hal::HWDisplayId) {
2134     Mutex::Autolock lock(mStateLock);
2135     scheduleComposite(FrameHint::kNone);
2136 }
2137 
onComposerHalVsyncIdle(hal::HWDisplayId)2138 void SurfaceFlinger::onComposerHalVsyncIdle(hal::HWDisplayId) {
2139     ATRACE_CALL();
2140     mScheduler->forceNextResync();
2141 }
2142 
onRefreshRateChangedDebug(const RefreshRateChangedDebugData & data)2143 void SurfaceFlinger::onRefreshRateChangedDebug(const RefreshRateChangedDebugData& data) {
2144     ATRACE_CALL();
2145     if (const auto displayId = getHwComposer().toPhysicalDisplayId(data.display); displayId) {
2146         const Fps fps = Fps::fromPeriodNsecs(data.vsyncPeriodNanos);
2147         ATRACE_FORMAT("%s Fps %d", __func__, fps.getIntValue());
2148         static_cast<void>(mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
2149             {
2150                 {
2151                     const auto display = getDisplayDeviceLocked(*displayId);
2152                     FTL_FAKE_GUARD(kMainThreadContext,
2153                                    display->updateRefreshRateOverlayRate(fps,
2154                                                                          display->getActiveMode()
2155                                                                                  .fps,
2156                                                                          /* setByHwc */ true));
2157                 }
2158             }
2159         }));
2160     }
2161 }
2162 
configure()2163 void SurfaceFlinger::configure() {
2164     Mutex::Autolock lock(mStateLock);
2165     if (configureLocked()) {
2166         setTransactionFlags(eDisplayTransactionNeeded);
2167     }
2168 }
2169 
updateLayerSnapshotsLegacy(VsyncId vsyncId,frontend::Update & update,bool transactionsFlushed,bool & outTransactionsAreEmpty)2170 bool SurfaceFlinger::updateLayerSnapshotsLegacy(VsyncId vsyncId, frontend::Update& update,
2171                                                 bool transactionsFlushed,
2172                                                 bool& outTransactionsAreEmpty) {
2173     ATRACE_CALL();
2174     bool needsTraversal = false;
2175     if (transactionsFlushed) {
2176         needsTraversal |= commitMirrorDisplays(vsyncId);
2177         needsTraversal |= commitCreatedLayers(vsyncId, update.layerCreatedStates);
2178         needsTraversal |= applyTransactions(update.transactions, vsyncId);
2179     }
2180     outTransactionsAreEmpty = !needsTraversal;
2181     const bool shouldCommit = (getTransactionFlags() & ~eTransactionFlushNeeded) || needsTraversal;
2182     if (shouldCommit) {
2183         commitTransactions();
2184     }
2185 
2186     bool mustComposite = latchBuffers() || shouldCommit;
2187     updateLayerGeometry();
2188     return mustComposite;
2189 }
2190 
updateLayerHistory(const frontend::LayerSnapshot & snapshot)2191 void SurfaceFlinger::updateLayerHistory(const frontend::LayerSnapshot& snapshot) {
2192     using Changes = frontend::RequestedLayerState::Changes;
2193     if (snapshot.path.isClone() ||
2194         !snapshot.changes.any(Changes::FrameRate | Changes::Buffer | Changes::Animation)) {
2195         return;
2196     }
2197 
2198     const auto layerProps = scheduler::LayerProps{
2199             .visible = snapshot.isVisible,
2200             .bounds = snapshot.geomLayerBounds,
2201             .transform = snapshot.geomLayerTransform,
2202             .setFrameRateVote = snapshot.frameRate,
2203             .frameRateSelectionPriority = snapshot.frameRateSelectionPriority,
2204     };
2205 
2206     auto it = mLegacyLayers.find(snapshot.sequence);
2207     LOG_ALWAYS_FATAL_IF(it == mLegacyLayers.end(), "Couldnt find layer object for %s",
2208                         snapshot.getDebugString().c_str());
2209 
2210     if (snapshot.changes.test(Changes::Animation)) {
2211         it->second->recordLayerHistoryAnimationTx(layerProps);
2212     }
2213 
2214     if (snapshot.changes.test(Changes::FrameRate)) {
2215         it->second->setFrameRateForLayerTree(snapshot.frameRate, layerProps);
2216     }
2217 
2218     if (snapshot.changes.test(Changes::Buffer)) {
2219         it->second->recordLayerHistoryBufferUpdate(layerProps);
2220     }
2221 }
2222 
updateLayerSnapshots(VsyncId vsyncId,frontend::Update & update,bool transactionsFlushed,bool & outTransactionsAreEmpty)2223 bool SurfaceFlinger::updateLayerSnapshots(VsyncId vsyncId, frontend::Update& update,
2224                                           bool transactionsFlushed, bool& outTransactionsAreEmpty) {
2225     using Changes = frontend::RequestedLayerState::Changes;
2226     ATRACE_CALL();
2227     {
2228         mLayerLifecycleManager.addLayers(std::move(update.newLayers));
2229         mLayerLifecycleManager.applyTransactions(update.transactions);
2230         mLayerLifecycleManager.onHandlesDestroyed(update.destroyedHandles);
2231         for (auto& legacyLayer : update.layerCreatedStates) {
2232             sp<Layer> layer = legacyLayer.layer.promote();
2233             if (layer) {
2234                 mLegacyLayers[layer->sequence] = layer;
2235             }
2236         }
2237     }
2238     if (mLayerLifecycleManager.getGlobalChanges().test(Changes::Hierarchy)) {
2239         ATRACE_NAME("LayerHierarchyBuilder:update");
2240         mLayerHierarchyBuilder.update(mLayerLifecycleManager.getLayers(),
2241                                       mLayerLifecycleManager.getDestroyedLayers());
2242     }
2243 
2244     bool mustComposite = false;
2245     mustComposite |= applyAndCommitDisplayTransactionStates(update.transactions);
2246 
2247     {
2248         ATRACE_NAME("LayerSnapshotBuilder:update");
2249         frontend::LayerSnapshotBuilder::Args
2250                 args{.root = mLayerHierarchyBuilder.getHierarchy(),
2251                      .layerLifecycleManager = mLayerLifecycleManager,
2252                      .displays = mFrontEndDisplayInfos,
2253                      .displayChanges = mFrontEndDisplayInfosChanged,
2254                      .globalShadowSettings = mDrawingState.globalShadowSettings,
2255                      .supportsBlur = mSupportsBlur,
2256                      .forceFullDamage = mForceFullDamage,
2257                      .supportedLayerGenericMetadata =
2258                              getHwComposer().getSupportedLayerGenericMetadata(),
2259                      .genericLayerMetadataKeyMap = getGenericLayerMetadataKeyMap()};
2260         mLayerSnapshotBuilder.update(args);
2261     }
2262 
2263     if (mLayerLifecycleManager.getGlobalChanges().any(Changes::Geometry | Changes::Input |
2264                                                       Changes::Hierarchy | Changes::Visibility)) {
2265         mUpdateInputInfo = true;
2266     }
2267     if (mLayerLifecycleManager.getGlobalChanges().any(Changes::VisibleRegion | Changes::Hierarchy |
2268                                                       Changes::Visibility)) {
2269         mVisibleRegionsDirty = true;
2270     }
2271     outTransactionsAreEmpty = mLayerLifecycleManager.getGlobalChanges().get() == 0;
2272     mustComposite |= mLayerLifecycleManager.getGlobalChanges().get() != 0;
2273 
2274     bool newDataLatched = false;
2275     if (!mLegacyFrontEndEnabled) {
2276         ATRACE_NAME("DisplayCallbackAndStatsUpdates");
2277         applyTransactions(update.transactions, vsyncId);
2278         const nsecs_t latchTime = systemTime();
2279         bool unused = false;
2280 
2281         for (auto& layer : mLayerLifecycleManager.getLayers()) {
2282             if (layer->changes.test(frontend::RequestedLayerState::Changes::Created) &&
2283                 layer->bgColorLayer) {
2284                 sp<Layer> bgColorLayer = getFactory().createEffectLayer(
2285                         LayerCreationArgs(this, nullptr, layer->name,
2286                                           ISurfaceComposerClient::eFXSurfaceEffect, LayerMetadata(),
2287                                           std::make_optional(layer->id), true));
2288                 mLegacyLayers[bgColorLayer->sequence] = bgColorLayer;
2289             }
2290             const bool willReleaseBufferOnLatch = layer->willReleaseBufferOnLatch();
2291             if (!layer->hasReadyFrame() && !willReleaseBufferOnLatch) continue;
2292 
2293             auto it = mLegacyLayers.find(layer->id);
2294             LOG_ALWAYS_FATAL_IF(it == mLegacyLayers.end(), "Couldnt find layer object for %s",
2295                                 layer->getDebugString().c_str());
2296             const bool bgColorOnly =
2297                     !layer->externalTexture && (layer->bgColorLayerId != UNASSIGNED_LAYER_ID);
2298             if (willReleaseBufferOnLatch) {
2299                 mLayersWithBuffersRemoved.emplace(it->second);
2300             }
2301             it->second->latchBufferImpl(unused, latchTime, bgColorOnly);
2302             mLayersWithQueuedFrames.emplace(it->second);
2303         }
2304 
2305         for (auto& snapshot : mLayerSnapshotBuilder.getSnapshots()) {
2306             updateLayerHistory(*snapshot);
2307             if (!snapshot->hasReadyFrame) continue;
2308             newDataLatched = true;
2309             if (!snapshot->isVisible) break;
2310 
2311             Region visibleReg;
2312             visibleReg.set(snapshot->transformedBoundsWithoutTransparentRegion);
2313             invalidateLayerStack(snapshot->outputFilter, visibleReg);
2314         }
2315 
2316         for (auto& destroyedLayer : mLayerLifecycleManager.getDestroyedLayers()) {
2317             mLegacyLayers.erase(destroyedLayer->id);
2318         }
2319 
2320         {
2321             ATRACE_NAME("LLM:commitChanges");
2322             mLayerLifecycleManager.commitChanges();
2323         }
2324 
2325         commitTransactions();
2326 
2327         // enter boot animation on first buffer latch
2328         if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2329             ALOGI("Enter boot animation");
2330             mBootStage = BootStage::BOOTANIMATION;
2331         }
2332     }
2333     mustComposite |= (getTransactionFlags() & ~eTransactionFlushNeeded) || newDataLatched;
2334     return mustComposite;
2335 }
2336 
commit(PhysicalDisplayId pacesetterId,const scheduler::FrameTargets & frameTargets)2337 bool SurfaceFlinger::commit(PhysicalDisplayId pacesetterId,
2338                             const scheduler::FrameTargets& frameTargets) {
2339     const scheduler::FrameTarget& pacesetterFrameTarget = *frameTargets.get(pacesetterId)->get();
2340 
2341     const VsyncId vsyncId = pacesetterFrameTarget.vsyncId();
2342     ATRACE_NAME(ftl::Concat(__func__, ' ', ftl::to_underlying(vsyncId)).c_str());
2343 
2344     if (pacesetterFrameTarget.didMissFrame()) {
2345         mTimeStats->incrementMissedFrames();
2346     }
2347 
2348     if (mTracingEnabledChanged) {
2349         mLayerTracingEnabled = mLayerTracing.isEnabled();
2350         mTracingEnabledChanged = false;
2351     }
2352 
2353     // If a mode set is pending and the fence hasn't fired yet, wait for the next commit.
2354     if (std::any_of(frameTargets.begin(), frameTargets.end(),
2355                     [this](const auto& pair) FTL_FAKE_GUARD(mStateLock)
2356                             FTL_FAKE_GUARD(kMainThreadContext) {
2357                                 if (!pair.second->isFramePending()) return false;
2358 
2359                                 if (const auto display = getDisplayDeviceLocked(pair.first)) {
2360                                     return display->isModeSetPending();
2361                                 }
2362 
2363                                 return false;
2364                             })) {
2365         mScheduler->scheduleFrame();
2366         return false;
2367     }
2368 
2369     {
2370         Mutex::Autolock lock(mStateLock);
2371 
2372         for (const auto [id, target] : frameTargets) {
2373             // TODO(b/241285876): This is `nullptr` when the DisplayDevice is about to be removed in
2374             // this commit, since the PhysicalDisplay has already been removed. Rather than checking
2375             // for `nullptr` below, change Scheduler::onFrameSignal to filter out the FrameTarget of
2376             // the removed display.
2377             const auto display = getDisplayDeviceLocked(id);
2378 
2379             if (display && display->isModeSetPending()) {
2380                 finalizeDisplayModeChange(*display);
2381             }
2382         }
2383     }
2384 
2385     if (pacesetterFrameTarget.isFramePending()) {
2386         if (mBackpressureGpuComposition || pacesetterFrameTarget.didMissHwcFrame()) {
2387             scheduleCommit(FrameHint::kNone);
2388             return false;
2389         }
2390     }
2391 
2392     const Period vsyncPeriod = mScheduler->getVsyncSchedule()->period();
2393 
2394     // Save this once per commit + composite to ensure consistency
2395     // TODO (b/240619471): consider removing active display check once AOD is fixed
2396     const auto activeDisplay = FTL_FAKE_GUARD(mStateLock, getDisplayDeviceLocked(mActiveDisplayId));
2397     mPowerHintSessionEnabled = mPowerAdvisor->usePowerHintSession() && activeDisplay &&
2398             activeDisplay->getPowerMode() == hal::PowerMode::ON;
2399     if (mPowerHintSessionEnabled) {
2400         mPowerAdvisor->setCommitStart(pacesetterFrameTarget.frameBeginTime());
2401         mPowerAdvisor->setExpectedPresentTime(pacesetterFrameTarget.expectedPresentTime());
2402 
2403         // Frame delay is how long we should have minus how long we actually have.
2404         const Duration idealSfWorkDuration =
2405                 mScheduler->vsyncModulator().getVsyncConfig().sfWorkDuration;
2406         const Duration frameDelay =
2407                 idealSfWorkDuration - pacesetterFrameTarget.expectedFrameDuration();
2408 
2409         mPowerAdvisor->setFrameDelay(frameDelay);
2410         mPowerAdvisor->setTotalFrameTargetWorkDuration(idealSfWorkDuration);
2411 
2412         const auto& display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked()).get();
2413         const Period idealVsyncPeriod = display->getActiveMode().fps.getPeriod();
2414         mPowerAdvisor->updateTargetWorkDuration(idealVsyncPeriod);
2415     }
2416 
2417     if (mRefreshRateOverlaySpinner) {
2418         Mutex::Autolock lock(mStateLock);
2419         if (const auto display = getDefaultDisplayDeviceLocked()) {
2420             display->animateRefreshRateOverlay();
2421         }
2422     }
2423 
2424     // Composite if transactions were committed, or if requested by HWC.
2425     bool mustComposite = mMustComposite.exchange(false);
2426     {
2427         mFrameTimeline->setSfWakeUp(ftl::to_underlying(vsyncId),
2428                                     pacesetterFrameTarget.frameBeginTime().ns(),
2429                                     Fps::fromPeriodNsecs(vsyncPeriod.ns()));
2430 
2431         const bool flushTransactions = clearTransactionFlags(eTransactionFlushNeeded);
2432         frontend::Update updates;
2433         if (flushTransactions) {
2434             updates = flushLifecycleUpdates();
2435             if (mTransactionTracing) {
2436                 mTransactionTracing
2437                         ->addCommittedTransactions(ftl::to_underlying(vsyncId),
2438                                                    pacesetterFrameTarget.frameBeginTime().ns(),
2439                                                    updates, mFrontEndDisplayInfos,
2440                                                    mFrontEndDisplayInfosChanged);
2441             }
2442         }
2443         bool transactionsAreEmpty;
2444         if (mLegacyFrontEndEnabled) {
2445             mustComposite |= updateLayerSnapshotsLegacy(vsyncId, updates, flushTransactions,
2446                                                         transactionsAreEmpty);
2447         }
2448         if (mLayerLifecycleManagerEnabled) {
2449             mustComposite |=
2450                     updateLayerSnapshots(vsyncId, updates, flushTransactions, transactionsAreEmpty);
2451         }
2452 
2453         if (transactionFlushNeeded()) {
2454             setTransactionFlags(eTransactionFlushNeeded);
2455         }
2456 
2457         // This has to be called after latchBuffers because we want to include the layers that have
2458         // been latched in the commit callback
2459         if (transactionsAreEmpty) {
2460             // Invoke empty transaction callbacks early.
2461             mTransactionCallbackInvoker.sendCallbacks(false /* onCommitOnly */);
2462         } else {
2463             // Invoke OnCommit callbacks.
2464             mTransactionCallbackInvoker.sendCallbacks(true /* onCommitOnly */);
2465         }
2466     }
2467 
2468     // Layers need to get updated (in the previous line) before we can use them for
2469     // choosing the refresh rate.
2470     // Hold mStateLock as chooseRefreshRateForContent promotes wp<Layer> to sp<Layer>
2471     // and may eventually call to ~Layer() if it holds the last reference
2472     {
2473         Mutex::Autolock lock(mStateLock);
2474         mScheduler->chooseRefreshRateForContent();
2475         initiateDisplayModeChanges();
2476     }
2477 
2478     updateCursorAsync();
2479     updateInputFlinger(vsyncId, pacesetterFrameTarget.frameBeginTime());
2480 
2481     if (mLayerTracingEnabled && !mLayerTracing.flagIsSet(LayerTracing::TRACE_COMPOSITION)) {
2482         // This will block and tracing should only be enabled for debugging.
2483         addToLayerTracing(mVisibleRegionsDirty, pacesetterFrameTarget.frameBeginTime(), vsyncId);
2484     }
2485     mLastCommittedVsyncId = vsyncId;
2486 
2487     persistDisplayBrightness(mustComposite);
2488 
2489     return mustComposite && CC_LIKELY(mBootStage != BootStage::BOOTLOADER);
2490 }
2491 
composite(PhysicalDisplayId pacesetterId,const scheduler::FrameTargeters & frameTargeters)2492 CompositeResultsPerDisplay SurfaceFlinger::composite(
2493         PhysicalDisplayId pacesetterId, const scheduler::FrameTargeters& frameTargeters) {
2494     const scheduler::FrameTarget& pacesetterTarget =
2495             frameTargeters.get(pacesetterId)->get()->target();
2496 
2497     const VsyncId vsyncId = pacesetterTarget.vsyncId();
2498     ATRACE_NAME(ftl::Concat(__func__, ' ', ftl::to_underlying(vsyncId)).c_str());
2499 
2500     compositionengine::CompositionRefreshArgs refreshArgs;
2501     refreshArgs.powerCallback = this;
2502     const auto& displays = FTL_FAKE_GUARD(mStateLock, mDisplays);
2503     refreshArgs.outputs.reserve(displays.size());
2504 
2505     // Add outputs for physical displays.
2506     for (const auto& [id, targeter] : frameTargeters) {
2507         ftl::FakeGuard guard(mStateLock);
2508 
2509         if (const auto display = getCompositionDisplayLocked(id)) {
2510             refreshArgs.outputs.push_back(display);
2511         }
2512     }
2513 
2514     std::vector<DisplayId> displayIds;
2515     for (const auto& [_, display] : displays) {
2516         displayIds.push_back(display->getId());
2517         display->tracePowerMode();
2518 
2519         // Add outputs for virtual displays.
2520         if (display->isVirtual()) {
2521             const Fps refreshRate = display->getAdjustedRefreshRate();
2522 
2523             if (!refreshRate.isValid() ||
2524                 mScheduler->isVsyncInPhase(pacesetterTarget.frameBeginTime(), refreshRate)) {
2525                 refreshArgs.outputs.push_back(display->getCompositionDisplay());
2526             }
2527         }
2528     }
2529     mPowerAdvisor->setDisplays(displayIds);
2530 
2531     const bool updateTaskMetadata = mCompositionEngine->getFeatureFlags().test(
2532             compositionengine::Feature::kSnapshotLayerMetadata);
2533     if (updateTaskMetadata && (mVisibleRegionsDirty || mLayerMetadataSnapshotNeeded)) {
2534         updateLayerMetadataSnapshot();
2535         mLayerMetadataSnapshotNeeded = false;
2536     }
2537 
2538     if (DOES_CONTAIN_BORDER) {
2539         refreshArgs.borderInfoList.clear();
2540         mDrawingState.traverse([&refreshArgs](Layer* layer) {
2541             if (layer->isBorderEnabled()) {
2542                 compositionengine::BorderRenderInfo info;
2543                 info.width = layer->getBorderWidth();
2544                 info.color = layer->getBorderColor();
2545                 layer->traverse(LayerVector::StateSet::Drawing, [&info](Layer* ilayer) {
2546                     info.layerIds.push_back(ilayer->getSequence());
2547                 });
2548                 refreshArgs.borderInfoList.emplace_back(std::move(info));
2549             }
2550         });
2551     }
2552 
2553     refreshArgs.bufferIdsToUncache = std::move(mBufferIdsToUncache);
2554 
2555     refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
2556     for (auto layer : mLayersWithQueuedFrames) {
2557         if (auto layerFE = layer->getCompositionEngineLayerFE())
2558             refreshArgs.layersWithQueuedFrames.push_back(layerFE);
2559     }
2560 
2561     refreshArgs.outputColorSetting = useColorManagement
2562             ? mDisplayColorSetting
2563             : compositionengine::OutputColorSetting::kUnmanaged;
2564     refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
2565     refreshArgs.forceOutputColorMode = mForceColorMode;
2566 
2567     refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
2568     refreshArgs.updatingGeometryThisFrame = mGeometryDirty.exchange(false) || mVisibleRegionsDirty;
2569     refreshArgs.internalDisplayRotationFlags = getActiveDisplayRotationFlags();
2570 
2571     if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
2572         refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
2573         mDrawingState.colorMatrixChanged = false;
2574     }
2575 
2576     refreshArgs.devOptForceClientComposition = mDebugDisableHWC;
2577 
2578     if (mDebugFlashDelay != 0) {
2579         refreshArgs.devOptForceClientComposition = true;
2580         refreshArgs.devOptFlashDirtyRegionsDelay = std::chrono::milliseconds(mDebugFlashDelay);
2581     }
2582 
2583     const Period vsyncPeriod = mScheduler->getVsyncSchedule()->period();
2584 
2585     if (!getHwComposer().getComposer()->isSupported(
2586                 Hwc2::Composer::OptionalFeature::ExpectedPresentTime) &&
2587         pacesetterTarget.wouldPresentEarly(vsyncPeriod)) {
2588         const auto hwcMinWorkDuration = mVsyncConfiguration->getCurrentConfigs().hwcMinWorkDuration;
2589 
2590         // TODO(b/255601557): Calculate and pass per-display values for each FrameTarget.
2591         refreshArgs.earliestPresentTime =
2592                 pacesetterTarget.previousFrameVsyncTime(vsyncPeriod) - hwcMinWorkDuration;
2593     }
2594 
2595     refreshArgs.scheduledFrameTime = mScheduler->getScheduledFrameTime();
2596     refreshArgs.expectedPresentTime = pacesetterTarget.expectedPresentTime().ns();
2597     refreshArgs.hasTrustedPresentationListener = mNumTrustedPresentationListeners > 0;
2598 
2599     // Store the present time just before calling to the composition engine so we could notify
2600     // the scheduler.
2601     const auto presentTime = systemTime();
2602 
2603     constexpr bool kCursorOnly = false;
2604     const auto layers = moveSnapshotsToCompositionArgs(refreshArgs, kCursorOnly);
2605 
2606     mCompositionEngine->present(refreshArgs);
2607     moveSnapshotsFromCompositionArgs(refreshArgs, layers);
2608 
2609     for (auto [layer, layerFE] : layers) {
2610         CompositionResult compositionResult{layerFE->stealCompositionResult()};
2611         layer->onPreComposition(compositionResult.refreshStartTime);
2612         for (auto& [releaseFence, layerStack] : compositionResult.releaseFences) {
2613             Layer* clonedFrom = layer->getClonedFrom().get();
2614             auto owningLayer = clonedFrom ? clonedFrom : layer;
2615             owningLayer->onLayerDisplayed(std::move(releaseFence), layerStack);
2616         }
2617         if (compositionResult.lastClientCompositionFence) {
2618             layer->setWasClientComposed(compositionResult.lastClientCompositionFence);
2619         }
2620     }
2621 
2622     mTimeStats->recordFrameDuration(pacesetterTarget.frameBeginTime().ns(), systemTime());
2623 
2624     // Send a power hint after presentation is finished.
2625     if (mPowerHintSessionEnabled) {
2626         // Now that the current frame has been presented above, PowerAdvisor needs the present time
2627         // of the previous frame (whose fence is signaled by now) to determine how long the HWC had
2628         // waited on that fence to retire before presenting.
2629         const auto& previousPresentFence = pacesetterTarget.presentFenceForPreviousFrame();
2630 
2631         mPowerAdvisor->setSfPresentTiming(TimePoint::fromNs(previousPresentFence->getSignalTime()),
2632                                           TimePoint::now());
2633         mPowerAdvisor->reportActualWorkDuration();
2634     }
2635 
2636     if (mScheduler->onPostComposition(presentTime)) {
2637         scheduleComposite(FrameHint::kNone);
2638     }
2639 
2640     postComposition(pacesetterId, frameTargeters, presentTime);
2641 
2642     const bool hadGpuComposited =
2643             multiDisplayUnion(mCompositionCoverage).test(CompositionCoverage::Gpu);
2644     mCompositionCoverage.clear();
2645 
2646     TimeStats::ClientCompositionRecord clientCompositionRecord;
2647 
2648     for (const auto& [_, display] : displays) {
2649         const auto& state = display->getCompositionDisplay()->getState();
2650         CompositionCoverageFlags& flags =
2651                 mCompositionCoverage.try_emplace(display->getId()).first->second;
2652 
2653         if (state.usesDeviceComposition) {
2654             flags |= CompositionCoverage::Hwc;
2655         }
2656 
2657         if (state.reusedClientComposition) {
2658             flags |= CompositionCoverage::GpuReuse;
2659         } else if (state.usesClientComposition) {
2660             flags |= CompositionCoverage::Gpu;
2661         }
2662 
2663         clientCompositionRecord.predicted |=
2664                 (state.strategyPrediction != CompositionStrategyPredictionState::DISABLED);
2665         clientCompositionRecord.predictionSucceeded |=
2666                 (state.strategyPrediction == CompositionStrategyPredictionState::SUCCESS);
2667     }
2668 
2669     const auto coverage = multiDisplayUnion(mCompositionCoverage);
2670     const bool hasGpuComposited = coverage.test(CompositionCoverage::Gpu);
2671 
2672     clientCompositionRecord.hadClientComposition = hasGpuComposited;
2673     clientCompositionRecord.reused = coverage.test(CompositionCoverage::GpuReuse);
2674     clientCompositionRecord.changed = hadGpuComposited != hasGpuComposited;
2675 
2676     mTimeStats->pushCompositionStrategyState(clientCompositionRecord);
2677 
2678     using namespace ftl::flag_operators;
2679 
2680     // TODO(b/160583065): Enable skip validation when SF caches all client composition layers.
2681     const bool hasGpuUseOrReuse =
2682             coverage.any(CompositionCoverage::Gpu | CompositionCoverage::GpuReuse);
2683     mScheduler->modulateVsync({}, &VsyncModulator::onDisplayRefresh, hasGpuUseOrReuse);
2684 
2685     mLayersWithQueuedFrames.clear();
2686     if (mLayerTracingEnabled && mLayerTracing.flagIsSet(LayerTracing::TRACE_COMPOSITION)) {
2687         // This will block and should only be used for debugging.
2688         addToLayerTracing(mVisibleRegionsDirty, pacesetterTarget.frameBeginTime(), vsyncId);
2689     }
2690 
2691     if (mVisibleRegionsDirty) mHdrLayerInfoChanged = true;
2692     mVisibleRegionsDirty = false;
2693 
2694     if (mCompositionEngine->needsAnotherUpdate()) {
2695         scheduleCommit(FrameHint::kNone);
2696     }
2697 
2698     if (mPowerHintSessionEnabled) {
2699         mPowerAdvisor->setCompositeEnd(TimePoint::now());
2700     }
2701 
2702     CompositeResultsPerDisplay resultsPerDisplay;
2703 
2704     // Filter out virtual displays.
2705     for (const auto& [id, coverage] : mCompositionCoverage) {
2706         if (const auto idOpt = PhysicalDisplayId::tryCast(id)) {
2707             resultsPerDisplay.try_emplace(*idOpt, CompositeResult{coverage});
2708         }
2709     }
2710 
2711     return resultsPerDisplay;
2712 }
2713 
updateLayerGeometry()2714 void SurfaceFlinger::updateLayerGeometry() {
2715     ATRACE_CALL();
2716 
2717     if (mVisibleRegionsDirty) {
2718         computeLayerBounds();
2719     }
2720 
2721     for (auto& layer : mLayersPendingRefresh) {
2722         Region visibleReg;
2723         visibleReg.set(layer->getScreenBounds());
2724         invalidateLayerStack(layer->getOutputFilter(), visibleReg);
2725     }
2726     mLayersPendingRefresh.clear();
2727 }
2728 
isHdrLayer(const frontend::LayerSnapshot & snapshot) const2729 bool SurfaceFlinger::isHdrLayer(const frontend::LayerSnapshot& snapshot) const {
2730     // Even though the camera layer may be using an HDR transfer function or otherwise be "HDR"
2731     // the device may need to avoid boosting the brightness as a result of these layers to
2732     // reduce power consumption during camera recording
2733     if (mIgnoreHdrCameraLayers) {
2734         if (snapshot.externalTexture &&
2735             (snapshot.externalTexture->getUsage() & GRALLOC_USAGE_HW_CAMERA_WRITE) != 0) {
2736             return false;
2737         }
2738     }
2739     // RANGE_EXTENDED layer may identify themselves as being "HDR"
2740     // via a desired hdr/sdr ratio
2741     auto pixelFormat = snapshot.buffer
2742             ? std::make_optional(static_cast<ui::PixelFormat>(snapshot.buffer->getPixelFormat()))
2743             : std::nullopt;
2744 
2745     if (getHdrRenderType(snapshot.dataspace, pixelFormat, snapshot.desiredHdrSdrRatio) !=
2746         HdrRenderType::SDR) {
2747         return true;
2748     }
2749     // If the layer is not allowed to be dimmed, treat it as HDR. WindowManager may disable
2750     // dimming in order to keep animations invoking SDR screenshots of HDR layers seamless.
2751     // Treat such tagged layers as HDR so that DisplayManagerService does not try to change
2752     // the screen brightness
2753     if (!snapshot.dimmingEnabled) {
2754         return true;
2755     }
2756     return false;
2757 }
2758 
getPhysicalDisplayOrientation(DisplayId displayId,bool isPrimary) const2759 ui::Rotation SurfaceFlinger::getPhysicalDisplayOrientation(DisplayId displayId,
2760                                                            bool isPrimary) const {
2761     const auto id = PhysicalDisplayId::tryCast(displayId);
2762     if (!id) {
2763         return ui::ROTATION_0;
2764     }
2765     if (!mIgnoreHwcPhysicalDisplayOrientation &&
2766         getHwComposer().getComposer()->isSupported(
2767                 Hwc2::Composer::OptionalFeature::PhysicalDisplayOrientation)) {
2768         switch (getHwComposer().getPhysicalDisplayOrientation(*id)) {
2769             case Hwc2::AidlTransform::ROT_90:
2770                 return ui::ROTATION_90;
2771             case Hwc2::AidlTransform::ROT_180:
2772                 return ui::ROTATION_180;
2773             case Hwc2::AidlTransform::ROT_270:
2774                 return ui::ROTATION_270;
2775             default:
2776                 return ui::ROTATION_0;
2777         }
2778     }
2779 
2780     if (isPrimary) {
2781         using Values = SurfaceFlingerProperties::primary_display_orientation_values;
2782         switch (primary_display_orientation(Values::ORIENTATION_0)) {
2783             case Values::ORIENTATION_90:
2784                 return ui::ROTATION_90;
2785             case Values::ORIENTATION_180:
2786                 return ui::ROTATION_180;
2787             case Values::ORIENTATION_270:
2788                 return ui::ROTATION_270;
2789             default:
2790                 break;
2791         }
2792     }
2793     return ui::ROTATION_0;
2794 }
2795 
postComposition(PhysicalDisplayId pacesetterId,const scheduler::FrameTargeters & frameTargeters,nsecs_t presentStartTime)2796 void SurfaceFlinger::postComposition(PhysicalDisplayId pacesetterId,
2797                                      const scheduler::FrameTargeters& frameTargeters,
2798                                      nsecs_t presentStartTime) {
2799     ATRACE_CALL();
2800     ALOGV(__func__);
2801 
2802     ui::PhysicalDisplayMap<PhysicalDisplayId, std::shared_ptr<FenceTime>> presentFences;
2803     ui::PhysicalDisplayMap<PhysicalDisplayId, const sp<Fence>> gpuCompositionDoneFences;
2804 
2805     for (const auto& [id, targeter] : frameTargeters) {
2806         auto presentFence = getHwComposer().getPresentFence(id);
2807 
2808         if (id == pacesetterId) {
2809             mTransactionCallbackInvoker.addPresentFence(presentFence);
2810         }
2811 
2812         if (auto fenceTime = targeter->setPresentFence(std::move(presentFence));
2813             fenceTime->isValid()) {
2814             presentFences.try_emplace(id, std::move(fenceTime));
2815         }
2816 
2817         ftl::FakeGuard guard(mStateLock);
2818         if (const auto display = getCompositionDisplayLocked(id);
2819             display && display->getState().usesClientComposition) {
2820             gpuCompositionDoneFences
2821                     .try_emplace(id, display->getRenderSurface()->getClientTargetAcquireFence());
2822         }
2823     }
2824 
2825     const auto pacesetterDisplay = FTL_FAKE_GUARD(mStateLock, getDisplayDeviceLocked(pacesetterId));
2826 
2827     std::shared_ptr<FenceTime> pacesetterPresentFenceTime =
2828             presentFences.get(pacesetterId)
2829                     .transform([](const FenceTimePtr& ptr) { return ptr; })
2830                     .value_or(FenceTime::NO_FENCE);
2831 
2832     std::shared_ptr<FenceTime> pacesetterGpuCompositionDoneFenceTime =
2833             gpuCompositionDoneFences.get(pacesetterId)
2834                     .transform([](sp<Fence> fence) {
2835                         return std::make_shared<FenceTime>(std::move(fence));
2836                     })
2837                     .value_or(FenceTime::NO_FENCE);
2838 
2839     const TimePoint presentTime = TimePoint::now();
2840 
2841     // Set presentation information before calling Layer::releasePendingBuffer, such that jank
2842     // information from previous' frame classification is already available when sending jank info
2843     // to clients, so they get jank classification as early as possible.
2844     mFrameTimeline->setSfPresent(presentTime.ns(), pacesetterPresentFenceTime,
2845                                  pacesetterGpuCompositionDoneFenceTime);
2846 
2847     // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
2848     // be sampled a little later than when we started doing work for this frame,
2849     // but that should be okay since CompositorTiming has snapping logic.
2850     const TimePoint compositeTime =
2851             TimePoint::fromNs(mCompositionEngine->getLastFrameRefreshTimestamp());
2852     const Duration presentLatency =
2853             getHwComposer().hasCapability(Capability::PRESENT_FENCE_IS_NOT_RELIABLE)
2854             ? Duration::zero()
2855             : mPresentLatencyTracker.trackPendingFrame(compositeTime, pacesetterPresentFenceTime);
2856 
2857     const auto schedule = mScheduler->getVsyncSchedule();
2858     const TimePoint vsyncDeadline = schedule->vsyncDeadlineAfter(presentTime);
2859     const Period vsyncPeriod = schedule->period();
2860     const nsecs_t vsyncPhase = mVsyncConfiguration->getCurrentConfigs().late.sfOffset;
2861 
2862     const CompositorTiming compositorTiming(vsyncDeadline.ns(), vsyncPeriod.ns(), vsyncPhase,
2863                                             presentLatency.ns());
2864 
2865     ui::DisplayMap<ui::LayerStack, const DisplayDevice*> layerStackToDisplay;
2866     {
2867         if (!mLayersWithBuffersRemoved.empty() || mNumTrustedPresentationListeners > 0) {
2868             Mutex::Autolock lock(mStateLock);
2869             for (const auto& [token, display] : mDisplays) {
2870                 layerStackToDisplay.emplace_or_replace(display->getLayerStack(), display.get());
2871             }
2872         }
2873     }
2874 
2875     for (auto layer : mLayersWithBuffersRemoved) {
2876         std::vector<ui::LayerStack> previouslyPresentedLayerStacks =
2877                 std::move(layer->mPreviouslyPresentedLayerStacks);
2878         layer->mPreviouslyPresentedLayerStacks.clear();
2879         for (auto layerStack : previouslyPresentedLayerStacks) {
2880             auto optDisplay = layerStackToDisplay.get(layerStack);
2881             if (optDisplay && !optDisplay->get()->isVirtual()) {
2882                 auto fence = getHwComposer().getPresentFence(optDisplay->get()->getPhysicalId());
2883                 layer->onLayerDisplayed(ftl::yield<FenceResult>(fence).share(),
2884                                         ui::INVALID_LAYER_STACK);
2885             }
2886         }
2887         layer->releasePendingBuffer(presentTime.ns());
2888     }
2889     mLayersWithBuffersRemoved.clear();
2890 
2891     for (const auto& layer: mLayersWithQueuedFrames) {
2892         layer->onPostComposition(pacesetterDisplay.get(), pacesetterGpuCompositionDoneFenceTime,
2893                                  pacesetterPresentFenceTime, compositorTiming);
2894         layer->releasePendingBuffer(presentTime.ns());
2895     }
2896 
2897     std::vector<std::pair<std::shared_ptr<compositionengine::Display>, sp<HdrLayerInfoReporter>>>
2898             hdrInfoListeners;
2899     bool haveNewListeners = false;
2900     {
2901         Mutex::Autolock lock(mStateLock);
2902         if (mFpsReporter) {
2903             mFpsReporter->dispatchLayerFps();
2904         }
2905 
2906         if (mTunnelModeEnabledReporter) {
2907             mTunnelModeEnabledReporter->updateTunnelModeStatus();
2908         }
2909         hdrInfoListeners.reserve(mHdrLayerInfoListeners.size());
2910         for (const auto& [displayId, reporter] : mHdrLayerInfoListeners) {
2911             if (reporter && reporter->hasListeners()) {
2912                 if (const auto display = getDisplayDeviceLocked(displayId)) {
2913                     hdrInfoListeners.emplace_back(display->getCompositionDisplay(), reporter);
2914                 }
2915             }
2916         }
2917         haveNewListeners = mAddingHDRLayerInfoListener; // grab this with state lock
2918         mAddingHDRLayerInfoListener = false;
2919     }
2920 
2921     if (haveNewListeners || mHdrLayerInfoChanged) {
2922         for (auto& [compositionDisplay, listener] : hdrInfoListeners) {
2923             HdrLayerInfoReporter::HdrLayerInfo info;
2924             int32_t maxArea = 0;
2925             mDrawingState.traverse([&, compositionDisplay = compositionDisplay](Layer* layer) {
2926                 const auto layerFe = layer->getCompositionEngineLayerFE();
2927                 const frontend::LayerSnapshot& snapshot = *layer->getLayerSnapshot();
2928                 if (snapshot.isVisible &&
2929                     compositionDisplay->includesLayer(snapshot.outputFilter)) {
2930                     if (isHdrLayer(snapshot)) {
2931                         const auto* outputLayer =
2932                             compositionDisplay->getOutputLayerForLayer(layerFe);
2933                         if (outputLayer) {
2934                             const float desiredHdrSdrRatio = snapshot.desiredHdrSdrRatio <= 1.f
2935                                     ? std::numeric_limits<float>::infinity()
2936                                     : snapshot.desiredHdrSdrRatio;
2937                             info.mergeDesiredRatio(desiredHdrSdrRatio);
2938                             info.numberOfHdrLayers++;
2939                             const auto displayFrame = outputLayer->getState().displayFrame;
2940                             const int32_t area = displayFrame.width() * displayFrame.height();
2941                             if (area > maxArea) {
2942                                 maxArea = area;
2943                                 info.maxW = displayFrame.width();
2944                                 info.maxH = displayFrame.height();
2945                             }
2946                         }
2947                     }
2948                 }
2949             });
2950             listener->dispatchHdrLayerInfo(info);
2951         }
2952     }
2953 
2954     mHdrLayerInfoChanged = false;
2955 
2956     mTransactionCallbackInvoker.sendCallbacks(false /* onCommitOnly */);
2957     mTransactionCallbackInvoker.clearCompletedTransactions();
2958 
2959     mTimeStats->incrementTotalFrames();
2960     mTimeStats->setPresentFenceGlobal(pacesetterPresentFenceTime);
2961 
2962     for (auto&& [id, presentFence] : presentFences) {
2963         ftl::FakeGuard guard(mStateLock);
2964         const bool isInternalDisplay =
2965                 mPhysicalDisplays.get(id).transform(&PhysicalDisplay::isInternal).value_or(false);
2966 
2967         if (isInternalDisplay) {
2968             mScheduler->addPresentFence(id, std::move(presentFence));
2969         }
2970     }
2971 
2972     const bool hasPacesetterDisplay =
2973             pacesetterDisplay && getHwComposer().isConnected(pacesetterId);
2974 
2975     if (!hasSyncFramework) {
2976         if (hasPacesetterDisplay && pacesetterDisplay->isPoweredOn()) {
2977             mScheduler->enableHardwareVsync(pacesetterId);
2978         }
2979     }
2980 
2981     const size_t sfConnections = mScheduler->getEventThreadConnectionCount(mSfConnectionHandle);
2982     const size_t appConnections = mScheduler->getEventThreadConnectionCount(mAppConnectionHandle);
2983     mTimeStats->recordDisplayEventConnectionCount(sfConnections + appConnections);
2984 
2985     if (hasPacesetterDisplay && !pacesetterDisplay->isPoweredOn()) {
2986         getRenderEngine().cleanupPostRender();
2987         return;
2988     }
2989 
2990     // Cleanup any outstanding resources due to rendering a prior frame.
2991     getRenderEngine().cleanupPostRender();
2992 
2993     {
2994         std::lock_guard lock(mTexturePoolMutex);
2995         if (mTexturePool.size() < mTexturePoolSize) {
2996             const size_t refillCount = mTexturePoolSize - mTexturePool.size();
2997             const size_t offset = mTexturePool.size();
2998             mTexturePool.resize(mTexturePoolSize);
2999             getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
3000             ATRACE_INT("TexturePoolSize", mTexturePool.size());
3001         } else if (mTexturePool.size() > mTexturePoolSize) {
3002             const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
3003             const size_t offset = mTexturePoolSize;
3004             getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
3005             mTexturePool.resize(mTexturePoolSize);
3006             ATRACE_INT("TexturePoolSize", mTexturePool.size());
3007         }
3008     }
3009 
3010     if (mNumTrustedPresentationListeners > 0) {
3011         // We avoid any reverse traversal upwards so this shouldn't be too expensive
3012         traverseLegacyLayers([&](Layer* layer) {
3013             if (!layer->hasTrustedPresentationListener()) {
3014                 return;
3015             }
3016             const frontend::LayerSnapshot* snapshot = mLayerLifecycleManagerEnabled
3017                     ? mLayerSnapshotBuilder.getSnapshot(layer->sequence)
3018                     : layer->getLayerSnapshot();
3019             std::optional<const DisplayDevice*> displayOpt = std::nullopt;
3020             if (snapshot) {
3021                 displayOpt = layerStackToDisplay.get(snapshot->outputFilter.layerStack);
3022             }
3023             const DisplayDevice* display = displayOpt.value_or(nullptr);
3024             layer->updateTrustedPresentationState(display, snapshot,
3025                                                   nanoseconds_to_milliseconds(presentStartTime),
3026                                                   false);
3027         });
3028     }
3029 
3030     // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
3031     // side-effect of getTotalSize(), so we check that again here
3032     if (ATRACE_ENABLED()) {
3033         // getTotalSize returns the total number of buffers that were allocated by SurfaceFlinger
3034         ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
3035     }
3036 
3037     logFrameStats(presentTime);
3038 }
3039 
getMaxDisplayBounds()3040 FloatRect SurfaceFlinger::getMaxDisplayBounds() {
3041     const ui::Size maxSize = [this] {
3042         ftl::FakeGuard guard(mStateLock);
3043 
3044         // The LayerTraceGenerator tool runs without displays.
3045         if (mDisplays.empty()) return ui::Size{5000, 5000};
3046 
3047         return std::accumulate(mDisplays.begin(), mDisplays.end(), ui::kEmptySize,
3048                                [](ui::Size size, const auto& pair) -> ui::Size {
3049                                    const auto& display = pair.second;
3050                                    return {std::max(size.getWidth(), display->getWidth()),
3051                                            std::max(size.getHeight(), display->getHeight())};
3052                                });
3053     }();
3054 
3055     // Ignore display bounds for now since they will be computed later. Use a large Rect bound
3056     // to ensure it's bigger than an actual display will be.
3057     const float xMax = maxSize.getWidth() * 10.f;
3058     const float yMax = maxSize.getHeight() * 10.f;
3059 
3060     return {-xMax, -yMax, xMax, yMax};
3061 }
3062 
computeLayerBounds()3063 void SurfaceFlinger::computeLayerBounds() {
3064     const FloatRect maxBounds = getMaxDisplayBounds();
3065     for (const auto& layer : mDrawingState.layersSortedByZ) {
3066         layer->computeBounds(maxBounds, ui::Transform(), 0.f /* shadowRadius */);
3067     }
3068 }
3069 
commitTransactions()3070 void SurfaceFlinger::commitTransactions() {
3071     ATRACE_CALL();
3072 
3073     // Keep a copy of the drawing state (that is going to be overwritten
3074     // by commitTransactionsLocked) outside of mStateLock so that the side
3075     // effects of the State assignment don't happen with mStateLock held,
3076     // which can cause deadlocks.
3077     State drawingState(mDrawingState);
3078 
3079     Mutex::Autolock lock(mStateLock);
3080     mDebugInTransaction = systemTime();
3081 
3082     // Here we're guaranteed that some transaction flags are set
3083     // so we can call commitTransactionsLocked unconditionally.
3084     // We clear the flags with mStateLock held to guarantee that
3085     // mCurrentState won't change until the transaction is committed.
3086     mScheduler->modulateVsync({}, &VsyncModulator::onTransactionCommit);
3087     commitTransactionsLocked(clearTransactionFlags(eTransactionMask));
3088 
3089     mDebugInTransaction = 0;
3090 }
3091 
loadDisplayModes(PhysicalDisplayId displayId) const3092 std::pair<DisplayModes, DisplayModePtr> SurfaceFlinger::loadDisplayModes(
3093         PhysicalDisplayId displayId) const {
3094     std::vector<HWComposer::HWCDisplayMode> hwcModes;
3095     std::optional<hal::HWDisplayId> activeModeHwcId;
3096 
3097     int attempt = 0;
3098     constexpr int kMaxAttempts = 3;
3099     do {
3100         hwcModes = getHwComposer().getModes(displayId);
3101         activeModeHwcId = getHwComposer().getActiveMode(displayId);
3102 
3103         const auto isActiveMode = [activeModeHwcId](const HWComposer::HWCDisplayMode& mode) {
3104             return mode.hwcId == activeModeHwcId;
3105         };
3106 
3107         if (std::any_of(hwcModes.begin(), hwcModes.end(), isActiveMode)) {
3108             break;
3109         }
3110     } while (++attempt < kMaxAttempts);
3111 
3112     if (attempt == kMaxAttempts) {
3113         const std::string activeMode =
3114                 activeModeHwcId ? std::to_string(*activeModeHwcId) : "unknown"s;
3115         ALOGE("HWC failed to report an active mode that is supported: activeModeHwcId=%s, "
3116               "hwcModes={%s}",
3117               activeMode.c_str(), base::Join(hwcModes, ", ").c_str());
3118         return {};
3119     }
3120 
3121     const DisplayModes oldModes = mPhysicalDisplays.get(displayId)
3122                                           .transform([](const PhysicalDisplay& display) {
3123                                               return display.snapshot().displayModes();
3124                                           })
3125                                           .value_or(DisplayModes{});
3126 
3127     ui::DisplayModeId nextModeId = 1 +
3128             std::accumulate(oldModes.begin(), oldModes.end(), static_cast<ui::DisplayModeId>(-1),
3129                             [](ui::DisplayModeId max, const auto& pair) {
3130                                 return std::max(max, pair.first.value());
3131                             });
3132 
3133     DisplayModes newModes;
3134     for (const auto& hwcMode : hwcModes) {
3135         const DisplayModeId id{nextModeId++};
3136         newModes.try_emplace(id,
3137                              DisplayMode::Builder(hwcMode.hwcId)
3138                                      .setId(id)
3139                                      .setPhysicalDisplayId(displayId)
3140                                      .setResolution({hwcMode.width, hwcMode.height})
3141                                      .setVsyncPeriod(hwcMode.vsyncPeriod)
3142                                      .setDpiX(hwcMode.dpiX)
3143                                      .setDpiY(hwcMode.dpiY)
3144                                      .setGroup(hwcMode.configGroup)
3145                                      .build());
3146     }
3147 
3148     const bool sameModes =
3149             std::equal(newModes.begin(), newModes.end(), oldModes.begin(), oldModes.end(),
3150                        [](const auto& lhs, const auto& rhs) {
3151                            return equalsExceptDisplayModeId(*lhs.second, *rhs.second);
3152                        });
3153 
3154     // Keep IDs if modes have not changed.
3155     const auto& modes = sameModes ? oldModes : newModes;
3156     const DisplayModePtr activeMode =
3157             std::find_if(modes.begin(), modes.end(), [activeModeHwcId](const auto& pair) {
3158                 return pair.second->getHwcId() == activeModeHwcId;
3159             })->second;
3160 
3161     return {modes, activeMode};
3162 }
3163 
configureLocked()3164 bool SurfaceFlinger::configureLocked() {
3165     std::vector<HotplugEvent> events;
3166     {
3167         std::lock_guard<std::mutex> lock(mHotplugMutex);
3168         events = std::move(mPendingHotplugEvents);
3169     }
3170 
3171     for (const auto [hwcDisplayId, connection] : events) {
3172         if (auto info = getHwComposer().onHotplug(hwcDisplayId, connection)) {
3173             const auto displayId = info->id;
3174             const bool connected = connection == hal::Connection::CONNECTED;
3175 
3176             if (const char* const log =
3177                         processHotplug(displayId, hwcDisplayId, connected, std::move(*info))) {
3178                 ALOGI("%s display %s (HAL ID %" PRIu64 ")", log, to_string(displayId).c_str(),
3179                       hwcDisplayId);
3180             }
3181         }
3182     }
3183 
3184     return !events.empty();
3185 }
3186 
processHotplug(PhysicalDisplayId displayId,hal::HWDisplayId hwcDisplayId,bool connected,DisplayIdentificationInfo && info)3187 const char* SurfaceFlinger::processHotplug(PhysicalDisplayId displayId,
3188                                            hal::HWDisplayId hwcDisplayId, bool connected,
3189                                            DisplayIdentificationInfo&& info) {
3190     const auto displayOpt = mPhysicalDisplays.get(displayId);
3191     if (!connected) {
3192         LOG_ALWAYS_FATAL_IF(!displayOpt);
3193         const auto& display = displayOpt->get();
3194 
3195         if (const ssize_t index = mCurrentState.displays.indexOfKey(display.token()); index >= 0) {
3196             mCurrentState.displays.removeItemsAt(index);
3197         }
3198 
3199         mPhysicalDisplays.erase(displayId);
3200         return "Disconnecting";
3201     }
3202 
3203     auto [displayModes, activeMode] = loadDisplayModes(displayId);
3204     if (!activeMode) {
3205         // TODO(b/241286153): Report hotplug failure to the framework.
3206         ALOGE("Failed to hotplug display %s", to_string(displayId).c_str());
3207         getHwComposer().disconnectDisplay(displayId);
3208         return nullptr;
3209     }
3210 
3211     ui::ColorModes colorModes = getHwComposer().getColorModes(displayId);
3212 
3213     if (displayOpt) {
3214         const auto& display = displayOpt->get();
3215         const auto& snapshot = display.snapshot();
3216 
3217         std::optional<DeviceProductInfo> deviceProductInfo;
3218         if (getHwComposer().updatesDeviceProductInfoOnHotplugReconnect()) {
3219             deviceProductInfo = std::move(info.deviceProductInfo);
3220         } else {
3221             deviceProductInfo = snapshot.deviceProductInfo();
3222         }
3223 
3224         const auto it =
3225                 mPhysicalDisplays.try_replace(displayId, display.token(), displayId,
3226                                               snapshot.connectionType(), std::move(displayModes),
3227                                               std::move(colorModes), std::move(deviceProductInfo));
3228 
3229         auto& state = mCurrentState.displays.editValueFor(it->second.token());
3230         state.sequenceId = DisplayDeviceState{}.sequenceId; // Generate new sequenceId.
3231         state.physical->activeMode = std::move(activeMode);
3232         return "Reconnecting";
3233     }
3234 
3235     const sp<IBinder> token = sp<BBinder>::make();
3236 
3237     mPhysicalDisplays.try_emplace(displayId, token, displayId,
3238                                   getHwComposer().getDisplayConnectionType(displayId),
3239                                   std::move(displayModes), std::move(colorModes),
3240                                   std::move(info.deviceProductInfo));
3241 
3242     DisplayDeviceState state;
3243     state.physical = {.id = displayId,
3244                       .hwcDisplayId = hwcDisplayId,
3245                       .activeMode = std::move(activeMode)};
3246     state.isSecure = true; // All physical displays are currently considered secure.
3247     state.displayName = std::move(info.name);
3248 
3249     mCurrentState.displays.add(token, state);
3250     return "Connecting";
3251 }
3252 
dispatchDisplayHotplugEvent(PhysicalDisplayId displayId,bool connected)3253 void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
3254     mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
3255     mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
3256 }
3257 
dispatchDisplayModeChangeEvent(PhysicalDisplayId displayId,const scheduler::FrameRateMode & mode)3258 void SurfaceFlinger::dispatchDisplayModeChangeEvent(PhysicalDisplayId displayId,
3259                                                     const scheduler::FrameRateMode& mode) {
3260     // TODO(b/255635821): Merge code paths and move to Scheduler.
3261     const auto onDisplayModeChanged = displayId == mActiveDisplayId
3262             ? &scheduler::Scheduler::onPrimaryDisplayModeChanged
3263             : &scheduler::Scheduler::onNonPrimaryDisplayModeChanged;
3264 
3265     ((*mScheduler).*onDisplayModeChanged)(mAppConnectionHandle, mode);
3266 }
3267 
setupNewDisplayDeviceInternal(const wp<IBinder> & displayToken,std::shared_ptr<compositionengine::Display> compositionDisplay,const DisplayDeviceState & state,const sp<compositionengine::DisplaySurface> & displaySurface,const sp<IGraphicBufferProducer> & producer)3268 sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
3269         const wp<IBinder>& displayToken,
3270         std::shared_ptr<compositionengine::Display> compositionDisplay,
3271         const DisplayDeviceState& state,
3272         const sp<compositionengine::DisplaySurface>& displaySurface,
3273         const sp<IGraphicBufferProducer>& producer) {
3274     DisplayDeviceCreationArgs creationArgs(sp<SurfaceFlinger>::fromExisting(this), getHwComposer(),
3275                                            displayToken, compositionDisplay);
3276     creationArgs.sequenceId = state.sequenceId;
3277     creationArgs.isSecure = state.isSecure;
3278     creationArgs.displaySurface = displaySurface;
3279     creationArgs.hasWideColorGamut = false;
3280     creationArgs.supportedPerFrameMetadata = 0;
3281 
3282     if (const auto& physical = state.physical) {
3283         creationArgs.activeModeId = physical->activeMode->getId();
3284         const auto [kernelIdleTimerController, idleTimerTimeoutMs] =
3285                 getKernelIdleTimerProperties(compositionDisplay->getId());
3286 
3287         using Config = scheduler::RefreshRateSelector::Config;
3288         const auto enableFrameRateOverride = sysprop::enable_frame_rate_override(true)
3289                 ? Config::FrameRateOverride::Enabled
3290                 : Config::FrameRateOverride::Disabled;
3291         Config config =
3292                 {.enableFrameRateOverride = enableFrameRateOverride,
3293                  .frameRateMultipleThreshold =
3294                          base::GetIntProperty("debug.sf.frame_rate_multiple_threshold", 0),
3295                  .idleTimerTimeout = idleTimerTimeoutMs,
3296                  .kernelIdleTimerController = kernelIdleTimerController};
3297 
3298         creationArgs.refreshRateSelector =
3299                 mPhysicalDisplays.get(physical->id)
3300                         .transform(&PhysicalDisplay::snapshotRef)
3301                         .transform([&](const display::DisplaySnapshot& snapshot) {
3302                             return std::make_shared<
3303                                     scheduler::RefreshRateSelector>(snapshot.displayModes(),
3304                                                                     creationArgs.activeModeId,
3305                                                                     config);
3306                         })
3307                         .value_or(nullptr);
3308 
3309         creationArgs.isPrimary = physical->id == getPrimaryDisplayIdLocked();
3310 
3311         if (useColorManagement) {
3312             mPhysicalDisplays.get(physical->id)
3313                     .transform(&PhysicalDisplay::snapshotRef)
3314                     .transform(ftl::unit_fn([&](const display::DisplaySnapshot& snapshot) {
3315                         for (const auto mode : snapshot.colorModes()) {
3316                             creationArgs.hasWideColorGamut |= ui::isWideColorMode(mode);
3317                             creationArgs.hwcColorModes
3318                                     .emplace(mode,
3319                                              getHwComposer().getRenderIntents(physical->id, mode));
3320                         }
3321                     }));
3322         }
3323     }
3324 
3325     if (const auto id = HalDisplayId::tryCast(compositionDisplay->getId())) {
3326         getHwComposer().getHdrCapabilities(*id, &creationArgs.hdrCapabilities);
3327         creationArgs.supportedPerFrameMetadata = getHwComposer().getSupportedPerFrameMetadata(*id);
3328     }
3329 
3330     auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
3331     auto nativeWindow = nativeWindowSurface->getNativeWindow();
3332     creationArgs.nativeWindow = nativeWindow;
3333 
3334     // Make sure that composition can never be stalled by a virtual display
3335     // consumer that isn't processing buffers fast enough. We have to do this
3336     // here, in case the display is composed entirely by HWC.
3337     if (state.isVirtual()) {
3338         nativeWindow->setSwapInterval(nativeWindow.get(), 0);
3339     }
3340 
3341     creationArgs.physicalOrientation =
3342             getPhysicalDisplayOrientation(compositionDisplay->getId(), creationArgs.isPrimary);
3343     ALOGV("Display Orientation: %s", toCString(creationArgs.physicalOrientation));
3344 
3345     // virtual displays are always considered enabled
3346     creationArgs.initialPowerMode =
3347             state.isVirtual() ? std::make_optional(hal::PowerMode::ON) : std::nullopt;
3348 
3349     creationArgs.requestedRefreshRate = state.requestedRefreshRate;
3350 
3351     sp<DisplayDevice> display = getFactory().createDisplayDevice(creationArgs);
3352 
3353     nativeWindowSurface->preallocateBuffers();
3354 
3355     ui::ColorMode defaultColorMode = ui::ColorMode::NATIVE;
3356     Dataspace defaultDataSpace = Dataspace::UNKNOWN;
3357     if (display->hasWideColorGamut()) {
3358         defaultColorMode = ui::ColorMode::SRGB;
3359         defaultDataSpace = Dataspace::V0_SRGB;
3360     }
3361     display->getCompositionDisplay()->setColorProfile(
3362             compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
3363                                                     RenderIntent::COLORIMETRIC,
3364                                                     Dataspace::UNKNOWN});
3365 
3366     if (const auto& physical = state.physical) {
3367         const auto& mode = *physical->activeMode;
3368         display->setActiveMode(mode.getId(), mode.getFps(), mode.getFps());
3369     }
3370 
3371     display->setLayerFilter(makeLayerFilterForDisplay(display->getId(), state.layerStack));
3372     display->setProjection(state.orientation, state.layerStackSpaceRect,
3373                            state.orientedDisplaySpaceRect);
3374     display->setDisplayName(state.displayName);
3375     display->setFlags(state.flags);
3376 
3377     return display;
3378 }
3379 
processDisplayAdded(const wp<IBinder> & displayToken,const DisplayDeviceState & state)3380 void SurfaceFlinger::processDisplayAdded(const wp<IBinder>& displayToken,
3381                                          const DisplayDeviceState& state) {
3382     ui::Size resolution(0, 0);
3383     ui::PixelFormat pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_UNKNOWN);
3384     if (state.physical) {
3385         resolution = state.physical->activeMode->getResolution();
3386         pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_RGBA_8888);
3387     } else if (state.surface != nullptr) {
3388         int status = state.surface->query(NATIVE_WINDOW_WIDTH, &resolution.width);
3389         ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
3390         status = state.surface->query(NATIVE_WINDOW_HEIGHT, &resolution.height);
3391         ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
3392         int format;
3393         status = state.surface->query(NATIVE_WINDOW_FORMAT, &format);
3394         ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
3395         pixelFormat = static_cast<ui::PixelFormat>(format);
3396     } else {
3397         // Virtual displays without a surface are dormant:
3398         // they have external state (layer stack, projection,
3399         // etc.) but no internal state (i.e. a DisplayDevice).
3400         return;
3401     }
3402 
3403     compositionengine::DisplayCreationArgsBuilder builder;
3404     if (const auto& physical = state.physical) {
3405         builder.setId(physical->id);
3406     } else {
3407         builder.setId(acquireVirtualDisplay(resolution, pixelFormat));
3408     }
3409 
3410     builder.setPixels(resolution);
3411     builder.setIsSecure(state.isSecure);
3412     builder.setPowerAdvisor(mPowerAdvisor.get());
3413     builder.setName(state.displayName);
3414     auto compositionDisplay = getCompositionEngine().createDisplay(builder.build());
3415     compositionDisplay->setLayerCachingEnabled(mLayerCachingEnabled);
3416 
3417     sp<compositionengine::DisplaySurface> displaySurface;
3418     sp<IGraphicBufferProducer> producer;
3419     sp<IGraphicBufferProducer> bqProducer;
3420     sp<IGraphicBufferConsumer> bqConsumer;
3421     getFactory().createBufferQueue(&bqProducer, &bqConsumer, /*consumerIsSurfaceFlinger =*/false);
3422 
3423     if (state.isVirtual()) {
3424         const auto displayId = VirtualDisplayId::tryCast(compositionDisplay->getId());
3425         LOG_FATAL_IF(!displayId);
3426         auto surface = sp<VirtualDisplaySurface>::make(getHwComposer(), *displayId, state.surface,
3427                                                        bqProducer, bqConsumer, state.displayName);
3428         displaySurface = surface;
3429         producer = std::move(surface);
3430     } else {
3431         ALOGE_IF(state.surface != nullptr,
3432                  "adding a supported display, but rendering "
3433                  "surface is provided (%p), ignoring it",
3434                  state.surface.get());
3435         const auto displayId = PhysicalDisplayId::tryCast(compositionDisplay->getId());
3436         LOG_FATAL_IF(!displayId);
3437         displaySurface =
3438                 sp<FramebufferSurface>::make(getHwComposer(), *displayId, bqConsumer,
3439                                              state.physical->activeMode->getResolution(),
3440                                              ui::Size(maxGraphicsWidth, maxGraphicsHeight));
3441         producer = bqProducer;
3442     }
3443 
3444     LOG_FATAL_IF(!displaySurface);
3445     auto display = setupNewDisplayDeviceInternal(displayToken, std::move(compositionDisplay), state,
3446                                                  displaySurface, producer);
3447 
3448     if (mScheduler && !display->isVirtual()) {
3449         const auto displayId = display->getPhysicalId();
3450         {
3451             // TODO(b/241285876): Annotate `processDisplayAdded` instead.
3452             ftl::FakeGuard guard(kMainThreadContext);
3453 
3454             // For hotplug reconnect, renew the registration since display modes have been reloaded.
3455             mScheduler->registerDisplay(displayId, display->holdRefreshRateSelector());
3456         }
3457 
3458         dispatchDisplayHotplugEvent(displayId, true);
3459     }
3460 
3461     if (display->isVirtual()) {
3462         display->adjustRefreshRate(mScheduler->getPacesetterRefreshRate());
3463     }
3464 
3465     mDisplays.try_emplace(displayToken, std::move(display));
3466 }
3467 
processDisplayRemoved(const wp<IBinder> & displayToken)3468 void SurfaceFlinger::processDisplayRemoved(const wp<IBinder>& displayToken) {
3469     auto display = getDisplayDeviceLocked(displayToken);
3470     if (display) {
3471         display->disconnect();
3472 
3473         if (display->isVirtual()) {
3474             releaseVirtualDisplay(display->getVirtualId());
3475         } else {
3476             dispatchDisplayHotplugEvent(display->getPhysicalId(), false);
3477             mScheduler->unregisterDisplay(display->getPhysicalId());
3478         }
3479     }
3480 
3481     mDisplays.erase(displayToken);
3482 
3483     if (display && display->isVirtual()) {
3484         static_cast<void>(mScheduler->schedule([display = std::move(display)] {
3485             // Destroy the display without holding the mStateLock.
3486             // This is a temporary solution until we can manage transaction queues without
3487             // holding the mStateLock.
3488             // With blast, the IGBP that is passed to the VirtualDisplaySurface is owned by the
3489             // client. When the IGBP is disconnected, its buffer cache in SF will be cleared
3490             // via SurfaceComposerClient::doUncacheBufferTransaction. This call from the client
3491             // ends up running on the main thread causing a deadlock since setTransactionstate
3492             // will try to acquire the mStateLock. Instead we extend the lifetime of
3493             // DisplayDevice and destroy it in the main thread without holding the mStateLock.
3494             // The display will be disconnected and removed from the mDisplays list so it will
3495             // not be accessible.
3496         }));
3497     }
3498 }
3499 
processDisplayChanged(const wp<IBinder> & displayToken,const DisplayDeviceState & currentState,const DisplayDeviceState & drawingState)3500 void SurfaceFlinger::processDisplayChanged(const wp<IBinder>& displayToken,
3501                                            const DisplayDeviceState& currentState,
3502                                            const DisplayDeviceState& drawingState) {
3503     const sp<IBinder> currentBinder = IInterface::asBinder(currentState.surface);
3504     const sp<IBinder> drawingBinder = IInterface::asBinder(drawingState.surface);
3505 
3506     // Recreate the DisplayDevice if the surface or sequence ID changed.
3507     if (currentBinder != drawingBinder || currentState.sequenceId != drawingState.sequenceId) {
3508         getRenderEngine().cleanFramebufferCache();
3509 
3510         if (const auto display = getDisplayDeviceLocked(displayToken)) {
3511             display->disconnect();
3512             if (display->isVirtual()) {
3513                 releaseVirtualDisplay(display->getVirtualId());
3514             }
3515         }
3516 
3517         mDisplays.erase(displayToken);
3518 
3519         if (const auto& physical = currentState.physical) {
3520             getHwComposer().allocatePhysicalDisplay(physical->hwcDisplayId, physical->id);
3521         }
3522 
3523         processDisplayAdded(displayToken, currentState);
3524 
3525         if (currentState.physical) {
3526             const auto display = getDisplayDeviceLocked(displayToken);
3527             setPowerModeInternal(display, hal::PowerMode::ON);
3528 
3529             // TODO(b/175678251) Call a listener instead.
3530             if (currentState.physical->hwcDisplayId == getHwComposer().getPrimaryHwcDisplayId()) {
3531                 resetPhaseConfiguration(display->getActiveMode().fps);
3532             }
3533         }
3534         return;
3535     }
3536 
3537     if (const auto display = getDisplayDeviceLocked(displayToken)) {
3538         if (currentState.layerStack != drawingState.layerStack) {
3539             display->setLayerFilter(
3540                     makeLayerFilterForDisplay(display->getId(), currentState.layerStack));
3541         }
3542         if (currentState.flags != drawingState.flags) {
3543             display->setFlags(currentState.flags);
3544         }
3545         if ((currentState.orientation != drawingState.orientation) ||
3546             (currentState.layerStackSpaceRect != drawingState.layerStackSpaceRect) ||
3547             (currentState.orientedDisplaySpaceRect != drawingState.orientedDisplaySpaceRect)) {
3548             display->setProjection(currentState.orientation, currentState.layerStackSpaceRect,
3549                                    currentState.orientedDisplaySpaceRect);
3550             if (display->getId() == mActiveDisplayId) {
3551                 mActiveDisplayTransformHint = display->getTransformHint();
3552                 sActiveDisplayRotationFlags =
3553                         ui::Transform::toRotationFlags(display->getOrientation());
3554             }
3555         }
3556         if (currentState.width != drawingState.width ||
3557             currentState.height != drawingState.height) {
3558             display->setDisplaySize(currentState.width, currentState.height);
3559 
3560             if (display->getId() == mActiveDisplayId) {
3561                 onActiveDisplaySizeChanged(*display);
3562             }
3563         }
3564     }
3565 }
3566 
resetPhaseConfiguration(Fps refreshRate)3567 void SurfaceFlinger::resetPhaseConfiguration(Fps refreshRate) {
3568     // Cancel the pending refresh rate change, if any, before updating the phase configuration.
3569     mScheduler->vsyncModulator().cancelRefreshRateChange();
3570 
3571     mVsyncConfiguration->reset();
3572     updatePhaseConfiguration(refreshRate);
3573     mRefreshRateStats->setRefreshRate(refreshRate);
3574 }
3575 
processDisplayChangesLocked()3576 void SurfaceFlinger::processDisplayChangesLocked() {
3577     // here we take advantage of Vector's copy-on-write semantics to
3578     // improve performance by skipping the transaction entirely when
3579     // know that the lists are identical
3580     const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
3581     const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
3582     if (!curr.isIdenticalTo(draw)) {
3583         mVisibleRegionsDirty = true;
3584         mUpdateInputInfo = true;
3585 
3586         // find the displays that were removed
3587         // (ie: in drawing state but not in current state)
3588         // also handle displays that changed
3589         // (ie: displays that are in both lists)
3590         for (size_t i = 0; i < draw.size(); i++) {
3591             const wp<IBinder>& displayToken = draw.keyAt(i);
3592             const ssize_t j = curr.indexOfKey(displayToken);
3593             if (j < 0) {
3594                 // in drawing state but not in current state
3595                 processDisplayRemoved(displayToken);
3596             } else {
3597                 // this display is in both lists. see if something changed.
3598                 const DisplayDeviceState& currentState = curr[j];
3599                 const DisplayDeviceState& drawingState = draw[i];
3600                 processDisplayChanged(displayToken, currentState, drawingState);
3601             }
3602         }
3603 
3604         // find displays that were added
3605         // (ie: in current state but not in drawing state)
3606         for (size_t i = 0; i < curr.size(); i++) {
3607             const wp<IBinder>& displayToken = curr.keyAt(i);
3608             if (draw.indexOfKey(displayToken) < 0) {
3609                 processDisplayAdded(displayToken, curr[i]);
3610             }
3611         }
3612     }
3613 
3614     mDrawingState.displays = mCurrentState.displays;
3615 }
3616 
commitTransactionsLocked(uint32_t transactionFlags)3617 void SurfaceFlinger::commitTransactionsLocked(uint32_t transactionFlags) {
3618     // Commit display transactions.
3619     const bool displayTransactionNeeded = transactionFlags & eDisplayTransactionNeeded;
3620     mFrontEndDisplayInfosChanged = displayTransactionNeeded;
3621     if (displayTransactionNeeded && !mLayerLifecycleManagerEnabled) {
3622         processDisplayChangesLocked();
3623         mFrontEndDisplayInfos.clear();
3624         for (const auto& [_, display] : mDisplays) {
3625             mFrontEndDisplayInfos.try_emplace(display->getLayerStack(), display->getFrontEndInfo());
3626         }
3627     }
3628     mForceTransactionDisplayChange = displayTransactionNeeded;
3629 
3630     if (mSomeChildrenChanged) {
3631         mVisibleRegionsDirty = true;
3632         mSomeChildrenChanged = false;
3633         mUpdateInputInfo = true;
3634     }
3635 
3636     // Update transform hint.
3637     if (transactionFlags & (eTransformHintUpdateNeeded | eDisplayTransactionNeeded)) {
3638         // Layers and/or displays have changed, so update the transform hint for each layer.
3639         //
3640         // NOTE: we do this here, rather than when presenting the display so that
3641         // the hint is set before we acquire a buffer from the surface texture.
3642         //
3643         // NOTE: layer transactions have taken place already, so we use their
3644         // drawing state. However, SurfaceFlinger's own transaction has not
3645         // happened yet, so we must use the current state layer list
3646         // (soon to become the drawing state list).
3647         //
3648         sp<const DisplayDevice> hintDisplay;
3649         ui::LayerStack layerStack;
3650 
3651         mCurrentState.traverse([&](Layer* layer) REQUIRES(mStateLock) {
3652             // NOTE: we rely on the fact that layers are sorted by
3653             // layerStack first (so we don't have to traverse the list
3654             // of displays for every layer).
3655             if (const auto filter = layer->getOutputFilter(); layerStack != filter.layerStack) {
3656                 layerStack = filter.layerStack;
3657                 hintDisplay = nullptr;
3658 
3659                 // Find the display that includes the layer.
3660                 for (const auto& [token, display] : mDisplays) {
3661                     if (!display->getCompositionDisplay()->includesLayer(filter)) {
3662                         continue;
3663                     }
3664 
3665                     // Pick the primary display if another display mirrors the layer.
3666                     if (hintDisplay) {
3667                         hintDisplay = nullptr;
3668                         break;
3669                     }
3670 
3671                     hintDisplay = display;
3672                 }
3673             }
3674 
3675             if (!hintDisplay) {
3676                 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
3677                 // redraw after transform hint changes. See bug 8508397.
3678                 // could be null when this layer is using a layerStack
3679                 // that is not visible on any display. Also can occur at
3680                 // screen off/on times.
3681                 // U Update: Don't provide stale hints to the clients. For
3682                 // special cases where we want the app to draw its
3683                 // first frame before the display is available, we rely
3684                 // on WMS and DMS to provide the right information
3685                 // so the client can calculate the hint.
3686                 ALOGV("Skipping reporting transform hint update for %s", layer->getDebugName());
3687                 layer->skipReportingTransformHint();
3688             } else {
3689                 layer->updateTransformHint(hintDisplay->getTransformHint());
3690             }
3691         });
3692     }
3693 
3694     if (mLayersAdded) {
3695         mLayersAdded = false;
3696         // Layers have been added.
3697         mVisibleRegionsDirty = true;
3698         mUpdateInputInfo = true;
3699     }
3700 
3701     // some layers might have been removed, so
3702     // we need to update the regions they're exposing.
3703     if (mLayersRemoved) {
3704         mLayersRemoved = false;
3705         mVisibleRegionsDirty = true;
3706         mUpdateInputInfo = true;
3707         mDrawingState.traverseInZOrder([&](Layer* layer) {
3708             if (mLayersPendingRemoval.indexOf(sp<Layer>::fromExisting(layer)) >= 0) {
3709                 // this layer is not visible anymore
3710                 Region visibleReg;
3711                 visibleReg.set(layer->getScreenBounds());
3712                 invalidateLayerStack(layer->getOutputFilter(), visibleReg);
3713             }
3714         });
3715     }
3716 
3717     if (transactionFlags & eInputInfoUpdateNeeded) {
3718         mUpdateInputInfo = true;
3719     }
3720 
3721     doCommitTransactions();
3722 }
3723 
updateInputFlinger(VsyncId vsyncId,TimePoint frameTime)3724 void SurfaceFlinger::updateInputFlinger(VsyncId vsyncId, TimePoint frameTime) {
3725     if (!mInputFlinger || (!mUpdateInputInfo && mInputWindowCommands.empty())) {
3726         return;
3727     }
3728     ATRACE_CALL();
3729 
3730     std::vector<WindowInfo> windowInfos;
3731     std::vector<DisplayInfo> displayInfos;
3732     bool updateWindowInfo = false;
3733     if (mUpdateInputInfo) {
3734         mUpdateInputInfo = false;
3735         updateWindowInfo = true;
3736         buildWindowInfos(windowInfos, displayInfos);
3737     }
3738 
3739     std::unordered_set<int32_t> visibleWindowIds;
3740     for (WindowInfo& windowInfo : windowInfos) {
3741         if (!windowInfo.inputConfig.test(WindowInfo::InputConfig::NOT_VISIBLE)) {
3742             visibleWindowIds.insert(windowInfo.id);
3743         }
3744     }
3745     bool visibleWindowsChanged = false;
3746     if (visibleWindowIds != mVisibleWindowIds) {
3747         visibleWindowsChanged = true;
3748         mVisibleWindowIds = std::move(visibleWindowIds);
3749     }
3750 
3751     BackgroundExecutor::getInstance().sendCallbacks({[updateWindowInfo,
3752                                                       windowInfos = std::move(windowInfos),
3753                                                       displayInfos = std::move(displayInfos),
3754                                                       inputWindowCommands =
3755                                                               std::move(mInputWindowCommands),
3756                                                       inputFlinger = mInputFlinger, this,
3757                                                       visibleWindowsChanged, vsyncId, frameTime]() {
3758         ATRACE_NAME("BackgroundExecutor::updateInputFlinger");
3759         if (updateWindowInfo) {
3760             mWindowInfosListenerInvoker
3761                     ->windowInfosChanged(gui::WindowInfosUpdate{std::move(windowInfos),
3762                                                                 std::move(displayInfos),
3763                                                                 ftl::to_underlying(vsyncId),
3764                                                                 frameTime.ns()},
3765                                          std::move(
3766                                                  inputWindowCommands.windowInfosReportedListeners),
3767                                          /* forceImmediateCall= */ visibleWindowsChanged ||
3768                                                  !inputWindowCommands.focusRequests.empty());
3769         } else {
3770             // If there are listeners but no changes to input windows, call the listeners
3771             // immediately.
3772             for (const auto& listener : inputWindowCommands.windowInfosReportedListeners) {
3773                 if (IInterface::asBinder(listener)->isBinderAlive()) {
3774                     listener->onWindowInfosReported();
3775                 }
3776             }
3777         }
3778         for (const auto& focusRequest : inputWindowCommands.focusRequests) {
3779             inputFlinger->setFocusedWindow(focusRequest);
3780         }
3781     }});
3782 
3783     mInputWindowCommands.clear();
3784 }
3785 
persistDisplayBrightness(bool needsComposite)3786 void SurfaceFlinger::persistDisplayBrightness(bool needsComposite) {
3787     const bool supportsDisplayBrightnessCommand = getHwComposer().getComposer()->isSupported(
3788             Hwc2::Composer::OptionalFeature::DisplayBrightnessCommand);
3789     if (!supportsDisplayBrightnessCommand) {
3790         return;
3791     }
3792 
3793     for (const auto& [_, display] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
3794         if (const auto brightness = display->getStagedBrightness(); brightness) {
3795             if (!needsComposite) {
3796                 const status_t error =
3797                         getHwComposer()
3798                                 .setDisplayBrightness(display->getPhysicalId(), *brightness,
3799                                                       display->getCompositionDisplay()
3800                                                               ->getState()
3801                                                               .displayBrightnessNits,
3802                                                       Hwc2::Composer::DisplayBrightnessOptions{
3803                                                               .applyImmediately = true})
3804                                 .get();
3805 
3806                 ALOGE_IF(error != NO_ERROR,
3807                          "Error setting display brightness for display %s: %d (%s)",
3808                          to_string(display->getId()).c_str(), error, strerror(error));
3809             }
3810             display->persistBrightness(needsComposite);
3811         }
3812     }
3813 }
3814 
buildWindowInfos(std::vector<WindowInfo> & outWindowInfos,std::vector<DisplayInfo> & outDisplayInfos)3815 void SurfaceFlinger::buildWindowInfos(std::vector<WindowInfo>& outWindowInfos,
3816                                       std::vector<DisplayInfo>& outDisplayInfos) {
3817     static size_t sNumWindowInfos = 0;
3818     outWindowInfos.reserve(sNumWindowInfos);
3819     sNumWindowInfos = 0;
3820 
3821     if (mLayerLifecycleManagerEnabled) {
3822         mLayerSnapshotBuilder.forEachInputSnapshot(
3823                 [&outWindowInfos](const frontend::LayerSnapshot& snapshot) {
3824                     outWindowInfos.push_back(snapshot.inputInfo);
3825                 });
3826     } else {
3827         mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
3828             if (!layer->needsInputInfo()) return;
3829             const auto opt =
3830                     mFrontEndDisplayInfos.get(layer->getLayerStack())
3831                             .transform([](const frontend::DisplayInfo& info) {
3832                                 return Layer::InputDisplayArgs{&info.transform, info.isSecure};
3833                             });
3834 
3835             outWindowInfos.push_back(layer->fillInputInfo(opt.value_or(Layer::InputDisplayArgs{})));
3836         });
3837     }
3838 
3839     sNumWindowInfos = outWindowInfos.size();
3840 
3841     outDisplayInfos.reserve(mFrontEndDisplayInfos.size());
3842     for (const auto& [_, info] : mFrontEndDisplayInfos) {
3843         outDisplayInfos.push_back(info.info);
3844     }
3845 }
3846 
updateCursorAsync()3847 void SurfaceFlinger::updateCursorAsync() {
3848     compositionengine::CompositionRefreshArgs refreshArgs;
3849     for (const auto& [_, display] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
3850         if (HalDisplayId::tryCast(display->getId())) {
3851             refreshArgs.outputs.push_back(display->getCompositionDisplay());
3852         }
3853     }
3854 
3855     constexpr bool kCursorOnly = true;
3856     const auto layers = moveSnapshotsToCompositionArgs(refreshArgs, kCursorOnly);
3857     mCompositionEngine->updateCursorAsync(refreshArgs);
3858     moveSnapshotsFromCompositionArgs(refreshArgs, layers);
3859 }
3860 
requestHardwareVsync(PhysicalDisplayId displayId,bool enable)3861 void SurfaceFlinger::requestHardwareVsync(PhysicalDisplayId displayId, bool enable) {
3862     getHwComposer().setVsyncEnabled(displayId, enable ? hal::Vsync::ENABLE : hal::Vsync::DISABLE);
3863 }
3864 
requestDisplayModes(std::vector<display::DisplayModeRequest> modeRequests)3865 void SurfaceFlinger::requestDisplayModes(std::vector<display::DisplayModeRequest> modeRequests) {
3866     if (mBootStage != BootStage::FINISHED) {
3867         ALOGV("Currently in the boot stage, skipping display mode changes");
3868         return;
3869     }
3870 
3871     ATRACE_CALL();
3872 
3873     // If this is called from the main thread mStateLock must be locked before
3874     // Currently the only way to call this function from the main thread is from
3875     // Scheduler::chooseRefreshRateForContent
3876 
3877     ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
3878 
3879     for (auto& request : modeRequests) {
3880         const auto& modePtr = request.mode.modePtr;
3881 
3882         const auto displayId = modePtr->getPhysicalDisplayId();
3883         const auto display = getDisplayDeviceLocked(displayId);
3884 
3885         if (!display) continue;
3886 
3887         if (ftl::FakeGuard guard(kMainThreadContext);
3888             !shouldApplyRefreshRateSelectorPolicy(*display)) {
3889             ALOGV("%s(%s): Skipped applying policy", __func__, to_string(displayId).c_str());
3890             continue;
3891         }
3892 
3893         if (display->refreshRateSelector().isModeAllowed(request.mode)) {
3894             setDesiredActiveMode(std::move(request));
3895         } else {
3896             ALOGV("%s: Mode %d is disallowed for display %s", __func__, modePtr->getId().value(),
3897                   to_string(displayId).c_str());
3898         }
3899     }
3900 }
3901 
triggerOnFrameRateOverridesChanged()3902 void SurfaceFlinger::triggerOnFrameRateOverridesChanged() {
3903     PhysicalDisplayId displayId = [&]() {
3904         ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
3905         return getDefaultDisplayDeviceLocked()->getPhysicalId();
3906     }();
3907 
3908     mScheduler->onFrameRateOverridesChanged(mAppConnectionHandle, displayId);
3909 }
3910 
notifyCpuLoadUp()3911 void SurfaceFlinger::notifyCpuLoadUp() {
3912     mPowerAdvisor->notifyCpuLoadUp();
3913 }
3914 
initScheduler(const sp<const DisplayDevice> & display)3915 void SurfaceFlinger::initScheduler(const sp<const DisplayDevice>& display) {
3916     using namespace scheduler;
3917 
3918     LOG_ALWAYS_FATAL_IF(mScheduler);
3919 
3920     const auto activeMode = display->refreshRateSelector().getActiveMode();
3921     const Fps activeRefreshRate = activeMode.fps;
3922     mRefreshRateStats =
3923             std::make_unique<RefreshRateStats>(*mTimeStats, activeRefreshRate, hal::PowerMode::OFF);
3924 
3925     mVsyncConfiguration = getFactory().createVsyncConfiguration(activeRefreshRate);
3926 
3927     FeatureFlags features;
3928 
3929     if (sysprop::use_content_detection_for_refresh_rate(false)) {
3930         features |= Feature::kContentDetection;
3931         if (base::GetBoolProperty("debug.sf.enable_small_dirty_detection"s, false)) {
3932             features |= Feature::kSmallDirtyContentDetection;
3933         }
3934     }
3935     if (base::GetBoolProperty("debug.sf.show_predicted_vsync"s, false)) {
3936         features |= Feature::kTracePredictedVsync;
3937     }
3938     if (!base::GetBoolProperty("debug.sf.vsync_reactor_ignore_present_fences"s, false) &&
3939         !getHwComposer().hasCapability(Capability::PRESENT_FENCE_IS_NOT_RELIABLE)) {
3940         features |= Feature::kPresentFences;
3941     }
3942     if (display->refreshRateSelector().kernelIdleTimerController()) {
3943         features |= Feature::kKernelIdleTimer;
3944     }
3945     if (mBackpressureGpuComposition) {
3946         features |= Feature::kBackpressureGpuComposition;
3947     }
3948 
3949     auto modulatorPtr = sp<VsyncModulator>::make(mVsyncConfiguration->getCurrentConfigs());
3950 
3951     mScheduler = std::make_unique<Scheduler>(static_cast<ICompositor&>(*this),
3952                                              static_cast<ISchedulerCallback&>(*this), features,
3953                                              std::move(modulatorPtr));
3954     mScheduler->registerDisplay(display->getPhysicalId(), display->holdRefreshRateSelector());
3955     mScheduler->startTimers();
3956 
3957     const auto configs = mVsyncConfiguration->getCurrentConfigs();
3958 
3959     mAppConnectionHandle =
3960             mScheduler->createEventThread(Scheduler::Cycle::Render,
3961                                           mFrameTimeline->getTokenManager(),
3962                                           /* workDuration */ configs.late.appWorkDuration,
3963                                           /* readyDuration */ configs.late.sfWorkDuration);
3964     mSfConnectionHandle =
3965             mScheduler->createEventThread(Scheduler::Cycle::LastComposite,
3966                                           mFrameTimeline->getTokenManager(),
3967                                           /* workDuration */ activeRefreshRate.getPeriod(),
3968                                           /* readyDuration */ configs.late.sfWorkDuration);
3969 
3970     mScheduler->initVsync(mScheduler->getVsyncSchedule()->getDispatch(),
3971                           *mFrameTimeline->getTokenManager(), configs.late.sfWorkDuration);
3972 
3973     mRegionSamplingThread =
3974             sp<RegionSamplingThread>::make(*this,
3975                                            RegionSamplingThread::EnvironmentTimingTunables());
3976     mFpsReporter = sp<FpsReporter>::make(*mFrameTimeline, *this);
3977 }
3978 
updatePhaseConfiguration(Fps refreshRate)3979 void SurfaceFlinger::updatePhaseConfiguration(Fps refreshRate) {
3980     mVsyncConfiguration->setRefreshRateFps(refreshRate);
3981     mScheduler->setVsyncConfigSet(mVsyncConfiguration->getCurrentConfigs(),
3982                                   refreshRate.getPeriod());
3983 }
3984 
doCommitTransactions()3985 void SurfaceFlinger::doCommitTransactions() {
3986     ATRACE_CALL();
3987 
3988     if (!mLayersPendingRemoval.isEmpty()) {
3989         // Notify removed layers now that they can't be drawn from
3990         for (const auto& l : mLayersPendingRemoval) {
3991             // Ensure any buffers set to display on any children are released.
3992             if (l->isRemovedFromCurrentState()) {
3993                 l->latchAndReleaseBuffer();
3994             }
3995 
3996             // If a layer has a parent, we allow it to out-live it's handle
3997             // with the idea that the parent holds a reference and will eventually
3998             // be cleaned up. However no one cleans up the top-level so we do so
3999             // here.
4000             if (l->isAtRoot()) {
4001                 l->setIsAtRoot(false);
4002                 mCurrentState.layersSortedByZ.remove(l);
4003             }
4004 
4005             // If the layer has been removed and has no parent, then it will not be reachable
4006             // when traversing layers on screen. Add the layer to the offscreenLayers set to
4007             // ensure we can copy its current to drawing state.
4008             if (!l->getParent()) {
4009                 mOffscreenLayers.emplace(l.get());
4010             }
4011         }
4012         mLayersPendingRemoval.clear();
4013     }
4014 
4015     mDrawingState = mCurrentState;
4016     // clear the "changed" flags in current state
4017     mCurrentState.colorMatrixChanged = false;
4018 
4019     if (mVisibleRegionsDirty) {
4020         for (const auto& rootLayer : mDrawingState.layersSortedByZ) {
4021             rootLayer->commitChildList();
4022         }
4023     }
4024 
4025     commitOffscreenLayers();
4026     if (mLayerMirrorRoots.size() > 0) {
4027         std::deque<Layer*> pendingUpdates;
4028         pendingUpdates.insert(pendingUpdates.end(), mLayerMirrorRoots.begin(),
4029                               mLayerMirrorRoots.end());
4030         std::vector<Layer*> needsUpdating;
4031         for (Layer* cloneRoot : mLayerMirrorRoots) {
4032             pendingUpdates.pop_front();
4033             if (cloneRoot->isRemovedFromCurrentState()) {
4034                 continue;
4035             }
4036             if (cloneRoot->updateMirrorInfo(pendingUpdates)) {
4037             } else {
4038                 needsUpdating.push_back(cloneRoot);
4039             }
4040         }
4041         for (Layer* cloneRoot : needsUpdating) {
4042             cloneRoot->updateMirrorInfo({});
4043         }
4044     }
4045 }
4046 
commitOffscreenLayers()4047 void SurfaceFlinger::commitOffscreenLayers() {
4048     for (Layer* offscreenLayer : mOffscreenLayers) {
4049         offscreenLayer->traverse(LayerVector::StateSet::Drawing, [](Layer* layer) {
4050             if (layer->clearTransactionFlags(eTransactionNeeded)) {
4051                 layer->doTransaction(0);
4052                 layer->commitChildList();
4053             }
4054         });
4055     }
4056 }
4057 
invalidateLayerStack(const ui::LayerFilter & layerFilter,const Region & dirty)4058 void SurfaceFlinger::invalidateLayerStack(const ui::LayerFilter& layerFilter, const Region& dirty) {
4059     for (const auto& [token, displayDevice] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
4060         auto display = displayDevice->getCompositionDisplay();
4061         if (display->includesLayer(layerFilter)) {
4062             display->editState().dirtyRegion.orSelf(dirty);
4063         }
4064     }
4065 }
4066 
latchBuffers()4067 bool SurfaceFlinger::latchBuffers() {
4068     ATRACE_CALL();
4069 
4070     const nsecs_t latchTime = systemTime();
4071 
4072     bool visibleRegions = false;
4073     bool frameQueued = false;
4074     bool newDataLatched = false;
4075 
4076     // Store the set of layers that need updates. This set must not change as
4077     // buffers are being latched, as this could result in a deadlock.
4078     // Example: Two producers share the same command stream and:
4079     // 1.) Layer 0 is latched
4080     // 2.) Layer 0 gets a new frame
4081     // 2.) Layer 1 gets a new frame
4082     // 3.) Layer 1 is latched.
4083     // Display is now waiting on Layer 1's frame, which is behind layer 0's
4084     // second frame. But layer 0's second frame could be waiting on display.
4085     mDrawingState.traverse([&](Layer* layer) {
4086         if (layer->clearTransactionFlags(eTransactionNeeded) || mForceTransactionDisplayChange) {
4087             const uint32_t flags = layer->doTransaction(0);
4088             if (flags & Layer::eVisibleRegion) {
4089                 mVisibleRegionsDirty = true;
4090             }
4091         }
4092 
4093         if (layer->hasReadyFrame() || layer->willReleaseBufferOnLatch()) {
4094             frameQueued = true;
4095             mLayersWithQueuedFrames.emplace(sp<Layer>::fromExisting(layer));
4096         } else {
4097             layer->useEmptyDamage();
4098             if (!layer->hasBuffer()) {
4099                 // The last latch time is used to classify a missed frame as buffer stuffing
4100                 // instead of a missed frame. This is used to identify scenarios where we
4101                 // could not latch a buffer or apply a transaction due to backpressure.
4102                 // We only update the latch time for buffer less layers here, the latch time
4103                 // is updated for buffer layers when the buffer is latched.
4104                 layer->updateLastLatchTime(latchTime);
4105             }
4106         }
4107     });
4108     mForceTransactionDisplayChange = false;
4109 
4110     // The client can continue submitting buffers for offscreen layers, but they will not
4111     // be shown on screen. Therefore, we need to latch and release buffers of offscreen
4112     // layers to ensure dequeueBuffer doesn't block indefinitely.
4113     for (Layer* offscreenLayer : mOffscreenLayers) {
4114         offscreenLayer->traverse(LayerVector::StateSet::Drawing,
4115                                          [&](Layer* l) { l->latchAndReleaseBuffer(); });
4116     }
4117 
4118     if (!mLayersWithQueuedFrames.empty()) {
4119         // mStateLock is needed for latchBuffer as LayerRejecter::reject()
4120         // writes to Layer current state. See also b/119481871
4121         Mutex::Autolock lock(mStateLock);
4122 
4123         for (const auto& layer : mLayersWithQueuedFrames) {
4124             if (layer->willReleaseBufferOnLatch()) {
4125                 mLayersWithBuffersRemoved.emplace(layer);
4126             }
4127             if (layer->latchBuffer(visibleRegions, latchTime)) {
4128                 mLayersPendingRefresh.push_back(layer);
4129                 newDataLatched = true;
4130             }
4131             layer->useSurfaceDamage();
4132         }
4133     }
4134 
4135     mVisibleRegionsDirty |= visibleRegions;
4136 
4137     // If we will need to wake up at some time in the future to deal with a
4138     // queued frame that shouldn't be displayed during this vsync period, wake
4139     // up during the next vsync period to check again.
4140     if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
4141         scheduleCommit(FrameHint::kNone);
4142     }
4143 
4144     // enter boot animation on first buffer latch
4145     if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
4146         ALOGI("Enter boot animation");
4147         mBootStage = BootStage::BOOTANIMATION;
4148     }
4149 
4150     if (mLayerMirrorRoots.size() > 0) {
4151         mDrawingState.traverse([&](Layer* layer) { layer->updateCloneBufferInfo(); });
4152     }
4153 
4154     // Only continue with the refresh if there is actually new work to do
4155     return !mLayersWithQueuedFrames.empty() && newDataLatched;
4156 }
4157 
addClientLayer(LayerCreationArgs & args,const sp<IBinder> & handle,const sp<Layer> & layer,const wp<Layer> & parent,uint32_t * outTransformHint)4158 status_t SurfaceFlinger::addClientLayer(LayerCreationArgs& args, const sp<IBinder>& handle,
4159                                         const sp<Layer>& layer, const wp<Layer>& parent,
4160                                         uint32_t* outTransformHint) {
4161     if (mNumLayers >= MAX_LAYERS) {
4162         ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
4163               MAX_LAYERS);
4164         static_cast<void>(mScheduler->schedule([=] {
4165             ALOGE("Dumping layer keeping > 20 children alive:");
4166             bool leakingParentLayerFound = false;
4167             mDrawingState.traverse([&](Layer* layer) {
4168                 if (leakingParentLayerFound) {
4169                     return;
4170                 }
4171                 if (layer->getChildrenCount() > 20) {
4172                     leakingParentLayerFound = true;
4173                     sp<Layer> parent = sp<Layer>::fromExisting(layer);
4174                     while (parent) {
4175                         ALOGE("Parent Layer: %s%s", parent->getName().c_str(),
4176                               (parent->isHandleAlive() ? "handleAlive" : ""));
4177                         parent = parent->getParent();
4178                     }
4179                     // Sample up to 100 layers
4180                     ALOGE("Dumping random sampling of child layers total(%zu): ",
4181                           layer->getChildrenCount());
4182                     int sampleSize = (layer->getChildrenCount() / 100) + 1;
4183                     layer->traverseChildren([&](Layer* layer) {
4184                         if (rand() % sampleSize == 0) {
4185                             ALOGE("Child Layer: %s", layer->getName().c_str());
4186                         }
4187                     });
4188                 }
4189             });
4190 
4191             int numLayers = 0;
4192             mDrawingState.traverse([&](Layer* layer) { numLayers++; });
4193 
4194             ALOGE("Dumping random sampling of on-screen layers total(%u):", numLayers);
4195             mDrawingState.traverse([&](Layer* layer) {
4196                 // Aim to dump about 200 layers to avoid totally trashing
4197                 // logcat. On the other hand, if there really are 4096 layers
4198                 // something has gone totally wrong its probably the most
4199                 // useful information in logcat.
4200                 if (rand() % 20 == 13) {
4201                     ALOGE("Layer: %s%s", layer->getName().c_str(),
4202                           (layer->isHandleAlive() ? "handleAlive" : ""));
4203                     std::this_thread::sleep_for(std::chrono::milliseconds(5));
4204                 }
4205             });
4206             ALOGE("Dumping random sampling of off-screen layers total(%zu): ",
4207                   mOffscreenLayers.size());
4208             for (Layer* offscreenLayer : mOffscreenLayers) {
4209                 if (rand() % 20 == 13) {
4210                     ALOGE("Offscreen-layer: %s%s", offscreenLayer->getName().c_str(),
4211                           (offscreenLayer->isHandleAlive() ? "handleAlive" : ""));
4212                     std::this_thread::sleep_for(std::chrono::milliseconds(5));
4213                 }
4214             }
4215         }));
4216         return NO_MEMORY;
4217     }
4218 
4219     layer->updateTransformHint(mActiveDisplayTransformHint);
4220     if (outTransformHint) {
4221         *outTransformHint = mActiveDisplayTransformHint;
4222     }
4223     args.parentId = LayerHandle::getLayerId(args.parentHandle.promote());
4224     args.layerIdToMirror = LayerHandle::getLayerId(args.mirrorLayerHandle.promote());
4225     {
4226         std::scoped_lock<std::mutex> lock(mCreatedLayersLock);
4227         mCreatedLayers.emplace_back(layer, parent, args.addToRoot);
4228         mNewLayers.emplace_back(std::make_unique<frontend::RequestedLayerState>(args));
4229         args.mirrorLayerHandle.clear();
4230         args.parentHandle.clear();
4231         mNewLayerArgs.emplace_back(std::move(args));
4232     }
4233 
4234     setTransactionFlags(eTransactionNeeded);
4235     return NO_ERROR;
4236 }
4237 
getTransactionFlags() const4238 uint32_t SurfaceFlinger::getTransactionFlags() const {
4239     return mTransactionFlags;
4240 }
4241 
clearTransactionFlags(uint32_t mask)4242 uint32_t SurfaceFlinger::clearTransactionFlags(uint32_t mask) {
4243     uint32_t transactionFlags = mTransactionFlags.fetch_and(~mask);
4244     ATRACE_INT("mTransactionFlags", transactionFlags);
4245     return transactionFlags & mask;
4246 }
4247 
setTransactionFlags(uint32_t mask,TransactionSchedule schedule,const sp<IBinder> & applyToken,FrameHint frameHint)4248 void SurfaceFlinger::setTransactionFlags(uint32_t mask, TransactionSchedule schedule,
4249                                          const sp<IBinder>& applyToken, FrameHint frameHint) {
4250     mScheduler->modulateVsync({}, &VsyncModulator::setTransactionSchedule, schedule, applyToken);
4251     uint32_t transactionFlags = mTransactionFlags.fetch_or(mask);
4252     ATRACE_INT("mTransactionFlags", transactionFlags);
4253 
4254     if (const bool scheduled = transactionFlags & mask; !scheduled) {
4255         scheduleCommit(frameHint);
4256     } else if (frameHint == FrameHint::kActive) {
4257         // Even if the next frame is already scheduled, we should reset the idle timer
4258         // as a new activity just happened.
4259         mScheduler->resetIdleTimer();
4260     }
4261 }
4262 
transactionReadyTimelineCheck(const TransactionHandler::TransactionFlushState & flushState)4263 TransactionHandler::TransactionReadiness SurfaceFlinger::transactionReadyTimelineCheck(
4264         const TransactionHandler::TransactionFlushState& flushState) {
4265     const auto& transaction = *flushState.transaction;
4266 
4267     const TimePoint desiredPresentTime = TimePoint::fromNs(transaction.desiredPresentTime);
4268     const TimePoint expectedPresentTime = mScheduler->expectedPresentTimeForPacesetter();
4269 
4270     using TransactionReadiness = TransactionHandler::TransactionReadiness;
4271 
4272     // Do not present if the desiredPresentTime has not passed unless it is more than
4273     // one second in the future. We ignore timestamps more than 1 second in the future
4274     // for stability reasons.
4275     if (!transaction.isAutoTimestamp && desiredPresentTime >= expectedPresentTime &&
4276         desiredPresentTime < expectedPresentTime + 1s) {
4277         ATRACE_FORMAT("not current desiredPresentTime: %" PRId64 " expectedPresentTime: %" PRId64,
4278                       desiredPresentTime, expectedPresentTime);
4279         return TransactionReadiness::NotReady;
4280     }
4281 
4282     if (!mScheduler->isVsyncValid(expectedPresentTime, transaction.originUid)) {
4283         ATRACE_FORMAT("!isVsyncValid expectedPresentTime: %" PRId64 " uid: %d", expectedPresentTime,
4284                       transaction.originUid);
4285         return TransactionReadiness::NotReady;
4286     }
4287 
4288     // If the client didn't specify desiredPresentTime, use the vsyncId to determine the
4289     // expected present time of this transaction.
4290     if (transaction.isAutoTimestamp &&
4291         frameIsEarly(expectedPresentTime, VsyncId{transaction.frameTimelineInfo.vsyncId})) {
4292         ATRACE_FORMAT("frameIsEarly vsyncId: %" PRId64 " expectedPresentTime: %" PRId64,
4293                       transaction.frameTimelineInfo.vsyncId, expectedPresentTime);
4294         return TransactionReadiness::NotReady;
4295     }
4296 
4297     return TransactionReadiness::Ready;
4298 }
4299 
transactionReadyBufferCheck(const TransactionHandler::TransactionFlushState & flushState)4300 TransactionHandler::TransactionReadiness SurfaceFlinger::transactionReadyBufferCheck(
4301         const TransactionHandler::TransactionFlushState& flushState) {
4302     using TransactionReadiness = TransactionHandler::TransactionReadiness;
4303     auto ready = TransactionReadiness::Ready;
4304     flushState.transaction->traverseStatesWithBuffersWhileTrue([&](const layer_state_t& s,
4305                                                                    const std::shared_ptr<
4306                                                                            renderengine::
4307                                                                                    ExternalTexture>&
4308                                                                            externalTexture)
4309                                                                        -> bool {
4310         sp<Layer> layer = LayerHandle::getLayer(s.surface);
4311         const auto& transaction = *flushState.transaction;
4312         // check for barrier frames
4313         if (s.bufferData->hasBarrier) {
4314             // The current producerId is already a newer producer than the buffer that has a
4315             // barrier. This means the incoming buffer is older and we can release it here. We
4316             // don't wait on the barrier since we know that's stale information.
4317             if (layer->getDrawingState().barrierProducerId > s.bufferData->producerId) {
4318                 layer->callReleaseBufferCallback(s.bufferData->releaseBufferListener,
4319                                                  externalTexture->getBuffer(),
4320                                                  s.bufferData->frameNumber,
4321                                                  s.bufferData->acquireFence);
4322                 // Delete the entire state at this point and not just release the buffer because
4323                 // everything associated with the Layer in this Transaction is now out of date.
4324                 ATRACE_FORMAT("DeleteStaleBuffer %s barrierProducerId:%d > %d",
4325                               layer->getDebugName(), layer->getDrawingState().barrierProducerId,
4326                               s.bufferData->producerId);
4327                 return TraverseBuffersReturnValues::DELETE_AND_CONTINUE_TRAVERSAL;
4328             }
4329 
4330             if (layer->getDrawingState().barrierFrameNumber < s.bufferData->barrierFrameNumber) {
4331                 const bool willApplyBarrierFrame =
4332                         flushState.bufferLayersReadyToPresent.contains(s.surface.get()) &&
4333                         ((flushState.bufferLayersReadyToPresent.get(s.surface.get()) >=
4334                           s.bufferData->barrierFrameNumber));
4335                 if (!willApplyBarrierFrame) {
4336                     ATRACE_FORMAT("NotReadyBarrier %s barrierFrameNumber:%" PRId64 " > %" PRId64,
4337                                   layer->getDebugName(),
4338                                   layer->getDrawingState().barrierFrameNumber,
4339                                   s.bufferData->barrierFrameNumber);
4340                     ready = TransactionReadiness::NotReadyBarrier;
4341                     return TraverseBuffersReturnValues::STOP_TRAVERSAL;
4342                 }
4343             }
4344         }
4345 
4346         // If backpressure is enabled and we already have a buffer to commit, keep
4347         // the transaction in the queue.
4348         const bool hasPendingBuffer =
4349                 flushState.bufferLayersReadyToPresent.contains(s.surface.get());
4350         if (layer->backpressureEnabled() && hasPendingBuffer && transaction.isAutoTimestamp) {
4351             ATRACE_FORMAT("hasPendingBuffer %s", layer->getDebugName());
4352             ready = TransactionReadiness::NotReady;
4353             return TraverseBuffersReturnValues::STOP_TRAVERSAL;
4354         }
4355 
4356         // ignore the acquire fence if LatchUnsignaledConfig::Always is set.
4357         const bool checkAcquireFence = enableLatchUnsignaledConfig != LatchUnsignaledConfig::Always;
4358         const bool acquireFenceAvailable = s.bufferData &&
4359                 s.bufferData->flags.test(BufferData::BufferDataChange::fenceChanged) &&
4360                 s.bufferData->acquireFence;
4361         const bool fenceSignaled = !checkAcquireFence || !acquireFenceAvailable ||
4362                 s.bufferData->acquireFence->getStatus() != Fence::Status::Unsignaled;
4363         if (!fenceSignaled) {
4364             // check fence status
4365             const bool allowLatchUnsignaled =
4366                     shouldLatchUnsignaled(layer, s, transaction.states.size(),
4367                                           flushState.firstTransaction);
4368             if (allowLatchUnsignaled) {
4369                 ATRACE_FORMAT("fence unsignaled try allowLatchUnsignaled %s",
4370                               layer->getDebugName());
4371                 ready = TransactionReadiness::NotReadyUnsignaled;
4372             } else {
4373                 ready = TransactionReadiness::NotReady;
4374                 auto& listener = s.bufferData->releaseBufferListener;
4375                 if (listener &&
4376                     (flushState.queueProcessTime - transaction.postTime) >
4377                             std::chrono::nanoseconds(4s).count()) {
4378                     mTransactionHandler
4379                             .onTransactionQueueStalled(transaction.id,
4380                                                        {.pid = layer->getOwnerPid(),
4381                                                         .layerId = static_cast<uint32_t>(
4382                                                                 layer->getSequence()),
4383                                                         .layerName = layer->getDebugName(),
4384                                                         .bufferId = s.bufferData->getId(),
4385                                                         .frameNumber = s.bufferData->frameNumber});
4386                 }
4387                 ATRACE_FORMAT("fence unsignaled %s", layer->getDebugName());
4388                 return TraverseBuffersReturnValues::STOP_TRAVERSAL;
4389             }
4390         }
4391         return TraverseBuffersReturnValues::CONTINUE_TRAVERSAL;
4392     });
4393     return ready;
4394 }
4395 
addTransactionReadyFilters()4396 void SurfaceFlinger::addTransactionReadyFilters() {
4397     mTransactionHandler.addTransactionReadyFilter(
4398             std::bind(&SurfaceFlinger::transactionReadyTimelineCheck, this, std::placeholders::_1));
4399     mTransactionHandler.addTransactionReadyFilter(
4400             std::bind(&SurfaceFlinger::transactionReadyBufferCheck, this, std::placeholders::_1));
4401 }
4402 
4403 // For tests only
flushTransactionQueues(VsyncId vsyncId)4404 bool SurfaceFlinger::flushTransactionQueues(VsyncId vsyncId) {
4405     std::vector<TransactionState> transactions = mTransactionHandler.flushTransactions();
4406     return applyTransactions(transactions, vsyncId);
4407 }
4408 
applyTransactions(std::vector<TransactionState> & transactions,VsyncId vsyncId)4409 bool SurfaceFlinger::applyTransactions(std::vector<TransactionState>& transactions,
4410                                        VsyncId vsyncId) {
4411     Mutex::Autolock lock(mStateLock);
4412     return applyTransactionsLocked(transactions, vsyncId);
4413 }
4414 
applyTransactionsLocked(std::vector<TransactionState> & transactions,VsyncId vsyncId)4415 bool SurfaceFlinger::applyTransactionsLocked(std::vector<TransactionState>& transactions,
4416                                              VsyncId vsyncId) {
4417     bool needsTraversal = false;
4418     // Now apply all transactions.
4419     for (auto& transaction : transactions) {
4420         needsTraversal |=
4421                 applyTransactionState(transaction.frameTimelineInfo, transaction.states,
4422                                       transaction.displays, transaction.flags,
4423                                       transaction.inputWindowCommands,
4424                                       transaction.desiredPresentTime, transaction.isAutoTimestamp,
4425                                       std::move(transaction.uncacheBufferIds), transaction.postTime,
4426                                       transaction.hasListenerCallbacks,
4427                                       transaction.listenerCallbacks, transaction.originPid,
4428                                       transaction.originUid, transaction.id);
4429     }
4430     return needsTraversal;
4431 }
4432 
transactionFlushNeeded()4433 bool SurfaceFlinger::transactionFlushNeeded() {
4434     return mTransactionHandler.hasPendingTransactions();
4435 }
4436 
frameIsEarly(TimePoint expectedPresentTime,VsyncId vsyncId) const4437 bool SurfaceFlinger::frameIsEarly(TimePoint expectedPresentTime, VsyncId vsyncId) const {
4438     const auto prediction =
4439             mFrameTimeline->getTokenManager()->getPredictionsForToken(ftl::to_underlying(vsyncId));
4440     if (!prediction) {
4441         return false;
4442     }
4443 
4444     const auto predictedPresentTime = TimePoint::fromNs(prediction->presentTime);
4445 
4446     if (std::chrono::abs(predictedPresentTime - expectedPresentTime) >=
4447         scheduler::VsyncConfig::kEarlyLatchMaxThreshold) {
4448         return false;
4449     }
4450 
4451     const Duration earlyLatchVsyncThreshold = mScheduler->getVsyncSchedule()->period() / 2;
4452 
4453     return predictedPresentTime >= expectedPresentTime &&
4454             predictedPresentTime - expectedPresentTime >= earlyLatchVsyncThreshold;
4455 }
4456 
shouldLatchUnsignaled(const sp<Layer> & layer,const layer_state_t & state,size_t numStates,bool firstTransaction) const4457 bool SurfaceFlinger::shouldLatchUnsignaled(const sp<Layer>& layer, const layer_state_t& state,
4458                                            size_t numStates, bool firstTransaction) const {
4459     if (enableLatchUnsignaledConfig == LatchUnsignaledConfig::Disabled) {
4460         ATRACE_FORMAT_INSTANT("%s: false (LatchUnsignaledConfig::Disabled)", __func__);
4461         return false;
4462     }
4463 
4464     if (enableLatchUnsignaledConfig == LatchUnsignaledConfig::Always) {
4465         ATRACE_FORMAT_INSTANT("%s: true (LatchUnsignaledConfig::Always)", __func__);
4466         return true;
4467     }
4468 
4469     // We only want to latch unsignaled when a single layer is updated in this
4470     // transaction (i.e. not a blast sync transaction).
4471     if (numStates != 1) {
4472         ATRACE_FORMAT_INSTANT("%s: false (numStates=%zu)", __func__, numStates);
4473         return false;
4474     }
4475 
4476     if (enableLatchUnsignaledConfig == LatchUnsignaledConfig::AutoSingleLayer) {
4477         if (!firstTransaction) {
4478             ATRACE_FORMAT_INSTANT("%s: false (LatchUnsignaledConfig::AutoSingleLayer; not first "
4479                                   "transaction)",
4480                                   __func__);
4481             return false;
4482         }
4483 
4484         // We don't want to latch unsignaled if are in early / client composition
4485         // as it leads to jank due to RenderEngine waiting for unsignaled buffer
4486         // or window animations being slow.
4487         if (mScheduler->vsyncModulator().isVsyncConfigEarly()) {
4488             ATRACE_FORMAT_INSTANT("%s: false (LatchUnsignaledConfig::AutoSingleLayer; "
4489                                   "isVsyncConfigEarly)",
4490                                   __func__);
4491             return false;
4492         }
4493     }
4494 
4495     return layer->isSimpleBufferUpdate(state);
4496 }
4497 
setTransactionState(const FrameTimelineInfo & frameTimelineInfo,Vector<ComposerState> & states,const Vector<DisplayState> & displays,uint32_t flags,const sp<IBinder> & applyToken,InputWindowCommands inputWindowCommands,int64_t desiredPresentTime,bool isAutoTimestamp,const std::vector<client_cache_t> & uncacheBuffers,bool hasListenerCallbacks,const std::vector<ListenerCallbacks> & listenerCallbacks,uint64_t transactionId,const std::vector<uint64_t> & mergedTransactionIds)4498 status_t SurfaceFlinger::setTransactionState(
4499         const FrameTimelineInfo& frameTimelineInfo, Vector<ComposerState>& states,
4500         const Vector<DisplayState>& displays, uint32_t flags, const sp<IBinder>& applyToken,
4501         InputWindowCommands inputWindowCommands, int64_t desiredPresentTime, bool isAutoTimestamp,
4502         const std::vector<client_cache_t>& uncacheBuffers, bool hasListenerCallbacks,
4503         const std::vector<ListenerCallbacks>& listenerCallbacks, uint64_t transactionId,
4504         const std::vector<uint64_t>& mergedTransactionIds) {
4505     ATRACE_CALL();
4506 
4507     IPCThreadState* ipc = IPCThreadState::self();
4508     const int originPid = ipc->getCallingPid();
4509     const int originUid = ipc->getCallingUid();
4510     uint32_t permissions = LayerStatePermissions::getTransactionPermissions(originPid, originUid);
4511     for (auto composerState : states) {
4512         composerState.state.sanitize(permissions);
4513     }
4514 
4515     for (DisplayState display : displays) {
4516         display.sanitize(permissions);
4517     }
4518 
4519     if (!inputWindowCommands.empty() &&
4520         (permissions & layer_state_t::Permission::ACCESS_SURFACE_FLINGER) == 0) {
4521         ALOGE("Only privileged callers are allowed to send input commands.");
4522         inputWindowCommands.clear();
4523     }
4524 
4525     if (flags & (eEarlyWakeupStart | eEarlyWakeupEnd)) {
4526         const bool hasPermission =
4527                 (permissions & layer_state_t::Permission::ACCESS_SURFACE_FLINGER) ||
4528                 callingThreadHasPermission(sWakeupSurfaceFlinger);
4529         if (!hasPermission) {
4530             ALOGE("Caller needs permission android.permission.WAKEUP_SURFACE_FLINGER to use "
4531                   "eEarlyWakeup[Start|End] flags");
4532             flags &= ~(eEarlyWakeupStart | eEarlyWakeupEnd);
4533         }
4534     }
4535 
4536     const int64_t postTime = systemTime();
4537 
4538     std::vector<uint64_t> uncacheBufferIds;
4539     uncacheBufferIds.reserve(uncacheBuffers.size());
4540     for (const auto& uncacheBuffer : uncacheBuffers) {
4541         sp<GraphicBuffer> buffer = ClientCache::getInstance().erase(uncacheBuffer);
4542         if (buffer != nullptr) {
4543             uncacheBufferIds.push_back(buffer->getId());
4544         }
4545     }
4546 
4547     std::vector<ResolvedComposerState> resolvedStates;
4548     resolvedStates.reserve(states.size());
4549     for (auto& state : states) {
4550         resolvedStates.emplace_back(std::move(state));
4551         auto& resolvedState = resolvedStates.back();
4552         if (resolvedState.state.hasBufferChanges() && resolvedState.state.hasValidBuffer() &&
4553             resolvedState.state.surface) {
4554             sp<Layer> layer = LayerHandle::getLayer(resolvedState.state.surface);
4555             std::string layerName = (layer) ?
4556                     layer->getDebugName() : std::to_string(resolvedState.state.layerId);
4557             resolvedState.externalTexture =
4558                     getExternalTextureFromBufferData(*resolvedState.state.bufferData,
4559                                                      layerName.c_str(), transactionId);
4560             if (resolvedState.externalTexture) {
4561                 resolvedState.state.bufferData->buffer = resolvedState.externalTexture->getBuffer();
4562             }
4563             mBufferCountTracker.increment(resolvedState.state.surface->localBinder());
4564         }
4565         resolvedState.layerId = LayerHandle::getLayerId(resolvedState.state.surface);
4566         if (resolvedState.state.what & layer_state_t::eReparent) {
4567             resolvedState.parentId =
4568                     getLayerIdFromSurfaceControl(resolvedState.state.parentSurfaceControlForChild);
4569         }
4570         if (resolvedState.state.what & layer_state_t::eRelativeLayerChanged) {
4571             resolvedState.relativeParentId =
4572                     getLayerIdFromSurfaceControl(resolvedState.state.relativeLayerSurfaceControl);
4573         }
4574         if (resolvedState.state.what & layer_state_t::eInputInfoChanged) {
4575             wp<IBinder>& touchableRegionCropHandle =
4576                     resolvedState.state.windowInfoHandle->editInfo()->touchableRegionCropHandle;
4577             resolvedState.touchCropId =
4578                     LayerHandle::getLayerId(touchableRegionCropHandle.promote());
4579         }
4580     }
4581 
4582     TransactionState state{frameTimelineInfo,
4583                            resolvedStates,
4584                            displays,
4585                            flags,
4586                            applyToken,
4587                            std::move(inputWindowCommands),
4588                            desiredPresentTime,
4589                            isAutoTimestamp,
4590                            std::move(uncacheBufferIds),
4591                            postTime,
4592                            hasListenerCallbacks,
4593                            listenerCallbacks,
4594                            originPid,
4595                            originUid,
4596                            transactionId,
4597                            mergedTransactionIds};
4598 
4599     if (mTransactionTracing) {
4600         mTransactionTracing->addQueuedTransaction(state);
4601     }
4602 
4603     const auto schedule = [](uint32_t flags) {
4604         if (flags & eEarlyWakeupEnd) return TransactionSchedule::EarlyEnd;
4605         if (flags & eEarlyWakeupStart) return TransactionSchedule::EarlyStart;
4606         return TransactionSchedule::Late;
4607     }(state.flags);
4608 
4609     const auto frameHint = state.isFrameActive() ? FrameHint::kActive : FrameHint::kNone;
4610     mTransactionHandler.queueTransaction(std::move(state));
4611     setTransactionFlags(eTransactionFlushNeeded, schedule, applyToken, frameHint);
4612     return NO_ERROR;
4613 }
4614 
applyTransactionState(const FrameTimelineInfo & frameTimelineInfo,std::vector<ResolvedComposerState> & states,Vector<DisplayState> & displays,uint32_t flags,const InputWindowCommands & inputWindowCommands,const int64_t desiredPresentTime,bool isAutoTimestamp,const std::vector<uint64_t> & uncacheBufferIds,const int64_t postTime,bool hasListenerCallbacks,const std::vector<ListenerCallbacks> & listenerCallbacks,int originPid,int originUid,uint64_t transactionId)4615 bool SurfaceFlinger::applyTransactionState(const FrameTimelineInfo& frameTimelineInfo,
4616                                            std::vector<ResolvedComposerState>& states,
4617                                            Vector<DisplayState>& displays, uint32_t flags,
4618                                            const InputWindowCommands& inputWindowCommands,
4619                                            const int64_t desiredPresentTime, bool isAutoTimestamp,
4620                                            const std::vector<uint64_t>& uncacheBufferIds,
4621                                            const int64_t postTime, bool hasListenerCallbacks,
4622                                            const std::vector<ListenerCallbacks>& listenerCallbacks,
4623                                            int originPid, int originUid, uint64_t transactionId) {
4624     uint32_t transactionFlags = 0;
4625     if (!mLayerLifecycleManagerEnabled) {
4626         for (DisplayState& display : displays) {
4627             transactionFlags |= setDisplayStateLocked(display);
4628         }
4629     }
4630 
4631     // start and end registration for listeners w/ no surface so they can get their callback.  Note
4632     // that listeners with SurfaceControls will start registration during setClientStateLocked
4633     // below.
4634     for (const auto& listener : listenerCallbacks) {
4635         mTransactionCallbackInvoker.addEmptyTransaction(listener);
4636     }
4637 
4638     uint32_t clientStateFlags = 0;
4639     for (auto& resolvedState : states) {
4640         if (mLegacyFrontEndEnabled) {
4641             clientStateFlags |=
4642                     setClientStateLocked(frameTimelineInfo, resolvedState, desiredPresentTime,
4643                                          isAutoTimestamp, postTime, transactionId);
4644 
4645         } else /*mLayerLifecycleManagerEnabled*/ {
4646             clientStateFlags |= updateLayerCallbacksAndStats(frameTimelineInfo, resolvedState,
4647                                                              desiredPresentTime, isAutoTimestamp,
4648                                                              postTime, transactionId);
4649         }
4650         if ((flags & eAnimation) && resolvedState.state.surface) {
4651             if (const auto layer = LayerHandle::getLayer(resolvedState.state.surface)) {
4652                 const auto layerProps = scheduler::LayerProps{
4653                         .visible = layer->isVisible(),
4654                         .bounds = layer->getBounds(),
4655                         .transform = layer->getTransform(),
4656                         .setFrameRateVote = layer->getFrameRateForLayerTree(),
4657                         .frameRateSelectionPriority = layer->getFrameRateSelectionPriority(),
4658                 };
4659                 layer->recordLayerHistoryAnimationTx(layerProps);
4660             }
4661         }
4662     }
4663 
4664     transactionFlags |= clientStateFlags;
4665     transactionFlags |= addInputWindowCommands(inputWindowCommands);
4666 
4667     for (uint64_t uncacheBufferId : uncacheBufferIds) {
4668         mBufferIdsToUncache.push_back(uncacheBufferId);
4669     }
4670 
4671     // If a synchronous transaction is explicitly requested without any changes, force a transaction
4672     // anyway. This can be used as a flush mechanism for previous async transactions.
4673     // Empty animation transaction can be used to simulate back-pressure, so also force a
4674     // transaction for empty animation transactions.
4675     if (transactionFlags == 0 && (flags & eAnimation)) {
4676         transactionFlags = eTransactionNeeded;
4677     }
4678 
4679     bool needsTraversal = false;
4680     if (transactionFlags) {
4681         // We are on the main thread, we are about to perform a traversal. Clear the traversal bit
4682         // so we don't have to wake up again next frame to perform an unnecessary traversal.
4683         if (transactionFlags & eTraversalNeeded) {
4684             transactionFlags = transactionFlags & (~eTraversalNeeded);
4685             needsTraversal = true;
4686         }
4687         if (transactionFlags) {
4688             setTransactionFlags(transactionFlags);
4689         }
4690     }
4691 
4692     return needsTraversal;
4693 }
4694 
applyAndCommitDisplayTransactionStates(std::vector<TransactionState> & transactions)4695 bool SurfaceFlinger::applyAndCommitDisplayTransactionStates(
4696         std::vector<TransactionState>& transactions) {
4697     Mutex::Autolock lock(mStateLock);
4698     bool needsTraversal = false;
4699     uint32_t transactionFlags = 0;
4700     for (auto& transaction : transactions) {
4701         for (DisplayState& display : transaction.displays) {
4702             transactionFlags |= setDisplayStateLocked(display);
4703         }
4704     }
4705 
4706     if (transactionFlags) {
4707         // We are on the main thread, we are about to perform a traversal. Clear the traversal bit
4708         // so we don't have to wake up again next frame to perform an unnecessary traversal.
4709         if (transactionFlags & eTraversalNeeded) {
4710             transactionFlags = transactionFlags & (~eTraversalNeeded);
4711             needsTraversal = true;
4712         }
4713         if (transactionFlags) {
4714             setTransactionFlags(transactionFlags);
4715         }
4716     }
4717 
4718     mFrontEndDisplayInfosChanged = mTransactionFlags & eDisplayTransactionNeeded;
4719     if (mFrontEndDisplayInfosChanged && !mLegacyFrontEndEnabled) {
4720         processDisplayChangesLocked();
4721         mFrontEndDisplayInfos.clear();
4722         for (const auto& [_, display] : mDisplays) {
4723             mFrontEndDisplayInfos.try_emplace(display->getLayerStack(), display->getFrontEndInfo());
4724         }
4725         needsTraversal = true;
4726     }
4727 
4728     return needsTraversal;
4729 }
4730 
setDisplayStateLocked(const DisplayState & s)4731 uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
4732     const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
4733     if (index < 0) return 0;
4734 
4735     uint32_t flags = 0;
4736     DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
4737 
4738     const uint32_t what = s.what;
4739     if (what & DisplayState::eSurfaceChanged) {
4740         if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
4741             state.surface = s.surface;
4742             flags |= eDisplayTransactionNeeded;
4743         }
4744     }
4745     if (what & DisplayState::eLayerStackChanged) {
4746         if (state.layerStack != s.layerStack) {
4747             state.layerStack = s.layerStack;
4748             flags |= eDisplayTransactionNeeded;
4749         }
4750     }
4751     if (what & DisplayState::eFlagsChanged) {
4752         if (state.flags != s.flags) {
4753             state.flags = s.flags;
4754             flags |= eDisplayTransactionNeeded;
4755         }
4756     }
4757     if (what & DisplayState::eDisplayProjectionChanged) {
4758         if (state.orientation != s.orientation) {
4759             state.orientation = s.orientation;
4760             flags |= eDisplayTransactionNeeded;
4761         }
4762         if (state.orientedDisplaySpaceRect != s.orientedDisplaySpaceRect) {
4763             state.orientedDisplaySpaceRect = s.orientedDisplaySpaceRect;
4764             flags |= eDisplayTransactionNeeded;
4765         }
4766         if (state.layerStackSpaceRect != s.layerStackSpaceRect) {
4767             state.layerStackSpaceRect = s.layerStackSpaceRect;
4768             flags |= eDisplayTransactionNeeded;
4769         }
4770     }
4771     if (what & DisplayState::eDisplaySizeChanged) {
4772         if (state.width != s.width) {
4773             state.width = s.width;
4774             flags |= eDisplayTransactionNeeded;
4775         }
4776         if (state.height != s.height) {
4777             state.height = s.height;
4778             flags |= eDisplayTransactionNeeded;
4779         }
4780     }
4781 
4782     return flags;
4783 }
4784 
callingThreadHasUnscopedSurfaceFlingerAccess(bool usePermissionCache)4785 bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess(bool usePermissionCache) {
4786     IPCThreadState* ipc = IPCThreadState::self();
4787     const int pid = ipc->getCallingPid();
4788     const int uid = ipc->getCallingUid();
4789     if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
4790         (usePermissionCache ? !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)
4791                             : !checkPermission(sAccessSurfaceFlinger, pid, uid))) {
4792         return false;
4793     }
4794     return true;
4795 }
4796 
setClientStateLocked(const FrameTimelineInfo & frameTimelineInfo,ResolvedComposerState & composerState,int64_t desiredPresentTime,bool isAutoTimestamp,int64_t postTime,uint64_t transactionId)4797 uint32_t SurfaceFlinger::setClientStateLocked(const FrameTimelineInfo& frameTimelineInfo,
4798                                               ResolvedComposerState& composerState,
4799                                               int64_t desiredPresentTime, bool isAutoTimestamp,
4800                                               int64_t postTime, uint64_t transactionId) {
4801     layer_state_t& s = composerState.state;
4802 
4803     std::vector<ListenerCallbacks> filteredListeners;
4804     for (auto& listener : s.listeners) {
4805         // Starts a registration but separates the callback ids according to callback type. This
4806         // allows the callback invoker to send on latch callbacks earlier.
4807         // note that startRegistration will not re-register if the listener has
4808         // already be registered for a prior surface control
4809 
4810         ListenerCallbacks onCommitCallbacks = listener.filter(CallbackId::Type::ON_COMMIT);
4811         if (!onCommitCallbacks.callbackIds.empty()) {
4812             filteredListeners.push_back(onCommitCallbacks);
4813         }
4814 
4815         ListenerCallbacks onCompleteCallbacks = listener.filter(CallbackId::Type::ON_COMPLETE);
4816         if (!onCompleteCallbacks.callbackIds.empty()) {
4817             filteredListeners.push_back(onCompleteCallbacks);
4818         }
4819     }
4820 
4821     const uint64_t what = s.what;
4822     uint32_t flags = 0;
4823     sp<Layer> layer = nullptr;
4824     if (s.surface) {
4825         layer = LayerHandle::getLayer(s.surface);
4826     } else {
4827         // The client may provide us a null handle. Treat it as if the layer was removed.
4828         ALOGW("Attempt to set client state with a null layer handle");
4829     }
4830     if (layer == nullptr) {
4831         for (auto& [listener, callbackIds] : s.listeners) {
4832             mTransactionCallbackInvoker.addCallbackHandle(sp<CallbackHandle>::make(listener,
4833                                                                                    callbackIds,
4834                                                                                    s.surface),
4835                                                           std::vector<JankData>());
4836         }
4837         return 0;
4838     }
4839     MUTEX_ALIAS(mStateLock, layer->mFlinger->mStateLock);
4840 
4841     ui::LayerStack oldLayerStack = layer->getLayerStack(LayerVector::StateSet::Current);
4842 
4843     // Only set by BLAST adapter layers
4844     if (what & layer_state_t::eProducerDisconnect) {
4845         layer->onDisconnect();
4846     }
4847 
4848     if (what & layer_state_t::ePositionChanged) {
4849         if (layer->setPosition(s.x, s.y)) {
4850             flags |= eTraversalNeeded;
4851         }
4852     }
4853     if (what & layer_state_t::eLayerChanged) {
4854         // NOTE: index needs to be calculated before we update the state
4855         const auto& p = layer->getParent();
4856         if (p == nullptr) {
4857             ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
4858             if (layer->setLayer(s.z) && idx >= 0) {
4859                 mCurrentState.layersSortedByZ.removeAt(idx);
4860                 mCurrentState.layersSortedByZ.add(layer);
4861                 // we need traversal (state changed)
4862                 // AND transaction (list changed)
4863                 flags |= eTransactionNeeded|eTraversalNeeded;
4864             }
4865         } else {
4866             if (p->setChildLayer(layer, s.z)) {
4867                 flags |= eTransactionNeeded|eTraversalNeeded;
4868             }
4869         }
4870     }
4871     if (what & layer_state_t::eRelativeLayerChanged) {
4872         // NOTE: index needs to be calculated before we update the state
4873         const auto& p = layer->getParent();
4874         const auto& relativeHandle = s.relativeLayerSurfaceControl ?
4875                 s.relativeLayerSurfaceControl->getHandle() : nullptr;
4876         if (p == nullptr) {
4877             ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
4878             if (layer->setRelativeLayer(relativeHandle, s.z) &&
4879                 idx >= 0) {
4880                 mCurrentState.layersSortedByZ.removeAt(idx);
4881                 mCurrentState.layersSortedByZ.add(layer);
4882                 // we need traversal (state changed)
4883                 // AND transaction (list changed)
4884                 flags |= eTransactionNeeded|eTraversalNeeded;
4885             }
4886         } else {
4887             if (p->setChildRelativeLayer(layer, relativeHandle, s.z)) {
4888                 flags |= eTransactionNeeded|eTraversalNeeded;
4889             }
4890         }
4891     }
4892     if (what & layer_state_t::eAlphaChanged) {
4893         if (layer->setAlpha(s.color.a)) flags |= eTraversalNeeded;
4894     }
4895     if (what & layer_state_t::eColorChanged) {
4896         if (layer->setColor(s.color.rgb)) flags |= eTraversalNeeded;
4897     }
4898     if (what & layer_state_t::eColorTransformChanged) {
4899         if (layer->setColorTransform(s.colorTransform)) {
4900             flags |= eTraversalNeeded;
4901         }
4902     }
4903     if (what & layer_state_t::eBackgroundColorChanged) {
4904         if (layer->setBackgroundColor(s.bgColor.rgb, s.bgColor.a, s.bgColorDataspace)) {
4905             flags |= eTraversalNeeded;
4906         }
4907     }
4908     if (what & layer_state_t::eMatrixChanged) {
4909         if (layer->setMatrix(s.matrix)) flags |= eTraversalNeeded;
4910     }
4911     if (what & layer_state_t::eTransparentRegionChanged) {
4912         if (layer->setTransparentRegionHint(s.transparentRegion))
4913             flags |= eTraversalNeeded;
4914     }
4915     if (what & layer_state_t::eFlagsChanged) {
4916         if (layer->setFlags(s.flags, s.mask)) flags |= eTraversalNeeded;
4917     }
4918     if (what & layer_state_t::eCornerRadiusChanged) {
4919         if (layer->setCornerRadius(s.cornerRadius))
4920             flags |= eTraversalNeeded;
4921     }
4922     if (what & layer_state_t::eBackgroundBlurRadiusChanged && mSupportsBlur) {
4923         if (layer->setBackgroundBlurRadius(s.backgroundBlurRadius)) flags |= eTraversalNeeded;
4924     }
4925     if (what & layer_state_t::eBlurRegionsChanged) {
4926         if (layer->setBlurRegions(s.blurRegions)) flags |= eTraversalNeeded;
4927     }
4928     if (what & layer_state_t::eRenderBorderChanged) {
4929         if (layer->enableBorder(s.borderEnabled, s.borderWidth, s.borderColor)) {
4930             flags |= eTraversalNeeded;
4931         }
4932     }
4933     if (what & layer_state_t::eLayerStackChanged) {
4934         ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
4935         // We only allow setting layer stacks for top level layers,
4936         // everything else inherits layer stack from its parent.
4937         if (layer->hasParent()) {
4938             ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
4939                   layer->getDebugName());
4940         } else if (idx < 0) {
4941             ALOGE("Attempt to set layer stack on layer without parent (%s) that "
4942                   "that also does not appear in the top level layer list. Something"
4943                   " has gone wrong.",
4944                   layer->getDebugName());
4945         } else if (layer->setLayerStack(s.layerStack)) {
4946             mCurrentState.layersSortedByZ.removeAt(idx);
4947             mCurrentState.layersSortedByZ.add(layer);
4948             // we need traversal (state changed)
4949             // AND transaction (list changed)
4950             flags |= eTransactionNeeded | eTraversalNeeded | eTransformHintUpdateNeeded;
4951         }
4952     }
4953     if (what & layer_state_t::eBufferTransformChanged) {
4954         if (layer->setTransform(s.bufferTransform)) flags |= eTraversalNeeded;
4955     }
4956     if (what & layer_state_t::eTransformToDisplayInverseChanged) {
4957         if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
4958             flags |= eTraversalNeeded;
4959     }
4960     if (what & layer_state_t::eCropChanged) {
4961         if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
4962     }
4963     if (what & layer_state_t::eDataspaceChanged) {
4964         if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
4965     }
4966     if (what & layer_state_t::eSurfaceDamageRegionChanged) {
4967         if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
4968     }
4969     if (what & layer_state_t::eApiChanged) {
4970         if (layer->setApi(s.api)) flags |= eTraversalNeeded;
4971     }
4972     if (what & layer_state_t::eSidebandStreamChanged) {
4973         if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
4974     }
4975     if (what & layer_state_t::eInputInfoChanged) {
4976         layer->setInputInfo(*s.windowInfoHandle->getInfo());
4977         flags |= eTraversalNeeded;
4978     }
4979     std::optional<nsecs_t> dequeueBufferTimestamp;
4980     if (what & layer_state_t::eMetadataChanged) {
4981         dequeueBufferTimestamp = s.metadata.getInt64(gui::METADATA_DEQUEUE_TIME);
4982 
4983         if (const int32_t gameMode = s.metadata.getInt32(gui::METADATA_GAME_MODE, -1);
4984             gameMode != -1) {
4985             // The transaction will be received on the Task layer and needs to be applied to all
4986             // child layers. Child layers that are added at a later point will obtain the game mode
4987             // info through addChild().
4988             layer->setGameModeForTree(static_cast<GameMode>(gameMode));
4989         }
4990 
4991         if (layer->setMetadata(s.metadata)) {
4992             flags |= eTraversalNeeded;
4993             mLayerMetadataSnapshotNeeded = true;
4994         }
4995     }
4996     if (what & layer_state_t::eColorSpaceAgnosticChanged) {
4997         if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
4998             flags |= eTraversalNeeded;
4999         }
5000     }
5001     if (what & layer_state_t::eShadowRadiusChanged) {
5002         if (layer->setShadowRadius(s.shadowRadius)) flags |= eTraversalNeeded;
5003     }
5004     if (what & layer_state_t::eDefaultFrameRateCompatibilityChanged) {
5005         const auto compatibility =
5006                 Layer::FrameRate::convertCompatibility(s.defaultFrameRateCompatibility);
5007 
5008         if (layer->setDefaultFrameRateCompatibility(compatibility)) {
5009             flags |= eTraversalNeeded;
5010         }
5011     }
5012     if (what & layer_state_t::eFrameRateSelectionPriority) {
5013         if (layer->setFrameRateSelectionPriority(s.frameRateSelectionPriority)) {
5014             flags |= eTraversalNeeded;
5015         }
5016     }
5017     if (what & layer_state_t::eFrameRateChanged) {
5018         const auto compatibility =
5019             Layer::FrameRate::convertCompatibility(s.frameRateCompatibility);
5020         const auto strategy =
5021             Layer::FrameRate::convertChangeFrameRateStrategy(s.changeFrameRateStrategy);
5022 
5023         if (layer->setFrameRate(
5024                 Layer::FrameRate(Fps::fromValue(s.frameRate), compatibility, strategy))) {
5025           flags |= eTraversalNeeded;
5026         }
5027     }
5028     if (what & layer_state_t::eFixedTransformHintChanged) {
5029         if (layer->setFixedTransformHint(s.fixedTransformHint)) {
5030             flags |= eTraversalNeeded | eTransformHintUpdateNeeded;
5031         }
5032     }
5033     if (what & layer_state_t::eAutoRefreshChanged) {
5034         layer->setAutoRefresh(s.autoRefresh);
5035     }
5036     if (what & layer_state_t::eDimmingEnabledChanged) {
5037         if (layer->setDimmingEnabled(s.dimmingEnabled)) flags |= eTraversalNeeded;
5038     }
5039     if (what & layer_state_t::eExtendedRangeBrightnessChanged) {
5040         if (layer->setExtendedRangeBrightness(s.currentHdrSdrRatio, s.desiredHdrSdrRatio)) {
5041             flags |= eTraversalNeeded;
5042         }
5043     }
5044     if (what & layer_state_t::eCachingHintChanged) {
5045         if (layer->setCachingHint(s.cachingHint)) {
5046             flags |= eTraversalNeeded;
5047         }
5048     }
5049     if (what & layer_state_t::eHdrMetadataChanged) {
5050         if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
5051     }
5052     if (what & layer_state_t::eTrustedOverlayChanged) {
5053         if (layer->setTrustedOverlay(s.isTrustedOverlay)) {
5054             flags |= eTraversalNeeded;
5055         }
5056     }
5057     if (what & layer_state_t::eStretchChanged) {
5058         if (layer->setStretchEffect(s.stretchEffect)) {
5059             flags |= eTraversalNeeded;
5060         }
5061     }
5062     if (what & layer_state_t::eBufferCropChanged) {
5063         if (layer->setBufferCrop(s.bufferCrop)) {
5064             flags |= eTraversalNeeded;
5065         }
5066     }
5067     if (what & layer_state_t::eDestinationFrameChanged) {
5068         if (layer->setDestinationFrame(s.destinationFrame)) {
5069             flags |= eTraversalNeeded;
5070         }
5071     }
5072     if (what & layer_state_t::eDropInputModeChanged) {
5073         if (layer->setDropInputMode(s.dropInputMode)) {
5074             flags |= eTraversalNeeded;
5075             mUpdateInputInfo = true;
5076         }
5077     }
5078     // This has to happen after we reparent children because when we reparent to null we remove
5079     // child layers from current state and remove its relative z. If the children are reparented in
5080     // the same transaction, then we have to make sure we reparent the children first so we do not
5081     // lose its relative z order.
5082     if (what & layer_state_t::eReparent) {
5083         bool hadParent = layer->hasParent();
5084         auto parentHandle = (s.parentSurfaceControlForChild)
5085                 ? s.parentSurfaceControlForChild->getHandle()
5086                 : nullptr;
5087         if (layer->reparent(parentHandle)) {
5088             if (!hadParent) {
5089                 layer->setIsAtRoot(false);
5090                 mCurrentState.layersSortedByZ.remove(layer);
5091             }
5092             flags |= eTransactionNeeded | eTraversalNeeded;
5093         }
5094     }
5095     std::vector<sp<CallbackHandle>> callbackHandles;
5096     if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!filteredListeners.empty())) {
5097         for (auto& [listener, callbackIds] : filteredListeners) {
5098             callbackHandles.emplace_back(
5099                     sp<CallbackHandle>::make(listener, callbackIds, s.surface));
5100         }
5101     }
5102 
5103     if (what & layer_state_t::eBufferChanged) {
5104         if (layer->setBuffer(composerState.externalTexture, *s.bufferData, postTime,
5105                              desiredPresentTime, isAutoTimestamp, dequeueBufferTimestamp,
5106                              frameTimelineInfo)) {
5107             flags |= eTraversalNeeded;
5108         }
5109     } else if (frameTimelineInfo.vsyncId != FrameTimelineInfo::INVALID_VSYNC_ID) {
5110         layer->setFrameTimelineVsyncForBufferlessTransaction(frameTimelineInfo, postTime);
5111     }
5112 
5113     if ((what & layer_state_t::eBufferChanged) == 0) {
5114         layer->setDesiredPresentTime(desiredPresentTime, isAutoTimestamp);
5115     }
5116 
5117     if (what & layer_state_t::eTrustedPresentationInfoChanged) {
5118         if (layer->setTrustedPresentationInfo(s.trustedPresentationThresholds,
5119                                               s.trustedPresentationListener)) {
5120             flags |= eTraversalNeeded;
5121         }
5122     }
5123 
5124     if (what & layer_state_t::eFlushJankData) {
5125         // Do nothing. Processing the transaction completed listeners currently cause the flush.
5126     }
5127 
5128     if (layer->setTransactionCompletedListeners(callbackHandles,
5129                                                 layer->willPresentCurrentTransaction() ||
5130                                                         layer->willReleaseBufferOnLatch())) {
5131         flags |= eTraversalNeeded;
5132     }
5133 
5134     // Do not put anything that updates layer state or modifies flags after
5135     // setTransactionCompletedListener
5136 
5137     // if the layer has been parented on to a new display, update its transform hint.
5138     if (((flags & eTransformHintUpdateNeeded) == 0) &&
5139         oldLayerStack != layer->getLayerStack(LayerVector::StateSet::Current)) {
5140         flags |= eTransformHintUpdateNeeded;
5141     }
5142 
5143     return flags;
5144 }
5145 
updateLayerCallbacksAndStats(const FrameTimelineInfo & frameTimelineInfo,ResolvedComposerState & composerState,int64_t desiredPresentTime,bool isAutoTimestamp,int64_t postTime,uint64_t transactionId)5146 uint32_t SurfaceFlinger::updateLayerCallbacksAndStats(const FrameTimelineInfo& frameTimelineInfo,
5147                                                       ResolvedComposerState& composerState,
5148                                                       int64_t desiredPresentTime,
5149                                                       bool isAutoTimestamp, int64_t postTime,
5150                                                       uint64_t transactionId) {
5151     layer_state_t& s = composerState.state;
5152 
5153     std::vector<ListenerCallbacks> filteredListeners;
5154     for (auto& listener : s.listeners) {
5155         // Starts a registration but separates the callback ids according to callback type. This
5156         // allows the callback invoker to send on latch callbacks earlier.
5157         // note that startRegistration will not re-register if the listener has
5158         // already be registered for a prior surface control
5159 
5160         ListenerCallbacks onCommitCallbacks = listener.filter(CallbackId::Type::ON_COMMIT);
5161         if (!onCommitCallbacks.callbackIds.empty()) {
5162             filteredListeners.push_back(onCommitCallbacks);
5163         }
5164 
5165         ListenerCallbacks onCompleteCallbacks = listener.filter(CallbackId::Type::ON_COMPLETE);
5166         if (!onCompleteCallbacks.callbackIds.empty()) {
5167             filteredListeners.push_back(onCompleteCallbacks);
5168         }
5169     }
5170 
5171     const uint64_t what = s.what;
5172     uint32_t flags = 0;
5173     sp<Layer> layer = nullptr;
5174     if (s.surface) {
5175         layer = LayerHandle::getLayer(s.surface);
5176     } else {
5177         // The client may provide us a null handle. Treat it as if the layer was removed.
5178         ALOGW("Attempt to set client state with a null layer handle");
5179     }
5180     if (layer == nullptr) {
5181         for (auto& [listener, callbackIds] : s.listeners) {
5182             mTransactionCallbackInvoker.addCallbackHandle(sp<CallbackHandle>::make(listener,
5183                                                                                    callbackIds,
5184                                                                                    s.surface),
5185                                                           std::vector<JankData>());
5186         }
5187         return 0;
5188     }
5189     if (what & layer_state_t::eProducerDisconnect) {
5190         layer->onDisconnect();
5191     }
5192     std::optional<nsecs_t> dequeueBufferTimestamp;
5193     if (what & layer_state_t::eMetadataChanged) {
5194         dequeueBufferTimestamp = s.metadata.getInt64(gui::METADATA_DEQUEUE_TIME);
5195     }
5196 
5197     std::vector<sp<CallbackHandle>> callbackHandles;
5198     if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!filteredListeners.empty())) {
5199         for (auto& [listener, callbackIds] : filteredListeners) {
5200             callbackHandles.emplace_back(
5201                     sp<CallbackHandle>::make(listener, callbackIds, s.surface));
5202         }
5203     }
5204     // TODO(b/238781169) remove after screenshot refactor, currently screenshots
5205     // requires to read drawing state from binder thread. So we need to fix that
5206     // before removing this.
5207     if (what & layer_state_t::eCropChanged) {
5208         if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
5209     }
5210     if (what & layer_state_t::eSidebandStreamChanged) {
5211         if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
5212     }
5213     if (what & layer_state_t::eBufferChanged) {
5214         std::optional<ui::Transform::RotationFlags> transformHint = std::nullopt;
5215         frontend::LayerSnapshot* snapshot = mLayerSnapshotBuilder.getSnapshot(layer->sequence);
5216         if (snapshot) {
5217             transformHint = snapshot->transformHint;
5218         }
5219         layer->setTransformHint(transformHint);
5220         if (layer->setBuffer(composerState.externalTexture, *s.bufferData, postTime,
5221                              desiredPresentTime, isAutoTimestamp, dequeueBufferTimestamp,
5222                              frameTimelineInfo)) {
5223             flags |= eTraversalNeeded;
5224         }
5225         mLayersWithQueuedFrames.emplace(layer);
5226     } else if (frameTimelineInfo.vsyncId != FrameTimelineInfo::INVALID_VSYNC_ID) {
5227         layer->setFrameTimelineVsyncForBufferlessTransaction(frameTimelineInfo, postTime);
5228     }
5229 
5230     if ((what & layer_state_t::eBufferChanged) == 0) {
5231         layer->setDesiredPresentTime(desiredPresentTime, isAutoTimestamp);
5232     }
5233 
5234     if (what & layer_state_t::eTrustedPresentationInfoChanged) {
5235         if (layer->setTrustedPresentationInfo(s.trustedPresentationThresholds,
5236                                               s.trustedPresentationListener)) {
5237             flags |= eTraversalNeeded;
5238         }
5239     }
5240 
5241     const auto& requestedLayerState = mLayerLifecycleManager.getLayerFromId(layer->getSequence());
5242     bool willPresentCurrentTransaction = requestedLayerState &&
5243             (requestedLayerState->hasReadyFrame() ||
5244              requestedLayerState->willReleaseBufferOnLatch());
5245     if (layer->setTransactionCompletedListeners(callbackHandles, willPresentCurrentTransaction))
5246         flags |= eTraversalNeeded;
5247 
5248     return flags;
5249 }
5250 
addInputWindowCommands(const InputWindowCommands & inputWindowCommands)5251 uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
5252     bool hasChanges = mInputWindowCommands.merge(inputWindowCommands);
5253     return hasChanges ? eTraversalNeeded : 0;
5254 }
5255 
mirrorLayer(const LayerCreationArgs & args,const sp<IBinder> & mirrorFromHandle,gui::CreateSurfaceResult & outResult)5256 status_t SurfaceFlinger::mirrorLayer(const LayerCreationArgs& args,
5257                                      const sp<IBinder>& mirrorFromHandle,
5258                                      gui::CreateSurfaceResult& outResult) {
5259     if (!mirrorFromHandle) {
5260         return NAME_NOT_FOUND;
5261     }
5262 
5263     sp<Layer> mirrorLayer;
5264     sp<Layer> mirrorFrom;
5265     LayerCreationArgs mirrorArgs = LayerCreationArgs::fromOtherArgs(args);
5266     {
5267         Mutex::Autolock _l(mStateLock);
5268         mirrorFrom = LayerHandle::getLayer(mirrorFromHandle);
5269         if (!mirrorFrom) {
5270             return NAME_NOT_FOUND;
5271         }
5272         mirrorArgs.flags |= ISurfaceComposerClient::eNoColorFill;
5273         mirrorArgs.mirrorLayerHandle = mirrorFromHandle;
5274         mirrorArgs.addToRoot = false;
5275         status_t result = createEffectLayer(mirrorArgs, &outResult.handle, &mirrorLayer);
5276         if (result != NO_ERROR) {
5277             return result;
5278         }
5279 
5280         mirrorLayer->setClonedChild(mirrorFrom->createClone(mirrorLayer->getSequence()));
5281     }
5282 
5283     outResult.layerId = mirrorLayer->sequence;
5284     outResult.layerName = String16(mirrorLayer->getDebugName());
5285     return addClientLayer(mirrorArgs, outResult.handle, mirrorLayer /* layer */,
5286                           nullptr /* parent */, nullptr /* outTransformHint */);
5287 }
5288 
mirrorDisplay(DisplayId displayId,const LayerCreationArgs & args,gui::CreateSurfaceResult & outResult)5289 status_t SurfaceFlinger::mirrorDisplay(DisplayId displayId, const LayerCreationArgs& args,
5290                                        gui::CreateSurfaceResult& outResult) {
5291     IPCThreadState* ipc = IPCThreadState::self();
5292     const int uid = ipc->getCallingUid();
5293     if (uid != AID_ROOT && uid != AID_GRAPHICS && uid != AID_SYSTEM && uid != AID_SHELL) {
5294         ALOGE("Permission denied when trying to mirror display");
5295         return PERMISSION_DENIED;
5296     }
5297 
5298     ui::LayerStack layerStack;
5299     sp<Layer> rootMirrorLayer;
5300     status_t result = 0;
5301 
5302     {
5303         Mutex::Autolock lock(mStateLock);
5304 
5305         const auto display = getDisplayDeviceLocked(displayId);
5306         if (!display) {
5307             return NAME_NOT_FOUND;
5308         }
5309 
5310         layerStack = display->getLayerStack();
5311         LayerCreationArgs mirrorArgs = LayerCreationArgs::fromOtherArgs(args);
5312         mirrorArgs.flags |= ISurfaceComposerClient::eNoColorFill;
5313         mirrorArgs.addToRoot = true;
5314         mirrorArgs.layerStackToMirror = layerStack;
5315         result = createEffectLayer(mirrorArgs, &outResult.handle, &rootMirrorLayer);
5316         outResult.layerId = rootMirrorLayer->sequence;
5317         outResult.layerName = String16(rootMirrorLayer->getDebugName());
5318         result |= addClientLayer(mirrorArgs, outResult.handle, rootMirrorLayer /* layer */,
5319                                  nullptr /* parent */, nullptr /* outTransformHint */);
5320     }
5321 
5322     if (result != NO_ERROR) {
5323         return result;
5324     }
5325 
5326     if (mLegacyFrontEndEnabled) {
5327         std::scoped_lock<std::mutex> lock(mMirrorDisplayLock);
5328         mMirrorDisplays.emplace_back(layerStack, outResult.handle, args.client);
5329     }
5330 
5331     setTransactionFlags(eTransactionFlushNeeded);
5332     return NO_ERROR;
5333 }
5334 
createLayer(LayerCreationArgs & args,gui::CreateSurfaceResult & outResult)5335 status_t SurfaceFlinger::createLayer(LayerCreationArgs& args, gui::CreateSurfaceResult& outResult) {
5336     status_t result = NO_ERROR;
5337 
5338     sp<Layer> layer;
5339 
5340     switch (args.flags & ISurfaceComposerClient::eFXSurfaceMask) {
5341         case ISurfaceComposerClient::eFXSurfaceBufferQueue:
5342         case ISurfaceComposerClient::eFXSurfaceContainer:
5343         case ISurfaceComposerClient::eFXSurfaceBufferState:
5344             args.flags |= ISurfaceComposerClient::eNoColorFill;
5345             FMT_FALLTHROUGH;
5346         case ISurfaceComposerClient::eFXSurfaceEffect: {
5347             result = createBufferStateLayer(args, &outResult.handle, &layer);
5348             std::atomic<int32_t>* pendingBufferCounter = layer->getPendingBufferCounter();
5349             if (pendingBufferCounter) {
5350                 std::string counterName = layer->getPendingBufferCounterName();
5351                 mBufferCountTracker.add(outResult.handle->localBinder(), counterName,
5352                                         pendingBufferCounter);
5353             }
5354         } break;
5355         default:
5356             result = BAD_VALUE;
5357             break;
5358     }
5359 
5360     if (result != NO_ERROR) {
5361         return result;
5362     }
5363 
5364     args.addToRoot = args.addToRoot && callingThreadHasUnscopedSurfaceFlingerAccess();
5365     // We can safely promote the parent layer in binder thread because we have a strong reference
5366     // to the layer's handle inside this scope.
5367     sp<Layer> parent = LayerHandle::getLayer(args.parentHandle.promote());
5368     if (args.parentHandle != nullptr && parent == nullptr) {
5369         ALOGE("Invalid parent handle %p", args.parentHandle.promote().get());
5370         args.addToRoot = false;
5371     }
5372 
5373     uint32_t outTransformHint;
5374     result = addClientLayer(args, outResult.handle, layer, parent, &outTransformHint);
5375     if (result != NO_ERROR) {
5376         return result;
5377     }
5378 
5379     outResult.transformHint = static_cast<int32_t>(outTransformHint);
5380     outResult.layerId = layer->sequence;
5381     outResult.layerName = String16(layer->getDebugName());
5382     return result;
5383 }
5384 
createBufferStateLayer(LayerCreationArgs & args,sp<IBinder> * handle,sp<Layer> * outLayer)5385 status_t SurfaceFlinger::createBufferStateLayer(LayerCreationArgs& args, sp<IBinder>* handle,
5386                                                 sp<Layer>* outLayer) {
5387     args.textureName = getNewTexture();
5388     *outLayer = getFactory().createBufferStateLayer(args);
5389     *handle = (*outLayer)->getHandle();
5390     return NO_ERROR;
5391 }
5392 
createEffectLayer(const LayerCreationArgs & args,sp<IBinder> * handle,sp<Layer> * outLayer)5393 status_t SurfaceFlinger::createEffectLayer(const LayerCreationArgs& args, sp<IBinder>* handle,
5394                                            sp<Layer>* outLayer) {
5395     *outLayer = getFactory().createEffectLayer(args);
5396     *handle = (*outLayer)->getHandle();
5397     return NO_ERROR;
5398 }
5399 
markLayerPendingRemovalLocked(const sp<Layer> & layer)5400 void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
5401     mLayersPendingRemoval.add(layer);
5402     mLayersRemoved = true;
5403     setTransactionFlags(eTransactionNeeded);
5404 }
5405 
onHandleDestroyed(BBinder * handle,sp<Layer> & layer,uint32_t layerId)5406 void SurfaceFlinger::onHandleDestroyed(BBinder* handle, sp<Layer>& layer, uint32_t layerId) {
5407     {
5408         std::scoped_lock<std::mutex> lock(mCreatedLayersLock);
5409         mDestroyedHandles.emplace_back(layerId);
5410     }
5411 
5412     mTransactionHandler.onLayerDestroyed(layerId);
5413 
5414     Mutex::Autolock lock(mStateLock);
5415     markLayerPendingRemovalLocked(layer);
5416     layer->onHandleDestroyed();
5417     mBufferCountTracker.remove(handle);
5418     layer.clear();
5419 
5420     setTransactionFlags(eTransactionFlushNeeded);
5421 }
5422 
initializeDisplays()5423 void SurfaceFlinger::initializeDisplays() {
5424     const auto display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
5425     if (!display) return;
5426 
5427     const sp<IBinder> token = display->getDisplayToken().promote();
5428     LOG_ALWAYS_FATAL_IF(token == nullptr);
5429 
5430     TransactionState state;
5431     state.inputWindowCommands = mInputWindowCommands;
5432     const nsecs_t now = systemTime();
5433     state.desiredPresentTime = now;
5434     state.postTime = now;
5435     state.originPid = mPid;
5436     state.originUid = static_cast<int>(getuid());
5437     const uint64_t transactionId = (static_cast<uint64_t>(mPid) << 32) | mUniqueTransactionId++;
5438     state.id = transactionId;
5439 
5440     // reset screen orientation and use primary layer stack
5441     Vector<DisplayState> displays;
5442     DisplayState d;
5443     d.what = DisplayState::eDisplayProjectionChanged |
5444              DisplayState::eLayerStackChanged;
5445     d.token = token;
5446     d.layerStack = ui::DEFAULT_LAYER_STACK;
5447     d.orientation = ui::ROTATION_0;
5448     d.orientedDisplaySpaceRect.makeInvalid();
5449     d.layerStackSpaceRect.makeInvalid();
5450     d.width = 0;
5451     d.height = 0;
5452     state.displays.add(d);
5453 
5454     std::vector<TransactionState> transactions;
5455     transactions.emplace_back(state);
5456 
5457     if (mLegacyFrontEndEnabled) {
5458         applyTransactions(transactions, VsyncId{0});
5459     } else {
5460         applyAndCommitDisplayTransactionStates(transactions);
5461     }
5462 
5463     {
5464         ftl::FakeGuard guard(mStateLock);
5465         setPowerModeInternal(display, hal::PowerMode::ON);
5466     }
5467 }
5468 
setPowerModeInternal(const sp<DisplayDevice> & display,hal::PowerMode mode)5469 void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, hal::PowerMode mode) {
5470     if (display->isVirtual()) {
5471         ALOGE("%s: Invalid operation on virtual display", __func__);
5472         return;
5473     }
5474 
5475     const auto displayId = display->getPhysicalId();
5476     ALOGD("Setting power mode %d on display %s", mode, to_string(displayId).c_str());
5477 
5478     const auto currentModeOpt = display->getPowerMode();
5479     if (currentModeOpt == mode) {
5480         return;
5481     }
5482 
5483     const bool isInternalDisplay = mPhysicalDisplays.get(displayId)
5484                                            .transform(&PhysicalDisplay::isInternal)
5485                                            .value_or(false);
5486 
5487     const auto activeDisplay = getDisplayDeviceLocked(mActiveDisplayId);
5488 
5489     ALOGW_IF(display != activeDisplay && isInternalDisplay && activeDisplay &&
5490                      activeDisplay->isPoweredOn(),
5491              "Trying to change power mode on inactive display without powering off active display");
5492 
5493     display->setPowerMode(mode);
5494 
5495     const auto refreshRate = display->refreshRateSelector().getActiveMode().modePtr->getFps();
5496     if (!currentModeOpt || *currentModeOpt == hal::PowerMode::OFF) {
5497         // Turn on the display
5498 
5499         // Activate the display (which involves a modeset to the active mode) when the inner or
5500         // outer display of a foldable is powered on. This condition relies on the above
5501         // DisplayDevice::setPowerMode. If `display` and `activeDisplay` are the same display,
5502         // then the `activeDisplay->isPoweredOn()` below is true, such that the display is not
5503         // activated every time it is powered on.
5504         //
5505         // TODO(b/255635821): Remove the concept of active display.
5506         if (isInternalDisplay && (!activeDisplay || !activeDisplay->isPoweredOn())) {
5507             onActiveDisplayChangedLocked(activeDisplay.get(), *display);
5508         }
5509 
5510         if (displayId == mActiveDisplayId) {
5511             // TODO(b/281692563): Merge the syscalls. For now, keep uclamp in a separate syscall and
5512             // set it before SCHED_FIFO due to b/190237315.
5513             if (setSchedAttr(true) != NO_ERROR) {
5514                 ALOGW("Failed to set uclamp.min after powering on active display: %s",
5515                       strerror(errno));
5516             }
5517             if (setSchedFifo(true) != NO_ERROR) {
5518                 ALOGW("Failed to set SCHED_FIFO after powering on active display: %s",
5519                       strerror(errno));
5520             }
5521         }
5522 
5523         getHwComposer().setPowerMode(displayId, mode);
5524         if (displayId == mActiveDisplayId && mode != hal::PowerMode::DOZE_SUSPEND) {
5525             const bool enable =
5526                     mScheduler->getVsyncSchedule(displayId)->getPendingHardwareVsyncState();
5527             requestHardwareVsync(displayId, enable);
5528 
5529             mScheduler->enableSyntheticVsync(false);
5530 
5531             constexpr bool kAllowToEnable = true;
5532             mScheduler->resyncToHardwareVsync(displayId, kAllowToEnable, refreshRate);
5533         }
5534 
5535         mVisibleRegionsDirty = true;
5536         scheduleComposite(FrameHint::kActive);
5537     } else if (mode == hal::PowerMode::OFF) {
5538         // Turn off the display
5539 
5540         if (displayId == mActiveDisplayId) {
5541             if (const auto display = getActivatableDisplay()) {
5542                 onActiveDisplayChangedLocked(activeDisplay.get(), *display);
5543             } else {
5544                 if (setSchedFifo(false) != NO_ERROR) {
5545                     ALOGW("Failed to set SCHED_OTHER after powering off active display: %s",
5546                           strerror(errno));
5547                 }
5548                 if (setSchedAttr(false) != NO_ERROR) {
5549                     ALOGW("Failed set uclamp.min after powering off active display: %s",
5550                           strerror(errno));
5551                 }
5552 
5553                 if (*currentModeOpt != hal::PowerMode::DOZE_SUSPEND) {
5554                     mScheduler->disableHardwareVsync(displayId, true);
5555                     mScheduler->enableSyntheticVsync();
5556                 }
5557             }
5558         }
5559 
5560         // Disable VSYNC before turning off the display.
5561         requestHardwareVsync(displayId, false);
5562         getHwComposer().setPowerMode(displayId, mode);
5563 
5564         mVisibleRegionsDirty = true;
5565         // from this point on, SF will stop drawing on this display
5566     } else if (mode == hal::PowerMode::DOZE || mode == hal::PowerMode::ON) {
5567         // Update display while dozing
5568         getHwComposer().setPowerMode(displayId, mode);
5569         if (displayId == mActiveDisplayId && *currentModeOpt == hal::PowerMode::DOZE_SUSPEND) {
5570             ALOGI("Force repainting for DOZE_SUSPEND -> DOZE or ON.");
5571             mVisibleRegionsDirty = true;
5572             scheduleRepaint();
5573             mScheduler->enableSyntheticVsync(false);
5574             mScheduler->resyncToHardwareVsync(displayId, true /* allowToEnable */, refreshRate);
5575         }
5576     } else if (mode == hal::PowerMode::DOZE_SUSPEND) {
5577         // Leave display going to doze
5578         if (displayId == mActiveDisplayId) {
5579             mScheduler->disableHardwareVsync(displayId, true);
5580             mScheduler->enableSyntheticVsync();
5581         }
5582         getHwComposer().setPowerMode(displayId, mode);
5583     } else {
5584         ALOGE("Attempting to set unknown power mode: %d\n", mode);
5585         getHwComposer().setPowerMode(displayId, mode);
5586     }
5587 
5588     if (displayId == mActiveDisplayId) {
5589         mTimeStats->setPowerMode(mode);
5590         mRefreshRateStats->setPowerMode(mode);
5591     }
5592 
5593     mScheduler->setDisplayPowerMode(displayId, mode);
5594 
5595     ALOGD("Finished setting power mode %d on display %s", mode, to_string(displayId).c_str());
5596 }
5597 
setPowerMode(const sp<IBinder> & displayToken,int mode)5598 void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
5599     auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) FTL_FAKE_GUARD(
5600                                                kMainThreadContext) {
5601         const auto display = getDisplayDeviceLocked(displayToken);
5602         if (!display) {
5603             ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
5604                   displayToken.get());
5605         } else if (display->isVirtual()) {
5606             ALOGW("Attempt to set power mode %d for virtual display", mode);
5607         } else {
5608             setPowerModeInternal(display, static_cast<hal::PowerMode>(mode));
5609         }
5610     });
5611 
5612     future.wait();
5613 }
5614 
doDump(int fd,const DumpArgs & args,bool asProto)5615 status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args, bool asProto) {
5616     std::string result;
5617 
5618     IPCThreadState* ipc = IPCThreadState::self();
5619     const int pid = ipc->getCallingPid();
5620     const int uid = ipc->getCallingUid();
5621 
5622     if ((uid != AID_SHELL) &&
5623             !PermissionCache::checkPermission(sDump, pid, uid)) {
5624         StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
5625                       pid, uid);
5626     } else {
5627         static const std::unordered_map<std::string, Dumper> dumpers = {
5628                 {"--comp-displays"s, dumper(&SurfaceFlinger::dumpCompositionDisplays)},
5629                 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
5630                 {"--displays"s, dumper(&SurfaceFlinger::dumpDisplays)},
5631                 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
5632                 {"--events"s, dumper(&SurfaceFlinger::dumpEvents)},
5633                 {"--frametimeline"s, argsDumper(&SurfaceFlinger::dumpFrameTimeline)},
5634                 {"--hwclayers"s, dumper(&SurfaceFlinger::dumpHwcLayersMinidumpLocked)},
5635                 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
5636                 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
5637                 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
5638                 {"--planner"s, argsDumper(&SurfaceFlinger::dumpPlannerInfo)},
5639                 {"--scheduler"s, dumper(&SurfaceFlinger::dumpScheduler)},
5640                 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
5641                 {"--vsync"s, dumper(&SurfaceFlinger::dumpVsync)},
5642                 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
5643         };
5644 
5645         const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
5646 
5647         // Traversal of drawing state must happen on the main thread.
5648         // Otherwise, SortedVector may have shared ownership during concurrent
5649         // traversals, which can result in use-after-frees.
5650         std::string compositionLayers;
5651         mScheduler
5652                 ->schedule([&] {
5653                     StringAppendF(&compositionLayers, "Composition layers\n");
5654                     mDrawingState.traverseInZOrder([&](Layer* layer) {
5655                         auto* compositionState = layer->getCompositionState();
5656                         if (!compositionState || !compositionState->isVisible) return;
5657 
5658                         android::base::StringAppendF(&compositionLayers, "* Layer %p (%s)\n", layer,
5659                                                      layer->getDebugName() ? layer->getDebugName()
5660                                                                            : "<unknown>");
5661                         compositionState->dump(compositionLayers);
5662                     });
5663                 })
5664                 .get();
5665 
5666         bool dumpLayers = true;
5667         {
5668             TimedLock lock(mStateLock, s2ns(1), __func__);
5669             if (!lock.locked()) {
5670                 StringAppendF(&result, "Dumping without lock after timeout: %s (%d)\n",
5671                               strerror(-lock.status), lock.status);
5672             }
5673 
5674             if (const auto it = dumpers.find(flag); it != dumpers.end()) {
5675                 (it->second)(args, asProto, result);
5676                 dumpLayers = false;
5677             } else if (!asProto) {
5678                 dumpAllLocked(args, compositionLayers, result);
5679             }
5680         }
5681 
5682         if (dumpLayers) {
5683             LayersTraceFileProto traceFileProto = mLayerTracing.createTraceFileProto();
5684             LayersTraceProto* layersTrace = traceFileProto.add_entry();
5685             LayersProto layersProto = dumpProtoFromMainThread();
5686             layersTrace->mutable_layers()->Swap(&layersProto);
5687             auto displayProtos = dumpDisplayProto();
5688             layersTrace->mutable_displays()->Swap(&displayProtos);
5689 
5690             if (asProto) {
5691                 result.append(traceFileProto.SerializeAsString());
5692             } else {
5693                 // Dump info that we need to access from the main thread
5694                 const auto layerTree = LayerProtoParser::generateLayerTree(layersTrace->layers());
5695                 result.append(LayerProtoParser::layerTreeToString(layerTree));
5696                 result.append("\n");
5697                 dumpOffscreenLayers(result);
5698             }
5699         }
5700     }
5701     write(fd, result.c_str(), result.size());
5702     return NO_ERROR;
5703 }
5704 
dumpCritical(int fd,const DumpArgs &,bool asProto)5705 status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
5706     return doDump(fd, DumpArgs(), asProto);
5707 }
5708 
listLayersLocked(std::string & result) const5709 void SurfaceFlinger::listLayersLocked(std::string& result) const {
5710     mCurrentState.traverseInZOrder(
5711             [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getDebugName()); });
5712 }
5713 
dumpStatsLocked(const DumpArgs & args,std::string & result) const5714 void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
5715     StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriodFromHWC());
5716     if (args.size() < 2) return;
5717 
5718     const auto name = String8(args[1]);
5719     mCurrentState.traverseInZOrder([&](Layer* layer) {
5720         if (layer->getName() == name.string()) {
5721             layer->dumpFrameStats(result);
5722         }
5723     });
5724 }
5725 
clearStatsLocked(const DumpArgs & args,std::string &)5726 void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
5727     const bool clearAll = args.size() < 2;
5728     const auto name = clearAll ? String8() : String8(args[1]);
5729 
5730     mCurrentState.traverse([&](Layer* layer) {
5731         if (clearAll || layer->getName() == name.string()) {
5732             layer->clearFrameStats();
5733         }
5734     });
5735 }
5736 
dumpTimeStats(const DumpArgs & args,bool asProto,std::string & result) const5737 void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
5738     mTimeStats->parseArgs(asProto, args, result);
5739 }
5740 
dumpFrameTimeline(const DumpArgs & args,std::string & result) const5741 void SurfaceFlinger::dumpFrameTimeline(const DumpArgs& args, std::string& result) const {
5742     mFrameTimeline->parseArgs(args, result);
5743 }
5744 
logFrameStats(TimePoint now)5745 void SurfaceFlinger::logFrameStats(TimePoint now) {
5746     static TimePoint sTimestamp = now;
5747     if (now - sTimestamp < 30min) return;
5748     sTimestamp = now;
5749 
5750     ATRACE_CALL();
5751     mDrawingState.traverse([&](Layer* layer) { layer->logFrameStats(); });
5752 }
5753 
appendSfConfigString(std::string & result) const5754 void SurfaceFlinger::appendSfConfigString(std::string& result) const {
5755     result.append(" [sf");
5756 
5757     StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
5758     StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
5759     StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%zu",
5760                   getHwComposer().getMaxVirtualDisplayDimension());
5761     StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
5762     StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
5763                   maxFrameBufferAcquiredBuffers);
5764     result.append("]");
5765 }
5766 
dumpScheduler(std::string & result) const5767 void SurfaceFlinger::dumpScheduler(std::string& result) const {
5768     utils::Dumper dumper{result};
5769 
5770     mScheduler->dump(dumper);
5771 
5772     // TODO(b/241285876): Move to DisplayModeController.
5773     dumper.dump("debugDisplayModeSetByBackdoor"sv, mDebugDisplayModeSetByBackdoor);
5774     dumper.eol();
5775 
5776     mRefreshRateStats->dump(result);
5777     dumper.eol();
5778 
5779     mVsyncConfiguration->dump(result);
5780     StringAppendF(&result,
5781                   "         present offset: %9" PRId64 " ns\t        VSYNC period: %9" PRId64
5782                   " ns\n\n",
5783                   dispSyncPresentTimeOffset, getVsyncPeriodFromHWC());
5784 }
5785 
dumpEvents(std::string & result) const5786 void SurfaceFlinger::dumpEvents(std::string& result) const {
5787     mScheduler->dump(mAppConnectionHandle, result);
5788 }
5789 
dumpVsync(std::string & result) const5790 void SurfaceFlinger::dumpVsync(std::string& result) const {
5791     mScheduler->dumpVsync(result);
5792 }
5793 
dumpPlannerInfo(const DumpArgs & args,std::string & result) const5794 void SurfaceFlinger::dumpPlannerInfo(const DumpArgs& args, std::string& result) const {
5795     for (const auto& [token, display] : mDisplays) {
5796         const auto compositionDisplay = display->getCompositionDisplay();
5797         compositionDisplay->dumpPlannerInfo(args, result);
5798     }
5799 }
5800 
dumpCompositionDisplays(std::string & result) const5801 void SurfaceFlinger::dumpCompositionDisplays(std::string& result) const {
5802     for (const auto& [token, display] : mDisplays) {
5803         display->getCompositionDisplay()->dump(result);
5804         result += '\n';
5805     }
5806 }
5807 
dumpDisplays(std::string & result) const5808 void SurfaceFlinger::dumpDisplays(std::string& result) const {
5809     utils::Dumper dumper{result};
5810 
5811     for (const auto& [id, display] : mPhysicalDisplays) {
5812         utils::Dumper::Section section(dumper, ftl::Concat("Display ", id.value).str());
5813 
5814         display.snapshot().dump(dumper);
5815 
5816         if (const auto device = getDisplayDeviceLocked(id)) {
5817             device->dump(dumper);
5818         }
5819     }
5820 
5821     for (const auto& [token, display] : mDisplays) {
5822         if (display->isVirtual()) {
5823             const auto displayId = display->getId();
5824             utils::Dumper::Section section(dumper,
5825                                            ftl::Concat("Virtual Display ", displayId.value).str());
5826             display->dump(dumper);
5827         }
5828     }
5829 }
5830 
dumpDisplayIdentificationData(std::string & result) const5831 void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
5832     for (const auto& [token, display] : mDisplays) {
5833         const auto displayId = PhysicalDisplayId::tryCast(display->getId());
5834         if (!displayId) {
5835             continue;
5836         }
5837         const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
5838         if (!hwcDisplayId) {
5839             continue;
5840         }
5841 
5842         StringAppendF(&result,
5843                       "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
5844                       *hwcDisplayId);
5845         uint8_t port;
5846         DisplayIdentificationData data;
5847         if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
5848             result.append("no identification data\n");
5849             continue;
5850         }
5851 
5852         if (!isEdid(data)) {
5853             result.append("unknown identification data\n");
5854             continue;
5855         }
5856 
5857         const auto edid = parseEdid(data);
5858         if (!edid) {
5859             result.append("invalid EDID\n");
5860             continue;
5861         }
5862 
5863         StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
5864         result.append(edid->displayName.data(), edid->displayName.length());
5865         result.append("\"\n");
5866     }
5867 }
5868 
dumpRawDisplayIdentificationData(const DumpArgs & args,std::string & result) const5869 void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
5870                                                       std::string& result) const {
5871     hal::HWDisplayId hwcDisplayId;
5872     uint8_t port;
5873     DisplayIdentificationData data;
5874 
5875     if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
5876         getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
5877         result.append(reinterpret_cast<const char*>(data.data()), data.size());
5878     }
5879 }
5880 
dumpWideColorInfo(std::string & result) const5881 void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
5882     StringAppendF(&result, "Device supports wide color: %d\n", mSupportsWideColor);
5883     StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
5884     StringAppendF(&result, "DisplayColorSetting: %s\n",
5885                   decodeDisplayColorSetting(mDisplayColorSetting).c_str());
5886 
5887     // TODO: print out if wide-color mode is active or not
5888 
5889     for (const auto& [id, display] : mPhysicalDisplays) {
5890         StringAppendF(&result, "Display %s color modes:\n", to_string(id).c_str());
5891         for (const auto mode : display.snapshot().colorModes()) {
5892             StringAppendF(&result, "    %s (%d)\n", decodeColorMode(mode).c_str(), mode);
5893         }
5894 
5895         if (const auto display = getDisplayDeviceLocked(id)) {
5896             ui::ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
5897             StringAppendF(&result, "    Current color mode: %s (%d)\n",
5898                           decodeColorMode(currentMode).c_str(), currentMode);
5899         }
5900     }
5901     result.append("\n");
5902 }
5903 
dumpDrawingStateProto(uint32_t traceFlags) const5904 LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
5905     std::unordered_set<uint64_t> stackIdsToSkip;
5906 
5907     // Determine if virtual layers display should be skipped
5908     if ((traceFlags & LayerTracing::TRACE_VIRTUAL_DISPLAYS) == 0) {
5909         for (const auto& [_, display] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
5910             if (display->isVirtual()) {
5911                 stackIdsToSkip.insert(display->getLayerStack().id);
5912             }
5913         }
5914     }
5915 
5916     if (mLegacyFrontEndEnabled) {
5917         LayersProto layersProto;
5918         for (const sp<Layer>& layer : mDrawingState.layersSortedByZ) {
5919             if (stackIdsToSkip.find(layer->getLayerStack().id) != stackIdsToSkip.end()) {
5920                 continue;
5921             }
5922             layer->writeToProto(layersProto, traceFlags);
5923         }
5924         return layersProto;
5925     }
5926 
5927     return LayerProtoFromSnapshotGenerator(mLayerSnapshotBuilder, mFrontEndDisplayInfos,
5928                                            mLegacyLayers, traceFlags)
5929             .generate(mLayerHierarchyBuilder.getHierarchy());
5930 }
5931 
dumpDisplayProto() const5932 google::protobuf::RepeatedPtrField<DisplayProto> SurfaceFlinger::dumpDisplayProto() const {
5933     google::protobuf::RepeatedPtrField<DisplayProto> displays;
5934     for (const auto& [_, display] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
5935         DisplayProto* displayProto = displays.Add();
5936         displayProto->set_id(display->getId().value);
5937         displayProto->set_name(display->getDisplayName());
5938         displayProto->set_layer_stack(display->getLayerStack().id);
5939         LayerProtoHelper::writeSizeToProto(display->getWidth(), display->getHeight(),
5940                                            [&]() { return displayProto->mutable_size(); });
5941         LayerProtoHelper::writeToProto(display->getLayerStackSpaceRect(), [&]() {
5942             return displayProto->mutable_layer_stack_space_rect();
5943         });
5944         LayerProtoHelper::writeTransformToProto(display->getTransform(),
5945                                                 displayProto->mutable_transform());
5946         displayProto->set_is_virtual(display->isVirtual());
5947     }
5948     return displays;
5949 }
5950 
dumpHwc(std::string & result) const5951 void SurfaceFlinger::dumpHwc(std::string& result) const {
5952     getHwComposer().dump(result);
5953 }
5954 
dumpOffscreenLayersProto(LayersProto & layersProto,uint32_t traceFlags) const5955 void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
5956     // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
5957     // it.
5958     LayerProto* rootProto = layersProto.add_layers();
5959     const int32_t offscreenRootLayerId = INT32_MAX - 2;
5960     rootProto->set_id(offscreenRootLayerId);
5961     rootProto->set_name("Offscreen Root");
5962     rootProto->set_parent(-1);
5963 
5964     for (Layer* offscreenLayer : mOffscreenLayers) {
5965         // Add layer as child of the fake root
5966         rootProto->add_children(offscreenLayer->sequence);
5967 
5968         // Add layer
5969         LayerProto* layerProto = offscreenLayer->writeToProto(layersProto, traceFlags);
5970         layerProto->set_parent(offscreenRootLayerId);
5971     }
5972 }
5973 
dumpProtoFromMainThread(uint32_t traceFlags)5974 LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
5975     return mScheduler->schedule([=] { return dumpDrawingStateProto(traceFlags); }).get();
5976 }
5977 
dumpOffscreenLayers(std::string & result)5978 void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
5979     auto future = mScheduler->schedule([this] {
5980         std::string result;
5981         for (Layer* offscreenLayer : mOffscreenLayers) {
5982             offscreenLayer->traverse(LayerVector::StateSet::Drawing,
5983                                      [&](Layer* layer) { layer->dumpOffscreenDebugInfo(result); });
5984         }
5985         return result;
5986     });
5987 
5988     result.append("Offscreen Layers:\n");
5989     result.append(future.get());
5990 }
5991 
dumpHwcLayersMinidumpLocked(std::string & result) const5992 void SurfaceFlinger::dumpHwcLayersMinidumpLocked(std::string& result) const {
5993     for (const auto& [token, display] : mDisplays) {
5994         const auto displayId = HalDisplayId::tryCast(display->getId());
5995         if (!displayId) {
5996             continue;
5997         }
5998 
5999         StringAppendF(&result, "Display %s (%s) HWC layers:\n", to_string(*displayId).c_str(),
6000                       displayId == mActiveDisplayId ? "active" : "inactive");
6001         Layer::miniDumpHeader(result);
6002 
6003         const DisplayDevice& ref = *display;
6004         mDrawingState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, ref); });
6005         result.append("\n");
6006     }
6007 }
6008 
dumpAllLocked(const DumpArgs & args,const std::string & compositionLayers,std::string & result) const6009 void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, const std::string& compositionLayers,
6010                                    std::string& result) const {
6011     const bool colorize = !args.empty() && args[0] == String16("--color");
6012     Colorizer colorizer(colorize);
6013 
6014     // figure out if we're stuck somewhere
6015     const nsecs_t now = systemTime();
6016     const nsecs_t inTransaction(mDebugInTransaction);
6017     nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
6018 
6019     /*
6020      * Dump library configuration.
6021      */
6022 
6023     colorizer.bold(result);
6024     result.append("Build configuration:");
6025     colorizer.reset(result);
6026     appendSfConfigString(result);
6027     result.append("\n");
6028 
6029     result.append("\nDisplay identification data:\n");
6030     dumpDisplayIdentificationData(result);
6031 
6032     result.append("\nWide-Color information:\n");
6033     dumpWideColorInfo(result);
6034 
6035     colorizer.bold(result);
6036     result.append("Sync configuration: ");
6037     colorizer.reset(result);
6038     result.append(SyncFeatures::getInstance().toString());
6039     result.append("\n\n");
6040 
6041     colorizer.bold(result);
6042     result.append("Scheduler:\n");
6043     colorizer.reset(result);
6044     dumpScheduler(result);
6045     dumpEvents(result);
6046     dumpVsync(result);
6047     result.append("\n");
6048 
6049     /*
6050      * Dump the visible layer list
6051      */
6052     colorizer.bold(result);
6053     StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
6054     colorizer.reset(result);
6055 
6056     result.append(compositionLayers);
6057 
6058     colorizer.bold(result);
6059     StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
6060     colorizer.reset(result);
6061     dumpDisplays(result);
6062     dumpCompositionDisplays(result);
6063     result.push_back('\n');
6064 
6065     mCompositionEngine->dump(result);
6066 
6067     /*
6068      * Dump SurfaceFlinger global state
6069      */
6070 
6071     colorizer.bold(result);
6072     result.append("SurfaceFlinger global state:\n");
6073     colorizer.reset(result);
6074 
6075     getRenderEngine().dump(result);
6076 
6077     result.append("ClientCache state:\n");
6078     ClientCache::getInstance().dump(result);
6079     DebugEGLImageTracker::getInstance()->dump(result);
6080 
6081     if (const auto display = getDefaultDisplayDeviceLocked()) {
6082         display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
6083                                                                           "undefinedRegion");
6084         StringAppendF(&result, "  orientation=%s, isPoweredOn=%d\n",
6085                       toCString(display->getOrientation()), display->isPoweredOn());
6086     }
6087     StringAppendF(&result, "  transaction-flags         : %08x\n", mTransactionFlags.load());
6088 
6089     if (const auto display = getDefaultDisplayDeviceLocked()) {
6090         std::string fps, xDpi, yDpi;
6091         if (const auto activeModePtr =
6092                     display->refreshRateSelector().getActiveMode().modePtr.get()) {
6093             fps = to_string(activeModePtr->getFps());
6094 
6095             const auto dpi = activeModePtr->getDpi();
6096             xDpi = base::StringPrintf("%.2f", dpi.x);
6097             yDpi = base::StringPrintf("%.2f", dpi.y);
6098         } else {
6099             fps = "unknown";
6100             xDpi = "unknown";
6101             yDpi = "unknown";
6102         }
6103         StringAppendF(&result,
6104                       "  refresh-rate              : %s\n"
6105                       "  x-dpi                     : %s\n"
6106                       "  y-dpi                     : %s\n",
6107                       fps.c_str(), xDpi.c_str(), yDpi.c_str());
6108     }
6109 
6110     StringAppendF(&result, "  transaction time: %f us\n", inTransactionDuration / 1000.0);
6111 
6112     /*
6113      * Tracing state
6114      */
6115     mLayerTracing.dump(result);
6116 
6117     result.append("\nTransaction tracing: ");
6118     if (mTransactionTracing) {
6119         result.append("enabled\n");
6120         mTransactionTracing->dump(result);
6121     } else {
6122         result.append("disabled\n");
6123     }
6124     result.push_back('\n');
6125 
6126     dumpHwcLayersMinidumpLocked(result);
6127 
6128     {
6129         DumpArgs plannerArgs;
6130         plannerArgs.add(); // first argument is ignored
6131         plannerArgs.add(String16("--layers"));
6132         dumpPlannerInfo(plannerArgs, result);
6133     }
6134 
6135     /*
6136      * Dump HWComposer state
6137      */
6138     colorizer.bold(result);
6139     result.append("h/w composer state:\n");
6140     colorizer.reset(result);
6141     const bool hwcDisabled = mDebugDisableHWC || mDebugFlashDelay;
6142     StringAppendF(&result, "  h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
6143     dumpHwc(result);
6144 
6145     /*
6146      * Dump gralloc state
6147      */
6148     const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
6149     alloc.dump(result);
6150 
6151     /*
6152      * Dump flag/property manager state
6153      */
6154     mFlagManager.dump(result);
6155 
6156     result.append(mTimeStats->miniDump());
6157     result.append("\n");
6158 
6159     result.append("Window Infos:\n");
6160     auto windowInfosDebug = mWindowInfosListenerInvoker->getDebugInfo();
6161     StringAppendF(&result, "  max send vsync id: %" PRId64 "\n",
6162                   ftl::to_underlying(windowInfosDebug.maxSendDelayVsyncId));
6163     StringAppendF(&result, "  max send delay (ns): %" PRId64 " ns\n",
6164                   windowInfosDebug.maxSendDelayDuration);
6165     StringAppendF(&result, "  unsent messages: %zu\n", windowInfosDebug.pendingMessageCount);
6166     result.append("\n");
6167 }
6168 
calculateColorMatrix(float saturation)6169 mat4 SurfaceFlinger::calculateColorMatrix(float saturation) {
6170     if (saturation == 1) {
6171         return mat4();
6172     }
6173 
6174     float3 luminance{0.213f, 0.715f, 0.072f};
6175     luminance *= 1.0f - saturation;
6176     mat4 saturationMatrix = mat4(vec4{luminance.r + saturation, luminance.r, luminance.r, 0.0f},
6177                                  vec4{luminance.g, luminance.g + saturation, luminance.g, 0.0f},
6178                                  vec4{luminance.b, luminance.b, luminance.b + saturation, 0.0f},
6179                                  vec4{0.0f, 0.0f, 0.0f, 1.0f});
6180     return saturationMatrix;
6181 }
6182 
updateColorMatrixLocked()6183 void SurfaceFlinger::updateColorMatrixLocked() {
6184     mat4 colorMatrix =
6185             mClientColorMatrix * calculateColorMatrix(mGlobalSaturationFactor) * mDaltonizer();
6186 
6187     if (mCurrentState.colorMatrix != colorMatrix) {
6188         mCurrentState.colorMatrix = colorMatrix;
6189         mCurrentState.colorMatrixChanged = true;
6190         setTransactionFlags(eTransactionNeeded);
6191     }
6192 }
6193 
CheckTransactCodeCredentials(uint32_t code)6194 status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
6195 #pragma clang diagnostic push
6196 #pragma clang diagnostic error "-Wswitch-enum"
6197     switch (static_cast<ISurfaceComposerTag>(code)) {
6198         // These methods should at minimum make sure that the client requested
6199         // access to SF.
6200         case GET_HDR_CAPABILITIES:
6201         case GET_AUTO_LOW_LATENCY_MODE_SUPPORT:
6202         case GET_GAME_CONTENT_TYPE_SUPPORT:
6203         case ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN: {
6204             // OVERRIDE_HDR_TYPES is used by CTS tests, which acquire the necessary
6205             // permission dynamically. Don't use the permission cache for this check.
6206             bool usePermissionCache = code != OVERRIDE_HDR_TYPES;
6207             if (!callingThreadHasUnscopedSurfaceFlingerAccess(usePermissionCache)) {
6208                 IPCThreadState* ipc = IPCThreadState::self();
6209                 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
6210                         ipc->getCallingPid(), ipc->getCallingUid());
6211                 return PERMISSION_DENIED;
6212             }
6213             return OK;
6214         }
6215         // The following calls are currently used by clients that do not
6216         // request necessary permissions. However, they do not expose any secret
6217         // information, so it is OK to pass them.
6218         case GET_ACTIVE_COLOR_MODE:
6219         case GET_ACTIVE_DISPLAY_MODE:
6220         case GET_DISPLAY_COLOR_MODES:
6221         case GET_DISPLAY_MODES:
6222         // Calling setTransactionState is safe, because you need to have been
6223         // granted a reference to Client* and Handle* to do anything with it.
6224         case SET_TRANSACTION_STATE: {
6225             // This is not sensitive information, so should not require permission control.
6226             return OK;
6227         }
6228         case BOOT_FINISHED:
6229         // Used by apps to hook Choreographer to SurfaceFlinger.
6230         case CREATE_DISPLAY_EVENT_CONNECTION:
6231         case CREATE_CONNECTION:
6232         case CREATE_DISPLAY:
6233         case DESTROY_DISPLAY:
6234         case GET_PRIMARY_PHYSICAL_DISPLAY_ID:
6235         case GET_PHYSICAL_DISPLAY_IDS:
6236         case GET_PHYSICAL_DISPLAY_TOKEN:
6237         case AUTHENTICATE_SURFACE:
6238         case SET_POWER_MODE:
6239         case GET_SUPPORTED_FRAME_TIMESTAMPS:
6240         case GET_DISPLAY_STATE:
6241         case GET_DISPLAY_STATS:
6242         case GET_STATIC_DISPLAY_INFO:
6243         case GET_DYNAMIC_DISPLAY_INFO:
6244         case GET_DISPLAY_NATIVE_PRIMARIES:
6245         case SET_ACTIVE_COLOR_MODE:
6246         case SET_BOOT_DISPLAY_MODE:
6247         case CLEAR_BOOT_DISPLAY_MODE:
6248         case GET_BOOT_DISPLAY_MODE_SUPPORT:
6249         case SET_AUTO_LOW_LATENCY_MODE:
6250         case SET_GAME_CONTENT_TYPE:
6251         case CAPTURE_LAYERS:
6252         case CAPTURE_DISPLAY:
6253         case CAPTURE_DISPLAY_BY_ID:
6254         case CLEAR_ANIMATION_FRAME_STATS:
6255         case GET_ANIMATION_FRAME_STATS:
6256         case OVERRIDE_HDR_TYPES:
6257         case ON_PULL_ATOM:
6258         case ENABLE_VSYNC_INJECTIONS:
6259         case INJECT_VSYNC:
6260         case GET_LAYER_DEBUG_INFO:
6261         case GET_COLOR_MANAGEMENT:
6262         case GET_COMPOSITION_PREFERENCE:
6263         case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
6264         case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
6265         case GET_DISPLAYED_CONTENT_SAMPLE:
6266         case GET_PROTECTED_CONTENT_SUPPORT:
6267         case IS_WIDE_COLOR_DISPLAY:
6268         case ADD_REGION_SAMPLING_LISTENER:
6269         case REMOVE_REGION_SAMPLING_LISTENER:
6270         case ADD_FPS_LISTENER:
6271         case REMOVE_FPS_LISTENER:
6272         case ADD_TUNNEL_MODE_ENABLED_LISTENER:
6273         case REMOVE_TUNNEL_MODE_ENABLED_LISTENER:
6274         case ADD_WINDOW_INFOS_LISTENER:
6275         case REMOVE_WINDOW_INFOS_LISTENER:
6276         case SET_DESIRED_DISPLAY_MODE_SPECS:
6277         case GET_DESIRED_DISPLAY_MODE_SPECS:
6278         case GET_DISPLAY_BRIGHTNESS_SUPPORT:
6279         case SET_DISPLAY_BRIGHTNESS:
6280         case ADD_HDR_LAYER_INFO_LISTENER:
6281         case REMOVE_HDR_LAYER_INFO_LISTENER:
6282         case NOTIFY_POWER_BOOST:
6283         case SET_GLOBAL_SHADOW_SETTINGS:
6284         case GET_DISPLAY_DECORATION_SUPPORT:
6285         case SET_FRAME_RATE:
6286         case SET_OVERRIDE_FRAME_RATE:
6287         case SET_FRAME_TIMELINE_INFO:
6288         case ADD_TRANSACTION_TRACE_LISTENER:
6289         case GET_GPU_CONTEXT_PRIORITY:
6290         case GET_MAX_ACQUIRED_BUFFER_COUNT:
6291             LOG_FATAL("Deprecated opcode: %d, migrated to AIDL", code);
6292             return PERMISSION_DENIED;
6293     }
6294 
6295     // These codes are used for the IBinder protocol to either interrogate the recipient
6296     // side of the transaction for its canonical interface descriptor or to dump its state.
6297     // We let them pass by default.
6298     if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
6299         code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
6300         code == IBinder::SYSPROPS_TRANSACTION) {
6301         return OK;
6302     }
6303     // Numbers from 1000 to 1042 are currently used for backdoors. The code
6304     // in onTransact verifies that the user is root, and has access to use SF.
6305     if (code >= 1000 && code <= 1042) {
6306         ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
6307         return OK;
6308     }
6309     ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
6310     return PERMISSION_DENIED;
6311 #pragma clang diagnostic pop
6312 }
6313 
onTransact(uint32_t code,const Parcel & data,Parcel * reply,uint32_t flags)6314 status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
6315                                     uint32_t flags) {
6316     if (const status_t error = CheckTransactCodeCredentials(code); error != OK) {
6317         return error;
6318     }
6319 
6320     status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
6321     if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
6322         CHECK_INTERFACE(ISurfaceComposer, data, reply);
6323         IPCThreadState* ipc = IPCThreadState::self();
6324         const int uid = ipc->getCallingUid();
6325         if (CC_UNLIKELY(uid != AID_SYSTEM
6326                 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
6327             const int pid = ipc->getCallingPid();
6328             ALOGE("Permission Denial: "
6329                     "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
6330             return PERMISSION_DENIED;
6331         }
6332         int n;
6333         switch (code) {
6334             case 1000: // Unused.
6335             case 1001:
6336                 return NAME_NOT_FOUND;
6337             case 1002: // Toggle flashing on surface damage.
6338                 if (const int delay = data.readInt32(); delay > 0) {
6339                     mDebugFlashDelay = delay;
6340                 } else {
6341                     mDebugFlashDelay = mDebugFlashDelay ? 0 : 1;
6342                 }
6343                 scheduleRepaint();
6344                 return NO_ERROR;
6345             case 1004: // Force composite ahead of next VSYNC.
6346             case 1006:
6347                 scheduleComposite(FrameHint::kActive);
6348                 return NO_ERROR;
6349             case 1005: { // Force commit ahead of next VSYNC.
6350                 Mutex::Autolock lock(mStateLock);
6351                 setTransactionFlags(eTransactionNeeded | eDisplayTransactionNeeded |
6352                                     eTraversalNeeded);
6353                 return NO_ERROR;
6354             }
6355             case 1007: // Unused.
6356                 return NAME_NOT_FOUND;
6357             case 1008: // Toggle forced GPU composition.
6358                 mDebugDisableHWC = data.readInt32() != 0;
6359                 scheduleRepaint();
6360                 return NO_ERROR;
6361             case 1009: // Toggle use of transform hint.
6362                 mDebugDisableTransformHint = data.readInt32() != 0;
6363                 scheduleRepaint();
6364                 return NO_ERROR;
6365             case 1010: // Interrogate.
6366                 reply->writeInt32(0);
6367                 reply->writeInt32(0);
6368                 reply->writeInt32(mDebugFlashDelay);
6369                 reply->writeInt32(0);
6370                 reply->writeInt32(mDebugDisableHWC);
6371                 return NO_ERROR;
6372             case 1013: // Unused.
6373                 return NAME_NOT_FOUND;
6374             case 1014: {
6375                 Mutex::Autolock _l(mStateLock);
6376                 // daltonize
6377                 n = data.readInt32();
6378                 switch (n % 10) {
6379                     case 1:
6380                         mDaltonizer.setType(ColorBlindnessType::Protanomaly);
6381                         break;
6382                     case 2:
6383                         mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
6384                         break;
6385                     case 3:
6386                         mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
6387                         break;
6388                     default:
6389                         mDaltonizer.setType(ColorBlindnessType::None);
6390                         break;
6391                 }
6392                 if (n >= 10) {
6393                     mDaltonizer.setMode(ColorBlindnessMode::Correction);
6394                 } else {
6395                     mDaltonizer.setMode(ColorBlindnessMode::Simulation);
6396                 }
6397 
6398                 updateColorMatrixLocked();
6399                 return NO_ERROR;
6400             }
6401             case 1015: {
6402                 Mutex::Autolock _l(mStateLock);
6403                 // apply a color matrix
6404                 n = data.readInt32();
6405                 if (n) {
6406                     // color matrix is sent as a column-major mat4 matrix
6407                     for (size_t i = 0 ; i < 4; i++) {
6408                         for (size_t j = 0; j < 4; j++) {
6409                             mClientColorMatrix[i][j] = data.readFloat();
6410                         }
6411                     }
6412                 } else {
6413                     mClientColorMatrix = mat4();
6414                 }
6415 
6416                 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
6417                 // the division by w in the fragment shader
6418                 float4 lastRow(transpose(mClientColorMatrix)[3]);
6419                 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
6420                     ALOGE("The color transform's last row must be (0, 0, 0, 1)");
6421                 }
6422 
6423                 updateColorMatrixLocked();
6424                 return NO_ERROR;
6425             }
6426             case 1016: { // Unused.
6427                 return NAME_NOT_FOUND;
6428             }
6429             case 1017: {
6430                 n = data.readInt32();
6431                 mForceFullDamage = n != 0;
6432                 return NO_ERROR;
6433             }
6434             case 1018: { // Modify Choreographer's duration
6435                 n = data.readInt32();
6436                 mScheduler->setDuration(mAppConnectionHandle, std::chrono::nanoseconds(n), 0ns);
6437                 return NO_ERROR;
6438             }
6439             case 1019: { // Modify SurfaceFlinger's duration
6440                 n = data.readInt32();
6441                 mScheduler->setDuration(mSfConnectionHandle, std::chrono::nanoseconds(n), 0ns);
6442                 return NO_ERROR;
6443             }
6444             case 1020: { // Unused
6445                 return NAME_NOT_FOUND;
6446             }
6447             case 1021: { // Disable HWC virtual displays
6448                 const bool enable = data.readInt32() != 0;
6449                 static_cast<void>(
6450                         mScheduler->schedule([this, enable] { enableHalVirtualDisplays(enable); }));
6451                 return NO_ERROR;
6452             }
6453             case 1022: { // Set saturation boost
6454                 Mutex::Autolock _l(mStateLock);
6455                 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
6456 
6457                 updateColorMatrixLocked();
6458                 return NO_ERROR;
6459             }
6460             case 1023: { // Set color mode.
6461                 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
6462 
6463                 if (int32_t colorMode; data.readInt32(&colorMode) == NO_ERROR) {
6464                     mForceColorMode = static_cast<ui::ColorMode>(colorMode);
6465                 }
6466                 scheduleRepaint();
6467                 return NO_ERROR;
6468             }
6469             // Deprecate, use 1030 to check whether the device is color managed.
6470             case 1024: {
6471                 return NAME_NOT_FOUND;
6472             }
6473             case 1025: { // Set layer tracing
6474                 n = data.readInt32();
6475                 bool tracingEnabledChanged;
6476                 if (n == 1) {
6477                     int64_t fixedStartingTime = data.readInt64();
6478                     ALOGD("LayerTracing enabled");
6479                     tracingEnabledChanged = mLayerTracing.enable();
6480                     if (tracingEnabledChanged) {
6481                         const TimePoint startingTime = fixedStartingTime
6482                                 ? TimePoint::fromNs(fixedStartingTime)
6483                                 : TimePoint::now();
6484 
6485                         mScheduler
6486                                 ->schedule([this, startingTime]() FTL_FAKE_GUARD(
6487                                                    mStateLock) FTL_FAKE_GUARD(kMainThreadContext) {
6488                                     constexpr bool kVisibleRegionDirty = true;
6489                                     addToLayerTracing(kVisibleRegionDirty, startingTime,
6490                                                       mLastCommittedVsyncId);
6491                                 })
6492                                 .wait();
6493                     }
6494                 } else if (n == 2) {
6495                     std::string filename = std::string(data.readCString());
6496                     ALOGD("LayerTracing disabled. Trace wrote to %s", filename.c_str());
6497                     tracingEnabledChanged = mLayerTracing.disable(filename.c_str());
6498                 } else {
6499                     ALOGD("LayerTracing disabled");
6500                     tracingEnabledChanged = mLayerTracing.disable();
6501                 }
6502                 mTracingEnabledChanged = tracingEnabledChanged;
6503                 reply->writeInt32(NO_ERROR);
6504                 return NO_ERROR;
6505             }
6506             case 1026: { // Get layer tracing status
6507                 reply->writeBool(mLayerTracing.isEnabled());
6508                 return NO_ERROR;
6509             }
6510             // Is a DisplayColorSetting supported?
6511             case 1027: {
6512                 const auto display = getDefaultDisplayDevice();
6513                 if (!display) {
6514                     return NAME_NOT_FOUND;
6515                 }
6516 
6517                 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
6518                 switch (setting) {
6519                     case DisplayColorSetting::kManaged:
6520                         reply->writeBool(useColorManagement);
6521                         break;
6522                     case DisplayColorSetting::kUnmanaged:
6523                         reply->writeBool(true);
6524                         break;
6525                     case DisplayColorSetting::kEnhanced:
6526                         reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
6527                         break;
6528                     default: // vendor display color setting
6529                         reply->writeBool(
6530                                 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
6531                         break;
6532                 }
6533                 return NO_ERROR;
6534             }
6535             case 1028: { // Unused.
6536                 return NAME_NOT_FOUND;
6537             }
6538             // Set buffer size for SF tracing (value in KB)
6539             case 1029: {
6540                 n = data.readInt32();
6541                 if (n <= 0 || n > MAX_TRACING_MEMORY) {
6542                     ALOGW("Invalid buffer size: %d KB", n);
6543                     reply->writeInt32(BAD_VALUE);
6544                     return BAD_VALUE;
6545                 }
6546 
6547                 ALOGD("Updating trace buffer to %d KB", n);
6548                 mLayerTracing.setBufferSize(n * 1024);
6549                 reply->writeInt32(NO_ERROR);
6550                 return NO_ERROR;
6551             }
6552             // Is device color managed?
6553             case 1030: {
6554                 reply->writeBool(useColorManagement);
6555                 return NO_ERROR;
6556             }
6557             // Override default composition data space
6558             // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
6559             // && adb shell stop zygote && adb shell start zygote
6560             // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
6561             // adb shell stop zygote && adb shell start zygote
6562             case 1031: {
6563                 Mutex::Autolock _l(mStateLock);
6564                 n = data.readInt32();
6565                 if (n) {
6566                     n = data.readInt32();
6567                     if (n) {
6568                         Dataspace dataspace = static_cast<Dataspace>(n);
6569                         if (!validateCompositionDataspace(dataspace)) {
6570                             return BAD_VALUE;
6571                         }
6572                         mDefaultCompositionDataspace = dataspace;
6573                     }
6574                     n = data.readInt32();
6575                     if (n) {
6576                         Dataspace dataspace = static_cast<Dataspace>(n);
6577                         if (!validateCompositionDataspace(dataspace)) {
6578                             return BAD_VALUE;
6579                         }
6580                         mWideColorGamutCompositionDataspace = dataspace;
6581                     }
6582                 } else {
6583                     // restore composition data space.
6584                     mDefaultCompositionDataspace = defaultCompositionDataspace;
6585                     mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
6586                 }
6587                 return NO_ERROR;
6588             }
6589             // Set trace flags
6590             case 1033: {
6591                 n = data.readUint32();
6592                 ALOGD("Updating trace flags to 0x%x", n);
6593                 mLayerTracing.setTraceFlags(n);
6594                 reply->writeInt32(NO_ERROR);
6595                 return NO_ERROR;
6596             }
6597             case 1034: {
6598                 auto future = mScheduler->schedule(
6599                         [&]() FTL_FAKE_GUARD(mStateLock) FTL_FAKE_GUARD(kMainThreadContext) {
6600                             switch (n = data.readInt32()) {
6601                                 case 0:
6602                                 case 1:
6603                                     enableRefreshRateOverlay(static_cast<bool>(n));
6604                                     break;
6605                                 default:
6606                                     reply->writeBool(isRefreshRateOverlayEnabled());
6607                             }
6608                         });
6609 
6610                 future.wait();
6611                 return NO_ERROR;
6612             }
6613             case 1035: {
6614                 const int modeId = data.readInt32();
6615 
6616                 const auto display = [&]() -> sp<IBinder> {
6617                     uint64_t value;
6618                     if (data.readUint64(&value) != NO_ERROR) {
6619                         return getDefaultDisplayDevice()->getDisplayToken().promote();
6620                     }
6621 
6622                     if (const auto id = DisplayId::fromValue<PhysicalDisplayId>(value)) {
6623                         return getPhysicalDisplayToken(*id);
6624                     }
6625 
6626                     ALOGE("Invalid physical display ID");
6627                     return nullptr;
6628                 }();
6629 
6630                 mDebugDisplayModeSetByBackdoor = false;
6631                 const status_t result = setActiveModeFromBackdoor(display, DisplayModeId{modeId});
6632                 mDebugDisplayModeSetByBackdoor = result == NO_ERROR;
6633                 return result;
6634             }
6635             // Turn on/off frame rate flexibility mode. When turned on it overrides the display
6636             // manager frame rate policy a new policy which allows switching between all refresh
6637             // rates.
6638             case 1036: {
6639                 if (data.readInt32() > 0) { // turn on
6640                     return mScheduler
6641                             ->schedule([this]() FTL_FAKE_GUARD(kMainThreadContext) {
6642                                 const auto display =
6643                                         FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
6644 
6645                                 // This is a little racy, but not in a way that hurts anything. As
6646                                 // we grab the defaultMode from the display manager policy, we could
6647                                 // be setting a new display manager policy, leaving us using a stale
6648                                 // defaultMode. The defaultMode doesn't matter for the override
6649                                 // policy though, since we set allowGroupSwitching to true, so it's
6650                                 // not a problem.
6651                                 scheduler::RefreshRateSelector::OverridePolicy overridePolicy;
6652                                 overridePolicy.defaultMode = display->refreshRateSelector()
6653                                                                      .getDisplayManagerPolicy()
6654                                                                      .defaultMode;
6655                                 overridePolicy.allowGroupSwitching = true;
6656                                 return setDesiredDisplayModeSpecsInternal(display, overridePolicy);
6657                             })
6658                             .get();
6659                 } else { // turn off
6660                     return mScheduler
6661                             ->schedule([this]() FTL_FAKE_GUARD(kMainThreadContext) {
6662                                 const auto display =
6663                                         FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
6664                                 return setDesiredDisplayModeSpecsInternal(
6665                                         display,
6666                                         scheduler::RefreshRateSelector::NoOverridePolicy{});
6667                             })
6668                             .get();
6669                 }
6670             }
6671             // Inject a hotplug connected event for the primary display. This will deallocate and
6672             // reallocate the display state including framebuffers.
6673             case 1037: {
6674                 const hal::HWDisplayId hwcId =
6675                         (Mutex::Autolock(mStateLock), getHwComposer().getPrimaryHwcDisplayId());
6676 
6677                 onComposerHalHotplug(hwcId, hal::Connection::CONNECTED);
6678                 return NO_ERROR;
6679             }
6680             // Modify the max number of display frames stored within FrameTimeline
6681             case 1038: {
6682                 n = data.readInt32();
6683                 if (n < 0 || n > MAX_ALLOWED_DISPLAY_FRAMES) {
6684                     ALOGW("Invalid max size. Maximum allowed is %d", MAX_ALLOWED_DISPLAY_FRAMES);
6685                     return BAD_VALUE;
6686                 }
6687                 if (n == 0) {
6688                     // restore to default
6689                     mFrameTimeline->reset();
6690                     return NO_ERROR;
6691                 }
6692                 mFrameTimeline->setMaxDisplayFrames(n);
6693                 return NO_ERROR;
6694             }
6695             case 1039: {
6696                 PhysicalDisplayId displayId = [&]() {
6697                     Mutex::Autolock lock(mStateLock);
6698                     return getDefaultDisplayDeviceLocked()->getPhysicalId();
6699                 }();
6700 
6701                 auto inUid = static_cast<uid_t>(data.readInt32());
6702                 const auto refreshRate = data.readFloat();
6703                 mScheduler->setPreferredRefreshRateForUid(FrameRateOverride{inUid, refreshRate});
6704                 mScheduler->onFrameRateOverridesChanged(mAppConnectionHandle, displayId);
6705                 return NO_ERROR;
6706             }
6707             // Toggle caching feature
6708             // First argument is an int32 - nonzero enables caching and zero disables caching
6709             // Second argument is an optional uint64 - if present, then limits enabling/disabling
6710             // caching to a particular physical display
6711             case 1040: {
6712                 auto future = mScheduler->schedule([&] {
6713                     n = data.readInt32();
6714                     std::optional<PhysicalDisplayId> inputId = std::nullopt;
6715                     if (uint64_t inputDisplayId; data.readUint64(&inputDisplayId) == NO_ERROR) {
6716                         inputId = DisplayId::fromValue<PhysicalDisplayId>(inputDisplayId);
6717                         if (!inputId || getPhysicalDisplayToken(*inputId)) {
6718                             ALOGE("No display with id: %" PRIu64, inputDisplayId);
6719                             return NAME_NOT_FOUND;
6720                         }
6721                     }
6722                     {
6723                         Mutex::Autolock lock(mStateLock);
6724                         mLayerCachingEnabled = n != 0;
6725                         for (const auto& [_, display] : mDisplays) {
6726                             if (!inputId || *inputId == display->getPhysicalId()) {
6727                                 display->enableLayerCaching(mLayerCachingEnabled);
6728                             }
6729                         }
6730                     }
6731                     return OK;
6732                 });
6733 
6734                 if (const status_t error = future.get(); error != OK) {
6735                     return error;
6736                 }
6737                 scheduleRepaint();
6738                 return NO_ERROR;
6739             }
6740             case 1041: { // Transaction tracing
6741                 if (mTransactionTracing) {
6742                     if (data.readInt32()) {
6743                         // Transaction tracing is always running but allow the user to temporarily
6744                         // increase the buffer when actively debugging.
6745                         mTransactionTracing->setBufferSize(
6746                                 TransactionTracing::ACTIVE_TRACING_BUFFER_SIZE);
6747                     } else {
6748                         TransactionTraceWriter::getInstance().invoke("", /* overwrite= */ true);
6749                         mTransactionTracing->setBufferSize(
6750                                 TransactionTracing::CONTINUOUS_TRACING_BUFFER_SIZE);
6751                     }
6752                 }
6753                 reply->writeInt32(NO_ERROR);
6754                 return NO_ERROR;
6755             }
6756             case 1042: { // Write layers trace or transaction trace to file
6757                 if (mTransactionTracing) {
6758                     mTransactionTracing->writeToFile();
6759                 }
6760                 if (mLayerTracingEnabled) {
6761                     mLayerTracing.writeToFile();
6762                 }
6763                 reply->writeInt32(NO_ERROR);
6764                 return NO_ERROR;
6765             }
6766         }
6767     }
6768     return err;
6769 }
6770 
kernelTimerChanged(bool expired)6771 void SurfaceFlinger::kernelTimerChanged(bool expired) {
6772     static bool updateOverlay =
6773             property_get_bool("debug.sf.kernel_idle_timer_update_overlay", true);
6774     if (!updateOverlay) return;
6775 
6776     // Update the overlay on the main thread to avoid race conditions with
6777     // RefreshRateSelector::getActiveMode
6778     static_cast<void>(mScheduler->schedule([=] {
6779         const auto display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked());
6780         if (!display) {
6781             ALOGW("%s: default display is null", __func__);
6782             return;
6783         }
6784         if (!display->isRefreshRateOverlayEnabled()) return;
6785 
6786         const auto desiredActiveMode = display->getDesiredActiveMode();
6787         const std::optional<DisplayModeId> desiredModeId = desiredActiveMode
6788                 ? std::make_optional(desiredActiveMode->modeOpt->modePtr->getId())
6789 
6790                 : std::nullopt;
6791 
6792         const bool timerExpired = mKernelIdleTimerEnabled && expired;
6793 
6794         if (display->onKernelTimerChanged(desiredModeId, timerExpired)) {
6795             mScheduler->scheduleFrame();
6796         }
6797     }));
6798 }
6799 
6800 std::pair<std::optional<KernelIdleTimerController>, std::chrono::milliseconds>
getKernelIdleTimerProperties(DisplayId displayId)6801 SurfaceFlinger::getKernelIdleTimerProperties(DisplayId displayId) {
6802     const bool isKernelIdleTimerHwcSupported = getHwComposer().getComposer()->isSupported(
6803             android::Hwc2::Composer::OptionalFeature::KernelIdleTimer);
6804     const auto timeout = getIdleTimerTimeout(displayId);
6805     if (isKernelIdleTimerHwcSupported) {
6806         if (const auto id = PhysicalDisplayId::tryCast(displayId);
6807             getHwComposer().hasDisplayIdleTimerCapability(*id)) {
6808             // In order to decide if we can use the HWC api for idle timer
6809             // we query DisplayCapability::DISPLAY_IDLE_TIMER directly on the composer
6810             // without relying on hasDisplayCapability.
6811             // hasDisplayCapability relies on DisplayCapabilities
6812             // which are updated after we set the PowerMode::ON.
6813             // DISPLAY_IDLE_TIMER is a display driver property
6814             // and is available before the PowerMode::ON
6815             return {KernelIdleTimerController::HwcApi, timeout};
6816         }
6817         return {std::nullopt, timeout};
6818     }
6819     if (getKernelIdleTimerSyspropConfig(displayId)) {
6820         return {KernelIdleTimerController::Sysprop, timeout};
6821     }
6822 
6823     return {std::nullopt, timeout};
6824 }
6825 
updateKernelIdleTimer(std::chrono::milliseconds timeout,KernelIdleTimerController controller,PhysicalDisplayId displayId)6826 void SurfaceFlinger::updateKernelIdleTimer(std::chrono::milliseconds timeout,
6827                                            KernelIdleTimerController controller,
6828                                            PhysicalDisplayId displayId) {
6829     switch (controller) {
6830         case KernelIdleTimerController::HwcApi: {
6831             getHwComposer().setIdleTimerEnabled(displayId, timeout);
6832             break;
6833         }
6834         case KernelIdleTimerController::Sysprop: {
6835             base::SetProperty(KERNEL_IDLE_TIMER_PROP, timeout > 0ms ? "true" : "false");
6836             break;
6837         }
6838     }
6839 }
6840 
toggleKernelIdleTimer()6841 void SurfaceFlinger::toggleKernelIdleTimer() {
6842     using KernelIdleTimerAction = scheduler::RefreshRateSelector::KernelIdleTimerAction;
6843 
6844     const auto display = getDefaultDisplayDeviceLocked();
6845     if (!display) {
6846         ALOGW("%s: default display is null", __func__);
6847         return;
6848     }
6849 
6850     // If the support for kernel idle timer is disabled for the active display,
6851     // don't do anything.
6852     const std::optional<KernelIdleTimerController> kernelIdleTimerController =
6853             display->refreshRateSelector().kernelIdleTimerController();
6854     if (!kernelIdleTimerController.has_value()) {
6855         return;
6856     }
6857 
6858     const KernelIdleTimerAction action = display->refreshRateSelector().getIdleTimerAction();
6859 
6860     switch (action) {
6861         case KernelIdleTimerAction::TurnOff:
6862             if (mKernelIdleTimerEnabled) {
6863                 ATRACE_INT("KernelIdleTimer", 0);
6864                 std::chrono::milliseconds constexpr kTimerDisabledTimeout = 0ms;
6865                 updateKernelIdleTimer(kTimerDisabledTimeout, kernelIdleTimerController.value(),
6866                                       display->getPhysicalId());
6867                 mKernelIdleTimerEnabled = false;
6868             }
6869             break;
6870         case KernelIdleTimerAction::TurnOn:
6871             if (!mKernelIdleTimerEnabled) {
6872                 ATRACE_INT("KernelIdleTimer", 1);
6873                 const std::chrono::milliseconds timeout =
6874                         display->refreshRateSelector().getIdleTimerTimeout();
6875                 updateKernelIdleTimer(timeout, kernelIdleTimerController.value(),
6876                                       display->getPhysicalId());
6877                 mKernelIdleTimerEnabled = true;
6878             }
6879             break;
6880     }
6881 }
6882 
6883 // A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
6884 class WindowDisconnector {
6885 public:
WindowDisconnector(ANativeWindow * window,int api)6886     WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
~WindowDisconnector()6887     ~WindowDisconnector() {
6888         native_window_api_disconnect(mWindow, mApi);
6889     }
6890 
6891 private:
6892     ANativeWindow* mWindow;
6893     const int mApi;
6894 };
6895 
hasCaptureBlackoutContentPermission()6896 static bool hasCaptureBlackoutContentPermission() {
6897     IPCThreadState* ipc = IPCThreadState::self();
6898     const int pid = ipc->getCallingPid();
6899     const int uid = ipc->getCallingUid();
6900     return uid == AID_GRAPHICS || uid == AID_SYSTEM ||
6901             PermissionCache::checkPermission(sCaptureBlackoutContent, pid, uid);
6902 }
6903 
validateScreenshotPermissions(const CaptureArgs & captureArgs)6904 static status_t validateScreenshotPermissions(const CaptureArgs& captureArgs) {
6905     IPCThreadState* ipc = IPCThreadState::self();
6906     const int pid = ipc->getCallingPid();
6907     const int uid = ipc->getCallingUid();
6908     if (uid == AID_GRAPHICS || PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
6909         return OK;
6910     }
6911 
6912     // If the caller doesn't have the correct permissions but is only attempting to screenshot
6913     // itself, we allow it to continue.
6914     if (captureArgs.uid == uid) {
6915         return OK;
6916     }
6917 
6918     ALOGE("Permission Denial: can't take screenshot pid=%d, uid=%d", pid, uid);
6919     return PERMISSION_DENIED;
6920 }
6921 
setSchedFifo(bool enabled)6922 status_t SurfaceFlinger::setSchedFifo(bool enabled) {
6923     static constexpr int kFifoPriority = 2;
6924     static constexpr int kOtherPriority = 0;
6925 
6926     struct sched_param param = {0};
6927     int sched_policy;
6928     if (enabled) {
6929         sched_policy = SCHED_FIFO;
6930         param.sched_priority = kFifoPriority;
6931     } else {
6932         sched_policy = SCHED_OTHER;
6933         param.sched_priority = kOtherPriority;
6934     }
6935 
6936     if (sched_setscheduler(0, sched_policy, &param) != 0) {
6937         return -errno;
6938     }
6939 
6940     return NO_ERROR;
6941 }
6942 
setSchedAttr(bool enabled)6943 status_t SurfaceFlinger::setSchedAttr(bool enabled) {
6944     static const unsigned int kUclampMin =
6945             base::GetUintProperty<unsigned int>("ro.surface_flinger.uclamp.min", 0U);
6946 
6947     if (!kUclampMin) {
6948         // uclamp.min set to 0 (default), skip setting
6949         return NO_ERROR;
6950     }
6951 
6952     // Currently, there is no wrapper in bionic: b/183240349.
6953     struct sched_attr {
6954         uint32_t size;
6955         uint32_t sched_policy;
6956         uint64_t sched_flags;
6957         int32_t sched_nice;
6958         uint32_t sched_priority;
6959         uint64_t sched_runtime;
6960         uint64_t sched_deadline;
6961         uint64_t sched_period;
6962         uint32_t sched_util_min;
6963         uint32_t sched_util_max;
6964     };
6965 
6966     sched_attr attr = {};
6967     attr.size = sizeof(attr);
6968 
6969     attr.sched_flags = (SCHED_FLAG_KEEP_ALL | SCHED_FLAG_UTIL_CLAMP);
6970     attr.sched_util_min = enabled ? kUclampMin : 0;
6971     attr.sched_util_max = 1024;
6972 
6973     if (syscall(__NR_sched_setattr, 0, &attr, 0)) {
6974         return -errno;
6975     }
6976 
6977     return NO_ERROR;
6978 }
6979 
6980 namespace {
6981 
pickBestDataspace(ui::Dataspace requestedDataspace,const DisplayDevice * display,bool capturingHdrLayers,bool hintForSeamlessTransition)6982 ui::Dataspace pickBestDataspace(ui::Dataspace requestedDataspace, const DisplayDevice* display,
6983                                 bool capturingHdrLayers, bool hintForSeamlessTransition) {
6984     if (requestedDataspace != ui::Dataspace::UNKNOWN || display == nullptr) {
6985         return requestedDataspace;
6986     }
6987 
6988     const auto& state = display->getCompositionDisplay()->getState();
6989 
6990     const auto dataspaceForColorMode = ui::pickDataspaceFor(state.colorMode);
6991 
6992     // TODO: Enable once HDR screenshots are ready.
6993     if constexpr (/* DISABLES CODE */ (false)) {
6994         // For now since we only support 8-bit screenshots, just use HLG and
6995         // assume that 1.0 >= display max luminance. This isn't quite as future
6996         // proof as PQ is, but is good enough.
6997         // Consider using PQ once we support 16-bit screenshots and we're able
6998         // to consistently supply metadata to image encoders.
6999         return ui::Dataspace::BT2020_HLG;
7000     }
7001 
7002     return dataspaceForColorMode;
7003 }
7004 
7005 } // namespace
7006 
captureDisplay(const DisplayCaptureArgs & args,const sp<IScreenCaptureListener> & captureListener)7007 status_t SurfaceFlinger::captureDisplay(const DisplayCaptureArgs& args,
7008                                         const sp<IScreenCaptureListener>& captureListener) {
7009     ATRACE_CALL();
7010 
7011     status_t validate = validateScreenshotPermissions(args);
7012     if (validate != OK) {
7013         return validate;
7014     }
7015 
7016     if (!args.displayToken) return BAD_VALUE;
7017 
7018     wp<const DisplayDevice> displayWeak;
7019     ui::LayerStack layerStack;
7020     ui::Size reqSize(args.width, args.height);
7021     std::unordered_set<uint32_t> excludeLayerIds;
7022     {
7023         Mutex::Autolock lock(mStateLock);
7024         sp<DisplayDevice> display = getDisplayDeviceLocked(args.displayToken);
7025         if (!display) return NAME_NOT_FOUND;
7026         displayWeak = display;
7027         layerStack = display->getLayerStack();
7028 
7029         // set the requested width/height to the logical display layer stack rect size by default
7030         if (args.width == 0 || args.height == 0) {
7031             reqSize = display->getLayerStackSpaceRect().getSize();
7032         }
7033 
7034         for (const auto& handle : args.excludeHandles) {
7035             uint32_t excludeLayer = LayerHandle::getLayerId(handle);
7036             if (excludeLayer != UNASSIGNED_LAYER_ID) {
7037                 excludeLayerIds.emplace(excludeLayer);
7038             } else {
7039                 ALOGW("Invalid layer handle passed as excludeLayer to captureDisplay");
7040                 return NAME_NOT_FOUND;
7041             }
7042         }
7043     }
7044 
7045     RenderAreaFuture renderAreaFuture = ftl::defer([=] {
7046         return DisplayRenderArea::create(displayWeak, args.sourceCrop, reqSize, args.dataspace,
7047                                          args.useIdentityTransform, args.hintForSeamlessTransition,
7048                                          args.captureSecureLayers);
7049     });
7050 
7051     GetLayerSnapshotsFunction getLayerSnapshots;
7052     if (mLayerLifecycleManagerEnabled) {
7053         getLayerSnapshots =
7054                 getLayerSnapshotsForScreenshots(layerStack, args.uid, std::move(excludeLayerIds));
7055     } else {
7056         auto traverseLayers = [this, args, excludeLayerIds,
7057                                layerStack](const LayerVector::Visitor& visitor) {
7058             traverseLayersInLayerStack(layerStack, args.uid, std::move(excludeLayerIds), visitor);
7059         };
7060         getLayerSnapshots = RenderArea::fromTraverseLayersLambda(traverseLayers);
7061     }
7062 
7063     auto future = captureScreenCommon(std::move(renderAreaFuture), getLayerSnapshots, reqSize,
7064                                       args.pixelFormat, args.allowProtected, args.grayscale,
7065                                       captureListener);
7066     return fenceStatus(future.get());
7067 }
7068 
captureDisplay(DisplayId displayId,const sp<IScreenCaptureListener> & captureListener)7069 status_t SurfaceFlinger::captureDisplay(DisplayId displayId,
7070                                         const sp<IScreenCaptureListener>& captureListener) {
7071     ui::LayerStack layerStack;
7072     wp<const DisplayDevice> displayWeak;
7073     ui::Size size;
7074     {
7075         Mutex::Autolock lock(mStateLock);
7076 
7077         const auto display = getDisplayDeviceLocked(displayId);
7078         if (!display) {
7079             return NAME_NOT_FOUND;
7080         }
7081 
7082         displayWeak = display;
7083         layerStack = display->getLayerStack();
7084         size = display->getLayerStackSpaceRect().getSize();
7085     }
7086 
7087     RenderAreaFuture renderAreaFuture = ftl::defer([=] {
7088         return DisplayRenderArea::create(displayWeak, Rect(), size, ui::Dataspace::UNKNOWN,
7089                                          false /* useIdentityTransform */,
7090                                          false /* hintForSeamlessTransition */,
7091                                          false /* captureSecureLayers */);
7092     });
7093 
7094     GetLayerSnapshotsFunction getLayerSnapshots;
7095     if (mLayerLifecycleManagerEnabled) {
7096         getLayerSnapshots = getLayerSnapshotsForScreenshots(layerStack, CaptureArgs::UNSET_UID,
7097                                                             /*snapshotFilterFn=*/nullptr);
7098     } else {
7099         auto traverseLayers = [this, layerStack](const LayerVector::Visitor& visitor) {
7100             traverseLayersInLayerStack(layerStack, CaptureArgs::UNSET_UID, {}, visitor);
7101         };
7102         getLayerSnapshots = RenderArea::fromTraverseLayersLambda(traverseLayers);
7103     }
7104 
7105     if (captureListener == nullptr) {
7106         ALOGE("capture screen must provide a capture listener callback");
7107         return BAD_VALUE;
7108     }
7109 
7110     constexpr bool kAllowProtected = false;
7111     constexpr bool kGrayscale = false;
7112 
7113     auto future = captureScreenCommon(std::move(renderAreaFuture), getLayerSnapshots, size,
7114                                       ui::PixelFormat::RGBA_8888, kAllowProtected, kGrayscale,
7115                                       captureListener);
7116     return fenceStatus(future.get());
7117 }
7118 
captureLayers(const LayerCaptureArgs & args,const sp<IScreenCaptureListener> & captureListener)7119 status_t SurfaceFlinger::captureLayers(const LayerCaptureArgs& args,
7120                                        const sp<IScreenCaptureListener>& captureListener) {
7121     ATRACE_CALL();
7122 
7123     status_t validate = validateScreenshotPermissions(args);
7124     if (validate != OK) {
7125         return validate;
7126     }
7127 
7128     ui::Size reqSize;
7129     sp<Layer> parent;
7130     Rect crop(args.sourceCrop);
7131     std::unordered_set<uint32_t> excludeLayerIds;
7132     ui::Dataspace dataspace = args.dataspace;
7133 
7134     // Call this before holding mStateLock to avoid any deadlocking.
7135     bool canCaptureBlackoutContent = hasCaptureBlackoutContentPermission();
7136 
7137     {
7138         Mutex::Autolock lock(mStateLock);
7139 
7140         parent = LayerHandle::getLayer(args.layerHandle);
7141         if (parent == nullptr) {
7142             ALOGE("captureLayers called with an invalid or removed parent");
7143             return NAME_NOT_FOUND;
7144         }
7145 
7146         if (!canCaptureBlackoutContent &&
7147             parent->getDrawingState().flags & layer_state_t::eLayerSecure) {
7148             ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
7149             return PERMISSION_DENIED;
7150         }
7151 
7152         Rect parentSourceBounds = parent->getCroppedBufferSize(parent->getDrawingState());
7153         if (args.sourceCrop.width() <= 0) {
7154             crop.left = 0;
7155             crop.right = parentSourceBounds.getWidth();
7156         }
7157 
7158         if (args.sourceCrop.height() <= 0) {
7159             crop.top = 0;
7160             crop.bottom = parentSourceBounds.getHeight();
7161         }
7162 
7163         if (crop.isEmpty() || args.frameScaleX <= 0.0f || args.frameScaleY <= 0.0f) {
7164             // Error out if the layer has no source bounds (i.e. they are boundless) and a source
7165             // crop was not specified, or an invalid frame scale was provided.
7166             return BAD_VALUE;
7167         }
7168         reqSize = ui::Size(crop.width() * args.frameScaleX, crop.height() * args.frameScaleY);
7169 
7170         for (const auto& handle : args.excludeHandles) {
7171             uint32_t excludeLayer = LayerHandle::getLayerId(handle);
7172             if (excludeLayer != UNASSIGNED_LAYER_ID) {
7173                 excludeLayerIds.emplace(excludeLayer);
7174             } else {
7175                 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
7176                 return NAME_NOT_FOUND;
7177             }
7178         }
7179     } // mStateLock
7180 
7181     // really small crop or frameScale
7182     if (reqSize.width <= 0 || reqSize.height <= 0) {
7183         ALOGW("Failed to captureLayes: crop or scale too small");
7184         return BAD_VALUE;
7185     }
7186 
7187     bool childrenOnly = args.childrenOnly;
7188     RenderAreaFuture renderAreaFuture = ftl::defer([=]() -> std::unique_ptr<RenderArea> {
7189         ui::Transform layerTransform;
7190         Rect layerBufferSize;
7191         if (mLayerLifecycleManagerEnabled) {
7192             frontend::LayerSnapshot* snapshot =
7193                     mLayerSnapshotBuilder.getSnapshot(parent->getSequence());
7194             if (!snapshot) {
7195                 ALOGW("Couldn't find layer snapshot for %d", parent->getSequence());
7196             } else {
7197                 layerTransform = snapshot->localTransform;
7198                 layerBufferSize = snapshot->bufferSize;
7199             }
7200         } else {
7201             layerTransform = parent->getTransform();
7202             layerBufferSize = parent->getBufferSize(parent->getDrawingState());
7203         }
7204 
7205         return std::make_unique<LayerRenderArea>(*this, parent, crop, reqSize, dataspace,
7206                                                  childrenOnly, args.captureSecureLayers,
7207                                                  layerTransform, layerBufferSize,
7208                                                  args.hintForSeamlessTransition);
7209     });
7210     GetLayerSnapshotsFunction getLayerSnapshots;
7211     if (mLayerLifecycleManagerEnabled) {
7212         std::optional<FloatRect> parentCrop = std::nullopt;
7213         if (args.childrenOnly) {
7214             parentCrop = crop.isEmpty() ? FloatRect(0, 0, reqSize.width, reqSize.height)
7215                                         : crop.toFloatRect();
7216         }
7217 
7218         getLayerSnapshots = getLayerSnapshotsForScreenshots(parent->sequence, args.uid,
7219                                                             std::move(excludeLayerIds),
7220                                                             args.childrenOnly, parentCrop);
7221     } else {
7222         auto traverseLayers = [parent, args, excludeLayerIds](const LayerVector::Visitor& visitor) {
7223             parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
7224                 if (!layer->isVisible()) {
7225                     return;
7226                 } else if (args.childrenOnly && layer == parent.get()) {
7227                     return;
7228                 } else if (args.uid != CaptureArgs::UNSET_UID && args.uid != layer->getOwnerUid()) {
7229                     return;
7230                 }
7231 
7232                 auto p = sp<Layer>::fromExisting(layer);
7233                 while (p != nullptr) {
7234                     if (excludeLayerIds.count(p->sequence) != 0) {
7235                         return;
7236                     }
7237                     p = p->getParent();
7238                 }
7239 
7240                 visitor(layer);
7241             });
7242         };
7243         getLayerSnapshots = RenderArea::fromTraverseLayersLambda(traverseLayers);
7244     }
7245 
7246     if (captureListener == nullptr) {
7247         ALOGE("capture screen must provide a capture listener callback");
7248         return BAD_VALUE;
7249     }
7250 
7251     auto future = captureScreenCommon(std::move(renderAreaFuture), getLayerSnapshots, reqSize,
7252                                       args.pixelFormat, args.allowProtected, args.grayscale,
7253                                       captureListener);
7254     return fenceStatus(future.get());
7255 }
7256 
captureScreenCommon(RenderAreaFuture renderAreaFuture,GetLayerSnapshotsFunction getLayerSnapshots,ui::Size bufferSize,ui::PixelFormat reqPixelFormat,bool allowProtected,bool grayscale,const sp<IScreenCaptureListener> & captureListener)7257 ftl::SharedFuture<FenceResult> SurfaceFlinger::captureScreenCommon(
7258         RenderAreaFuture renderAreaFuture, GetLayerSnapshotsFunction getLayerSnapshots,
7259         ui::Size bufferSize, ui::PixelFormat reqPixelFormat, bool allowProtected, bool grayscale,
7260         const sp<IScreenCaptureListener>& captureListener) {
7261     ATRACE_CALL();
7262 
7263     if (exceedsMaxRenderTargetSize(bufferSize.getWidth(), bufferSize.getHeight())) {
7264         ALOGE("Attempted to capture screen with size (%" PRId32 ", %" PRId32
7265               ") that exceeds render target size limit.",
7266               bufferSize.getWidth(), bufferSize.getHeight());
7267         return ftl::yield<FenceResult>(base::unexpected(BAD_VALUE)).share();
7268     }
7269 
7270     // Loop over all visible layers to see whether there's any protected layer. A protected layer is
7271     // typically a layer with DRM contents, or have the GRALLOC_USAGE_PROTECTED set on the buffer.
7272     // A protected layer has no implication on whether it's secure, which is explicitly set by
7273     // application to avoid being screenshot or drawn via unsecure display.
7274     const bool supportsProtected = getRenderEngine().supportsProtectedContent();
7275     bool hasProtectedLayer = false;
7276     if (allowProtected && supportsProtected) {
7277         hasProtectedLayer = mScheduler
7278                                     ->schedule([=]() {
7279                                         bool protectedLayerFound = false;
7280                                         auto layers = getLayerSnapshots();
7281                                         for (auto& [_, layerFe] : layers) {
7282                                             protectedLayerFound |=
7283                                                     (layerFe->mSnapshot->isVisible &&
7284                                                      layerFe->mSnapshot->hasProtectedContent);
7285                                         }
7286                                         return protectedLayerFound;
7287                                     })
7288                                     .get();
7289     }
7290 
7291     const uint32_t usage = GRALLOC_USAGE_HW_COMPOSER | GRALLOC_USAGE_HW_RENDER |
7292             GRALLOC_USAGE_HW_TEXTURE |
7293             (hasProtectedLayer && allowProtected && supportsProtected
7294                      ? GRALLOC_USAGE_PROTECTED
7295                      : GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN);
7296     sp<GraphicBuffer> buffer =
7297             getFactory().createGraphicBuffer(bufferSize.getWidth(), bufferSize.getHeight(),
7298                                              static_cast<android_pixel_format>(reqPixelFormat),
7299                                              1 /* layerCount */, usage, "screenshot");
7300 
7301     const status_t bufferStatus = buffer->initCheck();
7302     if (bufferStatus != OK) {
7303         // Animations may end up being really janky, but don't crash here.
7304         // Otherwise an irreponsible process may cause an SF crash by allocating
7305         // too much.
7306         ALOGE("%s: Buffer failed to allocate: %d", __func__, bufferStatus);
7307         return ftl::yield<FenceResult>(base::unexpected(bufferStatus)).share();
7308     }
7309     const std::shared_ptr<renderengine::ExternalTexture> texture = std::make_shared<
7310             renderengine::impl::ExternalTexture>(buffer, getRenderEngine(),
7311                                                  renderengine::impl::ExternalTexture::Usage::
7312                                                          WRITEABLE);
7313     return captureScreenCommon(std::move(renderAreaFuture), getLayerSnapshots, texture,
7314                                false /* regionSampling */, grayscale, captureListener);
7315 }
7316 
captureScreenCommon(RenderAreaFuture renderAreaFuture,GetLayerSnapshotsFunction getLayerSnapshots,const std::shared_ptr<renderengine::ExternalTexture> & buffer,bool regionSampling,bool grayscale,const sp<IScreenCaptureListener> & captureListener)7317 ftl::SharedFuture<FenceResult> SurfaceFlinger::captureScreenCommon(
7318         RenderAreaFuture renderAreaFuture, GetLayerSnapshotsFunction getLayerSnapshots,
7319         const std::shared_ptr<renderengine::ExternalTexture>& buffer, bool regionSampling,
7320         bool grayscale, const sp<IScreenCaptureListener>& captureListener) {
7321     ATRACE_CALL();
7322 
7323     bool canCaptureBlackoutContent = hasCaptureBlackoutContentPermission();
7324 
7325     auto future = mScheduler->schedule(
7326             [=, renderAreaFuture = std::move(renderAreaFuture)]() FTL_FAKE_GUARD(
7327                     kMainThreadContext) mutable -> ftl::SharedFuture<FenceResult> {
7328                 ScreenCaptureResults captureResults;
7329                 std::shared_ptr<RenderArea> renderArea = renderAreaFuture.get();
7330                 if (!renderArea) {
7331                     ALOGW("Skipping screen capture because of invalid render area.");
7332                     if (captureListener) {
7333                         captureResults.fenceResult = base::unexpected(NO_MEMORY);
7334                         captureListener->onScreenCaptureCompleted(captureResults);
7335                     }
7336                     return ftl::yield<FenceResult>(base::unexpected(NO_ERROR)).share();
7337                 }
7338 
7339                 ftl::SharedFuture<FenceResult> renderFuture;
7340                 renderArea->render([&]() FTL_FAKE_GUARD(kMainThreadContext) {
7341                     renderFuture = renderScreenImpl(renderArea, getLayerSnapshots, buffer,
7342                                                     canCaptureBlackoutContent, regionSampling,
7343                                                     grayscale, captureResults);
7344                 });
7345 
7346                 if (captureListener) {
7347                     // Defer blocking on renderFuture back to the Binder thread.
7348                     return ftl::Future(std::move(renderFuture))
7349                             .then([captureListener, captureResults = std::move(captureResults)](
7350                                           FenceResult fenceResult) mutable -> FenceResult {
7351                                 captureResults.fenceResult = std::move(fenceResult);
7352                                 captureListener->onScreenCaptureCompleted(captureResults);
7353                                 return base::unexpected(NO_ERROR);
7354                             })
7355                             .share();
7356                 }
7357                 return renderFuture;
7358             });
7359 
7360     // Flatten nested futures.
7361     auto chain = ftl::Future(std::move(future)).then([](ftl::SharedFuture<FenceResult> future) {
7362         return future;
7363     });
7364 
7365     return chain.share();
7366 }
7367 
renderScreenImpl(std::shared_ptr<const RenderArea> renderArea,GetLayerSnapshotsFunction getLayerSnapshots,const std::shared_ptr<renderengine::ExternalTexture> & buffer,bool canCaptureBlackoutContent,bool regionSampling,bool grayscale,ScreenCaptureResults & captureResults)7368 ftl::SharedFuture<FenceResult> SurfaceFlinger::renderScreenImpl(
7369         std::shared_ptr<const RenderArea> renderArea, GetLayerSnapshotsFunction getLayerSnapshots,
7370         const std::shared_ptr<renderengine::ExternalTexture>& buffer,
7371         bool canCaptureBlackoutContent, bool regionSampling, bool grayscale,
7372         ScreenCaptureResults& captureResults) {
7373     ATRACE_CALL();
7374 
7375     auto layers = getLayerSnapshots();
7376 
7377     for (auto& [_, layerFE] : layers) {
7378         frontend::LayerSnapshot* snapshot = layerFE->mSnapshot.get();
7379         captureResults.capturedSecureLayers |= (snapshot->isVisible && snapshot->isSecure);
7380         captureResults.capturedHdrLayers |= isHdrLayer(*snapshot);
7381         layerFE->mSnapshot->geomLayerTransform =
7382                 renderArea->getTransform() * layerFE->mSnapshot->geomLayerTransform;
7383         layerFE->mSnapshot->geomInverseLayerTransform =
7384                 layerFE->mSnapshot->geomLayerTransform.inverse();
7385     }
7386 
7387     // We allow the system server to take screenshots of secure layers for
7388     // use in situations like the Screen-rotation animation and place
7389     // the impetus on WindowManager to not persist them.
7390     if (captureResults.capturedSecureLayers && !canCaptureBlackoutContent) {
7391         ALOGW("FB is protected: PERMISSION_DENIED");
7392         return ftl::yield<FenceResult>(base::unexpected(PERMISSION_DENIED)).share();
7393     }
7394 
7395     auto capturedBuffer = buffer;
7396 
7397     auto requestedDataspace = renderArea->getReqDataSpace();
7398     auto parent = renderArea->getParentLayer();
7399     auto renderIntent = RenderIntent::TONE_MAP_COLORIMETRIC;
7400     auto sdrWhitePointNits = DisplayDevice::sDefaultMaxLumiance;
7401     auto displayBrightnessNits = DisplayDevice::sDefaultMaxLumiance;
7402 
7403     captureResults.capturedDataspace = requestedDataspace;
7404 
7405     {
7406         Mutex::Autolock lock(mStateLock);
7407         const DisplayDevice* display = nullptr;
7408         if (parent) {
7409             display = findDisplay([layerStack = parent->getLayerStack()](const auto& display) {
7410                           return display.getLayerStack() == layerStack;
7411                       }).get();
7412         }
7413 
7414         if (display == nullptr) {
7415             display = renderArea->getDisplayDevice().get();
7416         }
7417 
7418         if (display == nullptr) {
7419             display = getDefaultDisplayDeviceLocked().get();
7420         }
7421 
7422         if (display != nullptr) {
7423             const auto& state = display->getCompositionDisplay()->getState();
7424             captureResults.capturedDataspace =
7425                     pickBestDataspace(requestedDataspace, display, captureResults.capturedHdrLayers,
7426                                       renderArea->getHintForSeamlessTransition());
7427             sdrWhitePointNits = state.sdrWhitePointNits;
7428 
7429             if (!captureResults.capturedHdrLayers) {
7430                 displayBrightnessNits = sdrWhitePointNits;
7431             } else {
7432                 displayBrightnessNits = state.displayBrightnessNits;
7433                 // Only clamp the display brightness if this is not a seamless transition. Otherwise
7434                 // for seamless transitions it's important to match the current display state as the
7435                 // buffer will be shown under these same conditions, and we want to avoid any
7436                 // flickers
7437                 if (sdrWhitePointNits > 1.0f && !renderArea->getHintForSeamlessTransition()) {
7438                     // Restrict the amount of HDR "headroom" in the screenshot to avoid over-dimming
7439                     // the SDR portion. 2.0 chosen by experimentation
7440                     constexpr float kMaxScreenshotHeadroom = 2.0f;
7441                     displayBrightnessNits = std::min(sdrWhitePointNits * kMaxScreenshotHeadroom,
7442                                                      displayBrightnessNits);
7443                 }
7444             }
7445 
7446             // Screenshots leaving the device should be colorimetric
7447             if (requestedDataspace == ui::Dataspace::UNKNOWN &&
7448                 renderArea->getHintForSeamlessTransition()) {
7449                 renderIntent = state.renderIntent;
7450             }
7451         }
7452     }
7453 
7454     captureResults.buffer = capturedBuffer->getBuffer();
7455 
7456     ui::LayerStack layerStack{ui::DEFAULT_LAYER_STACK};
7457     if (!layers.empty()) {
7458         const sp<LayerFE>& layerFE = layers.back().second;
7459         layerStack = layerFE->getCompositionState()->outputFilter.layerStack;
7460     }
7461 
7462     auto copyLayerFEs = [&layers]() {
7463         std::vector<sp<compositionengine::LayerFE>> layerFEs;
7464         layerFEs.reserve(layers.size());
7465         for (const auto& [_, layerFE] : layers) {
7466             layerFEs.push_back(layerFE);
7467         }
7468         return layerFEs;
7469     };
7470 
7471     auto present = [this, buffer = capturedBuffer, dataspace = captureResults.capturedDataspace,
7472                     sdrWhitePointNits, displayBrightnessNits, grayscale, layerFEs = copyLayerFEs(),
7473                     layerStack, regionSampling, renderArea = std::move(renderArea),
7474                     renderIntent]() -> FenceResult {
7475         std::unique_ptr<compositionengine::CompositionEngine> compositionEngine =
7476                 mFactory.createCompositionEngine();
7477         compositionEngine->setRenderEngine(mRenderEngine.get());
7478 
7479         compositionengine::Output::ColorProfile colorProfile{.dataspace = dataspace,
7480                                                              .renderIntent = renderIntent};
7481 
7482         float targetBrightness = 1.0f;
7483         if (dataspace == ui::Dataspace::BT2020_HLG) {
7484             const float maxBrightnessNits = displayBrightnessNits / sdrWhitePointNits * 203;
7485             // With a low dimming ratio, don't fit the entire curve. Otherwise mixed content
7486             // will appear way too bright.
7487             if (maxBrightnessNits < 1000.f) {
7488                 targetBrightness = 1000.f / maxBrightnessNits;
7489             }
7490         }
7491 
7492         // Screenshots leaving the device must not dim in gamma space.
7493         const bool dimInGammaSpaceForEnhancedScreenshots = mDimInGammaSpaceForEnhancedScreenshots &&
7494                 renderArea->getHintForSeamlessTransition();
7495 
7496         std::shared_ptr<ScreenCaptureOutput> output = createScreenCaptureOutput(
7497                 ScreenCaptureOutputArgs{.compositionEngine = *compositionEngine,
7498                                         .colorProfile = colorProfile,
7499                                         .renderArea = *renderArea,
7500                                         .layerStack = layerStack,
7501                                         .buffer = std::move(buffer),
7502                                         .sdrWhitePointNits = sdrWhitePointNits,
7503                                         .displayBrightnessNits = displayBrightnessNits,
7504                                         .targetBrightness = targetBrightness,
7505                                         .regionSampling = regionSampling,
7506                                         .treat170mAsSrgb = mTreat170mAsSrgb,
7507                                         .dimInGammaSpaceForEnhancedScreenshots =
7508                                                 dimInGammaSpaceForEnhancedScreenshots});
7509 
7510         const float colorSaturation = grayscale ? 0 : 1;
7511         compositionengine::CompositionRefreshArgs refreshArgs{
7512                 .outputs = {output},
7513                 .layers = std::move(layerFEs),
7514                 .updatingOutputGeometryThisFrame = true,
7515                 .updatingGeometryThisFrame = true,
7516                 .colorTransformMatrix = calculateColorMatrix(colorSaturation),
7517         };
7518         compositionEngine->present(refreshArgs);
7519 
7520         return output->getRenderSurface()->getClientTargetAcquireFence();
7521     };
7522 
7523     // If RenderEngine is threaded, we can safely call CompositionEngine::present off the main
7524     // thread as the RenderEngine::drawLayers call will run on RenderEngine's thread. Otherwise,
7525     // we need RenderEngine to run on the main thread so we call CompositionEngine::present
7526     // immediately.
7527     //
7528     // TODO(b/196334700) Once we use RenderEngineThreaded everywhere we can always defer the call
7529     // to CompositionEngine::present.
7530     const bool renderEngineIsThreaded = [&]() {
7531         using Type = renderengine::RenderEngine::RenderEngineType;
7532         const auto type = mRenderEngine->getRenderEngineType();
7533         return type == Type::THREADED || type == Type::SKIA_GL_THREADED;
7534     }();
7535     auto presentFuture = renderEngineIsThreaded ? ftl::defer(std::move(present)).share()
7536                                                 : ftl::yield(present()).share();
7537 
7538     for (auto& [layer, layerFE] : layers) {
7539         layer->onLayerDisplayed(ftl::Future(presentFuture)
7540                                         .then([layerFE = std::move(layerFE)](FenceResult) {
7541                                             return layerFE->stealCompositionResult()
7542                                                     .releaseFences.back()
7543                                                     .first.get();
7544                                         })
7545                                         .share(),
7546                                 ui::INVALID_LAYER_STACK);
7547     }
7548 
7549     return presentFuture;
7550 }
7551 
traverseLegacyLayers(const LayerVector::Visitor & visitor) const7552 void SurfaceFlinger::traverseLegacyLayers(const LayerVector::Visitor& visitor) const {
7553     if (mLayerLifecycleManagerEnabled) {
7554         for (auto& layer : mLegacyLayers) {
7555             visitor(layer.second.get());
7556         }
7557     } else {
7558         mDrawingState.traverse(visitor);
7559     }
7560 }
7561 
7562 // ---------------------------------------------------------------------------
7563 
traverse(const LayerVector::Visitor & visitor) const7564 void SurfaceFlinger::State::traverse(const LayerVector::Visitor& visitor) const {
7565     layersSortedByZ.traverse(visitor);
7566 }
7567 
traverseInZOrder(const LayerVector::Visitor & visitor) const7568 void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
7569     layersSortedByZ.traverseInZOrder(stateSet, visitor);
7570 }
7571 
traverseInReverseZOrder(const LayerVector::Visitor & visitor) const7572 void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
7573     layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
7574 }
7575 
traverseLayersInLayerStack(ui::LayerStack layerStack,const int32_t uid,std::unordered_set<uint32_t> excludeLayerIds,const LayerVector::Visitor & visitor)7576 void SurfaceFlinger::traverseLayersInLayerStack(ui::LayerStack layerStack, const int32_t uid,
7577                                                 std::unordered_set<uint32_t> excludeLayerIds,
7578                                                 const LayerVector::Visitor& visitor) {
7579     // We loop through the first level of layers without traversing,
7580     // as we need to determine which layers belong to the requested display.
7581     for (const auto& layer : mDrawingState.layersSortedByZ) {
7582         if (layer->getLayerStack() != layerStack) {
7583             continue;
7584         }
7585         // relative layers are traversed in Layer::traverseInZOrder
7586         layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
7587             if (layer->isInternalDisplayOverlay()) {
7588                 return;
7589             }
7590             if (!layer->isVisible()) {
7591                 return;
7592             }
7593             if (uid != CaptureArgs::UNSET_UID && layer->getOwnerUid() != uid) {
7594                 return;
7595             }
7596 
7597             if (!excludeLayerIds.empty()) {
7598                 auto p = sp<Layer>::fromExisting(layer);
7599                 while (p != nullptr) {
7600                     if (excludeLayerIds.count(p->sequence) != 0) {
7601                         return;
7602                     }
7603                     p = p->getParent();
7604                 }
7605             }
7606 
7607             visitor(layer);
7608         });
7609     }
7610 }
7611 
getPreferredDisplayMode(PhysicalDisplayId displayId,DisplayModeId defaultModeId) const7612 ftl::Optional<scheduler::FrameRateMode> SurfaceFlinger::getPreferredDisplayMode(
7613         PhysicalDisplayId displayId, DisplayModeId defaultModeId) const {
7614     if (const auto schedulerMode = mScheduler->getPreferredDisplayMode();
7615         schedulerMode.modePtr->getPhysicalDisplayId() == displayId) {
7616         return schedulerMode;
7617     }
7618 
7619     return mPhysicalDisplays.get(displayId)
7620             .transform(&PhysicalDisplay::snapshotRef)
7621             .and_then([&](const display::DisplaySnapshot& snapshot) {
7622                 return snapshot.displayModes().get(defaultModeId);
7623             })
7624             .transform([](const DisplayModePtr& modePtr) {
7625                 return scheduler::FrameRateMode{modePtr->getFps(), ftl::as_non_null(modePtr)};
7626             });
7627 }
7628 
setDesiredDisplayModeSpecsInternal(const sp<DisplayDevice> & display,const scheduler::RefreshRateSelector::PolicyVariant & policy)7629 status_t SurfaceFlinger::setDesiredDisplayModeSpecsInternal(
7630         const sp<DisplayDevice>& display,
7631         const scheduler::RefreshRateSelector::PolicyVariant& policy) {
7632     const auto displayId = display->getPhysicalId();
7633     ATRACE_NAME(ftl::Concat(__func__, ' ', displayId.value).c_str());
7634 
7635     Mutex::Autolock lock(mStateLock);
7636 
7637     if (mDebugDisplayModeSetByBackdoor) {
7638         // ignore this request as mode is overridden by backdoor
7639         return NO_ERROR;
7640     }
7641 
7642     auto& selector = display->refreshRateSelector();
7643     using SetPolicyResult = scheduler::RefreshRateSelector::SetPolicyResult;
7644 
7645     switch (selector.setPolicy(policy)) {
7646         case SetPolicyResult::Invalid:
7647             return BAD_VALUE;
7648         case SetPolicyResult::Unchanged:
7649             return NO_ERROR;
7650         case SetPolicyResult::Changed:
7651             break;
7652     }
7653 
7654     if (!shouldApplyRefreshRateSelectorPolicy(*display)) {
7655         ALOGV("%s(%s): Skipped applying policy", __func__, to_string(displayId).c_str());
7656         return NO_ERROR;
7657     }
7658 
7659     return applyRefreshRateSelectorPolicy(displayId, selector);
7660 }
7661 
shouldApplyRefreshRateSelectorPolicy(const DisplayDevice & display) const7662 bool SurfaceFlinger::shouldApplyRefreshRateSelectorPolicy(const DisplayDevice& display) const {
7663     if (display.isPoweredOn() || mPhysicalDisplays.size() == 1) return true;
7664 
7665     LOG_ALWAYS_FATAL_IF(display.isVirtual());
7666     const auto displayId = display.getPhysicalId();
7667 
7668     // The display is powered off, and this is a multi-display device. If the display is the
7669     // inactive internal display of a dual-display foldable, then the policy will be applied
7670     // when it becomes active upon powering on.
7671     //
7672     // TODO(b/255635711): Remove this function (i.e. returning `false` as a special case) once
7673     // concurrent mode setting across multiple (potentially powered off) displays is supported.
7674     //
7675     return displayId == mActiveDisplayId ||
7676             !mPhysicalDisplays.get(displayId)
7677                      .transform(&PhysicalDisplay::isInternal)
7678                      .value_or(false);
7679 }
7680 
applyRefreshRateSelectorPolicy(PhysicalDisplayId displayId,const scheduler::RefreshRateSelector & selector,bool force)7681 status_t SurfaceFlinger::applyRefreshRateSelectorPolicy(
7682         PhysicalDisplayId displayId, const scheduler::RefreshRateSelector& selector, bool force) {
7683     const scheduler::RefreshRateSelector::Policy currentPolicy = selector.getCurrentPolicy();
7684     ALOGV("Setting desired display mode specs: %s", currentPolicy.toString().c_str());
7685 
7686     // TODO(b/140204874): Leave the event in until we do proper testing with all apps that might
7687     // be depending in this callback.
7688     if (const auto activeMode = selector.getActiveMode(); displayId == mActiveDisplayId) {
7689         mScheduler->onPrimaryDisplayModeChanged(mAppConnectionHandle, activeMode);
7690         toggleKernelIdleTimer();
7691     } else {
7692         mScheduler->onNonPrimaryDisplayModeChanged(mAppConnectionHandle, activeMode);
7693     }
7694 
7695     auto preferredModeOpt = getPreferredDisplayMode(displayId, currentPolicy.defaultMode);
7696     if (!preferredModeOpt) {
7697         ALOGE("%s: Preferred mode is unknown", __func__);
7698         return NAME_NOT_FOUND;
7699     }
7700 
7701     auto preferredMode = std::move(*preferredModeOpt);
7702     const auto preferredModeId = preferredMode.modePtr->getId();
7703 
7704     ALOGV("Switching to Scheduler preferred mode %d (%s)", preferredModeId.value(),
7705           to_string(preferredMode.fps).c_str());
7706 
7707     if (!selector.isModeAllowed(preferredMode)) {
7708         ALOGE("%s: Preferred mode %d is disallowed", __func__, preferredModeId.value());
7709         return INVALID_OPERATION;
7710     }
7711 
7712     setDesiredActiveMode({std::move(preferredMode), .emitEvent = true}, force);
7713     return NO_ERROR;
7714 }
7715 
7716 namespace {
translate(const gui::DisplayModeSpecs::RefreshRateRanges::RefreshRateRange & aidlRange)7717 FpsRange translate(const gui::DisplayModeSpecs::RefreshRateRanges::RefreshRateRange& aidlRange) {
7718     return FpsRange{Fps::fromValue(aidlRange.min), Fps::fromValue(aidlRange.max)};
7719 }
7720 
translate(const gui::DisplayModeSpecs::RefreshRateRanges & aidlRanges)7721 FpsRanges translate(const gui::DisplayModeSpecs::RefreshRateRanges& aidlRanges) {
7722     return FpsRanges{translate(aidlRanges.physical), translate(aidlRanges.render)};
7723 }
7724 
translate(const FpsRange & range)7725 gui::DisplayModeSpecs::RefreshRateRanges::RefreshRateRange translate(const FpsRange& range) {
7726     gui::DisplayModeSpecs::RefreshRateRanges::RefreshRateRange aidlRange;
7727     aidlRange.min = range.min.getValue();
7728     aidlRange.max = range.max.getValue();
7729     return aidlRange;
7730 }
7731 
translate(const FpsRanges & ranges)7732 gui::DisplayModeSpecs::RefreshRateRanges translate(const FpsRanges& ranges) {
7733     gui::DisplayModeSpecs::RefreshRateRanges aidlRanges;
7734     aidlRanges.physical = translate(ranges.physical);
7735     aidlRanges.render = translate(ranges.render);
7736     return aidlRanges;
7737 }
7738 
7739 } // namespace
7740 
setDesiredDisplayModeSpecs(const sp<IBinder> & displayToken,const gui::DisplayModeSpecs & specs)7741 status_t SurfaceFlinger::setDesiredDisplayModeSpecs(const sp<IBinder>& displayToken,
7742                                                     const gui::DisplayModeSpecs& specs) {
7743     ATRACE_CALL();
7744 
7745     if (!displayToken) {
7746         return BAD_VALUE;
7747     }
7748 
7749     auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(kMainThreadContext) -> status_t {
7750         const auto display = FTL_FAKE_GUARD(mStateLock, getDisplayDeviceLocked(displayToken));
7751         if (!display) {
7752             ALOGE("Attempt to set desired display modes for invalid display token %p",
7753                   displayToken.get());
7754             return NAME_NOT_FOUND;
7755         } else if (display->isVirtual()) {
7756             ALOGW("Attempt to set desired display modes for virtual display");
7757             return INVALID_OPERATION;
7758         } else {
7759             using Policy = scheduler::RefreshRateSelector::DisplayManagerPolicy;
7760             const Policy policy{DisplayModeId(specs.defaultMode), translate(specs.primaryRanges),
7761                                 translate(specs.appRequestRanges), specs.allowGroupSwitching};
7762 
7763             return setDesiredDisplayModeSpecsInternal(display, policy);
7764         }
7765     });
7766 
7767     return future.get();
7768 }
7769 
getDesiredDisplayModeSpecs(const sp<IBinder> & displayToken,gui::DisplayModeSpecs * outSpecs)7770 status_t SurfaceFlinger::getDesiredDisplayModeSpecs(const sp<IBinder>& displayToken,
7771                                                     gui::DisplayModeSpecs* outSpecs) {
7772     ATRACE_CALL();
7773 
7774     if (!displayToken || !outSpecs) {
7775         return BAD_VALUE;
7776     }
7777 
7778     Mutex::Autolock lock(mStateLock);
7779     const auto display = getDisplayDeviceLocked(displayToken);
7780     if (!display) {
7781         return NAME_NOT_FOUND;
7782     }
7783 
7784     if (display->isVirtual()) {
7785         return INVALID_OPERATION;
7786     }
7787 
7788     scheduler::RefreshRateSelector::Policy policy =
7789             display->refreshRateSelector().getDisplayManagerPolicy();
7790     outSpecs->defaultMode = policy.defaultMode.value();
7791     outSpecs->allowGroupSwitching = policy.allowGroupSwitching;
7792     outSpecs->primaryRanges = translate(policy.primaryRanges);
7793     outSpecs->appRequestRanges = translate(policy.appRequestRanges);
7794     return NO_ERROR;
7795 }
7796 
onLayerFirstRef(Layer * layer)7797 void SurfaceFlinger::onLayerFirstRef(Layer* layer) {
7798     mNumLayers++;
7799     if (!layer->isRemovedFromCurrentState()) {
7800         mScheduler->registerLayer(layer);
7801     }
7802 }
7803 
onLayerDestroyed(Layer * layer)7804 void SurfaceFlinger::onLayerDestroyed(Layer* layer) {
7805     mNumLayers--;
7806     removeHierarchyFromOffscreenLayers(layer);
7807     if (!layer->isRemovedFromCurrentState()) {
7808         mScheduler->deregisterLayer(layer);
7809     }
7810     if (mTransactionTracing) {
7811         mTransactionTracing->onLayerRemoved(layer->getSequence());
7812     }
7813 }
7814 
onLayerUpdate()7815 void SurfaceFlinger::onLayerUpdate() {
7816     scheduleCommit(FrameHint::kActive);
7817 }
7818 
7819 // WARNING: ONLY CALL THIS FROM LAYER DTOR
7820 // Here we add children in the current state to offscreen layers and remove the
7821 // layer itself from the offscreen layer list.  Since
7822 // this is the dtor, it is safe to access the current state.  This keeps us
7823 // from dangling children layers such that they are not reachable from the
7824 // Drawing state nor the offscreen layer list
7825 // See b/141111965
removeHierarchyFromOffscreenLayers(Layer * layer)7826 void SurfaceFlinger::removeHierarchyFromOffscreenLayers(Layer* layer) {
7827     for (auto& child : layer->getCurrentChildren()) {
7828         mOffscreenLayers.emplace(child.get());
7829     }
7830     mOffscreenLayers.erase(layer);
7831 }
7832 
removeFromOffscreenLayers(Layer * layer)7833 void SurfaceFlinger::removeFromOffscreenLayers(Layer* layer) {
7834     mOffscreenLayers.erase(layer);
7835 }
7836 
setGlobalShadowSettings(const half4 & ambientColor,const half4 & spotColor,float lightPosY,float lightPosZ,float lightRadius)7837 status_t SurfaceFlinger::setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor,
7838                                                  float lightPosY, float lightPosZ,
7839                                                  float lightRadius) {
7840     Mutex::Autolock _l(mStateLock);
7841     mCurrentState.globalShadowSettings.ambientColor = vec4(ambientColor);
7842     mCurrentState.globalShadowSettings.spotColor = vec4(spotColor);
7843     mCurrentState.globalShadowSettings.lightPos.y = lightPosY;
7844     mCurrentState.globalShadowSettings.lightPos.z = lightPosZ;
7845     mCurrentState.globalShadowSettings.lightRadius = lightRadius;
7846 
7847     // these values are overridden when calculating the shadow settings for a layer.
7848     mCurrentState.globalShadowSettings.lightPos.x = 0.f;
7849     mCurrentState.globalShadowSettings.length = 0.f;
7850     return NO_ERROR;
7851 }
7852 
getGenericLayerMetadataKeyMap() const7853 const std::unordered_map<std::string, uint32_t>& SurfaceFlinger::getGenericLayerMetadataKeyMap()
7854         const {
7855     // TODO(b/149500060): Remove this fixed/static mapping. Please prefer taking
7856     // on the work to remove the table in that bug rather than adding more to
7857     // it.
7858     static const std::unordered_map<std::string, uint32_t> genericLayerMetadataKeyMap{
7859             {"org.chromium.arc.V1_0.TaskId", gui::METADATA_TASK_ID},
7860             {"org.chromium.arc.V1_0.CursorInfo", gui::METADATA_MOUSE_CURSOR},
7861     };
7862     return genericLayerMetadataKeyMap;
7863 }
7864 
setOverrideFrameRate(uid_t uid,float frameRate)7865 status_t SurfaceFlinger::setOverrideFrameRate(uid_t uid, float frameRate) {
7866     PhysicalDisplayId displayId = [&]() {
7867         Mutex::Autolock lock(mStateLock);
7868         return getDefaultDisplayDeviceLocked()->getPhysicalId();
7869     }();
7870 
7871     mScheduler->setGameModeRefreshRateForUid(FrameRateOverride{static_cast<uid_t>(uid), frameRate});
7872     mScheduler->onFrameRateOverridesChanged(mAppConnectionHandle, displayId);
7873     return NO_ERROR;
7874 }
7875 
updateSmallAreaDetection(std::vector<std::pair<uid_t,float>> & uidThresholdMappings)7876 status_t SurfaceFlinger::updateSmallAreaDetection(
7877         std::vector<std::pair<uid_t, float>>& uidThresholdMappings) {
7878     mScheduler->updateSmallAreaDetection(uidThresholdMappings);
7879     return NO_ERROR;
7880 }
7881 
setSmallAreaDetectionThreshold(uid_t uid,float threshold)7882 status_t SurfaceFlinger::setSmallAreaDetectionThreshold(uid_t uid, float threshold) {
7883     mScheduler->setSmallAreaDetectionThreshold(uid, threshold);
7884     return NO_ERROR;
7885 }
7886 
enableRefreshRateOverlay(bool enable)7887 void SurfaceFlinger::enableRefreshRateOverlay(bool enable) {
7888     bool setByHwc = getHwComposer().hasCapability(Capability::REFRESH_RATE_CHANGED_CALLBACK_DEBUG);
7889     for (const auto& [id, display] : mPhysicalDisplays) {
7890         if (display.snapshot().connectionType() == ui::DisplayConnectionType::Internal) {
7891             if (const auto device = getDisplayDeviceLocked(id)) {
7892                 const auto enableOverlay = [&](const bool setByHwc) FTL_FAKE_GUARD(
7893                                                    kMainThreadContext) {
7894                     device->enableRefreshRateOverlay(enable, setByHwc, mRefreshRateOverlaySpinner,
7895                                                      mRefreshRateOverlayRenderRate,
7896                                                      mRefreshRateOverlayShowInMiddle);
7897                 };
7898                 enableOverlay(setByHwc);
7899                 if (setByHwc) {
7900                     const auto status =
7901                             getHwComposer().setRefreshRateChangedCallbackDebugEnabled(id, enable);
7902                     if (status != NO_ERROR) {
7903                         ALOGE("Error updating the refresh rate changed callback debug enabled");
7904                         enableOverlay(/*setByHwc*/ false);
7905                     }
7906                 }
7907             }
7908         }
7909     }
7910 }
7911 
getGpuContextPriority()7912 int SurfaceFlinger::getGpuContextPriority() {
7913     return getRenderEngine().getContextPriority();
7914 }
7915 
calculateMaxAcquiredBufferCount(Fps refreshRate,std::chrono::nanoseconds presentLatency)7916 int SurfaceFlinger::calculateMaxAcquiredBufferCount(Fps refreshRate,
7917                                                     std::chrono::nanoseconds presentLatency) {
7918     auto pipelineDepth = presentLatency.count() / refreshRate.getPeriodNsecs();
7919     if (presentLatency.count() % refreshRate.getPeriodNsecs()) {
7920         pipelineDepth++;
7921     }
7922     return std::max(1ll, pipelineDepth - 1);
7923 }
7924 
getMaxAcquiredBufferCount(int * buffers) const7925 status_t SurfaceFlinger::getMaxAcquiredBufferCount(int* buffers) const {
7926     Fps maxRefreshRate = 60_Hz;
7927 
7928     if (!getHwComposer().isHeadless()) {
7929         if (const auto display = getDefaultDisplayDevice()) {
7930             maxRefreshRate = display->refreshRateSelector().getSupportedRefreshRateRange().max;
7931         }
7932     }
7933 
7934     *buffers = getMaxAcquiredBufferCountForRefreshRate(maxRefreshRate);
7935     return NO_ERROR;
7936 }
7937 
getMaxAcquiredBufferCountForCurrentRefreshRate(uid_t uid) const7938 uint32_t SurfaceFlinger::getMaxAcquiredBufferCountForCurrentRefreshRate(uid_t uid) const {
7939     Fps refreshRate = 60_Hz;
7940 
7941     if (const auto frameRateOverride = mScheduler->getFrameRateOverride(uid)) {
7942         refreshRate = *frameRateOverride;
7943     } else if (!getHwComposer().isHeadless()) {
7944         if (const auto display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked())) {
7945             refreshRate = display->refreshRateSelector().getActiveMode().fps;
7946         }
7947     }
7948 
7949     return getMaxAcquiredBufferCountForRefreshRate(refreshRate);
7950 }
7951 
getMaxAcquiredBufferCountForRefreshRate(Fps refreshRate) const7952 int SurfaceFlinger::getMaxAcquiredBufferCountForRefreshRate(Fps refreshRate) const {
7953     const auto vsyncConfig = mVsyncConfiguration->getConfigsForRefreshRate(refreshRate).late;
7954     const auto presentLatency = vsyncConfig.appWorkDuration + vsyncConfig.sfWorkDuration;
7955     return calculateMaxAcquiredBufferCount(refreshRate, presentLatency);
7956 }
7957 
handleLayerCreatedLocked(const LayerCreatedState & state,VsyncId vsyncId)7958 void SurfaceFlinger::handleLayerCreatedLocked(const LayerCreatedState& state, VsyncId vsyncId) {
7959     sp<Layer> layer = state.layer.promote();
7960     if (!layer) {
7961         ALOGD("Layer was destroyed soon after creation %p", state.layer.unsafe_get());
7962         return;
7963     }
7964     MUTEX_ALIAS(mStateLock, layer->mFlinger->mStateLock);
7965 
7966     sp<Layer> parent;
7967     bool addToRoot = state.addToRoot;
7968     if (state.initialParent != nullptr) {
7969         parent = state.initialParent.promote();
7970         if (parent == nullptr) {
7971             ALOGD("Parent was destroyed soon after creation %p", state.initialParent.unsafe_get());
7972             addToRoot = false;
7973         }
7974     }
7975 
7976     if (parent == nullptr && addToRoot) {
7977         layer->setIsAtRoot(true);
7978         mCurrentState.layersSortedByZ.add(layer);
7979     } else if (parent == nullptr) {
7980         layer->onRemovedFromCurrentState();
7981     } else if (parent->isRemovedFromCurrentState()) {
7982         parent->addChild(layer);
7983         layer->onRemovedFromCurrentState();
7984     } else {
7985         parent->addChild(layer);
7986     }
7987 
7988     ui::LayerStack layerStack = layer->getLayerStack(LayerVector::StateSet::Current);
7989     sp<const DisplayDevice> hintDisplay;
7990     // Find the display that includes the layer.
7991     for (const auto& [token, display] : mDisplays) {
7992         if (display->getLayerStack() == layerStack) {
7993             hintDisplay = display;
7994             break;
7995         }
7996     }
7997 
7998     if (hintDisplay) {
7999         layer->updateTransformHint(hintDisplay->getTransformHint());
8000     }
8001 }
8002 
sample()8003 void SurfaceFlinger::sample() {
8004     if (!mLumaSampling || !mRegionSamplingThread) {
8005         return;
8006     }
8007 
8008     mRegionSamplingThread->onCompositionComplete(mScheduler->getScheduledFrameTime());
8009 }
8010 
onActiveDisplaySizeChanged(const DisplayDevice & activeDisplay)8011 void SurfaceFlinger::onActiveDisplaySizeChanged(const DisplayDevice& activeDisplay) {
8012     mScheduler->onActiveDisplayAreaChanged(activeDisplay.getWidth() * activeDisplay.getHeight());
8013     getRenderEngine().onActiveDisplaySizeChanged(activeDisplay.getSize());
8014 
8015     // Notify layers to update small dirty flag.
8016     if (mScheduler->supportSmallDirtyDetection()) {
8017         mCurrentState.traverse([&](Layer* layer) {
8018             if (layer->getLayerStack() == activeDisplay.getLayerStack()) {
8019                 layer->setIsSmallDirty();
8020             }
8021         });
8022     }
8023 }
8024 
getActivatableDisplay() const8025 sp<DisplayDevice> SurfaceFlinger::getActivatableDisplay() const {
8026     if (mPhysicalDisplays.size() == 1) return nullptr;
8027 
8028     // TODO(b/255635821): Choose the pacesetter display, considering both internal and external
8029     // displays. For now, pick the other internal display, assuming a dual-display foldable.
8030     return findDisplay([this](const DisplayDevice& display) REQUIRES(mStateLock) {
8031         const auto idOpt = PhysicalDisplayId::tryCast(display.getId());
8032         return idOpt && *idOpt != mActiveDisplayId && display.isPoweredOn() &&
8033                 mPhysicalDisplays.get(*idOpt)
8034                         .transform(&PhysicalDisplay::isInternal)
8035                         .value_or(false);
8036     });
8037 }
8038 
onActiveDisplayChangedLocked(const DisplayDevice * inactiveDisplayPtr,const DisplayDevice & activeDisplay)8039 void SurfaceFlinger::onActiveDisplayChangedLocked(const DisplayDevice* inactiveDisplayPtr,
8040                                                   const DisplayDevice& activeDisplay) {
8041     ATRACE_CALL();
8042 
8043     // For the first display activated during boot, there is no need to force setDesiredActiveMode,
8044     // because DM is about to send its policy via setDesiredDisplayModeSpecs.
8045     bool forceApplyPolicy = false;
8046 
8047     if (inactiveDisplayPtr) {
8048         inactiveDisplayPtr->getCompositionDisplay()->setLayerCachingTexturePoolEnabled(false);
8049         forceApplyPolicy = true;
8050     }
8051 
8052     mActiveDisplayId = activeDisplay.getPhysicalId();
8053     activeDisplay.getCompositionDisplay()->setLayerCachingTexturePoolEnabled(true);
8054 
8055     resetPhaseConfiguration(activeDisplay.getActiveMode().fps);
8056 
8057     // TODO(b/255635711): Check for pending mode changes on other displays.
8058     mScheduler->setModeChangePending(false);
8059 
8060     mScheduler->setPacesetterDisplay(mActiveDisplayId);
8061 
8062     onActiveDisplaySizeChanged(activeDisplay);
8063     mActiveDisplayTransformHint = activeDisplay.getTransformHint();
8064     sActiveDisplayRotationFlags = ui::Transform::toRotationFlags(activeDisplay.getOrientation());
8065 
8066     // The policy of the new active/pacesetter display may have changed while it was inactive. In
8067     // that case, its preferred mode has not been propagated to HWC (via setDesiredActiveMode). In
8068     // either case, the Scheduler's cachedModeChangedParams must be initialized to the newly active
8069     // mode, and the kernel idle timer of the newly active display must be toggled.
8070     applyRefreshRateSelectorPolicy(mActiveDisplayId, activeDisplay.refreshRateSelector(),
8071                                    forceApplyPolicy);
8072 }
8073 
addWindowInfosListener(const sp<IWindowInfosListener> & windowInfosListener,gui::WindowInfosListenerInfo * outInfo)8074 status_t SurfaceFlinger::addWindowInfosListener(const sp<IWindowInfosListener>& windowInfosListener,
8075                                                 gui::WindowInfosListenerInfo* outInfo) {
8076     mWindowInfosListenerInvoker->addWindowInfosListener(windowInfosListener, outInfo);
8077     setTransactionFlags(eInputInfoUpdateNeeded);
8078     return NO_ERROR;
8079 }
8080 
removeWindowInfosListener(const sp<IWindowInfosListener> & windowInfosListener) const8081 status_t SurfaceFlinger::removeWindowInfosListener(
8082         const sp<IWindowInfosListener>& windowInfosListener) const {
8083     mWindowInfosListenerInvoker->removeWindowInfosListener(windowInfosListener);
8084     return NO_ERROR;
8085 }
8086 
getStalledTransactionInfo(int pid,std::optional<TransactionHandler::StalledTransactionInfo> & result)8087 status_t SurfaceFlinger::getStalledTransactionInfo(
8088         int pid, std::optional<TransactionHandler::StalledTransactionInfo>& result) {
8089     result = mTransactionHandler.getStalledTransactionInfo(pid);
8090     return NO_ERROR;
8091 }
8092 
getExternalTextureFromBufferData(BufferData & bufferData,const char * layerName,uint64_t transactionId)8093 std::shared_ptr<renderengine::ExternalTexture> SurfaceFlinger::getExternalTextureFromBufferData(
8094         BufferData& bufferData, const char* layerName, uint64_t transactionId) {
8095     if (bufferData.buffer &&
8096         exceedsMaxRenderTargetSize(bufferData.buffer->getWidth(), bufferData.buffer->getHeight())) {
8097         std::string errorMessage =
8098                 base::StringPrintf("Attempted to create an ExternalTexture with size (%u, %u) for "
8099                                    "layer %s that exceeds render target size limit of %u.",
8100                                    bufferData.buffer->getWidth(), bufferData.buffer->getHeight(),
8101                                    layerName, static_cast<uint32_t>(mMaxRenderTargetSize));
8102         ALOGD("%s", errorMessage.c_str());
8103         if (bufferData.releaseBufferListener) {
8104             bufferData.releaseBufferListener->onTransactionQueueStalled(
8105                     String8(errorMessage.c_str()));
8106         }
8107         return nullptr;
8108     }
8109 
8110     bool cachedBufferChanged =
8111             bufferData.flags.test(BufferData::BufferDataChange::cachedBufferChanged);
8112     if (cachedBufferChanged && bufferData.buffer) {
8113         auto result = ClientCache::getInstance().add(bufferData.cachedBuffer, bufferData.buffer);
8114         if (result.ok()) {
8115             return result.value();
8116         }
8117 
8118         if (result.error() == ClientCache::AddError::CacheFull) {
8119             ALOGE("Attempted to create an ExternalTexture for layer %s but CacheFull", layerName);
8120 
8121             if (bufferData.releaseBufferListener) {
8122                 bufferData.releaseBufferListener->onTransactionQueueStalled(
8123                         String8("Buffer processing hung due to full buffer cache"));
8124             }
8125         }
8126 
8127         return nullptr;
8128     }
8129 
8130     if (cachedBufferChanged) {
8131         return ClientCache::getInstance().get(bufferData.cachedBuffer);
8132     }
8133 
8134     if (bufferData.buffer) {
8135         return std::make_shared<
8136                 renderengine::impl::ExternalTexture>(bufferData.buffer, getRenderEngine(),
8137                                                      renderengine::impl::ExternalTexture::Usage::
8138                                                              READABLE);
8139     }
8140 
8141     return nullptr;
8142 }
8143 
commitMirrorDisplays(VsyncId vsyncId)8144 bool SurfaceFlinger::commitMirrorDisplays(VsyncId vsyncId) {
8145     std::vector<MirrorDisplayState> mirrorDisplays;
8146     {
8147         std::scoped_lock<std::mutex> lock(mMirrorDisplayLock);
8148         mirrorDisplays = std::move(mMirrorDisplays);
8149         mMirrorDisplays.clear();
8150         if (mirrorDisplays.size() == 0) {
8151             return false;
8152         }
8153     }
8154 
8155     sp<IBinder> unused;
8156     for (const auto& mirrorDisplay : mirrorDisplays) {
8157         // Set mirror layer's default layer stack to -1 so it doesn't end up rendered on a display
8158         // accidentally.
8159         sp<Layer> rootMirrorLayer = LayerHandle::getLayer(mirrorDisplay.rootHandle);
8160         ssize_t idx = mCurrentState.layersSortedByZ.indexOf(rootMirrorLayer);
8161         bool ret = rootMirrorLayer->setLayerStack(ui::LayerStack::fromValue(-1));
8162         if (idx >= 0 && ret) {
8163             mCurrentState.layersSortedByZ.removeAt(idx);
8164             mCurrentState.layersSortedByZ.add(rootMirrorLayer);
8165         }
8166 
8167         for (const auto& layer : mDrawingState.layersSortedByZ) {
8168             if (layer->getLayerStack() != mirrorDisplay.layerStack ||
8169                 layer->isInternalDisplayOverlay()) {
8170                 continue;
8171             }
8172 
8173             LayerCreationArgs mirrorArgs(this, mirrorDisplay.client, "MirrorLayerParent",
8174                                          ISurfaceComposerClient::eNoColorFill,
8175                                          gui::LayerMetadata());
8176             sp<Layer> childMirror;
8177             {
8178                 Mutex::Autolock lock(mStateLock);
8179                 createEffectLayer(mirrorArgs, &unused, &childMirror);
8180                 MUTEX_ALIAS(mStateLock, childMirror->mFlinger->mStateLock);
8181                 childMirror->setClonedChild(layer->createClone(childMirror->getSequence()));
8182                 childMirror->reparent(mirrorDisplay.rootHandle);
8183             }
8184             // lock on mStateLock needs to be released before binder handle gets destroyed
8185             unused.clear();
8186         }
8187     }
8188     return true;
8189 }
8190 
commitCreatedLayers(VsyncId vsyncId,std::vector<LayerCreatedState> & createdLayers)8191 bool SurfaceFlinger::commitCreatedLayers(VsyncId vsyncId,
8192                                          std::vector<LayerCreatedState>& createdLayers) {
8193     if (createdLayers.size() == 0) {
8194         return false;
8195     }
8196 
8197     Mutex::Autolock _l(mStateLock);
8198     for (const auto& createdLayer : createdLayers) {
8199         handleLayerCreatedLocked(createdLayer, vsyncId);
8200     }
8201     mLayersAdded = true;
8202     return mLayersAdded;
8203 }
8204 
updateLayerMetadataSnapshot()8205 void SurfaceFlinger::updateLayerMetadataSnapshot() {
8206     LayerMetadata parentMetadata;
8207     for (const auto& layer : mDrawingState.layersSortedByZ) {
8208         layer->updateMetadataSnapshot(parentMetadata);
8209     }
8210 
8211     std::unordered_set<Layer*> visited;
8212     mDrawingState.traverse([&visited](Layer* layer) {
8213         if (visited.find(layer) != visited.end()) {
8214             return;
8215         }
8216 
8217         // If the layer isRelativeOf, then either it's relative metadata will be set
8218         // recursively when updateRelativeMetadataSnapshot is called on its relative parent or
8219         // it's relative parent has been deleted. Clear the layer's relativeLayerMetadata to ensure
8220         // that layers with deleted relative parents don't hold stale relativeLayerMetadata.
8221         if (layer->getDrawingState().isRelativeOf) {
8222             layer->editLayerSnapshot()->relativeLayerMetadata = {};
8223             return;
8224         }
8225 
8226         layer->updateRelativeMetadataSnapshot({}, visited);
8227     });
8228 }
8229 
moveSnapshotsFromCompositionArgs(compositionengine::CompositionRefreshArgs & refreshArgs,const std::vector<std::pair<Layer *,LayerFE * >> & layers)8230 void SurfaceFlinger::moveSnapshotsFromCompositionArgs(
8231         compositionengine::CompositionRefreshArgs& refreshArgs,
8232         const std::vector<std::pair<Layer*, LayerFE*>>& layers) {
8233     if (mLayerLifecycleManagerEnabled) {
8234         std::vector<std::unique_ptr<frontend::LayerSnapshot>>& snapshots =
8235                 mLayerSnapshotBuilder.getSnapshots();
8236         for (auto [_, layerFE] : layers) {
8237             auto i = layerFE->mSnapshot->globalZ;
8238             snapshots[i] = std::move(layerFE->mSnapshot);
8239         }
8240     }
8241     if (mLegacyFrontEndEnabled && !mLayerLifecycleManagerEnabled) {
8242         for (auto [layer, layerFE] : layers) {
8243             layer->updateLayerSnapshot(std::move(layerFE->mSnapshot));
8244         }
8245     }
8246 }
8247 
moveSnapshotsToCompositionArgs(compositionengine::CompositionRefreshArgs & refreshArgs,bool cursorOnly)8248 std::vector<std::pair<Layer*, LayerFE*>> SurfaceFlinger::moveSnapshotsToCompositionArgs(
8249         compositionengine::CompositionRefreshArgs& refreshArgs, bool cursorOnly) {
8250     std::vector<std::pair<Layer*, LayerFE*>> layers;
8251     if (mLayerLifecycleManagerEnabled) {
8252         nsecs_t currentTime = systemTime();
8253         mLayerSnapshotBuilder.forEachVisibleSnapshot(
8254                 [&](std::unique_ptr<frontend::LayerSnapshot>& snapshot) {
8255                     if (cursorOnly &&
8256                         snapshot->compositionType !=
8257                                 aidl::android::hardware::graphics::composer3::Composition::CURSOR) {
8258                         return;
8259                     }
8260 
8261                     if (!snapshot->hasSomethingToDraw()) {
8262                         return;
8263                     }
8264 
8265                     auto it = mLegacyLayers.find(snapshot->sequence);
8266                     LOG_ALWAYS_FATAL_IF(it == mLegacyLayers.end(),
8267                                         "Couldnt find layer object for %s",
8268                                         snapshot->getDebugString().c_str());
8269                     auto& legacyLayer = it->second;
8270                     sp<LayerFE> layerFE = legacyLayer->getCompositionEngineLayerFE(snapshot->path);
8271                     snapshot->fps = getLayerFramerate(currentTime, snapshot->sequence);
8272                     layerFE->mSnapshot = std::move(snapshot);
8273                     refreshArgs.layers.push_back(layerFE);
8274                     layers.emplace_back(legacyLayer.get(), layerFE.get());
8275                 });
8276     }
8277     if (mLegacyFrontEndEnabled && !mLayerLifecycleManagerEnabled) {
8278         auto moveSnapshots = [&layers, &refreshArgs, cursorOnly](Layer* layer) {
8279             if (const auto& layerFE = layer->getCompositionEngineLayerFE()) {
8280                 if (cursorOnly &&
8281                     layer->getLayerSnapshot()->compositionType !=
8282                             aidl::android::hardware::graphics::composer3::Composition::CURSOR)
8283                     return;
8284                 layer->updateSnapshot(refreshArgs.updatingGeometryThisFrame);
8285                 layerFE->mSnapshot = layer->stealLayerSnapshot();
8286                 refreshArgs.layers.push_back(layerFE);
8287                 layers.emplace_back(layer, layerFE.get());
8288             }
8289         };
8290 
8291         if (cursorOnly || !mVisibleRegionsDirty) {
8292             // for hot path avoid traversals by walking though the previous composition list
8293             for (sp<Layer> layer : mPreviouslyComposedLayers) {
8294                 moveSnapshots(layer.get());
8295             }
8296         } else {
8297             mPreviouslyComposedLayers.clear();
8298             mDrawingState.traverseInZOrder(
8299                     [&moveSnapshots](Layer* layer) { moveSnapshots(layer); });
8300             mPreviouslyComposedLayers.reserve(layers.size());
8301             for (auto [layer, _] : layers) {
8302                 mPreviouslyComposedLayers.push_back(sp<Layer>::fromExisting(layer));
8303             }
8304         }
8305     }
8306 
8307     return layers;
8308 }
8309 
8310 std::function<std::vector<std::pair<Layer*, sp<LayerFE>>>()>
getLayerSnapshotsForScreenshots(std::optional<ui::LayerStack> layerStack,uint32_t uid,std::function<bool (const frontend::LayerSnapshot &,bool & outStopTraversal)> snapshotFilterFn)8311 SurfaceFlinger::getLayerSnapshotsForScreenshots(
8312         std::optional<ui::LayerStack> layerStack, uint32_t uid,
8313         std::function<bool(const frontend::LayerSnapshot&, bool& outStopTraversal)>
8314                 snapshotFilterFn) {
8315     return [&, layerStack, uid]() {
8316         std::vector<std::pair<Layer*, sp<LayerFE>>> layers;
8317         bool stopTraversal = false;
8318         mLayerSnapshotBuilder.forEachVisibleSnapshot(
8319                 [&](std::unique_ptr<frontend::LayerSnapshot>& snapshot) {
8320                     if (stopTraversal) {
8321                         return;
8322                     }
8323                     if (layerStack && snapshot->outputFilter.layerStack != *layerStack) {
8324                         return;
8325                     }
8326                     if (uid != CaptureArgs::UNSET_UID && snapshot->uid != gui::Uid(uid)) {
8327                         return;
8328                     }
8329                     if (!snapshot->hasSomethingToDraw()) {
8330                         return;
8331                     }
8332                     if (snapshotFilterFn && !snapshotFilterFn(*snapshot, stopTraversal)) {
8333                         return;
8334                     }
8335 
8336                     auto it = mLegacyLayers.find(snapshot->sequence);
8337                     LOG_ALWAYS_FATAL_IF(it == mLegacyLayers.end(),
8338                                         "Couldnt find layer object for %s",
8339                                         snapshot->getDebugString().c_str());
8340                     Layer* legacyLayer = (it == mLegacyLayers.end()) ? nullptr : it->second.get();
8341                     sp<LayerFE> layerFE = getFactory().createLayerFE(snapshot->name);
8342                     layerFE->mSnapshot = std::make_unique<frontend::LayerSnapshot>(*snapshot);
8343                     layers.emplace_back(legacyLayer, std::move(layerFE));
8344                 });
8345 
8346         return layers;
8347     };
8348 }
8349 
8350 std::function<std::vector<std::pair<Layer*, sp<LayerFE>>>()>
getLayerSnapshotsForScreenshots(std::optional<ui::LayerStack> layerStack,uint32_t uid,std::unordered_set<uint32_t> excludeLayerIds)8351 SurfaceFlinger::getLayerSnapshotsForScreenshots(std::optional<ui::LayerStack> layerStack,
8352                                                 uint32_t uid,
8353                                                 std::unordered_set<uint32_t> excludeLayerIds) {
8354     return [&, layerStack, uid, excludeLayerIds = std::move(excludeLayerIds)]() {
8355         if (excludeLayerIds.empty()) {
8356             auto getLayerSnapshotsFn =
8357                     getLayerSnapshotsForScreenshots(layerStack, uid, /*snapshotFilterFn=*/nullptr);
8358             std::vector<std::pair<Layer*, sp<LayerFE>>> layers = getLayerSnapshotsFn();
8359             return layers;
8360         }
8361 
8362         frontend::LayerSnapshotBuilder::Args
8363                 args{.root = mLayerHierarchyBuilder.getHierarchy(),
8364                      .layerLifecycleManager = mLayerLifecycleManager,
8365                      .forceUpdate = frontend::LayerSnapshotBuilder::ForceUpdateFlags::HIERARCHY,
8366                      .displays = mFrontEndDisplayInfos,
8367                      .displayChanges = true,
8368                      .globalShadowSettings = mDrawingState.globalShadowSettings,
8369                      .supportsBlur = mSupportsBlur,
8370                      .forceFullDamage = mForceFullDamage,
8371                      .excludeLayerIds = std::move(excludeLayerIds),
8372                      .supportedLayerGenericMetadata =
8373                              getHwComposer().getSupportedLayerGenericMetadata(),
8374                      .genericLayerMetadataKeyMap = getGenericLayerMetadataKeyMap()};
8375         mLayerSnapshotBuilder.update(args);
8376 
8377         auto getLayerSnapshotsFn =
8378                 getLayerSnapshotsForScreenshots(layerStack, uid, /*snapshotFilterFn=*/nullptr);
8379         std::vector<std::pair<Layer*, sp<LayerFE>>> layers = getLayerSnapshotsFn();
8380 
8381         args.excludeLayerIds.clear();
8382         mLayerSnapshotBuilder.update(args);
8383 
8384         return layers;
8385     };
8386 }
8387 
8388 std::function<std::vector<std::pair<Layer*, sp<LayerFE>>>()>
getLayerSnapshotsForScreenshots(uint32_t rootLayerId,uint32_t uid,std::unordered_set<uint32_t> excludeLayerIds,bool childrenOnly,const std::optional<FloatRect> & parentCrop)8389 SurfaceFlinger::getLayerSnapshotsForScreenshots(uint32_t rootLayerId, uint32_t uid,
8390                                                 std::unordered_set<uint32_t> excludeLayerIds,
8391                                                 bool childrenOnly,
8392                                                 const std::optional<FloatRect>& parentCrop) {
8393     return [&, rootLayerId, uid, excludeLayerIds = std::move(excludeLayerIds), childrenOnly,
8394             parentCrop]() {
8395         auto root = mLayerHierarchyBuilder.getPartialHierarchy(rootLayerId, childrenOnly);
8396         frontend::LayerSnapshotBuilder::Args
8397                 args{.root = root,
8398                      .layerLifecycleManager = mLayerLifecycleManager,
8399                      .forceUpdate = frontend::LayerSnapshotBuilder::ForceUpdateFlags::HIERARCHY,
8400                      .displays = mFrontEndDisplayInfos,
8401                      .displayChanges = true,
8402                      .globalShadowSettings = mDrawingState.globalShadowSettings,
8403                      .supportsBlur = mSupportsBlur,
8404                      .forceFullDamage = mForceFullDamage,
8405                      .parentCrop = parentCrop,
8406                      .excludeLayerIds = std::move(excludeLayerIds),
8407                      .supportedLayerGenericMetadata =
8408                              getHwComposer().getSupportedLayerGenericMetadata(),
8409                      .genericLayerMetadataKeyMap = getGenericLayerMetadataKeyMap()};
8410         mLayerSnapshotBuilder.update(args);
8411 
8412         auto getLayerSnapshotsFn =
8413                 getLayerSnapshotsForScreenshots({}, uid, /*snapshotFilterFn=*/nullptr);
8414         std::vector<std::pair<Layer*, sp<LayerFE>>> layers = getLayerSnapshotsFn();
8415         args.root = mLayerHierarchyBuilder.getHierarchy();
8416         args.parentCrop.reset();
8417         args.excludeLayerIds.clear();
8418         mLayerSnapshotBuilder.update(args);
8419         return layers;
8420     };
8421 }
8422 
flushLifecycleUpdates()8423 frontend::Update SurfaceFlinger::flushLifecycleUpdates() {
8424     frontend::Update update;
8425     ATRACE_NAME("TransactionHandler:flushTransactions");
8426     // Locking:
8427     // 1. to prevent onHandleDestroyed from being called while the state lock is held,
8428     // we must keep a copy of the transactions (specifically the composer
8429     // states) around outside the scope of the lock.
8430     // 2. Transactions and created layers do not share a lock. To prevent applying
8431     // transactions with layers still in the createdLayer queue, flush the transactions
8432     // before committing the created layers.
8433     update.transactions = mTransactionHandler.flushTransactions();
8434     {
8435         // TODO(b/238781169) lockless queue this and keep order.
8436         std::scoped_lock<std::mutex> lock(mCreatedLayersLock);
8437         update.layerCreatedStates = std::move(mCreatedLayers);
8438         mCreatedLayers.clear();
8439         update.newLayers = std::move(mNewLayers);
8440         mNewLayers.clear();
8441         update.layerCreationArgs = std::move(mNewLayerArgs);
8442         mNewLayerArgs.clear();
8443         update.destroyedHandles = std::move(mDestroyedHandles);
8444         mDestroyedHandles.clear();
8445     }
8446     return update;
8447 }
8448 
addToLayerTracing(bool visibleRegionDirty,TimePoint time,VsyncId vsyncId)8449 void SurfaceFlinger::addToLayerTracing(bool visibleRegionDirty, TimePoint time, VsyncId vsyncId) {
8450     const uint32_t tracingFlags = mLayerTracing.getFlags();
8451     LayersProto layers(dumpDrawingStateProto(tracingFlags));
8452     if (tracingFlags & LayerTracing::TRACE_EXTRA) {
8453         dumpOffscreenLayersProto(layers);
8454     }
8455     std::string hwcDump;
8456     if (tracingFlags & LayerTracing::TRACE_HWC) {
8457         dumpHwc(hwcDump);
8458     }
8459     auto displays = dumpDisplayProto();
8460     mLayerTracing.notify(visibleRegionDirty, time.ns(), ftl::to_underlying(vsyncId), &layers,
8461                          std::move(hwcDump), &displays);
8462 }
8463 
8464 // gui::ISurfaceComposer
8465 
bootFinished()8466 binder::Status SurfaceComposerAIDL::bootFinished() {
8467     status_t status = checkAccessPermission();
8468     if (status != OK) {
8469         return binderStatusFromStatusT(status);
8470     }
8471     mFlinger->bootFinished();
8472     return binder::Status::ok();
8473 }
8474 
createDisplayEventConnection(VsyncSource vsyncSource,EventRegistration eventRegistration,const sp<IBinder> & layerHandle,sp<IDisplayEventConnection> * outConnection)8475 binder::Status SurfaceComposerAIDL::createDisplayEventConnection(
8476         VsyncSource vsyncSource, EventRegistration eventRegistration,
8477         const sp<IBinder>& layerHandle, sp<IDisplayEventConnection>* outConnection) {
8478     sp<IDisplayEventConnection> conn =
8479             mFlinger->createDisplayEventConnection(vsyncSource, eventRegistration, layerHandle);
8480     if (conn == nullptr) {
8481         *outConnection = nullptr;
8482         return binderStatusFromStatusT(BAD_VALUE);
8483     } else {
8484         *outConnection = conn;
8485         return binder::Status::ok();
8486     }
8487 }
8488 
createConnection(sp<gui::ISurfaceComposerClient> * outClient)8489 binder::Status SurfaceComposerAIDL::createConnection(sp<gui::ISurfaceComposerClient>* outClient) {
8490     const sp<Client> client = sp<Client>::make(mFlinger);
8491     if (client->initCheck() == NO_ERROR) {
8492         *outClient = client;
8493         return binder::Status::ok();
8494     } else {
8495         *outClient = nullptr;
8496         return binderStatusFromStatusT(BAD_VALUE);
8497     }
8498 }
8499 
createDisplay(const std::string & displayName,bool secure,float requestedRefreshRate,sp<IBinder> * outDisplay)8500 binder::Status SurfaceComposerAIDL::createDisplay(const std::string& displayName, bool secure,
8501                                                   float requestedRefreshRate,
8502                                                   sp<IBinder>* outDisplay) {
8503     status_t status = checkAccessPermission();
8504     if (status != OK) {
8505         return binderStatusFromStatusT(status);
8506     }
8507     String8 displayName8 = String8::format("%s", displayName.c_str());
8508     *outDisplay = mFlinger->createDisplay(displayName8, secure, requestedRefreshRate);
8509     return binder::Status::ok();
8510 }
8511 
destroyDisplay(const sp<IBinder> & display)8512 binder::Status SurfaceComposerAIDL::destroyDisplay(const sp<IBinder>& display) {
8513     status_t status = checkAccessPermission();
8514     if (status != OK) {
8515         return binderStatusFromStatusT(status);
8516     }
8517     mFlinger->destroyDisplay(display);
8518     return binder::Status::ok();
8519 }
8520 
getPhysicalDisplayIds(std::vector<int64_t> * outDisplayIds)8521 binder::Status SurfaceComposerAIDL::getPhysicalDisplayIds(std::vector<int64_t>* outDisplayIds) {
8522     std::vector<PhysicalDisplayId> physicalDisplayIds = mFlinger->getPhysicalDisplayIds();
8523     std::vector<int64_t> displayIds;
8524     displayIds.reserve(physicalDisplayIds.size());
8525     for (auto item : physicalDisplayIds) {
8526         displayIds.push_back(static_cast<int64_t>(item.value));
8527     }
8528     *outDisplayIds = displayIds;
8529     return binder::Status::ok();
8530 }
8531 
getPhysicalDisplayToken(int64_t displayId,sp<IBinder> * outDisplay)8532 binder::Status SurfaceComposerAIDL::getPhysicalDisplayToken(int64_t displayId,
8533                                                             sp<IBinder>* outDisplay) {
8534     status_t status = checkAccessPermission();
8535     if (status != OK) {
8536         return binderStatusFromStatusT(status);
8537     }
8538     const auto id = DisplayId::fromValue<PhysicalDisplayId>(static_cast<uint64_t>(displayId));
8539     *outDisplay = mFlinger->getPhysicalDisplayToken(*id);
8540     return binder::Status::ok();
8541 }
8542 
setPowerMode(const sp<IBinder> & display,int mode)8543 binder::Status SurfaceComposerAIDL::setPowerMode(const sp<IBinder>& display, int mode) {
8544     status_t status = checkAccessPermission();
8545     if (status != OK) {
8546         return binderStatusFromStatusT(status);
8547     }
8548     mFlinger->setPowerMode(display, mode);
8549     return binder::Status::ok();
8550 }
8551 
getSupportedFrameTimestamps(std::vector<FrameEvent> * outSupported)8552 binder::Status SurfaceComposerAIDL::getSupportedFrameTimestamps(
8553         std::vector<FrameEvent>* outSupported) {
8554     status_t status;
8555     if (!outSupported) {
8556         status = UNEXPECTED_NULL;
8557     } else {
8558         outSupported->clear();
8559         status = mFlinger->getSupportedFrameTimestamps(outSupported);
8560     }
8561     return binderStatusFromStatusT(status);
8562 }
8563 
getDisplayStats(const sp<IBinder> & display,gui::DisplayStatInfo * outStatInfo)8564 binder::Status SurfaceComposerAIDL::getDisplayStats(const sp<IBinder>& display,
8565                                                     gui::DisplayStatInfo* outStatInfo) {
8566     DisplayStatInfo statInfo;
8567     status_t status = mFlinger->getDisplayStats(display, &statInfo);
8568     if (status == NO_ERROR) {
8569         outStatInfo->vsyncTime = static_cast<long>(statInfo.vsyncTime);
8570         outStatInfo->vsyncPeriod = static_cast<long>(statInfo.vsyncPeriod);
8571     }
8572     return binderStatusFromStatusT(status);
8573 }
8574 
getDisplayState(const sp<IBinder> & display,gui::DisplayState * outState)8575 binder::Status SurfaceComposerAIDL::getDisplayState(const sp<IBinder>& display,
8576                                                     gui::DisplayState* outState) {
8577     ui::DisplayState state;
8578     status_t status = mFlinger->getDisplayState(display, &state);
8579     if (status == NO_ERROR) {
8580         outState->layerStack = state.layerStack.id;
8581         outState->orientation = static_cast<gui::Rotation>(state.orientation);
8582         outState->layerStackSpaceRect.width = state.layerStackSpaceRect.width;
8583         outState->layerStackSpaceRect.height = state.layerStackSpaceRect.height;
8584     }
8585     return binderStatusFromStatusT(status);
8586 }
8587 
getStaticDisplayInfo(int64_t displayId,gui::StaticDisplayInfo * outInfo)8588 binder::Status SurfaceComposerAIDL::getStaticDisplayInfo(int64_t displayId,
8589                                                          gui::StaticDisplayInfo* outInfo) {
8590     using Tag = gui::DeviceProductInfo::ManufactureOrModelDate::Tag;
8591     ui::StaticDisplayInfo info;
8592 
8593     status_t status = mFlinger->getStaticDisplayInfo(displayId, &info);
8594     if (status == NO_ERROR) {
8595         // convert ui::StaticDisplayInfo to gui::StaticDisplayInfo
8596         outInfo->connectionType = static_cast<gui::DisplayConnectionType>(info.connectionType);
8597         outInfo->density = info.density;
8598         outInfo->secure = info.secure;
8599         outInfo->installOrientation = static_cast<gui::Rotation>(info.installOrientation);
8600 
8601         if (const std::optional<DeviceProductInfo> dpi = info.deviceProductInfo) {
8602             gui::DeviceProductInfo dinfo;
8603             dinfo.name = std::move(dpi->name);
8604             dinfo.manufacturerPnpId = std::vector<uint8_t>(dpi->manufacturerPnpId.begin(),
8605                                                            dpi->manufacturerPnpId.end());
8606             dinfo.productId = dpi->productId;
8607             dinfo.relativeAddress =
8608                     std::vector<uint8_t>(dpi->relativeAddress.begin(), dpi->relativeAddress.end());
8609             if (const auto* model =
8610                         std::get_if<DeviceProductInfo::ModelYear>(&dpi->manufactureOrModelDate)) {
8611                 gui::DeviceProductInfo::ModelYear modelYear;
8612                 modelYear.year = model->year;
8613                 dinfo.manufactureOrModelDate.set<Tag::modelYear>(modelYear);
8614             } else if (const auto* manufacture = std::get_if<DeviceProductInfo::ManufactureYear>(
8615                                &dpi->manufactureOrModelDate)) {
8616                 gui::DeviceProductInfo::ManufactureYear date;
8617                 date.modelYear.year = manufacture->year;
8618                 dinfo.manufactureOrModelDate.set<Tag::manufactureYear>(date);
8619             } else if (const auto* manufacture =
8620                                std::get_if<DeviceProductInfo::ManufactureWeekAndYear>(
8621                                        &dpi->manufactureOrModelDate)) {
8622                 gui::DeviceProductInfo::ManufactureWeekAndYear date;
8623                 date.manufactureYear.modelYear.year = manufacture->year;
8624                 date.week = manufacture->week;
8625                 dinfo.manufactureOrModelDate.set<Tag::manufactureWeekAndYear>(date);
8626             }
8627 
8628             outInfo->deviceProductInfo = dinfo;
8629         }
8630     }
8631     return binderStatusFromStatusT(status);
8632 }
8633 
getDynamicDisplayInfoInternal(ui::DynamicDisplayInfo & info,gui::DynamicDisplayInfo * & outInfo)8634 void SurfaceComposerAIDL::getDynamicDisplayInfoInternal(ui::DynamicDisplayInfo& info,
8635                                                         gui::DynamicDisplayInfo*& outInfo) {
8636     // convert ui::DynamicDisplayInfo to gui::DynamicDisplayInfo
8637     outInfo->supportedDisplayModes.clear();
8638     outInfo->supportedDisplayModes.reserve(info.supportedDisplayModes.size());
8639     for (const auto& mode : info.supportedDisplayModes) {
8640         gui::DisplayMode outMode;
8641         outMode.id = mode.id;
8642         outMode.resolution.width = mode.resolution.width;
8643         outMode.resolution.height = mode.resolution.height;
8644         outMode.xDpi = mode.xDpi;
8645         outMode.yDpi = mode.yDpi;
8646         outMode.refreshRate = mode.refreshRate;
8647         outMode.appVsyncOffset = mode.appVsyncOffset;
8648         outMode.sfVsyncOffset = mode.sfVsyncOffset;
8649         outMode.presentationDeadline = mode.presentationDeadline;
8650         outMode.group = mode.group;
8651         std::transform(mode.supportedHdrTypes.begin(), mode.supportedHdrTypes.end(),
8652                        std::back_inserter(outMode.supportedHdrTypes),
8653                        [](const ui::Hdr& value) { return static_cast<int32_t>(value); });
8654         outInfo->supportedDisplayModes.push_back(outMode);
8655     }
8656 
8657     outInfo->activeDisplayModeId = info.activeDisplayModeId;
8658     outInfo->renderFrameRate = info.renderFrameRate;
8659 
8660     outInfo->supportedColorModes.clear();
8661     outInfo->supportedColorModes.reserve(info.supportedColorModes.size());
8662     for (const auto& cmode : info.supportedColorModes) {
8663         outInfo->supportedColorModes.push_back(static_cast<int32_t>(cmode));
8664     }
8665 
8666     outInfo->activeColorMode = static_cast<int32_t>(info.activeColorMode);
8667 
8668     gui::HdrCapabilities& hdrCapabilities = outInfo->hdrCapabilities;
8669     hdrCapabilities.supportedHdrTypes.clear();
8670     hdrCapabilities.supportedHdrTypes.reserve(info.hdrCapabilities.getSupportedHdrTypes().size());
8671     for (const auto& hdr : info.hdrCapabilities.getSupportedHdrTypes()) {
8672         hdrCapabilities.supportedHdrTypes.push_back(static_cast<int32_t>(hdr));
8673     }
8674     hdrCapabilities.maxLuminance = info.hdrCapabilities.getDesiredMaxLuminance();
8675     hdrCapabilities.maxAverageLuminance = info.hdrCapabilities.getDesiredMaxAverageLuminance();
8676     hdrCapabilities.minLuminance = info.hdrCapabilities.getDesiredMinLuminance();
8677 
8678     outInfo->autoLowLatencyModeSupported = info.autoLowLatencyModeSupported;
8679     outInfo->gameContentTypeSupported = info.gameContentTypeSupported;
8680     outInfo->preferredBootDisplayMode = info.preferredBootDisplayMode;
8681 }
8682 
getDynamicDisplayInfoFromToken(const sp<IBinder> & display,gui::DynamicDisplayInfo * outInfo)8683 binder::Status SurfaceComposerAIDL::getDynamicDisplayInfoFromToken(
8684         const sp<IBinder>& display, gui::DynamicDisplayInfo* outInfo) {
8685     ui::DynamicDisplayInfo info;
8686     status_t status = mFlinger->getDynamicDisplayInfoFromToken(display, &info);
8687     if (status == NO_ERROR) {
8688         getDynamicDisplayInfoInternal(info, outInfo);
8689     }
8690     return binderStatusFromStatusT(status);
8691 }
8692 
getDynamicDisplayInfoFromId(int64_t displayId,gui::DynamicDisplayInfo * outInfo)8693 binder::Status SurfaceComposerAIDL::getDynamicDisplayInfoFromId(int64_t displayId,
8694                                                                 gui::DynamicDisplayInfo* outInfo) {
8695     ui::DynamicDisplayInfo info;
8696     status_t status = mFlinger->getDynamicDisplayInfoFromId(displayId, &info);
8697     if (status == NO_ERROR) {
8698         getDynamicDisplayInfoInternal(info, outInfo);
8699     }
8700     return binderStatusFromStatusT(status);
8701 }
8702 
getDisplayNativePrimaries(const sp<IBinder> & display,gui::DisplayPrimaries * outPrimaries)8703 binder::Status SurfaceComposerAIDL::getDisplayNativePrimaries(const sp<IBinder>& display,
8704                                                               gui::DisplayPrimaries* outPrimaries) {
8705     ui::DisplayPrimaries primaries;
8706     status_t status = mFlinger->getDisplayNativePrimaries(display, primaries);
8707     if (status == NO_ERROR) {
8708         outPrimaries->red.X = primaries.red.X;
8709         outPrimaries->red.Y = primaries.red.Y;
8710         outPrimaries->red.Z = primaries.red.Z;
8711 
8712         outPrimaries->green.X = primaries.green.X;
8713         outPrimaries->green.Y = primaries.green.Y;
8714         outPrimaries->green.Z = primaries.green.Z;
8715 
8716         outPrimaries->blue.X = primaries.blue.X;
8717         outPrimaries->blue.Y = primaries.blue.Y;
8718         outPrimaries->blue.Z = primaries.blue.Z;
8719 
8720         outPrimaries->white.X = primaries.white.X;
8721         outPrimaries->white.Y = primaries.white.Y;
8722         outPrimaries->white.Z = primaries.white.Z;
8723     }
8724     return binderStatusFromStatusT(status);
8725 }
8726 
setActiveColorMode(const sp<IBinder> & display,int colorMode)8727 binder::Status SurfaceComposerAIDL::setActiveColorMode(const sp<IBinder>& display, int colorMode) {
8728     status_t status = checkAccessPermission();
8729     if (status == OK) {
8730         status = mFlinger->setActiveColorMode(display, static_cast<ui::ColorMode>(colorMode));
8731     }
8732     return binderStatusFromStatusT(status);
8733 }
8734 
setBootDisplayMode(const sp<IBinder> & display,int displayModeId)8735 binder::Status SurfaceComposerAIDL::setBootDisplayMode(const sp<IBinder>& display,
8736                                                        int displayModeId) {
8737     status_t status = checkAccessPermission();
8738     if (status == OK) {
8739         status = mFlinger->setBootDisplayMode(display, DisplayModeId{displayModeId});
8740     }
8741     return binderStatusFromStatusT(status);
8742 }
8743 
clearBootDisplayMode(const sp<IBinder> & display)8744 binder::Status SurfaceComposerAIDL::clearBootDisplayMode(const sp<IBinder>& display) {
8745     status_t status = checkAccessPermission();
8746     if (status == OK) {
8747         status = mFlinger->clearBootDisplayMode(display);
8748     }
8749     return binderStatusFromStatusT(status);
8750 }
8751 
getOverlaySupport(gui::OverlayProperties * outProperties)8752 binder::Status SurfaceComposerAIDL::getOverlaySupport(gui::OverlayProperties* outProperties) {
8753     status_t status = checkAccessPermission();
8754     if (status == OK) {
8755         status = mFlinger->getOverlaySupport(outProperties);
8756     }
8757     return binderStatusFromStatusT(status);
8758 }
8759 
getBootDisplayModeSupport(bool * outMode)8760 binder::Status SurfaceComposerAIDL::getBootDisplayModeSupport(bool* outMode) {
8761     status_t status = checkAccessPermission();
8762     if (status == OK) {
8763         status = mFlinger->getBootDisplayModeSupport(outMode);
8764     }
8765     return binderStatusFromStatusT(status);
8766 }
8767 
getHdrConversionCapabilities(std::vector<gui::HdrConversionCapability> * hdrConversionCapabilities)8768 binder::Status SurfaceComposerAIDL::getHdrConversionCapabilities(
8769         std::vector<gui::HdrConversionCapability>* hdrConversionCapabilities) {
8770     status_t status = checkAccessPermission();
8771     if (status == OK) {
8772         status = mFlinger->getHdrConversionCapabilities(hdrConversionCapabilities);
8773     }
8774     return binderStatusFromStatusT(status);
8775 }
8776 
setHdrConversionStrategy(const gui::HdrConversionStrategy & hdrConversionStrategy,int32_t * outPreferredHdrOutputType)8777 binder::Status SurfaceComposerAIDL::setHdrConversionStrategy(
8778         const gui::HdrConversionStrategy& hdrConversionStrategy,
8779         int32_t* outPreferredHdrOutputType) {
8780     status_t status = checkAccessPermission();
8781     if (status == OK) {
8782         status = mFlinger->setHdrConversionStrategy(hdrConversionStrategy,
8783                                                     outPreferredHdrOutputType);
8784     }
8785     return binderStatusFromStatusT(status);
8786 }
8787 
getHdrOutputConversionSupport(bool * outMode)8788 binder::Status SurfaceComposerAIDL::getHdrOutputConversionSupport(bool* outMode) {
8789     status_t status = checkAccessPermission();
8790     if (status == OK) {
8791         status = mFlinger->getHdrOutputConversionSupport(outMode);
8792     }
8793     return binderStatusFromStatusT(status);
8794 }
8795 
setAutoLowLatencyMode(const sp<IBinder> & display,bool on)8796 binder::Status SurfaceComposerAIDL::setAutoLowLatencyMode(const sp<IBinder>& display, bool on) {
8797     status_t status = checkAccessPermission();
8798     if (status != OK) {
8799         return binderStatusFromStatusT(status);
8800     }
8801     mFlinger->setAutoLowLatencyMode(display, on);
8802     return binder::Status::ok();
8803 }
8804 
setGameContentType(const sp<IBinder> & display,bool on)8805 binder::Status SurfaceComposerAIDL::setGameContentType(const sp<IBinder>& display, bool on) {
8806     status_t status = checkAccessPermission();
8807     if (status != OK) {
8808         return binderStatusFromStatusT(status);
8809     }
8810     mFlinger->setGameContentType(display, on);
8811     return binder::Status::ok();
8812 }
8813 
captureDisplay(const DisplayCaptureArgs & args,const sp<IScreenCaptureListener> & captureListener)8814 binder::Status SurfaceComposerAIDL::captureDisplay(
8815         const DisplayCaptureArgs& args, const sp<IScreenCaptureListener>& captureListener) {
8816     status_t status = mFlinger->captureDisplay(args, captureListener);
8817     return binderStatusFromStatusT(status);
8818 }
8819 
captureDisplayById(int64_t displayId,const sp<IScreenCaptureListener> & captureListener)8820 binder::Status SurfaceComposerAIDL::captureDisplayById(
8821         int64_t displayId, const sp<IScreenCaptureListener>& captureListener) {
8822     status_t status;
8823     IPCThreadState* ipc = IPCThreadState::self();
8824     const int uid = ipc->getCallingUid();
8825     if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
8826         std::optional<DisplayId> id = DisplayId::fromValue(static_cast<uint64_t>(displayId));
8827         status = mFlinger->captureDisplay(*id, captureListener);
8828     } else {
8829         status = PERMISSION_DENIED;
8830     }
8831     return binderStatusFromStatusT(status);
8832 }
8833 
captureLayers(const LayerCaptureArgs & args,const sp<IScreenCaptureListener> & captureListener)8834 binder::Status SurfaceComposerAIDL::captureLayers(
8835         const LayerCaptureArgs& args, const sp<IScreenCaptureListener>& captureListener) {
8836     status_t status = mFlinger->captureLayers(args, captureListener);
8837     return binderStatusFromStatusT(status);
8838 }
8839 
overrideHdrTypes(const sp<IBinder> & display,const std::vector<int32_t> & hdrTypes)8840 binder::Status SurfaceComposerAIDL::overrideHdrTypes(const sp<IBinder>& display,
8841                                                      const std::vector<int32_t>& hdrTypes) {
8842     // overrideHdrTypes is used by CTS tests, which acquire the necessary
8843     // permission dynamically. Don't use the permission cache for this check.
8844     status_t status = checkAccessPermission(false);
8845     if (status != OK) {
8846         return binderStatusFromStatusT(status);
8847     }
8848 
8849     std::vector<ui::Hdr> hdrTypesVector;
8850     for (int32_t i : hdrTypes) {
8851         hdrTypesVector.push_back(static_cast<ui::Hdr>(i));
8852     }
8853     status = mFlinger->overrideHdrTypes(display, hdrTypesVector);
8854     return binderStatusFromStatusT(status);
8855 }
8856 
onPullAtom(int32_t atomId,gui::PullAtomData * outPullData)8857 binder::Status SurfaceComposerAIDL::onPullAtom(int32_t atomId, gui::PullAtomData* outPullData) {
8858     status_t status;
8859     const int uid = IPCThreadState::self()->getCallingUid();
8860     if (uid != AID_SYSTEM) {
8861         status = PERMISSION_DENIED;
8862     } else {
8863         status = mFlinger->onPullAtom(atomId, &outPullData->data, &outPullData->success);
8864     }
8865     return binderStatusFromStatusT(status);
8866 }
8867 
getLayerDebugInfo(std::vector<gui::LayerDebugInfo> * outLayers)8868 binder::Status SurfaceComposerAIDL::getLayerDebugInfo(std::vector<gui::LayerDebugInfo>* outLayers) {
8869     if (!outLayers) {
8870         return binderStatusFromStatusT(UNEXPECTED_NULL);
8871     }
8872 
8873     IPCThreadState* ipc = IPCThreadState::self();
8874     const int pid = ipc->getCallingPid();
8875     const int uid = ipc->getCallingUid();
8876     if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
8877         ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
8878         return binderStatusFromStatusT(PERMISSION_DENIED);
8879     }
8880     status_t status = mFlinger->getLayerDebugInfo(outLayers);
8881     return binderStatusFromStatusT(status);
8882 }
8883 
getColorManagement(bool * outGetColorManagement)8884 binder::Status SurfaceComposerAIDL::getColorManagement(bool* outGetColorManagement) {
8885     status_t status = mFlinger->getColorManagement(outGetColorManagement);
8886     return binderStatusFromStatusT(status);
8887 }
8888 
getCompositionPreference(gui::CompositionPreference * outPref)8889 binder::Status SurfaceComposerAIDL::getCompositionPreference(gui::CompositionPreference* outPref) {
8890     ui::Dataspace dataspace;
8891     ui::PixelFormat pixelFormat;
8892     ui::Dataspace wideColorGamutDataspace;
8893     ui::PixelFormat wideColorGamutPixelFormat;
8894     status_t status =
8895             mFlinger->getCompositionPreference(&dataspace, &pixelFormat, &wideColorGamutDataspace,
8896                                                &wideColorGamutPixelFormat);
8897     if (status == NO_ERROR) {
8898         outPref->defaultDataspace = static_cast<int32_t>(dataspace);
8899         outPref->defaultPixelFormat = static_cast<int32_t>(pixelFormat);
8900         outPref->wideColorGamutDataspace = static_cast<int32_t>(wideColorGamutDataspace);
8901         outPref->wideColorGamutPixelFormat = static_cast<int32_t>(wideColorGamutPixelFormat);
8902     }
8903     return binderStatusFromStatusT(status);
8904 }
8905 
getDisplayedContentSamplingAttributes(const sp<IBinder> & display,gui::ContentSamplingAttributes * outAttrs)8906 binder::Status SurfaceComposerAIDL::getDisplayedContentSamplingAttributes(
8907         const sp<IBinder>& display, gui::ContentSamplingAttributes* outAttrs) {
8908     status_t status = checkAccessPermission();
8909     if (status != OK) {
8910         return binderStatusFromStatusT(status);
8911     }
8912 
8913     ui::PixelFormat format;
8914     ui::Dataspace dataspace;
8915     uint8_t componentMask;
8916     status = mFlinger->getDisplayedContentSamplingAttributes(display, &format, &dataspace,
8917                                                              &componentMask);
8918     if (status == NO_ERROR) {
8919         outAttrs->format = static_cast<int32_t>(format);
8920         outAttrs->dataspace = static_cast<int32_t>(dataspace);
8921         outAttrs->componentMask = static_cast<int8_t>(componentMask);
8922     }
8923     return binderStatusFromStatusT(status);
8924 }
8925 
setDisplayContentSamplingEnabled(const sp<IBinder> & display,bool enable,int8_t componentMask,int64_t maxFrames)8926 binder::Status SurfaceComposerAIDL::setDisplayContentSamplingEnabled(const sp<IBinder>& display,
8927                                                                      bool enable,
8928                                                                      int8_t componentMask,
8929                                                                      int64_t maxFrames) {
8930     status_t status = checkAccessPermission();
8931     if (status == OK) {
8932         status = mFlinger->setDisplayContentSamplingEnabled(display, enable,
8933                                                             static_cast<uint8_t>(componentMask),
8934                                                             static_cast<uint64_t>(maxFrames));
8935     }
8936     return binderStatusFromStatusT(status);
8937 }
8938 
getDisplayedContentSample(const sp<IBinder> & display,int64_t maxFrames,int64_t timestamp,gui::DisplayedFrameStats * outStats)8939 binder::Status SurfaceComposerAIDL::getDisplayedContentSample(const sp<IBinder>& display,
8940                                                               int64_t maxFrames, int64_t timestamp,
8941                                                               gui::DisplayedFrameStats* outStats) {
8942     if (!outStats) {
8943         return binderStatusFromStatusT(BAD_VALUE);
8944     }
8945 
8946     status_t status = checkAccessPermission();
8947     if (status != OK) {
8948         return binderStatusFromStatusT(status);
8949     }
8950 
8951     DisplayedFrameStats stats;
8952     status = mFlinger->getDisplayedContentSample(display, static_cast<uint64_t>(maxFrames),
8953                                                  static_cast<uint64_t>(timestamp), &stats);
8954     if (status == NO_ERROR) {
8955         // convert from ui::DisplayedFrameStats to gui::DisplayedFrameStats
8956         outStats->numFrames = static_cast<int64_t>(stats.numFrames);
8957         outStats->component_0_sample.reserve(stats.component_0_sample.size());
8958         for (const auto& s : stats.component_0_sample) {
8959             outStats->component_0_sample.push_back(static_cast<int64_t>(s));
8960         }
8961         outStats->component_1_sample.reserve(stats.component_1_sample.size());
8962         for (const auto& s : stats.component_1_sample) {
8963             outStats->component_1_sample.push_back(static_cast<int64_t>(s));
8964         }
8965         outStats->component_2_sample.reserve(stats.component_2_sample.size());
8966         for (const auto& s : stats.component_2_sample) {
8967             outStats->component_2_sample.push_back(static_cast<int64_t>(s));
8968         }
8969         outStats->component_3_sample.reserve(stats.component_3_sample.size());
8970         for (const auto& s : stats.component_3_sample) {
8971             outStats->component_3_sample.push_back(static_cast<int64_t>(s));
8972         }
8973     }
8974     return binderStatusFromStatusT(status);
8975 }
8976 
getProtectedContentSupport(bool * outSupported)8977 binder::Status SurfaceComposerAIDL::getProtectedContentSupport(bool* outSupported) {
8978     status_t status = mFlinger->getProtectedContentSupport(outSupported);
8979     return binderStatusFromStatusT(status);
8980 }
8981 
isWideColorDisplay(const sp<IBinder> & token,bool * outIsWideColorDisplay)8982 binder::Status SurfaceComposerAIDL::isWideColorDisplay(const sp<IBinder>& token,
8983                                                        bool* outIsWideColorDisplay) {
8984     status_t status = mFlinger->isWideColorDisplay(token, outIsWideColorDisplay);
8985     return binderStatusFromStatusT(status);
8986 }
8987 
addRegionSamplingListener(const gui::ARect & samplingArea,const sp<IBinder> & stopLayerHandle,const sp<gui::IRegionSamplingListener> & listener)8988 binder::Status SurfaceComposerAIDL::addRegionSamplingListener(
8989         const gui::ARect& samplingArea, const sp<IBinder>& stopLayerHandle,
8990         const sp<gui::IRegionSamplingListener>& listener) {
8991     status_t status = checkReadFrameBufferPermission();
8992     if (status != OK) {
8993         return binderStatusFromStatusT(status);
8994     }
8995     android::Rect rect;
8996     rect.left = samplingArea.left;
8997     rect.top = samplingArea.top;
8998     rect.right = samplingArea.right;
8999     rect.bottom = samplingArea.bottom;
9000     status = mFlinger->addRegionSamplingListener(rect, stopLayerHandle, listener);
9001     return binderStatusFromStatusT(status);
9002 }
9003 
removeRegionSamplingListener(const sp<gui::IRegionSamplingListener> & listener)9004 binder::Status SurfaceComposerAIDL::removeRegionSamplingListener(
9005         const sp<gui::IRegionSamplingListener>& listener) {
9006     status_t status = checkReadFrameBufferPermission();
9007     if (status == OK) {
9008         status = mFlinger->removeRegionSamplingListener(listener);
9009     }
9010     return binderStatusFromStatusT(status);
9011 }
9012 
addFpsListener(int32_t taskId,const sp<gui::IFpsListener> & listener)9013 binder::Status SurfaceComposerAIDL::addFpsListener(int32_t taskId,
9014                                                    const sp<gui::IFpsListener>& listener) {
9015     status_t status = checkReadFrameBufferPermission();
9016     if (status == OK) {
9017         status = mFlinger->addFpsListener(taskId, listener);
9018     }
9019     return binderStatusFromStatusT(status);
9020 }
9021 
removeFpsListener(const sp<gui::IFpsListener> & listener)9022 binder::Status SurfaceComposerAIDL::removeFpsListener(const sp<gui::IFpsListener>& listener) {
9023     status_t status = checkReadFrameBufferPermission();
9024     if (status == OK) {
9025         status = mFlinger->removeFpsListener(listener);
9026     }
9027     return binderStatusFromStatusT(status);
9028 }
9029 
addTunnelModeEnabledListener(const sp<gui::ITunnelModeEnabledListener> & listener)9030 binder::Status SurfaceComposerAIDL::addTunnelModeEnabledListener(
9031         const sp<gui::ITunnelModeEnabledListener>& listener) {
9032     status_t status = checkAccessPermission();
9033     if (status == OK) {
9034         status = mFlinger->addTunnelModeEnabledListener(listener);
9035     }
9036     return binderStatusFromStatusT(status);
9037 }
9038 
removeTunnelModeEnabledListener(const sp<gui::ITunnelModeEnabledListener> & listener)9039 binder::Status SurfaceComposerAIDL::removeTunnelModeEnabledListener(
9040         const sp<gui::ITunnelModeEnabledListener>& listener) {
9041     status_t status = checkAccessPermission();
9042     if (status == OK) {
9043         status = mFlinger->removeTunnelModeEnabledListener(listener);
9044     }
9045     return binderStatusFromStatusT(status);
9046 }
9047 
setDesiredDisplayModeSpecs(const sp<IBinder> & displayToken,const gui::DisplayModeSpecs & specs)9048 binder::Status SurfaceComposerAIDL::setDesiredDisplayModeSpecs(const sp<IBinder>& displayToken,
9049                                                                const gui::DisplayModeSpecs& specs) {
9050     status_t status = checkAccessPermission();
9051     if (status == OK) {
9052         status = mFlinger->setDesiredDisplayModeSpecs(displayToken, specs);
9053     }
9054     return binderStatusFromStatusT(status);
9055 }
9056 
getDesiredDisplayModeSpecs(const sp<IBinder> & displayToken,gui::DisplayModeSpecs * outSpecs)9057 binder::Status SurfaceComposerAIDL::getDesiredDisplayModeSpecs(const sp<IBinder>& displayToken,
9058                                                                gui::DisplayModeSpecs* outSpecs) {
9059     if (!outSpecs) {
9060         return binderStatusFromStatusT(BAD_VALUE);
9061     }
9062 
9063     status_t status = checkAccessPermission();
9064     if (status != OK) {
9065         return binderStatusFromStatusT(status);
9066     }
9067 
9068     status = mFlinger->getDesiredDisplayModeSpecs(displayToken, outSpecs);
9069     return binderStatusFromStatusT(status);
9070 }
9071 
getDisplayBrightnessSupport(const sp<IBinder> & displayToken,bool * outSupport)9072 binder::Status SurfaceComposerAIDL::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
9073                                                                 bool* outSupport) {
9074     status_t status = mFlinger->getDisplayBrightnessSupport(displayToken, outSupport);
9075     return binderStatusFromStatusT(status);
9076 }
9077 
setDisplayBrightness(const sp<IBinder> & displayToken,const gui::DisplayBrightness & brightness)9078 binder::Status SurfaceComposerAIDL::setDisplayBrightness(const sp<IBinder>& displayToken,
9079                                                          const gui::DisplayBrightness& brightness) {
9080     status_t status = checkControlDisplayBrightnessPermission();
9081     if (status == OK) {
9082         status = mFlinger->setDisplayBrightness(displayToken, brightness);
9083     }
9084     return binderStatusFromStatusT(status);
9085 }
9086 
addHdrLayerInfoListener(const sp<IBinder> & displayToken,const sp<gui::IHdrLayerInfoListener> & listener)9087 binder::Status SurfaceComposerAIDL::addHdrLayerInfoListener(
9088         const sp<IBinder>& displayToken, const sp<gui::IHdrLayerInfoListener>& listener) {
9089     status_t status = checkControlDisplayBrightnessPermission();
9090     if (status == OK) {
9091         status = mFlinger->addHdrLayerInfoListener(displayToken, listener);
9092     }
9093     return binderStatusFromStatusT(status);
9094 }
9095 
removeHdrLayerInfoListener(const sp<IBinder> & displayToken,const sp<gui::IHdrLayerInfoListener> & listener)9096 binder::Status SurfaceComposerAIDL::removeHdrLayerInfoListener(
9097         const sp<IBinder>& displayToken, const sp<gui::IHdrLayerInfoListener>& listener) {
9098     status_t status = checkControlDisplayBrightnessPermission();
9099     if (status == OK) {
9100         status = mFlinger->removeHdrLayerInfoListener(displayToken, listener);
9101     }
9102     return binderStatusFromStatusT(status);
9103 }
9104 
notifyPowerBoost(int boostId)9105 binder::Status SurfaceComposerAIDL::notifyPowerBoost(int boostId) {
9106     status_t status = checkAccessPermission();
9107     if (status == OK) {
9108         status = mFlinger->notifyPowerBoost(boostId);
9109     }
9110     return binderStatusFromStatusT(status);
9111 }
9112 
setGlobalShadowSettings(const gui::Color & ambientColor,const gui::Color & spotColor,float lightPosY,float lightPosZ,float lightRadius)9113 binder::Status SurfaceComposerAIDL::setGlobalShadowSettings(const gui::Color& ambientColor,
9114                                                             const gui::Color& spotColor,
9115                                                             float lightPosY, float lightPosZ,
9116                                                             float lightRadius) {
9117     status_t status = checkAccessPermission();
9118     if (status != OK) {
9119         return binderStatusFromStatusT(status);
9120     }
9121 
9122     half4 ambientColorHalf = {ambientColor.r, ambientColor.g, ambientColor.b, ambientColor.a};
9123     half4 spotColorHalf = {spotColor.r, spotColor.g, spotColor.b, spotColor.a};
9124     status = mFlinger->setGlobalShadowSettings(ambientColorHalf, spotColorHalf, lightPosY,
9125                                                lightPosZ, lightRadius);
9126     return binderStatusFromStatusT(status);
9127 }
9128 
getDisplayDecorationSupport(const sp<IBinder> & displayToken,std::optional<gui::DisplayDecorationSupport> * outSupport)9129 binder::Status SurfaceComposerAIDL::getDisplayDecorationSupport(
9130         const sp<IBinder>& displayToken, std::optional<gui::DisplayDecorationSupport>* outSupport) {
9131     std::optional<aidl::android::hardware::graphics::common::DisplayDecorationSupport> support;
9132     status_t status = mFlinger->getDisplayDecorationSupport(displayToken, &support);
9133     if (status != NO_ERROR) {
9134         ALOGE("getDisplayDecorationSupport failed with error %d", status);
9135         return binderStatusFromStatusT(status);
9136     }
9137 
9138     if (!support || !support.has_value()) {
9139         outSupport->reset();
9140     } else {
9141         outSupport->emplace();
9142         outSupport->value().format = static_cast<int32_t>(support->format);
9143         outSupport->value().alphaInterpretation =
9144                 static_cast<int32_t>(support->alphaInterpretation);
9145     }
9146 
9147     return binder::Status::ok();
9148 }
9149 
setOverrideFrameRate(int32_t uid,float frameRate)9150 binder::Status SurfaceComposerAIDL::setOverrideFrameRate(int32_t uid, float frameRate) {
9151     status_t status;
9152     const int c_uid = IPCThreadState::self()->getCallingUid();
9153     if (c_uid == AID_ROOT || c_uid == AID_SYSTEM) {
9154         status = mFlinger->setOverrideFrameRate(uid, frameRate);
9155     } else {
9156         ALOGE("setOverrideFrameRate() permission denied for uid: %d", c_uid);
9157         status = PERMISSION_DENIED;
9158     }
9159     return binderStatusFromStatusT(status);
9160 }
9161 
updateSmallAreaDetection(const std::vector<int32_t> & uids,const std::vector<float> & thresholds)9162 binder::Status SurfaceComposerAIDL::updateSmallAreaDetection(const std::vector<int32_t>& uids,
9163                                                              const std::vector<float>& thresholds) {
9164     status_t status;
9165     const int c_uid = IPCThreadState::self()->getCallingUid();
9166     if (c_uid == AID_ROOT || c_uid == AID_SYSTEM) {
9167         if (uids.size() != thresholds.size()) return binderStatusFromStatusT(BAD_VALUE);
9168 
9169         std::vector<std::pair<uid_t, float>> mappings;
9170         const size_t size = uids.size();
9171         mappings.reserve(size);
9172         for (int i = 0; i < size; i++) {
9173             auto row = std::make_pair(static_cast<uid_t>(uids[i]), thresholds[i]);
9174             mappings.push_back(row);
9175         }
9176         status = mFlinger->updateSmallAreaDetection(mappings);
9177     } else {
9178         ALOGE("updateSmallAreaDetection() permission denied for uid: %d", c_uid);
9179         status = PERMISSION_DENIED;
9180     }
9181     return binderStatusFromStatusT(status);
9182 }
9183 
setSmallAreaDetectionThreshold(int32_t uid,float threshold)9184 binder::Status SurfaceComposerAIDL::setSmallAreaDetectionThreshold(int32_t uid, float threshold) {
9185     status_t status;
9186     const int c_uid = IPCThreadState::self()->getCallingUid();
9187     if (c_uid == AID_ROOT || c_uid == AID_SYSTEM) {
9188         status = mFlinger->setSmallAreaDetectionThreshold(uid, threshold);
9189     } else {
9190         ALOGE("setSmallAreaDetectionThreshold() permission denied for uid: %d", c_uid);
9191         status = PERMISSION_DENIED;
9192     }
9193     return binderStatusFromStatusT(status);
9194 }
9195 
getGpuContextPriority(int32_t * outPriority)9196 binder::Status SurfaceComposerAIDL::getGpuContextPriority(int32_t* outPriority) {
9197     *outPriority = mFlinger->getGpuContextPriority();
9198     return binder::Status::ok();
9199 }
9200 
getMaxAcquiredBufferCount(int32_t * buffers)9201 binder::Status SurfaceComposerAIDL::getMaxAcquiredBufferCount(int32_t* buffers) {
9202     status_t status = mFlinger->getMaxAcquiredBufferCount(buffers);
9203     return binderStatusFromStatusT(status);
9204 }
9205 
addWindowInfosListener(const sp<gui::IWindowInfosListener> & windowInfosListener,gui::WindowInfosListenerInfo * outInfo)9206 binder::Status SurfaceComposerAIDL::addWindowInfosListener(
9207         const sp<gui::IWindowInfosListener>& windowInfosListener,
9208         gui::WindowInfosListenerInfo* outInfo) {
9209     status_t status;
9210     const int pid = IPCThreadState::self()->getCallingPid();
9211     const int uid = IPCThreadState::self()->getCallingUid();
9212     // TODO(b/270566761) update permissions check so that only system_server and shell can add
9213     // WindowInfosListeners
9214     if (uid == AID_SYSTEM || uid == AID_GRAPHICS ||
9215         checkPermission(sAccessSurfaceFlinger, pid, uid)) {
9216         status = mFlinger->addWindowInfosListener(windowInfosListener, outInfo);
9217     } else {
9218         status = PERMISSION_DENIED;
9219     }
9220     return binderStatusFromStatusT(status);
9221 }
9222 
removeWindowInfosListener(const sp<gui::IWindowInfosListener> & windowInfosListener)9223 binder::Status SurfaceComposerAIDL::removeWindowInfosListener(
9224         const sp<gui::IWindowInfosListener>& windowInfosListener) {
9225     status_t status;
9226     const int pid = IPCThreadState::self()->getCallingPid();
9227     const int uid = IPCThreadState::self()->getCallingUid();
9228     if (uid == AID_SYSTEM || uid == AID_GRAPHICS ||
9229         checkPermission(sAccessSurfaceFlinger, pid, uid)) {
9230         status = mFlinger->removeWindowInfosListener(windowInfosListener);
9231     } else {
9232         status = PERMISSION_DENIED;
9233     }
9234     return binderStatusFromStatusT(status);
9235 }
9236 
getStalledTransactionInfo(int pid,std::optional<gui::StalledTransactionInfo> * outInfo)9237 binder::Status SurfaceComposerAIDL::getStalledTransactionInfo(
9238         int pid, std::optional<gui::StalledTransactionInfo>* outInfo) {
9239     const int callingPid = IPCThreadState::self()->getCallingPid();
9240     const int callingUid = IPCThreadState::self()->getCallingUid();
9241     if (!checkPermission(sAccessSurfaceFlinger, callingPid, callingUid)) {
9242         return binderStatusFromStatusT(PERMISSION_DENIED);
9243     }
9244 
9245     std::optional<TransactionHandler::StalledTransactionInfo> stalledTransactionInfo;
9246     status_t status = mFlinger->getStalledTransactionInfo(pid, stalledTransactionInfo);
9247     if (stalledTransactionInfo) {
9248         gui::StalledTransactionInfo result;
9249         result.layerName = String16{stalledTransactionInfo->layerName.c_str()},
9250         result.bufferId = stalledTransactionInfo->bufferId,
9251         result.frameNumber = stalledTransactionInfo->frameNumber,
9252         outInfo->emplace(std::move(result));
9253     } else {
9254         outInfo->reset();
9255     }
9256     return binderStatusFromStatusT(status);
9257 }
9258 
checkAccessPermission(bool usePermissionCache)9259 status_t SurfaceComposerAIDL::checkAccessPermission(bool usePermissionCache) {
9260     if (!mFlinger->callingThreadHasUnscopedSurfaceFlingerAccess(usePermissionCache)) {
9261         IPCThreadState* ipc = IPCThreadState::self();
9262         ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", ipc->getCallingPid(),
9263               ipc->getCallingUid());
9264         return PERMISSION_DENIED;
9265     }
9266     return OK;
9267 }
9268 
checkControlDisplayBrightnessPermission()9269 status_t SurfaceComposerAIDL::checkControlDisplayBrightnessPermission() {
9270     IPCThreadState* ipc = IPCThreadState::self();
9271     const int pid = ipc->getCallingPid();
9272     const int uid = ipc->getCallingUid();
9273     if ((uid != AID_GRAPHICS) && (uid != AID_SYSTEM) &&
9274         !PermissionCache::checkPermission(sControlDisplayBrightness, pid, uid)) {
9275         ALOGE("Permission Denial: can't control brightness pid=%d, uid=%d", pid, uid);
9276         return PERMISSION_DENIED;
9277     }
9278     return OK;
9279 }
9280 
checkReadFrameBufferPermission()9281 status_t SurfaceComposerAIDL::checkReadFrameBufferPermission() {
9282     IPCThreadState* ipc = IPCThreadState::self();
9283     const int pid = ipc->getCallingPid();
9284     const int uid = ipc->getCallingUid();
9285     if ((uid != AID_GRAPHICS) && !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
9286         ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
9287         return PERMISSION_DENIED;
9288     }
9289     return OK;
9290 }
9291 
forceFutureUpdate(int delayInMs)9292 void SurfaceFlinger::forceFutureUpdate(int delayInMs) {
9293     static_cast<void>(mScheduler->scheduleDelayed([&]() { scheduleRepaint(); }, ms2ns(delayInMs)));
9294 }
9295 
getDisplayFromLayerStack(ui::LayerStack layerStack)9296 const DisplayDevice* SurfaceFlinger::getDisplayFromLayerStack(ui::LayerStack layerStack) {
9297     for (const auto& [_, display] : mDisplays) {
9298         if (display->getLayerStack() == layerStack) {
9299             return display.get();
9300         }
9301     }
9302     return nullptr;
9303 }
9304 
9305 } // namespace android
9306 
9307 #if defined(__gl_h_)
9308 #error "don't include gl/gl.h in this file"
9309 #endif
9310 
9311 #if defined(__gl2_h_)
9312 #error "don't include gl2/gl2.h in this file"
9313 #endif
9314 
9315 // TODO(b/129481165): remove the #pragma below and fix conversion issues
9316 #pragma clang diagnostic pop // ignored "-Wconversion -Wextra"
9317