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