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