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