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