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