blob: 9d65f2f2af769bee086d5ec5c0c3cfebd1f34452 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
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
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -080017// TODO(b/129481165): remove the #pragma below and fix conversion issues
18#pragma clang diagnostic push
19#pragma clang diagnostic ignored "-Wconversion"
20
Alec Mourie7d1d4a2019-02-05 01:13:46 +000021//#define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080022#define ATRACE_TAG ATRACE_TAG_GRAPHICS
23
Alec Mouri989ddbe2020-02-06 09:26:19 -080024#include "SurfaceFlinger.h"
Dominik Laskowski83b88212018-12-11 13:34:06 -080025
Ana Krulecb9afd792020-06-11 13:16:15 -070026#include <android-base/properties.h>
Alec Mouri989ddbe2020-02-06 09:26:19 -080027#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>
Steven Thomas62a4cf82020-01-31 12:04:03 -080032#include <android/native_window.h>
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070033#include <binder/IPCThreadState.h>
34#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070035#include <binder/PermissionCache.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070036#include <compositionengine/CompositionEngine.h>
Lloyd Piqueab039b52019-02-13 14:22:42 -080037#include <compositionengine/CompositionRefreshArgs.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070038#include <compositionengine/Display.h>
Lloyd Pique3d0c02e2018-10-19 18:38:12 -070039#include <compositionengine/DisplayColorProfile.h>
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -070040#include <compositionengine/DisplayCreationArgs.h>
Lloyd Piquede196652020-01-22 17:29:58 -080041#include <compositionengine/LayerFECompositionState.h>
Lloyd Piquecc01a452018-12-04 17:24:00 -080042#include <compositionengine/OutputLayer.h>
Lloyd Pique31cb2942018-10-19 17:23:03 -070043#include <compositionengine/RenderSurface.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070044#include <compositionengine/impl/OutputCompositionState.h>
Alec Mouri989ddbe2020-02-06 09:26:19 -080045#include <configstore/Utils.h>
46#include <cutils/compiler.h>
47#include <cutils/properties.h>
48#include <dlfcn.h>
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080049#include <dvr/vr_flinger.h>
Alec Mouri989ddbe2020-02-06 09:26:19 -080050#include <errno.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070051#include <gui/BufferQueue.h>
Ady Abrahama3b08ef2019-07-15 18:43:10 -070052#include <gui/DebugEGLImageTracker.h>
Andy McFadden4803b742012-09-24 19:07:20 -070053#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070054#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080055#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080056#include <gui/LayerDebugInfo.h>
Lloyd Pique4603f3c2020-02-11 12:06:56 -080057#include <gui/LayerMetadata.h>
Steven Thomas62a4cf82020-01-31 12:04:03 -080058#include <gui/LayerState.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080059#include <gui/Surface.h>
Steven Moreland7c8af942020-07-08 18:35:51 +000060#include <hidl/ServiceManagement.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070061#include <input/IInputFlinger.h>
Alec Mouri989ddbe2020-02-06 09:26:19 -080062#include <layerproto/LayerProtoParser.h>
63#include <log/log.h>
64#include <private/android_filesystem_config.h>
65#include <private/gui/SyncFeatures.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070066#include <renderengine/RenderEngine.h>
Alec Mouri989ddbe2020-02-06 09:26:19 -080067#include <statslog.h>
68#include <sys/types.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070069#include <ui/ColorSpace.h>
70#include <ui/DebugUtils.h>
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -080071#include <ui/DisplayConfig.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070072#include <ui/DisplayInfo.h>
73#include <ui/DisplayStatInfo.h>
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -080074#include <ui/DisplayState.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070075#include <ui/GraphicBufferAllocator.h>
76#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070077#include <ui/UiConfig.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080078#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070079#include <utils/String16.h>
80#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070081#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080082#include <utils/Trace.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070083#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080084
Alec Mouri989ddbe2020-02-06 09:26:19 -080085#include <algorithm>
86#include <cinttypes>
87#include <cmath>
88#include <cstdint>
89#include <functional>
90#include <mutex>
91#include <optional>
92#include <unordered_map>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080093
Robert Carr578038f2018-03-09 12:25:24 -080094#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070095#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070096#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020097#include "Client.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020098#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080099#include "ContainerLayer.h"
Robert Carr578038f2018-03-09 12:25:24 -0800100#include "DisplayDevice.h"
Steven Thomasb02664d2017-07-26 18:48:28 -0700101#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -0700102#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -0700103#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -0700104#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -0700105#include "DisplayHardware/VirtualDisplaySurface.h"
Alec Mouri989ddbe2020-02-06 09:26:19 -0800106#include "EffectLayer.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -0700107#include "Effects/Daltonizer.h"
Mikael Pessa90092f42019-08-26 17:22:04 -0700108#include "FrameTracer/FrameTracer.h"
Alec Mouri989ddbe2020-02-06 09:26:19 -0800109#include "Layer.h"
110#include "LayerVector.h"
111#include "MonitoredProducer.h"
112#include "NativeWindowSurface.h"
Dominik Laskowski5690bde2020-04-23 19:04:22 -0700113#include "Promise.h"
Alec Mouri989ddbe2020-02-06 09:26:19 -0800114#include "RefreshRateOverlay.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700115#include "RegionSamplingThread.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700116#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -0700117#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700118#include "Scheduler/EventControlThread.h"
119#include "Scheduler/EventThread.h"
Ady Abraham5def7332020-05-29 16:13:47 -0700120#include "Scheduler/LayerHistory.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -0700121#include "Scheduler/MessageQueue.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700122#include "Scheduler/PhaseOffsets.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700123#include "Scheduler/Scheduler.h"
Alec Mouri989ddbe2020-02-06 09:26:19 -0800124#include "StartPropertySetThread.h"
125#include "SurfaceFlingerProperties.h"
126#include "SurfaceInterceptor.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800127#include "TimeStats/TimeStats.h"
Dominik Laskowskib6e54372019-09-04 14:06:28 -0700128#include "android-base/parseint.h"
David Sodman7e4ae112018-02-09 15:02:28 -0800129#include "android-base/stringprintf.h"
130
Dominik Laskowskia19f4b62020-04-21 00:27:31 -0700131#define MAIN_THREAD ACQUIRE(mStateLock) RELEASE(mStateLock)
132
133#define ON_MAIN_THREAD(expr) \
134 [&] { \
135 LOG_FATAL_IF(std::this_thread::get_id() != mMainThreadId); \
136 UnnecessaryLock lock(mStateLock); \
137 return (expr); \
138 }()
139
140#undef NO_THREAD_SAFETY_ANALYSIS
141#define NO_THREAD_SAFETY_ANALYSIS \
142 _Pragma("GCC error \"Prefer MAIN_THREAD macros or {Conditional,Timed,Unnecessary}Lock.\"")
143
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800144namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700145
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700146using namespace std::string_literals;
147
Jaesoo Lee43518572017-01-23 19:03:16 +0900148using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900149using namespace android::hardware::configstore::V1_0;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900150using namespace android::sysprop;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800151
Ady Abraham8532d012019-05-08 14:50:56 -0700152using android::hardware::power::V1_0::PowerHint;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800153using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700154using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700155using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800156using ui::DisplayPrimaries;
Peiyong Lin62665892018-04-16 11:07:44 -0700157using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700158using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900159
Peiyong Line9d809e2020-04-14 13:10:48 -0700160namespace hal = android::hardware::graphics::composer::hal;
161
Steven Thomasb02664d2017-07-26 18:48:28 -0700162namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700163
164#pragma clang diagnostic push
165#pragma clang diagnostic error "-Wswitch-enum"
166
167bool isWideColorMode(const ColorMode colorMode) {
168 switch (colorMode) {
169 case ColorMode::DISPLAY_P3:
170 case ColorMode::ADOBE_RGB:
171 case ColorMode::DCI_P3:
172 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700173 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700174 case ColorMode::BT2100_PQ:
175 case ColorMode::BT2100_HLG:
176 return true;
177 case ColorMode::NATIVE:
178 case ColorMode::STANDARD_BT601_625:
179 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
180 case ColorMode::STANDARD_BT601_525:
181 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
182 case ColorMode::STANDARD_BT709:
183 case ColorMode::SRGB:
184 return false;
185 }
186 return false;
187}
188
189#pragma clang diagnostic pop
190
Dominik Laskowski542c9dc2020-04-10 12:42:02 -0700191template <typename Mutex>
Dominik Laskowskia19f4b62020-04-21 00:27:31 -0700192struct SCOPED_CAPABILITY ConditionalLockGuard {
193 ConditionalLockGuard(Mutex& mutex, bool lock) ACQUIRE(mutex) : mutex(mutex), lock(lock) {
Dominik Laskowski542c9dc2020-04-10 12:42:02 -0700194 if (lock) mutex.lock();
Steven Thomasb02664d2017-07-26 18:48:28 -0700195 }
Dominik Laskowski542c9dc2020-04-10 12:42:02 -0700196
Dominik Laskowskia19f4b62020-04-21 00:27:31 -0700197 ~ConditionalLockGuard() RELEASE() {
Dominik Laskowski542c9dc2020-04-10 12:42:02 -0700198 if (lock) mutex.unlock();
199 }
200
201 Mutex& mutex;
202 const bool lock;
Steven Thomasb02664d2017-07-26 18:48:28 -0700203};
Peiyong Linfca547f2018-07-09 13:03:33 -0700204
Dominik Laskowski542c9dc2020-04-10 12:42:02 -0700205using ConditionalLock = ConditionalLockGuard<Mutex>;
206
Dominik Laskowskia19f4b62020-04-21 00:27:31 -0700207struct SCOPED_CAPABILITY TimedLock {
208 TimedLock(Mutex& mutex, nsecs_t timeout, const char* whence) ACQUIRE(mutex)
209 : mutex(mutex), status(mutex.timedLock(timeout)) {
210 ALOGE_IF(!locked(), "%s timed out locking: %s (%d)", whence, strerror(-status), status);
211 }
212
213 ~TimedLock() RELEASE() {
214 if (locked()) mutex.unlock();
215 }
216
217 bool locked() const { return status == NO_ERROR; }
218
219 Mutex& mutex;
220 const status_t status;
221};
222
223struct SCOPED_CAPABILITY UnnecessaryLock {
224 explicit UnnecessaryLock(Mutex& mutex) ACQUIRE(mutex) {}
225 ~UnnecessaryLock() RELEASE() {}
226};
227
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800228// TODO(b/141333600): Consolidate with HWC2::Display::Config::Builder::getDefaultDensity.
Dominik Laskowskid125d0e2020-05-08 12:36:39 -0700229constexpr float FALLBACK_DENSITY = ACONFIGURATION_DENSITY_TV;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800230
231float getDensityFromProperty(const char* property, bool required) {
232 char value[PROPERTY_VALUE_MAX];
233 const float density = property_get(property, value, nullptr) > 0 ? std::atof(value) : 0.f;
234 if (!density && required) {
235 ALOGE("%s must be defined as a build property", property);
236 return FALLBACK_DENSITY;
237 }
Dominik Laskowskid125d0e2020-05-08 12:36:39 -0700238 return density;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800239}
240
Peiyong Lin9d846a52018-11-05 13:18:20 -0800241// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
242bool validateCompositionDataspace(Dataspace dataspace) {
243 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
244}
245
Steven Thomasd4071902020-03-24 16:02:53 -0700246class FrameRateFlexibilityToken : public BBinder {
247public:
248 FrameRateFlexibilityToken(std::function<void()> callback) : mCallback(callback) {}
249 virtual ~FrameRateFlexibilityToken() { mCallback(); }
250
251private:
252 std::function<void()> mCallback;
253};
254
Steven Thomasb02664d2017-07-26 18:48:28 -0700255} // namespace anonymous
256
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800257// ---------------------------------------------------------------------------
258
Mathias Agopian99b49842011-06-27 16:05:52 -0700259const String16 sHardwareTest("android.permission.HARDWARE_TEST");
260const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
261const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
262const String16 sDump("android.permission.DUMP");
Amy Hsuc8cdfef2020-05-07 13:06:25 +0800263const char* KERNEL_IDLE_TIMER_PROP = "graphics.display.kernel_idle_timer.enabled";
Mathias Agopian99b49842011-06-27 16:05:52 -0700264
265// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700266int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700267bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800268uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800269bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800270bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800271int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Brian Lindahla13f2d52020-03-05 11:54:17 +0100272uint32_t SurfaceFlinger::maxGraphicsWidth;
273uint32_t SurfaceFlinger::maxGraphicsHeight;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600274bool SurfaceFlinger::hasWideColorDisplay;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800275ui::Rotation SurfaceFlinger::internalDisplayOrientation = ui::ROTATION_0;
Peiyong Lin13effd12018-07-24 17:01:47 -0700276bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700277bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700278Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
279ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
280Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
281ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Ana Krulec3803b8d2020-02-03 16:35:46 -0800282bool SurfaceFlinger::useFrameRateApi;
Mathias Agopian99b49842011-06-27 16:05:52 -0700283
Kalle Raitaa099a242017-01-11 11:17:29 -0800284std::string getHwcServiceName() {
285 char value[PROPERTY_VALUE_MAX] = {};
286 property_get("debug.sf.hwc_service_name", value, "default");
287 ALOGI("Using HWComposer service: '%s'", value);
288 return std::string(value);
289}
290
291bool useTrebleTestingOverride() {
292 char value[PROPERTY_VALUE_MAX] = {};
293 property_get("debug.sf.treble_testing_override", value, "false");
294 ALOGI("Treble testing override: '%s'", value);
295 return std::string(value) == "true";
296}
297
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800298std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
299 switch(displayColorSetting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800300 case DisplayColorSetting::kManaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700301 return std::string("Managed");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800302 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700303 return std::string("Unmanaged");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800304 case DisplayColorSetting::kEnhanced:
Chia-I Wu0d711262018-05-21 15:19:35 -0700305 return std::string("Enhanced");
306 default:
307 return std::string("Unknown ") +
308 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800309 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800310}
311
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700312SurfaceFlingerBE::SurfaceFlingerBE() : mHwcServiceName(getHwcServiceName()) {}
David Sodmanbc815282017-11-05 18:57:52 -0800313
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700314SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
315 : mFactory(factory),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700316 mInterceptor(mFactory.createSurfaceInterceptor(this)),
Yiwei Zhangf0229a72019-09-09 19:28:02 -0700317 mTimeStats(std::make_shared<impl::TimeStats>()),
Mikael Pessa90092f42019-08-26 17:22:04 -0700318 mFrameTracer(std::make_unique<FrameTracer>()),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700319 mEventQueue(mFactory.createMessageQueue()),
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700320 mCompositionEngine(mFactory.createCompositionEngine()),
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800321 mInternalDisplayDensity(getDensityFromProperty("ro.sf.lcd_density", true)),
322 mEmulatedDisplayDensity(getDensityFromProperty("qemu.sf.lcd_density", false)) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800323
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700324SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800325 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800326
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900327 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800328
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900329 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700330
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900331 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700332
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900333 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800334
Steven Thomas050b2c82017-03-06 11:45:16 -0800335 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900336 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800337
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900338 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800339
Brian Lindahla13f2d52020-03-05 11:54:17 +0100340 maxGraphicsWidth = std::max(max_graphics_width(0), 0);
341 maxGraphicsHeight = std::max(max_graphics_height(0), 0);
342
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900343 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700344
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900345 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600346
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900347 mDefaultCompositionDataspace =
348 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
Peiyong Lin8cabfc32019-06-14 14:25:43 -0700349 mWideColorGamutCompositionDataspace = static_cast<ui::Dataspace>(wcg_composition_dataspace(
350 hasWideColorDisplay ? Dataspace::DISPLAY_P3 : Dataspace::V0_SRGB));
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900351 defaultCompositionDataspace = mDefaultCompositionDataspace;
352 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
353 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
354 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
355 wideColorGamutCompositionPixelFormat =
356 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700357
Yichi Chenda901bf2019-06-28 14:58:27 +0800358 mColorSpaceAgnosticDataspace =
359 static_cast<ui::Dataspace>(color_space_agnostic_dataspace(Dataspace::UNKNOWN));
360
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900361 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800362
Dominik Laskowski718f9602019-11-09 20:01:35 -0800363 using Values = SurfaceFlingerProperties::primary_display_orientation_values;
364 switch (primary_display_orientation(Values::ORIENTATION_0)) {
365 case Values::ORIENTATION_0:
Iris Chang7501ed62018-04-30 14:45:42 +0800366 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800367 case Values::ORIENTATION_90:
368 internalDisplayOrientation = ui::ROTATION_90;
Iris Chang7501ed62018-04-30 14:45:42 +0800369 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800370 case Values::ORIENTATION_180:
371 internalDisplayOrientation = ui::ROTATION_180;
Iris Chang7501ed62018-04-30 14:45:42 +0800372 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800373 case Values::ORIENTATION_270:
374 internalDisplayOrientation = ui::ROTATION_270;
Iris Chang7501ed62018-04-30 14:45:42 +0800375 break;
376 }
Dominik Laskowski718f9602019-11-09 20:01:35 -0800377 ALOGV("Internal Display Orientation: %s", toCString(internalDisplayOrientation));
Iris Chang7501ed62018-04-30 14:45:42 +0800378
Sundong Ahn85131bd2019-02-18 15:51:53 +0900379 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800380
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800381 // debugging stuff...
382 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700383
Mathias Agopianb4b17302013-03-20 18:36:41 -0700384 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700385 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700386
Alec Mouri989ddbe2020-02-06 09:26:19 -0800387 property_get("ro.build.type", value, "user");
388 mIsUserBuild = strcmp(value, "user") == 0;
389
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800390 property_get("debug.sf.showupdates", value, "0");
391 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700392
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700393 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodson34397da2019-02-04 09:36:10 +0000394
395 // DDMS debugging deprecated (b/120782499)
396 property_get("debug.sf.ddms", value, "0");
397 int debugDdms = atoi(value);
398 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700399
400 property_get("debug.sf.disable_backpressure", value, "0");
401 mPropagateBackpressure = !atoi(value);
402 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700403
Ady Abrahamadb9a992019-09-19 21:21:55 +0000404 property_get("debug.sf.enable_gl_backpressure", value, "0");
405 mPropagateBackpressureClientComposition = atoi(value);
406 ALOGI_IF(mPropagateBackpressureClientComposition,
407 "Enabling backpressure propagation for Client Composition");
408
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800409 property_get("debug.sf.enable_hwc_vds", value, "0");
410 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800411 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800412
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800413 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800414 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800415 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700416
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800417 property_get("ro.surface_flinger.supports_background_blur", value, "0");
418 bool supportsBlurs = atoi(value);
Lucas Dupin00f16422020-03-11 11:33:04 -0700419 mSupportsBlur = supportsBlurs;
420 ALOGI_IF(!mSupportsBlur, "Disabling blur effects, they are not supported.");
Lucas Dupin2dd6f392020-02-18 17:43:36 -0800421 property_get("ro.sf.blurs_are_expensive", value, "0");
422 mBlursAreExpensive = atoi(value);
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800423
Ady Abraham0a525092020-03-03 12:51:24 -0800424 const size_t defaultListSize = ISurfaceComposer::MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700425 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
426 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
427
Dan Stozaec460082018-12-17 15:35:09 -0800428 property_get("debug.sf.luma_sampling", value, "1");
429 mLumaSampling = atoi(value);
430
Vishnu Nairb2a999b2020-01-23 13:43:02 -0800431 property_get("debug.sf.disable_client_composition_cache", value, "0");
Vishnu Nair9b079a22020-01-21 14:36:08 -0800432 mDisableClientCompositionCache = atoi(value);
433
Romain Guy11d63f42017-07-20 12:47:14 -0700434 // We should be reading 'persist.sys.sf.color_saturation' here
435 // but since /data may be encrypted, we need to wait until after vold
436 // comes online to attempt to read the property. The property is
437 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800438
439 if (useTrebleTestingOverride()) {
440 // Without the override SurfaceFlinger cannot connect to HIDL
441 // services that are not listed in the manifests. Considered
442 // deriving the setting from the set service name, but it
443 // would be brittle if the name that's not 'default' is used
444 // for production purposes later on.
Steven Moreland7c8af942020-07-08 18:35:51 +0000445 android::hardware::details::setTrebleTestingOverride(true);
Kalle Raitaa099a242017-01-11 11:17:29 -0800446 }
Ana Krulec3803b8d2020-02-03 16:35:46 -0800447
448 useFrameRateApi = use_frame_rate_api(true);
Ana Krulecb9afd792020-06-11 13:16:15 -0700449
450 mKernelIdleTimerEnabled = mSupportKernelIdleTimer = sysprop::support_kernel_idle_timer(false);
451 base::SetProperty(KERNEL_IDLE_TIMER_PROP, mKernelIdleTimerEnabled ? "true" : "false");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800452}
453
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700454SurfaceFlinger::~SurfaceFlinger() = default;
455
456void SurfaceFlinger::onFirstRef() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800457 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800458}
459
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700460void SurfaceFlinger::binderDied(const wp<IBinder>&) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800461 // the window manager died on us. prepare its eulogy.
Rob Carr2aa78cb2020-03-10 14:27:49 -0700462 mBootFinished = false;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800463
Andy McFadden13a082e2012-08-24 10:16:42 -0700464 // restore initial conditions (default device unblank, etc)
465 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800466
467 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700468 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800469}
470
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700471void SurfaceFlinger::run() {
472 while (true) {
473 mEventQueue->waitMessage();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800474 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700475}
476
477template <typename F, typename T>
478inline std::future<T> SurfaceFlinger::schedule(F&& f) {
479 auto [task, future] = makeTask(std::move(f));
480 mEventQueue->postMessage(std::move(task));
481 return std::move(future);
Robert Carr1db73f62016-12-21 12:58:51 -0800482}
483
484sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700485 const sp<Client> client = new Client(this);
486 return client->initCheck() == NO_ERROR ? client : nullptr;
Robert Carr1db73f62016-12-21 12:58:51 -0800487}
488
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700489sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName, bool secure) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700490 class DisplayToken : public BBinder {
491 sp<SurfaceFlinger> flinger;
492 virtual ~DisplayToken() {
493 // no more references, this display must be terminated
494 Mutex::Autolock _l(flinger->mStateLock);
495 flinger->mCurrentState.displays.removeItem(this);
496 flinger->setTransactionFlags(eDisplayTransactionNeeded);
497 }
498 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700499 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700500 : flinger(flinger) {
501 }
502 };
503
504 sp<BBinder> token = new DisplayToken(this);
505
506 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700507 // Display ID is assigned when virtual display is allocated by HWC.
508 DisplayDeviceState state;
509 state.isSecure = secure;
510 state.displayName = displayName;
511 mCurrentState.displays.add(token, state);
512 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700513 return token;
514}
515
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700516void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700517 Mutex::Autolock lock(mStateLock);
Jesse Hall6c913be2013-08-08 12:15:49 -0700518
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700519 const ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700520 if (index < 0) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700521 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700522 return;
523 }
524
Dominik Laskowski075d3172018-05-24 15:50:06 -0700525 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700526 if (state.physical) {
527 ALOGE("%s: Invalid operation on physical display", __FUNCTION__);
Jesse Hall6c913be2013-08-08 12:15:49 -0700528 return;
529 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700530 mInterceptor->saveDisplayDeletion(state.sequenceId);
531 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700532 setTransactionFlags(eDisplayTransactionNeeded);
533}
534
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800535std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
536 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700537
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800538 const auto internalDisplayId = getInternalDisplayIdLocked();
539 if (!internalDisplayId) {
540 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700541 }
542
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800543 std::vector<PhysicalDisplayId> displayIds;
544 displayIds.reserve(mPhysicalDisplayTokens.size());
545 displayIds.push_back(internalDisplayId->value);
546
547 for (const auto& [id, token] : mPhysicalDisplayTokens) {
548 if (id != *internalDisplayId) {
549 displayIds.push_back(id.value);
550 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700551 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700552
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800553 return displayIds;
554}
555
556sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
557 Mutex::Autolock lock(mStateLock);
558 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700559}
560
Ady Abraham37965d42018-11-01 13:43:32 -0700561status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
562 if (!outGetColorManagement) {
563 return BAD_VALUE;
564 }
565 *outGetColorManagement = useColorManagement;
566 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700567}
568
Lloyd Pique441d5042018-10-18 16:49:51 -0700569HWComposer& SurfaceFlinger::getHwComposer() const {
570 return mCompositionEngine->getHwComposer();
571}
572
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700573renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
574 return mCompositionEngine->getRenderEngine();
575}
576
Lloyd Pique70d91362018-10-18 16:02:55 -0700577compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
578 return *mCompositionEngine.get();
579}
580
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800581void SurfaceFlinger::bootFinished()
582{
Rob Carr2aa78cb2020-03-10 14:27:49 -0700583 if (mBootFinished == true) {
584 ALOGE("Extra call to bootFinished");
585 return;
586 }
587 mBootFinished = true;
Wei Wangf9b05ee2017-07-19 20:59:39 -0700588 if (mStartPropertySetThread->join() != NO_ERROR) {
589 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800590 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800591 const nsecs_t now = systemTime();
592 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000593 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700594
Mikael Pessa90092f42019-08-26 17:22:04 -0700595 mFrameTracer->initialize();
Alec Mouri8e2f31b2020-01-16 22:04:35 +0000596 mTimeStats->onBootFinished();
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700597
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700598 // wait patiently for the window manager death
599 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700600 mWindowManager = defaultServiceManager()->getService(name);
601 if (mWindowManager != 0) {
602 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700603 }
Robert Carr720e5062018-07-30 17:45:14 -0700604 sp<IBinder> input(defaultServiceManager()->getService(
605 String16("inputflinger")));
606 if (input == nullptr) {
607 ALOGE("Failed to link to input service");
608 } else {
609 mInputFlinger = interface_cast<IInputFlinger>(input);
610 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700611
Steven Thomas050b2c82017-03-06 11:45:16 -0800612 if (mVrFlinger) {
613 mVrFlinger->OnBootFinished();
614 }
615
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700616 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700617 // formerly we would just kill the process, but we now ask it to exit so it
618 // can choose where to stop the animation.
619 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700620
621 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
622 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
623 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700624
Dominik Laskowski20134642020-04-20 22:36:44 -0700625 static_cast<void>(schedule([this] {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800626 readPersistentProperties();
Dan Stoza29e7bdf2020-03-23 14:43:09 -0700627 mPowerAdvisor.onBootFinished();
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800628 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800629
Ady Abraham8a82ba62020-01-17 12:43:17 -0800630 if (property_get_bool("sf.debug.show_refresh_rate_overlay", false)) {
Dominik Laskowski20134642020-04-20 22:36:44 -0700631 enableRefreshRateOverlay(true);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800632 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800633 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800634}
635
Dan Stoza436ccf32018-06-21 12:10:12 -0700636uint32_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
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700652 return schedule([this] {
653 uint32_t name = 0;
654 getRenderEngine().genTextures(1, &name);
655 return name;
656 })
657 .get();
Dan Stoza436ccf32018-06-21 12:10:12 -0700658}
659
Mathias Agopian3f844832013-08-07 21:24:32 -0700660void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700661 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());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700666}
667
Wei Wangf9b05ee2017-07-19 20:59:39 -0700668// Do not call property_set on main thread which will be blocked by init
669// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700670void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700671 ALOGI( "SurfaceFlinger's main thread ready to run. "
672 "Initializing graphics H/W...");
Steven Thomasb02664d2017-07-26 18:48:28 -0700673 Mutex::Autolock _l(mStateLock);
Kevin DuBois413287f2019-02-25 08:46:47 -0800674
Steven Thomasb02664d2017-07-26 18:48:28 -0700675 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin0256f722018-08-31 15:45:10 -0700676 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800677 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700678 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)
Lucas Dupin00f16422020-03-11 11:33:04 -0700685 .setSupportsBackgroundBlur(mSupportsBlur)
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700686 .setContextPriority(useContextPriority
687 ? renderengine::RenderEngine::ContextPriority::HIGH
688 : renderengine::RenderEngine::ContextPriority::MEDIUM)
689 .build()));
Alec Mourie4034bb2019-11-19 12:45:54 -0800690 mCompositionEngine->setTimeStats(mTimeStats);
Steven Thomasb02664d2017-07-26 18:48:28 -0700691
692 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
693 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700694 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
Lloyd Pique4603f3c2020-02-11 12:06:56 -0800695 mCompositionEngine->getHwComposer().setConfiguration(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800696 // Process any initial hotplug and resulting display changes.
697 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700698 const auto display = getDefaultDisplayDeviceLocked();
699 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700700 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700701 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800702
Steven Thomas050b2c82017-03-06 11:45:16 -0800703 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700704 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700705 // 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.
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700711 static_cast<void>(schedule([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700712 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
713 mVrFlingerRequestsDisplay = requestDisplay;
714 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700715 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800716 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700717 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
718 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700719 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700720 .value_or(0),
721 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800722 if (!mVrFlinger) {
723 ALOGE("Failed to start vrflinger");
724 }
725 }
726
Mathias Agopian92a979a2012-08-02 18:32:23 -0700727 // initialize our drawing state
728 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700729
Andy McFadden13a082e2012-08-24 10:16:42 -0700730 // set initial conditions (e.g. unblank default device)
731 initializeDisplays();
732
Steven Thomas137d4bc2019-07-25 16:55:14 -0700733 char primeShaderCache[PROPERTY_VALUE_MAX];
734 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
735 if (atoi(primeShaderCache)) {
736 getRenderEngine().primeCache();
737 }
Dan Stoza4e637772016-07-28 13:31:51 -0700738
Wei Wangf9b05ee2017-07-19 20:59:39 -0700739 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700740
741 const bool presentFenceReliable =
Peiyong Line9d809e2020-04-14 13:10:48 -0700742 !getHwComposer().hasCapability(hal::Capability::PRESENT_FENCE_IS_NOT_RELIABLE);
Lloyd Pique90c115d2018-09-18 21:39:42 -0700743 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700744
745 if (mStartPropertySetThread->Start() != NO_ERROR) {
746 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800747 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800748
Dan Stoza9e56aa02015-11-02 13:00:03 -0800749 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700750}
751
Romain Guy11d63f42017-07-20 12:47:14 -0700752void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700753 Mutex::Autolock _l(mStateLock);
754
Romain Guy11d63f42017-07-20 12:47:14 -0700755 char value[PROPERTY_VALUE_MAX];
756
757 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800758 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700759 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800760 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100761
762 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700763 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800764
765 property_get("persist.sys.sf.color_mode", value, "0");
766 mForceColorMode = static_cast<ColorMode>(atoi(value));
Lucas Dupin00f16422020-03-11 11:33:04 -0700767
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.");
Romain Guy11d63f42017-07-20 12:47:14 -0700772}
773
Mathias Agopiana67e4182012-06-19 17:26:12 -0700774void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800775 // Start boot animation service by setting a property mailbox
776 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700777 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800778 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700779 if (mStartPropertySetThread->join() != NO_ERROR) {
780 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800781 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700782}
783
Mathias Agopian875d8e12013-06-07 15:35:48 -0700784size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700785 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700786}
787
Mathias Agopian875d8e12013-06-07 15:35:48 -0700788size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700789 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700790}
791
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800792// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800793
Jamie Gennis582270d2011-08-17 18:19:00 -0700794bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800795 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800796 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800797 return authenticateSurfaceTextureLocked(bufferProducer);
798}
799
800bool SurfaceFlinger::authenticateSurfaceTextureLocked(
801 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800802 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800803 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800804}
805
Brian Anderson6b376712017-04-04 10:51:39 -0700806status_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 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700818 ConditionalLock _l(mStateLock,
819 std::this_thread::get_id() != mMainThreadId);
Peiyong Line9d809e2020-04-14 13:10:48 -0700820 if (!getHwComposer().hasCapability(hal::Capability::PRESENT_FENCE_IS_NOT_RELIABLE)) {
Brian Anderson6b376712017-04-04 10:51:39 -0700821 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
822 }
823 return NO_ERROR;
824}
825
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800826status_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
847status_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
Dominik Laskowski55c85402020-01-21 16:25:47 -0800859 if (const auto connectionType = display->getConnectionType())
860 info->connectionType = *connectionType;
861 else {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800862 return INVALID_OPERATION;
863 }
864
865 if (mEmulatedDisplayDensity) {
866 info->density = mEmulatedDisplayDensity;
867 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -0800868 info->density = info->connectionType == DisplayConnectionType::Internal
869 ? mInternalDisplayDensity
870 : FALLBACK_DENSITY;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800871 }
Dominik Laskowskid125d0e2020-05-08 12:36:39 -0700872 info->density /= ACONFIGURATION_DENSITY_MEDIUM;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800873
874 info->secure = display->isSecure();
Marin Shalamanovf5de90d2019-10-08 10:57:25 +0200875 info->deviceProductInfo = getDeviceProductInfoLocked(*display);
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800876
877 return NO_ERROR;
878}
879
Dominik Laskowski22488f62019-03-28 09:53:04 -0700880status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800881 Vector<DisplayConfig>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700882 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700883 return BAD_VALUE;
884 }
885
Dominik Laskowski22488f62019-03-28 09:53:04 -0700886 Mutex::Autolock lock(mStateLock);
887
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800888 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700889 if (!displayId) {
890 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700891 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700892
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800893 const bool isInternal = (displayId == getInternalDisplayIdLocked());
Mathias Agopian1604f772012-09-18 21:54:42 -0700894
Dan Stoza7f7da322014-05-02 15:26:25 -0700895 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700896
Dominik Laskowski075d3172018-05-24 15:50:06 -0700897 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800898 DisplayConfig config;
Dan Stoza7f7da322014-05-02 15:26:25 -0700899
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800900 auto width = hwConfig->getWidth();
901 auto height = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700902
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800903 auto xDpi = hwConfig->getDpiX();
904 auto yDpi = hwConfig->getDpiY();
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700905
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800906 if (isInternal &&
907 (internalDisplayOrientation == ui::ROTATION_90 ||
908 internalDisplayOrientation == ui::ROTATION_270)) {
909 std::swap(width, height);
910 std::swap(xDpi, yDpi);
Dan Stoza7f7da322014-05-02 15:26:25 -0700911 }
912
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800913 config.resolution = ui::Size(width, height);
Ady Abraham2139f732019-11-13 18:56:40 -0800914
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800915 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;
Ady Abrahamff731d82020-02-18 17:22:46 -0800929 config.configGroup = hwConfig->getConfigGroup();
Dan Stoza9e56aa02015-11-02 13:00:03 -0800930
Andy McFadden91b2ca82014-06-13 14:04:23 -0700931 // 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.
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800943 config.presentationDeadline = period - config.sfVsyncOffset + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700944
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800945 configs->push_back(config);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700946 }
947
Dan Stoza7f7da322014-05-02 15:26:25 -0700948 return NO_ERROR;
949}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700950
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700951status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
952 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700953 return BAD_VALUE;
954 }
955
Ana Krulecc2870422019-01-29 19:00:58 -0800956 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700957 return NO_ERROR;
958}
959
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700960int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700961 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 }
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800974 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700975
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700976 if (isPrimary) {
Dominik Laskowski20134642020-04-20 22:36:44 -0700977 if (const auto config = getDesiredActiveConfig()) {
978 return config->configId.value();
Steven Thomasc9098452019-09-30 17:15:05 -0700979 }
Steven Thomasc9098452019-09-30 17:15:05 -0700980 }
Ady Abraham2139f732019-11-13 18:56:40 -0800981
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700982 return activeConfig;
Dan Stoza7f7da322014-05-02 15:26:25 -0700983}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700984
Ady Abraham03b02dd2019-03-21 15:40:11 -0700985void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800986 ATRACE_CALL();
Ady Abraham2e1dd892020-03-05 13:48:36 -0800987 auto& refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(info.configId);
Ady Abrahamabc27602020-04-08 17:20:29 -0700988 ALOGV("setDesiredActiveConfig(%s)", refreshRate.getName().c_str());
Ana Krulec7d1d6832018-12-27 11:10:09 -0800989
Ady Abrahamb838aed2019-02-12 15:30:16 -0800990 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham59db0a32020-03-02 18:04:20 -0800991 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();
Ady Abrahamabc27602020-04-08 17:20:29 -07001000 if (!display || display->getActiveConfig() == refreshRate.getConfigId()) {
Ady Abraham59db0a32020-03-02 18:04:20 -08001001 return;
1002 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001003
Ady Abraham59db0a32020-03-02 18:04:20 -08001004 // Initiate a config change.
1005 mDesiredActiveConfigChanged = true;
1006 mDesiredActiveConfig = info;
1007
Ady Abrahamb838aed2019-02-12 15:30:16 -08001008 // This will trigger HWC refresh without resetting the idle timer.
1009 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -07001010 // Start receiving vsync samples now, so that we can detect a period
1011 // switch.
Ady Abrahamabc27602020-04-08 17:20:29 -07001012 mScheduler->resyncToHardwareVsync(true, refreshRate.getVsyncPeriod());
Ady Abraham53852a52019-05-28 18:07:44 -07001013 // As we called to set period, we will call to onRefreshRateChangeCompleted once
1014 // DispSync model is locked.
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001015 mVSyncModulator->onRefreshRateChangeInitiated();
Ady Abraham2139f732019-11-13 18:56:40 -08001016
Ady Abrahamabc27602020-04-08 17:20:29 -07001017 mPhaseConfiguration->setRefreshRateFps(refreshRate.getFps());
Ady Abraham9e16a482019-12-03 17:19:41 -08001018 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham32efd542020-05-19 17:49:26 -07001019 mScheduler->setConfigChangePending(true);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001020 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07001021
1022 if (mRefreshRateOverlay) {
Ady Abraham2139f732019-11-13 18:56:40 -08001023 mRefreshRateOverlay->changeRefreshRate(refreshRate);
Ady Abraham03b02dd2019-03-21 15:40:11 -07001024 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001025}
1026
1027status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
1028 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -08001029
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001030 if (!displayToken) {
1031 return BAD_VALUE;
1032 }
Ady Abraham838de062019-02-04 10:24:03 -08001033
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001034 auto future = schedule([=]() -> status_t {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001035 const auto display = ON_MAIN_THREAD(getDisplayDeviceLocked(displayToken));
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001036 if (!display) {
1037 ALOGE("Attempt to set allowed display configs for invalid display token %p",
1038 displayToken.get());
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001039 return NAME_NOT_FOUND;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001040 } else if (display->isVirtual()) {
1041 ALOGW("Attempt to set allowed display configs for virtual display");
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001042 return INVALID_OPERATION;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001043 } else {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001044 const HwcConfigIndexType config(mode);
1045 const float fps = mRefreshRateConfigs->getRefreshRateFromConfigId(config).getFps();
Steven Thomasf734df42020-04-13 21:09:28 -07001046 const scheduler::RefreshRateConfigs::Policy policy{config, {fps, fps}};
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001047 constexpr bool kOverridePolicy = false;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001048
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001049 return setDesiredDisplayConfigSpecsInternal(display, policy, kOverridePolicy);
1050 }
1051 });
1052
1053 return future.get();
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001054}
1055
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001056void SurfaceFlinger::setActiveConfigInternal() {
1057 ATRACE_CALL();
1058
Dominik Laskowski22488f62019-03-28 09:53:04 -07001059 const auto display = getDefaultDisplayDeviceLocked();
1060 if (!display) {
1061 return;
1062 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001063
Alec Mouri8de697e2020-03-19 10:52:01 -07001064 auto& oldRefreshRate =
1065 mRefreshRateConfigs->getRefreshRateFromConfigId(display->getActiveConfig());
1066
Dominik Laskowski22488f62019-03-28 09:53:04 -07001067 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham2139f732019-11-13 18:56:40 -08001068 mRefreshRateConfigs->setCurrentConfigId(mUpcomingActiveConfig.configId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001069 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001070 display->setActiveConfig(mUpcomingActiveConfig.configId);
1071
Ady Abraham2e1dd892020-03-05 13:48:36 -08001072 auto& refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -08001073 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId);
Ady Abrahamabc27602020-04-08 17:20:29 -07001074 if (refreshRate.getVsyncPeriod() != oldRefreshRate.getVsyncPeriod()) {
Alec Mouri8de697e2020-03-19 10:52:01 -07001075 mTimeStats->incrementRefreshRateSwitches();
1076 }
Ady Abrahamabc27602020-04-08 17:20:29 -07001077 mPhaseConfiguration->setRefreshRateFps(refreshRate.getFps());
Ady Abraham9e16a482019-12-03 17:19:41 -08001078 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abrahamabc27602020-04-08 17:20:29 -07001079 ATRACE_INT("ActiveConfigFPS", refreshRate.getFps());
Dominik Laskowski22488f62019-03-28 09:53:04 -07001080
Ana Krulec8d3e4f32019-03-05 10:40:33 -08001081 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Alec Mouri60aee1c2019-10-28 16:18:59 -07001082 const nsecs_t vsyncPeriod =
1083 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId)
Ady Abrahamabc27602020-04-08 17:20:29 -07001084 .getVsyncPeriod();
Ady Abrahamdfd62162020-06-10 16:11:56 -07001085 mScheduler->onPrimaryDisplayConfigChanged(mAppConnectionHandle, display->getId()->value,
1086 mUpcomingActiveConfig.configId, vsyncPeriod);
Ady Abraham447052e2019-02-13 16:07:27 -08001087 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001088}
1089
Ady Abraham53852a52019-05-28 18:07:44 -07001090void SurfaceFlinger::desiredActiveConfigChangeDone() {
1091 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1092 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
1093 mDesiredActiveConfigChanged = false;
Ady Abraham53852a52019-05-28 18:07:44 -07001094
Ady Abraham2e1dd892020-03-05 13:48:36 -08001095 const auto& refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -08001096 mRefreshRateConfigs->getRefreshRateFromConfigId(mDesiredActiveConfig.configId);
Ady Abrahamabc27602020-04-08 17:20:29 -07001097 mScheduler->resyncToHardwareVsync(true, refreshRate.getVsyncPeriod());
1098 mPhaseConfiguration->setRefreshRateFps(refreshRate.getFps());
Ady Abraham9e16a482019-12-03 17:19:41 -08001099 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham32efd542020-05-19 17:49:26 -07001100 mScheduler->setConfigChangePending(false);
Ady Abraham53852a52019-05-28 18:07:44 -07001101}
1102
Ady Abraham27cbed72020-04-10 12:56:59 -07001103void SurfaceFlinger::performSetActiveConfig() {
Alec Mourife3dc942019-02-12 14:19:18 -08001104 ATRACE_CALL();
Ady Abraham2139f732019-11-13 18:56:40 -08001105 ALOGV("performSetActiveConfig");
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001106 // Store the local variable to release the lock.
Dominik Laskowski20134642020-04-20 22:36:44 -07001107 const auto desiredActiveConfig = getDesiredActiveConfig();
Ady Abraham27cbed72020-04-10 12:56:59 -07001108 if (!desiredActiveConfig) {
1109 // No desired active config pending to be applied
1110 return;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001111 }
1112
Ady Abraham2e1dd892020-03-05 13:48:36 -08001113 auto& refreshRate =
Ady Abraham27cbed72020-04-10 12:56:59 -07001114 mRefreshRateConfigs->getRefreshRateFromConfigId(desiredActiveConfig->configId);
Ady Abrahamabc27602020-04-08 17:20:29 -07001115 ALOGV("performSetActiveConfig changing active config to %d(%s)",
1116 refreshRate.getConfigId().value(), refreshRate.getName().c_str());
Dominik Laskowski22488f62019-03-28 09:53:04 -07001117 const auto display = getDefaultDisplayDeviceLocked();
Ady Abraham27cbed72020-04-10 12:56:59 -07001118 if (!display || display->getActiveConfig() == desiredActiveConfig->configId) {
Ady Abrahamb838aed2019-02-12 15:30:16 -08001119 // display is not valid or we are already in the requested mode
1120 // on both cases there is nothing left to do
Ady Abraham53852a52019-05-28 18:07:44 -07001121 desiredActiveConfigChangeDone();
Ady Abraham27cbed72020-04-10 12:56:59 -07001122 return;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001123 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001124
Ady Abraham838de062019-02-04 10:24:03 -08001125 // 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
Ady Abraham27cbed72020-04-10 12:56:59 -07001128 if (!isDisplayConfigAllowed(desiredActiveConfig->configId)) {
Ady Abraham53852a52019-05-28 18:07:44 -07001129 desiredActiveConfigChangeDone();
Ady Abraham27cbed72020-04-10 12:56:59 -07001130 return;
Ady Abraham838de062019-02-04 10:24:03 -08001131 }
Alec Mouri7f015182019-07-11 13:56:22 -07001132
Ady Abraham27cbed72020-04-10 12:56:59 -07001133 mUpcomingActiveConfig = *desiredActiveConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -08001134 const auto displayId = display->getId();
1135 LOG_ALWAYS_FATAL_IF(!displayId);
1136
Ady Abrahamabc27602020-04-08 17:20:29 -07001137 ATRACE_INT("ActiveConfigFPS_HWC", refreshRate.getFps());
Ady Abrahamb838aed2019-02-12 15:30:16 -08001138
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001139 // TODO(b/142753666) use constrains
Peiyong Line9d809e2020-04-14 13:10:48 -07001140 hal::VsyncPeriodChangeConstraints constraints;
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001141 constraints.desiredTimeNanos = systemTime();
1142 constraints.seamlessRequired = false;
1143
Peiyong Line9d809e2020-04-14 13:10:48 -07001144 hal::VsyncPeriodChangeTimeline outTimeline;
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001145 auto status =
1146 getHwComposer().setActiveConfigWithConstraints(*displayId,
1147 mUpcomingActiveConfig.configId.value(),
1148 constraints, &outTimeline);
1149 if (status != NO_ERROR) {
Ady Abraham5e95aa22020-03-04 10:26:05 -08001150 // 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);
Ady Abraham27cbed72020-04-10 12:56:59 -07001153 return;
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001154 }
1155
1156 mScheduler->onNewVsyncPeriodChangeTimeline(outTimeline);
1157 // Scheduler will submit an empty frame to HWC if needed.
Ady Abraham27cbed72020-04-10 12:56:59 -07001158 mSetActiveConfigPending = true;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001159}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001160
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001161status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1162 Vector<ColorMode>* outColorModes) {
1163 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001164 return BAD_VALUE;
1165 }
1166
Peiyong Lina52f0292018-03-14 17:26:31 -07001167 std::vector<ColorMode> modes;
Peiyong Linff84a152019-05-17 18:36:19 -07001168 bool isInternalDisplay = false;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001169 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001170 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
Dominik Laskowski075d3172018-05-24 15:50:06 -07001177 modes = getHwComposer().getColorModes(*displayId);
Peiyong Linff84a152019-05-17 18:36:19 -07001178 isInternalDisplay = displayId == getInternalDisplayIdLocked();
Steven Thomas6d8110b2017-08-31 18:24:21 -07001179 }
Michael Wright28f24d02016-07-12 13:30:53 -07001180 outColorModes->clear();
Peiyong Linff84a152019-05-17 18:36:19 -07001181
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 }
Michael Wright28f24d02016-07-12 13:30:53 -07001192
1193 return NO_ERROR;
1194}
1195
Daniel Solomon42d04562019-01-20 21:03:19 -08001196status_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) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001204 return NAME_NOT_FOUND;
Daniel Solomon42d04562019-01-20 21:03:19 -08001205 }
1206
1207 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1208 return NO_ERROR;
1209}
1210
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001211ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001212 Mutex::Autolock lock(mStateLock);
1213
1214 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001215 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001216 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001217 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001218}
1219
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001220status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001221 schedule([=]() MAIN_THREAD {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001222 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;
Michael Wright28f24d02016-07-12 13:30:53 -07001229 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001230 const auto display = getDisplayDeviceLocked(displayToken);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001231 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 {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001238 display->getCompositionDisplay()->setColorProfile(
1239 compositionengine::Output::ColorProfile{mode, Dataspace::UNKNOWN,
1240 RenderIntent::COLORIMETRIC,
1241 Dataspace::UNKNOWN});
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001242 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001243 }).wait();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001244
Michael Wright28f24d02016-07-12 13:30:53 -07001245 return NO_ERROR;
1246}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001247
Galia Peycheva5492cb52019-10-30 14:13:16 +01001248status_t SurfaceFlinger::getAutoLowLatencyModeSupport(const sp<IBinder>& displayToken,
1249 bool* outSupport) const {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001250 if (!displayToken) {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001251 return BAD_VALUE;
1252 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001253
1254 Mutex::Autolock lock(mStateLock);
1255
Galia Peycheva5492cb52019-10-30 14:13:16 +01001256 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1257 if (!displayId) {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001258 return NAME_NOT_FOUND;
1259 }
Peiyong Line9d809e2020-04-14 13:10:48 -07001260 *outSupport =
1261 getHwComposer().hasDisplayCapability(*displayId,
1262 hal::DisplayCapability::AUTO_LOW_LATENCY_MODE);
Galia Peycheva5492cb52019-10-30 14:13:16 +01001263 return NO_ERROR;
1264}
1265
1266void SurfaceFlinger::setAutoLowLatencyMode(const sp<IBinder>& displayToken, bool on) {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001267 static_cast<void>(schedule([=]() MAIN_THREAD {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001268 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 }));
Galia Peycheva5492cb52019-10-30 14:13:16 +01001274}
1275
1276status_t SurfaceFlinger::getGameContentTypeSupport(const sp<IBinder>& displayToken,
1277 bool* outSupport) const {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001278 if (!displayToken) {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001279 return BAD_VALUE;
1280 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001281
1282 Mutex::Autolock lock(mStateLock);
1283
Galia Peycheva5492cb52019-10-30 14:13:16 +01001284 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1285 if (!displayId) {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001286 return NAME_NOT_FOUND;
1287 }
1288
Peiyong Line9d809e2020-04-14 13:10:48 -07001289 std::vector<hal::ContentType> types;
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001290 getHwComposer().getSupportedContentTypes(*displayId, &types);
1291
1292 *outSupport = std::any_of(types.begin(), types.end(),
Peiyong Line9d809e2020-04-14 13:10:48 -07001293 [](auto type) { return type == hal::ContentType::GAME; });
Galia Peycheva5492cb52019-10-30 14:13:16 +01001294 return NO_ERROR;
1295}
1296
1297void SurfaceFlinger::setGameContentType(const sp<IBinder>& displayToken, bool on) {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001298 static_cast<void>(schedule([=]() MAIN_THREAD {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001299 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
Peiyong Line9d809e2020-04-14 13:10:48 -07001300 const auto type = on ? hal::ContentType::GAME : hal::ContentType::NONE;
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001301 getHwComposer().setContentType(*displayId, type);
1302 } else {
1303 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1304 }
1305 }));
Galia Peycheva5492cb52019-10-30 14:13:16 +01001306}
1307
Svetoslavd85084b2014-03-20 10:28:31 -07001308status_t SurfaceFlinger::clearAnimationFrameStats() {
1309 Mutex::Autolock _l(mStateLock);
1310 mAnimFrameTracker.clearStats();
1311 return NO_ERROR;
1312}
1313
1314status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1315 Mutex::Autolock _l(mStateLock);
1316 mAnimFrameTracker.getStats(outStats);
1317 return NO_ERROR;
1318}
1319
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001320status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1321 HdrCapabilities* outCapabilities) const {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001322 Mutex::Autolock lock(mStateLock);
Dan Stozac4f471e2016-03-24 09:31:08 -07001323
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001324 const auto display = getDisplayDeviceLocked(displayToken);
1325 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001326 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1327 return NAME_NOT_FOUND;
Dan Stozac4f471e2016-03-24 09:31:08 -07001328 }
1329
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001330 // At this point the DisplayDevice should already be set up,
Peiyong Linfb069302018-04-25 14:34:31 -07001331 // meaning the luminance information is already queried from
1332 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001333 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001334 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1335 capabilities.getDesiredMaxLuminance(),
1336 capabilities.getDesiredMaxAverageLuminance(),
1337 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001338
1339 return NO_ERROR;
1340}
1341
Marin Shalamanovf5de90d2019-10-08 10:57:25 +02001342std::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
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001366status_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 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001373
1374 Mutex::Autolock lock(mStateLock);
1375
1376 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1377 if (!displayId) {
1378 return NAME_NOT_FOUND;
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001379 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001380
1381 return getHwComposer().getDisplayedContentSamplingAttributes(*displayId, outFormat,
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001382 outDataspace, outComponentMask);
1383}
1384
Kevin DuBois74e53772018-11-19 10:52:38 -08001385status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1386 bool enable, uint8_t componentMask,
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001387 uint64_t maxFrames) {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001388 return schedule([=]() MAIN_THREAD -> status_t {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001389 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();
Kevin DuBois74e53772018-11-19 10:52:38 -08001399}
1400
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001401status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1402 uint64_t maxFrames, uint64_t timestamp,
1403 DisplayedFrameStats* outStats) const {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001404 Mutex::Autolock lock(mStateLock);
1405
1406 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1407 if (!displayId) {
1408 return NAME_NOT_FOUND;
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001409 }
1410
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001411 return getHwComposer().getDisplayedContentSample(*displayId, maxFrames, timestamp, outStats);
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001412}
1413
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001414status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1415 if (!outSupported) {
1416 return BAD_VALUE;
1417 }
1418 *outSupported = getRenderEngine().supportsProtectedContent();
1419 return NO_ERROR;
1420}
1421
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001422status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1423 bool* outIsWideColorDisplay) const {
1424 if (!displayToken || !outIsWideColorDisplay) {
1425 return BAD_VALUE;
1426 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001427
1428 Mutex::Autolock lock(mStateLock);
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001429 const auto display = getDisplayDeviceLocked(displayToken);
1430 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001431 return NAME_NOT_FOUND;
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001432 }
Peiyong Linff84a152019-05-17 18:36:19 -07001433
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001434 *outIsWideColorDisplay =
1435 display->isPrimary() ? hasWideColorDisplay : display->hasWideColorGamut();
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001436 return NO_ERROR;
1437}
1438
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001439status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001440 schedule([=] {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001441 Mutex::Autolock lock(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001442
Dominik Laskowski6505f792019-09-18 11:10:05 -07001443 if (const auto handle = mScheduler->enableVSyncInjection(enable)) {
1444 mEventQueue->setEventConnection(
1445 mScheduler->getEventConnection(enable ? handle : mSfConnectionHandle));
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001446 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001447 }).wait();
Dominik Laskowski8c001672018-05-30 16:52:06 -07001448
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001449 return NO_ERROR;
1450}
1451
1452status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001453 Mutex::Autolock lock(mStateLock);
Ady Abraham5facfb12020-04-22 15:18:31 -07001454 return mScheduler->injectVSync(when, calculateExpectedPresentTime(when)) ? NO_ERROR : BAD_VALUE;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001455}
1456
Vishnu Nair43bccf82020-06-05 10:53:37 -07001457status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) {
Kalle Raitaa099a242017-01-11 11:17:29 -08001458 outLayers->clear();
Vishnu Nair43bccf82020-06-05 10:53:37 -07001459 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();
Kalle Raitaa099a242017-01-11 11:17:29 -08001465 return NO_ERROR;
1466}
1467
Peiyong Linc6780972018-10-28 15:24:08 -07001468status_t SurfaceFlinger::getCompositionPreference(
1469 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1470 Dataspace* outWideColorGamutDataspace,
1471 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001472 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001473 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001474 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001475 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001476 return NO_ERROR;
1477}
1478
Dan Stozaec460082018-12-17 15:35:09 -08001479status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1480 const sp<IBinder>& stopLayerHandle,
1481 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001482 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001483 return BAD_VALUE;
1484 }
Alec Mouri9a02eda2020-04-21 17:39:34 -07001485
1486 const wp<Layer> stopLayer = fromHandle(stopLayerHandle);
1487 mRegionSamplingThread->addListener(samplingArea, stopLayer, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001488 return NO_ERROR;
1489}
1490
Dan Stozaec460082018-12-17 15:35:09 -08001491status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001492 if (!listener) {
1493 return BAD_VALUE;
1494 }
Dan Stozaec460082018-12-17 15:35:09 -08001495 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001496 return NO_ERROR;
1497}
Dan Gittik57e63c52019-01-18 16:37:54 +00001498
1499status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1500 bool* outSupport) const {
1501 if (!displayToken || !outSupport) {
1502 return BAD_VALUE;
1503 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001504
1505 Mutex::Autolock lock(mStateLock);
1506
Dan Gittik57e63c52019-01-18 16:37:54 +00001507 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1508 if (!displayId) {
1509 return NAME_NOT_FOUND;
1510 }
1511 *outSupport =
Peiyong Line9d809e2020-04-14 13:10:48 -07001512 getHwComposer().hasDisplayCapability(*displayId, hal::DisplayCapability::BRIGHTNESS);
Dan Gittik57e63c52019-01-18 16:37:54 +00001513 return NO_ERROR;
1514}
1515
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001516status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken, float brightness) {
Dan Gittik57e63c52019-01-18 16:37:54 +00001517 if (!displayToken) {
1518 return BAD_VALUE;
1519 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001520
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001521 return promise::chain(schedule([=]() MAIN_THREAD {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001522 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1523 return getHwComposer().setDisplayBrightness(*displayId, brightness);
1524 } else {
1525 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
Dominik Laskowski5690bde2020-04-23 19:04:22 -07001526 return promise::yield<status_t>(NAME_NOT_FOUND);
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001527 }
Dominik Laskowski5690bde2020-04-23 19:04:22 -07001528 }))
1529 .then([](std::future<status_t> task) { return task; })
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001530 .get();
Dan Gittik57e63c52019-01-18 16:37:54 +00001531}
1532
Ady Abraham8532d012019-05-08 14:50:56 -07001533status_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
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001543// ----------------------------------------------------------------------------
1544
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001545sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001546 ISurfaceComposer::VsyncSource vsyncSource, ISurfaceComposer::ConfigChanged configChanged) {
Ana Krulecc2870422019-01-29 19:00:58 -08001547 const auto& handle =
1548 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001549
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001550 return mScheduler->createDisplayEventConnection(handle, configChanged);
Mathias Agopianbb641242010-05-18 17:06:55 -07001551}
1552
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001553void SurfaceFlinger::signalTransaction() {
Ady Abraham8532d012019-05-08 14:50:56 -07001554 mScheduler->resetIdleTimer();
Dan Stoza030fbc12020-02-19 15:32:01 -08001555 mPowerAdvisor.notifyDisplayUpdateImminent();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001556 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001557}
1558
1559void SurfaceFlinger::signalLayerUpdate() {
Ady Abraham8532d012019-05-08 14:50:56 -07001560 mScheduler->resetIdleTimer();
Dan Stoza030fbc12020-02-19 15:32:01 -08001561 mPowerAdvisor.notifyDisplayUpdateImminent();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001562 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001563}
1564
1565void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001566 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001567 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001568}
1569
Dominik Laskowski83b88212018-12-11 13:34:06 -08001570nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001571 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001572 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1573 return 0;
1574 }
1575
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001576 return getHwComposer().getDisplayVsyncPeriod(*displayId);
Dominik Laskowski83b88212018-12-11 13:34:06 -08001577}
1578
Peiyong Line9d809e2020-04-14 13:10:48 -07001579void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hal::HWDisplayId hwcDisplayId,
Ady Abraham7159f572019-10-11 11:10:18 -07001580 int64_t timestamp,
Peiyong Line9d809e2020-04-14 13:10:48 -07001581 std::optional<hal::VsyncPeriodNanos> vsyncPeriod) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001582 ATRACE_NAME("SF onVsync");
1583
Steven Thomas3cfac282017-02-06 12:29:30 -08001584 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001585 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001586 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001587 return;
1588 }
1589
Dominik Laskowski075d3172018-05-24 15:50:06 -07001590 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001591 return;
1592 }
1593
Dominik Laskowski075d3172018-05-24 15:50:06 -07001594 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001595 // For now, we don't do anything with external display vsyncs.
1596 return;
1597 }
1598
Alec Mourif8e689c2019-05-20 18:32:22 -07001599 bool periodFlushed = false;
Ady Abraham5dee2f12020-02-05 17:49:47 -08001600 mScheduler->addResyncSample(timestamp, vsyncPeriod, &periodFlushed);
Alec Mourif8e689c2019-05-20 18:32:22 -07001601 if (periodFlushed) {
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001602 mVSyncModulator->onRefreshRateChangeCompleted();
Alec Mouri754c98a2019-03-18 18:53:42 -07001603 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001604}
1605
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001606void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001607 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1608 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001609}
1610
Ady Abraham2139f732019-11-13 18:56:40 -08001611bool SurfaceFlinger::isDisplayConfigAllowed(HwcConfigIndexType configId) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001612 return mRefreshRateConfigs->isConfigAllowed(configId);
Ady Abraham838de062019-02-04 10:24:03 -08001613}
1614
Ady Abraham2139f732019-11-13 18:56:40 -08001615void SurfaceFlinger::changeRefreshRateLocked(const RefreshRate& refreshRate,
1616 Scheduler::ConfigEvent event) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001617 const auto display = getDefaultDisplayDeviceLocked();
1618 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001619 return;
1620 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001621 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001622
Ana Krulec7d1d6832018-12-27 11:10:09 -08001623 // Don't do any updating if the current fps is the same as the new one.
Ady Abrahamabc27602020-04-08 17:20:29 -07001624 if (!isDisplayConfigAllowed(refreshRate.getConfigId())) {
Ady Abraham2139f732019-11-13 18:56:40 -08001625 ALOGV("Skipping config %d as it is not part of allowed configs",
Ady Abrahamabc27602020-04-08 17:20:29 -07001626 refreshRate.getConfigId().value());
Ady Abraham1902d072019-03-01 17:18:59 -08001627 return;
1628 }
1629
Ady Abrahamabc27602020-04-08 17:20:29 -07001630 setDesiredActiveConfig({refreshRate.getConfigId(), event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001631}
1632
Peiyong Line9d809e2020-04-14 13:10:48 -07001633void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hal::HWDisplayId hwcDisplayId,
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001634 hal::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001635 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Peiyong Line9d809e2020-04-14 13:10:48 -07001636 connection == hal::Connection::CONNECTED ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001637
Lloyd Piqueba04e622017-12-14 17:11:26 -08001638 // Ignore events that do not have the right sequenceId.
1639 if (sequenceId != getBE().mComposerSequenceId) {
1640 return;
1641 }
1642
Steven Thomasb02664d2017-07-26 18:48:28 -07001643 // 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.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001647 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001648
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001649 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001650
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001651 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
Lloyd Piqueba04e622017-12-14 17:11:26 -08001656 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001657}
1658
Ady Abraham7159f572019-10-11 11:10:18 -07001659void SurfaceFlinger::onVsyncPeriodTimingChangedReceived(
Peiyong Line9d809e2020-04-14 13:10:48 -07001660 int32_t sequenceId, hal::HWDisplayId /*display*/,
1661 const hal::VsyncPeriodChangeTimeline& updatedTimeline) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001662 Mutex::Autolock lock(mStateLock);
1663 if (sequenceId != getBE().mComposerSequenceId) {
1664 return;
1665 }
1666 mScheduler->onNewVsyncPeriodChangeTimeline(updatedTimeline);
Ady Abraham7159f572019-10-11 11:10:18 -07001667}
1668
Peiyong Line9d809e2020-04-14 13:10:48 -07001669void SurfaceFlinger::onSeamlessPossible(int32_t /*sequenceId*/, hal::HWDisplayId /*display*/) {
Ady Abrahamb0433bc2020-01-08 17:31:06 -08001670 // 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
Peiyong Line9d809e2020-04-14 13:10:48 -07001674void SurfaceFlinger::onRefreshReceived(int sequenceId, hal::HWDisplayId /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001675 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001676 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001677 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001678 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001679 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001680}
1681
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001682void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001683 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001684
1685 // Enable / Disable HWVsync from the main thread to avoid race conditions with
1686 // display power state.
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001687 static_cast<void>(schedule([=]() MAIN_THREAD { setPrimaryVsyncEnabledInternal(enabled); }));
Ady Abraham9ba25122019-06-03 17:10:55 -07001688}
1689
1690void SurfaceFlinger::setPrimaryVsyncEnabledInternal(bool enabled) {
1691 ATRACE_CALL();
1692
Peiyong Line9d809e2020-04-14 13:10:48 -07001693 mHWCVsyncPendingState = enabled ? hal::Vsync::ENABLE : hal::Vsync::DISABLE;
Ady Abraham27c70212019-06-11 10:52:26 -07001694
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001695 if (const auto displayId = getInternalDisplayIdLocked()) {
Ady Abraham9ba25122019-06-03 17:10:55 -07001696 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
1697 if (display && display->isPoweredOn()) {
Marin Shalamanovc75b0772020-06-12 22:29:11 +02001698 getHwComposer().setVsyncEnabled(*displayId, mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001699 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001700 }
Mathias Agopian86303202012-07-24 22:46:10 -07001701}
1702
Steven Thomasb02664d2017-07-26 18:48:28 -07001703void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001704 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001705 // 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
Steven Thomas050b2c82017-03-06 11:45:16 -08001713void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001714 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001715 if (!mVrFlinger)
1716 return;
1717 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001718 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001719 return;
1720 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001721
Lloyd Pique441d5042018-10-18 16:49:51 -07001722 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001723 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;
Mark Urbanus209beca2017-02-23 11:16:04 -08001728 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001729
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001730 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001731
Steven Thomas0123ac62018-07-12 11:32:34 -07001732 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001733 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001734
Peiyong Lin65248e02020-04-18 21:15:07 -07001735 const hal::PowerMode currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001736
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) {
Lloyd Pique01c77c12019-04-17 12:48:32 -07001742 displayDevice->getCompositionDisplay()->clearOutputLayers();
Lloyd Pique07e33212018-12-18 16:33:37 -08001743 }
1744
Steven Thomas0123ac62018-07-12 11:32:34 -07001745 // 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();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001749
Steven Thomasb02664d2017-07-26 18:48:28 -07001750 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001751 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001752 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001753
Steven Thomasb02664d2017-07-26 18:48:28 -07001754 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001755 // 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));
Lloyd Pique4603f3c2020-02-11 12:06:56 -08001759 mCompositionEngine->getHwComposer().setConfiguration(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001760
Lloyd Pique441d5042018-10-18 16:49:51 -07001761 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001762 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001763
1764 if (vrFlingerRequestsDisplay) {
1765 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001766 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001767
1768 mVisibleRegionsDirty = true;
1769 invalidateHwcGeometry();
1770
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001771 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001772 display = getDefaultDisplayDeviceLocked();
1773 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001774 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001775
Steven Thomasb02664d2017-07-26 18:48:28 -07001776 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001777 const nsecs_t vsyncPeriod = getVsyncPeriod();
1778 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001779
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001780 // The present fences returned from vr_hwc are not an accurate
1781 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001782 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001783
Steven Thomasb02664d2017-07-26 18:48:28 -07001784 // Use phase of 0 since phase is not known.
1785 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001786 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001787 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001788
Ana Krulecc2870422019-01-29 19:00:58 -08001789 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001790
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001791 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001792 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001793}
1794
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001795sp<Fence> SurfaceFlinger::previousFrameFence() {
Ady Abrahambe0f9482019-04-24 15:41:53 -07001796 // 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
Alec Mouri6d414b52020-03-17 11:18:05 -07001799 return mVSyncModulator->getOffsets().sf > 0 ? mPreviousPresentFences[0]
1800 : mPreviousPresentFences[1];
1801}
1802
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001803bool SurfaceFlinger::previousFramePending(int graceTimeMs) {
Alec Mouri6d414b52020-03-17 11:18:05 -07001804 ATRACE_CALL();
1805 const sp<Fence>& fence = previousFrameFence();
Ady Abrahambe0f9482019-04-24 15:41:53 -07001806
Ady Abraham11579302019-09-19 12:35:58 -07001807 if (fence == Fence::NO_FENCE) {
1808 return false;
1809 }
1810
Dan Stoza59083052020-04-28 10:13:20 -07001811 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;
Ady Abrahambe0f9482019-04-24 15:41:53 -07001815}
1816
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001817nsecs_t SurfaceFlinger::previousFramePresentTime() {
Alec Mouri6d414b52020-03-17 11:18:05 -07001818 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
Ady Abraham5facfb12020-04-22 15:18:31 -07001827nsecs_t SurfaceFlinger::calculateExpectedPresentTime(nsecs_t now) const {
Alec Mouriaa614192019-06-06 13:28:34 -07001828 DisplayStatInfo stats;
1829 mScheduler->getDisplayStatInfo(&stats);
Ady Abraham5facfb12020-04-22 15:18:31 -07001830 const nsecs_t presentTime = mScheduler->getDispSyncExpectedPresentTime(now);
Alec Mouriaa614192019-06-06 13:28:34 -07001831 // Inflate the expected present time if we're targetting the next vsync.
Ady Abraham5facfb12020-04-22 15:18:31 -07001832 return mVSyncModulator->getOffsets().sf > 0 ? presentTime : presentTime + stats.vsyncPeriod;
Alec Mouriaa614192019-06-06 13:28:34 -07001833}
1834
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001835void SurfaceFlinger::onMessageReceived(int32_t what, nsecs_t expectedVSyncTime) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001836 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001837 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001838 case MessageQueue::INVALIDATE: {
Dan Stoza28d46a52020-04-28 09:54:54 -07001839 onMessageInvalidate(expectedVSyncTime);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001840 break;
1841 }
1842 case MessageQueue::REFRESH: {
Dan Stoza28d46a52020-04-28 09:54:54 -07001843 onMessageRefresh();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001844 break;
1845 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001846 }
1847}
1848
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001849void SurfaceFlinger::onMessageInvalidate(nsecs_t expectedVSyncTime) {
Dan Stoza28d46a52020-04-28 09:54:54 -07001850 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;
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001922 ON_MAIN_THREAD(setActiveConfigInternal());
Dan Stoza28d46a52020-04-28 09:54:54 -07001923 }
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();
Alec Mouri1b6a60c2020-06-08 13:54:24 -07001939 nsecs_t jankDurationToUpload = -1;
Dan Stoza28d46a52020-04-28 09:54:54 -07001940 // If we're in a user build then don't push any atoms
1941 if (!mIsUserBuild && mMissedFrameJankCount > 0) {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001942 const auto display = ON_MAIN_THREAD(getDefaultDisplayDeviceLocked());
Dan Stoza28d46a52020-04-28 09:54:54 -07001943 // 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.
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001947 if (display && display->getPowerMode() == hal::PowerMode::ON) {
Dan Stoza28d46a52020-04-28 09:54:54 -07001948 const nsecs_t currentTime = systemTime();
1949 const nsecs_t jankDuration = currentTime - mMissedFrameJankStart;
1950 if (jankDuration > kMinJankyDuration && jankDuration < kMaxJankyDuration) {
Alec Mouri1b6a60c2020-06-08 13:54:24 -07001951 jankDurationToUpload = jankDuration;
Dan Stoza28d46a52020-04-28 09:54:54 -07001952 }
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
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07001997 ON_MAIN_THREAD(performSetActiveConfig());
Dan Stoza28d46a52020-04-28 09:54:54 -07001998
1999 updateCursorAsync();
2000 updateInputFlinger();
2001
2002 refreshNeeded |= mRepaintEverything;
2003 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Alec Mouri1b6a60c2020-06-08 13:54:24 -07002004 mLastJankDuration = jankDurationToUpload;
Dan Stoza28d46a52020-04-28 09:54:54 -07002005 // 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
Dan Stoza6b9454d2014-11-07 16:00:59 -08002019bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08002020 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002021 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07002022
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002023 bool flushedATransaction = flushTransactionQueues();
2024
Valerie Hau47826a72020-06-15 12:34:40 -07002025 bool runHandleTransaction =
2026 (transactionFlags && (transactionFlags != eTransactionFlushNeeded)) ||
Robert Carr6417d2e2020-06-24 15:26:32 -07002027 flushedATransaction ||
2028 mForceTraversal;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002029
2030 if (runHandleTransaction) {
2031 handleTransaction(eTransactionMask);
2032 } else {
2033 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07002034 }
2035
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002036 if (transactionFlushNeeded()) {
2037 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002038 }
Marissa Wall713b63f2018-10-17 15:42:43 -07002039
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002040 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002041}
2042
Dan Stoza28d46a52020-04-28 09:54:54 -07002043void SurfaceFlinger::onMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002044 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07002045
Dan Stoza2b6d38e2017-06-01 16:40:30 -07002046 mRefreshPending = false;
2047
Lloyd Piqueab039b52019-02-13 14:22:42 -08002048 compositionengine::CompositionRefreshArgs refreshArgs;
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002049 const auto& displays = ON_MAIN_THREAD(mDisplays);
2050 refreshArgs.outputs.reserve(displays.size());
2051 for (const auto& [_, display] : displays) {
Lloyd Piqueab039b52019-02-13 14:22:42 -08002052 refreshArgs.outputs.push_back(display->getCompositionDisplay());
2053 }
2054 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08002055 if (auto layerFE = layer->getCompositionEngineLayerFE())
2056 refreshArgs.layers.push_back(layerFE);
Lloyd Piqueab039b52019-02-13 14:22:42 -08002057 });
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002058 refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
2059 for (sp<Layer> layer : mLayersWithQueuedFrames) {
Lloyd Piquede196652020-01-22 17:29:58 -08002060 if (auto layerFE = layer->getCompositionEngineLayerFE())
2061 refreshArgs.layersWithQueuedFrames.push_back(layerFE);
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002062 }
2063
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08002064 refreshArgs.repaintEverything = mRepaintEverything.exchange(false);
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002065 refreshArgs.outputColorSetting = useColorManagement
2066 ? mDisplayColorSetting
2067 : compositionengine::OutputColorSetting::kUnmanaged;
2068 refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
2069 refreshArgs.forceOutputColorMode = mForceColorMode;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002070
2071 refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
2072 refreshArgs.updatingGeometryThisFrame = mGeometryInvalid || mVisibleRegionsDirty;
Lucas Dupin2dd6f392020-02-18 17:43:36 -08002073 refreshArgs.blursAreExpensive = mBlursAreExpensive;
Snild Dolkow9e217d62020-04-22 15:53:42 +02002074 refreshArgs.internalDisplayRotationFlags = DisplayDevice::getPrimaryDisplayRotationFlags();
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002075
2076 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
2077 refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
2078 mDrawingState.colorMatrixChanged = false;
2079 }
2080
2081 refreshArgs.devOptForceClientComposition = mDebugDisableHWC || mDebugRegion;
2082
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08002083 if (mDebugRegion != 0) {
2084 refreshArgs.devOptFlashDirtyRegionsDelay =
2085 std::chrono::milliseconds(mDebugRegion > 1 ? mDebugRegion : 0);
2086 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08002087
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002088 mGeometryInvalid = false;
2089
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002090 // Store the present time just before calling to the composition engine so we could notify
2091 // the scheduler.
2092 const auto presentTime = systemTime();
2093
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002094 mCompositionEngine->present(refreshArgs);
Alec Mouri9519bf12019-11-15 16:54:44 -08002095 mTimeStats->recordFrameDuration(mFrameStartTime, systemTime());
2096 // Reset the frame start time now that we've recorded this frame.
2097 mFrameStartTime = 0;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002098
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002099 mScheduler->onDisplayRefreshed(presentTime);
2100
David Sodmanfa9b2af2017-12-24 13:28:59 -08002101 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08002102 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07002103
Alec Mouri8f7a0102020-04-15 12:11:10 -07002104 const bool prevFrameHadDeviceComposition = mHadDeviceComposition;
2105
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002106 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 });
Vishnu Nair9b079a22020-01-21 14:36:08 -08002114 mReusedClientComposition =
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002115 std::any_of(displays.cbegin(), displays.cend(), [](const auto& pair) {
2116 const auto& state = pair.second->getCompositionDisplay()->getState();
2117 return state.reusedClientComposition;
Vishnu Nair9b079a22020-01-21 14:36:08 -08002118 });
David Sodmanfa9b2af2017-12-24 13:28:59 -08002119
Alec Mouri8f7a0102020-04-15 12:11:10 -07002120 // 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
Yichi Chen28dee2c2020-07-06 21:24:14 +08002125 // TODO: b/160583065 Enable skip validation when SF caches all client composition layers
2126 mVSyncModulator->onRefreshed(mHadClientComposition || mReusedClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07002127
David Sodman7e4ae112018-02-09 15:02:28 -08002128 mLayersWithQueuedFrames.clear();
Vishnu Nairdf529052019-06-07 14:53:14 -07002129 if (mVisibleRegionsDirty) {
2130 mVisibleRegionsDirty = false;
Vishnu Nair60db8c02020-04-02 11:55:16 -07002131 if (mTracingEnabled && mAddCompositionStateToTrace) {
Vishnu Nairdf529052019-06-07 14:53:14 -07002132 mTracing.notify("visibleRegionsDirty");
2133 }
2134 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08002135
2136 if (mCompositionEngine->needsAnotherUpdate()) {
2137 signalLayerUpdate();
2138 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002139}
Mathias Agopian4fec8732012-06-29 14:12:52 -07002140
David Sodmanfa9b2af2017-12-24 13:28:59 -08002141bool SurfaceFlinger::handleMessageInvalidate() {
2142 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002143 bool refreshNeeded = handlePageFlip();
2144
Vishnu Nair4351ad52019-02-11 14:13:02 -08002145 if (mVisibleRegionsDirty) {
2146 computeLayerBounds();
2147 }
2148
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002149 for (auto& layer : mLayersPendingRefresh) {
2150 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002151 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002152 invalidateLayerStack(layer, visibleReg);
2153 }
2154 mLayersPendingRefresh.clear();
2155 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002156}
2157
Ana Krulece588e312018-09-18 12:32:24 -07002158void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
2159 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002160 // Update queue of past composite+present times and determine the
2161 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08002162 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002163 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08002164 while (!getBE().mCompositePresentTimes.empty()) {
2165 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002166 // 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;
David Sodman99974d22017-11-28 12:04:33 -08002173 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002174 }
2175
2176 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08002177 while (getBE().mCompositePresentTimes.size() > 16) {
2178 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002179 }
2180
Ana Krulece588e312018-09-18 12:32:24 -07002181 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08002182}
2183
Ana Krulece588e312018-09-18 12:32:24 -07002184void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
2185 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002186 // Integer division and modulo round toward 0 not -inf, so we need to
2187 // treat negative and positive offsets differently.
Ady Abraham9e16a482019-12-03 17:19:41 -08002188 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);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002192
Ady Abraham9e16a482019-12-03 17:19:41 -08002193 // Just in case mPhaseConfiguration->getCurrentOffsets().late.sf == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08002194 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07002195 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08002196 }
2197
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002198 // 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.
Ady Abraham9e16a482019-12-03 17:19:41 -08002202 // Snapping also allows an app to precisely calculate
2203 // mPhaseConfiguration->getCurrentOffsets().late.sf with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07002204 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;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002208
David Sodman99974d22017-11-28 12:04:33 -08002209 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002210 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
2211 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002212 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002213}
2214
David Sodman2b406362017-12-15 13:33:47 -08002215void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002216{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002217 ATRACE_CALL();
2218 ALOGV("postComposition");
2219
Brian Andersonf6386862016-10-31 16:34:13 -07002220 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002221 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002222 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002223 }
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002224
2225 const auto* display = ON_MAIN_THREAD(getDefaultDisplayDeviceLocked()).get();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002226
David Sodman73beded2017-11-15 11:56:06 -08002227 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002228 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002229 if (display && display->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002230 glCompositionDoneFenceTime =
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002231 std::make_shared<FenceTime>(display->getCompositionDisplay()
Lloyd Pique31cb2942018-10-19 17:23:03 -07002232 ->getRenderSurface()
2233 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002234 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002235 } else {
2236 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2237 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002238
David Sodman73beded2017-11-15 11:56:06 -08002239 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07002240 mPreviousPresentFences[1] = mPreviousPresentFences[0];
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002241 mPreviousPresentFences[0] =
2242 display ? getHwComposer().getPresentFence(*display->getId()) : Fence::NO_FENCE;
Ady Abrahambe0f9482019-04-24 15:41:53 -07002243 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08002244 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002245
Ana Krulece588e312018-09-18 12:32:24 -07002246 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08002247 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002248
Lloyd Piqueab039b52019-02-13 14:22:42 -08002249 // 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);
Brian Andersond0010582017-03-07 13:20:31 -08002254 CompositorTiming compositorTiming;
2255 {
David Sodman99974d22017-11-28 12:04:33 -08002256 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2257 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002258 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002259
Edgar Arriaga844fa672020-01-16 14:21:42 -08002260 mDrawingState.traverse([&](Layer* layer) {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002261 const bool frameLatched = layer->onPostComposition(display, glCompositionDoneFenceTime,
2262 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07002263 if (frameLatched) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002264 recordBufferingStats(layer->getName(), layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002265 }
Robert Carr2047fae2016-11-28 14:09:09 -08002266 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002267
Valerie Hau4b678442020-04-14 10:50:42 -07002268 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
2269 mTransactionCompletedThread.sendCallbacks();
2270
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002271 if (display && display->isPrimary() && display->getPowerMode() == hal::PowerMode::ON &&
2272 presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002273 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002274 }
2275
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002276 const bool isDisplayConnected = display && getHwComposer().isConnected(*display->getId());
2277
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002278 if (!hasSyncFramework) {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002279 if (isDisplayConnected && display->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002280 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002281 }
2282 }
2283
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002284 if (mAnimCompositionPending) {
2285 mAnimCompositionPending = false;
2286
Brian Anderson4e606e32017-03-16 15:34:57 -07002287 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002288 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002289 std::move(presentFenceTime));
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002290 } else if (isDisplayConnected) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002291 // The HWC doesn't support present fences, so use the refresh
2292 // timestamp instead.
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002293 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(*display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002294 mAnimFrameTracker.setActualPresentTime(presentTime);
2295 }
2296 mAnimFrameTracker.advanceFrame();
2297 }
Dan Stozab90cf072015-03-05 11:05:59 -08002298
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002299 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002300 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002301 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002302 }
2303
Vishnu Nair9b079a22020-01-21 14:36:08 -08002304 if (mReusedClientComposition) {
2305 mTimeStats->incrementClientCompositionReusedFrames();
2306 }
2307
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002308 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002309
Alec Mouri717bcb62020-02-10 17:07:19 -08002310 const size_t sfConnections = mScheduler->getEventThreadConnectionCount(mSfConnectionHandle);
2311 const size_t appConnections = mScheduler->getEventThreadConnectionCount(mAppConnectionHandle);
2312 mTimeStats->recordDisplayEventConnectionCount(sfConnections + appConnections);
2313
Alec Mouri1b6a60c2020-06-08 13:54:24 -07002314 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
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002322 if (isDisplayConnected && !display->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002323 return;
2324 }
2325
2326 nsecs_t currentTime = systemTime();
2327 if (mHasPoweredOff) {
2328 mHasPoweredOff = false;
2329 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002330 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002331 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002332 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2333 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002334 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002335 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002336 }
David Sodman4a36e932017-11-07 14:29:47 -08002337 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002338 }
David Sodman4a36e932017-11-07 14:29:47 -08002339 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002340
Alec Mouri4dde1782019-09-30 17:27:13 -07002341 // Cleanup any outstanding resources due to rendering a prior frame.
2342 getRenderEngine().cleanupPostRender();
2343
Dan Stoza436ccf32018-06-21 12:10:12 -07002344 {
2345 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002346 if (mTexturePool.size() < mTexturePoolSize) {
2347 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002348 const size_t offset = mTexturePool.size();
2349 mTexturePool.resize(mTexturePoolSize);
2350 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2351 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002352 } 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());
Dan Stoza436ccf32018-06-21 12:10:12 -07002358 }
2359 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002360
Kevin DuBois413287f2019-02-25 08:46:47 -08002361 if (mLumaSampling && mRegionSamplingThread) {
2362 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002363 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07002364
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()) {
Marissa Wall22b2de12019-12-02 18:11:43 -08002368 // getTotalSize returns the total number of buffers that were allocated by SurfaceFlinger
Dan Stoza45de5ba2019-04-25 14:12:09 -07002369 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2370 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002371}
2372
Lloyd Pique7eebe692020-04-22 22:40:06 -07002373FloatRect SurfaceFlinger::getLayerClipBoundsForDisplay(const DisplayDevice& displayDevice) const {
2374 return displayDevice.getViewport().toFloatRect();
2375}
2376
Vishnu Nair4351ad52019-02-11 14:13:02 -08002377void SurfaceFlinger::computeLayerBounds() {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002378 for (const auto& pair : ON_MAIN_THREAD(mDisplays)) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08002379 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())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002384 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002385 }
2386
Lloyd Pique7eebe692020-04-22 22:40:06 -07002387 layer->computeBounds(getLayerClipBoundsForDisplay(*displayDevice), ui::Transform(),
Vishnu Nairc97b8db2019-10-29 18:19:35 -07002388 0.f /* shadowRadius */);
Vishnu Nair4351ad52019-02-11 14:13:02 -08002389 }
2390 }
2391}
2392
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002393void SurfaceFlinger::postFrame() {
2394 const auto display = ON_MAIN_THREAD(getDefaultDisplayDeviceLocked());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002395 if (display && getHwComposer().isConnected(*display->getId())) {
2396 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002397 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2398 logFrameStats();
2399 }
2400 }
2401}
2402
Mathias Agopian87baae12012-07-31 12:38:26 -07002403void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002404{
Mathias Agopian841cde52012-03-01 15:44:37 -08002405 ATRACE_CALL();
2406
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002407 // 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
Mathias Agopianca4d3602011-05-19 15:38:14 -07002413 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002414 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002415
Mathias Agopianca4d3602011-05-19 15:38:14 -07002416 // 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.
Mathias Agopian4da75192010-08-10 17:19:56 -07002421
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002422 mVSyncModulator->onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002423 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002424 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002425
Mathias Agopianca4d3602011-05-19 15:38:14 -07002426 mDebugInTransaction = 0;
2427 invalidateHwcGeometry();
2428 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002429}
2430
Lloyd Piqueba04e622017-12-14 17:11:26 -08002431void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2432 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002433 const std::optional<DisplayIdentificationInfo> info =
2434 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002435
Dominik Laskowski075d3172018-05-24 15:50:06 -07002436 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002437 continue;
2438 }
2439
Dominik Laskowski55c85402020-01-21 16:25:47 -08002440 const DisplayId displayId = info->id;
2441 const auto it = mPhysicalDisplayTokens.find(displayId);
2442
Peiyong Line9d809e2020-04-14 13:10:48 -07002443 if (event.connection == hal::Connection::CONNECTED) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002444 if (it == mPhysicalDisplayTokens.end()) {
2445 ALOGV("Creating display %s", to_string(displayId).c_str());
2446
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002447 if (event.hwcDisplayId == getHwComposer().getInternalHwcDisplayId()) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002448 initScheduler(displayId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002449 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002450
Dominik Laskowski075d3172018-05-24 15:50:06 -07002451 DisplayDeviceState state;
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002452 state.physical = {displayId, getHwComposer().getDisplayConnectionType(displayId),
2453 event.hwcDisplayId};
Dominik Laskowski075d3172018-05-24 15:50:06 -07002454 state.isSecure = true; // All physical displays are currently considered secure.
2455 state.displayName = info->name;
Dominik Laskowski55c85402020-01-21 16:25:47 -08002456
2457 sp<IBinder> token = new BBinder();
2458 mCurrentState.displays.add(token, state);
2459 mPhysicalDisplayTokens.emplace(displayId, std::move(token));
2460
Dominik Laskowski075d3172018-05-24 15:50:06 -07002461 mInterceptor->saveDisplayCreation(state);
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002462 } 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;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002468 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002469 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002470 ALOGV("Removing display %s", to_string(displayId).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002471
Dominik Laskowski55c85402020-01-21 16:25:47 -08002472 const ssize_t index = mCurrentState.displays.indexOfKey(it->second);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002473 if (index >= 0) {
2474 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2475 mInterceptor->saveDisplayDeletion(state.sequenceId);
2476 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002477 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002478 mPhysicalDisplayTokens.erase(it);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002479 }
2480
2481 processDisplayChangesLocked();
2482 }
2483
2484 mPendingHotplugEvents.clear();
2485}
2486
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002487void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski98041832019-08-01 18:35:59 -07002488 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2489 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002490}
2491
Lloyd Pique99d3da52018-01-22 17:48:03 -08002492sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002493 const wp<IBinder>& displayToken,
2494 std::shared_ptr<compositionengine::Display> compositionDisplay,
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002495 const DisplayDeviceState& state,
2496 const sp<compositionengine::DisplaySurface>& displaySurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002497 const sp<IGraphicBufferProducer>& producer) {
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002498 auto displayId = compositionDisplay->getDisplayId();
2499 DisplayDeviceCreationArgs creationArgs(this, displayToken, compositionDisplay);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002500 creationArgs.sequenceId = state.sequenceId;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002501 creationArgs.isSecure = state.isSecure;
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002502 creationArgs.displaySurface = displaySurface;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002503 creationArgs.hasWideColorGamut = false;
2504 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002505
Dominik Laskowski55c85402020-01-21 16:25:47 -08002506 if (const auto& physical = state.physical) {
2507 creationArgs.connectionType = physical->type;
2508 }
2509
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002510 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002511 creationArgs.isPrimary = isInternalDisplay;
2512
2513 if (useColorManagement && displayId) {
2514 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002515 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002516 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002517 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002518 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002519
Dominik Laskowski7e045462018-05-30 13:02:02 -07002520 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002521 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002522 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002523 }
tangrobin6753a022018-08-10 10:58:54 +08002524 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002525
Dominik Laskowski075d3172018-05-24 15:50:06 -07002526 if (displayId) {
2527 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002528 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002529 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002530 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002531
Lloyd Pique90c115d2018-09-18 21:39:42 -07002532 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002533 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002534 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002535
Lloyd Pique99d3da52018-01-22 17:48:03 -08002536 // 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
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002538 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002539 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002540 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2541 }
2542
Dominik Laskowski718f9602019-11-09 20:01:35 -08002543 creationArgs.physicalOrientation =
2544 isInternalDisplay ? internalDisplayOrientation : ui::ROTATION_0;
Chia-I Wua02871c2018-08-27 14:38:23 -07002545
Lloyd Pique99d3da52018-01-22 17:48:03 -08002546 // virtual displays are always considered enabled
Peiyong Lin65248e02020-04-18 21:15:07 -07002547 creationArgs.initialPowerMode = state.isVirtual() ? hal::PowerMode::ON : hal::PowerMode::OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002548
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002549 sp<DisplayDevice> display = getFactory().createDisplayDevice(creationArgs);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002550
2551 if (maxFrameBufferAcquiredBuffers >= 3) {
2552 nativeWindowSurface->preallocateBuffers();
2553 }
2554
2555 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002556 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002557 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002558 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002559 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002560 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002561 display->getCompositionDisplay()->setColorProfile(
2562 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2563 RenderIntent::COLORIMETRIC,
2564 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002565 if (!state.isVirtual()) {
2566 LOG_ALWAYS_FATAL_IF(!displayId);
Ady Abraham2139f732019-11-13 18:56:40 -08002567 auto activeConfigId = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(*displayId));
2568 display->setActiveConfig(activeConfigId);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002569 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002570
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002571 display->setLayerStack(state.layerStack);
2572 display->setProjection(state.orientation, state.viewport, state.frame);
2573 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002574
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002575 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002576}
2577
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002578void 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
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002645 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 }
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002653
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002654 if (display->isPrimary()) {
2655 mScheduler->onPrimaryDisplayAreaChanged(display->getWidth() * display->getHeight());
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002656 }
2657}
2658
2659void 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()) {
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002666 LOG_FATAL_IF(!displayId);
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002667 dispatchDisplayHotplugEvent(displayId->value, false);
2668 }
2669 }
2670
2671 mDisplays.erase(displayToken);
2672}
2673
2674void 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);
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002679 if (currentBinder != drawingBinder || currentState.sequenceId != drawingState.sequenceId) {
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002680 // 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);
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002685 if (const auto& physical = currentState.physical) {
2686 getHwComposer().allocatePhysicalDisplay(physical->hwcDisplayId, physical->id);
2687 }
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002688 processDisplayAdded(displayToken, currentState);
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002689 if (currentState.physical) {
Marin Shalamanov4c5e3012020-06-04 21:41:42 +02002690 const auto display = getDisplayDeviceLocked(displayToken);
2691 setPowerModeInternal(display, hal::PowerMode::ON);
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002692 }
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002693 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);
Dominik Laskowski20134642020-04-20 22:36:44 -07002709
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002710 if (display->isPrimary()) {
2711 mScheduler->onPrimaryDisplayAreaChanged(currentState.width * currentState.height);
2712 }
Dominik Laskowski20134642020-04-20 22:36:44 -07002713
2714 if (mRefreshRateOverlay) {
2715 mRefreshRateOverlay->setViewport(display->getSize());
2716 }
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002717 }
2718 }
2719}
2720
Lloyd Pique347200f2017-12-14 17:00:15 -08002721void 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;
Lloyd Pique347200f2017-12-14 17:00:15 -08002729
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)
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002734 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);
Lloyd Pique347200f2017-12-14 17:00:15 -08002737 if (j < 0) {
2738 // in drawing state but not in current state
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002739 processDisplayRemoved(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002740 } else {
2741 // this display is in both lists. see if something changed.
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002742 const DisplayDeviceState& currentState = curr[j];
2743 const DisplayDeviceState& drawingState = draw[i];
2744 processDisplayChanged(displayToken, currentState, drawingState);
Lloyd Pique347200f2017-12-14 17:00:15 -08002745 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002746 }
2747
2748 // find displays that were added
2749 // (ie: in current state but not in drawing state)
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002750 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]);
Lloyd Pique347200f2017-12-14 17:00:15 -08002754 }
2755 }
2756 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002757
2758 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002759}
2760
Mathias Agopian87baae12012-07-31 12:38:26 -07002761void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002762{
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002763 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2764
Dan Stoza7dde5992015-05-22 09:51:44 -07002765 // Notify all layers of available frames
Edgar Arriaga844fa672020-01-16 14:21:42 -08002766 mCurrentState.traverse([expectedPresentTime](Layer* layer) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002767 layer->notifyAvailableFrames(expectedPresentTime);
Robert Carr2047fae2016-11-28 14:09:09 -08002768 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002769
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002770 /*
2771 * Traversal of the children
2772 * (perform the transaction for each of them if needed)
2773 */
2774
Valerie Haud50e7412020-06-16 17:58:14 -07002775 if ((transactionFlags & eTraversalNeeded) || mForceTraversal) {
2776 mForceTraversal = false;
Edgar Arriaga844fa672020-01-16 14:21:42 -08002777 mCurrentState.traverse([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002778 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002779 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002780
2781 const uint32_t flags = layer->doTransaction(0);
2782 if (flags & Layer::eVisibleRegion)
2783 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002784
2785 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002786 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002787 }
Robert Carr2047fae2016-11-28 14:09:09 -08002788 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002789 }
2790
2791 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002792 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002793 */
2794
Mathias Agopiane57f2922012-08-09 16:29:12 -07002795 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002796 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002797 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002798 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002799
Vishnu Nair6213bd92020-05-08 17:42:25 -07002800 if (transactionFlags & (eTransformHintUpdateNeeded | eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002801 // 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 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002812 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08002813 // 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 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002820 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002821 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002822 bool first = true;
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002823 mCurrentState.traverse([&](Layer* layer) REQUIRES(mStateLock) {
Mathias Agopian84300952012-11-21 16:02:13 -08002824 // 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).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002827 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002828 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002829 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.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002833 hintDisplay = nullptr;
2834 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002835 if (display->getCompositionDisplay()
2836 ->belongsInOutput(layer->getLayerStack(),
2837 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002838 if (hintDisplay) {
2839 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002840 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002841 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002842 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002843 }
2844 }
2845 }
2846 }
Chet Haase91d25932013-04-11 15:24:55 -07002847
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002848 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002849 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2850 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002851
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002852 // 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.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002855 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002856 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002857
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002858 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002859 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002860 if (hintDisplay) {
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002861 layer->updateTransformHint(hintDisplay->getTransformHint());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002862 }
Robert Carr2047fae2016-11-28 14:09:09 -08002863
2864 first = false;
2865 });
Mathias Agopian84300952012-11-21 16:02:13 -08002866 }
2867
Mathias Agopian3559b072012-08-15 13:46:03 -07002868 /*
2869 * Perform our own transaction if needed
2870 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002871
2872 if (mLayersAdded) {
2873 mLayersAdded = false;
2874 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002875 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;
Robert Carr2047fae2016-11-28 14:09:09 -08002883 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002884 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002885 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002886 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002887 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002888 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002889 }
Robert Carr2047fae2016-11-28 14:09:09 -08002890 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002891 }
2892
Vishnu Nairec0ab382019-02-13 15:32:56 -08002893 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002894 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002895}
2896
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002897void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002898 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002899 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002900 return;
2901 }
2902
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002903 if (mVisibleRegionsDirty || mInputInfoChanged) {
2904 mInputInfoChanged = false;
2905 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002906 } 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();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002910 }
2911
Arthur Hung6cbb9752019-09-05 16:38:18 +08002912 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002913}
2914
2915void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002916 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002917
2918 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Robert Carredd13602020-04-13 17:24:34 -07002919 if (layer->needsInputInfo()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002920 // When calculating the screen bounds we ignore the transparent region since it may
2921 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002922 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002923 }
2924 });
chaviw291d88a2019-02-14 10:33:58 -08002925
2926 mInputFlinger->setInputWindows(inputHandles,
2927 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2928 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07002929}
2930
Vishnu Nairec0ab382019-02-13 15:32:56 -08002931void SurfaceFlinger::commitInputWindowCommands() {
Rob Carr9a2cc992020-03-06 12:44:45 -08002932 mInputWindowCommands.merge(mPendingInputWindowCommands);
Vishnu Nairec0ab382019-02-13 15:32:56 -08002933 mPendingInputWindowCommands.clear();
2934}
2935
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002936void SurfaceFlinger::updateCursorAsync() {
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002937 compositionengine::CompositionRefreshArgs refreshArgs;
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002938 for (const auto& [_, display] : ON_MAIN_THREAD(mDisplays)) {
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002939 if (display->getId()) {
2940 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07002941 }
2942 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002943
2944 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002945}
2946
Ady Abraham2139f732019-11-13 18:56:40 -08002947void SurfaceFlinger::changeRefreshRate(const RefreshRate& refreshRate,
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07002948 Scheduler::ConfigEvent event) {
Ady Abraham8a82ba62020-01-17 12:43:17 -08002949 // 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);
Ady Abraham2139f732019-11-13 18:56:40 -08002954 changeRefreshRateLocked(refreshRate, event);
2955}
2956
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002957void 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
Ady Abraham2139f732019-11-13 18:56:40 -08002965 auto currentConfig = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(primaryDisplayId));
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002966 mRefreshRateConfigs =
Ana Krulec3f6a2062020-01-23 15:48:01 -08002967 std::make_unique<scheduler::RefreshRateConfigs>(getHwComposer().getConfigs(
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002968 primaryDisplayId),
2969 currentConfig);
2970 mRefreshRateStats =
2971 std::make_unique<scheduler::RefreshRateStats>(*mRefreshRateConfigs, *mTimeStats,
Peiyong Lin65248e02020-04-18 21:15:07 -07002972 currentConfig, hal::PowerMode::OFF);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002973 mRefreshRateStats->setConfigMode(currentConfig);
2974
Ady Abraham9e16a482019-12-03 17:19:41 -08002975 mPhaseConfiguration = getFactory().createPhaseConfiguration(*mRefreshRateConfigs);
2976
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002977 // start the EventThread
2978 mScheduler =
2979 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002980 *mRefreshRateConfigs, *this);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002981 mAppConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002982 mScheduler->createConnection("app", mPhaseConfiguration->getCurrentOffsets().late.app,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002983 impl::EventThread::InterceptVSyncsCallback());
2984 mSfConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002985 mScheduler->createConnection("sf", mPhaseConfiguration->getCurrentOffsets().late.sf,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002986 [this](nsecs_t timestamp) {
2987 mInterceptor->saveVSyncEvent(timestamp);
2988 });
2989
2990 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
2991 mVSyncModulator.emplace(*mScheduler, mAppConnectionHandle, mSfConnectionHandle,
Ady Abraham9e16a482019-12-03 17:19:41 -08002992 mPhaseConfiguration->getCurrentOffsets());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002993
2994 mRegionSamplingThread =
2995 new RegionSamplingThread(*this, *mScheduler,
2996 RegionSamplingThread::EnvironmentTimingTunables());
Alec Mouri60aee1c2019-10-28 16:18:59 -07002997 // 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 =
Ady Abrahamabc27602020-04-08 17:20:29 -07003005 mRefreshRateConfigs->getRefreshRateFromConfigId(currentConfig).getVsyncPeriod();
Ady Abrahamdfd62162020-06-10 16:11:56 -07003006 mScheduler->onPrimaryDisplayConfigChanged(mAppConnectionHandle, primaryDisplayId.value,
3007 currentConfig, vsyncPeriod);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003008}
3009
Mathias Agopian4fec8732012-06-29 14:12:52 -07003010void SurfaceFlinger::commitTransaction()
3011{
Vishnu Nair60db8c02020-04-02 11:55:16 -07003012 commitTransactionLocked();
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003013 mTransactionPending = false;
3014 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003015 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003016}
3017
Lloyd Pique58e24a32019-08-01 15:50:14 -07003018void SurfaceFlinger::commitTransactionLocked() {
3019 if (!mLayersPendingRemoval.isEmpty()) {
3020 // Notify removed layers now that they can't be drawn from
3021 for (const auto& l : mLayersPendingRemoval) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003022 recordBufferingStats(l->getName(), l->getOccupancyHistory(true));
Lloyd Pique58e24a32019-08-01 15:50:14 -07003023
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
Edgar Arriaga844fa672020-01-16 14:21:42 -08003047 mDrawingState.traverse([&](Layer* layer) {
Lloyd Pique58e24a32019-08-01 15:50:14 -07003048 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();
Edgar Arriaga844fa672020-01-16 14:21:42 -08003058 mDrawingState.traverse([&](Layer* layer) { layer->updateMirrorInfo(); });
Lloyd Pique58e24a32019-08-01 15:50:14 -07003059}
3060
chaviw74d90ad2019-04-26 14:45:26 -07003061void SurfaceFlinger::commitOffscreenLayers() {
3062 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003063 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [](Layer* layer) {
chaviw74d90ad2019-04-26 14:45:26 -07003064 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
3065 if (!trFlags) return;
3066
3067 layer->doTransaction(0);
3068 layer->commitChildList();
3069 });
3070 }
3071}
3072
Chia-I Wuab0c3192017-08-01 11:29:00 -07003073void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07003074 for (const auto& [token, displayDevice] : ON_MAIN_THREAD(mDisplays)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003075 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003076 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003077 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003078 }
3079 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003080}
3081
Dan Stoza6b9454d2014-11-07 16:00:59 -08003082bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003083{
Ady Abraham09bd3922019-04-08 10:44:56 -07003084 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003085 ALOGV("handlePageFlip");
3086
Brian Andersond6927fb2016-07-23 23:37:30 -07003087 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003088
Mathias Agopian4fec8732012-06-29 14:12:52 -07003089 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003090 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003091 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003092
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003093 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
3094
Eric Penner51c59cd2014-07-28 19:51:58 -07003095 // 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.
Edgar Arriaga844fa672020-01-16 14:21:42 -08003104 mDrawingState.traverse([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003105 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003106 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003107 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003108 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003109 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07003110 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07003111 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003112 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003113 } else {
3114 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003115 }
Robert Carr2047fae2016-11-28 14:09:09 -08003116 });
3117
chaviw49a108c2019-08-12 11:23:06 -07003118 // 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) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003122 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
chaviw49a108c2019-08-12 11:23:06 -07003123 [&](Layer* l) { l->latchAndReleaseBuffer(); });
3124 }
3125
Lloyd Piquef2c79392018-12-20 16:23:33 -08003126 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) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003132 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003133 mLayersPendingRefresh.push_back(layer);
3134 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003135 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003136 if (layer->isBufferLatched()) {
3137 newDataLatched = true;
3138 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003139 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003140 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003141
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003142 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003143
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.
Chia-I Wua36bf922017-06-30 12:51:05 -07003147 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003148 signalLayerUpdate();
3149 }
3150
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003151 // 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
Edgar Arriaga844fa672020-01-16 14:21:42 -08003157 mDrawingState.traverse([&](Layer* layer) { layer->updateCloneBufferInfo(); });
chaviw74b03172019-08-19 11:09:03 -07003158
Dan Stoza6b9454d2014-11-07 16:00:59 -08003159 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003160 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003161}
3162
Mathias Agopianad456f92011-01-13 17:53:01 -08003163void SurfaceFlinger::invalidateHwcGeometry()
3164{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003165 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003166}
3167
Robert Carrc0df3122019-04-11 13:18:21 -07003168status_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,
Vishnu Nair6213bd92020-05-08 17:42:25 -07003171 const sp<Layer>& parentLayer, bool addToCurrentState,
3172 uint32_t* outTransformHint) {
Dan Stoza7d89d062015-04-30 13:29:25 -07003173 // add this layer to the current state list
3174 {
3175 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07003176 sp<Layer> parent;
3177 if (parentHandle != nullptr) {
Alec Mouri9a02eda2020-04-21 17:39:34 -07003178 parent = fromHandleLocked(parentHandle).promote();
Robert Carrc0df3122019-04-11 13:18:21 -07003179 if (parent == nullptr) {
3180 return NAME_NOT_FOUND;
3181 }
3182 } else {
3183 parent = parentLayer;
3184 }
3185
Ady Abraham0a525092020-03-03 12:51:24 -08003186 if (mNumLayers >= ISurfaceComposer::MAX_LAYERS) {
chaviweadf0d42019-08-12 13:28:29 -07003187 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Ady Abraham0a525092020-03-03 12:51:24 -08003188 ISurfaceComposer::MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003189 return NO_MEMORY;
3190 }
Robert Carrc0df3122019-04-11 13:18:21 -07003191
3192 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
3193
Robert Carrb89ea9d2018-12-10 13:01:14 -08003194 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003195 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003196 } else if (parent == nullptr) {
3197 lbc->onRemovedFromCurrentState();
3198 } else if (parent->isRemovedFromCurrentState()) {
3199 parent->addChild(lbc);
3200 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003201 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003202 parent->addChild(lbc);
3203 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003204
Yiwei Zhang243b3782018-05-15 17:40:04 -07003205 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(),
chaviweadf0d42019-08-12 13:28:29 -07003211 mMaxGraphicBufferProducerListSize, mNumLayers.load());
Yiwei Zhang243b3782018-05-15 17:40:04 -07003212 }
Vishnu Nair6213bd92020-05-08 17:42:25 -07003213
3214 if (const auto display = getDefaultDisplayDeviceLocked()) {
Dominik Laskowskib7251f42020-04-20 17:42:59 -07003215 lbc->updateTransformHint(display->getTransformHint());
Vishnu Nair6213bd92020-05-08 17:42:25 -07003216 }
3217 if (outTransformHint) {
3218 *outTransformHint = lbc->getTransformHint();
3219 }
3220
Robert Carr1f0a16a2016-10-24 16:27:39 -07003221 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003222 }
3223
Mathias Agopian96f08192010-06-02 23:28:45 -07003224 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003225 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003226
Dan Stoza7d89d062015-04-30 13:29:25 -07003227 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003228}
3229
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07003230void SurfaceFlinger::removeGraphicBufferProducerAsync(const wp<IBinder>& binder) {
3231 static_cast<void>(schedule([=] {
3232 Mutex::Autolock lock(mStateLock);
3233 mGraphicBufferProducerList.erase(binder);
3234 }));
3235}
3236
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003237uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003238 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003239}
3240
Mathias Agopian3f844832013-08-07 21:24:32 -07003241uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003242 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003243}
3244
Mathias Agopian3f844832013-08-07 21:24:32 -07003245uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ady Abrahambf1349c2020-06-12 14:26:18 -07003246 return setTransactionFlags(flags, Scheduler::TransactionStart::Normal);
Dan Stoza84d619e2018-03-28 17:07:36 -07003247}
3248
3249uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003250 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003251 uint32_t old = mTransactionFlags.fetch_or(flags);
Dominik Laskowskieddeda12019-07-19 11:54:13 -07003252 mVSyncModulator->setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003253 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003254 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003255 }
3256 return old;
3257}
3258
Valerie Haud50e7412020-06-16 17:58:14 -07003259void SurfaceFlinger::setTraversalNeeded() {
3260 mForceTraversal = true;
Robert Carr7ec777d2020-05-29 12:02:51 -07003261}
3262
Marissa Wall713b63f2018-10-17 15:42:43 -07003263bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07003264 // 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;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003268 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07003269 {
3270 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003271
Valerie Haufce31b82019-04-30 16:41:14 -07003272 auto it = mTransactionQueues.begin();
3273 while (it != mTransactionQueues.end()) {
3274 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07003275
Valerie Haufce31b82019-04-30 16:41:14 -07003276 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,
Valerie Hau9dab9732019-08-20 09:29:25 -07003286 transaction.buffer, transaction.postTime,
3287 transaction.privileged, transaction.hasListenerCallbacks,
3288 transaction.listenerCallbacks, /*isMainThread*/ true);
Valerie Haufce31b82019-04-30 16:41:14 -07003289 transactionQueue.pop();
3290 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003291 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003292
Valerie Haufce31b82019-04-30 16:41:14 -07003293 if (transactionQueue.empty()) {
3294 it = mTransactionQueues.erase(it);
3295 mTransactionCV.broadcast();
3296 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07003297 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07003298 }
Valerie Hauf6016b62019-03-28 10:49:59 -07003299 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003300 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003301 return flushedATransaction;
3302}
3303
3304bool SurfaceFlinger::transactionFlushNeeded() {
3305 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003306}
3307
chaviwca27f252018-02-06 16:46:39 -08003308
Marissa Wall17b4e452018-12-26 16:32:34 -08003309bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3310 const Vector<ComposerState>& states) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003311
3312 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08003313 // 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
Marissa Wall713b63f2018-10-17 15:42:43 -07003320 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) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003326 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003327 }
3328 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003329 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003330}
3331
Valerie Hau9dab9732019-08-20 09:29:25 -07003332void 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) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003337 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003338
Valerie Haubc6ddb12019-03-08 11:10:15 -08003339 const int64_t postTime = systemTime();
3340
Robert Carr14167e02019-02-13 13:50:55 -08003341 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3342
Mathias Agopian698c0872011-06-28 19:09:31 -07003343 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003344
Marissa Wall713b63f2018-10-17 15:42:43 -07003345 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07003346 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 }
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003361
Ady Abraham5facfb12020-04-22 15:18:31 -07003362 const bool pendingTransactions = itr != mTransactionQueues.end();
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003363 // Expected present time is computed and cached on invalidate, so it may be stale.
Ady Abraham5facfb12020-04-22 15:18:31 -07003364 if (!pendingTransactions) {
3365 mExpectedPresentTime = calculateExpectedPresentTime(systemTime());
3366 }
3367
3368 if (pendingTransactions || !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003369 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003370 uncacheBuffer, postTime, privileged,
3371 hasListenerCallbacks, listenerCallbacks);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003372 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07003373 return;
3374 }
3375
Valerie Haubc6ddb12019-03-08 11:10:15 -08003376 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003377 uncacheBuffer, postTime, privileged, hasListenerCallbacks,
3378 listenerCallbacks);
Marissa Wall713b63f2018-10-17 15:42:43 -07003379}
3380
Valerie Hau9dab9732019-08-20 09:29:25 -07003381void 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) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003387 uint32_t transactionFlags = 0;
3388
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003389 if (flags & eAnimation) {
3390 // For window updates that are part of an animation we must wait for
3391 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07003392 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003393 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003394 if (CC_UNLIKELY(err != NO_ERROR)) {
3395 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003396 // caller after a few seconds.
3397 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3398 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003399 mAnimTransactionPending = false;
3400 break;
3401 }
3402 }
3403 }
3404
chaviwca27f252018-02-06 16:46:39 -08003405 for (const DisplayState& display : displays) {
3406 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003407 }
3408
Valerie Hau9dab9732019-08-20 09:29:25 -07003409 // 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);
Marissa Walld600d572019-03-26 15:38:50 -07003415 }
3416
Valerie Hau9dab9732019-08-20 09:29:25 -07003417 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash> listenerCallbacksWithSurfaces;
Marissa Walle2ffb422018-10-12 11:33:52 -07003418 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003419 for (const ComposerState& state : states) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003420 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, postTime, privileged,
3421 listenerCallbacksWithSurfaces);
Ady Abraham5def7332020-05-29 16:13:47 -07003422 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 }
Marissa Wall3dad52d2019-03-22 14:03:19 -07003428 }
3429
Valerie Hau9dab9732019-08-20 09:29:25 -07003430 for (const auto& listenerCallback : listenerCallbacksWithSurfaces) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003431 mTransactionCompletedThread.endRegistration(listenerCallback);
3432 }
3433
Marissa Walle2ffb422018-10-12 11:33:52 -07003434 // If the state doesn't require a traversal and there are callbacks, send them now
Valerie Hau9dab9732019-08-20 09:29:25 -07003435 if (!(clientStateFlags & eTraversalNeeded) && hasListenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003436 mTransactionCompletedThread.sendCallbacks();
3437 }
3438 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003439
chaviw273171b2018-12-26 11:46:30 -08003440 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3441
Marissa Wall947d34e2019-03-29 14:03:53 -07003442 if (uncacheBuffer.isValid()) {
3443 ClientCache::getInstance().erase(uncacheBuffer);
Alec Mouri4545a8a2019-08-08 20:05:32 -07003444 getRenderEngine().unbindExternalTextureBuffer(uncacheBuffer.id);
Marissa Wall78b72202019-03-15 14:58:34 -07003445 }
3446
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003447 // 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))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003453 transactionFlags = eTransactionNeeded;
3454 }
3455
Marissa Wall06255332019-03-27 13:48:27 -07003456 // 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);
Valerie Haud50e7412020-06-16 17:58:14 -07003460 mForceTraversal = true;
Marissa Wall06255332019-03-27 13:48:27 -07003461 }
3462
Ady Abrahambf1349c2020-06-12 14:26:18 -07003463 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
Mathias Agopian386aa982011-11-07 21:58:03 -08003476 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003477 if (mInterceptor->isEnabled()) {
3478 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003479 }
Irvel468051e2016-06-13 16:44:44 -07003480
Ady Abrahambf1349c2020-06-12 14:26:18 -07003481 // 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
Mathias Agopian386aa982011-11-07 21:58:03 -08003491 // this triggers the transaction
Ady Abrahambf1349c2020-06-12 14:26:18 -07003492 setTransactionFlags(transactionFlags, transactionStart);
Mathias Agopian386aa982011-11-07 21:58:03 -08003493
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003494 if (flags & eAnimation) {
3495 mAnimTransactionPending = true;
3496 }
Robert Carr238f4a22020-04-29 13:04:02 -07003497
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) {
chaviw4fe36852019-04-15 16:25:49 -07003510 mPendingSyncInputWindows = true;
3511 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003512
Robert Carr238f4a22020-04-29 13:04:02 -07003513
Valerie Hau0779ded2019-03-19 12:43:04 -07003514 // 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)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003519 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.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003523 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3524 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003525 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003526 break;
3527 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003528 }
Ady Abrahambf1349c2020-06-12 14:26:18 -07003529 } 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 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003536 }
3537}
3538
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003539uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3540 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3541 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003542
Mathias Agopiane57f2922012-08-09 16:29:12 -07003543 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003544 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;
Michael Lentine47e45402014-07-18 15:34:25 -07003551 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003552 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003553 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
Mathias Agopiane57f2922012-08-09 16:29:12 -07003584 return flags;
3585}
3586
Steven Thomasd4071902020-03-24 16:02:53 -07003587bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess(bool usePermissionCache) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003588 IPCThreadState* ipc = IPCThreadState::self();
3589 const int pid = ipc->getCallingPid();
3590 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003591 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Steven Thomasd4071902020-03-24 16:02:53 -07003592 (usePermissionCache ? !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)
3593 : !checkPermission(sAccessSurfaceFlinger, pid, uid))) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003594 return false;
3595 }
3596 return true;
3597}
3598
Marissa Wall3dad52d2019-03-22 14:03:19 -07003599uint32_t SurfaceFlinger::setClientStateLocked(
Valerie Hau9dab9732019-08-20 09:29:25 -07003600 const ComposerState& composerState, int64_t desiredPresentTime, int64_t postTime,
3601 bool privileged,
3602 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash>& listenerCallbacks) {
chaviwca27f252018-02-06 16:46:39 -08003603 const layer_state_t& s = composerState.state;
chaviwca27f252018-02-06 16:46:39 -08003604
Valerie Hau9dab9732019-08-20 09:29:25 -07003605 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
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08003612 sp<Layer> layer = nullptr;
3613 if (s.surface) {
Alec Mouri9a02eda2020-04-21 17:39:34 -07003614 layer = fromHandleLocked(s.surface).promote();
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08003615 } 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 }
chaviw8b3871a2017-11-01 17:41:01 -07003619 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003620 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003621 mTransactionCompletedThread.registerUnpresentedCallbackHandle(
Valerie Hau9dab9732019-08-20 09:29:25 -07003622 new CallbackHandle(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07003623 }
chaviw8b3871a2017-11-01 17:41:01 -07003624 return 0;
3625 }
3626
chaviw8b3871a2017-11-01 17:41:01 -07003627 uint32_t flags = 0;
3628
Garfield Tan8a3083e2018-12-03 13:21:07 -08003629 const uint64_t what = s.what;
Jorim Jaggidba32732018-05-28 17:43:52 +02003630
3631 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3632 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003633 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003634 layer->pushPendingState();
3635 }
3636
Valerie Hau871d6352020-01-29 08:44:02 -08003637 // Only set by BLAST adapter layers
3638 if (what & layer_state_t::eProducerDisconnect) {
3639 layer->onDisconnect();
3640 }
3641
chaviw8b3871a2017-11-01 17:41:01 -07003642 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07003643 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07003644 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003645 }
chaviw8b3871a2017-11-01 17:41:01 -07003646 }
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) {
chaviw64f7b422017-07-12 10:31:58 -07003651 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003652 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003653 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 }
chaviw8b3871a2017-11-01 17:41:01 -07003659 } else {
3660 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003661 flags |= eTransactionNeeded|eTraversalNeeded;
3662 }
3663 }
chaviw8b3871a2017-11-01 17:41:01 -07003664 }
3665 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003666 // 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 }
chaviw8b3871a2017-11-01 17:41:01 -07003681 }
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 }
Peiyong Lind3788632018-09-18 16:01:31 -07003696 if (what & layer_state_t::eColorTransformChanged) {
3697 if (layer->setColorTransform(s.colorTransform)) {
3698 flags |= eTraversalNeeded;
3699 }
3700 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003701 if (what & layer_state_t::eBackgroundColorChanged) {
3702 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3703 flags |= eTraversalNeeded;
3704 }
3705 }
chaviw8b3871a2017-11-01 17:41:01 -07003706 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003707 // 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.
Robert Carr14167e02019-02-13 13:50:55 -08003722 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003723 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 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003733 if (what & layer_state_t::eCropChanged_legacy) {
chaviw214c89d2019-09-04 16:03:53 -07003734 if (layer->setCrop_legacy(s.crop_legacy)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07003735 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003736 if (what & layer_state_t::eCornerRadiusChanged) {
3737 if (layer->setCornerRadius(s.cornerRadius))
3738 flags |= eTraversalNeeded;
3739 }
Lucas Dupin130e55c2020-05-26 16:11:18 -07003740 if (what & layer_state_t::eBackgroundBlurRadiusChanged && !mDisableBlurs && mSupportsBlur) {
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08003741 if (layer->setBackgroundBlurRadius(s.backgroundBlurRadius)) flags |= eTraversalNeeded;
3742 }
chaviw8b3871a2017-11-01 17:41:01 -07003743 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",
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003749 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003750 } else if (idx < 0) {
3751 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003752 "that also does not appear in the top level layer list. Something"
3753 " has gone wrong.",
3754 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003755 } 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)
Vishnu Nair6213bd92020-05-08 17:42:25 -07003760 flags |= eTransactionNeeded | eTraversalNeeded | eTransformHintUpdateNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07003761 }
3762 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003763 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;
chaviw8b3871a2017-11-01 17:41:01 -07003768 if (authenticateSurfaceTextureLocked(gbp)) {
3769 const auto& otherLayer =
3770 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003771 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003772 } else {
3773 ALOGE("Attempt to defer transaction to to an"
3774 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003775 }
3776 }
chaviw8b3871a2017-11-01 17:41:01 -07003777 // 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 }
chaviw8b3871a2017-11-01 17:41:01 -07003780 if (what & layer_state_t::eReparentChildren) {
3781 if (layer->reparentChildren(s.reparentHandle)) {
3782 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003783 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003784 }
chaviw8b3871a2017-11-01 17:41:01 -07003785 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 }
Marissa Wall61c58622018-07-18 10:12:20 -07003793 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 }
Marissa Wall861616d2018-10-22 12:52:23 -07003803 if (what & layer_state_t::eFrameChanged) {
3804 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3805 }
Marissa Wall61c58622018-07-18 10:12:20 -07003806 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 }
Robert Carr720e5062018-07-30 17:45:14 -07003824 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08003825 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003826 layer->setInputInfo(s.inputInfo);
3827 flags |= eTraversalNeeded;
3828 } else {
3829 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3830 }
Robert Carr720e5062018-07-30 17:45:14 -07003831 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003832 if (what & layer_state_t::eMetadataChanged) {
3833 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3834 }
Peiyong Linc502cb72019-03-01 15:00:23 -08003835 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
3836 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
3837 flags |= eTraversalNeeded;
3838 }
3839 }
Vishnu Nairc97b8db2019-10-29 18:19:35 -07003840 if (what & layer_state_t::eShadowRadiusChanged) {
3841 if (layer->setShadowRadius(s.shadowRadius)) flags |= eTraversalNeeded;
3842 }
Ana Krulecc84d09b2019-11-02 23:10:29 +01003843 if (what & layer_state_t::eFrameRateSelectionPriority) {
3844 if (privileged && layer->setFrameRateSelectionPriority(s.frameRateSelectionPriority)) {
3845 flags |= eTraversalNeeded;
3846 }
3847 }
Steven Thomas3172e202020-01-06 19:25:30 -08003848 if (what & layer_state_t::eFrameRateChanged) {
Steven Thomas62a4cf82020-01-31 12:04:03 -08003849 if (ValidateFrameRate(s.frameRate, s.frameRateCompatibility,
3850 "SurfaceFlinger::setClientStateLocked") &&
3851 layer->setFrameRate(Layer::FrameRate(s.frameRate,
3852 Layer::FrameRate::convertCompatibility(
3853 s.frameRateCompatibility)))) {
Ady Abraham71c437d2020-01-31 15:56:57 -08003854 flags |= eTraversalNeeded;
Steven Thomas62a4cf82020-01-31 12:04:03 -08003855 }
Steven Thomas3172e202020-01-06 19:25:30 -08003856 }
Vishnu Nair6213bd92020-05-08 17:42:25 -07003857 if (what & layer_state_t::eFixedTransformHintChanged) {
3858 if (layer->setFixedTransformHint(s.fixedTransformHint)) {
3859 flags |= eTraversalNeeded | eTransformHintUpdateNeeded;
3860 }
3861 }
Vishnu Nair14d76922019-08-05 08:41:20 -07003862 // 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 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003875 std::vector<sp<CallbackHandle>> callbackHandles;
Valerie Hau9dab9732019-08-20 09:29:25 -07003876 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!s.listeners.empty())) {
3877 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003878 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3879 }
3880 }
Marissa Wall78b72202019-03-15 14:58:34 -07003881 bool bufferChanged = what & layer_state_t::eBufferChanged;
3882 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
3883 sp<GraphicBuffer> buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003884 if (bufferChanged && cacheIdChanged && s.buffer != nullptr) {
Marissa Wall78b72202019-03-15 14:58:34 -07003885 buffer = s.buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003886 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 }
Marissa Wall78b72202019-03-15 14:58:34 -07003896 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003897 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003898 } else if (bufferChanged) {
3899 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08003900 }
Marissa Wall78b72202019-03-15 14:58:34 -07003901 if (buffer) {
Valerie Haubf784642020-01-29 07:25:23 -08003902 if (layer->setBuffer(buffer, s.acquireFence, postTime, desiredPresentTime,
3903 s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08003904 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08003905 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003906 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003907 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3908 // Do not put anything that updates layer state or modifies flags after
3909 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003910 return flags;
3911}
3912
chaviw273171b2018-12-26 11:46:30 -08003913uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3914 uint32_t flags = 0;
chaviwa911b102019-02-14 10:18:33 -08003915 if (inputWindowCommands.syncInputWindows) {
3916 flags |= eTraversalNeeded;
3917 }
3918
Vishnu Nairec0ab382019-02-13 15:32:56 -08003919 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08003920 return flags;
3921}
3922
chaviwfe94a222019-08-21 13:52:59 -07003923status_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;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003931 std::string uniqueName = getUniqueLayerName("MirrorRoot");
chaviwfe94a222019-08-21 13:52:59 -07003932
3933 {
3934 Mutex::Autolock _l(mStateLock);
Alec Mouri9a02eda2020-04-21 17:39:34 -07003935 mirrorFrom = fromHandleLocked(mirrorFromHandle).promote();
chaviwfe94a222019-08-21 13:52:59 -07003936 if (!mirrorFrom) {
3937 return NAME_NOT_FOUND;
3938 }
3939
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003940 status_t result = createContainerLayer(client, std::move(uniqueName), -1, -1, 0,
3941 LayerMetadata(), outHandle, &mirrorLayer);
chaviwfe94a222019-08-21 13:52:59 -07003942 if (result != NO_ERROR) {
3943 return result;
3944 }
3945
3946 mirrorLayer->mClonedChild = mirrorFrom->createClone();
3947 }
3948
Vishnu Nair6213bd92020-05-08 17:42:25 -07003949 return addClientLayer(client, *outHandle, nullptr, mirrorLayer, nullptr, nullptr, false,
3950 nullptr /* outTransformHint */);
chaviwfe94a222019-08-21 13:52:59 -07003951}
3952
Marissa Wall2d814fb2019-04-09 18:52:57 +00003953status_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,
Robert Carrc0df3122019-04-11 13:18:21 -07003956 sp<IGraphicBufferProducer>* gbp,
Valerie Hau1acd6962019-10-28 16:35:48 -07003957 const sp<IBinder>& parentHandle, const sp<Layer>& parentLayer,
3958 uint32_t* outTransformHint) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003959 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003960 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003961 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003962 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003963 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003964
Robert Carrc0df3122019-04-11 13:18:21 -07003965 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
3966 "Expected only one of parentLayer or parentHandle to be non-null. "
3967 "Programmer error?");
3968
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003969 status_t result = NO_ERROR;
3970
3971 sp<Layer> layer;
3972
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003973 std::string uniqueName = getUniqueLayerName(name.string());
Cody Northropbc755282017-03-31 12:00:08 -06003974
Evan Roskya1f1e152019-01-24 16:17:46 -08003975 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) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07003982 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08003983 primaryDisplayOnly = true;
3984 }
3985 }
3986
Mathias Agopian3165cc22012-08-08 19:42:09 -07003987 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003988 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003989 result = createBufferQueueLayer(client, std::move(uniqueName), w, h, flags,
3990 std::move(metadata), format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003991
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003992 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003993 case ISurfaceComposerClient::eFXSurfaceBufferState:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003994 result = createBufferStateLayer(client, std::move(uniqueName), w, h, flags,
Vishnu Nair6213bd92020-05-08 17:42:25 -07003995 std::move(metadata), handle, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07003996 break;
Vishnu Nairfa247b12020-02-11 08:58:26 -08003997 case ISurfaceComposerClient::eFXSurfaceEffect:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003998 // 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
Vishnu Nairfa247b12020-02-11 08:58:26 -08004005 result = createEffectLayer(client, std::move(uniqueName), w, h, flags,
4006 std::move(metadata), handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004007 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004008 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004009 // 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 }
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004015 result = createContainerLayer(client, std::move(uniqueName), w, h, flags,
4016 std::move(metadata), handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07004017 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004018 default:
4019 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004020 break;
4021 }
4022
Dan Stoza7d89d062015-04-30 13:29:25 -07004023 if (result != NO_ERROR) {
4024 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004025 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004026
Evan Roskya1f1e152019-01-24 16:17:46 -08004027 if (primaryDisplayOnly) {
4028 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07004029 }
4030
Robert Carrb89ea9d2018-12-10 13:01:14 -08004031 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07004032 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
Vishnu Nair6213bd92020-05-08 17:42:25 -07004033 addToCurrentState, outTransformHint);
Dan Stoza7d89d062015-04-30 13:29:25 -07004034 if (result != NO_ERROR) {
4035 return result;
4036 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004037 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004038
4039 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004040 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004041}
4042
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004043std::string SurfaceFlinger::getUniqueLayerName(const char* name) {
4044 unsigned dupeCounter = 0;
Cody Northropbc755282017-03-31 12:00:08 -06004045
4046 // Tack on our counter whether there is a hit or not, so everyone gets a tag
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004047 std::string uniqueName = base::StringPrintf("%s#%u", name, dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06004048
Dan Stoza436ccf32018-06-21 12:10:12 -07004049 // Grab the state lock since we're accessing mCurrentState
4050 Mutex::Autolock lock(mStateLock);
4051
Cody Northropbc755282017-03-31 12:00:08 -06004052 // Loop over layers until we're sure there is no matching name
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004053 bool matchFound = true;
Cody Northropbc755282017-03-31 12:00:08 -06004054 while (matchFound) {
4055 matchFound = false;
Edgar Arriaga844fa672020-01-16 14:21:42 -08004056 mCurrentState.traverse([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004057 if (layer->getName() == uniqueName) {
4058 matchFound = true;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004059 uniqueName = base::StringPrintf("%s#%u", name, ++dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06004060 }
4061 });
4062 }
4063
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004064 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name, uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004065 return uniqueName;
4066}
4067
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004068status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, std::string name,
Marissa Wallfd668622018-05-10 10:21:13 -07004069 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08004070 LayerMetadata metadata, PixelFormat& format,
4071 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07004072 sp<IGraphicBufferProducer>* gbp,
4073 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004074 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004075 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004076 case PIXEL_FORMAT_TRANSPARENT:
4077 case PIXEL_FORMAT_TRANSLUCENT:
4078 format = PIXEL_FORMAT_RGBA_8888;
4079 break;
4080 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004081 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004082 break;
4083 }
4084
chaviwb4c6e582019-08-16 14:35:07 -07004085 sp<BufferQueueLayer> layer;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004086 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07004087 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
Marissa Wallfd668622018-05-10 10:21:13 -07004096 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004097 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004098 *handle = layer->getHandle();
4099 *gbp = layer->getProducer();
4100 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004101 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004102
Marissa Wallfd668622018-05-10 10:21:13 -07004103 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004104 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004105}
4106
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004107status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, std::string name,
Marissa Wall61c58622018-07-18 10:12:20 -07004108 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08004109 LayerMetadata metadata, sp<IBinder>* handle,
Vishnu Nair6213bd92020-05-08 17:42:25 -07004110 sp<Layer>* outLayer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004111 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07004112 args.textureName = getNewTexture();
4113 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(args);
Marissa Wall61c58622018-07-18 10:12:20 -07004114 *handle = layer->getHandle();
4115 *outLayer = layer;
4116
4117 return NO_ERROR;
4118}
4119
Vishnu Nairfa247b12020-02-11 08:58:26 -08004120status_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(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004124 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004125 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004126 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004127}
4128
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004129status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, std::string name,
Evan Roskya1f1e152019-01-24 16:17:46 -08004130 uint32_t w, uint32_t h, uint32_t flags,
4131 LayerMetadata metadata, sp<IBinder>* handle,
4132 sp<Layer>* outLayer) {
4133 *outLayer = getFactory().createContainerLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004134 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Robert Carr6b3f6c52018-08-13 13:05:17 -07004135 *handle = (*outLayer)->getHandle();
4136 return NO_ERROR;
4137}
4138
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004139void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004140 mLayersPendingRemoval.add(layer);
4141 mLayersRemoved = true;
4142 setTransactionFlags(eTransactionNeeded);
4143}
4144
Robert Carr695d5282018-12-18 15:27:58 -08004145void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004146{
Robert Carr2e102c92018-10-23 12:11:15 -07004147 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004148 // 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);
Robert Carrc0df3122019-04-11 13:18:21 -07004156
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
Robert Carr695d5282018-12-18 15:27:58 -08004166 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004167}
4168
Mathias Agopianb60314a2012-04-10 22:09:54 -07004169// ---------------------------------------------------------------------------
4170
Andy McFadden13a082e2012-08-24 10:16:42 -07004171void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004172 const auto display = getDefaultDisplayDeviceLocked();
4173 if (!display) return;
4174
4175 const sp<IBinder> token = display->getDisplayToken().promote();
4176 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004177
Jesse Hall01e29052013-02-19 16:13:35 -08004178 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004179 Vector<ComposerState> state;
4180 Vector<DisplayState> displays;
4181 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004182 d.what = DisplayState::eDisplayProjectionChanged |
4183 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004184 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004185 d.layerStack = 0;
Dominik Laskowski718f9602019-11-09 20:01:35 -08004186 d.orientation = ui::ROTATION_0;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004187 d.frame.makeInvalid();
4188 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004189 d.width = 0;
4190 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004191 displays.add(d);
Valerie Hau9dab9732019-08-20 09:29:25 -07004192 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, false,
4193 {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07004194
Peiyong Lin65248e02020-04-18 21:15:07 -07004195 setPowerModeInternal(display, hal::PowerMode::ON);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004196
Dominik Laskowski83b88212018-12-11 13:34:06 -08004197 const nsecs_t vsyncPeriod = getVsyncPeriod();
4198 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004199
Brian Andersond0010582017-03-07 13:20:31 -08004200 // Use phase of 0 since phase is not known.
4201 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004202 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004203 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004204}
4205
4206void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004207 // Async since we may be called from the main thread.
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07004208 static_cast<void>(schedule([this]() MAIN_THREAD { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004209}
4210
Peiyong Lin65248e02020-04-18 21:15:07 -07004211void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, hal::PowerMode mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004212 if (display->isVirtual()) {
4213 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004214 return;
4215 }
4216
Dominik Laskowski075d3172018-05-24 15:50:06 -07004217 const auto displayId = display->getId();
4218 LOG_ALWAYS_FATAL_IF(!displayId);
4219
Dominik Laskowski34157762018-10-31 13:07:19 -07004220 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004221
Peiyong Lin65248e02020-04-18 21:15:07 -07004222 const hal::PowerMode currentMode = display->getPowerMode();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004223 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004224 return;
4225 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004226
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004227 display->setPowerMode(mode);
4228
Lloyd Pique4dccc412018-01-22 17:21:36 -08004229 if (mInterceptor->isEnabled()) {
Peiyong Lin65248e02020-04-18 21:15:07 -07004230 mInterceptor->savePowerModeUpdate(display->getSequenceId(), static_cast<int32_t>(mode));
Irvelffc9efc2016-07-27 15:16:37 -07004231 }
4232
Peiyong Lin65248e02020-04-18 21:15:07 -07004233 if (currentMode == hal::PowerMode::OFF) {
Martin Liu4a322352020-03-24 21:30:38 +08004234 if (SurfaceFlinger::setSchedFifo(true) != NO_ERROR) {
4235 ALOGW("Couldn't set SCHED_FIFO on display on: %s\n", strerror(errno));
4236 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004237 getHwComposer().setPowerMode(*displayId, mode);
Peiyong Lin65248e02020-04-18 21:15:07 -07004238 if (display->isPrimary() && mode != hal::PowerMode::DOZE_SUSPEND) {
Marin Shalamanovc75b0772020-06-12 22:29:11 +02004239 getHwComposer().setVsyncEnabled(*displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08004240 mScheduler->onScreenAcquired(mAppConnectionHandle);
4241 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004242 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004243
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004244 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004245 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004246 repaintEverything();
Peiyong Lin65248e02020-04-18 21:15:07 -07004247 } else if (mode == hal::PowerMode::OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004248 // Turn off the display
Martin Liu4a322352020-03-24 21:30:38 +08004249 if (SurfaceFlinger::setSchedFifo(false) != NO_ERROR) {
4250 ALOGW("Couldn't set SCHED_OTHER on display off: %s\n", strerror(errno));
Tim Murrayf9d4e442016-08-02 15:43:59 -07004251 }
Peiyong Lin65248e02020-04-18 21:15:07 -07004252 if (display->isPrimary() && currentMode != hal::PowerMode::DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004253 mScheduler->disableHardwareVsync(true);
4254 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004255 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004256
Ady Abraham27c70212019-06-11 10:52:26 -07004257 // Make sure HWVsync is disabled before turning off the display
Marin Shalamanovc75b0772020-06-12 22:29:11 +02004258 getHwComposer().setVsyncEnabled(*displayId, hal::Vsync::DISABLE);
Ady Abraham27c70212019-06-11 10:52:26 -07004259
Dominik Laskowski075d3172018-05-24 15:50:06 -07004260 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004261 mVisibleRegionsDirty = true;
4262 // from this point on, SF will stop drawing on this display
Peiyong Lin65248e02020-04-18 21:15:07 -07004263 } else if (mode == hal::PowerMode::DOZE || mode == hal::PowerMode::ON) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004264 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004265 getHwComposer().setPowerMode(*displayId, mode);
Peiyong Lin65248e02020-04-18 21:15:07 -07004266 if (display->isPrimary() && currentMode == hal::PowerMode::DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004267 mScheduler->onScreenAcquired(mAppConnectionHandle);
4268 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004269 }
Peiyong Lin65248e02020-04-18 21:15:07 -07004270 } else if (mode == hal::PowerMode::DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004271 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004272 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004273 mScheduler->disableHardwareVsync(true);
4274 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004275 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004276 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004277 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004278 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004279 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004280 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004281
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004282 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004283 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004284 mRefreshRateStats->setPowerMode(mode);
Peiyong Lin65248e02020-04-18 21:15:07 -07004285 mScheduler->setDisplayPowerState(mode == hal::PowerMode::ON);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004286 }
4287
Dominik Laskowski34157762018-10-31 13:07:19 -07004288 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004289}
4290
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004291void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07004292 schedule([=]() MAIN_THREAD {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07004293 const auto display = getDisplayDeviceLocked(displayToken);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004294 if (!display) {
4295 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4296 displayToken.get());
4297 } else if (display->isVirtual()) {
4298 ALOGW("Attempt to set power mode %d for virtual display", mode);
4299 } else {
Peiyong Lin65248e02020-04-18 21:15:07 -07004300 setPowerModeInternal(display, static_cast<hal::PowerMode>(mode));
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004301 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07004302 }).wait();
Mathias Agopianb60314a2012-04-10 22:09:54 -07004303}
4304
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07004305status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args, bool asProto) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004306 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004307
Mathias Agopianbd115332013-04-18 16:41:04 -07004308 IPCThreadState* ipc = IPCThreadState::self();
4309 const int pid = ipc->getCallingPid();
4310 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004311
Mathias Agopianbd115332013-04-18 16:41:04 -07004312 if ((uid != AID_SHELL) &&
4313 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004314 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4315 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004316 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004317 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004318 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski98041832019-08-01 18:35:59 -07004319 {"--dispsync"s,
4320 dumper([this](std::string& s) { mScheduler->getPrimaryDispSync().dump(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004321 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004322 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4323 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4324 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4325 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4326 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4327 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004328 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004329 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4330 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004331
Dominik Laskowskic2867142019-01-21 11:33:38 -08004332 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004333
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07004334 bool dumpLayers = true;
4335 {
4336 TimedLock lock(mStateLock, s2ns(1), __FUNCTION__);
4337 if (!lock.locked()) {
4338 StringAppendF(&result, "Dumping without lock after timeout: %s (%d)\n",
4339 strerror(-lock.status), lock.status);
4340 }
4341
4342 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4343 (it->second)(args, asProto, result);
4344 dumpLayers = false;
4345 } else if (!asProto) {
4346 dumpAllLocked(args, result);
4347 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004348 }
4349
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07004350 if (dumpLayers) {
Dominik Laskowski46470112019-08-02 13:13:11 -07004351 const LayersProto layersProto = dumpProtoFromMainThread();
4352 if (asProto) {
4353 result.append(layersProto.SerializeAsString());
4354 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004355 // Dump info that we need to access from the main thread
Dominik Laskowski46470112019-08-02 13:13:11 -07004356 const auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4357 result.append(LayerProtoParser::layerTreeToString(layerTree));
4358 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07004359 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07004360 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004361 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004362 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004363 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004364 return NO_ERROR;
4365}
4366
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004367status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4368 if (asProto && mTracing.isEnabled()) {
4369 mTracing.writeToFileAsync();
4370 }
4371
4372 return doDump(fd, DumpArgs(), asProto);
4373}
4374
Dominik Laskowskic2867142019-01-21 11:33:38 -08004375void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004376 mCurrentState.traverseInZOrder(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004377 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getDebugName()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004378}
4379
Dominik Laskowskic2867142019-01-21 11:33:38 -08004380void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004381 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004382
Dominik Laskowskic2867142019-01-21 11:33:38 -08004383 if (args.size() > 1) {
4384 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004385 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004386 if (layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004387 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004388 }
Robert Carr2047fae2016-11-28 14:09:09 -08004389 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004390 } else {
4391 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004392 }
4393}
4394
Dominik Laskowskic2867142019-01-21 11:33:38 -08004395void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004396 const bool clearAll = args.size() < 2;
4397 const auto name = clearAll ? String8() : String8(args[1]);
4398
Edgar Arriaga844fa672020-01-16 14:21:42 -08004399 mCurrentState.traverse([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004400 if (clearAll || layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004401 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004402 }
Robert Carr2047fae2016-11-28 14:09:09 -08004403 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004404
Svetoslavd85084b2014-03-20 10:28:31 -07004405 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004406}
4407
Dominik Laskowskic2867142019-01-21 11:33:38 -08004408void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4409 mTimeStats->parseArgs(asProto, args, result);
4410}
4411
Jamie Gennis6547ff42013-07-16 20:12:42 -07004412// This should only be called from the main thread. Otherwise it would need
4413// the lock and should use mCurrentState rather than mDrawingState.
4414void SurfaceFlinger::logFrameStats() {
Edgar Arriaga844fa672020-01-16 14:21:42 -08004415 mDrawingState.traverse([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004416 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004417 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004418
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004419 mAnimFrameTracker.logAndResetStats("<win-anim>");
Jamie Gennis6547ff42013-07-16 20:12:42 -07004420}
4421
Yiwei Zhang5434a782018-12-05 18:06:32 -08004422void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004423 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004424
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004425 if (isLayerTripleBufferingDisabled())
4426 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004427
Yiwei Zhang5434a782018-12-05 18:06:32 -08004428 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4429 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4430 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4431 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4432 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4433 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004434 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004435}
4436
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004437void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07004438 mScheduler->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004439
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004440 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004441 result.append("\n");
4442
Ady Abraham9e16a482019-12-03 17:19:41 -08004443 mPhaseConfiguration->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004444 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07004445 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004446 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004447
Steven Thomasd4071902020-03-24 16:02:53 -07004448 scheduler::RefreshRateConfigs::Policy policy = mRefreshRateConfigs->getDisplayManagerPolicy();
Ana Krulec234bb162019-11-10 22:55:55 +01004449 StringAppendF(&result,
Ady Abraham07e54702020-04-16 15:05:37 -07004450 "DesiredDisplayConfigSpecs (DisplayManager): default config ID: %d"
Steven Thomasf734df42020-04-13 21:09:28 -07004451 ", primary range: [%.2f %.2f], app request range: [%.2f %.2f]\n\n",
4452 policy.defaultConfig.value(), policy.primaryRange.min, policy.primaryRange.max,
4453 policy.appRequestRange.min, policy.appRequestRange.max);
Ady Abraham42b3beb2019-07-09 18:09:52 -07004454 StringAppendF(&result, "(config override by backdoor: %s)\n\n",
4455 mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
Ady Abraham07e54702020-04-16 15:05:37 -07004456 scheduler::RefreshRateConfigs::Policy currentPolicy = mRefreshRateConfigs->getCurrentPolicy();
4457 if (currentPolicy != policy) {
4458 StringAppendF(&result,
4459 "DesiredDisplayConfigSpecs (Override): default config ID: %d"
Steven Thomasf734df42020-04-13 21:09:28 -07004460 ", primary range: [%.2f %.2f], app request range: [%.2f %.2f]\n\n",
4461 currentPolicy.defaultConfig.value(), currentPolicy.primaryRange.min,
4462 currentPolicy.primaryRange.max, currentPolicy.appRequestRange.min,
4463 currentPolicy.appRequestRange.max);
Ady Abraham07e54702020-04-16 15:05:37 -07004464 }
Dominik Laskowski98041832019-08-01 18:35:59 -07004465
Ana Krulecc2870422019-01-29 19:00:58 -08004466 mScheduler->dump(mAppConnectionHandle, result);
Ady Abraham75398722020-04-07 14:08:45 -07004467 mScheduler->getPrimaryDispSync().dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004468}
4469
Yiwei Zhang5434a782018-12-05 18:06:32 -08004470void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4471 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004472 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4473 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004474 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004475 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004476 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004477 }
David Sodman4a36e932017-11-07 14:29:47 -08004478 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004479 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004480 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004481 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4482 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004483}
4484
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004485void SurfaceFlinger::recordBufferingStats(const std::string& layerName,
4486 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004487 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4488 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004489 for (const auto& segment : history) {
4490 if (!segment.usedThirdBuffer) {
4491 stats.twoBufferTime += segment.totalTime;
4492 }
4493 if (segment.occupancyAverage < 1.0f) {
4494 stats.doubleBufferedTime += segment.totalTime;
4495 } else if (segment.occupancyAverage < 2.0f) {
4496 stats.tripleBufferedTime += segment.totalTime;
4497 }
4498 ++stats.numSegments;
4499 stats.totalTime += segment.totalTime;
4500 }
4501}
4502
Yiwei Zhang5434a782018-12-05 18:06:32 -08004503void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4504 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004505
4506 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4507 const size_t count = currentLayers.size();
4508 for (size_t i=0 ; i<count ; i++) {
4509 currentLayers[i]->dumpFrameEvents(result);
4510 }
4511}
4512
Yiwei Zhang5434a782018-12-05 18:06:32 -08004513void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004514 result.append("Buffering stats:\n");
4515 result.append(" [Layer name] <Active time> <Two buffer> "
4516 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004517 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004518 typedef std::tuple<std::string, float, float, float> BufferTuple;
4519 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004520 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004521 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004522 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004523 if (stats.numSegments == 0) {
4524 continue;
4525 }
4526 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4527 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4528 stats.totalTime;
4529 float doubleBufferRatio = static_cast<float>(
4530 stats.doubleBufferedTime) / stats.totalTime;
4531 float tripleBufferRatio = static_cast<float>(
4532 stats.tripleBufferedTime) / stats.totalTime;
4533 sorted.insert({activeTime, {name, twoBufferRatio,
4534 doubleBufferRatio, tripleBufferRatio}});
4535 }
4536 for (const auto& sortedPair : sorted) {
4537 float activeTime = sortedPair.first;
4538 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004539 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4540 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004541 }
4542 result.append("\n");
4543}
4544
Yiwei Zhang5434a782018-12-05 18:06:32 -08004545void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004546 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004547 const auto displayId = display->getId();
4548 if (!displayId) {
4549 continue;
4550 }
4551 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004552 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004553 continue;
4554 }
4555
Yiwei Zhang5434a782018-12-05 18:06:32 -08004556 StringAppendF(&result,
4557 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4558 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004559 uint8_t port;
4560 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004561 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004562 result.append("no identification data\n");
4563 continue;
4564 }
4565
4566 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004567 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004568 continue;
4569 }
4570
4571 const auto edid = parseEdid(data);
4572 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004573 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004574 continue;
4575 }
4576
Yiwei Zhang5434a782018-12-05 18:06:32 -08004577 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004578 result.append(edid->displayName.data(), edid->displayName.length());
4579 result.append("\"\n");
4580 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004581}
4582
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004583void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
4584 std::string& result) const {
Peiyong Line9d809e2020-04-14 13:10:48 -07004585 hal::HWDisplayId hwcDisplayId;
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004586 uint8_t port;
4587 DisplayIdentificationData data;
4588
4589 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
4590 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
4591 result.append(reinterpret_cast<const char*>(data.data()), data.size());
4592 }
4593}
4594
Yiwei Zhang5434a782018-12-05 18:06:32 -08004595void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004596 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004597 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4598 StringAppendF(&result, "DisplayColorSetting: %s\n",
4599 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004600
4601 // TODO: print out if wide-color mode is active or not
4602
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004603 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004604 const auto displayId = display->getId();
4605 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004606 continue;
4607 }
4608
Yiwei Zhang5434a782018-12-05 18:06:32 -08004609 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004610 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004611 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004612 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004613 }
4614
Lloyd Pique32cbe282018-10-19 13:09:22 -07004615 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004616 StringAppendF(&result, " Current color mode: %s (%d)\n",
4617 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004618 }
4619 result.append("\n");
4620}
4621
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07004622LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
4623 // If context is SurfaceTracing thread, mTracingLock blocks display transactions on main thread.
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07004624 const auto display = ON_MAIN_THREAD(getDefaultDisplayDeviceLocked());
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07004625
chaviw1d044282017-09-27 12:19:28 -07004626 LayersProto layersProto;
chaviw08f3cb22020-01-13 13:17:21 -08004627 for (const sp<Layer>& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskib7251f42020-04-20 17:42:59 -07004628 layer->writeToProto(layersProto, traceFlags, display.get());
chaviw08f3cb22020-01-13 13:17:21 -08004629 }
Alec Mouri6b9e9912020-01-21 10:50:24 -08004630
chaviw1d044282017-09-27 12:19:28 -07004631 return layersProto;
4632}
4633
Alec Mouri6b9e9912020-01-21 10:50:24 -08004634void SurfaceFlinger::dumpHwc(std::string& result) const {
4635 getHwComposer().dump(result);
4636}
4637
Vishnu Nair0f085c62019-08-30 08:49:12 -07004638void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
4639 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
4640 // it.
4641 LayerProto* rootProto = layersProto.add_layers();
4642 const int32_t offscreenRootLayerId = INT32_MAX - 2;
4643 rootProto->set_id(offscreenRootLayerId);
4644 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07004645 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004646
4647 for (Layer* offscreenLayer : mOffscreenLayers) {
4648 // Add layer as child of the fake root
4649 rootProto->add_children(offscreenLayer->sequence);
4650
4651 // Add layer
Alec Mouri6b9e9912020-01-21 10:50:24 -08004652 LayerProto* layerProto =
4653 offscreenLayer->writeToProto(layersProto, traceFlags, nullptr /*device*/);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004654 layerProto->set_parent(offscreenRootLayerId);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004655 }
4656}
4657
Vishnu Nair8406fd72019-07-30 11:29:31 -07004658LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07004659 return schedule([=] { return dumpDrawingStateProto(traceFlags); }).get();
Vishnu Nair8406fd72019-07-30 11:29:31 -07004660}
4661
Vishnu Nair0f085c62019-08-30 08:49:12 -07004662void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
4663 result.append("Offscreen Layers:\n");
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07004664 result.append(schedule([this] {
4665 std::string result;
4666 for (Layer* offscreenLayer : mOffscreenLayers) {
4667 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
4668 [&](Layer* layer) {
4669 layer->dumpCallingUidPid(result);
4670 });
4671 }
4672 return result;
4673 }).get());
Vishnu Nair0f085c62019-08-30 08:49:12 -07004674}
4675
Dominik Laskowskic2867142019-01-21 11:33:38 -08004676void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4677 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004678 Colorizer colorizer(colorize);
4679
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004680 // figure out if we're stuck somewhere
4681 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004682 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004683 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4684
4685 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004686 * Dump library configuration.
4687 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004688
4689 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004690 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004691 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004692 appendSfConfigString(result);
4693 appendUiConfigString(result);
4694 appendGuiConfigString(result);
4695 result.append("\n");
4696
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004697 result.append("\nDisplay identification data:\n");
4698 dumpDisplayIdentificationData(result);
4699
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004700 result.append("\nWide-Color information:\n");
4701 dumpWideColorInfo(result);
4702
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004703 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004704 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004705 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004706 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004707 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004708
Andy McFadden41d67d72014-04-25 16:58:34 -07004709 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004710 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004711 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004712 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004713 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004714
Dan Stozab90cf072015-03-05 11:05:59 -08004715 dumpStaticScreenStats(result);
4716 result.append("\n");
4717
Alec Mouri40189b02019-03-05 15:07:54 -08004718 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4719 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4720 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004721
Dan Stozae77c7662016-05-13 11:37:28 -07004722 dumpBufferingStats(result);
4723
Andy McFadden4803b742012-09-24 19:07:20 -07004724 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004725 * Dump the visible layer list
4726 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004727 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07004728 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Yiwei Zhang5434a782018-12-05 18:06:32 -08004729 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4730 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004731 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004732
Chia-I Wu2f884132018-09-13 15:17:58 -07004733 {
Lloyd Pique207def92019-02-28 16:09:52 -08004734 StringAppendF(&result, "Composition layers\n");
4735 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08004736 auto* compositionState = layer->getCompositionState();
4737 if (!compositionState) return;
4738
4739 android::base::StringAppendF(&result, "* Layer %p (%s)\n", layer,
4740 layer->getDebugName() ? layer->getDebugName()
4741 : "<unknown>");
4742 compositionState->dump(result);
Lloyd Pique207def92019-02-28 16:09:52 -08004743 });
4744 }
4745
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004746 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004747 * Dump Display state
4748 */
4749
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004750 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004751 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004752 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004753 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004754 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004755 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004756 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004757
4758 /*
Lloyd Piquec3cb7292019-05-17 15:25:14 -07004759 * Dump CompositionEngine state
4760 */
4761
4762 mCompositionEngine->dump(result);
4763
4764 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004765 * Dump SurfaceFlinger global state
4766 */
4767
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004768 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004769 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004770 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004771
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004772 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004773
Ady Abrahama3b08ef2019-07-15 18:43:10 -07004774 DebugEGLImageTracker::getInstance()->dump(result);
4775
Dominik Laskowski075d3172018-05-24 15:50:06 -07004776 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004777 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4778 "undefinedRegion");
Dominik Laskowski718f9602019-11-09 20:01:35 -08004779 StringAppendF(&result, " orientation=%s, isPoweredOn=%d\n",
4780 toCString(display->getOrientation()), display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004781 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004782 StringAppendF(&result,
4783 " transaction-flags : %08x\n"
4784 " gpu_to_cpu_unsupported : %d\n",
4785 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004786
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004787 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004788 displayId && getHwComposer().isConnected(*displayId)) {
4789 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004790 StringAppendF(&result,
4791 " refresh-rate : %f fps\n"
4792 " x-dpi : %f\n"
4793 " y-dpi : %f\n",
Ady Abraham3a77a7b2019-12-02 18:46:59 -08004794 1e9 / getHwComposer().getDisplayVsyncPeriod(*displayId),
4795 activeConfig->getDpiX(), activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004796 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004797
Yiwei Zhang5434a782018-12-05 18:06:32 -08004798 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004799
Dan Stozae22aec72016-08-01 13:20:59 -07004800 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004801 * Tracing state
4802 */
4803 mTracing.dump(result);
4804 result.append("\n");
4805
4806 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004807 * HWC layer minidump
4808 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004809 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004810 const auto displayId = display->getId();
4811 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004812 continue;
4813 }
4814
Yiwei Zhang5434a782018-12-05 18:06:32 -08004815 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004816 Layer::miniDumpHeader(result);
Dominik Laskowskib7251f42020-04-20 17:42:59 -07004817
4818 const DisplayDevice& ref = *display;
4819 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, ref); });
Dan Stozae22aec72016-08-01 13:20:59 -07004820 result.append("\n");
4821 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004822
4823 /*
4824 * Dump HWComposer state
4825 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004826 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004827 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004828 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004829 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004830 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004831 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004832
4833 /*
4834 * Dump gralloc state
4835 */
4836 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4837 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004838
4839 /*
4840 * Dump VrFlinger state if in use.
4841 */
4842 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4843 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004844 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004845 result.append("\n");
4846 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004847
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07004848 result.append(mTimeStats->miniDump());
4849 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004850}
4851
Chia-I Wu28f320b2018-05-03 11:02:56 -07004852void SurfaceFlinger::updateColorMatrixLocked() {
4853 mat4 colorMatrix;
4854 if (mGlobalSaturationFactor != 1.0f) {
4855 // Rec.709 luma coefficients
4856 float3 luminance{0.213f, 0.715f, 0.072f};
4857 luminance *= 1.0f - mGlobalSaturationFactor;
4858 mat4 saturationMatrix = mat4(
4859 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4860 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4861 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4862 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4863 );
4864 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4865 } else {
4866 colorMatrix = mClientColorMatrix * mDaltonizer();
4867 }
4868
4869 if (mCurrentState.colorMatrix != colorMatrix) {
4870 mCurrentState.colorMatrix = colorMatrix;
4871 mCurrentState.colorMatrixChanged = true;
4872 setTransactionFlags(eTransactionNeeded);
4873 }
4874}
4875
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004876status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004877#pragma clang diagnostic push
4878#pragma clang diagnostic error "-Wswitch-enum"
4879 switch (static_cast<ISurfaceComposerTag>(code)) {
4880 // These methods should at minimum make sure that the client requested
4881 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004882 case BOOT_FINISHED:
4883 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004884 case CREATE_DISPLAY:
4885 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004886 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004887 case GET_ANIMATION_FRAME_STATS:
4888 case GET_HDR_CAPABILITIES:
Ana Krulec0782b882019-10-15 17:34:54 -07004889 case SET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec234bb162019-11-10 22:55:55 +01004890 case GET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004891 case SET_ACTIVE_COLOR_MODE:
Galia Peycheva5492cb52019-10-30 14:13:16 +01004892 case GET_AUTO_LOW_LATENCY_MODE_SUPPORT:
4893 case SET_AUTO_LOW_LATENCY_MODE:
4894 case GET_GAME_CONTENT_TYPE_SUPPORT:
4895 case SET_GAME_CONTENT_TYPE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004896 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004897 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004898 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004899 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Ady Abraham8532d012019-05-08 14:50:56 -07004900 case GET_DISPLAYED_CONTENT_SAMPLE:
Vishnu Nairb13bb952019-11-15 10:24:08 -08004901 case NOTIFY_POWER_HINT:
Steven Thomasd4071902020-03-24 16:02:53 -07004902 case SET_GLOBAL_SHADOW_SETTINGS:
4903 case ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN: {
4904 // ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN is used by CTS tests, which acquire the
4905 // necessary permission dynamically. Don't use the permission cache for this check.
4906 bool usePermissionCache = code != ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN;
4907 if (!callingThreadHasUnscopedSurfaceFlingerAccess(usePermissionCache)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004908 IPCThreadState* ipc = IPCThreadState::self();
4909 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4910 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004911 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004912 }
Robert Carr1db73f62016-12-21 12:58:51 -08004913 return OK;
4914 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004915 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004916 IPCThreadState* ipc = IPCThreadState::self();
4917 const int pid = ipc->getCallingPid();
4918 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004919 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4920 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004921 return PERMISSION_DENIED;
4922 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004923 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004924 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004925 // Used by apps to hook Choreographer to SurfaceFlinger.
4926 case CREATE_DISPLAY_EVENT_CONNECTION:
4927 // The following calls are currently used by clients that do not
4928 // request necessary permissions. However, they do not expose any secret
4929 // information, so it is OK to pass them.
4930 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07004931 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004932 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004933 case GET_PHYSICAL_DISPLAY_IDS:
4934 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004935 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004936 case GET_DISPLAY_NATIVE_PRIMARIES:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004937 case GET_DISPLAY_INFO:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004938 case GET_DISPLAY_CONFIGS:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004939 case GET_DISPLAY_STATE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004940 case GET_DISPLAY_STATS:
4941 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4942 // Calling setTransactionState is safe, because you need to have been
4943 // granted a reference to Client* and Handle* to do anything with it.
4944 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004945 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004946 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004947 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004948 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00004949 case IS_WIDE_COLOR_DISPLAY:
Steven Thomas62a4cf82020-01-31 12:04:03 -08004950 // setFrameRate() is deliberately available for apps to call without any
4951 // special permissions.
4952 case SET_FRAME_RATE:
Dan Gittik57e63c52019-01-18 16:37:54 +00004953 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
4954 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004955 return OK;
4956 }
Chong Zhangd1690d12019-10-04 17:47:13 +00004957 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08004958 case CAPTURE_SCREEN:
4959 case ADD_REGION_SAMPLING_LISTENER:
4960 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004961 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004962 IPCThreadState* ipc = IPCThreadState::self();
4963 const int pid = ipc->getCallingPid();
4964 const int uid = ipc->getCallingUid();
4965 if ((uid != AID_GRAPHICS) &&
4966 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4967 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4968 return PERMISSION_DENIED;
4969 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004970 return OK;
4971 }
chaviw93df2ea2019-04-30 16:45:12 -07004972 case CAPTURE_SCREEN_BY_ID: {
4973 IPCThreadState* ipc = IPCThreadState::self();
4974 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07004975 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07004976 return OK;
4977 }
4978 return PERMISSION_DENIED;
4979 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004980 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004981
4982 // These codes are used for the IBinder protocol to either interrogate the recipient
4983 // side of the transaction for its canonical interface descriptor or to dump its state.
4984 // We let them pass by default.
4985 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4986 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4987 code == IBinder::SYSPROPS_TRANSACTION) {
4988 return OK;
4989 }
Ady Abraham07e54702020-04-16 15:05:37 -07004990 // Numbers from 1000 to 1036 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004991 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham07e54702020-04-16 15:05:37 -07004992 if (code >= 1000 && code <= 1036) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004993 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4994 return OK;
4995 }
4996 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4997 return PERMISSION_DENIED;
4998#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004999}
5000
Ana Krulec13be8ad2018-08-21 02:43:56 +00005001status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5002 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005003 status_t credentialCheck = CheckTransactCodeCredentials(code);
5004 if (credentialCheck != OK) {
5005 return credentialCheck;
5006 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005007
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005008 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5009 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005010 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005011 IPCThreadState* ipc = IPCThreadState::self();
5012 const int uid = ipc->getCallingUid();
5013 if (CC_UNLIKELY(uid != AID_SYSTEM
5014 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005015 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005016 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005017 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005018 return PERMISSION_DENIED;
5019 }
5020 int n;
5021 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07005022 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07005023 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005024 return NO_ERROR;
5025 case 1002: // SHOW_UPDATES
5026 n = data.readInt32();
5027 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005028 invalidateHwcGeometry();
5029 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005030 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005031 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005032 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005033 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005034 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005035 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005036 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005037 setTransactionFlags(
5038 eTransactionNeeded|
5039 eDisplayTransactionNeeded|
5040 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005041 return NO_ERROR;
5042 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005043 case 1006:{ // send empty update
5044 signalRefresh();
5045 return NO_ERROR;
5046 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005047 case 1008: // toggle use of hw composer
5048 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005049 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07005050 invalidateHwcGeometry();
5051 repaintEverything();
5052 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005053 case 1009: // toggle use of transform hint
5054 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005055 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07005056 invalidateHwcGeometry();
5057 repaintEverything();
5058 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005059 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005060 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005061 reply->writeInt32(0);
5062 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005063 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005064 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005065 return NO_ERROR;
5066 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005067 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005068 if (!display) {
5069 return NAME_NOT_FOUND;
5070 }
5071
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005072 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005073 return NO_ERROR;
5074 }
5075 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005076 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005077 // daltonize
5078 n = data.readInt32();
5079 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005080 case 1:
5081 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5082 break;
5083 case 2:
5084 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5085 break;
5086 case 3:
5087 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5088 break;
5089 default:
5090 mDaltonizer.setType(ColorBlindnessType::None);
5091 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005092 }
5093 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005094 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005095 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005096 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005097 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005098
5099 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005100 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005101 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005102 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005103 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005104 // apply a color matrix
5105 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005106 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005107 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005108 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005109 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005110 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005111 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005112 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005113 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005114 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005115 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005116
5117 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5118 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005119 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005120 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5121 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5122 }
5123
Chia-I Wu28f320b2018-05-03 11:02:56 -07005124 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005125 return NO_ERROR;
5126 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07005127 case 1016: { // Unused.
5128 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005129 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005130 case 1017: {
5131 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005132 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07005133 return NO_ERROR;
5134 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005135 case 1018: { // Modify Choreographer's phase offset
5136 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005137 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005138 return NO_ERROR;
5139 }
5140 case 1019: { // Modify SurfaceFlinger's phase offset
5141 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005142 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005143 return NO_ERROR;
5144 }
Irvel468051e2016-06-13 16:44:44 -07005145 case 1020: { // Layer updates interceptor
5146 n = data.readInt32();
5147 if (n) {
5148 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005149 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005150 }
5151 else{
5152 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005153 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005154 }
5155 return NO_ERROR;
5156 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005157 case 1021: { // Disable HWC virtual displays
5158 n = data.readInt32();
5159 mUseHwcVirtualDisplays = !n;
5160 return NO_ERROR;
5161 }
Romain Guy0147a172017-06-01 13:53:56 -07005162 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005163 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005164 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005165
Chia-I Wu28f320b2018-05-03 11:02:56 -07005166 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005167 return NO_ERROR;
5168 }
Romain Guy54f154a2017-10-24 21:40:32 +01005169 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005170 int32_t colorMode;
5171
Chia-I Wu0d711262018-05-21 15:19:35 -07005172 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005173 if (data.readInt32(&colorMode) == NO_ERROR) {
5174 mForceColorMode = static_cast<ColorMode>(colorMode);
5175 }
Romain Guy54f154a2017-10-24 21:40:32 +01005176 invalidateHwcGeometry();
5177 repaintEverything();
5178 return NO_ERROR;
5179 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005180 // Deprecate, use 1030 to check whether the device is color managed.
5181 case 1024: {
5182 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005183 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005184 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005185 n = data.readInt32();
5186 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005187 ALOGD("LayerTracing enabled");
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07005188 mTracingEnabledChanged = mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01005189 reply->writeInt32(NO_ERROR);
5190 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005191 ALOGD("LayerTracing disabled");
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07005192 mTracingEnabledChanged = mTracing.disable();
5193 if (mTracingEnabledChanged) {
Nataniel Borges2b796da2019-02-15 13:32:18 -08005194 reply->writeInt32(mTracing.writeToFile());
5195 } else {
5196 reply->writeInt32(NO_ERROR);
5197 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01005198 }
5199 return NO_ERROR;
5200 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005201 case 1026: { // Get layer tracing status
5202 reply->writeBool(mTracing.isEnabled());
5203 return NO_ERROR;
5204 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005205 // Is a DisplayColorSetting supported?
5206 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005207 const auto display = getDefaultDisplayDevice();
5208 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005209 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005210 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005211
5212 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5213 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005214 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07005215 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005216 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005217 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07005218 reply->writeBool(true);
5219 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005220 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005221 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005222 break;
5223 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005224 reply->writeBool(
5225 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005226 break;
5227 }
5228 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005229 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005230 // Is VrFlinger active?
5231 case 1028: {
5232 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005233 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005234 return NO_ERROR;
5235 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005236 // Set buffer size for SF tracing (value in KB)
5237 case 1029: {
5238 n = data.readInt32();
5239 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5240 ALOGW("Invalid buffer size: %d KB", n);
5241 reply->writeInt32(BAD_VALUE);
5242 return BAD_VALUE;
5243 }
5244
5245 ALOGD("Updating trace buffer to %d KB", n);
5246 mTracing.setBufferSize(n * 1024);
5247 reply->writeInt32(NO_ERROR);
5248 return NO_ERROR;
5249 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005250 // Is device color managed?
5251 case 1030: {
5252 reply->writeBool(useColorManagement);
5253 return NO_ERROR;
5254 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005255 // Override default composition data space
5256 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5257 // && adb shell stop zygote && adb shell start zygote
5258 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5259 // adb shell stop zygote && adb shell start zygote
5260 case 1031: {
5261 Mutex::Autolock _l(mStateLock);
5262 n = data.readInt32();
5263 if (n) {
5264 n = data.readInt32();
5265 if (n) {
5266 Dataspace dataspace = static_cast<Dataspace>(n);
5267 if (!validateCompositionDataspace(dataspace)) {
5268 return BAD_VALUE;
5269 }
5270 mDefaultCompositionDataspace = dataspace;
5271 }
5272 n = data.readInt32();
5273 if (n) {
5274 Dataspace dataspace = static_cast<Dataspace>(n);
5275 if (!validateCompositionDataspace(dataspace)) {
5276 return BAD_VALUE;
5277 }
5278 mWideColorGamutCompositionDataspace = dataspace;
5279 }
5280 } else {
5281 // restore composition data space.
5282 mDefaultCompositionDataspace = defaultCompositionDataspace;
5283 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5284 }
5285 return NO_ERROR;
5286 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005287 // Set trace flags
5288 case 1033: {
5289 n = data.readUint32();
5290 ALOGD("Updating trace flags to 0x%x", n);
5291 mTracing.setTraceFlags(n);
5292 reply->writeInt32(NO_ERROR);
5293 return NO_ERROR;
5294 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005295 case 1034: {
Dominik Laskowski20134642020-04-20 22:36:44 -07005296 switch (n = data.readInt32()) {
5297 case 0:
5298 case 1:
5299 enableRefreshRateOverlay(static_cast<bool>(n));
5300 break;
5301 default: {
5302 Mutex::Autolock lock(mStateLock);
5303 reply->writeBool(mRefreshRateOverlay != nullptr);
5304 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005305 }
5306 return NO_ERROR;
5307 }
Ady Abraham34392f72019-04-10 11:29:27 -07005308 case 1035: {
5309 n = data.readInt32();
5310 mDebugDisplayConfigSetByBackdoor = false;
5311 if (n >= 0) {
5312 const auto displayToken = getInternalDisplayToken();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005313 status_t result = setActiveConfig(displayToken, n);
Ady Abraham34392f72019-04-10 11:29:27 -07005314 if (result != NO_ERROR) {
5315 return result;
5316 }
5317 mDebugDisplayConfigSetByBackdoor = true;
5318 }
5319 return NO_ERROR;
5320 }
Ady Abraham07e54702020-04-16 15:05:37 -07005321 case 1036: {
5322 if (data.readInt32() > 0) {
5323 status_t result =
5324 acquireFrameRateFlexibilityToken(&mDebugFrameRateFlexibilityToken);
5325 if (result != NO_ERROR) {
5326 return result;
5327 }
5328 } else {
5329 mDebugFrameRateFlexibilityToken = nullptr;
5330 }
5331 return NO_ERROR;
5332 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005333 }
5334 }
5335 return err;
5336}
5337
Steven Thomas6d8110b2017-08-31 18:24:21 -07005338void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005339 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005340 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005341}
5342
Ana Krulec7d1d6832018-12-27 11:10:09 -08005343void SurfaceFlinger::repaintEverythingForHWC() {
5344 mRepaintEverything = true;
Dan Stoza030fbc12020-02-19 15:32:01 -08005345 mPowerAdvisor.notifyDisplayUpdateImminent();
Ady Abraham8532d012019-05-08 14:50:56 -07005346 mEventQueue->invalidate();
Ana Krulec7d1d6832018-12-27 11:10:09 -08005347}
5348
Ady Abrahama09852a2020-02-20 14:23:42 -08005349void SurfaceFlinger::kernelTimerChanged(bool expired) {
5350 static bool updateOverlay =
5351 property_get_bool("debug.sf.kernel_idle_timer_update_overlay", true);
Dominik Laskowski20134642020-04-20 22:36:44 -07005352 if (!updateOverlay) return;
5353 if (Mutex::Autolock lock(mStateLock); !mRefreshRateOverlay) return;
Ady Abrahama09852a2020-02-20 14:23:42 -08005354
5355 // Update the overlay on the main thread to avoid race conditions with
5356 // mRefreshRateConfigs->getCurrentRefreshRate()
Dominik Laskowski20134642020-04-20 22:36:44 -07005357 static_cast<void>(schedule([=] {
5358 const auto desiredActiveConfig = getDesiredActiveConfig();
5359 const auto& current = desiredActiveConfig
5360 ? mRefreshRateConfigs->getRefreshRateFromConfigId(desiredActiveConfig->configId)
5361 : mRefreshRateConfigs->getCurrentRefreshRate();
5362 const auto& min = mRefreshRateConfigs->getMinRefreshRate();
5363
5364 if (current != min) {
Ana Krulecb9afd792020-06-11 13:16:15 -07005365 const bool timerExpired = mKernelIdleTimerEnabled && expired;
Ady Abrahama09852a2020-02-20 14:23:42 -08005366
Dominik Laskowski20134642020-04-20 22:36:44 -07005367 if (Mutex::Autolock lock(mStateLock); mRefreshRateOverlay) {
Ady Abrahama09852a2020-02-20 14:23:42 -08005368 mRefreshRateOverlay->changeRefreshRate(timerExpired ? min : current);
Ady Abrahama09852a2020-02-20 14:23:42 -08005369 }
Dominik Laskowski20134642020-04-20 22:36:44 -07005370 mEventQueue->invalidate();
Ady Abrahama09852a2020-02-20 14:23:42 -08005371 }
5372 }));
5373}
5374
Ana Krulecb9afd792020-06-11 13:16:15 -07005375void SurfaceFlinger::toggleKernelIdleTimer() {
5376 using KernelIdleTimerAction = scheduler::RefreshRateConfigs::KernelIdleTimerAction;
5377
5378 // If the support for kernel idle timer is disabled in SF code, don't do anything.
5379 if (!mSupportKernelIdleTimer) {
5380 return;
5381 }
5382 const KernelIdleTimerAction action = mRefreshRateConfigs->getIdleTimerAction();
5383
5384 switch (action) {
5385 case KernelIdleTimerAction::TurnOff:
5386 if (mKernelIdleTimerEnabled) {
5387 ATRACE_INT("KernelIdleTimer", 0);
5388 base::SetProperty(KERNEL_IDLE_TIMER_PROP, "false");
5389 mKernelIdleTimerEnabled = false;
5390 }
5391 break;
5392 case KernelIdleTimerAction::TurnOn:
5393 if (!mKernelIdleTimerEnabled) {
5394 ATRACE_INT("KernelIdleTimer", 1);
5395 base::SetProperty(KERNEL_IDLE_TIMER_PROP, "true");
5396 mKernelIdleTimerEnabled = true;
5397 }
5398 break;
5399 case KernelIdleTimerAction::NoChange:
5400 break;
5401 }
5402}
5403
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005404// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5405class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005406public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005407 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5408 ~WindowDisconnector() {
5409 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005410 }
5411
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005412private:
5413 ANativeWindow* mWindow;
5414 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005415};
5416
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005417status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07005418 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
Dominik Laskowski718f9602019-11-09 20:01:35 -08005419 Dataspace reqDataspace, ui::PixelFormat reqPixelFormat,
5420 const Rect& sourceCrop, uint32_t reqWidth,
5421 uint32_t reqHeight, bool useIdentityTransform,
5422 ui::Rotation rotation, bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005423 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005424
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005425 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005426
Dominik Laskowski718f9602019-11-09 20:01:35 -08005427 auto renderAreaRotation = ui::Transform::toRotationFlags(rotation);
5428 if (renderAreaRotation == ui::Transform::ROT_INVALID) {
5429 ALOGE("%s: Invalid rotation: %s", __FUNCTION__, toCString(rotation));
5430 renderAreaRotation = ui::Transform::ROT_0;
5431 }
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005432
Chia-I Wu20261cb2018-08-23 12:55:44 -07005433 sp<DisplayDevice> display;
5434 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005435 Mutex::Autolock lock(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005436
Chia-I Wu20261cb2018-08-23 12:55:44 -07005437 display = getDisplayDeviceLocked(displayToken);
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005438 if (!display) return NAME_NOT_FOUND;
Chia-I Wu20261cb2018-08-23 12:55:44 -07005439
Chia-I Wucb023152018-08-28 12:57:23 -07005440 // set the requested width/height to the logical display viewport size
5441 // by default
5442 if (reqWidth == 0 || reqHeight == 0) {
5443 reqWidth = uint32_t(display->getViewport().width());
5444 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005445 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005446 }
5447
Peiyong Lin0e003c92018-09-17 11:09:51 -07005448 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08005449 renderAreaRotation, captureSecureLayers);
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005450 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5451 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005452 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005453 useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005454}
5455
chaviw93df2ea2019-04-30 16:45:12 -07005456static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
5457 switch (colorMode) {
5458 case ColorMode::DISPLAY_P3:
5459 case ColorMode::BT2100_PQ:
5460 case ColorMode::BT2100_HLG:
5461 case ColorMode::DISPLAY_BT2020:
5462 return Dataspace::DISPLAY_P3;
5463 default:
5464 return Dataspace::V0_SRGB;
5465 }
5466}
5467
Martin Liu4a322352020-03-24 21:30:38 +08005468status_t SurfaceFlinger::setSchedFifo(bool enabled) {
5469 static constexpr int kFifoPriority = 2;
5470 static constexpr int kOtherPriority = 0;
5471
5472 struct sched_param param = {0};
5473 int sched_policy;
5474 if (enabled) {
5475 sched_policy = SCHED_FIFO;
5476 param.sched_priority = kFifoPriority;
5477 } else {
5478 sched_policy = SCHED_OTHER;
5479 param.sched_priority = kOtherPriority;
5480 }
5481
5482 if (sched_setscheduler(0, sched_policy, &param) != 0) {
5483 return -errno;
5484 }
5485 return NO_ERROR;
5486}
5487
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07005488sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005489 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
5490 if (displayToken) {
5491 return getDisplayDeviceLocked(displayToken);
5492 }
5493 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
5494 // may not have a displayId.
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005495 return getDisplayByLayerStack(displayOrLayerStack);
5496}
5497
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07005498sp<DisplayDevice> SurfaceFlinger::getDisplayByLayerStack(uint64_t layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005499 for (const auto& [token, display] : mDisplays) {
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005500 if (display->getLayerStack() == layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005501 return display;
5502 }
5503 }
5504 return nullptr;
5505}
5506
5507status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
5508 sp<GraphicBuffer>* outBuffer) {
5509 sp<DisplayDevice> display;
5510 uint32_t width;
5511 uint32_t height;
Dominik Laskowski718f9602019-11-09 20:01:35 -08005512 ui::Transform::RotationFlags captureOrientation;
chaviw93df2ea2019-04-30 16:45:12 -07005513 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005514 Mutex::Autolock lock(mStateLock);
chaviw93df2ea2019-04-30 16:45:12 -07005515 display = getDisplayByIdOrLayerStack(displayOrLayerStack);
5516 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005517 return NAME_NOT_FOUND;
chaviw93df2ea2019-04-30 16:45:12 -07005518 }
5519
5520 width = uint32_t(display->getViewport().width());
5521 height = uint32_t(display->getViewport().height());
5522
Dominik Laskowski718f9602019-11-09 20:01:35 -08005523 const auto orientation = display->getOrientation();
5524 captureOrientation = ui::Transform::toRotationFlags(orientation);
5525
5526 switch (captureOrientation) {
5527 case ui::Transform::ROT_90:
5528 captureOrientation = ui::Transform::ROT_270;
5529 break;
5530
5531 case ui::Transform::ROT_270:
5532 captureOrientation = ui::Transform::ROT_90;
5533 break;
5534
5535 case ui::Transform::ROT_INVALID:
5536 ALOGE("%s: Invalid orientation: %s", __FUNCTION__, toCString(orientation));
5537 captureOrientation = ui::Transform::ROT_0;
5538 break;
5539
5540 default:
5541 break;
Alec Mouri21fab752019-06-20 14:12:17 -07005542 }
chaviw93df2ea2019-04-30 16:45:12 -07005543 *outDataspace =
5544 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
5545 }
5546
5547 DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
5548 false /* captureSecureLayers */);
5549
5550 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5551 std::placeholders::_1);
5552 bool ignored = false;
5553 return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
5554 false /* useIdentityTransform */,
5555 ignored /* outCapturedSecureLayers */);
5556}
5557
Robert Carr866455f2019-04-02 16:28:26 -07005558status_t SurfaceFlinger::captureLayers(
5559 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
5560 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
5561 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
5562 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005563 ATRACE_CALL();
5564
5565 class LayerRenderArea : public RenderArea {
5566 public:
Robert Carr578038f2018-03-09 12:25:24 -08005567 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005568 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005569 bool childrenOnly, const Rect& displayViewport)
5570 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace, displayViewport),
Robert Carr578038f2018-03-09 12:25:24 -08005571 mLayer(layer),
5572 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005573 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005574 mFlinger(flinger),
5575 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005576 const ui::Transform& getTransform() const override { return mTransform; }
Alec Mouri5a6d8572020-03-23 23:56:15 -07005577 Rect getBounds() const override { return mLayer->getBufferSize(mLayer->getDrawingState()); }
Marissa Wall61c58622018-07-18 10:12:20 -07005578 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005579 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005580 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005581 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005582 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005583 }
chaviwa76b2712017-09-20 12:02:26 -07005584 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005585 bool needsFiltering() const override { return mNeedsFiltering; }
Dominik Laskowski718f9602019-11-09 20:01:35 -08005586 sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005587 Rect getSourceCrop() const override {
5588 if (mCrop.isEmpty()) {
5589 return getBounds();
5590 } else {
5591 return mCrop;
5592 }
5593 }
Robert Carr578038f2018-03-09 12:25:24 -08005594 class ReparentForDrawing {
5595 public:
5596 const sp<Layer>& oldParent;
5597 const sp<Layer>& newParent;
5598
Vishnu Nair4351ad52019-02-11 14:13:02 -08005599 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5600 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005601 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005602 // Compute and cache the bounds for the new parent layer.
Vishnu Nairc97b8db2019-10-29 18:19:35 -07005603 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform(),
5604 0.f /* shadowRadius */);
Robert Carr15eae092018-03-23 13:43:53 -07005605 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005606 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005607 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005608 };
5609
5610 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005611 const Rect sourceCrop = getSourceCrop();
5612 // no need to check rotation because there is none
5613 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5614 sourceCrop.height() != getReqHeight();
5615
Robert Carr578038f2018-03-09 12:25:24 -08005616 if (!mChildrenOnly) {
5617 mTransform = mLayer->getTransform().inverse();
5618 drawLayers();
5619 } else {
Alec Mouri5a6d8572020-03-23 23:56:15 -07005620 uint32_t w = static_cast<uint32_t>(getWidth());
5621 uint32_t h = static_cast<uint32_t>(getHeight());
chaviw32811fd2019-08-12 13:16:09 -07005622 // In the "childrenOnly" case we reparent the children to a screenshot
5623 // layer which has no properties set and which does not draw.
5624 sp<ContainerLayer> screenshotParentLayer =
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005625 mFlinger->getFactory().createContainerLayer({mFlinger, nullptr,
5626 "Screenshot Parent"s, w, h, 0,
5627 LayerMetadata()});
Robert Carr578038f2018-03-09 12:25:24 -08005628
Vishnu Nair4351ad52019-02-11 14:13:02 -08005629 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005630 drawLayers();
5631 }
5632 }
chaviwa76b2712017-09-20 12:02:26 -07005633
chaviwa76b2712017-09-20 12:02:26 -07005634 private:
chaviw7206d492017-11-10 16:16:12 -08005635 const sp<Layer> mLayer;
5636 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005637
Peiyong Linefefaac2018-08-17 12:27:51 -07005638 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005639 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005640
5641 SurfaceFlinger* mFlinger;
5642 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005643 };
5644
Robert Carrc0df3122019-04-11 13:18:21 -07005645 int reqWidth = 0;
5646 int reqHeight = 0;
5647 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005648 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005649 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005650 Rect displayViewport;
Robert Carrc0df3122019-04-11 13:18:21 -07005651 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005652 Mutex::Autolock lock(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005653
Alec Mouri9a02eda2020-04-21 17:39:34 -07005654 parent = fromHandleLocked(layerHandleBinder).promote();
Robert Carrc0df3122019-04-11 13:18:21 -07005655 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5656 ALOGE("captureLayers called with an invalid or removed parent");
5657 return NAME_NOT_FOUND;
5658 }
5659
5660 const int uid = IPCThreadState::self()->getCallingUid();
5661 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5662 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5663 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5664 return PERMISSION_DENIED;
5665 }
5666
Vishnu Nairefc42e22019-12-03 17:36:12 -08005667 Rect parentSourceBounds = parent->getCroppedBufferSize(parent->getCurrentState());
Robert Carrc0df3122019-04-11 13:18:21 -07005668 if (sourceCrop.width() <= 0) {
5669 crop.left = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005670 crop.right = parentSourceBounds.getWidth();
Robert Carrc0df3122019-04-11 13:18:21 -07005671 }
5672
5673 if (sourceCrop.height() <= 0) {
5674 crop.top = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005675 crop.bottom = parentSourceBounds.getHeight();
5676 }
5677
5678 if (crop.isEmpty() || frameScale <= 0.0f) {
5679 // Error out if the layer has no source bounds (i.e. they are boundless) and a source
5680 // crop was not specified, or an invalid frame scale was provided.
5681 return BAD_VALUE;
Robert Carrc0df3122019-04-11 13:18:21 -07005682 }
5683 reqWidth = crop.width() * frameScale;
5684 reqHeight = crop.height() * frameScale;
5685
5686 for (const auto& handle : excludeHandles) {
Alec Mouri9a02eda2020-04-21 17:39:34 -07005687 sp<Layer> excludeLayer = fromHandleLocked(handle).promote();
Robert Carrc0df3122019-04-11 13:18:21 -07005688 if (excludeLayer != nullptr) {
5689 excludeLayers.emplace(excludeLayer);
5690 } else {
5691 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5692 return NAME_NOT_FOUND;
5693 }
5694 }
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005695
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005696 const auto display = getDisplayByLayerStack(parent->getLayerStack());
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005697 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005698 return NAME_NOT_FOUND;
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005699 }
5700
5701 displayViewport = display->getViewport();
Robert Carrc0df3122019-04-11 13:18:21 -07005702 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005703
Chia-I Wu20261cb2018-08-23 12:55:44 -07005704 // really small crop or frameScale
5705 if (reqWidth <= 0) {
5706 reqWidth = 1;
5707 }
5708 if (reqHeight <= 0) {
5709 reqHeight = 1;
5710 }
5711
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005712 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly,
5713 displayViewport);
Robert Carr866455f2019-04-02 16:28:26 -07005714 auto traverseLayers = [parent, childrenOnly,
5715 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005716 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5717 if (!layer->isVisible()) {
5718 return;
Robert Carr578038f2018-03-09 12:25:24 -08005719 } else if (childrenOnly && layer == parent.get()) {
5720 return;
chaviwa76b2712017-09-20 12:02:26 -07005721 }
Robert Carr866455f2019-04-02 16:28:26 -07005722
5723 sp<Layer> p = layer;
5724 while (p != nullptr) {
5725 if (excludeLayers.count(p) != 0) {
5726 return;
5727 }
5728 p = p->getParent();
5729 }
5730
chaviwa76b2712017-09-20 12:02:26 -07005731 visitor(layer);
5732 });
5733 };
Robert Carr108b2c72019-04-02 16:32:58 -07005734
5735 bool outCapturedSecureLayers = false;
5736 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5737 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005738}
5739
5740status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5741 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005742 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005743 const ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005744 bool useIdentityTransform,
5745 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005746 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005747
Peiyong Lin0e003c92018-09-17 11:09:51 -07005748 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005749 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5750 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005751 *outBuffer =
5752 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5753 static_cast<android_pixel_format>(reqPixelFormat), 1,
5754 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005755
Robert Carr108b2c72019-04-02 16:32:58 -07005756 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
Lucas Dupinf11eba52020-04-20 18:42:31 -07005757 false /* regionSampling */, outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005758}
5759
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005760status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5761 TraverseLayersFunction traverseLayers,
5762 const sp<GraphicBuffer>& buffer,
Lucas Dupinf11eba52020-04-20 18:42:31 -07005763 bool useIdentityTransform, bool regionSampling,
Robert Carr108b2c72019-04-02 16:32:58 -07005764 bool& outCapturedSecureLayers) {
Robert Carr03480e22018-01-04 16:02:06 -08005765 const int uid = IPCThreadState::self()->getCallingUid();
5766 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5767
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005768 status_t result;
5769 int syncFd;
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005770
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005771 do {
5772 std::tie(result, syncFd) =
5773 schedule([&] {
5774 if (mRefreshPending) {
5775 ATRACE_NAME("Skipping screenshot for now");
5776 return std::make_pair(EAGAIN, -1);
5777 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005778
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005779 status_t result = NO_ERROR;
5780 int fd = -1;
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005781
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005782 Mutex::Autolock lock(mStateLock);
5783 renderArea.render([&] {
5784 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
5785 useIdentityTransform, forSystem, &fd,
5786 regionSampling, outCapturedSecureLayers);
5787 });
5788
5789 return std::make_pair(result, fd);
5790 }).get();
5791 } while (result == EAGAIN);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005792
5793 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005794 sync_wait(syncFd, -1);
5795 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005796 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005797
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005798 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005799}
5800
chaviwa76b2712017-09-20 12:02:26 -07005801void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005802 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005803 ANativeWindowBuffer* buffer, bool useIdentityTransform,
Lucas Dupinf11eba52020-04-20 18:42:31 -07005804 bool regionSampling, int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005805 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005806
chaviwa76b2712017-09-20 12:02:26 -07005807 const auto reqWidth = renderArea.getReqWidth();
5808 const auto reqHeight = renderArea.getReqHeight();
Alec Mouriadb75f42019-03-28 21:42:24 -07005809 const auto sourceCrop = renderArea.getSourceCrop();
Alec Mouri5a6d8572020-03-23 23:56:15 -07005810 const auto transform = renderArea.getTransform();
5811 const auto rotation = renderArea.getRotationFlags();
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005812 const auto& displayViewport = renderArea.getDisplayViewport();
Dan Stozac1879002014-05-22 15:59:05 -07005813
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005814 renderengine::DisplaySettings clientCompositionDisplay;
Vishnu Nair9b079a22020-01-21 14:36:08 -08005815 std::vector<compositionengine::LayerFE::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005816
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005817 // assume that bounds are never offset, and that they are the same as the
5818 // buffer bounds.
5819 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07005820 clientCompositionDisplay.clip = sourceCrop;
Alec Mouri5a6d8572020-03-23 23:56:15 -07005821 clientCompositionDisplay.orientation = rotation;
Alec Mouriadb75f42019-03-28 21:42:24 -07005822
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005823 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5824 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005825
chaviw50da5042018-04-09 13:49:37 -07005826 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005827
Vishnu Nair9b079a22020-01-21 14:36:08 -08005828 compositionengine::LayerFE::LayerSettings fillLayer;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005829 fillLayer.source.buffer.buffer = nullptr;
5830 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
Alec Mouri5a6d8572020-03-23 23:56:15 -07005831 fillLayer.geometry.boundaries =
5832 FloatRect(sourceCrop.left, sourceCrop.top, sourceCrop.right, sourceCrop.bottom);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005833 fillLayer.alpha = half(alpha);
5834 clientCompositionLayers.push_back(fillLayer);
5835
Dominik Laskowskib7251f42020-04-20 17:42:59 -07005836 const auto display = renderArea.getDisplayDevice();
Yichi Chen40773d92020-04-01 10:10:18 +08005837 std::vector<Layer*> renderedLayers;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005838 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005839 traverseLayers([&](Layer* layer) {
Lloyd Piquef16688f2019-02-19 17:47:57 -08005840 const bool supportProtectedContent = false;
5841 Region clip(renderArea.getBounds());
5842 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
5843 clip,
5844 useIdentityTransform,
Dominik Laskowskib7251f42020-04-20 17:42:59 -07005845 layer->needsFilteringForScreenshots(display.get(), transform) ||
Alec Mouri5a6d8572020-03-23 23:56:15 -07005846 renderArea.needsFiltering(),
Lloyd Piquef16688f2019-02-19 17:47:57 -08005847 renderArea.isSecure(),
5848 supportProtectedContent,
5849 clearRegion,
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005850 displayViewport,
5851 clientCompositionDisplay.outputDataspace,
5852 true, /* realContentIsVisible */
5853 false, /* clearContent */
Lloyd Piquef16688f2019-02-19 17:47:57 -08005854 };
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005855 std::vector<compositionengine::LayerFE::LayerSettings> results =
5856 layer->prepareClientCompositionList(targetSettings);
Yichi Chen40773d92020-04-01 10:10:18 +08005857 if (results.size() > 0) {
Alec Mouri5a6d8572020-03-23 23:56:15 -07005858 for (auto& settings : results) {
5859 settings.geometry.positionTransform =
5860 transform.asMatrix4() * settings.geometry.positionTransform;
Lucas Dupinf11eba52020-04-20 18:42:31 -07005861 // There's no need to process blurs when we're executing region sampling,
5862 // we're just trying to understand what we're drawing, and doing so without
5863 // blurs is already a pretty good approximation.
5864 if (regionSampling) {
5865 settings.backgroundBlurRadius = 0;
5866 }
Alec Mouri5a6d8572020-03-23 23:56:15 -07005867 }
Yichi Chen40773d92020-04-01 10:10:18 +08005868 clientCompositionLayers.insert(clientCompositionLayers.end(),
5869 std::make_move_iterator(results.begin()),
5870 std::make_move_iterator(results.end()));
5871 renderedLayers.push_back(layer);
5872 }
chaviwa76b2712017-09-20 12:02:26 -07005873 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005874
Yichi Chen40773d92020-04-01 10:10:18 +08005875 std::vector<const renderengine::LayerSettings*> clientCompositionLayerPointers(
5876 clientCompositionLayers.size());
Vishnu Nair9b079a22020-01-21 14:36:08 -08005877 std::transform(clientCompositionLayers.begin(), clientCompositionLayers.end(),
Yichi Chen40773d92020-04-01 10:10:18 +08005878 clientCompositionLayerPointers.begin(),
5879 std::pointer_traits<renderengine::LayerSettings*>::pointer_to);
Vishnu Nair9b079a22020-01-21 14:36:08 -08005880
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005881 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005882 // Use an empty fence for the buffer fence, since we just created the buffer so
5883 // there is no need for synchronization with the GPU.
5884 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005885 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005886 getRenderEngine().useProtectedContext(false);
Vishnu Nair9b079a22020-01-21 14:36:08 -08005887 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayerPointers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07005888 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005889
5890 *outSyncFd = drawFence.release();
Yichi Chen40773d92020-04-01 10:10:18 +08005891
5892 if (*outSyncFd >= 0) {
5893 sp<Fence> releaseFence = new Fence(dup(*outSyncFd));
5894 for (auto* layer : renderedLayers) {
5895 layer->onLayerDisplayed(releaseFence);
5896 }
5897 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07005898}
5899
chaviwa76b2712017-09-20 12:02:26 -07005900status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5901 TraverseLayersFunction traverseLayers,
5902 ANativeWindowBuffer* buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005903 bool useIdentityTransform, bool forSystem,
Lucas Dupinf11eba52020-04-20 18:42:31 -07005904 int* outSyncFd, bool regionSampling,
5905 bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005906 ATRACE_CALL();
5907
chaviwa76b2712017-09-20 12:02:26 -07005908 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07005909 outCapturedSecureLayers =
5910 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07005911 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005912
Robert Carr03480e22018-01-04 16:02:06 -08005913 // We allow the system server to take screenshots of secure layers for
5914 // use in situations like the Screen-rotation animation and place
5915 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07005916 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005917 ALOGW("FB is protected: PERMISSION_DENIED");
5918 return PERMISSION_DENIED;
5919 }
Lucas Dupinf11eba52020-04-20 18:42:31 -07005920 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, regionSampling,
5921 outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005922 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005923}
5924
chaviw95ef3c42019-02-14 10:55:09 -08005925void SurfaceFlinger::setInputWindowsFinished() {
5926 Mutex::Autolock _l(mStateLock);
5927
5928 mPendingSyncInputWindows = false;
Rob Carr9a2cc992020-03-06 12:44:45 -08005929
chaviw95ef3c42019-02-14 10:55:09 -08005930 mTransactionCV.broadcast();
5931}
chaviw5f21a5e2019-02-14 10:00:34 -08005932
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005933// ---------------------------------------------------------------------------
5934
Edgar Arriaga844fa672020-01-16 14:21:42 -08005935void SurfaceFlinger::State::traverse(const LayerVector::Visitor& visitor) const {
5936 layersSortedByZ.traverse(visitor);
5937}
5938
Dan Stoza412903f2017-04-27 13:42:17 -07005939void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5940 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005941}
5942
Dan Stoza412903f2017-04-27 13:42:17 -07005943void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5944 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005945}
5946
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005947void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005948 const LayerVector::Visitor& visitor) {
5949 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005950 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005951 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005952 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005953 continue;
5954 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005955 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005956 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005957 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005958 return;
5959 }
chaviwa76b2712017-09-20 12:02:26 -07005960 if (!layer->isVisible()) {
5961 return;
5962 }
5963 visitor(layer);
5964 });
5965 }
5966}
5967
Steven Thomasd4071902020-03-24 16:02:53 -07005968status_t SurfaceFlinger::setDesiredDisplayConfigSpecsInternal(
5969 const sp<DisplayDevice>& display,
5970 const std::optional<scheduler::RefreshRateConfigs::Policy>& policy, bool overridePolicy) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005971 Mutex::Autolock lock(mStateLock);
5972
Steven Thomasd4071902020-03-24 16:02:53 -07005973 LOG_ALWAYS_FATAL_IF(!display->isPrimary() && overridePolicy,
5974 "Can only set override policy on the primary display");
5975 LOG_ALWAYS_FATAL_IF(!policy && !overridePolicy, "Can only clear the override policy");
5976
Dominik Laskowski22488f62019-03-28 09:53:04 -07005977 if (!display->isPrimary()) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005978 // TODO(b/144711714): For non-primary displays we should be able to set an active config
5979 // as well. For now, just call directly to setActiveConfigWithConstraints but ideally
5980 // it should go thru setDesiredActiveConfig, similar to primary display.
5981 ALOGV("setAllowedDisplayConfigsInternal for non-primary display");
5982 const auto displayId = display->getId();
5983 LOG_ALWAYS_FATAL_IF(!displayId);
5984
Peiyong Line9d809e2020-04-14 13:10:48 -07005985 hal::VsyncPeriodChangeConstraints constraints;
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005986 constraints.desiredTimeNanos = systemTime();
5987 constraints.seamlessRequired = false;
5988
Peiyong Line9d809e2020-04-14 13:10:48 -07005989 hal::VsyncPeriodChangeTimeline timeline = {0, 0, 0};
Steven Thomasd4071902020-03-24 16:02:53 -07005990 if (getHwComposer().setActiveConfigWithConstraints(*displayId,
5991 policy->defaultConfig.value(),
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005992 constraints, &timeline) < 0) {
5993 return BAD_VALUE;
5994 }
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005995 if (timeline.refreshRequired) {
5996 repaintEverythingForHWC();
5997 }
5998
Steven Thomasd4071902020-03-24 16:02:53 -07005999 display->setActiveConfig(policy->defaultConfig);
6000 const nsecs_t vsyncPeriod = getHwComposer()
6001 .getConfigs(*displayId)[policy->defaultConfig.value()]
6002 ->getVsyncPeriod();
Ady Abrahamdfd62162020-06-10 16:11:56 -07006003 mScheduler->onNonPrimaryDisplayConfigChanged(mAppConnectionHandle, display->getId()->value,
6004 policy->defaultConfig, vsyncPeriod);
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006005 return NO_ERROR;
Ady Abraham838de062019-02-04 10:24:03 -08006006 }
6007
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006008 if (mDebugDisplayConfigSetByBackdoor) {
6009 // ignore this request as config is overridden by backdoor
6010 return NO_ERROR;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07006011 }
6012
Steven Thomasd4071902020-03-24 16:02:53 -07006013 status_t setPolicyResult = overridePolicy
6014 ? mRefreshRateConfigs->setOverridePolicy(policy)
6015 : mRefreshRateConfigs->setDisplayManagerPolicy(*policy);
6016 if (setPolicyResult < 0) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006017 return BAD_VALUE;
6018 }
Steven Thomasd4071902020-03-24 16:02:53 -07006019 if (setPolicyResult == scheduler::RefreshRateConfigs::CURRENT_POLICY_UNCHANGED) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006020 return NO_ERROR;
6021 }
Steven Thomasd4071902020-03-24 16:02:53 -07006022 scheduler::RefreshRateConfigs::Policy currentPolicy = mRefreshRateConfigs->getCurrentPolicy();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006023
Steven Thomasf734df42020-04-13 21:09:28 -07006024 ALOGV("Setting desired display config specs: defaultConfig: %d primaryRange: [%.0f %.0f]"
6025 " expandedRange: [%.0f %.0f]",
6026 currentPolicy.defaultConfig.value(), currentPolicy.primaryRange.min,
6027 currentPolicy.primaryRange.max, currentPolicy.appRequestRange.min,
6028 currentPolicy.appRequestRange.max);
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07006029
Ana Krulecb9afd792020-06-11 13:16:15 -07006030 // TODO(b/140204874): Leave the event in until we do proper testing with all apps that might
6031 // be depending in this callback.
Alec Mouri60aee1c2019-10-28 16:18:59 -07006032 const nsecs_t vsyncPeriod =
Ady Abrahamabc27602020-04-08 17:20:29 -07006033 mRefreshRateConfigs->getRefreshRateFromConfigId(display->getActiveConfig())
6034 .getVsyncPeriod();
Ady Abrahamdfd62162020-06-10 16:11:56 -07006035 mScheduler->onPrimaryDisplayConfigChanged(mAppConnectionHandle, display->getId()->value,
6036 display->getActiveConfig(), vsyncPeriod);
Ana Krulecb9afd792020-06-11 13:16:15 -07006037 toggleKernelIdleTimer();
Ady Abraham838de062019-02-04 10:24:03 -08006038
Ana Krulec3f6a2062020-01-23 15:48:01 -08006039 auto configId = mScheduler->getPreferredConfigId();
Ady Abraham2e1dd892020-03-05 13:48:36 -08006040 auto& preferredRefreshRate = configId
Ana Krulec3f6a2062020-01-23 15:48:01 -08006041 ? mRefreshRateConfigs->getRefreshRateFromConfigId(*configId)
6042 // NOTE: Choose the default config ID, if Scheduler doesn't have one in mind.
Steven Thomasd4071902020-03-24 16:02:53 -07006043 : mRefreshRateConfigs->getRefreshRateFromConfigId(currentPolicy.defaultConfig);
Ana Krulec3f6a2062020-01-23 15:48:01 -08006044 ALOGV("trying to switch to Scheduler preferred config %d (%s)",
Ady Abrahamabc27602020-04-08 17:20:29 -07006045 preferredRefreshRate.getConfigId().value(), preferredRefreshRate.getName().c_str());
Ana Krulec3f6a2062020-01-23 15:48:01 -08006046
Ady Abrahamabc27602020-04-08 17:20:29 -07006047 if (isDisplayConfigAllowed(preferredRefreshRate.getConfigId())) {
6048 ALOGV("switching to Scheduler preferred config %d",
6049 preferredRefreshRate.getConfigId().value());
6050 setDesiredActiveConfig(
6051 {preferredRefreshRate.getConfigId(), Scheduler::ConfigEvent::Changed});
Ady Abraham2139f732019-11-13 18:56:40 -08006052 } else {
Ady Abrahamabc27602020-04-08 17:20:29 -07006053 LOG_ALWAYS_FATAL("Desired config not allowed: %d",
6054 preferredRefreshRate.getConfigId().value());
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07006055 }
6056
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006057 return NO_ERROR;
6058}
6059
Ana Krulec0782b882019-10-15 17:34:54 -07006060status_t SurfaceFlinger::setDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Steven Thomasf734df42020-04-13 21:09:28 -07006061 int32_t defaultConfig,
6062 float primaryRefreshRateMin,
6063 float primaryRefreshRateMax,
6064 float appRequestRefreshRateMin,
6065 float appRequestRefreshRateMax) {
Ana Krulec0782b882019-10-15 17:34:54 -07006066 ATRACE_CALL();
6067
6068 if (!displayToken) {
6069 return BAD_VALUE;
6070 }
6071
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006072 auto future = schedule([=]() -> status_t {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07006073 const auto display = ON_MAIN_THREAD(getDisplayDeviceLocked(displayToken));
Ana Krulec234bb162019-11-10 22:55:55 +01006074 if (!display) {
6075 ALOGE("Attempt to set desired display configs for invalid display token %p",
6076 displayToken.get());
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006077 return NAME_NOT_FOUND;
Ana Krulec234bb162019-11-10 22:55:55 +01006078 } else if (display->isVirtual()) {
6079 ALOGW("Attempt to set desired display configs for virtual display");
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006080 return INVALID_OPERATION;
Ana Krulec234bb162019-11-10 22:55:55 +01006081 } else {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006082 using Policy = scheduler::RefreshRateConfigs::Policy;
Steven Thomasf734df42020-04-13 21:09:28 -07006083 const Policy policy{HwcConfigIndexType(defaultConfig),
6084 {primaryRefreshRateMin, primaryRefreshRateMax},
6085 {appRequestRefreshRateMin, appRequestRefreshRateMax}};
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006086 constexpr bool kOverridePolicy = false;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006087
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006088 return setDesiredDisplayConfigSpecsInternal(display, policy, kOverridePolicy);
6089 }
6090 });
6091
6092 return future.get();
Ana Krulec234bb162019-11-10 22:55:55 +01006093}
6094
6095status_t SurfaceFlinger::getDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006096 int32_t* outDefaultConfig,
Steven Thomasf734df42020-04-13 21:09:28 -07006097 float* outPrimaryRefreshRateMin,
6098 float* outPrimaryRefreshRateMax,
6099 float* outAppRequestRefreshRateMin,
6100 float* outAppRequestRefreshRateMax) {
Ana Krulec234bb162019-11-10 22:55:55 +01006101 ATRACE_CALL();
6102
Steven Thomasf734df42020-04-13 21:09:28 -07006103 if (!displayToken || !outDefaultConfig || !outPrimaryRefreshRateMin ||
6104 !outPrimaryRefreshRateMax || !outAppRequestRefreshRateMin || !outAppRequestRefreshRateMax) {
Ana Krulec234bb162019-11-10 22:55:55 +01006105 return BAD_VALUE;
6106 }
6107
6108 Mutex::Autolock lock(mStateLock);
6109 const auto display = getDisplayDeviceLocked(displayToken);
6110 if (!display) {
6111 return NAME_NOT_FOUND;
6112 }
6113
6114 if (display->isPrimary()) {
Steven Thomasd4071902020-03-24 16:02:53 -07006115 scheduler::RefreshRateConfigs::Policy policy =
6116 mRefreshRateConfigs->getDisplayManagerPolicy();
6117 *outDefaultConfig = policy.defaultConfig.value();
Steven Thomasf734df42020-04-13 21:09:28 -07006118 *outPrimaryRefreshRateMin = policy.primaryRange.min;
6119 *outPrimaryRefreshRateMax = policy.primaryRange.max;
6120 *outAppRequestRefreshRateMin = policy.appRequestRange.min;
6121 *outAppRequestRefreshRateMax = policy.appRequestRange.max;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006122 return NO_ERROR;
6123 } else if (display->isVirtual()) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006124 return INVALID_OPERATION;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006125 } else {
6126 const auto displayId = display->getId();
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006127 LOG_FATAL_IF(!displayId);
6128
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006129 *outDefaultConfig = getHwComposer().getActiveConfigIndex(*displayId);
6130 auto vsyncPeriod = getHwComposer().getActiveConfig(*displayId)->getVsyncPeriod();
Steven Thomasf734df42020-04-13 21:09:28 -07006131 *outPrimaryRefreshRateMin = 1e9f / vsyncPeriod;
6132 *outPrimaryRefreshRateMax = 1e9f / vsyncPeriod;
6133 *outAppRequestRefreshRateMin = 1e9f / vsyncPeriod;
6134 *outAppRequestRefreshRateMax = 1e9f / vsyncPeriod;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006135 return NO_ERROR;
Ana Krulec234bb162019-11-10 22:55:55 +01006136 }
Ana Krulec0782b882019-10-15 17:34:54 -07006137}
6138
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006139void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08006140 mFlinger->setInputWindowsFinished();
6141}
6142
Alec Mouri9a02eda2020-04-21 17:39:34 -07006143wp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
6144 Mutex::Autolock _l(mStateLock);
6145 return fromHandleLocked(handle);
6146}
6147
6148wp<Layer> SurfaceFlinger::fromHandleLocked(const sp<IBinder>& handle) {
Valerie Hau09e60052019-12-15 14:51:15 -08006149 BBinder* b = nullptr;
6150 if (handle) {
6151 b = handle->localBinder();
6152 }
Robert Carrc0df3122019-04-11 13:18:21 -07006153 if (b == nullptr) {
6154 return nullptr;
6155 }
6156 auto it = mLayersByLocalBinderToken.find(b);
6157 if (it != mLayersByLocalBinderToken.end()) {
Alec Mouri9a02eda2020-04-21 17:39:34 -07006158 return it->second;
Robert Carrc0df3122019-04-11 13:18:21 -07006159 }
6160 return nullptr;
6161}
6162
Dominik Laskowski75848362019-11-11 17:57:20 -08006163void SurfaceFlinger::onLayerFirstRef(Layer* layer) {
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006164 mNumLayers++;
6165 mScheduler->registerLayer(layer);
6166}
6167
6168void SurfaceFlinger::onLayerDestroyed(Layer* layer) {
6169 mNumLayers--;
Valerie Hauc5686802019-11-22 14:18:09 -08006170 removeFromOffscreenLayers(layer);
6171}
6172
6173// WARNING: ONLY CALL THIS FROM LAYER DTOR
6174// Here we add children in the current state to offscreen layers and remove the
6175// layer itself from the offscreen layer list. Since
6176// this is the dtor, it is safe to access the current state. This keeps us
6177// from dangling children layers such that they are not reachable from the
6178// Drawing state nor the offscreen layer list
6179// See b/141111965
6180void SurfaceFlinger::removeFromOffscreenLayers(Layer* layer) {
6181 for (auto& child : layer->getCurrentChildren()) {
6182 mOffscreenLayers.emplace(child.get());
6183 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006184 mOffscreenLayers.erase(layer);
6185}
6186
Alec Mouri4545a8a2019-08-08 20:05:32 -07006187void SurfaceFlinger::bufferErased(const client_cache_t& clientCacheId) {
6188 getRenderEngine().unbindExternalTextureBuffer(clientCacheId.id);
6189}
6190
Vishnu Nair08f6eae2019-11-26 14:01:39 -08006191status_t SurfaceFlinger::setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor,
6192 float lightPosY, float lightPosZ,
6193 float lightRadius) {
6194 Mutex::Autolock _l(mStateLock);
6195 mCurrentState.globalShadowSettings.ambientColor = vec4(ambientColor);
6196 mCurrentState.globalShadowSettings.spotColor = vec4(spotColor);
6197 mCurrentState.globalShadowSettings.lightPos.y = lightPosY;
6198 mCurrentState.globalShadowSettings.lightPos.z = lightPosZ;
6199 mCurrentState.globalShadowSettings.lightRadius = lightRadius;
6200
6201 // these values are overridden when calculating the shadow settings for a layer.
6202 mCurrentState.globalShadowSettings.lightPos.x = 0.f;
6203 mCurrentState.globalShadowSettings.length = 0.f;
Vishnu Nairb13bb952019-11-15 10:24:08 -08006204 return NO_ERROR;
6205}
6206
Lloyd Pique8d9f8362020-02-11 19:13:09 -08006207const std::unordered_map<std::string, uint32_t>& SurfaceFlinger::getGenericLayerMetadataKeyMap()
6208 const {
6209 // TODO(b/149500060): Remove this fixed/static mapping. Please prefer taking
6210 // on the work to remove the table in that bug rather than adding more to
6211 // it.
6212 static const std::unordered_map<std::string, uint32_t> genericLayerMetadataKeyMap{
6213 // Note: METADATA_OWNER_UID and METADATA_WINDOW_TYPE are officially
6214 // supported, and exposed via the
6215 // IVrComposerClient::VrCommand::SET_LAYER_INFO command.
6216 {"org.chromium.arc.V1_0.TaskId", METADATA_TASK_ID},
6217 {"org.chromium.arc.V1_0.CursorInfo", METADATA_MOUSE_CURSOR},
6218 };
6219 return genericLayerMetadataKeyMap;
6220}
6221
Steven Thomas62a4cf82020-01-31 12:04:03 -08006222status_t SurfaceFlinger::setFrameRate(const sp<IGraphicBufferProducer>& surface, float frameRate,
6223 int8_t compatibility) {
6224 if (!ValidateFrameRate(frameRate, compatibility, "SurfaceFlinger::setFrameRate")) {
6225 return BAD_VALUE;
6226 }
6227
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07006228 static_cast<void>(schedule([=] {
Ady Abraham60e42ea2020-03-09 19:17:31 -07006229 Mutex::Autolock lock(mStateLock);
6230 if (authenticateSurfaceTextureLocked(surface)) {
6231 sp<Layer> layer = (static_cast<MonitoredProducer*>(surface.get()))->getLayer();
6232 if (layer->setFrameRate(
6233 Layer::FrameRate(frameRate,
6234 Layer::FrameRate::convertCompatibility(compatibility)))) {
6235 setTransactionFlags(eTraversalNeeded);
6236 }
6237 } else {
6238 ALOGE("Attempt to set frame rate on an unrecognized IGraphicBufferProducer");
6239 return BAD_VALUE;
Steven Thomas62a4cf82020-01-31 12:04:03 -08006240 }
Ady Abraham60e42ea2020-03-09 19:17:31 -07006241 return NO_ERROR;
6242 }));
6243
Steven Thomas62a4cf82020-01-31 12:04:03 -08006244 return NO_ERROR;
6245}
6246
Steven Thomasd4071902020-03-24 16:02:53 -07006247status_t SurfaceFlinger::acquireFrameRateFlexibilityToken(sp<IBinder>* outToken) {
6248 if (!outToken) {
6249 return BAD_VALUE;
6250 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006251
6252 auto future = schedule([this] {
6253 status_t result = NO_ERROR;
6254 sp<IBinder> token;
6255
Steven Thomasd4071902020-03-24 16:02:53 -07006256 if (mFrameRateFlexibilityTokenCount == 0) {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07006257 const auto display = ON_MAIN_THREAD(getDefaultDisplayDeviceLocked());
Steven Thomasd4071902020-03-24 16:02:53 -07006258
6259 // This is a little racy, but not in a way that hurts anything. As we grab the
6260 // defaultConfig from the display manager policy, we could be setting a new display
6261 // manager policy, leaving us using a stale defaultConfig. The defaultConfig doesn't
6262 // matter for the override policy though, since we set allowGroupSwitching to true, so
6263 // it's not a problem.
6264 scheduler::RefreshRateConfigs::Policy overridePolicy;
6265 overridePolicy.defaultConfig =
6266 mRefreshRateConfigs->getDisplayManagerPolicy().defaultConfig;
6267 overridePolicy.allowGroupSwitching = true;
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006268 constexpr bool kOverridePolicy = true;
6269 result = setDesiredDisplayConfigSpecsInternal(display, overridePolicy, kOverridePolicy);
Steven Thomasd4071902020-03-24 16:02:53 -07006270 }
6271
6272 if (result == NO_ERROR) {
6273 mFrameRateFlexibilityTokenCount++;
6274 // Handing out a reference to the SurfaceFlinger object, as we're doing in the line
6275 // below, is something to consider carefully. The lifetime of the
6276 // FrameRateFlexibilityToken isn't tied to SurfaceFlinger object lifetime, so if this
6277 // SurfaceFlinger object were to be destroyed while the token still exists, the token
6278 // destructor would be accessing a stale SurfaceFlinger reference, and crash. This is ok
6279 // in this case, for two reasons:
6280 // 1. Once SurfaceFlinger::run() is called by main_surfaceflinger.cpp, the only way
6281 // the program exits is via a crash. So we won't have a situation where the
6282 // SurfaceFlinger object is dead but the process is still up.
6283 // 2. The frame rate flexibility token is acquired/released only by CTS tests, so even
6284 // if condition 1 were changed, the problem would only show up when running CTS tests,
6285 // not on end user devices, so we could spot it and fix it without serious impact.
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006286 token = new FrameRateFlexibilityToken(
Steven Thomasd4071902020-03-24 16:02:53 -07006287 [this]() { onFrameRateFlexibilityTokenReleased(); });
6288 ALOGD("Frame rate flexibility token acquired. count=%d",
6289 mFrameRateFlexibilityTokenCount);
6290 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006291
6292 return std::make_pair(result, token);
6293 });
6294
6295 status_t result;
6296 std::tie(result, *outToken) = future.get();
Steven Thomasd4071902020-03-24 16:02:53 -07006297 return result;
6298}
6299
6300void SurfaceFlinger::onFrameRateFlexibilityTokenReleased() {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006301 static_cast<void>(schedule([this] {
Steven Thomasd4071902020-03-24 16:02:53 -07006302 LOG_ALWAYS_FATAL_IF(mFrameRateFlexibilityTokenCount == 0,
6303 "Failed tracking frame rate flexibility tokens");
6304 mFrameRateFlexibilityTokenCount--;
6305 ALOGD("Frame rate flexibility token released. count=%d", mFrameRateFlexibilityTokenCount);
6306 if (mFrameRateFlexibilityTokenCount == 0) {
Dominik Laskowskia19f4b62020-04-21 00:27:31 -07006307 const auto display = ON_MAIN_THREAD(getDefaultDisplayDeviceLocked());
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006308 constexpr bool kOverridePolicy = true;
6309 status_t result = setDesiredDisplayConfigSpecsInternal(display, {}, kOverridePolicy);
Steven Thomasd4071902020-03-24 16:02:53 -07006310 LOG_ALWAYS_FATAL_IF(result < 0, "Failed releasing frame rate flexibility token");
6311 }
6312 }));
6313}
6314
Dominik Laskowski20134642020-04-20 22:36:44 -07006315void SurfaceFlinger::enableRefreshRateOverlay(bool enable) {
6316 static_cast<void>(schedule([=] {
6317 std::unique_ptr<RefreshRateOverlay> overlay;
6318 if (enable) {
6319 overlay = std::make_unique<RefreshRateOverlay>(*this);
6320 }
6321
6322 {
6323 Mutex::Autolock lock(mStateLock);
6324
6325 // Destroy the layer of the current overlay, if any, outside the lock.
6326 mRefreshRateOverlay.swap(overlay);
6327 if (!mRefreshRateOverlay) return;
6328
6329 if (const auto display = getDefaultDisplayDeviceLocked()) {
6330 mRefreshRateOverlay->setViewport(display->getSize());
6331 }
6332
6333 mRefreshRateOverlay->changeRefreshRate(mRefreshRateConfigs->getCurrentRefreshRate());
6334 }
6335 }));
6336}
6337
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006338} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07006339
Mathias Agopian3f844832013-08-07 21:24:32 -07006340#if defined(__gl_h_)
6341#error "don't include gl/gl.h in this file"
6342#endif
6343
6344#if defined(__gl2_h_)
6345#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08006346#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08006347
6348// TODO(b/129481165): remove the #pragma below and fix conversion issues
6349#pragma clang diagnostic pop // ignored "-Wconversion"