blob: e68c48407b5093e43487ae5e9993e4978d7b01d6 [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 Mouri5f487d42020-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 Mouri5f487d42020-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>
Lais Andrade3a6e47d2020-04-02 11:20:16 +010031#include <android/hardware/power/Boost.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 Pique9370a482019-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 Mouri5f487d42020-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 Mouri5f487d42020-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>
Lloyd Pique70d91362018-10-18 16:02:55 -070060#include <input/IInputFlinger.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080061#include <layerproto/LayerProtoParser.h>
62#include <log/log.h>
63#include <private/android_filesystem_config.h>
64#include <private/gui/SyncFeatures.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070065#include <renderengine/RenderEngine.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080066#include <statslog.h>
67#include <sys/types.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070068#include <ui/ColorSpace.h>
69#include <ui/DebugUtils.h>
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -080070#include <ui/DisplayConfig.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070071#include <ui/DisplayInfo.h>
72#include <ui/DisplayStatInfo.h>
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -080073#include <ui/DisplayState.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070074#include <ui/GraphicBufferAllocator.h>
75#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070076#include <ui/UiConfig.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070078#include <utils/String16.h>
79#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070080#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080081#include <utils/Trace.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070082#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080083
Alec Mouri5f487d42020-02-06 09:26:19 -080084#include <algorithm>
85#include <cinttypes>
86#include <cmath>
87#include <cstdint>
88#include <functional>
89#include <mutex>
90#include <optional>
91#include <unordered_map>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080092
Robert Carr578038f2018-03-09 12:25:24 -080093#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070094#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070095#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020096#include "Client.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020097#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080098#include "ContainerLayer.h"
Robert Carr578038f2018-03-09 12:25:24 -080099#include "DisplayDevice.h"
Steven Thomasb02664d2017-07-26 18:48:28 -0700100#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -0700101#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -0700102#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -0700103#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -0700104#include "DisplayHardware/VirtualDisplaySurface.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800105#include "EffectLayer.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -0700106#include "Effects/Daltonizer.h"
Mikael Pessa90092f42019-08-26 17:22:04 -0700107#include "FrameTracer/FrameTracer.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800108#include "Layer.h"
109#include "LayerVector.h"
110#include "MonitoredProducer.h"
111#include "NativeWindowSurface.h"
Dominik Laskowski5690bde2020-04-23 19:04:22 -0700112#include "Promise.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800113#include "RefreshRateOverlay.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700114#include "RegionSamplingThread.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700115#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -0700116#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700117#include "Scheduler/EventControlThread.h"
118#include "Scheduler/EventThread.h"
Ady Abraham5def7332020-05-29 16:13:47 -0700119#include "Scheduler/LayerHistory.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -0700120#include "Scheduler/MessageQueue.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700121#include "Scheduler/PhaseOffsets.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700122#include "Scheduler/Scheduler.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800123#include "StartPropertySetThread.h"
124#include "SurfaceFlingerProperties.h"
125#include "SurfaceInterceptor.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800126#include "TimeStats/TimeStats.h"
Dominik Laskowskib6e54372019-09-04 14:06:28 -0700127#include "android-base/parseint.h"
David Sodman7e4ae112018-02-09 15:02:28 -0800128#include "android-base/stringprintf.h"
129
Dominik Laskowski0a1435d2020-04-21 00:27:31 -0700130#define MAIN_THREAD ACQUIRE(mStateLock) RELEASE(mStateLock)
131
132#define ON_MAIN_THREAD(expr) \
133 [&] { \
134 LOG_FATAL_IF(std::this_thread::get_id() != mMainThreadId); \
135 UnnecessaryLock lock(mStateLock); \
136 return (expr); \
137 }()
138
139#undef NO_THREAD_SAFETY_ANALYSIS
140#define NO_THREAD_SAFETY_ANALYSIS \
141 _Pragma("GCC error \"Prefer MAIN_THREAD macros or {Conditional,Timed,Unnecessary}Lock.\"")
142
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800143namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700144
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700145using namespace std::string_literals;
146
Jaesoo Lee43518572017-01-23 19:03:16 +0900147using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900148using namespace android::hardware::configstore::V1_0;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900149using namespace android::sysprop;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800150
Lais Andrade3a6e47d2020-04-02 11:20:16 +0100151using android::hardware::power::Boost;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800152using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700153using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700154using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800155using ui::DisplayPrimaries;
Peiyong Lin62665892018-04-16 11:07:44 -0700156using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700157using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900158
Peiyong Line9d809e2020-04-14 13:10:48 -0700159namespace hal = android::hardware::graphics::composer::hal;
160
Steven Thomasb02664d2017-07-26 18:48:28 -0700161namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700162
163#pragma clang diagnostic push
164#pragma clang diagnostic error "-Wswitch-enum"
165
166bool isWideColorMode(const ColorMode colorMode) {
167 switch (colorMode) {
168 case ColorMode::DISPLAY_P3:
169 case ColorMode::ADOBE_RGB:
170 case ColorMode::DCI_P3:
171 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700172 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700173 case ColorMode::BT2100_PQ:
174 case ColorMode::BT2100_HLG:
175 return true;
176 case ColorMode::NATIVE:
177 case ColorMode::STANDARD_BT601_625:
178 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
179 case ColorMode::STANDARD_BT601_525:
180 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
181 case ColorMode::STANDARD_BT709:
182 case ColorMode::SRGB:
183 return false;
184 }
185 return false;
186}
187
188#pragma clang diagnostic pop
189
Dominik Laskowski542c9dc2020-04-10 12:42:02 -0700190template <typename Mutex>
Dominik Laskowski0a1435d2020-04-21 00:27:31 -0700191struct SCOPED_CAPABILITY ConditionalLockGuard {
192 ConditionalLockGuard(Mutex& mutex, bool lock) ACQUIRE(mutex) : mutex(mutex), lock(lock) {
Dominik Laskowski542c9dc2020-04-10 12:42:02 -0700193 if (lock) mutex.lock();
Steven Thomasb02664d2017-07-26 18:48:28 -0700194 }
Dominik Laskowski542c9dc2020-04-10 12:42:02 -0700195
Dominik Laskowski0a1435d2020-04-21 00:27:31 -0700196 ~ConditionalLockGuard() RELEASE() {
Dominik Laskowski542c9dc2020-04-10 12:42:02 -0700197 if (lock) mutex.unlock();
198 }
199
200 Mutex& mutex;
201 const bool lock;
Steven Thomasb02664d2017-07-26 18:48:28 -0700202};
Peiyong Linfca547f2018-07-09 13:03:33 -0700203
Dominik Laskowski542c9dc2020-04-10 12:42:02 -0700204using ConditionalLock = ConditionalLockGuard<Mutex>;
205
Dominik Laskowski0a1435d2020-04-21 00:27:31 -0700206struct SCOPED_CAPABILITY TimedLock {
207 TimedLock(Mutex& mutex, nsecs_t timeout, const char* whence) ACQUIRE(mutex)
208 : mutex(mutex), status(mutex.timedLock(timeout)) {
209 ALOGE_IF(!locked(), "%s timed out locking: %s (%d)", whence, strerror(-status), status);
210 }
211
212 ~TimedLock() RELEASE() {
213 if (locked()) mutex.unlock();
214 }
215
216 bool locked() const { return status == NO_ERROR; }
217
218 Mutex& mutex;
219 const status_t status;
220};
221
222struct SCOPED_CAPABILITY UnnecessaryLock {
223 explicit UnnecessaryLock(Mutex& mutex) ACQUIRE(mutex) {}
224 ~UnnecessaryLock() RELEASE() {}
225};
226
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800227// TODO(b/141333600): Consolidate with HWC2::Display::Config::Builder::getDefaultDensity.
Dominik Laskowskid125d0e2020-05-08 12:36:39 -0700228constexpr float FALLBACK_DENSITY = ACONFIGURATION_DENSITY_TV;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800229
230float getDensityFromProperty(const char* property, bool required) {
231 char value[PROPERTY_VALUE_MAX];
232 const float density = property_get(property, value, nullptr) > 0 ? std::atof(value) : 0.f;
233 if (!density && required) {
234 ALOGE("%s must be defined as a build property", property);
235 return FALLBACK_DENSITY;
236 }
Dominik Laskowskid125d0e2020-05-08 12:36:39 -0700237 return density;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800238}
239
Peiyong Lin9d846a52018-11-05 13:18:20 -0800240// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
241bool validateCompositionDataspace(Dataspace dataspace) {
242 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
243}
244
Steven Thomasd4071902020-03-24 16:02:53 -0700245class FrameRateFlexibilityToken : public BBinder {
246public:
247 FrameRateFlexibilityToken(std::function<void()> callback) : mCallback(callback) {}
248 virtual ~FrameRateFlexibilityToken() { mCallback(); }
249
250private:
251 std::function<void()> mCallback;
252};
253
Steven Thomasb02664d2017-07-26 18:48:28 -0700254} // namespace anonymous
255
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800256// ---------------------------------------------------------------------------
257
Mathias Agopian99b49842011-06-27 16:05:52 -0700258const String16 sHardwareTest("android.permission.HARDWARE_TEST");
259const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
260const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
261const String16 sDump("android.permission.DUMP");
Amy Hsuc8cdfef2020-05-07 13:06:25 +0800262const char* KERNEL_IDLE_TIMER_PROP = "graphics.display.kernel_idle_timer.enabled";
Mathias Agopian99b49842011-06-27 16:05:52 -0700263
264// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700265int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700266bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800267uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800268bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800269bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800270int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Brian Lindahla13f2d52020-03-05 11:54:17 +0100271uint32_t SurfaceFlinger::maxGraphicsWidth;
272uint32_t SurfaceFlinger::maxGraphicsHeight;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600273bool SurfaceFlinger::hasWideColorDisplay;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800274ui::Rotation SurfaceFlinger::internalDisplayOrientation = ui::ROTATION_0;
Peiyong Lin13effd12018-07-24 17:01:47 -0700275bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700276bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700277Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
278ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
279Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
280ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Ana Krulec3803b8d2020-02-03 16:35:46 -0800281bool SurfaceFlinger::useFrameRateApi;
Mathias Agopian99b49842011-06-27 16:05:52 -0700282
Kalle Raitaa099a242017-01-11 11:17:29 -0800283std::string getHwcServiceName() {
284 char value[PROPERTY_VALUE_MAX] = {};
285 property_get("debug.sf.hwc_service_name", value, "default");
286 ALOGI("Using HWComposer service: '%s'", value);
287 return std::string(value);
288}
289
290bool useTrebleTestingOverride() {
291 char value[PROPERTY_VALUE_MAX] = {};
292 property_get("debug.sf.treble_testing_override", value, "false");
293 ALOGI("Treble testing override: '%s'", value);
294 return std::string(value) == "true";
295}
296
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800297std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
298 switch(displayColorSetting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800299 case DisplayColorSetting::kManaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700300 return std::string("Managed");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800301 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700302 return std::string("Unmanaged");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800303 case DisplayColorSetting::kEnhanced:
Chia-I Wu0d711262018-05-21 15:19:35 -0700304 return std::string("Enhanced");
305 default:
306 return std::string("Unknown ") +
307 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800308 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800309}
310
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700311SurfaceFlingerBE::SurfaceFlingerBE() : mHwcServiceName(getHwcServiceName()) {}
David Sodmanbc815282017-11-05 18:57:52 -0800312
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700313SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
314 : mFactory(factory),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700315 mInterceptor(mFactory.createSurfaceInterceptor(this)),
Yiwei Zhangf0229a72019-09-09 19:28:02 -0700316 mTimeStats(std::make_shared<impl::TimeStats>()),
Mikael Pessa90092f42019-08-26 17:22:04 -0700317 mFrameTracer(std::make_unique<FrameTracer>()),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700318 mEventQueue(mFactory.createMessageQueue()),
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700319 mCompositionEngine(mFactory.createCompositionEngine()),
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800320 mInternalDisplayDensity(getDensityFromProperty("ro.sf.lcd_density", true)),
321 mEmulatedDisplayDensity(getDensityFromProperty("qemu.sf.lcd_density", false)) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800322
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700323SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800324 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800325
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900326 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800327
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900328 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700329
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900330 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700331
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900332 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800333
Steven Thomas050b2c82017-03-06 11:45:16 -0800334 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900335 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800336
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900337 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800338
Brian Lindahla13f2d52020-03-05 11:54:17 +0100339 maxGraphicsWidth = std::max(max_graphics_width(0), 0);
340 maxGraphicsHeight = std::max(max_graphics_height(0), 0);
341
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900342 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700343
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900344 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600345
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900346 mDefaultCompositionDataspace =
347 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
Peiyong Lin8cabfc32019-06-14 14:25:43 -0700348 mWideColorGamutCompositionDataspace = static_cast<ui::Dataspace>(wcg_composition_dataspace(
349 hasWideColorDisplay ? Dataspace::DISPLAY_P3 : Dataspace::V0_SRGB));
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900350 defaultCompositionDataspace = mDefaultCompositionDataspace;
351 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
352 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
353 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
354 wideColorGamutCompositionPixelFormat =
355 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700356
Yichi Chenda901bf2019-06-28 14:58:27 +0800357 mColorSpaceAgnosticDataspace =
358 static_cast<ui::Dataspace>(color_space_agnostic_dataspace(Dataspace::UNKNOWN));
359
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900360 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800361
Dominik Laskowski718f9602019-11-09 20:01:35 -0800362 using Values = SurfaceFlingerProperties::primary_display_orientation_values;
363 switch (primary_display_orientation(Values::ORIENTATION_0)) {
364 case Values::ORIENTATION_0:
Iris Chang7501ed62018-04-30 14:45:42 +0800365 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800366 case Values::ORIENTATION_90:
367 internalDisplayOrientation = ui::ROTATION_90;
Iris Chang7501ed62018-04-30 14:45:42 +0800368 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800369 case Values::ORIENTATION_180:
370 internalDisplayOrientation = ui::ROTATION_180;
Iris Chang7501ed62018-04-30 14:45:42 +0800371 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800372 case Values::ORIENTATION_270:
373 internalDisplayOrientation = ui::ROTATION_270;
Iris Chang7501ed62018-04-30 14:45:42 +0800374 break;
375 }
Dominik Laskowski718f9602019-11-09 20:01:35 -0800376 ALOGV("Internal Display Orientation: %s", toCString(internalDisplayOrientation));
Iris Chang7501ed62018-04-30 14:45:42 +0800377
Sundong Ahn85131bd2019-02-18 15:51:53 +0900378 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800379
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800380 // debugging stuff...
381 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700382
Mathias Agopianb4b17302013-03-20 18:36:41 -0700383 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700384 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700385
Alec Mouri5f487d42020-02-06 09:26:19 -0800386 property_get("ro.build.type", value, "user");
387 mIsUserBuild = strcmp(value, "user") == 0;
388
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800389 property_get("debug.sf.showupdates", value, "0");
390 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700391
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700392 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodson34397da2019-02-04 09:36:10 +0000393
394 // DDMS debugging deprecated (b/120782499)
395 property_get("debug.sf.ddms", value, "0");
396 int debugDdms = atoi(value);
397 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700398
399 property_get("debug.sf.disable_backpressure", value, "0");
400 mPropagateBackpressure = !atoi(value);
401 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700402
Ady Abrahamadb9a992019-09-19 21:21:55 +0000403 property_get("debug.sf.enable_gl_backpressure", value, "0");
404 mPropagateBackpressureClientComposition = atoi(value);
405 ALOGI_IF(mPropagateBackpressureClientComposition,
406 "Enabling backpressure propagation for Client Composition");
407
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800408 property_get("debug.sf.enable_hwc_vds", value, "0");
409 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800410 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800411
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800412 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800413 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800414 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700415
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800416 property_get("ro.surface_flinger.supports_background_blur", value, "0");
417 bool supportsBlurs = atoi(value);
Lucas Dupin00f16422020-03-11 11:33:04 -0700418 mSupportsBlur = supportsBlurs;
419 ALOGI_IF(!mSupportsBlur, "Disabling blur effects, they are not supported.");
Lucas Dupin2dd6f392020-02-18 17:43:36 -0800420 property_get("ro.sf.blurs_are_expensive", value, "0");
421 mBlursAreExpensive = atoi(value);
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800422
Ady Abrahamb89ca7d2020-03-04 11:19:37 -0800423 const size_t defaultListSize = ISurfaceComposer::MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700424 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
425 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
Alec Mouri601393f2020-02-21 13:26:52 -0800426 mGraphicBufferProducerListSizeLogThreshold =
427 std::max(static_cast<int>(0.95 *
428 static_cast<double>(mMaxGraphicBufferProducerListSize)),
429 1);
Dan Stoza0a0158c2018-03-16 13:38:54 -0700430
Dan Stozaec460082018-12-17 15:35:09 -0800431 property_get("debug.sf.luma_sampling", value, "1");
432 mLumaSampling = atoi(value);
433
Vishnu Nairb2a999b2020-01-23 13:43:02 -0800434 property_get("debug.sf.disable_client_composition_cache", value, "0");
Vishnu Nair9b079a22020-01-21 14:36:08 -0800435 mDisableClientCompositionCache = atoi(value);
436
Romain Guy11d63f42017-07-20 12:47:14 -0700437 // We should be reading 'persist.sys.sf.color_saturation' here
438 // but since /data may be encrypted, we need to wait until after vold
439 // comes online to attempt to read the property. The property is
440 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800441
442 if (useTrebleTestingOverride()) {
443 // Without the override SurfaceFlinger cannot connect to HIDL
444 // services that are not listed in the manifests. Considered
445 // deriving the setting from the set service name, but it
446 // would be brittle if the name that's not 'default' is used
447 // for production purposes later on.
448 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
449 }
Ana Krulec3803b8d2020-02-03 16:35:46 -0800450
451 useFrameRateApi = use_frame_rate_api(true);
Ana Krulecb9afd792020-06-11 13:16:15 -0700452
453 mKernelIdleTimerEnabled = mSupportKernelIdleTimer = sysprop::support_kernel_idle_timer(false);
454 base::SetProperty(KERNEL_IDLE_TIMER_PROP, mKernelIdleTimerEnabled ? "true" : "false");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800455}
456
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700457SurfaceFlinger::~SurfaceFlinger() = default;
458
459void SurfaceFlinger::onFirstRef() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800460 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800461}
462
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700463void SurfaceFlinger::binderDied(const wp<IBinder>&) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800464 // the window manager died on us. prepare its eulogy.
Rob Carr2aa78cb2020-03-10 14:27:49 -0700465 mBootFinished = false;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800466
Andy McFadden13a082e2012-08-24 10:16:42 -0700467 // restore initial conditions (default device unblank, etc)
468 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800469
470 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700471 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800472}
473
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700474void SurfaceFlinger::run() {
475 while (true) {
476 mEventQueue->waitMessage();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800477 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700478}
479
480template <typename F, typename T>
481inline std::future<T> SurfaceFlinger::schedule(F&& f) {
482 auto [task, future] = makeTask(std::move(f));
483 mEventQueue->postMessage(std::move(task));
484 return std::move(future);
Robert Carr1db73f62016-12-21 12:58:51 -0800485}
486
487sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700488 const sp<Client> client = new Client(this);
489 return client->initCheck() == NO_ERROR ? client : nullptr;
Robert Carr1db73f62016-12-21 12:58:51 -0800490}
491
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700492sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName, bool secure) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700493 class DisplayToken : public BBinder {
494 sp<SurfaceFlinger> flinger;
495 virtual ~DisplayToken() {
496 // no more references, this display must be terminated
497 Mutex::Autolock _l(flinger->mStateLock);
498 flinger->mCurrentState.displays.removeItem(this);
499 flinger->setTransactionFlags(eDisplayTransactionNeeded);
500 }
501 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700502 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700503 : flinger(flinger) {
504 }
505 };
506
507 sp<BBinder> token = new DisplayToken(this);
508
509 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700510 // Display ID is assigned when virtual display is allocated by HWC.
511 DisplayDeviceState state;
512 state.isSecure = secure;
513 state.displayName = displayName;
514 mCurrentState.displays.add(token, state);
515 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700516 return token;
517}
518
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700519void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700520 Mutex::Autolock lock(mStateLock);
Jesse Hall6c913be2013-08-08 12:15:49 -0700521
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700522 const ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700523 if (index < 0) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700524 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700525 return;
526 }
527
Dominik Laskowski075d3172018-05-24 15:50:06 -0700528 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700529 if (state.physical) {
530 ALOGE("%s: Invalid operation on physical display", __FUNCTION__);
Jesse Hall6c913be2013-08-08 12:15:49 -0700531 return;
532 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700533 mInterceptor->saveDisplayDeletion(state.sequenceId);
534 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700535 setTransactionFlags(eDisplayTransactionNeeded);
536}
537
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800538std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
539 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700540
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800541 const auto internalDisplayId = getInternalDisplayIdLocked();
542 if (!internalDisplayId) {
543 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700544 }
545
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800546 std::vector<PhysicalDisplayId> displayIds;
547 displayIds.reserve(mPhysicalDisplayTokens.size());
548 displayIds.push_back(internalDisplayId->value);
549
550 for (const auto& [id, token] : mPhysicalDisplayTokens) {
551 if (id != *internalDisplayId) {
552 displayIds.push_back(id.value);
553 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700554 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700555
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800556 return displayIds;
557}
558
559sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
560 Mutex::Autolock lock(mStateLock);
561 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700562}
563
Ady Abraham37965d42018-11-01 13:43:32 -0700564status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
565 if (!outGetColorManagement) {
566 return BAD_VALUE;
567 }
568 *outGetColorManagement = useColorManagement;
569 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700570}
571
Lloyd Pique441d5042018-10-18 16:49:51 -0700572HWComposer& SurfaceFlinger::getHwComposer() const {
573 return mCompositionEngine->getHwComposer();
574}
575
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700576renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
577 return mCompositionEngine->getRenderEngine();
578}
579
Lloyd Pique70d91362018-10-18 16:02:55 -0700580compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
581 return *mCompositionEngine.get();
582}
583
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800584void SurfaceFlinger::bootFinished()
585{
Rob Carr2aa78cb2020-03-10 14:27:49 -0700586 if (mBootFinished == true) {
587 ALOGE("Extra call to bootFinished");
588 return;
589 }
590 mBootFinished = true;
Wei Wangf9b05ee2017-07-19 20:59:39 -0700591 if (mStartPropertySetThread->join() != NO_ERROR) {
592 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800593 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800594 const nsecs_t now = systemTime();
595 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000596 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700597
Mikael Pessa90092f42019-08-26 17:22:04 -0700598 mFrameTracer->initialize();
Alec Mouri8e2f31b2020-01-16 22:04:35 +0000599 mTimeStats->onBootFinished();
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700600
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700601 // wait patiently for the window manager death
602 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700603 mWindowManager = defaultServiceManager()->getService(name);
604 if (mWindowManager != 0) {
605 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700606 }
Robert Carr720e5062018-07-30 17:45:14 -0700607 sp<IBinder> input(defaultServiceManager()->getService(
608 String16("inputflinger")));
609 if (input == nullptr) {
610 ALOGE("Failed to link to input service");
611 } else {
612 mInputFlinger = interface_cast<IInputFlinger>(input);
613 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700614
Steven Thomas050b2c82017-03-06 11:45:16 -0800615 if (mVrFlinger) {
616 mVrFlinger->OnBootFinished();
617 }
618
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700619 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700620 // formerly we would just kill the process, but we now ask it to exit so it
621 // can choose where to stop the animation.
622 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700623
624 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
625 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
626 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700627
Dominik Laskowski20134642020-04-20 22:36:44 -0700628 static_cast<void>(schedule([this] {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800629 readPersistentProperties();
Dan Stoza29e7bdf2020-03-23 14:43:09 -0700630 mPowerAdvisor.onBootFinished();
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800631 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800632
Ady Abraham8a82ba62020-01-17 12:43:17 -0800633 if (property_get_bool("sf.debug.show_refresh_rate_overlay", false)) {
Dominik Laskowski20134642020-04-20 22:36:44 -0700634 enableRefreshRateOverlay(true);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800635 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800636 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800637}
638
Dan Stoza436ccf32018-06-21 12:10:12 -0700639uint32_t SurfaceFlinger::getNewTexture() {
640 {
641 std::lock_guard lock(mTexturePoolMutex);
642 if (!mTexturePool.empty()) {
643 uint32_t name = mTexturePool.back();
644 mTexturePool.pop_back();
645 ATRACE_INT("TexturePoolSize", mTexturePool.size());
646 return name;
647 }
648
649 // The pool was too small, so increase it for the future
650 ++mTexturePoolSize;
651 }
652
653 // The pool was empty, so we need to get a new texture name directly using a
654 // blocking call to the main thread
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700655 return schedule([this] {
656 uint32_t name = 0;
657 getRenderEngine().genTextures(1, &name);
658 return name;
659 })
660 .get();
Dan Stoza436ccf32018-06-21 12:10:12 -0700661}
662
Mathias Agopian3f844832013-08-07 21:24:32 -0700663void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700664 std::lock_guard lock(mTexturePoolMutex);
665 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
666 // to actually delete this or not based on mTexturePoolSize
667 mTexturePool.push_back(texture);
668 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700669}
670
Wei Wangf9b05ee2017-07-19 20:59:39 -0700671// Do not call property_set on main thread which will be blocked by init
672// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700673void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700674 ALOGI( "SurfaceFlinger's main thread ready to run. "
675 "Initializing graphics H/W...");
Steven Thomasb02664d2017-07-26 18:48:28 -0700676 Mutex::Autolock _l(mStateLock);
Kevin DuBois413287f2019-02-25 08:46:47 -0800677
Steven Thomasb02664d2017-07-26 18:48:28 -0700678 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin0256f722018-08-31 15:45:10 -0700679 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800680 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700681 mCompositionEngine->setRenderEngine(renderengine::RenderEngine::create(
682 renderengine::RenderEngineCreationArgs::Builder()
683 .setPixelFormat(static_cast<int32_t>(defaultCompositionPixelFormat))
684 .setImageCacheSize(maxFrameBufferAcquiredBuffers)
685 .setUseColorManagerment(useColorManagement)
686 .setEnableProtectedContext(enable_protected_contents(false))
687 .setPrecacheToneMapperShaderOnly(false)
Lucas Dupin00f16422020-03-11 11:33:04 -0700688 .setSupportsBackgroundBlur(mSupportsBlur)
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700689 .setContextPriority(useContextPriority
690 ? renderengine::RenderEngine::ContextPriority::HIGH
691 : renderengine::RenderEngine::ContextPriority::MEDIUM)
692 .build()));
Alec Mourie4034bb2019-11-19 12:45:54 -0800693 mCompositionEngine->setTimeStats(mTimeStats);
Steven Thomasb02664d2017-07-26 18:48:28 -0700694
695 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
696 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700697 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
Lloyd Pique4603f3c2020-02-11 12:06:56 -0800698 mCompositionEngine->getHwComposer().setConfiguration(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800699 // Process any initial hotplug and resulting display changes.
700 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700701 const auto display = getDefaultDisplayDeviceLocked();
702 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700703 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700704 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800705
Steven Thomas050b2c82017-03-06 11:45:16 -0800706 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700707 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700708 // This callback is called from the vr flinger dispatch thread. We
709 // need to call signalTransaction(), which requires holding
710 // mStateLock when we're not on the main thread. Acquiring
711 // mStateLock from the vr flinger dispatch thread might trigger a
712 // deadlock in surface flinger (see b/66916578), so post a message
713 // to be handled on the main thread instead.
Dominik Laskowskidd4ef272020-04-23 14:02:12 -0700714 static_cast<void>(schedule([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700715 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
716 mVrFlingerRequestsDisplay = requestDisplay;
717 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700718 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800719 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700720 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
721 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700722 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700723 .value_or(0),
724 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800725 if (!mVrFlinger) {
726 ALOGE("Failed to start vrflinger");
727 }
728 }
729
Mathias Agopian92a979a2012-08-02 18:32:23 -0700730 // initialize our drawing state
731 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700732
Andy McFadden13a082e2012-08-24 10:16:42 -0700733 // set initial conditions (e.g. unblank default device)
734 initializeDisplays();
735
Steven Thomas137d4bc2019-07-25 16:55:14 -0700736 char primeShaderCache[PROPERTY_VALUE_MAX];
737 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
738 if (atoi(primeShaderCache)) {
739 getRenderEngine().primeCache();
740 }
Dan Stoza4e637772016-07-28 13:31:51 -0700741
Wei Wangf9b05ee2017-07-19 20:59:39 -0700742 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700743
744 const bool presentFenceReliable =
Peiyong Line9d809e2020-04-14 13:10:48 -0700745 !getHwComposer().hasCapability(hal::Capability::PRESENT_FENCE_IS_NOT_RELIABLE);
Lloyd Pique90c115d2018-09-18 21:39:42 -0700746 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700747
748 if (mStartPropertySetThread->Start() != NO_ERROR) {
749 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800750 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800751
Dan Stoza9e56aa02015-11-02 13:00:03 -0800752 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700753}
754
Romain Guy11d63f42017-07-20 12:47:14 -0700755void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700756 Mutex::Autolock _l(mStateLock);
757
Romain Guy11d63f42017-07-20 12:47:14 -0700758 char value[PROPERTY_VALUE_MAX];
759
760 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800761 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700762 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800763 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100764
765 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700766 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800767
768 property_get("persist.sys.sf.color_mode", value, "0");
769 mForceColorMode = static_cast<ColorMode>(atoi(value));
Lucas Dupin00f16422020-03-11 11:33:04 -0700770
771 property_get("persist.sys.sf.disable_blurs", value, "0");
772 bool disableBlurs = atoi(value);
773 mDisableBlurs = disableBlurs;
774 ALOGI_IF(disableBlurs, "Disabling blur effects, user preference.");
Romain Guy11d63f42017-07-20 12:47:14 -0700775}
776
Mathias Agopiana67e4182012-06-19 17:26:12 -0700777void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800778 // Start boot animation service by setting a property mailbox
779 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700780 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800781 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700782 if (mStartPropertySetThread->join() != NO_ERROR) {
783 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800784 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700785}
786
Mathias Agopian875d8e12013-06-07 15:35:48 -0700787size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700788 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700789}
790
Mathias Agopian875d8e12013-06-07 15:35:48 -0700791size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700792 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700793}
794
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800795// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800796
Jamie Gennis582270d2011-08-17 18:19:00 -0700797bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800798 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800799 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800800 return authenticateSurfaceTextureLocked(bufferProducer);
801}
802
803bool SurfaceFlinger::authenticateSurfaceTextureLocked(
804 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800805 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800806 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800807}
808
Brian Anderson6b376712017-04-04 10:51:39 -0700809status_t SurfaceFlinger::getSupportedFrameTimestamps(
810 std::vector<FrameEvent>* outSupported) const {
811 *outSupported = {
812 FrameEvent::REQUESTED_PRESENT,
813 FrameEvent::ACQUIRE,
814 FrameEvent::LATCH,
815 FrameEvent::FIRST_REFRESH_START,
816 FrameEvent::LAST_REFRESH_START,
817 FrameEvent::GPU_COMPOSITION_DONE,
818 FrameEvent::DEQUEUE_READY,
819 FrameEvent::RELEASE,
820 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700821 ConditionalLock _l(mStateLock,
822 std::this_thread::get_id() != mMainThreadId);
Peiyong Line9d809e2020-04-14 13:10:48 -0700823 if (!getHwComposer().hasCapability(hal::Capability::PRESENT_FENCE_IS_NOT_RELIABLE)) {
Brian Anderson6b376712017-04-04 10:51:39 -0700824 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
825 }
826 return NO_ERROR;
827}
828
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800829status_t SurfaceFlinger::getDisplayState(const sp<IBinder>& displayToken, ui::DisplayState* state) {
830 if (!displayToken || !state) {
831 return BAD_VALUE;
832 }
833
834 Mutex::Autolock lock(mStateLock);
835
836 const auto display = getDisplayDeviceLocked(displayToken);
837 if (!display) {
838 return NAME_NOT_FOUND;
839 }
840
841 state->layerStack = display->getLayerStack();
842 state->orientation = display->getOrientation();
843
844 const Rect viewport = display->getViewport();
845 state->viewport = viewport.isValid() ? viewport.getSize() : display->getSize();
846
847 return NO_ERROR;
848}
849
850status_t SurfaceFlinger::getDisplayInfo(const sp<IBinder>& displayToken, DisplayInfo* info) {
851 if (!displayToken || !info) {
852 return BAD_VALUE;
853 }
854
855 Mutex::Autolock lock(mStateLock);
856
857 const auto display = getDisplayDeviceLocked(displayToken);
858 if (!display) {
859 return NAME_NOT_FOUND;
860 }
861
Dominik Laskowski55c85402020-01-21 16:25:47 -0800862 if (const auto connectionType = display->getConnectionType())
863 info->connectionType = *connectionType;
864 else {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800865 return INVALID_OPERATION;
866 }
867
868 if (mEmulatedDisplayDensity) {
869 info->density = mEmulatedDisplayDensity;
870 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -0800871 info->density = info->connectionType == DisplayConnectionType::Internal
872 ? mInternalDisplayDensity
873 : FALLBACK_DENSITY;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800874 }
Dominik Laskowskid125d0e2020-05-08 12:36:39 -0700875 info->density /= ACONFIGURATION_DENSITY_MEDIUM;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800876
877 info->secure = display->isSecure();
Marin Shalamanove5cceea2020-04-30 18:13:10 +0200878 info->deviceProductInfo = display->getDeviceProductInfo();
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800879
880 return NO_ERROR;
881}
882
Dominik Laskowski22488f62019-03-28 09:53:04 -0700883status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800884 Vector<DisplayConfig>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700885 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700886 return BAD_VALUE;
887 }
888
Dominik Laskowski22488f62019-03-28 09:53:04 -0700889 Mutex::Autolock lock(mStateLock);
890
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800891 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700892 if (!displayId) {
893 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700894 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700895
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800896 const bool isInternal = (displayId == getInternalDisplayIdLocked());
Mathias Agopian1604f772012-09-18 21:54:42 -0700897
Dan Stoza7f7da322014-05-02 15:26:25 -0700898 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700899
Dominik Laskowski075d3172018-05-24 15:50:06 -0700900 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800901 DisplayConfig config;
Dan Stoza7f7da322014-05-02 15:26:25 -0700902
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800903 auto width = hwConfig->getWidth();
904 auto height = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700905
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800906 auto xDpi = hwConfig->getDpiX();
907 auto yDpi = hwConfig->getDpiY();
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700908
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800909 if (isInternal &&
910 (internalDisplayOrientation == ui::ROTATION_90 ||
911 internalDisplayOrientation == ui::ROTATION_270)) {
912 std::swap(width, height);
913 std::swap(xDpi, yDpi);
Dan Stoza7f7da322014-05-02 15:26:25 -0700914 }
915
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800916 config.resolution = ui::Size(width, height);
Ady Abraham2139f732019-11-13 18:56:40 -0800917
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800918 if (mEmulatedDisplayDensity) {
919 config.xDpi = mEmulatedDisplayDensity;
920 config.yDpi = mEmulatedDisplayDensity;
921 } else {
922 config.xDpi = xDpi;
923 config.yDpi = yDpi;
924 }
925
926 const nsecs_t period = hwConfig->getVsyncPeriod();
927 config.refreshRate = 1e9f / period;
928
929 const auto offsets = mPhaseConfiguration->getOffsetsForRefreshRate(config.refreshRate);
930 config.appVsyncOffset = offsets.late.app;
931 config.sfVsyncOffset = offsets.late.sf;
Ady Abrahamff731d82020-02-18 17:22:46 -0800932 config.configGroup = hwConfig->getConfigGroup();
Dan Stoza9e56aa02015-11-02 13:00:03 -0800933
Andy McFadden91b2ca82014-06-13 14:04:23 -0700934 // This is how far in advance a buffer must be queued for
935 // presentation at a given time. If you want a buffer to appear
936 // on the screen at time N, you must submit the buffer before
937 // (N - presentationDeadline).
938 //
939 // Normally it's one full refresh period (to give SF a chance to
940 // latch the buffer), but this can be reduced by configuring a
941 // DispSync offset. Any additional delays introduced by the hardware
942 // composer or panel must be accounted for here.
943 //
944 // We add an additional 1ms to allow for processing time and
945 // differences between the ideal and actual refresh rate.
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800946 config.presentationDeadline = period - config.sfVsyncOffset + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700947
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800948 configs->push_back(config);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700949 }
950
Dan Stoza7f7da322014-05-02 15:26:25 -0700951 return NO_ERROR;
952}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700953
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700954status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
955 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700956 return BAD_VALUE;
957 }
958
Ana Krulecc2870422019-01-29 19:00:58 -0800959 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700960 return NO_ERROR;
961}
962
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700963int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700964 int activeConfig;
965 bool isPrimary;
966
967 {
968 Mutex::Autolock lock(mStateLock);
969
970 if (const auto display = getDisplayDeviceLocked(displayToken)) {
971 activeConfig = display->getActiveConfig().value();
972 isPrimary = display->isPrimary();
973 } else {
974 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
975 return NAME_NOT_FOUND;
976 }
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800977 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700978
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700979 if (isPrimary) {
Dominik Laskowski20134642020-04-20 22:36:44 -0700980 if (const auto config = getDesiredActiveConfig()) {
981 return config->configId.value();
Steven Thomasc9098452019-09-30 17:15:05 -0700982 }
Steven Thomasc9098452019-09-30 17:15:05 -0700983 }
Ady Abraham2139f732019-11-13 18:56:40 -0800984
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700985 return activeConfig;
Dan Stoza7f7da322014-05-02 15:26:25 -0700986}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700987
Ady Abraham03b02dd2019-03-21 15:40:11 -0700988void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800989 ATRACE_CALL();
Ady Abraham2e1dd892020-03-05 13:48:36 -0800990 auto& refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(info.configId);
Ady Abrahamabc27602020-04-08 17:20:29 -0700991 ALOGV("setDesiredActiveConfig(%s)", refreshRate.getName().c_str());
Ana Krulec7d1d6832018-12-27 11:10:09 -0800992
Ady Abrahamb838aed2019-02-12 15:30:16 -0800993 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham59db0a32020-03-02 18:04:20 -0800994 if (mDesiredActiveConfigChanged) {
995 // If a config change is pending, just cache the latest request in
996 // mDesiredActiveConfig
997 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
998 mDesiredActiveConfig = info;
999 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
1000 } else {
1001 // Check is we are already at the desired config
1002 const auto display = getDefaultDisplayDeviceLocked();
Ady Abrahamabc27602020-04-08 17:20:29 -07001003 if (!display || display->getActiveConfig() == refreshRate.getConfigId()) {
Ady Abraham59db0a32020-03-02 18:04:20 -08001004 return;
1005 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001006
Ady Abraham59db0a32020-03-02 18:04:20 -08001007 // Initiate a config change.
1008 mDesiredActiveConfigChanged = true;
1009 mDesiredActiveConfig = info;
1010
Ady Abrahamb838aed2019-02-12 15:30:16 -08001011 // This will trigger HWC refresh without resetting the idle timer.
1012 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -07001013 // Start receiving vsync samples now, so that we can detect a period
1014 // switch.
Ady Abrahamabc27602020-04-08 17:20:29 -07001015 mScheduler->resyncToHardwareVsync(true, refreshRate.getVsyncPeriod());
Ady Abraham53852a52019-05-28 18:07:44 -07001016 // As we called to set period, we will call to onRefreshRateChangeCompleted once
1017 // DispSync model is locked.
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001018 mVSyncModulator->onRefreshRateChangeInitiated();
Ady Abraham2139f732019-11-13 18:56:40 -08001019
Ady Abrahamabc27602020-04-08 17:20:29 -07001020 mPhaseConfiguration->setRefreshRateFps(refreshRate.getFps());
Ady Abraham9e16a482019-12-03 17:19:41 -08001021 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham32efd542020-05-19 17:49:26 -07001022 mScheduler->setConfigChangePending(true);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001023 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07001024
1025 if (mRefreshRateOverlay) {
Ady Abraham2139f732019-11-13 18:56:40 -08001026 mRefreshRateOverlay->changeRefreshRate(refreshRate);
Ady Abraham03b02dd2019-03-21 15:40:11 -07001027 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001028}
1029
1030status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
1031 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -08001032
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001033 if (!displayToken) {
1034 return BAD_VALUE;
1035 }
Ady Abraham838de062019-02-04 10:24:03 -08001036
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001037 auto future = schedule([=]() -> status_t {
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07001038 const auto display = ON_MAIN_THREAD(getDisplayDeviceLocked(displayToken));
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001039 if (!display) {
1040 ALOGE("Attempt to set allowed display configs for invalid display token %p",
1041 displayToken.get());
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001042 return NAME_NOT_FOUND;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001043 } else if (display->isVirtual()) {
1044 ALOGW("Attempt to set allowed display configs for virtual display");
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001045 return INVALID_OPERATION;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001046 } else {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001047 const HwcConfigIndexType config(mode);
1048 const float fps = mRefreshRateConfigs->getRefreshRateFromConfigId(config).getFps();
Steven Thomasf734df42020-04-13 21:09:28 -07001049 const scheduler::RefreshRateConfigs::Policy policy{config, {fps, fps}};
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001050 constexpr bool kOverridePolicy = false;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001051
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001052 return setDesiredDisplayConfigSpecsInternal(display, policy, kOverridePolicy);
1053 }
1054 });
1055
1056 return future.get();
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001057}
1058
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001059void SurfaceFlinger::setActiveConfigInternal() {
1060 ATRACE_CALL();
1061
Dominik Laskowski22488f62019-03-28 09:53:04 -07001062 const auto display = getDefaultDisplayDeviceLocked();
1063 if (!display) {
1064 return;
1065 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001066
Alec Mouri8de697e2020-03-19 10:52:01 -07001067 auto& oldRefreshRate =
1068 mRefreshRateConfigs->getRefreshRateFromConfigId(display->getActiveConfig());
1069
Dominik Laskowski22488f62019-03-28 09:53:04 -07001070 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham2139f732019-11-13 18:56:40 -08001071 mRefreshRateConfigs->setCurrentConfigId(mUpcomingActiveConfig.configId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001072 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001073 display->setActiveConfig(mUpcomingActiveConfig.configId);
1074
Ady Abraham2e1dd892020-03-05 13:48:36 -08001075 auto& refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -08001076 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId);
Ady Abrahamabc27602020-04-08 17:20:29 -07001077 if (refreshRate.getVsyncPeriod() != oldRefreshRate.getVsyncPeriod()) {
Alec Mouri8de697e2020-03-19 10:52:01 -07001078 mTimeStats->incrementRefreshRateSwitches();
1079 }
Ady Abrahamabc27602020-04-08 17:20:29 -07001080 mPhaseConfiguration->setRefreshRateFps(refreshRate.getFps());
Ady Abraham9e16a482019-12-03 17:19:41 -08001081 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abrahamabc27602020-04-08 17:20:29 -07001082 ATRACE_INT("ActiveConfigFPS", refreshRate.getFps());
Dominik Laskowski22488f62019-03-28 09:53:04 -07001083
Ana Krulec8d3e4f32019-03-05 10:40:33 -08001084 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Alec Mouri60aee1c2019-10-28 16:18:59 -07001085 const nsecs_t vsyncPeriod =
1086 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId)
Ady Abrahamabc27602020-04-08 17:20:29 -07001087 .getVsyncPeriod();
Ady Abrahamdfd62162020-06-10 16:11:56 -07001088 mScheduler->onPrimaryDisplayConfigChanged(mAppConnectionHandle, display->getId()->value,
1089 mUpcomingActiveConfig.configId, vsyncPeriod);
Ady Abraham447052e2019-02-13 16:07:27 -08001090 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001091}
1092
Ady Abraham53852a52019-05-28 18:07:44 -07001093void SurfaceFlinger::desiredActiveConfigChangeDone() {
1094 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1095 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
1096 mDesiredActiveConfigChanged = false;
Ady Abraham53852a52019-05-28 18:07:44 -07001097
Ady Abraham2e1dd892020-03-05 13:48:36 -08001098 const auto& refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -08001099 mRefreshRateConfigs->getRefreshRateFromConfigId(mDesiredActiveConfig.configId);
Ady Abrahamabc27602020-04-08 17:20:29 -07001100 mScheduler->resyncToHardwareVsync(true, refreshRate.getVsyncPeriod());
1101 mPhaseConfiguration->setRefreshRateFps(refreshRate.getFps());
Ady Abraham9e16a482019-12-03 17:19:41 -08001102 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham32efd542020-05-19 17:49:26 -07001103 mScheduler->setConfigChangePending(false);
Ady Abraham53852a52019-05-28 18:07:44 -07001104}
1105
Ady Abraham27cbed72020-04-10 12:56:59 -07001106void SurfaceFlinger::performSetActiveConfig() {
Alec Mourife3dc942019-02-12 14:19:18 -08001107 ATRACE_CALL();
Ady Abraham2139f732019-11-13 18:56:40 -08001108 ALOGV("performSetActiveConfig");
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001109 // Store the local variable to release the lock.
Dominik Laskowski20134642020-04-20 22:36:44 -07001110 const auto desiredActiveConfig = getDesiredActiveConfig();
Ady Abraham27cbed72020-04-10 12:56:59 -07001111 if (!desiredActiveConfig) {
1112 // No desired active config pending to be applied
1113 return;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001114 }
1115
Ady Abraham2e1dd892020-03-05 13:48:36 -08001116 auto& refreshRate =
Ady Abraham27cbed72020-04-10 12:56:59 -07001117 mRefreshRateConfigs->getRefreshRateFromConfigId(desiredActiveConfig->configId);
Ady Abrahamabc27602020-04-08 17:20:29 -07001118 ALOGV("performSetActiveConfig changing active config to %d(%s)",
1119 refreshRate.getConfigId().value(), refreshRate.getName().c_str());
Dominik Laskowski22488f62019-03-28 09:53:04 -07001120 const auto display = getDefaultDisplayDeviceLocked();
Ady Abraham27cbed72020-04-10 12:56:59 -07001121 if (!display || display->getActiveConfig() == desiredActiveConfig->configId) {
Ady Abrahamb838aed2019-02-12 15:30:16 -08001122 // display is not valid or we are already in the requested mode
1123 // on both cases there is nothing left to do
Ady Abraham53852a52019-05-28 18:07:44 -07001124 desiredActiveConfigChangeDone();
Ady Abraham27cbed72020-04-10 12:56:59 -07001125 return;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001126 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001127
Ady Abraham838de062019-02-04 10:24:03 -08001128 // Desired active config was set, it is different than the config currently in use, however
1129 // allowed configs might have change by the time we process the refresh.
1130 // Make sure the desired config is still allowed
Ady Abraham27cbed72020-04-10 12:56:59 -07001131 if (!isDisplayConfigAllowed(desiredActiveConfig->configId)) {
Ady Abraham53852a52019-05-28 18:07:44 -07001132 desiredActiveConfigChangeDone();
Ady Abraham27cbed72020-04-10 12:56:59 -07001133 return;
Ady Abraham838de062019-02-04 10:24:03 -08001134 }
Alec Mouri7f015182019-07-11 13:56:22 -07001135
Ady Abraham27cbed72020-04-10 12:56:59 -07001136 mUpcomingActiveConfig = *desiredActiveConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -08001137 const auto displayId = display->getId();
1138 LOG_ALWAYS_FATAL_IF(!displayId);
1139
Ady Abrahamabc27602020-04-08 17:20:29 -07001140 ATRACE_INT("ActiveConfigFPS_HWC", refreshRate.getFps());
Ady Abrahamb838aed2019-02-12 15:30:16 -08001141
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001142 // TODO(b/142753666) use constrains
Peiyong Line9d809e2020-04-14 13:10:48 -07001143 hal::VsyncPeriodChangeConstraints constraints;
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001144 constraints.desiredTimeNanos = systemTime();
1145 constraints.seamlessRequired = false;
1146
Peiyong Line9d809e2020-04-14 13:10:48 -07001147 hal::VsyncPeriodChangeTimeline outTimeline;
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001148 auto status =
1149 getHwComposer().setActiveConfigWithConstraints(*displayId,
1150 mUpcomingActiveConfig.configId.value(),
1151 constraints, &outTimeline);
1152 if (status != NO_ERROR) {
Ady Abraham5e95aa22020-03-04 10:26:05 -08001153 // setActiveConfigWithConstraints may fail if a hotplug event is just about
1154 // to be sent. We just log the error in this case.
1155 ALOGW("setActiveConfigWithConstraints failed: %d", status);
Ady Abraham27cbed72020-04-10 12:56:59 -07001156 return;
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001157 }
1158
1159 mScheduler->onNewVsyncPeriodChangeTimeline(outTimeline);
1160 // Scheduler will submit an empty frame to HWC if needed.
Ady Abraham27cbed72020-04-10 12:56:59 -07001161 mSetActiveConfigPending = true;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001162}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001163
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001164status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1165 Vector<ColorMode>* outColorModes) {
1166 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001167 return BAD_VALUE;
1168 }
1169
Peiyong Lina52f0292018-03-14 17:26:31 -07001170 std::vector<ColorMode> modes;
Peiyong Linff84a152019-05-17 18:36:19 -07001171 bool isInternalDisplay = false;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001172 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001173 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1174
1175 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1176 if (!displayId) {
1177 return NAME_NOT_FOUND;
1178 }
1179
Dominik Laskowski075d3172018-05-24 15:50:06 -07001180 modes = getHwComposer().getColorModes(*displayId);
Peiyong Linff84a152019-05-17 18:36:19 -07001181 isInternalDisplay = displayId == getInternalDisplayIdLocked();
Steven Thomas6d8110b2017-08-31 18:24:21 -07001182 }
Michael Wright28f24d02016-07-12 13:30:53 -07001183 outColorModes->clear();
Peiyong Linff84a152019-05-17 18:36:19 -07001184
1185 // If it's built-in display and the configuration claims it's not wide color capable,
1186 // filter out all wide color modes. The typical reason why this happens is that the
1187 // hardware is not good enough to support GPU composition of wide color, and thus the
1188 // OEMs choose to disable this capability.
1189 if (isInternalDisplay && !hasWideColorDisplay) {
1190 std::remove_copy_if(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes),
1191 isWideColorMode);
1192 } else {
1193 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1194 }
Michael Wright28f24d02016-07-12 13:30:53 -07001195
1196 return NO_ERROR;
1197}
1198
Daniel Solomon42d04562019-01-20 21:03:19 -08001199status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1200 ui::DisplayPrimaries &primaries) {
1201 if (!displayToken) {
1202 return BAD_VALUE;
1203 }
1204
1205 // Currently we only support this API for a single internal display.
1206 if (getInternalDisplayToken() != displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001207 return NAME_NOT_FOUND;
Daniel Solomon42d04562019-01-20 21:03:19 -08001208 }
1209
1210 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1211 return NO_ERROR;
1212}
1213
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001214ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001215 Mutex::Autolock lock(mStateLock);
1216
1217 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001218 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001219 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001220 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001221}
1222
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001223status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07001224 schedule([=]() MAIN_THREAD {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001225 Vector<ColorMode> modes;
1226 getDisplayColorModes(displayToken, &modes);
1227 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1228 if (mode < ColorMode::NATIVE || !exists) {
1229 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1230 decodeColorMode(mode).c_str(), mode, displayToken.get());
1231 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001232 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001233 const auto display = getDisplayDeviceLocked(displayToken);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001234 if (!display) {
1235 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1236 decodeColorMode(mode).c_str(), mode, displayToken.get());
1237 } else if (display->isVirtual()) {
1238 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1239 decodeColorMode(mode).c_str(), mode);
1240 } else {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001241 display->getCompositionDisplay()->setColorProfile(
1242 compositionengine::Output::ColorProfile{mode, Dataspace::UNKNOWN,
1243 RenderIntent::COLORIMETRIC,
1244 Dataspace::UNKNOWN});
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001245 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001246 }).wait();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001247
Michael Wright28f24d02016-07-12 13:30:53 -07001248 return NO_ERROR;
1249}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001250
Galia Peycheva5492cb52019-10-30 14:13:16 +01001251status_t SurfaceFlinger::getAutoLowLatencyModeSupport(const sp<IBinder>& displayToken,
1252 bool* outSupport) const {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001253 if (!displayToken) {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001254 return BAD_VALUE;
1255 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001256
1257 Mutex::Autolock lock(mStateLock);
1258
Galia Peycheva5492cb52019-10-30 14:13:16 +01001259 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1260 if (!displayId) {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001261 return NAME_NOT_FOUND;
1262 }
Peiyong Line9d809e2020-04-14 13:10:48 -07001263 *outSupport =
1264 getHwComposer().hasDisplayCapability(*displayId,
1265 hal::DisplayCapability::AUTO_LOW_LATENCY_MODE);
Galia Peycheva5492cb52019-10-30 14:13:16 +01001266 return NO_ERROR;
1267}
1268
1269void SurfaceFlinger::setAutoLowLatencyMode(const sp<IBinder>& displayToken, bool on) {
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07001270 static_cast<void>(schedule([=]() MAIN_THREAD {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001271 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1272 getHwComposer().setAutoLowLatencyMode(*displayId, on);
1273 } else {
1274 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1275 }
1276 }));
Galia Peycheva5492cb52019-10-30 14:13:16 +01001277}
1278
1279status_t SurfaceFlinger::getGameContentTypeSupport(const sp<IBinder>& displayToken,
1280 bool* outSupport) const {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001281 if (!displayToken) {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001282 return BAD_VALUE;
1283 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001284
1285 Mutex::Autolock lock(mStateLock);
1286
Galia Peycheva5492cb52019-10-30 14:13:16 +01001287 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1288 if (!displayId) {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001289 return NAME_NOT_FOUND;
1290 }
1291
Peiyong Line9d809e2020-04-14 13:10:48 -07001292 std::vector<hal::ContentType> types;
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001293 getHwComposer().getSupportedContentTypes(*displayId, &types);
1294
1295 *outSupport = std::any_of(types.begin(), types.end(),
Peiyong Line9d809e2020-04-14 13:10:48 -07001296 [](auto type) { return type == hal::ContentType::GAME; });
Galia Peycheva5492cb52019-10-30 14:13:16 +01001297 return NO_ERROR;
1298}
1299
1300void SurfaceFlinger::setGameContentType(const sp<IBinder>& displayToken, bool on) {
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07001301 static_cast<void>(schedule([=]() MAIN_THREAD {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001302 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
Peiyong Line9d809e2020-04-14 13:10:48 -07001303 const auto type = on ? hal::ContentType::GAME : hal::ContentType::NONE;
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001304 getHwComposer().setContentType(*displayId, type);
1305 } else {
1306 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1307 }
1308 }));
Galia Peycheva5492cb52019-10-30 14:13:16 +01001309}
1310
Svetoslavd85084b2014-03-20 10:28:31 -07001311status_t SurfaceFlinger::clearAnimationFrameStats() {
1312 Mutex::Autolock _l(mStateLock);
1313 mAnimFrameTracker.clearStats();
1314 return NO_ERROR;
1315}
1316
1317status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1318 Mutex::Autolock _l(mStateLock);
1319 mAnimFrameTracker.getStats(outStats);
1320 return NO_ERROR;
1321}
1322
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001323status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1324 HdrCapabilities* outCapabilities) const {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001325 Mutex::Autolock lock(mStateLock);
Dan Stozac4f471e2016-03-24 09:31:08 -07001326
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001327 const auto display = getDisplayDeviceLocked(displayToken);
1328 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001329 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1330 return NAME_NOT_FOUND;
Dan Stozac4f471e2016-03-24 09:31:08 -07001331 }
1332
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001333 // At this point the DisplayDevice should already be set up,
Peiyong Linfb069302018-04-25 14:34:31 -07001334 // meaning the luminance information is already queried from
1335 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001336 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001337 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1338 capabilities.getDesiredMaxLuminance(),
1339 capabilities.getDesiredMaxAverageLuminance(),
1340 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001341
1342 return NO_ERROR;
1343}
1344
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001345status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1346 ui::PixelFormat* outFormat,
1347 ui::Dataspace* outDataspace,
1348 uint8_t* outComponentMask) const {
1349 if (!outFormat || !outDataspace || !outComponentMask) {
1350 return BAD_VALUE;
1351 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001352
1353 Mutex::Autolock lock(mStateLock);
1354
1355 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1356 if (!displayId) {
1357 return NAME_NOT_FOUND;
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001358 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001359
1360 return getHwComposer().getDisplayedContentSamplingAttributes(*displayId, outFormat,
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001361 outDataspace, outComponentMask);
1362}
1363
Kevin DuBois74e53772018-11-19 10:52:38 -08001364status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1365 bool enable, uint8_t componentMask,
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001366 uint64_t maxFrames) {
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07001367 return schedule([=]() MAIN_THREAD -> status_t {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001368 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1369 return getHwComposer().setDisplayContentSamplingEnabled(*displayId, enable,
1370 componentMask,
1371 maxFrames);
1372 } else {
1373 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1374 return NAME_NOT_FOUND;
1375 }
1376 })
1377 .get();
Kevin DuBois74e53772018-11-19 10:52:38 -08001378}
1379
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001380status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1381 uint64_t maxFrames, uint64_t timestamp,
1382 DisplayedFrameStats* outStats) const {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001383 Mutex::Autolock lock(mStateLock);
1384
1385 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1386 if (!displayId) {
1387 return NAME_NOT_FOUND;
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001388 }
1389
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001390 return getHwComposer().getDisplayedContentSample(*displayId, maxFrames, timestamp, outStats);
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001391}
1392
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001393status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1394 if (!outSupported) {
1395 return BAD_VALUE;
1396 }
1397 *outSupported = getRenderEngine().supportsProtectedContent();
1398 return NO_ERROR;
1399}
1400
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001401status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1402 bool* outIsWideColorDisplay) const {
1403 if (!displayToken || !outIsWideColorDisplay) {
1404 return BAD_VALUE;
1405 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001406
1407 Mutex::Autolock lock(mStateLock);
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001408 const auto display = getDisplayDeviceLocked(displayToken);
1409 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001410 return NAME_NOT_FOUND;
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001411 }
Peiyong Linff84a152019-05-17 18:36:19 -07001412
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001413 *outIsWideColorDisplay =
1414 display->isPrimary() ? hasWideColorDisplay : display->hasWideColorGamut();
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001415 return NO_ERROR;
1416}
1417
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001418status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001419 schedule([=] {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001420 Mutex::Autolock lock(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001421
Dominik Laskowski6505f792019-09-18 11:10:05 -07001422 if (const auto handle = mScheduler->enableVSyncInjection(enable)) {
1423 mEventQueue->setEventConnection(
1424 mScheduler->getEventConnection(enable ? handle : mSfConnectionHandle));
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001425 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001426 }).wait();
Dominik Laskowski8c001672018-05-30 16:52:06 -07001427
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001428 return NO_ERROR;
1429}
1430
1431status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001432 Mutex::Autolock lock(mStateLock);
Ady Abraham5facfb12020-04-22 15:18:31 -07001433 return mScheduler->injectVSync(when, calculateExpectedPresentTime(when)) ? NO_ERROR : BAD_VALUE;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001434}
1435
Vishnu Nair43bccf82020-06-05 10:53:37 -07001436status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) {
Kalle Raitaa099a242017-01-11 11:17:29 -08001437 outLayers->clear();
Vishnu Nair43bccf82020-06-05 10:53:37 -07001438 schedule([=] {
1439 const auto display = ON_MAIN_THREAD(getDefaultDisplayDeviceLocked());
1440 mDrawingState.traverseInZOrder([&](Layer* layer) {
1441 outLayers->push_back(layer->getLayerDebugInfo(display.get()));
1442 });
1443 }).wait();
Kalle Raitaa099a242017-01-11 11:17:29 -08001444 return NO_ERROR;
1445}
1446
Peiyong Linc6780972018-10-28 15:24:08 -07001447status_t SurfaceFlinger::getCompositionPreference(
1448 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1449 Dataspace* outWideColorGamutDataspace,
1450 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001451 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001452 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001453 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001454 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001455 return NO_ERROR;
1456}
1457
Dan Stozaec460082018-12-17 15:35:09 -08001458status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1459 const sp<IBinder>& stopLayerHandle,
1460 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001461 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001462 return BAD_VALUE;
1463 }
Alec Mouri9a02eda2020-04-21 17:39:34 -07001464
1465 const wp<Layer> stopLayer = fromHandle(stopLayerHandle);
1466 mRegionSamplingThread->addListener(samplingArea, stopLayer, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001467 return NO_ERROR;
1468}
1469
Dan Stozaec460082018-12-17 15:35:09 -08001470status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001471 if (!listener) {
1472 return BAD_VALUE;
1473 }
Dan Stozaec460082018-12-17 15:35:09 -08001474 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001475 return NO_ERROR;
1476}
Dan Gittik57e63c52019-01-18 16:37:54 +00001477
1478status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1479 bool* outSupport) const {
1480 if (!displayToken || !outSupport) {
1481 return BAD_VALUE;
1482 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001483
1484 Mutex::Autolock lock(mStateLock);
1485
Dan Gittik57e63c52019-01-18 16:37:54 +00001486 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1487 if (!displayId) {
1488 return NAME_NOT_FOUND;
1489 }
1490 *outSupport =
Peiyong Line9d809e2020-04-14 13:10:48 -07001491 getHwComposer().hasDisplayCapability(*displayId, hal::DisplayCapability::BRIGHTNESS);
Dan Gittik57e63c52019-01-18 16:37:54 +00001492 return NO_ERROR;
1493}
1494
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001495status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken, float brightness) {
Dan Gittik57e63c52019-01-18 16:37:54 +00001496 if (!displayToken) {
1497 return BAD_VALUE;
1498 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001499
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07001500 return promise::chain(schedule([=]() MAIN_THREAD {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001501 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1502 return getHwComposer().setDisplayBrightness(*displayId, brightness);
1503 } else {
1504 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
Dominik Laskowski5690bde2020-04-23 19:04:22 -07001505 return promise::yield<status_t>(NAME_NOT_FOUND);
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001506 }
Dominik Laskowski5690bde2020-04-23 19:04:22 -07001507 }))
1508 .then([](std::future<status_t> task) { return task; })
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07001509 .get();
Dan Gittik57e63c52019-01-18 16:37:54 +00001510}
1511
Lais Andrade3a6e47d2020-04-02 11:20:16 +01001512status_t SurfaceFlinger::notifyPowerBoost(int32_t boostId) {
1513 Boost powerBoost = static_cast<Boost>(boostId);
Ady Abraham8532d012019-05-08 14:50:56 -07001514
Lais Andrade3a6e47d2020-04-02 11:20:16 +01001515 if (powerBoost == Boost::INTERACTION) {
Ady Abraham8532d012019-05-08 14:50:56 -07001516 mScheduler->notifyTouchEvent();
1517 }
1518
1519 return NO_ERROR;
1520}
1521
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001522// ----------------------------------------------------------------------------
1523
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001524sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001525 ISurfaceComposer::VsyncSource vsyncSource, ISurfaceComposer::ConfigChanged configChanged) {
Ana Krulecc2870422019-01-29 19:00:58 -08001526 const auto& handle =
1527 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001528
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001529 return mScheduler->createDisplayEventConnection(handle, configChanged);
Mathias Agopianbb641242010-05-18 17:06:55 -07001530}
1531
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001532void SurfaceFlinger::signalTransaction() {
Ady Abraham8532d012019-05-08 14:50:56 -07001533 mScheduler->resetIdleTimer();
Dan Stoza030fbc12020-02-19 15:32:01 -08001534 mPowerAdvisor.notifyDisplayUpdateImminent();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001535 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001536}
1537
1538void SurfaceFlinger::signalLayerUpdate() {
Ady Abraham8532d012019-05-08 14:50:56 -07001539 mScheduler->resetIdleTimer();
Dan Stoza030fbc12020-02-19 15:32:01 -08001540 mPowerAdvisor.notifyDisplayUpdateImminent();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001541 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001542}
1543
1544void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001545 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001546 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001547}
1548
Dominik Laskowski83b88212018-12-11 13:34:06 -08001549nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001550 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001551 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1552 return 0;
1553 }
1554
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001555 return getHwComposer().getDisplayVsyncPeriod(*displayId);
Dominik Laskowski83b88212018-12-11 13:34:06 -08001556}
1557
Peiyong Line9d809e2020-04-14 13:10:48 -07001558void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hal::HWDisplayId hwcDisplayId,
Ady Abraham7159f572019-10-11 11:10:18 -07001559 int64_t timestamp,
Peiyong Line9d809e2020-04-14 13:10:48 -07001560 std::optional<hal::VsyncPeriodNanos> vsyncPeriod) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001561 ATRACE_NAME("SF onVsync");
1562
Steven Thomas3cfac282017-02-06 12:29:30 -08001563 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001564 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001565 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001566 return;
1567 }
1568
Dominik Laskowski075d3172018-05-24 15:50:06 -07001569 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001570 return;
1571 }
1572
Dominik Laskowski075d3172018-05-24 15:50:06 -07001573 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001574 // For now, we don't do anything with external display vsyncs.
1575 return;
1576 }
1577
Alec Mourif8e689c2019-05-20 18:32:22 -07001578 bool periodFlushed = false;
Ady Abraham5dee2f12020-02-05 17:49:47 -08001579 mScheduler->addResyncSample(timestamp, vsyncPeriod, &periodFlushed);
Alec Mourif8e689c2019-05-20 18:32:22 -07001580 if (periodFlushed) {
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001581 mVSyncModulator->onRefreshRateChangeCompleted();
Alec Mouri754c98a2019-03-18 18:53:42 -07001582 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001583}
1584
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001585void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001586 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1587 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001588}
1589
Ady Abraham2139f732019-11-13 18:56:40 -08001590bool SurfaceFlinger::isDisplayConfigAllowed(HwcConfigIndexType configId) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001591 return mRefreshRateConfigs->isConfigAllowed(configId);
Ady Abraham838de062019-02-04 10:24:03 -08001592}
1593
Ady Abraham2139f732019-11-13 18:56:40 -08001594void SurfaceFlinger::changeRefreshRateLocked(const RefreshRate& refreshRate,
1595 Scheduler::ConfigEvent event) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001596 const auto display = getDefaultDisplayDeviceLocked();
1597 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001598 return;
1599 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001600 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001601
Ana Krulec7d1d6832018-12-27 11:10:09 -08001602 // Don't do any updating if the current fps is the same as the new one.
Ady Abrahamabc27602020-04-08 17:20:29 -07001603 if (!isDisplayConfigAllowed(refreshRate.getConfigId())) {
Ady Abraham2139f732019-11-13 18:56:40 -08001604 ALOGV("Skipping config %d as it is not part of allowed configs",
Ady Abrahamabc27602020-04-08 17:20:29 -07001605 refreshRate.getConfigId().value());
Ady Abraham1902d072019-03-01 17:18:59 -08001606 return;
1607 }
1608
Ady Abrahamabc27602020-04-08 17:20:29 -07001609 setDesiredActiveConfig({refreshRate.getConfigId(), event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001610}
1611
Peiyong Line9d809e2020-04-14 13:10:48 -07001612void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hal::HWDisplayId hwcDisplayId,
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07001613 hal::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001614 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Peiyong Line9d809e2020-04-14 13:10:48 -07001615 connection == hal::Connection::CONNECTED ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001616
Lloyd Piqueba04e622017-12-14 17:11:26 -08001617 // Ignore events that do not have the right sequenceId.
1618 if (sequenceId != getBE().mComposerSequenceId) {
1619 return;
1620 }
1621
Steven Thomasb02664d2017-07-26 18:48:28 -07001622 // Only lock if we're not on the main thread. This function is normally
1623 // called on a hwbinder thread, but for the primary display it's called on
1624 // the main thread with the state lock already held, so don't attempt to
1625 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001626 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001627
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001628 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001629
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001630 if (std::this_thread::get_id() == mMainThreadId) {
1631 // Process all pending hot plug events immediately if we are on the main thread.
1632 processDisplayHotplugEventsLocked();
1633 }
1634
Lloyd Piqueba04e622017-12-14 17:11:26 -08001635 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001636}
1637
Ady Abraham7159f572019-10-11 11:10:18 -07001638void SurfaceFlinger::onVsyncPeriodTimingChangedReceived(
Peiyong Line9d809e2020-04-14 13:10:48 -07001639 int32_t sequenceId, hal::HWDisplayId /*display*/,
1640 const hal::VsyncPeriodChangeTimeline& updatedTimeline) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001641 Mutex::Autolock lock(mStateLock);
1642 if (sequenceId != getBE().mComposerSequenceId) {
1643 return;
1644 }
1645 mScheduler->onNewVsyncPeriodChangeTimeline(updatedTimeline);
Ady Abraham7159f572019-10-11 11:10:18 -07001646}
1647
Peiyong Line9d809e2020-04-14 13:10:48 -07001648void SurfaceFlinger::onSeamlessPossible(int32_t /*sequenceId*/, hal::HWDisplayId /*display*/) {
Ady Abrahamb0433bc2020-01-08 17:31:06 -08001649 // TODO(b/142753666): use constraints when calling to setActiveConfigWithConstrains and
1650 // use this callback to know when to retry in case of SEAMLESS_NOT_POSSIBLE.
1651}
1652
Peiyong Line9d809e2020-04-14 13:10:48 -07001653void SurfaceFlinger::onRefreshReceived(int sequenceId, hal::HWDisplayId /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001654 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001655 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001656 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001657 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001658 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001659}
1660
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001661void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001662 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001663
1664 // Enable / Disable HWVsync from the main thread to avoid race conditions with
1665 // display power state.
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07001666 static_cast<void>(schedule([=]() MAIN_THREAD { setPrimaryVsyncEnabledInternal(enabled); }));
Ady Abraham9ba25122019-06-03 17:10:55 -07001667}
1668
1669void SurfaceFlinger::setPrimaryVsyncEnabledInternal(bool enabled) {
1670 ATRACE_CALL();
1671
Peiyong Line9d809e2020-04-14 13:10:48 -07001672 mHWCVsyncPendingState = enabled ? hal::Vsync::ENABLE : hal::Vsync::DISABLE;
Ady Abraham27c70212019-06-11 10:52:26 -07001673
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001674 if (const auto displayId = getInternalDisplayIdLocked()) {
Ady Abraham9ba25122019-06-03 17:10:55 -07001675 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
1676 if (display && display->isPoweredOn()) {
Marin Shalamanovc75b0772020-06-12 22:29:11 +02001677 getHwComposer().setVsyncEnabled(*displayId, mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001678 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001679 }
Mathias Agopian86303202012-07-24 22:46:10 -07001680}
1681
Steven Thomasb02664d2017-07-26 18:48:28 -07001682void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001683 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001684 // Clear the drawing state so that the logic inside of
1685 // handleTransactionLocked will fire. It will determine the delta between
1686 // mCurrentState and mDrawingState and re-apply all changes when we make the
1687 // transition.
1688 mDrawingState.displays.clear();
1689 mDisplays.clear();
1690}
1691
Steven Thomas050b2c82017-03-06 11:45:16 -08001692void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001693 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001694 if (!mVrFlinger)
1695 return;
1696 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001697 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001698 return;
1699 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001700
Lloyd Pique441d5042018-10-18 16:49:51 -07001701 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001702 ALOGE("Vr flinger is only supported for remote hardware composer"
1703 " service connections. Ignoring request to transition to vr"
1704 " flinger.");
1705 mVrFlingerRequestsDisplay = false;
1706 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001707 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001708
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001709 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001710
Steven Thomas0123ac62018-07-12 11:32:34 -07001711 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001712 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001713
Peiyong Lin65248e02020-04-18 21:15:07 -07001714 const hal::PowerMode currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001715
1716 // Clear out all the output layers from the composition engine for all
1717 // displays before destroying the hardware composer interface. This ensures
1718 // any HWC layers are destroyed through that interface before it becomes
1719 // invalid.
1720 for (const auto& [token, displayDevice] : mDisplays) {
Lloyd Pique01c77c12019-04-17 12:48:32 -07001721 displayDevice->getCompositionDisplay()->clearOutputLayers();
Lloyd Pique07e33212018-12-18 16:33:37 -08001722 }
1723
Steven Thomas0123ac62018-07-12 11:32:34 -07001724 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1725 // called below. Clear the reference now so we don't accidentally use it
1726 // later.
1727 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001728
Steven Thomasb02664d2017-07-26 18:48:28 -07001729 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001730 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001731 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001732
Steven Thomasb02664d2017-07-26 18:48:28 -07001733 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001734 // Delete the current instance before creating the new one
1735 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1736 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1737 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
Lloyd Pique4603f3c2020-02-11 12:06:56 -08001738 mCompositionEngine->getHwComposer().setConfiguration(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001739
Lloyd Pique441d5042018-10-18 16:49:51 -07001740 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001741 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001742
1743 if (vrFlingerRequestsDisplay) {
1744 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001745 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001746
1747 mVisibleRegionsDirty = true;
1748 invalidateHwcGeometry();
1749
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001750 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001751 display = getDefaultDisplayDeviceLocked();
1752 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001753 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001754
Steven Thomasb02664d2017-07-26 18:48:28 -07001755 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001756 const nsecs_t vsyncPeriod = getVsyncPeriod();
1757 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001758
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001759 // The present fences returned from vr_hwc are not an accurate
1760 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001761 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001762
Steven Thomasb02664d2017-07-26 18:48:28 -07001763 // Use phase of 0 since phase is not known.
1764 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001765 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001766 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001767
Ana Krulecc2870422019-01-29 19:00:58 -08001768 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001769
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001770 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001771 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001772}
1773
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07001774sp<Fence> SurfaceFlinger::previousFrameFence() {
Ady Abrahambe0f9482019-04-24 15:41:53 -07001775 // We are storing the last 2 present fences. If sf's phase offset is to be
1776 // woken up before the actual vsync but targeting the next vsync, we need to check
1777 // fence N-2
Alec Mouri6d414b52020-03-17 11:18:05 -07001778 return mVSyncModulator->getOffsets().sf > 0 ? mPreviousPresentFences[0]
1779 : mPreviousPresentFences[1];
1780}
1781
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07001782bool SurfaceFlinger::previousFramePending(int graceTimeMs) {
Alec Mouri6d414b52020-03-17 11:18:05 -07001783 ATRACE_CALL();
1784 const sp<Fence>& fence = previousFrameFence();
Ady Abrahambe0f9482019-04-24 15:41:53 -07001785
Ady Abraham11579302019-09-19 12:35:58 -07001786 if (fence == Fence::NO_FENCE) {
1787 return false;
1788 }
1789
Dan Stoza59083052020-04-28 10:13:20 -07001790 const status_t status = fence->wait(graceTimeMs);
1791 // This is the same as Fence::Status::Unsignaled, but it saves a getStatus() call,
1792 // which calls wait(0) again internally
1793 return status == -ETIME;
Ady Abrahambe0f9482019-04-24 15:41:53 -07001794}
1795
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07001796nsecs_t SurfaceFlinger::previousFramePresentTime() {
Alec Mouri6d414b52020-03-17 11:18:05 -07001797 const sp<Fence>& fence = previousFrameFence();
1798
1799 if (fence == Fence::NO_FENCE) {
1800 return Fence::SIGNAL_TIME_INVALID;
1801 }
1802
1803 return fence->getSignalTime();
1804}
1805
Ady Abraham5facfb12020-04-22 15:18:31 -07001806nsecs_t SurfaceFlinger::calculateExpectedPresentTime(nsecs_t now) const {
Alec Mouriaa614192019-06-06 13:28:34 -07001807 DisplayStatInfo stats;
1808 mScheduler->getDisplayStatInfo(&stats);
Ady Abraham5facfb12020-04-22 15:18:31 -07001809 const nsecs_t presentTime = mScheduler->getDispSyncExpectedPresentTime(now);
Alec Mouriaa614192019-06-06 13:28:34 -07001810 // Inflate the expected present time if we're targetting the next vsync.
Ady Abraham5facfb12020-04-22 15:18:31 -07001811 return mVSyncModulator->getOffsets().sf > 0 ? presentTime : presentTime + stats.vsyncPeriod;
Alec Mouriaa614192019-06-06 13:28:34 -07001812}
1813
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07001814void SurfaceFlinger::onMessageReceived(int32_t what, nsecs_t expectedVSyncTime) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001815 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001816 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001817 case MessageQueue::INVALIDATE: {
Dan Stoza28d46a52020-04-28 09:54:54 -07001818 onMessageInvalidate(expectedVSyncTime);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001819 break;
1820 }
1821 case MessageQueue::REFRESH: {
Dan Stoza28d46a52020-04-28 09:54:54 -07001822 onMessageRefresh();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001823 break;
1824 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001825 }
1826}
1827
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07001828void SurfaceFlinger::onMessageInvalidate(nsecs_t expectedVSyncTime) {
Dan Stoza28d46a52020-04-28 09:54:54 -07001829 ATRACE_CALL();
1830
1831 const nsecs_t frameStart = systemTime();
1832 // calculate the expected present time once and use the cached
1833 // value throughout this frame to make sure all layers are
1834 // seeing this same value.
1835 const nsecs_t lastExpectedPresentTime = mExpectedPresentTime.load();
1836 mExpectedPresentTime = expectedVSyncTime;
1837
1838 // When Backpressure propagation is enabled we want to give a small grace period
1839 // for the present fence to fire instead of just giving up on this frame to handle cases
1840 // where present fence is just about to get signaled.
1841 const int graceTimeForPresentFenceMs =
1842 (mPropagateBackpressure &&
1843 (mPropagateBackpressureClientComposition || !mHadClientComposition))
1844 ? 1
1845 : 0;
1846
1847 // Pending frames may trigger backpressure propagation.
1848 const TracedOrdinal<bool> framePending = {"PrevFramePending",
1849 previousFramePending(graceTimeForPresentFenceMs)};
1850
1851 // Frame missed counts for metrics tracking.
1852 // A frame is missed if the prior frame is still pending. If no longer pending,
1853 // then we still count the frame as missed if the predicted present time
1854 // was further in the past than when the fence actually fired.
1855
1856 // Add some slop to correct for drift. This should generally be
1857 // smaller than a typical frame duration, but should not be so small
1858 // that it reports reasonable drift as a missed frame.
1859 DisplayStatInfo stats;
1860 mScheduler->getDisplayStatInfo(&stats);
1861 const nsecs_t frameMissedSlop = stats.vsyncPeriod / 2;
1862 const nsecs_t previousPresentTime = previousFramePresentTime();
1863 const TracedOrdinal<bool> frameMissed = {"PrevFrameMissed",
1864 framePending ||
1865 (previousPresentTime >= 0 &&
1866 (lastExpectedPresentTime <
1867 previousPresentTime - frameMissedSlop))};
1868 const TracedOrdinal<bool> hwcFrameMissed = {"PrevHwcFrameMissed",
1869 mHadDeviceComposition && frameMissed};
1870 const TracedOrdinal<bool> gpuFrameMissed = {"PrevGpuFrameMissed",
1871 mHadClientComposition && frameMissed};
1872
1873 if (frameMissed) {
1874 mFrameMissedCount++;
1875 mTimeStats->incrementMissedFrames();
1876 if (mMissedFrameJankCount == 0) {
1877 mMissedFrameJankStart = systemTime();
1878 }
1879 mMissedFrameJankCount++;
1880 }
1881
1882 if (hwcFrameMissed) {
1883 mHwcFrameMissedCount++;
1884 }
1885
1886 if (gpuFrameMissed) {
1887 mGpuFrameMissedCount++;
1888 }
1889
1890 // If we are in the middle of a config change and the fence hasn't
1891 // fired yet just wait for the next invalidate
1892 if (mSetActiveConfigPending) {
1893 if (framePending) {
1894 mEventQueue->invalidate();
1895 return;
1896 }
1897
1898 // We received the present fence from the HWC, so we assume it successfully updated
1899 // the config, hence we update SF.
1900 mSetActiveConfigPending = false;
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07001901 ON_MAIN_THREAD(setActiveConfigInternal());
Dan Stoza28d46a52020-04-28 09:54:54 -07001902 }
1903
1904 if (framePending && mPropagateBackpressure) {
1905 if ((hwcFrameMissed && !gpuFrameMissed) || mPropagateBackpressureClientComposition) {
1906 signalLayerUpdate();
1907 return;
1908 }
1909 }
1910
1911 // Our jank window is always at least 100ms since we missed a
1912 // frame...
1913 static constexpr nsecs_t kMinJankyDuration =
1914 std::chrono::duration_cast<std::chrono::nanoseconds>(100ms).count();
1915 // ...but if it's larger than 1s then we missed the trace cutoff.
1916 static constexpr nsecs_t kMaxJankyDuration =
1917 std::chrono::duration_cast<std::chrono::nanoseconds>(1s).count();
Alec Mouri1b6a60c2020-06-08 13:54:24 -07001918 nsecs_t jankDurationToUpload = -1;
Dan Stoza28d46a52020-04-28 09:54:54 -07001919 // If we're in a user build then don't push any atoms
1920 if (!mIsUserBuild && mMissedFrameJankCount > 0) {
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07001921 const auto display = ON_MAIN_THREAD(getDefaultDisplayDeviceLocked());
Dan Stoza28d46a52020-04-28 09:54:54 -07001922 // Only report jank when the display is on, as displays in DOZE
1923 // power mode may operate at a different frame rate than is
1924 // reported in their config, which causes noticeable (but less
1925 // severe) jank.
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07001926 if (display && display->getPowerMode() == hal::PowerMode::ON) {
Dan Stoza28d46a52020-04-28 09:54:54 -07001927 const nsecs_t currentTime = systemTime();
1928 const nsecs_t jankDuration = currentTime - mMissedFrameJankStart;
1929 if (jankDuration > kMinJankyDuration && jankDuration < kMaxJankyDuration) {
Alec Mouri1b6a60c2020-06-08 13:54:24 -07001930 jankDurationToUpload = jankDuration;
Dan Stoza28d46a52020-04-28 09:54:54 -07001931 }
1932
1933 // We either reported a jank event or we missed the trace
1934 // window, so clear counters here.
1935 if (jankDuration > kMinJankyDuration) {
1936 mMissedFrameJankCount = 0;
1937 mMissedFrameJankStart = 0;
1938 }
1939 }
1940 }
1941
1942 // Now that we're going to make it to the handleMessageTransaction()
1943 // call below it's safe to call updateVrFlinger(), which will
1944 // potentially trigger a display handoff.
1945 updateVrFlinger();
1946
1947 if (mTracingEnabledChanged) {
1948 mTracingEnabled = mTracing.isEnabled();
1949 mTracingEnabledChanged = false;
1950 }
1951
1952 bool refreshNeeded;
1953 {
1954 ConditionalLockGuard<std::mutex> lock(mTracingLock, mTracingEnabled);
1955
1956 refreshNeeded = handleMessageTransaction();
1957 refreshNeeded |= handleMessageInvalidate();
1958 if (mTracingEnabled) {
1959 mAddCompositionStateToTrace =
1960 mTracing.flagIsSetLocked(SurfaceTracing::TRACE_COMPOSITION);
1961 if (mVisibleRegionsDirty && !mAddCompositionStateToTrace) {
1962 mTracing.notifyLocked("visibleRegionsDirty");
1963 }
1964 }
1965 }
1966
1967 // Layers need to get updated (in the previous line) before we can use them for
1968 // choosing the refresh rate.
1969 // Hold mStateLock as chooseRefreshRateForContent promotes wp<Layer> to sp<Layer>
1970 // and may eventually call to ~Layer() if it holds the last reference
1971 {
1972 Mutex::Autolock _l(mStateLock);
1973 mScheduler->chooseRefreshRateForContent();
1974 }
1975
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07001976 ON_MAIN_THREAD(performSetActiveConfig());
Dan Stoza28d46a52020-04-28 09:54:54 -07001977
1978 updateCursorAsync();
1979 updateInputFlinger();
1980
1981 refreshNeeded |= mRepaintEverything;
1982 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Alec Mouri1b6a60c2020-06-08 13:54:24 -07001983 mLastJankDuration = jankDurationToUpload;
Dan Stoza28d46a52020-04-28 09:54:54 -07001984 // Signal a refresh if a transaction modified the window state,
1985 // a new buffer was latched, or if HWC has requested a full
1986 // repaint
1987 if (mFrameStartTime <= 0) {
1988 // We should only use the time of the first invalidate
1989 // message that signals a refresh as the beginning of the
1990 // frame. Otherwise the real frame time will be
1991 // underestimated.
1992 mFrameStartTime = frameStart;
1993 }
1994 signalRefresh();
1995 }
1996}
1997
Dan Stoza6b9454d2014-11-07 16:00:59 -08001998bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001999 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002000 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07002001
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002002 bool flushedATransaction = flushTransactionQueues();
2003
Valerie Hau47826a72020-06-15 12:34:40 -07002004 bool runHandleTransaction =
2005 (transactionFlags && (transactionFlags != eTransactionFlushNeeded)) ||
2006 flushedATransaction;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002007
2008 if (runHandleTransaction) {
2009 handleTransaction(eTransactionMask);
2010 } else {
2011 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07002012 }
2013
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002014 if (transactionFlushNeeded()) {
2015 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002016 }
Marissa Wall713b63f2018-10-17 15:42:43 -07002017
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002018 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002019}
2020
Dan Stoza28d46a52020-04-28 09:54:54 -07002021void SurfaceFlinger::onMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002022 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07002023
Dan Stoza2b6d38e2017-06-01 16:40:30 -07002024 mRefreshPending = false;
2025
Lloyd Piqueab039b52019-02-13 14:22:42 -08002026 compositionengine::CompositionRefreshArgs refreshArgs;
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002027 const auto& displays = ON_MAIN_THREAD(mDisplays);
2028 refreshArgs.outputs.reserve(displays.size());
2029 for (const auto& [_, display] : displays) {
Lloyd Piqueab039b52019-02-13 14:22:42 -08002030 refreshArgs.outputs.push_back(display->getCompositionDisplay());
2031 }
2032 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08002033 if (auto layerFE = layer->getCompositionEngineLayerFE())
2034 refreshArgs.layers.push_back(layerFE);
Lloyd Piqueab039b52019-02-13 14:22:42 -08002035 });
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002036 refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
2037 for (sp<Layer> layer : mLayersWithQueuedFrames) {
Lloyd Piquede196652020-01-22 17:29:58 -08002038 if (auto layerFE = layer->getCompositionEngineLayerFE())
2039 refreshArgs.layersWithQueuedFrames.push_back(layerFE);
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002040 }
2041
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08002042 refreshArgs.repaintEverything = mRepaintEverything.exchange(false);
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002043 refreshArgs.outputColorSetting = useColorManagement
2044 ? mDisplayColorSetting
2045 : compositionengine::OutputColorSetting::kUnmanaged;
2046 refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
2047 refreshArgs.forceOutputColorMode = mForceColorMode;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002048
2049 refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
2050 refreshArgs.updatingGeometryThisFrame = mGeometryInvalid || mVisibleRegionsDirty;
Lucas Dupin2dd6f392020-02-18 17:43:36 -08002051 refreshArgs.blursAreExpensive = mBlursAreExpensive;
Snild Dolkow9e217d62020-04-22 15:53:42 +02002052 refreshArgs.internalDisplayRotationFlags = DisplayDevice::getPrimaryDisplayRotationFlags();
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002053
2054 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
2055 refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
2056 mDrawingState.colorMatrixChanged = false;
2057 }
2058
2059 refreshArgs.devOptForceClientComposition = mDebugDisableHWC || mDebugRegion;
2060
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08002061 if (mDebugRegion != 0) {
2062 refreshArgs.devOptFlashDirtyRegionsDelay =
2063 std::chrono::milliseconds(mDebugRegion > 1 ? mDebugRegion : 0);
2064 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08002065
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002066 mGeometryInvalid = false;
2067
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002068 // Store the present time just before calling to the composition engine so we could notify
2069 // the scheduler.
2070 const auto presentTime = systemTime();
2071
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002072 mCompositionEngine->present(refreshArgs);
Alec Mouri9519bf12019-11-15 16:54:44 -08002073 mTimeStats->recordFrameDuration(mFrameStartTime, systemTime());
2074 // Reset the frame start time now that we've recorded this frame.
2075 mFrameStartTime = 0;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002076
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002077 mScheduler->onDisplayRefreshed(presentTime);
2078
David Sodmanfa9b2af2017-12-24 13:28:59 -08002079 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08002080 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07002081
Alec Mouri8f7a0102020-04-15 12:11:10 -07002082 const bool prevFrameHadDeviceComposition = mHadDeviceComposition;
2083
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002084 mHadClientComposition = std::any_of(displays.cbegin(), displays.cend(), [](const auto& pair) {
2085 const auto& state = pair.second->getCompositionDisplay()->getState();
2086 return state.usesClientComposition && !state.reusedClientComposition;
2087 });
2088 mHadDeviceComposition = std::any_of(displays.cbegin(), displays.cend(), [](const auto& pair) {
2089 const auto& state = pair.second->getCompositionDisplay()->getState();
2090 return state.usesDeviceComposition;
2091 });
Vishnu Nair9b079a22020-01-21 14:36:08 -08002092 mReusedClientComposition =
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002093 std::any_of(displays.cbegin(), displays.cend(), [](const auto& pair) {
2094 const auto& state = pair.second->getCompositionDisplay()->getState();
2095 return state.reusedClientComposition;
Vishnu Nair9b079a22020-01-21 14:36:08 -08002096 });
David Sodmanfa9b2af2017-12-24 13:28:59 -08002097
Alec Mouri8f7a0102020-04-15 12:11:10 -07002098 // Only report a strategy change if we move in and out of composition with hw overlays
2099 if (prevFrameHadDeviceComposition != mHadDeviceComposition) {
2100 mTimeStats->incrementCompositionStrategyChanges();
2101 }
2102
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002103 mVSyncModulator->onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07002104
David Sodman7e4ae112018-02-09 15:02:28 -08002105 mLayersWithQueuedFrames.clear();
Vishnu Nairdf529052019-06-07 14:53:14 -07002106 if (mVisibleRegionsDirty) {
2107 mVisibleRegionsDirty = false;
Vishnu Nair60db8c02020-04-02 11:55:16 -07002108 if (mTracingEnabled && mAddCompositionStateToTrace) {
Vishnu Nairdf529052019-06-07 14:53:14 -07002109 mTracing.notify("visibleRegionsDirty");
2110 }
2111 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08002112
2113 if (mCompositionEngine->needsAnotherUpdate()) {
2114 signalLayerUpdate();
2115 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002116}
Mathias Agopian4fec8732012-06-29 14:12:52 -07002117
David Sodmanfa9b2af2017-12-24 13:28:59 -08002118bool SurfaceFlinger::handleMessageInvalidate() {
2119 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002120 bool refreshNeeded = handlePageFlip();
2121
Vishnu Nair4351ad52019-02-11 14:13:02 -08002122 if (mVisibleRegionsDirty) {
2123 computeLayerBounds();
2124 }
2125
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002126 for (auto& layer : mLayersPendingRefresh) {
2127 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002128 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002129 invalidateLayerStack(layer, visibleReg);
2130 }
2131 mLayersPendingRefresh.clear();
2132 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002133}
2134
Ana Krulece588e312018-09-18 12:32:24 -07002135void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
2136 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002137 // Update queue of past composite+present times and determine the
2138 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08002139 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002140 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08002141 while (!getBE().mCompositePresentTimes.empty()) {
2142 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002143 // Cached values should have been updated before calling this method,
2144 // which helps avoid duplicate syscalls.
2145 nsecs_t displayTime = cpt.display->getCachedSignalTime();
2146 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
2147 break;
2148 }
2149 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08002150 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002151 }
2152
2153 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08002154 while (getBE().mCompositePresentTimes.size() > 16) {
2155 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002156 }
2157
Ana Krulece588e312018-09-18 12:32:24 -07002158 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08002159}
2160
Ana Krulece588e312018-09-18 12:32:24 -07002161void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
2162 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002163 // Integer division and modulo round toward 0 not -inf, so we need to
2164 // treat negative and positive offsets differently.
Ady Abraham9e16a482019-12-03 17:19:41 -08002165 nsecs_t idealLatency = (mPhaseConfiguration->getCurrentOffsets().late.sf > 0)
2166 ? (stats.vsyncPeriod -
2167 (mPhaseConfiguration->getCurrentOffsets().late.sf % stats.vsyncPeriod))
2168 : ((-mPhaseConfiguration->getCurrentOffsets().late.sf) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002169
Ady Abraham9e16a482019-12-03 17:19:41 -08002170 // Just in case mPhaseConfiguration->getCurrentOffsets().late.sf == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08002171 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07002172 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08002173 }
2174
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002175 // Snap the latency to a value that removes scheduling jitter from the
2176 // composition and present times, which often have >1ms of jitter.
2177 // Reducing jitter is important if an app attempts to extrapolate
2178 // something (such as user input) to an accurate diasplay time.
Ady Abraham9e16a482019-12-03 17:19:41 -08002179 // Snapping also allows an app to precisely calculate
2180 // mPhaseConfiguration->getCurrentOffsets().late.sf with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07002181 nsecs_t bias = stats.vsyncPeriod / 2;
2182 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
2183 nsecs_t snappedCompositeToPresentLatency =
2184 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002185
David Sodman99974d22017-11-28 12:04:33 -08002186 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002187 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
2188 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002189 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002190}
2191
David Sodman2b406362017-12-15 13:33:47 -08002192void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002193{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002194 ATRACE_CALL();
2195 ALOGV("postComposition");
2196
Brian Andersonf6386862016-10-31 16:34:13 -07002197 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002198 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002199 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002200 }
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002201
2202 const auto* display = ON_MAIN_THREAD(getDefaultDisplayDeviceLocked()).get();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002203
David Sodman73beded2017-11-15 11:56:06 -08002204 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002205 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002206 if (display && display->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002207 glCompositionDoneFenceTime =
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002208 std::make_shared<FenceTime>(display->getCompositionDisplay()
Lloyd Pique31cb2942018-10-19 17:23:03 -07002209 ->getRenderSurface()
2210 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002211 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002212 } else {
2213 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2214 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002215
David Sodman73beded2017-11-15 11:56:06 -08002216 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07002217 mPreviousPresentFences[1] = mPreviousPresentFences[0];
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002218 mPreviousPresentFences[0] =
2219 display ? getHwComposer().getPresentFence(*display->getId()) : Fence::NO_FENCE;
Ady Abrahambe0f9482019-04-24 15:41:53 -07002220 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08002221 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002222
Ana Krulece588e312018-09-18 12:32:24 -07002223 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08002224 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002225
Lloyd Piqueab039b52019-02-13 14:22:42 -08002226 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
2227 // be sampled a little later than when we started doing work for this frame,
2228 // but that should be okay since updateCompositorTiming has snapping logic.
2229 updateCompositorTiming(stats, mCompositionEngine->getLastFrameRefreshTimestamp(),
2230 presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002231 CompositorTiming compositorTiming;
2232 {
David Sodman99974d22017-11-28 12:04:33 -08002233 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2234 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002235 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002236
Edgar Arriaga844fa672020-01-16 14:21:42 -08002237 mDrawingState.traverse([&](Layer* layer) {
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002238 const bool frameLatched = layer->onPostComposition(display, glCompositionDoneFenceTime,
2239 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07002240 if (frameLatched) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002241 recordBufferingStats(layer->getName(), layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002242 }
Robert Carr2047fae2016-11-28 14:09:09 -08002243 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002244
Valerie Hau4b678442020-04-14 10:50:42 -07002245 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
2246 mTransactionCompletedThread.sendCallbacks();
2247
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002248 if (display && display->isPrimary() && display->getPowerMode() == hal::PowerMode::ON &&
2249 presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002250 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002251 }
2252
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002253 const bool isDisplayConnected = display && getHwComposer().isConnected(*display->getId());
2254
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002255 if (!hasSyncFramework) {
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002256 if (isDisplayConnected && display->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002257 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002258 }
2259 }
2260
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002261 if (mAnimCompositionPending) {
2262 mAnimCompositionPending = false;
2263
Brian Anderson4e606e32017-03-16 15:34:57 -07002264 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002265 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002266 std::move(presentFenceTime));
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002267 } else if (isDisplayConnected) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002268 // The HWC doesn't support present fences, so use the refresh
2269 // timestamp instead.
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002270 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(*display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002271 mAnimFrameTracker.setActualPresentTime(presentTime);
2272 }
2273 mAnimFrameTracker.advanceFrame();
2274 }
Dan Stozab90cf072015-03-05 11:05:59 -08002275
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002276 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002277 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002278 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002279 }
2280
Vishnu Nair9b079a22020-01-21 14:36:08 -08002281 if (mReusedClientComposition) {
2282 mTimeStats->incrementClientCompositionReusedFrames();
2283 }
2284
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002285 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002286
Alec Mouri717bcb62020-02-10 17:07:19 -08002287 const size_t sfConnections = mScheduler->getEventThreadConnectionCount(mSfConnectionHandle);
2288 const size_t appConnections = mScheduler->getEventThreadConnectionCount(mAppConnectionHandle);
2289 mTimeStats->recordDisplayEventConnectionCount(sfConnections + appConnections);
2290
Alec Mouri1b6a60c2020-06-08 13:54:24 -07002291 if (mLastJankDuration > 0) {
2292 ATRACE_NAME("Jank detected");
2293 const int32_t jankyDurationMillis = mLastJankDuration / (1000 * 1000);
2294 android::util::stats_write(android::util::DISPLAY_JANK_REPORTED, jankyDurationMillis,
2295 mMissedFrameJankCount);
2296 mLastJankDuration = -1;
2297 }
2298
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002299 if (isDisplayConnected && !display->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002300 return;
2301 }
2302
2303 nsecs_t currentTime = systemTime();
2304 if (mHasPoweredOff) {
2305 mHasPoweredOff = false;
2306 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002307 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002308 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002309 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2310 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002311 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002312 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002313 }
David Sodman4a36e932017-11-07 14:29:47 -08002314 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002315 }
David Sodman4a36e932017-11-07 14:29:47 -08002316 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002317
Lingfeng Yang2e4fef62020-04-24 14:48:43 +00002318 // Cleanup any outstanding resources due to rendering a prior frame.
2319 getRenderEngine().cleanupPostRender();
2320
Dan Stoza436ccf32018-06-21 12:10:12 -07002321 {
2322 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002323 if (mTexturePool.size() < mTexturePoolSize) {
2324 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002325 const size_t offset = mTexturePool.size();
2326 mTexturePool.resize(mTexturePoolSize);
2327 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2328 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002329 } else if (mTexturePool.size() > mTexturePoolSize) {
2330 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2331 const size_t offset = mTexturePoolSize;
2332 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2333 mTexturePool.resize(mTexturePoolSize);
2334 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002335 }
2336 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002337
Kevin DuBois413287f2019-02-25 08:46:47 -08002338 if (mLumaSampling && mRegionSamplingThread) {
2339 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002340 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07002341
2342 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2343 // side-effect of getTotalSize(), so we check that again here
2344 if (ATRACE_ENABLED()) {
Marissa Wall22b2de12019-12-02 18:11:43 -08002345 // getTotalSize returns the total number of buffers that were allocated by SurfaceFlinger
Dan Stoza45de5ba2019-04-25 14:12:09 -07002346 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2347 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002348}
2349
Lloyd Pique7eebe692020-04-22 22:40:06 -07002350FloatRect SurfaceFlinger::getLayerClipBoundsForDisplay(const DisplayDevice& displayDevice) const {
2351 return displayDevice.getViewport().toFloatRect();
2352}
2353
Vishnu Nair4351ad52019-02-11 14:13:02 -08002354void SurfaceFlinger::computeLayerBounds() {
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002355 for (const auto& pair : ON_MAIN_THREAD(mDisplays)) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08002356 const auto& displayDevice = pair.second;
2357 const auto display = displayDevice->getCompositionDisplay();
2358 for (const auto& layer : mDrawingState.layersSortedByZ) {
2359 // only consider the layers on the given layer stack
2360 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002361 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002362 }
2363
Lloyd Pique7eebe692020-04-22 22:40:06 -07002364 layer->computeBounds(getLayerClipBoundsForDisplay(*displayDevice), ui::Transform(),
Vishnu Nairc97b8db2019-10-29 18:19:35 -07002365 0.f /* shadowRadius */);
Vishnu Nair4351ad52019-02-11 14:13:02 -08002366 }
2367 }
2368}
2369
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002370void SurfaceFlinger::postFrame() {
2371 const auto display = ON_MAIN_THREAD(getDefaultDisplayDeviceLocked());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002372 if (display && getHwComposer().isConnected(*display->getId())) {
2373 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002374 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2375 logFrameStats();
2376 }
2377 }
2378}
2379
Mathias Agopian87baae12012-07-31 12:38:26 -07002380void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002381{
Mathias Agopian841cde52012-03-01 15:44:37 -08002382 ATRACE_CALL();
2383
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002384 // here we keep a copy of the drawing state (that is the state that's
2385 // going to be overwritten by handleTransactionLocked()) outside of
2386 // mStateLock so that the side-effects of the State assignment
2387 // don't happen with mStateLock held (which can cause deadlocks).
2388 State drawingState(mDrawingState);
2389
Mathias Agopianca4d3602011-05-19 15:38:14 -07002390 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002391 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002392
Mathias Agopianca4d3602011-05-19 15:38:14 -07002393 // Here we're guaranteed that some transaction flags are set
2394 // so we can call handleTransactionLocked() unconditionally.
2395 // We call getTransactionFlags(), which will also clear the flags,
2396 // with mStateLock held to guarantee that mCurrentState won't change
2397 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002398
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002399 mVSyncModulator->onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002400 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002401 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002402
Mathias Agopianca4d3602011-05-19 15:38:14 -07002403 mDebugInTransaction = 0;
2404 invalidateHwcGeometry();
2405 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002406}
2407
Lloyd Piqueba04e622017-12-14 17:11:26 -08002408void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2409 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002410 const std::optional<DisplayIdentificationInfo> info =
2411 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002412
Dominik Laskowski075d3172018-05-24 15:50:06 -07002413 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002414 continue;
2415 }
2416
Dominik Laskowski55c85402020-01-21 16:25:47 -08002417 const DisplayId displayId = info->id;
2418 const auto it = mPhysicalDisplayTokens.find(displayId);
2419
Peiyong Line9d809e2020-04-14 13:10:48 -07002420 if (event.connection == hal::Connection::CONNECTED) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002421 if (it == mPhysicalDisplayTokens.end()) {
2422 ALOGV("Creating display %s", to_string(displayId).c_str());
2423
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002424 if (event.hwcDisplayId == getHwComposer().getInternalHwcDisplayId()) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002425 initScheduler(displayId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002426 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002427
Dominik Laskowski075d3172018-05-24 15:50:06 -07002428 DisplayDeviceState state;
Marin Shalamanov7ce87642020-05-06 13:45:58 +02002429 state.physical = {.id = displayId,
2430 .type = getHwComposer().getDisplayConnectionType(displayId),
2431 .hwcDisplayId = event.hwcDisplayId,
2432 .deviceProductInfo = info->deviceProductInfo};
Dominik Laskowski075d3172018-05-24 15:50:06 -07002433 state.isSecure = true; // All physical displays are currently considered secure.
2434 state.displayName = info->name;
Dominik Laskowski55c85402020-01-21 16:25:47 -08002435
2436 sp<IBinder> token = new BBinder();
2437 mCurrentState.displays.add(token, state);
2438 mPhysicalDisplayTokens.emplace(displayId, std::move(token));
2439
Dominik Laskowski075d3172018-05-24 15:50:06 -07002440 mInterceptor->saveDisplayCreation(state);
Marin Shalamanov700e6392020-02-12 20:22:26 +01002441 } else {
2442 ALOGV("Recreating display %s", to_string(displayId).c_str());
2443
2444 const auto token = it->second;
2445 auto& state = mCurrentState.displays.editValueFor(token);
2446 state.sequenceId = DisplayDeviceState{}.sequenceId;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002447 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002448 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002449 ALOGV("Removing display %s", to_string(displayId).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002450
Dominik Laskowski55c85402020-01-21 16:25:47 -08002451 const ssize_t index = mCurrentState.displays.indexOfKey(it->second);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002452 if (index >= 0) {
2453 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2454 mInterceptor->saveDisplayDeletion(state.sequenceId);
2455 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002456 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002457 mPhysicalDisplayTokens.erase(it);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002458 }
2459
2460 processDisplayChangesLocked();
2461 }
2462
2463 mPendingHotplugEvents.clear();
2464}
2465
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002466void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski98041832019-08-01 18:35:59 -07002467 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2468 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002469}
2470
Lloyd Pique99d3da52018-01-22 17:48:03 -08002471sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Lloyd Pique9370a482019-10-03 17:58:30 -07002472 const wp<IBinder>& displayToken,
2473 std::shared_ptr<compositionengine::Display> compositionDisplay,
Marin Shalamanovae685592020-02-12 17:12:22 +01002474 const DisplayDeviceState& state,
2475 const sp<compositionengine::DisplaySurface>& displaySurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002476 const sp<IGraphicBufferProducer>& producer) {
Lloyd Pique9370a482019-10-03 17:58:30 -07002477 auto displayId = compositionDisplay->getDisplayId();
2478 DisplayDeviceCreationArgs creationArgs(this, displayToken, compositionDisplay);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002479 creationArgs.sequenceId = state.sequenceId;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002480 creationArgs.isSecure = state.isSecure;
Marin Shalamanovae685592020-02-12 17:12:22 +01002481 creationArgs.displaySurface = displaySurface;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002482 creationArgs.hasWideColorGamut = false;
2483 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002484
Dominik Laskowski55c85402020-01-21 16:25:47 -08002485 if (const auto& physical = state.physical) {
2486 creationArgs.connectionType = physical->type;
2487 }
2488
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002489 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002490 creationArgs.isPrimary = isInternalDisplay;
2491
2492 if (useColorManagement && displayId) {
2493 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002494 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002495 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002496 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002497 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002498
Dominik Laskowski7e045462018-05-30 13:02:02 -07002499 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002500 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002501 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002502 }
tangrobin6753a022018-08-10 10:58:54 +08002503 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002504
Dominik Laskowski075d3172018-05-24 15:50:06 -07002505 if (displayId) {
2506 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002507 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002508 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002509 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002510
Lloyd Pique90c115d2018-09-18 21:39:42 -07002511 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002512 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002513 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002514
Lloyd Pique99d3da52018-01-22 17:48:03 -08002515 // Make sure that composition can never be stalled by a virtual display
2516 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002517 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002518 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002519 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2520 }
2521
Dominik Laskowski718f9602019-11-09 20:01:35 -08002522 creationArgs.physicalOrientation =
2523 isInternalDisplay ? internalDisplayOrientation : ui::ROTATION_0;
Chia-I Wua02871c2018-08-27 14:38:23 -07002524
Lloyd Pique99d3da52018-01-22 17:48:03 -08002525 // virtual displays are always considered enabled
Peiyong Lin65248e02020-04-18 21:15:07 -07002526 creationArgs.initialPowerMode = state.isVirtual() ? hal::PowerMode::ON : hal::PowerMode::OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002527
Lloyd Pique9370a482019-10-03 17:58:30 -07002528 sp<DisplayDevice> display = getFactory().createDisplayDevice(creationArgs);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002529
2530 if (maxFrameBufferAcquiredBuffers >= 3) {
2531 nativeWindowSurface->preallocateBuffers();
2532 }
2533
2534 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002535 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002536 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002537 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002538 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002539 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002540 display->getCompositionDisplay()->setColorProfile(
2541 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2542 RenderIntent::COLORIMETRIC,
2543 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002544 if (!state.isVirtual()) {
2545 LOG_ALWAYS_FATAL_IF(!displayId);
Ady Abraham2139f732019-11-13 18:56:40 -08002546 auto activeConfigId = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(*displayId));
2547 display->setActiveConfig(activeConfigId);
Marin Shalamanov7ce87642020-05-06 13:45:58 +02002548 display->setDeviceProductInfo(state.physical->deviceProductInfo);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002549 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002550
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002551 display->setLayerStack(state.layerStack);
2552 display->setProjection(state.orientation, state.viewport, state.frame);
2553 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002554
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002555 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002556}
2557
Marin Shalamanovae685592020-02-12 17:12:22 +01002558void SurfaceFlinger::processDisplayAdded(const wp<IBinder>& displayToken,
2559 const DisplayDeviceState& state) {
2560 int width = 0;
2561 int height = 0;
2562 ui::PixelFormat pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_UNKNOWN);
2563 if (state.physical) {
2564 const auto& activeConfig =
2565 getCompositionEngine().getHwComposer().getActiveConfig(state.physical->id);
2566 width = activeConfig->getWidth();
2567 height = activeConfig->getHeight();
2568 pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_RGBA_8888);
2569 } else if (state.surface != nullptr) {
2570 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2571 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2572 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2573 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2574 int intPixelFormat;
2575 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intPixelFormat);
2576 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
2577 pixelFormat = static_cast<ui::PixelFormat>(intPixelFormat);
2578 } else {
2579 // Virtual displays without a surface are dormant:
2580 // they have external state (layer stack, projection,
2581 // etc.) but no internal state (i.e. a DisplayDevice).
2582 return;
2583 }
2584
2585 compositionengine::DisplayCreationArgsBuilder builder;
2586 if (const auto& physical = state.physical) {
2587 builder.setPhysical({physical->id, physical->type});
2588 }
2589 builder.setPixels(ui::Size(width, height));
2590 builder.setPixelFormat(pixelFormat);
2591 builder.setIsSecure(state.isSecure);
2592 builder.setLayerStackId(state.layerStack);
2593 builder.setPowerAdvisor(&mPowerAdvisor);
2594 builder.setUseHwcVirtualDisplays(mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer());
2595 builder.setName(state.displayName);
2596 const auto compositionDisplay = getCompositionEngine().createDisplay(builder.build());
2597
2598 sp<compositionengine::DisplaySurface> displaySurface;
2599 sp<IGraphicBufferProducer> producer;
2600 sp<IGraphicBufferProducer> bqProducer;
2601 sp<IGraphicBufferConsumer> bqConsumer;
2602 getFactory().createBufferQueue(&bqProducer, &bqConsumer, /*consumerIsSurfaceFlinger =*/false);
2603
2604 std::optional<DisplayId> displayId = compositionDisplay->getId();
2605
2606 if (state.isVirtual()) {
2607 sp<VirtualDisplaySurface> vds =
2608 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface, bqProducer,
2609 bqConsumer, state.displayName);
2610
2611 displaySurface = vds;
2612 producer = vds;
2613 } else {
2614 ALOGE_IF(state.surface != nullptr,
2615 "adding a supported display, but rendering "
2616 "surface is provided (%p), ignoring it",
2617 state.surface.get());
2618
2619 LOG_ALWAYS_FATAL_IF(!displayId);
2620 displaySurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer,
2621 maxGraphicsWidth, maxGraphicsHeight);
2622 producer = bqProducer;
2623 }
2624
Marin Shalamanov700e6392020-02-12 20:22:26 +01002625 LOG_FATAL_IF(!displaySurface);
2626 const auto display = setupNewDisplayDeviceInternal(displayToken, compositionDisplay, state,
2627 displaySurface, producer);
2628 mDisplays.emplace(displayToken, display);
2629 if (!state.isVirtual()) {
2630 LOG_FATAL_IF(!displayId);
2631 dispatchDisplayHotplugEvent(displayId->value, true);
2632 }
Marin Shalamanovae685592020-02-12 17:12:22 +01002633
Marin Shalamanov700e6392020-02-12 20:22:26 +01002634 if (display->isPrimary()) {
2635 mScheduler->onPrimaryDisplayAreaChanged(display->getWidth() * display->getHeight());
Marin Shalamanovae685592020-02-12 17:12:22 +01002636 }
2637}
2638
2639void SurfaceFlinger::processDisplayRemoved(const wp<IBinder>& displayToken) {
2640 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2641 // Save display ID before disconnecting.
2642 const auto displayId = display->getId();
2643 display->disconnect();
2644
2645 if (!display->isVirtual()) {
Marin Shalamanov700e6392020-02-12 20:22:26 +01002646 LOG_FATAL_IF(!displayId);
Marin Shalamanovae685592020-02-12 17:12:22 +01002647 dispatchDisplayHotplugEvent(displayId->value, false);
2648 }
2649 }
2650
2651 mDisplays.erase(displayToken);
2652}
2653
2654void SurfaceFlinger::processDisplayChanged(const wp<IBinder>& displayToken,
2655 const DisplayDeviceState& currentState,
2656 const DisplayDeviceState& drawingState) {
2657 const sp<IBinder> currentBinder = IInterface::asBinder(currentState.surface);
2658 const sp<IBinder> drawingBinder = IInterface::asBinder(drawingState.surface);
Marin Shalamanov700e6392020-02-12 20:22:26 +01002659 if (currentBinder != drawingBinder || currentState.sequenceId != drawingState.sequenceId) {
Marin Shalamanovae685592020-02-12 17:12:22 +01002660 // changing the surface is like destroying and recreating the DisplayDevice
2661 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2662 display->disconnect();
2663 }
2664 mDisplays.erase(displayToken);
Marin Shalamanov700e6392020-02-12 20:22:26 +01002665 if (const auto& physical = currentState.physical) {
2666 getHwComposer().allocatePhysicalDisplay(physical->hwcDisplayId, physical->id);
2667 }
Marin Shalamanovae685592020-02-12 17:12:22 +01002668 processDisplayAdded(displayToken, currentState);
Marin Shalamanov700e6392020-02-12 20:22:26 +01002669 if (currentState.physical) {
Marin Shalamanov4c5e3012020-06-04 21:41:42 +02002670 const auto display = getDisplayDeviceLocked(displayToken);
2671 setPowerModeInternal(display, hal::PowerMode::ON);
Marin Shalamanov700e6392020-02-12 20:22:26 +01002672 }
Marin Shalamanovae685592020-02-12 17:12:22 +01002673 return;
2674 }
2675
2676 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2677 if (currentState.layerStack != drawingState.layerStack) {
2678 display->setLayerStack(currentState.layerStack);
2679 }
2680 if ((currentState.orientation != drawingState.orientation) ||
2681 (currentState.viewport != drawingState.viewport) ||
2682 (currentState.frame != drawingState.frame)) {
2683 display->setProjection(currentState.orientation, currentState.viewport,
2684 currentState.frame);
2685 }
2686 if (currentState.width != drawingState.width ||
2687 currentState.height != drawingState.height) {
2688 display->setDisplaySize(currentState.width, currentState.height);
Dominik Laskowski20134642020-04-20 22:36:44 -07002689
Marin Shalamanovae685592020-02-12 17:12:22 +01002690 if (display->isPrimary()) {
2691 mScheduler->onPrimaryDisplayAreaChanged(currentState.width * currentState.height);
2692 }
Dominik Laskowski20134642020-04-20 22:36:44 -07002693
2694 if (mRefreshRateOverlay) {
2695 mRefreshRateOverlay->setViewport(display->getSize());
2696 }
Marin Shalamanovae685592020-02-12 17:12:22 +01002697 }
2698 }
2699}
2700
Lloyd Pique347200f2017-12-14 17:00:15 -08002701void SurfaceFlinger::processDisplayChangesLocked() {
2702 // here we take advantage of Vector's copy-on-write semantics to
2703 // improve performance by skipping the transaction entirely when
2704 // know that the lists are identical
2705 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2706 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2707 if (!curr.isIdenticalTo(draw)) {
2708 mVisibleRegionsDirty = true;
Lloyd Pique347200f2017-12-14 17:00:15 -08002709
2710 // find the displays that were removed
2711 // (ie: in drawing state but not in current state)
2712 // also handle displays that changed
2713 // (ie: displays that are in both lists)
Marin Shalamanovae685592020-02-12 17:12:22 +01002714 for (size_t i = 0; i < draw.size(); i++) {
2715 const wp<IBinder>& displayToken = draw.keyAt(i);
2716 const ssize_t j = curr.indexOfKey(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002717 if (j < 0) {
2718 // in drawing state but not in current state
Marin Shalamanovae685592020-02-12 17:12:22 +01002719 processDisplayRemoved(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002720 } else {
2721 // this display is in both lists. see if something changed.
Marin Shalamanovae685592020-02-12 17:12:22 +01002722 const DisplayDeviceState& currentState = curr[j];
2723 const DisplayDeviceState& drawingState = draw[i];
2724 processDisplayChanged(displayToken, currentState, drawingState);
Lloyd Pique347200f2017-12-14 17:00:15 -08002725 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002726 }
2727
2728 // find displays that were added
2729 // (ie: in current state but not in drawing state)
Marin Shalamanovae685592020-02-12 17:12:22 +01002730 for (size_t i = 0; i < curr.size(); i++) {
2731 const wp<IBinder>& displayToken = curr.keyAt(i);
2732 if (draw.indexOfKey(displayToken) < 0) {
2733 processDisplayAdded(displayToken, curr[i]);
Lloyd Pique347200f2017-12-14 17:00:15 -08002734 }
2735 }
2736 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002737
2738 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002739}
2740
Mathias Agopian87baae12012-07-31 12:38:26 -07002741void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002742{
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002743 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2744
Dan Stoza7dde5992015-05-22 09:51:44 -07002745 // Notify all layers of available frames
Edgar Arriaga844fa672020-01-16 14:21:42 -08002746 mCurrentState.traverse([expectedPresentTime](Layer* layer) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002747 layer->notifyAvailableFrames(expectedPresentTime);
Robert Carr2047fae2016-11-28 14:09:09 -08002748 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002749
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002750 /*
2751 * Traversal of the children
2752 * (perform the transaction for each of them if needed)
2753 */
2754
Valerie Haud50e7412020-06-16 17:58:14 -07002755 if ((transactionFlags & eTraversalNeeded) || mForceTraversal) {
2756 mForceTraversal = false;
Edgar Arriaga844fa672020-01-16 14:21:42 -08002757 mCurrentState.traverse([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002758 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002759 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002760
2761 const uint32_t flags = layer->doTransaction(0);
2762 if (flags & Layer::eVisibleRegion)
2763 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002764
2765 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002766 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002767 }
Robert Carr2047fae2016-11-28 14:09:09 -08002768 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002769 }
2770
2771 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002772 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002773 */
2774
Mathias Agopiane57f2922012-08-09 16:29:12 -07002775 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002776 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002777 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002778 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002779
Vishnu Nair6213bd92020-05-08 17:42:25 -07002780 if (transactionFlags & (eTransformHintUpdateNeeded | eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002781 // The transform hint might have changed for some layers
2782 // (either because a display has changed, or because a layer
2783 // as changed).
2784 //
2785 // Walk through all the layers in currentLayers,
2786 // and update their transform hint.
2787 //
2788 // If a layer is visible only on a single display, then that
2789 // display is used to calculate the hint, otherwise we use the
2790 // default display.
2791 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002792 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08002793 // the hint is set before we acquire a buffer from the surface texture.
2794 //
2795 // NOTE: layer transactions have taken place already, so we use their
2796 // drawing state. However, SurfaceFlinger's own transaction has not
2797 // happened yet, so we must use the current state layer list
2798 // (soon to become the drawing state list).
2799 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002800 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002801 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002802 bool first = true;
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002803 mCurrentState.traverse([&](Layer* layer) REQUIRES(mStateLock) {
Mathias Agopian84300952012-11-21 16:02:13 -08002804 // NOTE: we rely on the fact that layers are sorted by
2805 // layerStack first (so we don't have to traverse the list
2806 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002807 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002808 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002809 currentlayerStack = layerStack;
2810 // figure out if this layerstack is mirrored
2811 // (more than one display) if so, pick the default display,
2812 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002813 hintDisplay = nullptr;
2814 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002815 if (display->getCompositionDisplay()
2816 ->belongsInOutput(layer->getLayerStack(),
2817 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002818 if (hintDisplay) {
2819 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002820 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002821 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002822 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002823 }
2824 }
2825 }
2826 }
Chet Haase91d25932013-04-11 15:24:55 -07002827
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002828 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002829 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2830 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002831
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002832 // could be null when this layer is using a layerStack
2833 // that is not visible on any display. Also can occur at
2834 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002835 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002836 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002837
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002838 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002839 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002840 if (hintDisplay) {
Dominik Laskowskib7251f42020-04-20 17:42:59 -07002841 layer->updateTransformHint(hintDisplay->getTransformHint());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002842 }
Robert Carr2047fae2016-11-28 14:09:09 -08002843
2844 first = false;
2845 });
Mathias Agopian84300952012-11-21 16:02:13 -08002846 }
2847
Mathias Agopian3559b072012-08-15 13:46:03 -07002848 /*
2849 * Perform our own transaction if needed
2850 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002851
2852 if (mLayersAdded) {
2853 mLayersAdded = false;
2854 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002855 mVisibleRegionsDirty = true;
2856 }
2857
2858 // some layers might have been removed, so
2859 // we need to update the regions they're exposing.
2860 if (mLayersRemoved) {
2861 mLayersRemoved = false;
2862 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002863 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002864 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002865 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002866 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002867 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002868 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002869 }
Robert Carr2047fae2016-11-28 14:09:09 -08002870 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002871 }
2872
Vishnu Nairec0ab382019-02-13 15:32:56 -08002873 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002874 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002875}
2876
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002877void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002878 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002879 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002880 return;
2881 }
2882
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002883 if (mVisibleRegionsDirty || mInputInfoChanged) {
2884 mInputInfoChanged = false;
2885 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002886 } else if (mInputWindowCommands.syncInputWindows) {
2887 // If the caller requested to sync input windows, but there are no
2888 // changes to input windows, notify immediately.
2889 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002890 }
2891
Arthur Hung6cbb9752019-09-05 16:38:18 +08002892 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002893}
2894
2895void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002896 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002897
2898 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Robert Carredd13602020-04-13 17:24:34 -07002899 if (layer->needsInputInfo()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002900 // When calculating the screen bounds we ignore the transparent region since it may
2901 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002902 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002903 }
2904 });
chaviw291d88a2019-02-14 10:33:58 -08002905
2906 mInputFlinger->setInputWindows(inputHandles,
2907 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2908 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07002909}
2910
Vishnu Nairec0ab382019-02-13 15:32:56 -08002911void SurfaceFlinger::commitInputWindowCommands() {
Rob Carr9a2cc992020-03-06 12:44:45 -08002912 mInputWindowCommands.merge(mPendingInputWindowCommands);
Vishnu Nairec0ab382019-02-13 15:32:56 -08002913 mPendingInputWindowCommands.clear();
2914}
2915
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002916void SurfaceFlinger::updateCursorAsync() {
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002917 compositionengine::CompositionRefreshArgs refreshArgs;
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002918 for (const auto& [_, display] : ON_MAIN_THREAD(mDisplays)) {
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002919 if (display->getId()) {
2920 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07002921 }
2922 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002923
2924 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002925}
2926
Ady Abraham2139f732019-11-13 18:56:40 -08002927void SurfaceFlinger::changeRefreshRate(const RefreshRate& refreshRate,
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07002928 Scheduler::ConfigEvent event) {
Ady Abraham8a82ba62020-01-17 12:43:17 -08002929 // If this is called from the main thread mStateLock must be locked before
2930 // Currently the only way to call this function from the main thread is from
2931 // Sheduler::chooseRefreshRateForContent
2932
2933 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Ady Abraham2139f732019-11-13 18:56:40 -08002934 changeRefreshRateLocked(refreshRate, event);
2935}
2936
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002937void SurfaceFlinger::initScheduler(DisplayId primaryDisplayId) {
2938 if (mScheduler) {
2939 // In practice it's not allowed to hotplug in/out the primary display once it's been
2940 // connected during startup, but some tests do it, so just warn and return.
2941 ALOGW("Can't re-init scheduler");
2942 return;
2943 }
2944
Ady Abraham2139f732019-11-13 18:56:40 -08002945 auto currentConfig = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(primaryDisplayId));
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002946 mRefreshRateConfigs =
Ana Krulec3f6a2062020-01-23 15:48:01 -08002947 std::make_unique<scheduler::RefreshRateConfigs>(getHwComposer().getConfigs(
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002948 primaryDisplayId),
2949 currentConfig);
2950 mRefreshRateStats =
2951 std::make_unique<scheduler::RefreshRateStats>(*mRefreshRateConfigs, *mTimeStats,
Peiyong Lin65248e02020-04-18 21:15:07 -07002952 currentConfig, hal::PowerMode::OFF);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002953 mRefreshRateStats->setConfigMode(currentConfig);
2954
Ady Abraham9e16a482019-12-03 17:19:41 -08002955 mPhaseConfiguration = getFactory().createPhaseConfiguration(*mRefreshRateConfigs);
2956
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002957 // start the EventThread
2958 mScheduler =
2959 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002960 *mRefreshRateConfigs, *this);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002961 mAppConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002962 mScheduler->createConnection("app", mPhaseConfiguration->getCurrentOffsets().late.app,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002963 impl::EventThread::InterceptVSyncsCallback());
2964 mSfConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002965 mScheduler->createConnection("sf", mPhaseConfiguration->getCurrentOffsets().late.sf,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002966 [this](nsecs_t timestamp) {
2967 mInterceptor->saveVSyncEvent(timestamp);
2968 });
2969
2970 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
2971 mVSyncModulator.emplace(*mScheduler, mAppConnectionHandle, mSfConnectionHandle,
Ady Abraham9e16a482019-12-03 17:19:41 -08002972 mPhaseConfiguration->getCurrentOffsets());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002973
2974 mRegionSamplingThread =
2975 new RegionSamplingThread(*this, *mScheduler,
2976 RegionSamplingThread::EnvironmentTimingTunables());
Alec Mouri60aee1c2019-10-28 16:18:59 -07002977 // Dispatch a config change request for the primary display on scheduler
2978 // initialization, so that the EventThreads always contain a reference to a
2979 // prior configuration.
2980 //
2981 // This is a bit hacky, but this avoids a back-pointer into the main SF
2982 // classes from EventThread, and there should be no run-time binder cost
2983 // anyway since there are no connected apps at this point.
2984 const nsecs_t vsyncPeriod =
Ady Abrahamabc27602020-04-08 17:20:29 -07002985 mRefreshRateConfigs->getRefreshRateFromConfigId(currentConfig).getVsyncPeriod();
Ady Abrahamdfd62162020-06-10 16:11:56 -07002986 mScheduler->onPrimaryDisplayConfigChanged(mAppConnectionHandle, primaryDisplayId.value,
2987 currentConfig, vsyncPeriod);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002988}
2989
Mathias Agopian4fec8732012-06-29 14:12:52 -07002990void SurfaceFlinger::commitTransaction()
2991{
Vishnu Nair60db8c02020-04-02 11:55:16 -07002992 commitTransactionLocked();
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002993 mTransactionPending = false;
2994 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002995 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002996}
2997
Lloyd Pique58e24a32019-08-01 15:50:14 -07002998void SurfaceFlinger::commitTransactionLocked() {
2999 if (!mLayersPendingRemoval.isEmpty()) {
3000 // Notify removed layers now that they can't be drawn from
3001 for (const auto& l : mLayersPendingRemoval) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003002 recordBufferingStats(l->getName(), l->getOccupancyHistory(true));
Lloyd Pique58e24a32019-08-01 15:50:14 -07003003
3004 // Ensure any buffers set to display on any children are released.
3005 if (l->isRemovedFromCurrentState()) {
3006 l->latchAndReleaseBuffer();
3007 }
3008
3009 // If the layer has been removed and has no parent, then it will not be reachable
3010 // when traversing layers on screen. Add the layer to the offscreenLayers set to
3011 // ensure we can copy its current to drawing state.
3012 if (!l->getParent()) {
3013 mOffscreenLayers.emplace(l.get());
3014 }
3015 }
3016 mLayersPendingRemoval.clear();
3017 }
3018
3019 // If this transaction is part of a window animation then the next frame
3020 // we composite should be considered an animation as well.
3021 mAnimCompositionPending = mAnimTransactionPending;
3022
3023 mDrawingState = mCurrentState;
3024 // clear the "changed" flags in current state
3025 mCurrentState.colorMatrixChanged = false;
3026
Edgar Arriaga844fa672020-01-16 14:21:42 -08003027 mDrawingState.traverse([&](Layer* layer) {
Lloyd Pique58e24a32019-08-01 15:50:14 -07003028 layer->commitChildList();
3029
3030 // If the layer can be reached when traversing mDrawingState, then the layer is no
3031 // longer offscreen. Remove the layer from the offscreenLayer set.
3032 if (mOffscreenLayers.count(layer)) {
3033 mOffscreenLayers.erase(layer);
3034 }
3035 });
3036
3037 commitOffscreenLayers();
Edgar Arriaga844fa672020-01-16 14:21:42 -08003038 mDrawingState.traverse([&](Layer* layer) { layer->updateMirrorInfo(); });
Lloyd Pique58e24a32019-08-01 15:50:14 -07003039}
3040
chaviw74d90ad2019-04-26 14:45:26 -07003041void SurfaceFlinger::commitOffscreenLayers() {
3042 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003043 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [](Layer* layer) {
chaviw74d90ad2019-04-26 14:45:26 -07003044 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
3045 if (!trFlags) return;
3046
3047 layer->doTransaction(0);
3048 layer->commitChildList();
3049 });
3050 }
3051}
3052
Chia-I Wuab0c3192017-08-01 11:29:00 -07003053void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07003054 for (const auto& [token, displayDevice] : ON_MAIN_THREAD(mDisplays)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003055 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003056 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003057 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003058 }
3059 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003060}
3061
Dan Stoza6b9454d2014-11-07 16:00:59 -08003062bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003063{
Ady Abraham09bd3922019-04-08 10:44:56 -07003064 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003065 ALOGV("handlePageFlip");
3066
Brian Andersond6927fb2016-07-23 23:37:30 -07003067 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003068
Mathias Agopian4fec8732012-06-29 14:12:52 -07003069 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003070 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003071 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003072
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003073 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
3074
Eric Penner51c59cd2014-07-28 19:51:58 -07003075 // Store the set of layers that need updates. This set must not change as
3076 // buffers are being latched, as this could result in a deadlock.
3077 // Example: Two producers share the same command stream and:
3078 // 1.) Layer 0 is latched
3079 // 2.) Layer 0 gets a new frame
3080 // 2.) Layer 1 gets a new frame
3081 // 3.) Layer 1 is latched.
3082 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3083 // second frame. But layer 0's second frame could be waiting on display.
Edgar Arriaga844fa672020-01-16 14:21:42 -08003084 mDrawingState.traverse([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003085 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003086 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003087 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003088 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003089 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07003090 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07003091 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003092 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003093 } else {
3094 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003095 }
Robert Carr2047fae2016-11-28 14:09:09 -08003096 });
3097
chaviw49a108c2019-08-12 11:23:06 -07003098 // The client can continue submitting buffers for offscreen layers, but they will not
3099 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
3100 // layers to ensure dequeueBuffer doesn't block indefinitely.
3101 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003102 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
chaviw49a108c2019-08-12 11:23:06 -07003103 [&](Layer* l) { l->latchAndReleaseBuffer(); });
3104 }
3105
Lloyd Piquef2c79392018-12-20 16:23:33 -08003106 if (!mLayersWithQueuedFrames.empty()) {
3107 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3108 // writes to Layer current state. See also b/119481871
3109 Mutex::Autolock lock(mStateLock);
3110
3111 for (auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003112 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003113 mLayersPendingRefresh.push_back(layer);
3114 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003115 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003116 if (layer->isBufferLatched()) {
3117 newDataLatched = true;
3118 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003119 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003120 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003121
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003122 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003123
3124 // If we will need to wake up at some time in the future to deal with a
3125 // queued frame that shouldn't be displayed during this vsync period, wake
3126 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003127 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003128 signalLayerUpdate();
3129 }
3130
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003131 // enter boot animation on first buffer latch
3132 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3133 ALOGI("Enter boot animation");
3134 mBootStage = BootStage::BOOTANIMATION;
3135 }
3136
Edgar Arriaga844fa672020-01-16 14:21:42 -08003137 mDrawingState.traverse([&](Layer* layer) { layer->updateCloneBufferInfo(); });
chaviw74b03172019-08-19 11:09:03 -07003138
Dan Stoza6b9454d2014-11-07 16:00:59 -08003139 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003140 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003141}
3142
Mathias Agopianad456f92011-01-13 17:53:01 -08003143void SurfaceFlinger::invalidateHwcGeometry()
3144{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003145 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003146}
3147
Robert Carrc0df3122019-04-11 13:18:21 -07003148status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
3149 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
3150 const sp<IBinder>& parentHandle,
Vishnu Nair6213bd92020-05-08 17:42:25 -07003151 const sp<Layer>& parentLayer, bool addToCurrentState,
3152 uint32_t* outTransformHint) {
Dan Stoza7d89d062015-04-30 13:29:25 -07003153 // add this layer to the current state list
3154 {
3155 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07003156 sp<Layer> parent;
3157 if (parentHandle != nullptr) {
Alec Mouri9a02eda2020-04-21 17:39:34 -07003158 parent = fromHandleLocked(parentHandle).promote();
Robert Carrc0df3122019-04-11 13:18:21 -07003159 if (parent == nullptr) {
3160 return NAME_NOT_FOUND;
3161 }
3162 } else {
3163 parent = parentLayer;
3164 }
3165
Ady Abrahamb89ca7d2020-03-04 11:19:37 -08003166 if (mNumLayers >= ISurfaceComposer::MAX_LAYERS) {
chaviweadf0d42019-08-12 13:28:29 -07003167 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Ady Abrahamb89ca7d2020-03-04 11:19:37 -08003168 ISurfaceComposer::MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003169 return NO_MEMORY;
3170 }
Robert Carrc0df3122019-04-11 13:18:21 -07003171
3172 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
3173
Robert Carrb89ea9d2018-12-10 13:01:14 -08003174 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003175 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003176 } else if (parent == nullptr) {
3177 lbc->onRemovedFromCurrentState();
3178 } else if (parent->isRemovedFromCurrentState()) {
3179 parent->addChild(lbc);
3180 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003181 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003182 parent->addChild(lbc);
3183 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003184
Yiwei Zhang243b3782018-05-15 17:40:04 -07003185 if (gbc != nullptr) {
3186 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3187 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3188 mMaxGraphicBufferProducerListSize,
3189 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3190 mGraphicBufferProducerList.size(),
chaviweadf0d42019-08-12 13:28:29 -07003191 mMaxGraphicBufferProducerListSize, mNumLayers.load());
Alec Mouri601393f2020-02-21 13:26:52 -08003192 if (mGraphicBufferProducerList.size() > mGraphicBufferProducerListSizeLogThreshold) {
3193 ALOGW("Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3194 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize,
3195 mNumLayers.load());
3196 }
Yiwei Zhang243b3782018-05-15 17:40:04 -07003197 }
Vishnu Nair6213bd92020-05-08 17:42:25 -07003198
3199 if (const auto display = getDefaultDisplayDeviceLocked()) {
Dominik Laskowskib7251f42020-04-20 17:42:59 -07003200 lbc->updateTransformHint(display->getTransformHint());
Vishnu Nair6213bd92020-05-08 17:42:25 -07003201 }
3202 if (outTransformHint) {
3203 *outTransformHint = lbc->getTransformHint();
3204 }
3205
Robert Carr1f0a16a2016-10-24 16:27:39 -07003206 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003207 }
3208
Mathias Agopian96f08192010-06-02 23:28:45 -07003209 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003210 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003211
Dan Stoza7d89d062015-04-30 13:29:25 -07003212 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003213}
3214
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07003215void SurfaceFlinger::removeGraphicBufferProducerAsync(const wp<IBinder>& binder) {
3216 static_cast<void>(schedule([=] {
3217 Mutex::Autolock lock(mStateLock);
3218 mGraphicBufferProducerList.erase(binder);
3219 }));
3220}
3221
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003222uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003223 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003224}
3225
Mathias Agopian3f844832013-08-07 21:24:32 -07003226uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003227 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003228}
3229
Mathias Agopian3f844832013-08-07 21:24:32 -07003230uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ady Abrahambf1349c2020-06-12 14:26:18 -07003231 return setTransactionFlags(flags, Scheduler::TransactionStart::Normal);
Dan Stoza84d619e2018-03-28 17:07:36 -07003232}
3233
3234uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003235 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003236 uint32_t old = mTransactionFlags.fetch_or(flags);
Dominik Laskowskieddeda12019-07-19 11:54:13 -07003237 mVSyncModulator->setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003238 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003239 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003240 }
3241 return old;
3242}
3243
Valerie Haud50e7412020-06-16 17:58:14 -07003244void SurfaceFlinger::setTraversalNeeded() {
3245 mForceTraversal = true;
Robert Carr4b874132020-05-29 12:02:51 -07003246}
3247
Marissa Wall713b63f2018-10-17 15:42:43 -07003248bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07003249 // to prevent onHandleDestroyed from being called while the lock is held,
3250 // we must keep a copy of the transactions (specifically the composer
3251 // states) around outside the scope of the lock
3252 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003253 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07003254 {
3255 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003256
Valerie Haufce31b82019-04-30 16:41:14 -07003257 auto it = mTransactionQueues.begin();
3258 while (it != mTransactionQueues.end()) {
3259 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07003260
Valerie Haufce31b82019-04-30 16:41:14 -07003261 while (!transactionQueue.empty()) {
3262 const auto& transaction = transactionQueue.front();
3263 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
3264 transaction.states)) {
3265 setTransactionFlags(eTransactionFlushNeeded);
3266 break;
3267 }
3268 transactions.push_back(transaction);
3269 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
3270 mPendingInputWindowCommands, transaction.desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003271 transaction.buffer, transaction.postTime,
3272 transaction.privileged, transaction.hasListenerCallbacks,
3273 transaction.listenerCallbacks, /*isMainThread*/ true);
Valerie Haufce31b82019-04-30 16:41:14 -07003274 transactionQueue.pop();
3275 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003276 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003277
Valerie Haufce31b82019-04-30 16:41:14 -07003278 if (transactionQueue.empty()) {
3279 it = mTransactionQueues.erase(it);
3280 mTransactionCV.broadcast();
3281 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07003282 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07003283 }
Valerie Hauf6016b62019-03-28 10:49:59 -07003284 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003285 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003286 return flushedATransaction;
3287}
3288
3289bool SurfaceFlinger::transactionFlushNeeded() {
3290 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003291}
3292
chaviwca27f252018-02-06 16:46:39 -08003293
Marissa Wall17b4e452018-12-26 16:32:34 -08003294bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3295 const Vector<ComposerState>& states) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003296
3297 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08003298 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3299 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3300 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3301 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3302 return false;
3303 }
3304
Marissa Wall713b63f2018-10-17 15:42:43 -07003305 for (const ComposerState& state : states) {
3306 const layer_state_t& s = state.state;
3307 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3308 continue;
3309 }
3310 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003311 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003312 }
3313 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003314 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003315}
3316
Valerie Hau9dab9732019-08-20 09:29:25 -07003317void SurfaceFlinger::setTransactionState(
3318 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3319 const sp<IBinder>& applyToken, const InputWindowCommands& inputWindowCommands,
3320 int64_t desiredPresentTime, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
3321 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003322 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003323
Valerie Haubc6ddb12019-03-08 11:10:15 -08003324 const int64_t postTime = systemTime();
3325
Robert Carr14167e02019-02-13 13:50:55 -08003326 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3327
Mathias Agopian698c0872011-06-28 19:09:31 -07003328 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003329
Marissa Wall713b63f2018-10-17 15:42:43 -07003330 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07003331 auto itr = mTransactionQueues.find(applyToken);
3332 // if this is an animation frame, wait until prior animation frame has
3333 // been applied by SF
3334 if (flags & eAnimation) {
3335 while (itr != mTransactionQueues.end()) {
3336 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3337 if (CC_UNLIKELY(err != NO_ERROR)) {
3338 ALOGW_IF(err == TIMED_OUT,
3339 "setTransactionState timed out "
3340 "waiting for animation frame to apply");
3341 break;
3342 }
3343 itr = mTransactionQueues.find(applyToken);
3344 }
3345 }
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003346
Ady Abraham5facfb12020-04-22 15:18:31 -07003347 const bool pendingTransactions = itr != mTransactionQueues.end();
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003348 // Expected present time is computed and cached on invalidate, so it may be stale.
Ady Abraham5facfb12020-04-22 15:18:31 -07003349 if (!pendingTransactions) {
3350 mExpectedPresentTime = calculateExpectedPresentTime(systemTime());
3351 }
3352
3353 if (pendingTransactions || !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003354 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003355 uncacheBuffer, postTime, privileged,
3356 hasListenerCallbacks, listenerCallbacks);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003357 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07003358 return;
3359 }
3360
Valerie Haubc6ddb12019-03-08 11:10:15 -08003361 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003362 uncacheBuffer, postTime, privileged, hasListenerCallbacks,
3363 listenerCallbacks);
Marissa Wall713b63f2018-10-17 15:42:43 -07003364}
3365
Valerie Hau9dab9732019-08-20 09:29:25 -07003366void SurfaceFlinger::applyTransactionState(
3367 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3368 const InputWindowCommands& inputWindowCommands, const int64_t desiredPresentTime,
3369 const client_cache_t& uncacheBuffer, const int64_t postTime, bool privileged,
3370 bool hasListenerCallbacks, const std::vector<ListenerCallbacks>& listenerCallbacks,
3371 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003372 uint32_t transactionFlags = 0;
3373
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003374 if (flags & eAnimation) {
3375 // For window updates that are part of an animation we must wait for
3376 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07003377 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003378 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003379 if (CC_UNLIKELY(err != NO_ERROR)) {
3380 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003381 // caller after a few seconds.
3382 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3383 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003384 mAnimTransactionPending = false;
3385 break;
3386 }
3387 }
3388 }
3389
chaviwca27f252018-02-06 16:46:39 -08003390 for (const DisplayState& display : displays) {
3391 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003392 }
3393
Valerie Hau9dab9732019-08-20 09:29:25 -07003394 // start and end registration for listeners w/ no surface so they can get their callback. Note
3395 // that listeners with SurfaceControls will start registration during setClientStateLocked
3396 // below.
3397 for (const auto& listener : listenerCallbacks) {
3398 mTransactionCompletedThread.startRegistration(listener);
3399 mTransactionCompletedThread.endRegistration(listener);
Marissa Walld600d572019-03-26 15:38:50 -07003400 }
3401
Valerie Hau9dab9732019-08-20 09:29:25 -07003402 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash> listenerCallbacksWithSurfaces;
Marissa Walle2ffb422018-10-12 11:33:52 -07003403 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003404 for (const ComposerState& state : states) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003405 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, postTime, privileged,
3406 listenerCallbacksWithSurfaces);
Ady Abraham5def7332020-05-29 16:13:47 -07003407 if ((flags & eAnimation) && state.state.surface) {
3408 if (const auto layer = fromHandleLocked(state.state.surface).promote(); layer) {
3409 mScheduler->recordLayerHistory(layer.get(), desiredPresentTime,
3410 LayerHistory::LayerUpdateType::AnimationTX);
3411 }
3412 }
Marissa Wall3dad52d2019-03-22 14:03:19 -07003413 }
3414
Valerie Hau9dab9732019-08-20 09:29:25 -07003415 for (const auto& listenerCallback : listenerCallbacksWithSurfaces) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003416 mTransactionCompletedThread.endRegistration(listenerCallback);
3417 }
3418
Marissa Walle2ffb422018-10-12 11:33:52 -07003419 // If the state doesn't require a traversal and there are callbacks, send them now
Valerie Hau9dab9732019-08-20 09:29:25 -07003420 if (!(clientStateFlags & eTraversalNeeded) && hasListenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003421 mTransactionCompletedThread.sendCallbacks();
3422 }
3423 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003424
chaviw273171b2018-12-26 11:46:30 -08003425 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3426
Marissa Wall947d34e2019-03-29 14:03:53 -07003427 if (uncacheBuffer.isValid()) {
3428 ClientCache::getInstance().erase(uncacheBuffer);
Alec Mouri4545a8a2019-08-08 20:05:32 -07003429 getRenderEngine().unbindExternalTextureBuffer(uncacheBuffer.id);
Marissa Wall78b72202019-03-15 14:58:34 -07003430 }
3431
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003432 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3433 // anyway. This can be used as a flush mechanism for previous async transactions.
3434 // Empty animation transaction can be used to simulate back-pressure, so also force a
3435 // transaction for empty animation transactions.
3436 if (transactionFlags == 0 &&
3437 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003438 transactionFlags = eTransactionNeeded;
3439 }
3440
Marissa Wall06255332019-03-27 13:48:27 -07003441 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3442 // so we don't have to wake up again next frame to preform an uneeded traversal.
3443 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3444 transactionFlags = transactionFlags & (~eTraversalNeeded);
Valerie Haud50e7412020-06-16 17:58:14 -07003445 mForceTraversal = true;
Marissa Wall06255332019-03-27 13:48:27 -07003446 }
3447
Ady Abrahambf1349c2020-06-12 14:26:18 -07003448 const auto transactionStart = [](uint32_t flags) {
3449 if (flags & eEarlyWakeup) {
3450 return Scheduler::TransactionStart::Early;
3451 }
3452 if (flags & eExplicitEarlyWakeupEnd) {
3453 return Scheduler::TransactionStart::EarlyEnd;
3454 }
3455 if (flags & eExplicitEarlyWakeupStart) {
3456 return Scheduler::TransactionStart::EarlyStart;
3457 }
3458 return Scheduler::TransactionStart::Normal;
3459 }(flags);
3460
Mathias Agopian386aa982011-11-07 21:58:03 -08003461 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003462 if (mInterceptor->isEnabled()) {
3463 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003464 }
Irvel468051e2016-06-13 16:44:44 -07003465
Ady Abrahambf1349c2020-06-12 14:26:18 -07003466 // TODO(b/159125966): Remove eEarlyWakeup completly as no client should use this flag
3467 if (flags & eEarlyWakeup) {
3468 ALOGW("eEarlyWakeup is deprecated. Use eExplicitEarlyWakeup[Start|End]");
3469 }
3470
3471 if (!privileged && (flags & (eExplicitEarlyWakeupStart | eExplicitEarlyWakeupEnd))) {
3472 ALOGE("Only WindowManager is allowed to use eExplicitEarlyWakeup[Start|End] flags");
3473 flags &= ~(eExplicitEarlyWakeupStart | eExplicitEarlyWakeupEnd);
3474 }
3475
Mathias Agopian386aa982011-11-07 21:58:03 -08003476 // this triggers the transaction
Ady Abrahambf1349c2020-06-12 14:26:18 -07003477 setTransactionFlags(transactionFlags, transactionStart);
Mathias Agopian386aa982011-11-07 21:58:03 -08003478
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003479 if (flags & eAnimation) {
3480 mAnimTransactionPending = true;
3481 }
Robert Carr238f4a22020-04-29 13:04:02 -07003482
3483 // if this is a synchronous transaction, wait for it to take effect
3484 // before returning.
3485 const bool synchronous = flags & eSynchronous;
3486 const bool syncInput = inputWindowCommands.syncInputWindows;
3487 if (!synchronous && !syncInput) {
3488 return;
3489 }
3490
3491 if (synchronous) {
3492 mTransactionPending = true;
3493 }
3494 if (syncInput) {
chaviw4fe36852019-04-15 16:25:49 -07003495 mPendingSyncInputWindows = true;
3496 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003497
Robert Carr238f4a22020-04-29 13:04:02 -07003498
Valerie Hau0779ded2019-03-19 12:43:04 -07003499 // applyTransactionState can be called by either the main SF thread or by
3500 // another process through setTransactionState. While a given process may wish
3501 // to wait on synchronous transactions, the main SF thread should never
3502 // be blocked. Therefore, we only wait if isMainThread is false.
3503 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003504 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3505 if (CC_UNLIKELY(err != NO_ERROR)) {
3506 // just in case something goes wrong in SF, return to the
3507 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003508 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3509 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003510 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003511 break;
3512 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003513 }
Ady Abrahambf1349c2020-06-12 14:26:18 -07003514 } else {
3515 // even if a transaction is not needed, we need to update VsyncModulator
3516 // about explicit early indications
3517 if (transactionStart == Scheduler::TransactionStart::EarlyStart ||
3518 transactionStart == Scheduler::TransactionStart::EarlyEnd) {
3519 mVSyncModulator->setTransactionStart(transactionStart);
3520 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003521 }
3522}
3523
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003524uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3525 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3526 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003527
Mathias Agopiane57f2922012-08-09 16:29:12 -07003528 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003529 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3530
3531 const uint32_t what = s.what;
3532 if (what & DisplayState::eSurfaceChanged) {
3533 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3534 state.surface = s.surface;
3535 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003536 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003537 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003538 if (what & DisplayState::eLayerStackChanged) {
3539 if (state.layerStack != s.layerStack) {
3540 state.layerStack = s.layerStack;
3541 flags |= eDisplayTransactionNeeded;
3542 }
3543 }
3544 if (what & DisplayState::eDisplayProjectionChanged) {
3545 if (state.orientation != s.orientation) {
3546 state.orientation = s.orientation;
3547 flags |= eDisplayTransactionNeeded;
3548 }
3549 if (state.frame != s.frame) {
3550 state.frame = s.frame;
3551 flags |= eDisplayTransactionNeeded;
3552 }
3553 if (state.viewport != s.viewport) {
3554 state.viewport = s.viewport;
3555 flags |= eDisplayTransactionNeeded;
3556 }
3557 }
3558 if (what & DisplayState::eDisplaySizeChanged) {
3559 if (state.width != s.width) {
3560 state.width = s.width;
3561 flags |= eDisplayTransactionNeeded;
3562 }
3563 if (state.height != s.height) {
3564 state.height = s.height;
3565 flags |= eDisplayTransactionNeeded;
3566 }
3567 }
3568
Mathias Agopiane57f2922012-08-09 16:29:12 -07003569 return flags;
3570}
3571
Steven Thomasd4071902020-03-24 16:02:53 -07003572bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess(bool usePermissionCache) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003573 IPCThreadState* ipc = IPCThreadState::self();
3574 const int pid = ipc->getCallingPid();
3575 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003576 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Steven Thomasd4071902020-03-24 16:02:53 -07003577 (usePermissionCache ? !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)
3578 : !checkPermission(sAccessSurfaceFlinger, pid, uid))) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003579 return false;
3580 }
3581 return true;
3582}
3583
Marissa Wall3dad52d2019-03-22 14:03:19 -07003584uint32_t SurfaceFlinger::setClientStateLocked(
Valerie Hau9dab9732019-08-20 09:29:25 -07003585 const ComposerState& composerState, int64_t desiredPresentTime, int64_t postTime,
3586 bool privileged,
3587 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash>& listenerCallbacks) {
chaviwca27f252018-02-06 16:46:39 -08003588 const layer_state_t& s = composerState.state;
chaviwca27f252018-02-06 16:46:39 -08003589
Valerie Hau9dab9732019-08-20 09:29:25 -07003590 for (auto& listener : s.listeners) {
3591 // note that startRegistration will not re-register if the listener has
3592 // already be registered for a prior surface control
3593 mTransactionCompletedThread.startRegistration(listener);
3594 listenerCallbacks.insert(listener);
3595 }
3596
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08003597 sp<Layer> layer = nullptr;
3598 if (s.surface) {
Alec Mouri9a02eda2020-04-21 17:39:34 -07003599 layer = fromHandleLocked(s.surface).promote();
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08003600 } else {
3601 // The client may provide us a null handle. Treat it as if the layer was removed.
3602 ALOGW("Attempt to set client state with a null layer handle");
3603 }
chaviw8b3871a2017-11-01 17:41:01 -07003604 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003605 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003606 mTransactionCompletedThread.registerUnpresentedCallbackHandle(
Valerie Hau9dab9732019-08-20 09:29:25 -07003607 new CallbackHandle(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07003608 }
chaviw8b3871a2017-11-01 17:41:01 -07003609 return 0;
3610 }
3611
chaviw8b3871a2017-11-01 17:41:01 -07003612 uint32_t flags = 0;
3613
Garfield Tan8a3083e2018-12-03 13:21:07 -08003614 const uint64_t what = s.what;
Jorim Jaggidba32732018-05-28 17:43:52 +02003615
3616 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3617 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003618 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003619 layer->pushPendingState();
3620 }
3621
Valerie Hau871d6352020-01-29 08:44:02 -08003622 // Only set by BLAST adapter layers
3623 if (what & layer_state_t::eProducerDisconnect) {
3624 layer->onDisconnect();
3625 }
3626
chaviw8b3871a2017-11-01 17:41:01 -07003627 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07003628 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07003629 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003630 }
chaviw8b3871a2017-11-01 17:41:01 -07003631 }
3632 if (what & layer_state_t::eLayerChanged) {
3633 // NOTE: index needs to be calculated before we update the state
3634 const auto& p = layer->getParent();
3635 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003636 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003637 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003638 mCurrentState.layersSortedByZ.removeAt(idx);
3639 mCurrentState.layersSortedByZ.add(layer);
3640 // we need traversal (state changed)
3641 // AND transaction (list changed)
3642 flags |= eTransactionNeeded|eTraversalNeeded;
3643 }
chaviw8b3871a2017-11-01 17:41:01 -07003644 } else {
3645 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003646 flags |= eTransactionNeeded|eTraversalNeeded;
3647 }
3648 }
chaviw8b3871a2017-11-01 17:41:01 -07003649 }
3650 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003651 // NOTE: index needs to be calculated before we update the state
3652 const auto& p = layer->getParent();
3653 if (p == nullptr) {
3654 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3655 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3656 mCurrentState.layersSortedByZ.removeAt(idx);
3657 mCurrentState.layersSortedByZ.add(layer);
3658 // we need traversal (state changed)
3659 // AND transaction (list changed)
3660 flags |= eTransactionNeeded|eTraversalNeeded;
3661 }
3662 } else {
3663 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3664 flags |= eTransactionNeeded|eTraversalNeeded;
3665 }
chaviw8b3871a2017-11-01 17:41:01 -07003666 }
3667 }
3668 if (what & layer_state_t::eSizeChanged) {
3669 if (layer->setSize(s.w, s.h)) {
3670 flags |= eTraversalNeeded;
3671 }
3672 }
3673 if (what & layer_state_t::eAlphaChanged) {
3674 if (layer->setAlpha(s.alpha))
3675 flags |= eTraversalNeeded;
3676 }
3677 if (what & layer_state_t::eColorChanged) {
3678 if (layer->setColor(s.color))
3679 flags |= eTraversalNeeded;
3680 }
Peiyong Lind3788632018-09-18 16:01:31 -07003681 if (what & layer_state_t::eColorTransformChanged) {
3682 if (layer->setColorTransform(s.colorTransform)) {
3683 flags |= eTraversalNeeded;
3684 }
3685 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003686 if (what & layer_state_t::eBackgroundColorChanged) {
3687 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3688 flags |= eTraversalNeeded;
3689 }
3690 }
chaviw8b3871a2017-11-01 17:41:01 -07003691 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003692 // TODO: b/109894387
3693 //
3694 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3695 // rotation. To see the problem observe that if we have a square parent, and a child
3696 // of the same size, then we rotate the child 45 degrees around it's center, the child
3697 // must now be cropped to a non rectangular 8 sided region.
3698 //
3699 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3700 // private API, and the WindowManager only uses rotation in one case, which is on a top
3701 // level layer in which cropping is not an issue.
3702 //
3703 // However given that abuse of rotation matrices could lead to surfaces extending outside
3704 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3705 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3706 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003707 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003708 flags |= eTraversalNeeded;
3709 }
3710 if (what & layer_state_t::eTransparentRegionChanged) {
3711 if (layer->setTransparentRegionHint(s.transparentRegion))
3712 flags |= eTraversalNeeded;
3713 }
3714 if (what & layer_state_t::eFlagsChanged) {
3715 if (layer->setFlags(s.flags, s.mask))
3716 flags |= eTraversalNeeded;
3717 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003718 if (what & layer_state_t::eCropChanged_legacy) {
chaviw214c89d2019-09-04 16:03:53 -07003719 if (layer->setCrop_legacy(s.crop_legacy)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07003720 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003721 if (what & layer_state_t::eCornerRadiusChanged) {
3722 if (layer->setCornerRadius(s.cornerRadius))
3723 flags |= eTraversalNeeded;
3724 }
Lucas Dupin130e55c2020-05-26 16:11:18 -07003725 if (what & layer_state_t::eBackgroundBlurRadiusChanged && !mDisableBlurs && mSupportsBlur) {
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08003726 if (layer->setBackgroundBlurRadius(s.backgroundBlurRadius)) flags |= eTraversalNeeded;
3727 }
chaviw8b3871a2017-11-01 17:41:01 -07003728 if (what & layer_state_t::eLayerStackChanged) {
3729 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3730 // We only allow setting layer stacks for top level layers,
3731 // everything else inherits layer stack from its parent.
3732 if (layer->hasParent()) {
3733 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003734 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003735 } else if (idx < 0) {
3736 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003737 "that also does not appear in the top level layer list. Something"
3738 " has gone wrong.",
3739 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003740 } else if (layer->setLayerStack(s.layerStack)) {
3741 mCurrentState.layersSortedByZ.removeAt(idx);
3742 mCurrentState.layersSortedByZ.add(layer);
3743 // we need traversal (state changed)
3744 // AND transaction (list changed)
Vishnu Nair6213bd92020-05-08 17:42:25 -07003745 flags |= eTransactionNeeded | eTraversalNeeded | eTransformHintUpdateNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07003746 }
3747 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003748 if (what & layer_state_t::eDeferTransaction_legacy) {
3749 if (s.barrierHandle_legacy != nullptr) {
3750 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3751 } else if (s.barrierGbp_legacy != nullptr) {
3752 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003753 if (authenticateSurfaceTextureLocked(gbp)) {
3754 const auto& otherLayer =
3755 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003756 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003757 } else {
3758 ALOGE("Attempt to defer transaction to to an"
3759 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003760 }
3761 }
chaviw8b3871a2017-11-01 17:41:01 -07003762 // We don't trigger a traversal here because if no other state is
3763 // changed, we don't want this to cause any more work
3764 }
chaviw8b3871a2017-11-01 17:41:01 -07003765 if (what & layer_state_t::eReparentChildren) {
3766 if (layer->reparentChildren(s.reparentHandle)) {
3767 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003768 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003769 }
chaviw8b3871a2017-11-01 17:41:01 -07003770 if (what & layer_state_t::eDetachChildren) {
3771 layer->detachChildren();
3772 }
3773 if (what & layer_state_t::eOverrideScalingModeChanged) {
3774 layer->setOverrideScalingMode(s.overrideScalingMode);
3775 // We don't trigger a traversal here because if no other state is
3776 // changed, we don't want this to cause any more work
3777 }
Marissa Wall61c58622018-07-18 10:12:20 -07003778 if (what & layer_state_t::eTransformChanged) {
3779 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3780 }
3781 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3782 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3783 flags |= eTraversalNeeded;
3784 }
3785 if (what & layer_state_t::eCropChanged) {
3786 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3787 }
Marissa Wall861616d2018-10-22 12:52:23 -07003788 if (what & layer_state_t::eFrameChanged) {
3789 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3790 }
Marissa Wall61c58622018-07-18 10:12:20 -07003791 if (what & layer_state_t::eAcquireFenceChanged) {
3792 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3793 }
3794 if (what & layer_state_t::eDataspaceChanged) {
3795 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3796 }
3797 if (what & layer_state_t::eHdrMetadataChanged) {
3798 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3799 }
3800 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3801 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3802 }
3803 if (what & layer_state_t::eApiChanged) {
3804 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3805 }
3806 if (what & layer_state_t::eSidebandStreamChanged) {
3807 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3808 }
Robert Carr720e5062018-07-30 17:45:14 -07003809 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08003810 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003811 layer->setInputInfo(s.inputInfo);
3812 flags |= eTraversalNeeded;
3813 } else {
3814 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3815 }
Robert Carr720e5062018-07-30 17:45:14 -07003816 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003817 if (what & layer_state_t::eMetadataChanged) {
3818 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3819 }
Peiyong Linc502cb72019-03-01 15:00:23 -08003820 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
3821 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
3822 flags |= eTraversalNeeded;
3823 }
3824 }
Vishnu Nairc97b8db2019-10-29 18:19:35 -07003825 if (what & layer_state_t::eShadowRadiusChanged) {
3826 if (layer->setShadowRadius(s.shadowRadius)) flags |= eTraversalNeeded;
3827 }
Ana Krulecc84d09b2019-11-02 23:10:29 +01003828 if (what & layer_state_t::eFrameRateSelectionPriority) {
3829 if (privileged && layer->setFrameRateSelectionPriority(s.frameRateSelectionPriority)) {
3830 flags |= eTraversalNeeded;
3831 }
3832 }
Steven Thomas3172e202020-01-06 19:25:30 -08003833 if (what & layer_state_t::eFrameRateChanged) {
Steven Thomas62a4cf82020-01-31 12:04:03 -08003834 if (ValidateFrameRate(s.frameRate, s.frameRateCompatibility,
3835 "SurfaceFlinger::setClientStateLocked") &&
3836 layer->setFrameRate(Layer::FrameRate(s.frameRate,
3837 Layer::FrameRate::convertCompatibility(
3838 s.frameRateCompatibility)))) {
Ady Abraham71c437d2020-01-31 15:56:57 -08003839 flags |= eTraversalNeeded;
Steven Thomas62a4cf82020-01-31 12:04:03 -08003840 }
Steven Thomas3172e202020-01-06 19:25:30 -08003841 }
Vishnu Nair6213bd92020-05-08 17:42:25 -07003842 if (what & layer_state_t::eFixedTransformHintChanged) {
3843 if (layer->setFixedTransformHint(s.fixedTransformHint)) {
3844 flags |= eTraversalNeeded | eTransformHintUpdateNeeded;
3845 }
3846 }
Vishnu Nair14d76922019-08-05 08:41:20 -07003847 // This has to happen after we reparent children because when we reparent to null we remove
3848 // child layers from current state and remove its relative z. If the children are reparented in
3849 // the same transaction, then we have to make sure we reparent the children first so we do not
3850 // lose its relative z order.
3851 if (what & layer_state_t::eReparent) {
3852 bool hadParent = layer->hasParent();
3853 if (layer->reparent(s.parentHandleForChild)) {
3854 if (!hadParent) {
3855 mCurrentState.layersSortedByZ.remove(layer);
3856 }
3857 flags |= eTransactionNeeded | eTraversalNeeded;
3858 }
3859 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003860 std::vector<sp<CallbackHandle>> callbackHandles;
Valerie Hau9dab9732019-08-20 09:29:25 -07003861 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!s.listeners.empty())) {
3862 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003863 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3864 }
3865 }
Marissa Wall78b72202019-03-15 14:58:34 -07003866 bool bufferChanged = what & layer_state_t::eBufferChanged;
3867 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
3868 sp<GraphicBuffer> buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003869 if (bufferChanged && cacheIdChanged && s.buffer != nullptr) {
Marissa Wall78b72202019-03-15 14:58:34 -07003870 buffer = s.buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003871 bool success = ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
3872 if (success) {
3873 getRenderEngine().cacheExternalTextureBuffer(s.buffer);
3874 success = ClientCache::getInstance()
3875 .registerErasedRecipient(s.cachedBuffer,
3876 wp<ClientCache::ErasedRecipient>(this));
3877 if (!success) {
3878 getRenderEngine().unbindExternalTextureBuffer(s.buffer->getId());
3879 }
3880 }
Marissa Wall78b72202019-03-15 14:58:34 -07003881 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003882 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003883 } else if (bufferChanged) {
3884 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08003885 }
Marissa Wall78b72202019-03-15 14:58:34 -07003886 if (buffer) {
Valerie Haubf784642020-01-29 07:25:23 -08003887 if (layer->setBuffer(buffer, s.acquireFence, postTime, desiredPresentTime,
3888 s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08003889 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08003890 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003891 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003892 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3893 // Do not put anything that updates layer state or modifies flags after
3894 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003895 return flags;
3896}
3897
chaviw273171b2018-12-26 11:46:30 -08003898uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3899 uint32_t flags = 0;
chaviwa911b102019-02-14 10:18:33 -08003900 if (inputWindowCommands.syncInputWindows) {
3901 flags |= eTraversalNeeded;
3902 }
3903
Vishnu Nairec0ab382019-02-13 15:32:56 -08003904 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08003905 return flags;
3906}
3907
chaviwfe94a222019-08-21 13:52:59 -07003908status_t SurfaceFlinger::mirrorLayer(const sp<Client>& client, const sp<IBinder>& mirrorFromHandle,
3909 sp<IBinder>* outHandle) {
3910 if (!mirrorFromHandle) {
3911 return NAME_NOT_FOUND;
3912 }
3913
3914 sp<Layer> mirrorLayer;
3915 sp<Layer> mirrorFrom;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003916 std::string uniqueName = getUniqueLayerName("MirrorRoot");
chaviwfe94a222019-08-21 13:52:59 -07003917
3918 {
3919 Mutex::Autolock _l(mStateLock);
Alec Mouri9a02eda2020-04-21 17:39:34 -07003920 mirrorFrom = fromHandleLocked(mirrorFromHandle).promote();
chaviwfe94a222019-08-21 13:52:59 -07003921 if (!mirrorFrom) {
3922 return NAME_NOT_FOUND;
3923 }
3924
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003925 status_t result = createContainerLayer(client, std::move(uniqueName), -1, -1, 0,
3926 LayerMetadata(), outHandle, &mirrorLayer);
chaviwfe94a222019-08-21 13:52:59 -07003927 if (result != NO_ERROR) {
3928 return result;
3929 }
3930
3931 mirrorLayer->mClonedChild = mirrorFrom->createClone();
3932 }
3933
Vishnu Nair6213bd92020-05-08 17:42:25 -07003934 return addClientLayer(client, *outHandle, nullptr, mirrorLayer, nullptr, nullptr, false,
3935 nullptr /* outTransformHint */);
chaviwfe94a222019-08-21 13:52:59 -07003936}
3937
Marissa Wall2d814fb2019-04-09 18:52:57 +00003938status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
3939 uint32_t h, PixelFormat format, uint32_t flags,
3940 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07003941 sp<IGraphicBufferProducer>* gbp,
Valerie Hau1acd6962019-10-28 16:35:48 -07003942 const sp<IBinder>& parentHandle, const sp<Layer>& parentLayer,
3943 uint32_t* outTransformHint) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003944 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003945 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003946 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003947 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003948 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003949
Robert Carrc0df3122019-04-11 13:18:21 -07003950 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
3951 "Expected only one of parentLayer or parentHandle to be non-null. "
3952 "Programmer error?");
3953
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003954 status_t result = NO_ERROR;
3955
3956 sp<Layer> layer;
3957
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003958 std::string uniqueName = getUniqueLayerName(name.string());
Cody Northropbc755282017-03-31 12:00:08 -06003959
Evan Roskya1f1e152019-01-24 16:17:46 -08003960 bool primaryDisplayOnly = false;
3961
3962 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3963 // TODO b/64227542
3964 if (metadata.has(METADATA_WINDOW_TYPE)) {
3965 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
3966 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07003967 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08003968 primaryDisplayOnly = true;
3969 }
3970 }
3971
Mathias Agopian3165cc22012-08-08 19:42:09 -07003972 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003973 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003974 result = createBufferQueueLayer(client, std::move(uniqueName), w, h, flags,
3975 std::move(metadata), format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003976
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003977 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003978 case ISurfaceComposerClient::eFXSurfaceBufferState:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003979 result = createBufferStateLayer(client, std::move(uniqueName), w, h, flags,
Vishnu Nair6213bd92020-05-08 17:42:25 -07003980 std::move(metadata), handle, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07003981 break;
Vishnu Nairfa247b12020-02-11 08:58:26 -08003982 case ISurfaceComposerClient::eFXSurfaceEffect:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003983 // check if buffer size is set for color layer.
3984 if (w > 0 || h > 0) {
3985 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3986 int(w), int(h));
3987 return BAD_VALUE;
3988 }
3989
Vishnu Nairfa247b12020-02-11 08:58:26 -08003990 result = createEffectLayer(client, std::move(uniqueName), w, h, flags,
3991 std::move(metadata), handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003992 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003993 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003994 // check if buffer size is set for container layer.
3995 if (w > 0 || h > 0) {
3996 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3997 int(w), int(h));
3998 return BAD_VALUE;
3999 }
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004000 result = createContainerLayer(client, std::move(uniqueName), w, h, flags,
4001 std::move(metadata), handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07004002 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004003 default:
4004 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004005 break;
4006 }
4007
Dan Stoza7d89d062015-04-30 13:29:25 -07004008 if (result != NO_ERROR) {
4009 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004010 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004011
Evan Roskya1f1e152019-01-24 16:17:46 -08004012 if (primaryDisplayOnly) {
4013 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07004014 }
4015
Robert Carrb89ea9d2018-12-10 13:01:14 -08004016 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07004017 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
Vishnu Nair6213bd92020-05-08 17:42:25 -07004018 addToCurrentState, outTransformHint);
Dan Stoza7d89d062015-04-30 13:29:25 -07004019 if (result != NO_ERROR) {
4020 return result;
4021 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004022 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004023
4024 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004025 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004026}
4027
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004028std::string SurfaceFlinger::getUniqueLayerName(const char* name) {
4029 unsigned dupeCounter = 0;
Cody Northropbc755282017-03-31 12:00:08 -06004030
4031 // Tack on our counter whether there is a hit or not, so everyone gets a tag
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004032 std::string uniqueName = base::StringPrintf("%s#%u", name, dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06004033
Dan Stoza436ccf32018-06-21 12:10:12 -07004034 // Grab the state lock since we're accessing mCurrentState
4035 Mutex::Autolock lock(mStateLock);
4036
Cody Northropbc755282017-03-31 12:00:08 -06004037 // Loop over layers until we're sure there is no matching name
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004038 bool matchFound = true;
Cody Northropbc755282017-03-31 12:00:08 -06004039 while (matchFound) {
4040 matchFound = false;
Edgar Arriaga844fa672020-01-16 14:21:42 -08004041 mCurrentState.traverse([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004042 if (layer->getName() == uniqueName) {
4043 matchFound = true;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004044 uniqueName = base::StringPrintf("%s#%u", name, ++dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06004045 }
4046 });
4047 }
4048
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004049 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name, uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004050 return uniqueName;
4051}
4052
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004053status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, std::string name,
Marissa Wallfd668622018-05-10 10:21:13 -07004054 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08004055 LayerMetadata metadata, PixelFormat& format,
4056 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07004057 sp<IGraphicBufferProducer>* gbp,
4058 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004059 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004060 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004061 case PIXEL_FORMAT_TRANSPARENT:
4062 case PIXEL_FORMAT_TRANSLUCENT:
4063 format = PIXEL_FORMAT_RGBA_8888;
4064 break;
4065 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004066 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004067 break;
4068 }
4069
chaviwb4c6e582019-08-16 14:35:07 -07004070 sp<BufferQueueLayer> layer;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004071 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07004072 args.textureName = getNewTexture();
4073 {
4074 // Grab the SF state lock during this since it's the only safe way to access
4075 // RenderEngine when creating a BufferLayerConsumer
4076 // TODO: Check if this lock is still needed here
4077 Mutex::Autolock lock(mStateLock);
4078 layer = getFactory().createBufferQueueLayer(args);
4079 }
4080
Marissa Wallfd668622018-05-10 10:21:13 -07004081 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004082 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004083 *handle = layer->getHandle();
4084 *gbp = layer->getProducer();
4085 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004086 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004087
Marissa Wallfd668622018-05-10 10:21:13 -07004088 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004089 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004090}
4091
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004092status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, std::string name,
Marissa Wall61c58622018-07-18 10:12:20 -07004093 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08004094 LayerMetadata metadata, sp<IBinder>* handle,
Vishnu Nair6213bd92020-05-08 17:42:25 -07004095 sp<Layer>* outLayer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004096 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07004097 args.textureName = getNewTexture();
4098 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(args);
Marissa Wall61c58622018-07-18 10:12:20 -07004099 *handle = layer->getHandle();
4100 *outLayer = layer;
4101
4102 return NO_ERROR;
4103}
4104
Vishnu Nairfa247b12020-02-11 08:58:26 -08004105status_t SurfaceFlinger::createEffectLayer(const sp<Client>& client, std::string name, uint32_t w,
4106 uint32_t h, uint32_t flags, LayerMetadata metadata,
4107 sp<IBinder>* handle, sp<Layer>* outLayer) {
4108 *outLayer = getFactory().createEffectLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004109 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004110 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004111 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004112}
4113
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004114status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, std::string name,
Evan Roskya1f1e152019-01-24 16:17:46 -08004115 uint32_t w, uint32_t h, uint32_t flags,
4116 LayerMetadata metadata, sp<IBinder>* handle,
4117 sp<Layer>* outLayer) {
4118 *outLayer = getFactory().createContainerLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004119 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Robert Carr6b3f6c52018-08-13 13:05:17 -07004120 *handle = (*outLayer)->getHandle();
4121 return NO_ERROR;
4122}
4123
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004124void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004125 mLayersPendingRemoval.add(layer);
4126 mLayersRemoved = true;
4127 setTransactionFlags(eTransactionNeeded);
4128}
4129
Robert Carr695d5282018-12-18 15:27:58 -08004130void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004131{
Robert Carr2e102c92018-10-23 12:11:15 -07004132 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004133 // If a layer has a parent, we allow it to out-live it's handle
4134 // with the idea that the parent holds a reference and will eventually
4135 // be cleaned up. However no one cleans up the top-level so we do so
4136 // here.
4137 if (layer->getParent() == nullptr) {
4138 mCurrentState.layersSortedByZ.remove(layer);
4139 }
4140 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07004141
4142 auto it = mLayersByLocalBinderToken.begin();
4143 while (it != mLayersByLocalBinderToken.end()) {
4144 if (it->second == layer) {
4145 it = mLayersByLocalBinderToken.erase(it);
4146 } else {
4147 it++;
4148 }
4149 }
4150
Robert Carr695d5282018-12-18 15:27:58 -08004151 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004152}
4153
Mathias Agopianb60314a2012-04-10 22:09:54 -07004154// ---------------------------------------------------------------------------
4155
Andy McFadden13a082e2012-08-24 10:16:42 -07004156void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004157 const auto display = getDefaultDisplayDeviceLocked();
4158 if (!display) return;
4159
4160 const sp<IBinder> token = display->getDisplayToken().promote();
4161 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004162
Jesse Hall01e29052013-02-19 16:13:35 -08004163 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004164 Vector<ComposerState> state;
4165 Vector<DisplayState> displays;
4166 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004167 d.what = DisplayState::eDisplayProjectionChanged |
4168 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004169 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004170 d.layerStack = 0;
Dominik Laskowski718f9602019-11-09 20:01:35 -08004171 d.orientation = ui::ROTATION_0;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004172 d.frame.makeInvalid();
4173 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004174 d.width = 0;
4175 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004176 displays.add(d);
Valerie Hau9dab9732019-08-20 09:29:25 -07004177 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, false,
4178 {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07004179
Peiyong Lin65248e02020-04-18 21:15:07 -07004180 setPowerModeInternal(display, hal::PowerMode::ON);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004181
Dominik Laskowski83b88212018-12-11 13:34:06 -08004182 const nsecs_t vsyncPeriod = getVsyncPeriod();
4183 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004184
Brian Andersond0010582017-03-07 13:20:31 -08004185 // Use phase of 0 since phase is not known.
4186 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004187 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004188 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004189}
4190
4191void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004192 // Async since we may be called from the main thread.
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07004193 static_cast<void>(schedule([this]() MAIN_THREAD { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004194}
4195
Peiyong Lin65248e02020-04-18 21:15:07 -07004196void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, hal::PowerMode mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004197 if (display->isVirtual()) {
4198 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004199 return;
4200 }
4201
Dominik Laskowski075d3172018-05-24 15:50:06 -07004202 const auto displayId = display->getId();
4203 LOG_ALWAYS_FATAL_IF(!displayId);
4204
Dominik Laskowski34157762018-10-31 13:07:19 -07004205 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004206
Peiyong Lin65248e02020-04-18 21:15:07 -07004207 const hal::PowerMode currentMode = display->getPowerMode();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004208 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004209 return;
4210 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004211
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004212 display->setPowerMode(mode);
4213
Lloyd Pique4dccc412018-01-22 17:21:36 -08004214 if (mInterceptor->isEnabled()) {
Peiyong Lin65248e02020-04-18 21:15:07 -07004215 mInterceptor->savePowerModeUpdate(display->getSequenceId(), static_cast<int32_t>(mode));
Irvelffc9efc2016-07-27 15:16:37 -07004216 }
4217
Peiyong Lin65248e02020-04-18 21:15:07 -07004218 if (currentMode == hal::PowerMode::OFF) {
Martin Liu4a322352020-03-24 21:30:38 +08004219 if (SurfaceFlinger::setSchedFifo(true) != NO_ERROR) {
4220 ALOGW("Couldn't set SCHED_FIFO on display on: %s\n", strerror(errno));
4221 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004222 getHwComposer().setPowerMode(*displayId, mode);
Peiyong Lin65248e02020-04-18 21:15:07 -07004223 if (display->isPrimary() && mode != hal::PowerMode::DOZE_SUSPEND) {
Marin Shalamanovc75b0772020-06-12 22:29:11 +02004224 getHwComposer().setVsyncEnabled(*displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08004225 mScheduler->onScreenAcquired(mAppConnectionHandle);
4226 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004227 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004228
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004229 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004230 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004231 repaintEverything();
Peiyong Lin65248e02020-04-18 21:15:07 -07004232 } else if (mode == hal::PowerMode::OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004233 // Turn off the display
Martin Liu4a322352020-03-24 21:30:38 +08004234 if (SurfaceFlinger::setSchedFifo(false) != NO_ERROR) {
4235 ALOGW("Couldn't set SCHED_OTHER on display off: %s\n", strerror(errno));
Tim Murrayf9d4e442016-08-02 15:43:59 -07004236 }
Peiyong Lin65248e02020-04-18 21:15:07 -07004237 if (display->isPrimary() && currentMode != hal::PowerMode::DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004238 mScheduler->disableHardwareVsync(true);
4239 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004240 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004241
Ady Abraham27c70212019-06-11 10:52:26 -07004242 // Make sure HWVsync is disabled before turning off the display
Marin Shalamanovc75b0772020-06-12 22:29:11 +02004243 getHwComposer().setVsyncEnabled(*displayId, hal::Vsync::DISABLE);
Ady Abraham27c70212019-06-11 10:52:26 -07004244
Dominik Laskowski075d3172018-05-24 15:50:06 -07004245 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004246 mVisibleRegionsDirty = true;
4247 // from this point on, SF will stop drawing on this display
Peiyong Lin65248e02020-04-18 21:15:07 -07004248 } else if (mode == hal::PowerMode::DOZE || mode == hal::PowerMode::ON) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004249 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004250 getHwComposer().setPowerMode(*displayId, mode);
Peiyong Lin65248e02020-04-18 21:15:07 -07004251 if (display->isPrimary() && currentMode == hal::PowerMode::DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004252 mScheduler->onScreenAcquired(mAppConnectionHandle);
4253 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004254 }
Peiyong Lin65248e02020-04-18 21:15:07 -07004255 } else if (mode == hal::PowerMode::DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004256 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004257 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004258 mScheduler->disableHardwareVsync(true);
4259 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004260 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004261 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004262 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004263 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004264 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004265 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004266
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004267 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004268 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004269 mRefreshRateStats->setPowerMode(mode);
Peiyong Lin65248e02020-04-18 21:15:07 -07004270 mScheduler->setDisplayPowerState(mode == hal::PowerMode::ON);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004271 }
4272
Dominik Laskowski34157762018-10-31 13:07:19 -07004273 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004274}
4275
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004276void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07004277 schedule([=]() MAIN_THREAD {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07004278 const auto display = getDisplayDeviceLocked(displayToken);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004279 if (!display) {
4280 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4281 displayToken.get());
4282 } else if (display->isVirtual()) {
4283 ALOGW("Attempt to set power mode %d for virtual display", mode);
4284 } else {
Peiyong Lin65248e02020-04-18 21:15:07 -07004285 setPowerModeInternal(display, static_cast<hal::PowerMode>(mode));
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004286 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07004287 }).wait();
Mathias Agopianb60314a2012-04-10 22:09:54 -07004288}
4289
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07004290status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args, bool asProto) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004291 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004292
Mathias Agopianbd115332013-04-18 16:41:04 -07004293 IPCThreadState* ipc = IPCThreadState::self();
4294 const int pid = ipc->getCallingPid();
4295 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004296
Mathias Agopianbd115332013-04-18 16:41:04 -07004297 if ((uid != AID_SHELL) &&
4298 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004299 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4300 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004301 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004302 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004303 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski98041832019-08-01 18:35:59 -07004304 {"--dispsync"s,
4305 dumper([this](std::string& s) { mScheduler->getPrimaryDispSync().dump(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004306 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004307 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4308 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4309 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4310 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4311 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4312 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004313 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004314 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4315 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004316
Dominik Laskowskic2867142019-01-21 11:33:38 -08004317 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004318
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07004319 bool dumpLayers = true;
4320 {
4321 TimedLock lock(mStateLock, s2ns(1), __FUNCTION__);
4322 if (!lock.locked()) {
4323 StringAppendF(&result, "Dumping without lock after timeout: %s (%d)\n",
4324 strerror(-lock.status), lock.status);
4325 }
4326
4327 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4328 (it->second)(args, asProto, result);
4329 dumpLayers = false;
4330 } else if (!asProto) {
4331 dumpAllLocked(args, result);
4332 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004333 }
4334
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07004335 if (dumpLayers) {
Dominik Laskowski46470112019-08-02 13:13:11 -07004336 const LayersProto layersProto = dumpProtoFromMainThread();
4337 if (asProto) {
4338 result.append(layersProto.SerializeAsString());
4339 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004340 // Dump info that we need to access from the main thread
Dominik Laskowski46470112019-08-02 13:13:11 -07004341 const auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4342 result.append(LayerProtoParser::layerTreeToString(layerTree));
4343 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07004344 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07004345 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004346 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004347 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004348 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004349 return NO_ERROR;
4350}
4351
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004352status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4353 if (asProto && mTracing.isEnabled()) {
4354 mTracing.writeToFileAsync();
4355 }
4356
4357 return doDump(fd, DumpArgs(), asProto);
4358}
4359
Dominik Laskowskic2867142019-01-21 11:33:38 -08004360void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004361 mCurrentState.traverseInZOrder(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004362 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getDebugName()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004363}
4364
Dominik Laskowskic2867142019-01-21 11:33:38 -08004365void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004366 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004367
Dominik Laskowskic2867142019-01-21 11:33:38 -08004368 if (args.size() > 1) {
4369 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004370 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004371 if (layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004372 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004373 }
Robert Carr2047fae2016-11-28 14:09:09 -08004374 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004375 } else {
4376 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004377 }
4378}
4379
Dominik Laskowskic2867142019-01-21 11:33:38 -08004380void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004381 const bool clearAll = args.size() < 2;
4382 const auto name = clearAll ? String8() : String8(args[1]);
4383
Edgar Arriaga844fa672020-01-16 14:21:42 -08004384 mCurrentState.traverse([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004385 if (clearAll || layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004386 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004387 }
Robert Carr2047fae2016-11-28 14:09:09 -08004388 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004389
Svetoslavd85084b2014-03-20 10:28:31 -07004390 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004391}
4392
Dominik Laskowskic2867142019-01-21 11:33:38 -08004393void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4394 mTimeStats->parseArgs(asProto, args, result);
4395}
4396
Jamie Gennis6547ff42013-07-16 20:12:42 -07004397// This should only be called from the main thread. Otherwise it would need
4398// the lock and should use mCurrentState rather than mDrawingState.
4399void SurfaceFlinger::logFrameStats() {
Edgar Arriaga844fa672020-01-16 14:21:42 -08004400 mDrawingState.traverse([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004401 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004402 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004403
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004404 mAnimFrameTracker.logAndResetStats("<win-anim>");
Jamie Gennis6547ff42013-07-16 20:12:42 -07004405}
4406
Yiwei Zhang5434a782018-12-05 18:06:32 -08004407void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004408 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004409
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004410 if (isLayerTripleBufferingDisabled())
4411 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004412
Yiwei Zhang5434a782018-12-05 18:06:32 -08004413 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4414 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4415 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4416 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4417 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4418 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004419 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004420}
4421
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004422void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07004423 mScheduler->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004424
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004425 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004426 result.append("\n");
4427
Ady Abraham9e16a482019-12-03 17:19:41 -08004428 mPhaseConfiguration->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004429 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07004430 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004431 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004432
Steven Thomasd4071902020-03-24 16:02:53 -07004433 scheduler::RefreshRateConfigs::Policy policy = mRefreshRateConfigs->getDisplayManagerPolicy();
Ana Krulec234bb162019-11-10 22:55:55 +01004434 StringAppendF(&result,
Ady Abraham07e54702020-04-16 15:05:37 -07004435 "DesiredDisplayConfigSpecs (DisplayManager): default config ID: %d"
Steven Thomasf734df42020-04-13 21:09:28 -07004436 ", primary range: [%.2f %.2f], app request range: [%.2f %.2f]\n\n",
4437 policy.defaultConfig.value(), policy.primaryRange.min, policy.primaryRange.max,
4438 policy.appRequestRange.min, policy.appRequestRange.max);
Ady Abraham42b3beb2019-07-09 18:09:52 -07004439 StringAppendF(&result, "(config override by backdoor: %s)\n\n",
4440 mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
Ady Abraham07e54702020-04-16 15:05:37 -07004441 scheduler::RefreshRateConfigs::Policy currentPolicy = mRefreshRateConfigs->getCurrentPolicy();
4442 if (currentPolicy != policy) {
4443 StringAppendF(&result,
4444 "DesiredDisplayConfigSpecs (Override): default config ID: %d"
Steven Thomasf734df42020-04-13 21:09:28 -07004445 ", primary range: [%.2f %.2f], app request range: [%.2f %.2f]\n\n",
4446 currentPolicy.defaultConfig.value(), currentPolicy.primaryRange.min,
4447 currentPolicy.primaryRange.max, currentPolicy.appRequestRange.min,
4448 currentPolicy.appRequestRange.max);
Ady Abraham07e54702020-04-16 15:05:37 -07004449 }
Dominik Laskowski98041832019-08-01 18:35:59 -07004450
Ana Krulecc2870422019-01-29 19:00:58 -08004451 mScheduler->dump(mAppConnectionHandle, result);
Ady Abraham75398722020-04-07 14:08:45 -07004452 mScheduler->getPrimaryDispSync().dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004453}
4454
Yiwei Zhang5434a782018-12-05 18:06:32 -08004455void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4456 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004457 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4458 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004459 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004460 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004461 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004462 }
David Sodman4a36e932017-11-07 14:29:47 -08004463 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004464 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004465 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004466 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4467 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004468}
4469
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004470void SurfaceFlinger::recordBufferingStats(const std::string& layerName,
4471 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004472 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4473 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004474 for (const auto& segment : history) {
4475 if (!segment.usedThirdBuffer) {
4476 stats.twoBufferTime += segment.totalTime;
4477 }
4478 if (segment.occupancyAverage < 1.0f) {
4479 stats.doubleBufferedTime += segment.totalTime;
4480 } else if (segment.occupancyAverage < 2.0f) {
4481 stats.tripleBufferedTime += segment.totalTime;
4482 }
4483 ++stats.numSegments;
4484 stats.totalTime += segment.totalTime;
4485 }
4486}
4487
Yiwei Zhang5434a782018-12-05 18:06:32 -08004488void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4489 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004490
4491 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4492 const size_t count = currentLayers.size();
4493 for (size_t i=0 ; i<count ; i++) {
4494 currentLayers[i]->dumpFrameEvents(result);
4495 }
4496}
4497
Yiwei Zhang5434a782018-12-05 18:06:32 -08004498void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004499 result.append("Buffering stats:\n");
4500 result.append(" [Layer name] <Active time> <Two buffer> "
4501 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004502 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004503 typedef std::tuple<std::string, float, float, float> BufferTuple;
4504 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004505 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004506 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004507 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004508 if (stats.numSegments == 0) {
4509 continue;
4510 }
4511 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4512 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4513 stats.totalTime;
4514 float doubleBufferRatio = static_cast<float>(
4515 stats.doubleBufferedTime) / stats.totalTime;
4516 float tripleBufferRatio = static_cast<float>(
4517 stats.tripleBufferedTime) / stats.totalTime;
4518 sorted.insert({activeTime, {name, twoBufferRatio,
4519 doubleBufferRatio, tripleBufferRatio}});
4520 }
4521 for (const auto& sortedPair : sorted) {
4522 float activeTime = sortedPair.first;
4523 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004524 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4525 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004526 }
4527 result.append("\n");
4528}
4529
Yiwei Zhang5434a782018-12-05 18:06:32 -08004530void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004531 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004532 const auto displayId = display->getId();
4533 if (!displayId) {
4534 continue;
4535 }
4536 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004537 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004538 continue;
4539 }
4540
Yiwei Zhang5434a782018-12-05 18:06:32 -08004541 StringAppendF(&result,
4542 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4543 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004544 uint8_t port;
4545 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004546 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004547 result.append("no identification data\n");
4548 continue;
4549 }
4550
4551 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004552 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004553 continue;
4554 }
4555
4556 const auto edid = parseEdid(data);
4557 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004558 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004559 continue;
4560 }
4561
Yiwei Zhang5434a782018-12-05 18:06:32 -08004562 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004563 result.append(edid->displayName.data(), edid->displayName.length());
4564 result.append("\"\n");
4565 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004566}
4567
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004568void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
4569 std::string& result) const {
Peiyong Line9d809e2020-04-14 13:10:48 -07004570 hal::HWDisplayId hwcDisplayId;
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004571 uint8_t port;
4572 DisplayIdentificationData data;
4573
4574 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
4575 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
4576 result.append(reinterpret_cast<const char*>(data.data()), data.size());
4577 }
4578}
4579
Yiwei Zhang5434a782018-12-05 18:06:32 -08004580void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004581 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004582 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4583 StringAppendF(&result, "DisplayColorSetting: %s\n",
4584 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004585
4586 // TODO: print out if wide-color mode is active or not
4587
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004588 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004589 const auto displayId = display->getId();
4590 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004591 continue;
4592 }
4593
Yiwei Zhang5434a782018-12-05 18:06:32 -08004594 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004595 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004596 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004597 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004598 }
4599
Lloyd Pique32cbe282018-10-19 13:09:22 -07004600 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004601 StringAppendF(&result, " Current color mode: %s (%d)\n",
4602 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004603 }
4604 result.append("\n");
4605}
4606
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07004607LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
4608 // If context is SurfaceTracing thread, mTracingLock blocks display transactions on main thread.
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07004609 const auto display = ON_MAIN_THREAD(getDefaultDisplayDeviceLocked());
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07004610
chaviw1d044282017-09-27 12:19:28 -07004611 LayersProto layersProto;
chaviw08f3cb22020-01-13 13:17:21 -08004612 for (const sp<Layer>& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskib7251f42020-04-20 17:42:59 -07004613 layer->writeToProto(layersProto, traceFlags, display.get());
chaviw08f3cb22020-01-13 13:17:21 -08004614 }
Alec Mouri6b9e9912020-01-21 10:50:24 -08004615
chaviw1d044282017-09-27 12:19:28 -07004616 return layersProto;
4617}
4618
Alec Mouri6b9e9912020-01-21 10:50:24 -08004619void SurfaceFlinger::dumpHwc(std::string& result) const {
4620 getHwComposer().dump(result);
4621}
4622
Vishnu Nair0f085c62019-08-30 08:49:12 -07004623void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
4624 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
4625 // it.
4626 LayerProto* rootProto = layersProto.add_layers();
4627 const int32_t offscreenRootLayerId = INT32_MAX - 2;
4628 rootProto->set_id(offscreenRootLayerId);
4629 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07004630 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004631
4632 for (Layer* offscreenLayer : mOffscreenLayers) {
4633 // Add layer as child of the fake root
4634 rootProto->add_children(offscreenLayer->sequence);
4635
4636 // Add layer
Alec Mouri6b9e9912020-01-21 10:50:24 -08004637 LayerProto* layerProto =
4638 offscreenLayer->writeToProto(layersProto, traceFlags, nullptr /*device*/);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004639 layerProto->set_parent(offscreenRootLayerId);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004640 }
4641}
4642
Vishnu Nair8406fd72019-07-30 11:29:31 -07004643LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07004644 return schedule([=] { return dumpDrawingStateProto(traceFlags); }).get();
Vishnu Nair8406fd72019-07-30 11:29:31 -07004645}
4646
Vishnu Nair0f085c62019-08-30 08:49:12 -07004647void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
4648 result.append("Offscreen Layers:\n");
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07004649 result.append(schedule([this] {
4650 std::string result;
4651 for (Layer* offscreenLayer : mOffscreenLayers) {
4652 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
4653 [&](Layer* layer) {
4654 layer->dumpCallingUidPid(result);
4655 });
4656 }
4657 return result;
4658 }).get());
Vishnu Nair0f085c62019-08-30 08:49:12 -07004659}
4660
Dominik Laskowskic2867142019-01-21 11:33:38 -08004661void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4662 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004663 Colorizer colorizer(colorize);
4664
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004665 // figure out if we're stuck somewhere
4666 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004667 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004668 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4669
4670 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004671 * Dump library configuration.
4672 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004673
4674 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004675 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004676 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004677 appendSfConfigString(result);
4678 appendUiConfigString(result);
4679 appendGuiConfigString(result);
4680 result.append("\n");
4681
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004682 result.append("\nDisplay identification data:\n");
4683 dumpDisplayIdentificationData(result);
4684
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004685 result.append("\nWide-Color information:\n");
4686 dumpWideColorInfo(result);
4687
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004688 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004689 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004690 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004691 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004692 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004693
Andy McFadden41d67d72014-04-25 16:58:34 -07004694 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004695 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004696 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004697 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004698 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004699
Dan Stozab90cf072015-03-05 11:05:59 -08004700 dumpStaticScreenStats(result);
4701 result.append("\n");
4702
Alec Mouri40189b02019-03-05 15:07:54 -08004703 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4704 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4705 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004706
Dan Stozae77c7662016-05-13 11:37:28 -07004707 dumpBufferingStats(result);
4708
Andy McFadden4803b742012-09-24 19:07:20 -07004709 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004710 * Dump the visible layer list
4711 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004712 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07004713 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Yiwei Zhang5434a782018-12-05 18:06:32 -08004714 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4715 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004716 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004717
Chia-I Wu2f884132018-09-13 15:17:58 -07004718 {
Lloyd Pique207def92019-02-28 16:09:52 -08004719 StringAppendF(&result, "Composition layers\n");
4720 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08004721 auto* compositionState = layer->getCompositionState();
Vishnu Nair49529172020-02-25 10:19:44 -08004722 if (!compositionState || !compositionState->isVisible) return;
Lloyd Piquede196652020-01-22 17:29:58 -08004723
4724 android::base::StringAppendF(&result, "* Layer %p (%s)\n", layer,
4725 layer->getDebugName() ? layer->getDebugName()
4726 : "<unknown>");
4727 compositionState->dump(result);
Lloyd Pique207def92019-02-28 16:09:52 -08004728 });
4729 }
4730
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004731 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004732 * Dump Display state
4733 */
4734
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004735 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004736 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004737 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004738 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004739 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004740 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004741 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004742
4743 /*
Lloyd Piquec3cb7292019-05-17 15:25:14 -07004744 * Dump CompositionEngine state
4745 */
4746
4747 mCompositionEngine->dump(result);
4748
4749 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004750 * Dump SurfaceFlinger global state
4751 */
4752
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004753 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004754 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004755 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004756
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004757 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004758
Ady Abrahama3b08ef2019-07-15 18:43:10 -07004759 DebugEGLImageTracker::getInstance()->dump(result);
4760
Dominik Laskowski075d3172018-05-24 15:50:06 -07004761 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004762 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4763 "undefinedRegion");
Dominik Laskowski718f9602019-11-09 20:01:35 -08004764 StringAppendF(&result, " orientation=%s, isPoweredOn=%d\n",
4765 toCString(display->getOrientation()), display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004766 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004767 StringAppendF(&result,
4768 " transaction-flags : %08x\n"
4769 " gpu_to_cpu_unsupported : %d\n",
4770 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004771
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004772 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004773 displayId && getHwComposer().isConnected(*displayId)) {
4774 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004775 StringAppendF(&result,
4776 " refresh-rate : %f fps\n"
4777 " x-dpi : %f\n"
4778 " y-dpi : %f\n",
Ady Abraham3a77a7b2019-12-02 18:46:59 -08004779 1e9 / getHwComposer().getDisplayVsyncPeriod(*displayId),
4780 activeConfig->getDpiX(), activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004781 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004782
Yiwei Zhang5434a782018-12-05 18:06:32 -08004783 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004784
Dan Stozae22aec72016-08-01 13:20:59 -07004785 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004786 * Tracing state
4787 */
4788 mTracing.dump(result);
4789 result.append("\n");
4790
4791 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004792 * HWC layer minidump
4793 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004794 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004795 const auto displayId = display->getId();
4796 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004797 continue;
4798 }
4799
Yiwei Zhang5434a782018-12-05 18:06:32 -08004800 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004801 Layer::miniDumpHeader(result);
Dominik Laskowskib7251f42020-04-20 17:42:59 -07004802
4803 const DisplayDevice& ref = *display;
4804 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, ref); });
Dan Stozae22aec72016-08-01 13:20:59 -07004805 result.append("\n");
4806 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004807
4808 /*
4809 * Dump HWComposer state
4810 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004811 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004812 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004813 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004814 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004815 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004816 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004817
4818 /*
4819 * Dump gralloc state
4820 */
4821 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4822 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004823
4824 /*
4825 * Dump VrFlinger state if in use.
4826 */
4827 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4828 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004829 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004830 result.append("\n");
4831 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004832
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07004833 result.append(mTimeStats->miniDump());
4834 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004835}
4836
Chia-I Wu28f320b2018-05-03 11:02:56 -07004837void SurfaceFlinger::updateColorMatrixLocked() {
4838 mat4 colorMatrix;
4839 if (mGlobalSaturationFactor != 1.0f) {
4840 // Rec.709 luma coefficients
4841 float3 luminance{0.213f, 0.715f, 0.072f};
4842 luminance *= 1.0f - mGlobalSaturationFactor;
4843 mat4 saturationMatrix = mat4(
4844 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4845 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4846 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4847 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4848 );
4849 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4850 } else {
4851 colorMatrix = mClientColorMatrix * mDaltonizer();
4852 }
4853
4854 if (mCurrentState.colorMatrix != colorMatrix) {
4855 mCurrentState.colorMatrix = colorMatrix;
4856 mCurrentState.colorMatrixChanged = true;
4857 setTransactionFlags(eTransactionNeeded);
4858 }
4859}
4860
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004861status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004862#pragma clang diagnostic push
4863#pragma clang diagnostic error "-Wswitch-enum"
4864 switch (static_cast<ISurfaceComposerTag>(code)) {
4865 // These methods should at minimum make sure that the client requested
4866 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004867 case BOOT_FINISHED:
4868 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004869 case CREATE_DISPLAY:
4870 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004871 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004872 case GET_ANIMATION_FRAME_STATS:
4873 case GET_HDR_CAPABILITIES:
Ana Krulec0782b882019-10-15 17:34:54 -07004874 case SET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec234bb162019-11-10 22:55:55 +01004875 case GET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004876 case SET_ACTIVE_COLOR_MODE:
Galia Peycheva5492cb52019-10-30 14:13:16 +01004877 case GET_AUTO_LOW_LATENCY_MODE_SUPPORT:
4878 case SET_AUTO_LOW_LATENCY_MODE:
4879 case GET_GAME_CONTENT_TYPE_SUPPORT:
4880 case SET_GAME_CONTENT_TYPE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004881 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004882 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004883 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004884 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Ady Abraham8532d012019-05-08 14:50:56 -07004885 case GET_DISPLAYED_CONTENT_SAMPLE:
Lais Andrade3a6e47d2020-04-02 11:20:16 +01004886 case NOTIFY_POWER_BOOST:
Steven Thomasd4071902020-03-24 16:02:53 -07004887 case SET_GLOBAL_SHADOW_SETTINGS:
4888 case ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN: {
4889 // ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN is used by CTS tests, which acquire the
4890 // necessary permission dynamically. Don't use the permission cache for this check.
4891 bool usePermissionCache = code != ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN;
4892 if (!callingThreadHasUnscopedSurfaceFlingerAccess(usePermissionCache)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004893 IPCThreadState* ipc = IPCThreadState::self();
4894 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4895 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004896 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004897 }
Robert Carr1db73f62016-12-21 12:58:51 -08004898 return OK;
4899 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004900 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004901 IPCThreadState* ipc = IPCThreadState::self();
4902 const int pid = ipc->getCallingPid();
4903 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004904 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4905 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004906 return PERMISSION_DENIED;
4907 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004908 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004909 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004910 // Used by apps to hook Choreographer to SurfaceFlinger.
4911 case CREATE_DISPLAY_EVENT_CONNECTION:
4912 // The following calls are currently used by clients that do not
4913 // request necessary permissions. However, they do not expose any secret
4914 // information, so it is OK to pass them.
4915 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07004916 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004917 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004918 case GET_PHYSICAL_DISPLAY_IDS:
4919 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004920 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004921 case GET_DISPLAY_NATIVE_PRIMARIES:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004922 case GET_DISPLAY_INFO:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004923 case GET_DISPLAY_CONFIGS:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004924 case GET_DISPLAY_STATE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004925 case GET_DISPLAY_STATS:
4926 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4927 // Calling setTransactionState is safe, because you need to have been
4928 // granted a reference to Client* and Handle* to do anything with it.
4929 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004930 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004931 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004932 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004933 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00004934 case IS_WIDE_COLOR_DISPLAY:
Steven Thomas62a4cf82020-01-31 12:04:03 -08004935 // setFrameRate() is deliberately available for apps to call without any
4936 // special permissions.
4937 case SET_FRAME_RATE:
Dan Gittik57e63c52019-01-18 16:37:54 +00004938 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
4939 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004940 return OK;
4941 }
Chong Zhangd1690d12019-10-04 17:47:13 +00004942 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08004943 case CAPTURE_SCREEN:
4944 case ADD_REGION_SAMPLING_LISTENER:
4945 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004946 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004947 IPCThreadState* ipc = IPCThreadState::self();
4948 const int pid = ipc->getCallingPid();
4949 const int uid = ipc->getCallingUid();
4950 if ((uid != AID_GRAPHICS) &&
4951 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4952 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4953 return PERMISSION_DENIED;
4954 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004955 return OK;
4956 }
chaviw93df2ea2019-04-30 16:45:12 -07004957 case CAPTURE_SCREEN_BY_ID: {
4958 IPCThreadState* ipc = IPCThreadState::self();
4959 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07004960 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07004961 return OK;
4962 }
4963 return PERMISSION_DENIED;
4964 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004965 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004966
4967 // These codes are used for the IBinder protocol to either interrogate the recipient
4968 // side of the transaction for its canonical interface descriptor or to dump its state.
4969 // We let them pass by default.
4970 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4971 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4972 code == IBinder::SYSPROPS_TRANSACTION) {
4973 return OK;
4974 }
Ady Abraham07e54702020-04-16 15:05:37 -07004975 // Numbers from 1000 to 1036 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004976 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham07e54702020-04-16 15:05:37 -07004977 if (code >= 1000 && code <= 1036) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004978 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4979 return OK;
4980 }
4981 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4982 return PERMISSION_DENIED;
4983#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004984}
4985
Ana Krulec13be8ad2018-08-21 02:43:56 +00004986status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4987 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004988 status_t credentialCheck = CheckTransactCodeCredentials(code);
4989 if (credentialCheck != OK) {
4990 return credentialCheck;
4991 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004992
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004993 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4994 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004995 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004996 IPCThreadState* ipc = IPCThreadState::self();
4997 const int uid = ipc->getCallingUid();
4998 if (CC_UNLIKELY(uid != AID_SYSTEM
4999 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005000 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005001 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005002 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005003 return PERMISSION_DENIED;
5004 }
5005 int n;
5006 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07005007 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07005008 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005009 return NO_ERROR;
5010 case 1002: // SHOW_UPDATES
5011 n = data.readInt32();
5012 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005013 invalidateHwcGeometry();
5014 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005015 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005016 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005017 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005018 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005019 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005020 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005021 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005022 setTransactionFlags(
5023 eTransactionNeeded|
5024 eDisplayTransactionNeeded|
5025 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005026 return NO_ERROR;
5027 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005028 case 1006:{ // send empty update
5029 signalRefresh();
5030 return NO_ERROR;
5031 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005032 case 1008: // toggle use of hw composer
5033 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005034 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07005035 invalidateHwcGeometry();
5036 repaintEverything();
5037 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005038 case 1009: // toggle use of transform hint
5039 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005040 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07005041 invalidateHwcGeometry();
5042 repaintEverything();
5043 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005044 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005045 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005046 reply->writeInt32(0);
5047 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005048 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005049 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005050 return NO_ERROR;
5051 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005052 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005053 if (!display) {
5054 return NAME_NOT_FOUND;
5055 }
5056
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005057 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005058 return NO_ERROR;
5059 }
5060 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005061 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005062 // daltonize
5063 n = data.readInt32();
5064 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005065 case 1:
5066 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5067 break;
5068 case 2:
5069 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5070 break;
5071 case 3:
5072 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5073 break;
5074 default:
5075 mDaltonizer.setType(ColorBlindnessType::None);
5076 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005077 }
5078 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005079 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005080 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005081 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005082 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005083
5084 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005085 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005086 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005087 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005088 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005089 // apply a color matrix
5090 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005091 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005092 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005093 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005094 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005095 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005096 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005097 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005098 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005099 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005100 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005101
5102 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5103 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005104 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005105 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5106 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5107 }
5108
Chia-I Wu28f320b2018-05-03 11:02:56 -07005109 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005110 return NO_ERROR;
5111 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07005112 case 1016: { // Unused.
5113 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005114 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005115 case 1017: {
5116 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005117 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07005118 return NO_ERROR;
5119 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005120 case 1018: { // Modify Choreographer's phase offset
5121 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005122 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005123 return NO_ERROR;
5124 }
5125 case 1019: { // Modify SurfaceFlinger's phase offset
5126 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005127 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005128 return NO_ERROR;
5129 }
Irvel468051e2016-06-13 16:44:44 -07005130 case 1020: { // Layer updates interceptor
5131 n = data.readInt32();
5132 if (n) {
5133 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005134 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005135 }
5136 else{
5137 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005138 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005139 }
5140 return NO_ERROR;
5141 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005142 case 1021: { // Disable HWC virtual displays
5143 n = data.readInt32();
5144 mUseHwcVirtualDisplays = !n;
5145 return NO_ERROR;
5146 }
Romain Guy0147a172017-06-01 13:53:56 -07005147 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005148 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005149 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005150
Chia-I Wu28f320b2018-05-03 11:02:56 -07005151 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005152 return NO_ERROR;
5153 }
Romain Guy54f154a2017-10-24 21:40:32 +01005154 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005155 int32_t colorMode;
5156
Chia-I Wu0d711262018-05-21 15:19:35 -07005157 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005158 if (data.readInt32(&colorMode) == NO_ERROR) {
5159 mForceColorMode = static_cast<ColorMode>(colorMode);
5160 }
Romain Guy54f154a2017-10-24 21:40:32 +01005161 invalidateHwcGeometry();
5162 repaintEverything();
5163 return NO_ERROR;
5164 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005165 // Deprecate, use 1030 to check whether the device is color managed.
5166 case 1024: {
5167 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005168 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005169 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005170 n = data.readInt32();
5171 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005172 ALOGD("LayerTracing enabled");
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07005173 mTracingEnabledChanged = mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01005174 reply->writeInt32(NO_ERROR);
5175 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005176 ALOGD("LayerTracing disabled");
Dominik Laskowski542c9dc2020-04-10 12:42:02 -07005177 mTracingEnabledChanged = mTracing.disable();
5178 if (mTracingEnabledChanged) {
Nataniel Borges2b796da2019-02-15 13:32:18 -08005179 reply->writeInt32(mTracing.writeToFile());
5180 } else {
5181 reply->writeInt32(NO_ERROR);
5182 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01005183 }
5184 return NO_ERROR;
5185 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005186 case 1026: { // Get layer tracing status
5187 reply->writeBool(mTracing.isEnabled());
5188 return NO_ERROR;
5189 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005190 // Is a DisplayColorSetting supported?
5191 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005192 const auto display = getDefaultDisplayDevice();
5193 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005194 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005195 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005196
5197 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5198 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005199 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07005200 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005201 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005202 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07005203 reply->writeBool(true);
5204 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005205 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005206 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005207 break;
5208 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005209 reply->writeBool(
5210 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005211 break;
5212 }
5213 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005214 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005215 // Is VrFlinger active?
5216 case 1028: {
5217 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005218 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005219 return NO_ERROR;
5220 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005221 // Set buffer size for SF tracing (value in KB)
5222 case 1029: {
5223 n = data.readInt32();
5224 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5225 ALOGW("Invalid buffer size: %d KB", n);
5226 reply->writeInt32(BAD_VALUE);
5227 return BAD_VALUE;
5228 }
5229
5230 ALOGD("Updating trace buffer to %d KB", n);
5231 mTracing.setBufferSize(n * 1024);
5232 reply->writeInt32(NO_ERROR);
5233 return NO_ERROR;
5234 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005235 // Is device color managed?
5236 case 1030: {
5237 reply->writeBool(useColorManagement);
5238 return NO_ERROR;
5239 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005240 // Override default composition data space
5241 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5242 // && adb shell stop zygote && adb shell start zygote
5243 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5244 // adb shell stop zygote && adb shell start zygote
5245 case 1031: {
5246 Mutex::Autolock _l(mStateLock);
5247 n = data.readInt32();
5248 if (n) {
5249 n = data.readInt32();
5250 if (n) {
5251 Dataspace dataspace = static_cast<Dataspace>(n);
5252 if (!validateCompositionDataspace(dataspace)) {
5253 return BAD_VALUE;
5254 }
5255 mDefaultCompositionDataspace = dataspace;
5256 }
5257 n = data.readInt32();
5258 if (n) {
5259 Dataspace dataspace = static_cast<Dataspace>(n);
5260 if (!validateCompositionDataspace(dataspace)) {
5261 return BAD_VALUE;
5262 }
5263 mWideColorGamutCompositionDataspace = dataspace;
5264 }
5265 } else {
5266 // restore composition data space.
5267 mDefaultCompositionDataspace = defaultCompositionDataspace;
5268 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5269 }
5270 return NO_ERROR;
5271 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005272 // Set trace flags
5273 case 1033: {
5274 n = data.readUint32();
5275 ALOGD("Updating trace flags to 0x%x", n);
5276 mTracing.setTraceFlags(n);
5277 reply->writeInt32(NO_ERROR);
5278 return NO_ERROR;
5279 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005280 case 1034: {
Dominik Laskowski20134642020-04-20 22:36:44 -07005281 switch (n = data.readInt32()) {
5282 case 0:
5283 case 1:
5284 enableRefreshRateOverlay(static_cast<bool>(n));
5285 break;
5286 default: {
5287 Mutex::Autolock lock(mStateLock);
5288 reply->writeBool(mRefreshRateOverlay != nullptr);
5289 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005290 }
5291 return NO_ERROR;
5292 }
Ady Abraham34392f72019-04-10 11:29:27 -07005293 case 1035: {
5294 n = data.readInt32();
5295 mDebugDisplayConfigSetByBackdoor = false;
5296 if (n >= 0) {
5297 const auto displayToken = getInternalDisplayToken();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005298 status_t result = setActiveConfig(displayToken, n);
Ady Abraham34392f72019-04-10 11:29:27 -07005299 if (result != NO_ERROR) {
5300 return result;
5301 }
5302 mDebugDisplayConfigSetByBackdoor = true;
5303 }
5304 return NO_ERROR;
5305 }
Ady Abraham07e54702020-04-16 15:05:37 -07005306 case 1036: {
5307 if (data.readInt32() > 0) {
5308 status_t result =
5309 acquireFrameRateFlexibilityToken(&mDebugFrameRateFlexibilityToken);
5310 if (result != NO_ERROR) {
5311 return result;
5312 }
5313 } else {
5314 mDebugFrameRateFlexibilityToken = nullptr;
5315 }
5316 return NO_ERROR;
5317 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005318 }
5319 }
5320 return err;
5321}
5322
Steven Thomas6d8110b2017-08-31 18:24:21 -07005323void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005324 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005325 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005326}
5327
Ana Krulec7d1d6832018-12-27 11:10:09 -08005328void SurfaceFlinger::repaintEverythingForHWC() {
5329 mRepaintEverything = true;
Dan Stoza030fbc12020-02-19 15:32:01 -08005330 mPowerAdvisor.notifyDisplayUpdateImminent();
Ady Abraham8532d012019-05-08 14:50:56 -07005331 mEventQueue->invalidate();
Ana Krulec7d1d6832018-12-27 11:10:09 -08005332}
5333
Ady Abrahama09852a2020-02-20 14:23:42 -08005334void SurfaceFlinger::kernelTimerChanged(bool expired) {
5335 static bool updateOverlay =
5336 property_get_bool("debug.sf.kernel_idle_timer_update_overlay", true);
Dominik Laskowski20134642020-04-20 22:36:44 -07005337 if (!updateOverlay) return;
5338 if (Mutex::Autolock lock(mStateLock); !mRefreshRateOverlay) return;
Ady Abrahama09852a2020-02-20 14:23:42 -08005339
5340 // Update the overlay on the main thread to avoid race conditions with
5341 // mRefreshRateConfigs->getCurrentRefreshRate()
Dominik Laskowski20134642020-04-20 22:36:44 -07005342 static_cast<void>(schedule([=] {
5343 const auto desiredActiveConfig = getDesiredActiveConfig();
5344 const auto& current = desiredActiveConfig
5345 ? mRefreshRateConfigs->getRefreshRateFromConfigId(desiredActiveConfig->configId)
5346 : mRefreshRateConfigs->getCurrentRefreshRate();
5347 const auto& min = mRefreshRateConfigs->getMinRefreshRate();
5348
5349 if (current != min) {
Ana Krulecb9afd792020-06-11 13:16:15 -07005350 const bool timerExpired = mKernelIdleTimerEnabled && expired;
Ady Abrahama09852a2020-02-20 14:23:42 -08005351
Dominik Laskowski20134642020-04-20 22:36:44 -07005352 if (Mutex::Autolock lock(mStateLock); mRefreshRateOverlay) {
Ady Abrahama09852a2020-02-20 14:23:42 -08005353 mRefreshRateOverlay->changeRefreshRate(timerExpired ? min : current);
Ady Abrahama09852a2020-02-20 14:23:42 -08005354 }
Dominik Laskowski20134642020-04-20 22:36:44 -07005355 mEventQueue->invalidate();
Ady Abrahama09852a2020-02-20 14:23:42 -08005356 }
5357 }));
5358}
5359
Ana Krulecb9afd792020-06-11 13:16:15 -07005360void SurfaceFlinger::toggleKernelIdleTimer() {
5361 using KernelIdleTimerAction = scheduler::RefreshRateConfigs::KernelIdleTimerAction;
5362
5363 // If the support for kernel idle timer is disabled in SF code, don't do anything.
5364 if (!mSupportKernelIdleTimer) {
5365 return;
5366 }
5367 const KernelIdleTimerAction action = mRefreshRateConfigs->getIdleTimerAction();
5368
5369 switch (action) {
5370 case KernelIdleTimerAction::TurnOff:
5371 if (mKernelIdleTimerEnabled) {
5372 ATRACE_INT("KernelIdleTimer", 0);
5373 base::SetProperty(KERNEL_IDLE_TIMER_PROP, "false");
5374 mKernelIdleTimerEnabled = false;
5375 }
5376 break;
5377 case KernelIdleTimerAction::TurnOn:
5378 if (!mKernelIdleTimerEnabled) {
5379 ATRACE_INT("KernelIdleTimer", 1);
5380 base::SetProperty(KERNEL_IDLE_TIMER_PROP, "true");
5381 mKernelIdleTimerEnabled = true;
5382 }
5383 break;
5384 case KernelIdleTimerAction::NoChange:
5385 break;
5386 }
5387}
5388
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005389// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5390class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005391public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005392 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5393 ~WindowDisconnector() {
5394 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005395 }
5396
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005397private:
5398 ANativeWindow* mWindow;
5399 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005400};
5401
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005402status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07005403 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
Dominik Laskowski718f9602019-11-09 20:01:35 -08005404 Dataspace reqDataspace, ui::PixelFormat reqPixelFormat,
5405 const Rect& sourceCrop, uint32_t reqWidth,
5406 uint32_t reqHeight, bool useIdentityTransform,
5407 ui::Rotation rotation, bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005408 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005409
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005410 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005411
Dominik Laskowski718f9602019-11-09 20:01:35 -08005412 auto renderAreaRotation = ui::Transform::toRotationFlags(rotation);
5413 if (renderAreaRotation == ui::Transform::ROT_INVALID) {
5414 ALOGE("%s: Invalid rotation: %s", __FUNCTION__, toCString(rotation));
5415 renderAreaRotation = ui::Transform::ROT_0;
5416 }
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005417
Marin Shalamanov1c434292020-06-12 01:47:29 +02005418 wp<DisplayDevice> displayWeak;
5419 ui::LayerStack layerStack;
5420 ui::Size reqSize(reqWidth, reqHeight);
Chia-I Wu20261cb2018-08-23 12:55:44 -07005421 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005422 Mutex::Autolock lock(mStateLock);
Marin Shalamanov1c434292020-06-12 01:47:29 +02005423 sp<DisplayDevice> display = getDisplayDeviceLocked(displayToken);
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005424 if (!display) return NAME_NOT_FOUND;
Marin Shalamanov1c434292020-06-12 01:47:29 +02005425 displayWeak = display;
5426 layerStack = display->getLayerStack();
Chia-I Wu20261cb2018-08-23 12:55:44 -07005427
Chia-I Wucb023152018-08-28 12:57:23 -07005428 // set the requested width/height to the logical display viewport size
5429 // by default
5430 if (reqWidth == 0 || reqHeight == 0) {
Marin Shalamanov1c434292020-06-12 01:47:29 +02005431 reqSize = display->getViewport().getSize();
Chia-I Wu20261cb2018-08-23 12:55:44 -07005432 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005433 }
5434
Marin Shalamanov1c434292020-06-12 01:47:29 +02005435 RenderAreaFuture renderAreaFuture = promise::defer([=] {
5436 return DisplayRenderArea::create(displayWeak, sourceCrop, reqSize, reqDataspace,
5437 renderAreaRotation, captureSecureLayers);
5438 });
5439
5440 auto traverseLayers = [this, layerStack](const LayerVector::Visitor& visitor) {
5441 traverseLayersInLayerStack(layerStack, visitor);
5442 };
5443 return captureScreenCommon(std::move(renderAreaFuture), traverseLayers, reqSize, outBuffer,
5444 reqPixelFormat, useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005445}
5446
chaviw93df2ea2019-04-30 16:45:12 -07005447static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
5448 switch (colorMode) {
5449 case ColorMode::DISPLAY_P3:
5450 case ColorMode::BT2100_PQ:
5451 case ColorMode::BT2100_HLG:
5452 case ColorMode::DISPLAY_BT2020:
5453 return Dataspace::DISPLAY_P3;
5454 default:
5455 return Dataspace::V0_SRGB;
5456 }
5457}
5458
Martin Liu4a322352020-03-24 21:30:38 +08005459status_t SurfaceFlinger::setSchedFifo(bool enabled) {
5460 static constexpr int kFifoPriority = 2;
5461 static constexpr int kOtherPriority = 0;
5462
5463 struct sched_param param = {0};
5464 int sched_policy;
5465 if (enabled) {
5466 sched_policy = SCHED_FIFO;
5467 param.sched_priority = kFifoPriority;
5468 } else {
5469 sched_policy = SCHED_OTHER;
5470 param.sched_priority = kOtherPriority;
5471 }
5472
5473 if (sched_setscheduler(0, sched_policy, &param) != 0) {
5474 return -errno;
5475 }
5476 return NO_ERROR;
5477}
5478
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07005479sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005480 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
5481 if (displayToken) {
5482 return getDisplayDeviceLocked(displayToken);
5483 }
5484 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
5485 // may not have a displayId.
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005486 return getDisplayByLayerStack(displayOrLayerStack);
5487}
5488
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07005489sp<DisplayDevice> SurfaceFlinger::getDisplayByLayerStack(uint64_t layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005490 for (const auto& [token, display] : mDisplays) {
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005491 if (display->getLayerStack() == layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005492 return display;
5493 }
5494 }
5495 return nullptr;
5496}
5497
5498status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
5499 sp<GraphicBuffer>* outBuffer) {
Marin Shalamanov1c434292020-06-12 01:47:29 +02005500 ui::LayerStack layerStack;
5501 wp<DisplayDevice> displayWeak;
5502 ui::Size size;
Dominik Laskowski718f9602019-11-09 20:01:35 -08005503 ui::Transform::RotationFlags captureOrientation;
chaviw93df2ea2019-04-30 16:45:12 -07005504 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005505 Mutex::Autolock lock(mStateLock);
Marin Shalamanov1c434292020-06-12 01:47:29 +02005506 sp<DisplayDevice> display = getDisplayByIdOrLayerStack(displayOrLayerStack);
chaviw93df2ea2019-04-30 16:45:12 -07005507 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005508 return NAME_NOT_FOUND;
chaviw93df2ea2019-04-30 16:45:12 -07005509 }
Marin Shalamanov1c434292020-06-12 01:47:29 +02005510 layerStack = display->getLayerStack();
5511 displayWeak = display;
chaviw93df2ea2019-04-30 16:45:12 -07005512
Marin Shalamanov1c434292020-06-12 01:47:29 +02005513 size = display->getViewport().getSize();
chaviw93df2ea2019-04-30 16:45:12 -07005514
Dominik Laskowski718f9602019-11-09 20:01:35 -08005515 const auto orientation = display->getOrientation();
5516 captureOrientation = ui::Transform::toRotationFlags(orientation);
5517
5518 switch (captureOrientation) {
5519 case ui::Transform::ROT_90:
5520 captureOrientation = ui::Transform::ROT_270;
5521 break;
5522
5523 case ui::Transform::ROT_270:
5524 captureOrientation = ui::Transform::ROT_90;
5525 break;
5526
5527 case ui::Transform::ROT_INVALID:
5528 ALOGE("%s: Invalid orientation: %s", __FUNCTION__, toCString(orientation));
5529 captureOrientation = ui::Transform::ROT_0;
5530 break;
5531
5532 default:
5533 break;
Alec Mouri21fab752019-06-20 14:12:17 -07005534 }
chaviw93df2ea2019-04-30 16:45:12 -07005535 *outDataspace =
5536 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
5537 }
5538
Marin Shalamanov1c434292020-06-12 01:47:29 +02005539 RenderAreaFuture renderAreaFuture = promise::defer([=] {
5540 return DisplayRenderArea::create(displayWeak, Rect(), size, *outDataspace,
5541 captureOrientation, false /* captureSecureLayers */);
5542 });
chaviw93df2ea2019-04-30 16:45:12 -07005543
Marin Shalamanov1c434292020-06-12 01:47:29 +02005544 auto traverseLayers = [this, layerStack](const LayerVector::Visitor& visitor) {
5545 traverseLayersInLayerStack(layerStack, visitor);
5546 };
5547
chaviw93df2ea2019-04-30 16:45:12 -07005548 bool ignored = false;
Marin Shalamanov1c434292020-06-12 01:47:29 +02005549
5550 return captureScreenCommon(std::move(renderAreaFuture), traverseLayers, size, outBuffer,
5551 ui::PixelFormat::RGBA_8888, false /* useIdentityTransform */,
chaviw93df2ea2019-04-30 16:45:12 -07005552 ignored /* outCapturedSecureLayers */);
5553}
5554
Robert Carr866455f2019-04-02 16:28:26 -07005555status_t SurfaceFlinger::captureLayers(
5556 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
5557 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
5558 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
5559 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005560 ATRACE_CALL();
5561
5562 class LayerRenderArea : public RenderArea {
5563 public:
Robert Carr578038f2018-03-09 12:25:24 -08005564 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Marin Shalamanov1c434292020-06-12 01:47:29 +02005565 ui::Size reqSize, Dataspace reqDataSpace, bool childrenOnly,
5566 const Rect& displayViewport)
5567 : RenderArea(reqSize, CaptureFill::CLEAR, reqDataSpace, displayViewport),
Robert Carr578038f2018-03-09 12:25:24 -08005568 mLayer(layer),
5569 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005570 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005571 mFlinger(flinger),
5572 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005573 const ui::Transform& getTransform() const override { return mTransform; }
Alec Mouri5a6d8572020-03-23 23:56:15 -07005574 Rect getBounds() const override { return mLayer->getBufferSize(mLayer->getDrawingState()); }
Marissa Wall61c58622018-07-18 10:12:20 -07005575 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005576 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005577 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005578 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005579 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005580 }
chaviwa76b2712017-09-20 12:02:26 -07005581 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005582 bool needsFiltering() const override { return mNeedsFiltering; }
Dominik Laskowski718f9602019-11-09 20:01:35 -08005583 sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005584 Rect getSourceCrop() const override {
5585 if (mCrop.isEmpty()) {
5586 return getBounds();
5587 } else {
5588 return mCrop;
5589 }
5590 }
Robert Carr578038f2018-03-09 12:25:24 -08005591 class ReparentForDrawing {
5592 public:
5593 const sp<Layer>& oldParent;
5594 const sp<Layer>& newParent;
5595
Vishnu Nair4351ad52019-02-11 14:13:02 -08005596 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5597 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005598 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005599 // Compute and cache the bounds for the new parent layer.
Vishnu Nairc97b8db2019-10-29 18:19:35 -07005600 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform(),
5601 0.f /* shadowRadius */);
Robert Carr15eae092018-03-23 13:43:53 -07005602 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005603 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005604 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005605 };
5606
5607 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005608 const Rect sourceCrop = getSourceCrop();
5609 // no need to check rotation because there is none
5610 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5611 sourceCrop.height() != getReqHeight();
5612
Robert Carr578038f2018-03-09 12:25:24 -08005613 if (!mChildrenOnly) {
5614 mTransform = mLayer->getTransform().inverse();
5615 drawLayers();
5616 } else {
Alec Mouri5a6d8572020-03-23 23:56:15 -07005617 uint32_t w = static_cast<uint32_t>(getWidth());
5618 uint32_t h = static_cast<uint32_t>(getHeight());
chaviw32811fd2019-08-12 13:16:09 -07005619 // In the "childrenOnly" case we reparent the children to a screenshot
5620 // layer which has no properties set and which does not draw.
5621 sp<ContainerLayer> screenshotParentLayer =
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005622 mFlinger->getFactory().createContainerLayer({mFlinger, nullptr,
5623 "Screenshot Parent"s, w, h, 0,
5624 LayerMetadata()});
Robert Carr578038f2018-03-09 12:25:24 -08005625
Vishnu Nair4351ad52019-02-11 14:13:02 -08005626 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005627 drawLayers();
5628 }
5629 }
chaviwa76b2712017-09-20 12:02:26 -07005630
chaviwa76b2712017-09-20 12:02:26 -07005631 private:
chaviw7206d492017-11-10 16:16:12 -08005632 const sp<Layer> mLayer;
5633 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005634
Peiyong Linefefaac2018-08-17 12:27:51 -07005635 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005636 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005637
5638 SurfaceFlinger* mFlinger;
5639 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005640 };
5641
Marin Shalamanov1c434292020-06-12 01:47:29 +02005642 ui::Size reqSize;
Robert Carrc0df3122019-04-11 13:18:21 -07005643 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005644 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005645 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005646 Rect displayViewport;
Robert Carrc0df3122019-04-11 13:18:21 -07005647 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005648 Mutex::Autolock lock(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005649
Alec Mouri9a02eda2020-04-21 17:39:34 -07005650 parent = fromHandleLocked(layerHandleBinder).promote();
Robert Carrc0df3122019-04-11 13:18:21 -07005651 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5652 ALOGE("captureLayers called with an invalid or removed parent");
5653 return NAME_NOT_FOUND;
5654 }
5655
5656 const int uid = IPCThreadState::self()->getCallingUid();
5657 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5658 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5659 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5660 return PERMISSION_DENIED;
5661 }
5662
Vishnu Nairefc42e22019-12-03 17:36:12 -08005663 Rect parentSourceBounds = parent->getCroppedBufferSize(parent->getCurrentState());
Robert Carrc0df3122019-04-11 13:18:21 -07005664 if (sourceCrop.width() <= 0) {
5665 crop.left = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005666 crop.right = parentSourceBounds.getWidth();
Robert Carrc0df3122019-04-11 13:18:21 -07005667 }
5668
5669 if (sourceCrop.height() <= 0) {
5670 crop.top = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005671 crop.bottom = parentSourceBounds.getHeight();
5672 }
5673
5674 if (crop.isEmpty() || frameScale <= 0.0f) {
5675 // Error out if the layer has no source bounds (i.e. they are boundless) and a source
5676 // crop was not specified, or an invalid frame scale was provided.
5677 return BAD_VALUE;
Robert Carrc0df3122019-04-11 13:18:21 -07005678 }
Marin Shalamanov1c434292020-06-12 01:47:29 +02005679 reqSize = ui::Size(crop.width() * frameScale, crop.height() * frameScale);
Robert Carrc0df3122019-04-11 13:18:21 -07005680
5681 for (const auto& handle : excludeHandles) {
Alec Mouri9a02eda2020-04-21 17:39:34 -07005682 sp<Layer> excludeLayer = fromHandleLocked(handle).promote();
Robert Carrc0df3122019-04-11 13:18:21 -07005683 if (excludeLayer != nullptr) {
5684 excludeLayers.emplace(excludeLayer);
5685 } else {
5686 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5687 return NAME_NOT_FOUND;
5688 }
5689 }
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005690
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005691 const auto display = getDisplayByLayerStack(parent->getLayerStack());
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005692 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005693 return NAME_NOT_FOUND;
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005694 }
5695
5696 displayViewport = display->getViewport();
Robert Carrc0df3122019-04-11 13:18:21 -07005697 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005698
Chia-I Wu20261cb2018-08-23 12:55:44 -07005699 // really small crop or frameScale
Marin Shalamanov1c434292020-06-12 01:47:29 +02005700 if (reqSize.width <= 0) {
5701 reqSize.width = 1;
Chia-I Wu20261cb2018-08-23 12:55:44 -07005702 }
Marin Shalamanov1c434292020-06-12 01:47:29 +02005703 if (reqSize.height <= 0) {
5704 reqSize.height = 1;
Chia-I Wu20261cb2018-08-23 12:55:44 -07005705 }
5706
Marin Shalamanov1c434292020-06-12 01:47:29 +02005707 RenderAreaFuture renderAreaFuture = promise::defer([=]() -> std::unique_ptr<RenderArea> {
5708 return std::make_unique<LayerRenderArea>(this, parent, crop, reqSize, reqDataspace,
5709 childrenOnly, displayViewport);
5710 });
5711
Robert Carr866455f2019-04-02 16:28:26 -07005712 auto traverseLayers = [parent, childrenOnly,
5713 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005714 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5715 if (!layer->isVisible()) {
5716 return;
Robert Carr578038f2018-03-09 12:25:24 -08005717 } else if (childrenOnly && layer == parent.get()) {
5718 return;
chaviwa76b2712017-09-20 12:02:26 -07005719 }
Robert Carr866455f2019-04-02 16:28:26 -07005720
5721 sp<Layer> p = layer;
5722 while (p != nullptr) {
5723 if (excludeLayers.count(p) != 0) {
5724 return;
5725 }
5726 p = p->getParent();
5727 }
5728
chaviwa76b2712017-09-20 12:02:26 -07005729 visitor(layer);
5730 });
5731 };
Robert Carr108b2c72019-04-02 16:32:58 -07005732
5733 bool outCapturedSecureLayers = false;
Marin Shalamanov1c434292020-06-12 01:47:29 +02005734 return captureScreenCommon(std::move(renderAreaFuture), traverseLayers, reqSize, outBuffer,
5735 reqPixelFormat, false, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005736}
5737
Marin Shalamanov1c434292020-06-12 01:47:29 +02005738status_t SurfaceFlinger::captureScreenCommon(RenderAreaFuture renderAreaFuture,
chaviwa76b2712017-09-20 12:02:26 -07005739 TraverseLayersFunction traverseLayers,
Marin Shalamanov1c434292020-06-12 01:47:29 +02005740 ui::Size bufferSize, sp<GraphicBuffer>* outBuffer,
5741 ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005742 bool useIdentityTransform,
5743 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005744 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005745
Peiyong Lin0e003c92018-09-17 11:09:51 -07005746 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005747 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5748 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Marin Shalamanov1c434292020-06-12 01:47:29 +02005749 *outBuffer = getFactory().createGraphicBuffer(bufferSize.getWidth(), bufferSize.getHeight(),
5750 static_cast<android_pixel_format>(reqPixelFormat),
5751 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005752
Marin Shalamanov1c434292020-06-12 01:47:29 +02005753 return captureScreenCommon(std::move(renderAreaFuture), traverseLayers, *outBuffer,
5754 useIdentityTransform, false /* regionSampling */,
5755 outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005756}
5757
Marin Shalamanov1c434292020-06-12 01:47:29 +02005758status_t SurfaceFlinger::captureScreenCommon(RenderAreaFuture renderAreaFuture,
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005759 TraverseLayersFunction traverseLayers,
5760 const sp<GraphicBuffer>& buffer,
Lucas Dupin9d763b72020-04-20 18:42:31 -07005761 bool useIdentityTransform, bool regionSampling,
Robert Carr108b2c72019-04-02 16:32:58 -07005762 bool& outCapturedSecureLayers) {
Robert Carr03480e22018-01-04 16:02:06 -08005763 const int uid = IPCThreadState::self()->getCallingUid();
5764 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5765
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005766 status_t result;
5767 int syncFd;
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005768
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005769 do {
5770 std::tie(result, syncFd) =
Marin Shalamanov1c434292020-06-12 01:47:29 +02005771 schedule([&]() -> std::pair<status_t, int> {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005772 if (mRefreshPending) {
Marin Shalamanov1c434292020-06-12 01:47:29 +02005773 ALOGW("Skipping screenshot for now");
5774 return {EAGAIN, -1};
5775 }
5776 std::unique_ptr<RenderArea> renderArea = renderAreaFuture.get();
5777 if (!renderArea) {
5778 ALOGW("Skipping screen capture because of invalid render area.");
5779 return {NO_MEMORY, -1};
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005780 }
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005781
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005782 status_t result = NO_ERROR;
5783 int fd = -1;
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005784
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005785 Mutex::Autolock lock(mStateLock);
Marin Shalamanov1c434292020-06-12 01:47:29 +02005786 renderArea->render([&] {
5787 result = captureScreenImplLocked(*renderArea, traverseLayers, buffer.get(),
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005788 useIdentityTransform, forSystem, &fd,
5789 regionSampling, outCapturedSecureLayers);
5790 });
5791
Marin Shalamanov1c434292020-06-12 01:47:29 +02005792 return {result, fd};
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07005793 }).get();
5794 } while (result == EAGAIN);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005795
5796 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005797 sync_wait(syncFd, -1);
5798 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005799 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005800
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005801 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005802}
5803
chaviwa76b2712017-09-20 12:02:26 -07005804void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005805 TraverseLayersFunction traverseLayers,
Ana Krulecfc874ae2020-02-22 15:39:32 -08005806 const sp<GraphicBuffer>& buffer,
Lucas Dupin9d763b72020-04-20 18:42:31 -07005807 bool useIdentityTransform, bool regionSampling,
5808 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005809 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005810
chaviwa76b2712017-09-20 12:02:26 -07005811 const auto reqWidth = renderArea.getReqWidth();
5812 const auto reqHeight = renderArea.getReqHeight();
Alec Mouriadb75f42019-03-28 21:42:24 -07005813 const auto sourceCrop = renderArea.getSourceCrop();
Alec Mouri5a6d8572020-03-23 23:56:15 -07005814 const auto transform = renderArea.getTransform();
5815 const auto rotation = renderArea.getRotationFlags();
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005816 const auto& displayViewport = renderArea.getDisplayViewport();
Dan Stozac1879002014-05-22 15:59:05 -07005817
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005818 renderengine::DisplaySettings clientCompositionDisplay;
Vishnu Nair9b079a22020-01-21 14:36:08 -08005819 std::vector<compositionengine::LayerFE::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005820
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005821 // assume that bounds are never offset, and that they are the same as the
5822 // buffer bounds.
5823 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07005824 clientCompositionDisplay.clip = sourceCrop;
Alec Mouri5a6d8572020-03-23 23:56:15 -07005825 clientCompositionDisplay.orientation = rotation;
Alec Mouriadb75f42019-03-28 21:42:24 -07005826
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005827 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5828 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005829
chaviw50da5042018-04-09 13:49:37 -07005830 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005831
Vishnu Nair9b079a22020-01-21 14:36:08 -08005832 compositionengine::LayerFE::LayerSettings fillLayer;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005833 fillLayer.source.buffer.buffer = nullptr;
5834 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
Alec Mouri5a6d8572020-03-23 23:56:15 -07005835 fillLayer.geometry.boundaries =
5836 FloatRect(sourceCrop.left, sourceCrop.top, sourceCrop.right, sourceCrop.bottom);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005837 fillLayer.alpha = half(alpha);
5838 clientCompositionLayers.push_back(fillLayer);
5839
Dominik Laskowskib7251f42020-04-20 17:42:59 -07005840 const auto display = renderArea.getDisplayDevice();
Yichi Chen40773d92020-04-01 10:10:18 +08005841 std::vector<Layer*> renderedLayers;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005842 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005843 traverseLayers([&](Layer* layer) {
Lloyd Piquef16688f2019-02-19 17:47:57 -08005844 const bool supportProtectedContent = false;
5845 Region clip(renderArea.getBounds());
5846 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
5847 clip,
5848 useIdentityTransform,
Dominik Laskowskib7251f42020-04-20 17:42:59 -07005849 layer->needsFilteringForScreenshots(display.get(), transform) ||
Alec Mouri5a6d8572020-03-23 23:56:15 -07005850 renderArea.needsFiltering(),
Lloyd Piquef16688f2019-02-19 17:47:57 -08005851 renderArea.isSecure(),
5852 supportProtectedContent,
5853 clearRegion,
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005854 displayViewport,
5855 clientCompositionDisplay.outputDataspace,
5856 true, /* realContentIsVisible */
5857 false, /* clearContent */
Lloyd Piquef16688f2019-02-19 17:47:57 -08005858 };
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005859 std::vector<compositionengine::LayerFE::LayerSettings> results =
5860 layer->prepareClientCompositionList(targetSettings);
Yichi Chen40773d92020-04-01 10:10:18 +08005861 if (results.size() > 0) {
Alec Mouri5a6d8572020-03-23 23:56:15 -07005862 for (auto& settings : results) {
5863 settings.geometry.positionTransform =
5864 transform.asMatrix4() * settings.geometry.positionTransform;
Lucas Dupin9d763b72020-04-20 18:42:31 -07005865 // There's no need to process blurs when we're executing region sampling,
5866 // we're just trying to understand what we're drawing, and doing so without
5867 // blurs is already a pretty good approximation.
5868 if (regionSampling) {
5869 settings.backgroundBlurRadius = 0;
5870 }
Alec Mouri5a6d8572020-03-23 23:56:15 -07005871 }
Yichi Chen40773d92020-04-01 10:10:18 +08005872 clientCompositionLayers.insert(clientCompositionLayers.end(),
5873 std::make_move_iterator(results.begin()),
5874 std::make_move_iterator(results.end()));
5875 renderedLayers.push_back(layer);
5876 }
chaviwa76b2712017-09-20 12:02:26 -07005877 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005878
Yichi Chen40773d92020-04-01 10:10:18 +08005879 std::vector<const renderengine::LayerSettings*> clientCompositionLayerPointers(
5880 clientCompositionLayers.size());
Vishnu Nair9b079a22020-01-21 14:36:08 -08005881 std::transform(clientCompositionLayers.begin(), clientCompositionLayers.end(),
Yichi Chen40773d92020-04-01 10:10:18 +08005882 clientCompositionLayerPointers.begin(),
5883 std::pointer_traits<renderengine::LayerSettings*>::pointer_to);
Vishnu Nair9b079a22020-01-21 14:36:08 -08005884
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005885 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005886 // Use an empty fence for the buffer fence, since we just created the buffer so
5887 // there is no need for synchronization with the GPU.
5888 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005889 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005890 getRenderEngine().useProtectedContext(false);
Vishnu Nair9b079a22020-01-21 14:36:08 -08005891 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayerPointers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07005892 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005893
5894 *outSyncFd = drawFence.release();
Yichi Chen40773d92020-04-01 10:10:18 +08005895
5896 if (*outSyncFd >= 0) {
5897 sp<Fence> releaseFence = new Fence(dup(*outSyncFd));
5898 for (auto* layer : renderedLayers) {
5899 layer->onLayerDisplayed(releaseFence);
5900 }
5901 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07005902}
5903
chaviwa76b2712017-09-20 12:02:26 -07005904status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5905 TraverseLayersFunction traverseLayers,
Ana Krulecfc874ae2020-02-22 15:39:32 -08005906 const sp<GraphicBuffer>& buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005907 bool useIdentityTransform, bool forSystem,
Lucas Dupin9d763b72020-04-20 18:42:31 -07005908 int* outSyncFd, bool regionSampling,
5909 bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005910 ATRACE_CALL();
5911
chaviwa76b2712017-09-20 12:02:26 -07005912 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07005913 outCapturedSecureLayers =
5914 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07005915 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005916
Robert Carr03480e22018-01-04 16:02:06 -08005917 // We allow the system server to take screenshots of secure layers for
5918 // use in situations like the Screen-rotation animation and place
5919 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07005920 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005921 ALOGW("FB is protected: PERMISSION_DENIED");
5922 return PERMISSION_DENIED;
5923 }
Lucas Dupin9d763b72020-04-20 18:42:31 -07005924 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, regionSampling,
5925 outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005926 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005927}
5928
chaviw95ef3c42019-02-14 10:55:09 -08005929void SurfaceFlinger::setInputWindowsFinished() {
5930 Mutex::Autolock _l(mStateLock);
5931
5932 mPendingSyncInputWindows = false;
Rob Carr9a2cc992020-03-06 12:44:45 -08005933
chaviw95ef3c42019-02-14 10:55:09 -08005934 mTransactionCV.broadcast();
5935}
chaviw5f21a5e2019-02-14 10:00:34 -08005936
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005937// ---------------------------------------------------------------------------
5938
Edgar Arriaga844fa672020-01-16 14:21:42 -08005939void SurfaceFlinger::State::traverse(const LayerVector::Visitor& visitor) const {
5940 layersSortedByZ.traverse(visitor);
5941}
5942
Dan Stoza412903f2017-04-27 13:42:17 -07005943void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5944 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005945}
5946
Dan Stoza412903f2017-04-27 13:42:17 -07005947void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5948 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005949}
5950
Marin Shalamanov1c434292020-06-12 01:47:29 +02005951void SurfaceFlinger::traverseLayersInLayerStack(ui::LayerStack layerStack,
5952 const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005953 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005954 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005955 for (const auto& layer : mDrawingState.layersSortedByZ) {
Marin Shalamanov1c434292020-06-12 01:47:29 +02005956 if (!layer->belongsToDisplay(layerStack, false)) {
chaviwa76b2712017-09-20 12:02:26 -07005957 continue;
5958 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005959 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005960 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Marin Shalamanov1c434292020-06-12 01:47:29 +02005961 if (!layer->belongsToDisplay(layerStack, false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005962 return;
5963 }
chaviwa76b2712017-09-20 12:02:26 -07005964 if (!layer->isVisible()) {
5965 return;
5966 }
5967 visitor(layer);
5968 });
5969 }
5970}
5971
Steven Thomasd4071902020-03-24 16:02:53 -07005972status_t SurfaceFlinger::setDesiredDisplayConfigSpecsInternal(
5973 const sp<DisplayDevice>& display,
5974 const std::optional<scheduler::RefreshRateConfigs::Policy>& policy, bool overridePolicy) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005975 Mutex::Autolock lock(mStateLock);
5976
Steven Thomasd4071902020-03-24 16:02:53 -07005977 LOG_ALWAYS_FATAL_IF(!display->isPrimary() && overridePolicy,
5978 "Can only set override policy on the primary display");
5979 LOG_ALWAYS_FATAL_IF(!policy && !overridePolicy, "Can only clear the override policy");
5980
Dominik Laskowski22488f62019-03-28 09:53:04 -07005981 if (!display->isPrimary()) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005982 // TODO(b/144711714): For non-primary displays we should be able to set an active config
5983 // as well. For now, just call directly to setActiveConfigWithConstraints but ideally
5984 // it should go thru setDesiredActiveConfig, similar to primary display.
5985 ALOGV("setAllowedDisplayConfigsInternal for non-primary display");
5986 const auto displayId = display->getId();
5987 LOG_ALWAYS_FATAL_IF(!displayId);
5988
Peiyong Line9d809e2020-04-14 13:10:48 -07005989 hal::VsyncPeriodChangeConstraints constraints;
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005990 constraints.desiredTimeNanos = systemTime();
5991 constraints.seamlessRequired = false;
5992
Peiyong Line9d809e2020-04-14 13:10:48 -07005993 hal::VsyncPeriodChangeTimeline timeline = {0, 0, 0};
Steven Thomasd4071902020-03-24 16:02:53 -07005994 if (getHwComposer().setActiveConfigWithConstraints(*displayId,
5995 policy->defaultConfig.value(),
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005996 constraints, &timeline) < 0) {
5997 return BAD_VALUE;
5998 }
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005999 if (timeline.refreshRequired) {
6000 repaintEverythingForHWC();
6001 }
6002
Steven Thomasd4071902020-03-24 16:02:53 -07006003 display->setActiveConfig(policy->defaultConfig);
6004 const nsecs_t vsyncPeriod = getHwComposer()
6005 .getConfigs(*displayId)[policy->defaultConfig.value()]
6006 ->getVsyncPeriod();
Ady Abrahamdfd62162020-06-10 16:11:56 -07006007 mScheduler->onNonPrimaryDisplayConfigChanged(mAppConnectionHandle, display->getId()->value,
6008 policy->defaultConfig, vsyncPeriod);
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006009 return NO_ERROR;
Ady Abraham838de062019-02-04 10:24:03 -08006010 }
6011
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006012 if (mDebugDisplayConfigSetByBackdoor) {
6013 // ignore this request as config is overridden by backdoor
6014 return NO_ERROR;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07006015 }
6016
Steven Thomasd4071902020-03-24 16:02:53 -07006017 status_t setPolicyResult = overridePolicy
6018 ? mRefreshRateConfigs->setOverridePolicy(policy)
6019 : mRefreshRateConfigs->setDisplayManagerPolicy(*policy);
6020 if (setPolicyResult < 0) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006021 return BAD_VALUE;
6022 }
Steven Thomasd4071902020-03-24 16:02:53 -07006023 if (setPolicyResult == scheduler::RefreshRateConfigs::CURRENT_POLICY_UNCHANGED) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006024 return NO_ERROR;
6025 }
Steven Thomasd4071902020-03-24 16:02:53 -07006026 scheduler::RefreshRateConfigs::Policy currentPolicy = mRefreshRateConfigs->getCurrentPolicy();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006027
Steven Thomasf734df42020-04-13 21:09:28 -07006028 ALOGV("Setting desired display config specs: defaultConfig: %d primaryRange: [%.0f %.0f]"
6029 " expandedRange: [%.0f %.0f]",
6030 currentPolicy.defaultConfig.value(), currentPolicy.primaryRange.min,
6031 currentPolicy.primaryRange.max, currentPolicy.appRequestRange.min,
6032 currentPolicy.appRequestRange.max);
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07006033
Ana Krulecb9afd792020-06-11 13:16:15 -07006034 // TODO(b/140204874): Leave the event in until we do proper testing with all apps that might
6035 // be depending in this callback.
Alec Mouri60aee1c2019-10-28 16:18:59 -07006036 const nsecs_t vsyncPeriod =
Ady Abrahamabc27602020-04-08 17:20:29 -07006037 mRefreshRateConfigs->getRefreshRateFromConfigId(display->getActiveConfig())
6038 .getVsyncPeriod();
Ady Abrahamdfd62162020-06-10 16:11:56 -07006039 mScheduler->onPrimaryDisplayConfigChanged(mAppConnectionHandle, display->getId()->value,
6040 display->getActiveConfig(), vsyncPeriod);
Ana Krulecb9afd792020-06-11 13:16:15 -07006041 toggleKernelIdleTimer();
Ady Abraham838de062019-02-04 10:24:03 -08006042
Ana Krulec3f6a2062020-01-23 15:48:01 -08006043 auto configId = mScheduler->getPreferredConfigId();
Ady Abraham2e1dd892020-03-05 13:48:36 -08006044 auto& preferredRefreshRate = configId
Ana Krulec3f6a2062020-01-23 15:48:01 -08006045 ? mRefreshRateConfigs->getRefreshRateFromConfigId(*configId)
6046 // NOTE: Choose the default config ID, if Scheduler doesn't have one in mind.
Steven Thomasd4071902020-03-24 16:02:53 -07006047 : mRefreshRateConfigs->getRefreshRateFromConfigId(currentPolicy.defaultConfig);
Ana Krulec3f6a2062020-01-23 15:48:01 -08006048 ALOGV("trying to switch to Scheduler preferred config %d (%s)",
Ady Abrahamabc27602020-04-08 17:20:29 -07006049 preferredRefreshRate.getConfigId().value(), preferredRefreshRate.getName().c_str());
Ana Krulec3f6a2062020-01-23 15:48:01 -08006050
Ady Abrahamabc27602020-04-08 17:20:29 -07006051 if (isDisplayConfigAllowed(preferredRefreshRate.getConfigId())) {
6052 ALOGV("switching to Scheduler preferred config %d",
6053 preferredRefreshRate.getConfigId().value());
6054 setDesiredActiveConfig(
6055 {preferredRefreshRate.getConfigId(), Scheduler::ConfigEvent::Changed});
Ady Abraham2139f732019-11-13 18:56:40 -08006056 } else {
Ady Abrahamabc27602020-04-08 17:20:29 -07006057 LOG_ALWAYS_FATAL("Desired config not allowed: %d",
6058 preferredRefreshRate.getConfigId().value());
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07006059 }
6060
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006061 return NO_ERROR;
6062}
6063
Ana Krulec0782b882019-10-15 17:34:54 -07006064status_t SurfaceFlinger::setDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Steven Thomasf734df42020-04-13 21:09:28 -07006065 int32_t defaultConfig,
6066 float primaryRefreshRateMin,
6067 float primaryRefreshRateMax,
6068 float appRequestRefreshRateMin,
6069 float appRequestRefreshRateMax) {
Ana Krulec0782b882019-10-15 17:34:54 -07006070 ATRACE_CALL();
6071
6072 if (!displayToken) {
6073 return BAD_VALUE;
6074 }
6075
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006076 auto future = schedule([=]() -> status_t {
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07006077 const auto display = ON_MAIN_THREAD(getDisplayDeviceLocked(displayToken));
Ana Krulec234bb162019-11-10 22:55:55 +01006078 if (!display) {
6079 ALOGE("Attempt to set desired display configs for invalid display token %p",
6080 displayToken.get());
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006081 return NAME_NOT_FOUND;
Ana Krulec234bb162019-11-10 22:55:55 +01006082 } else if (display->isVirtual()) {
6083 ALOGW("Attempt to set desired display configs for virtual display");
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006084 return INVALID_OPERATION;
Ana Krulec234bb162019-11-10 22:55:55 +01006085 } else {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006086 using Policy = scheduler::RefreshRateConfigs::Policy;
Steven Thomasf734df42020-04-13 21:09:28 -07006087 const Policy policy{HwcConfigIndexType(defaultConfig),
6088 {primaryRefreshRateMin, primaryRefreshRateMax},
6089 {appRequestRefreshRateMin, appRequestRefreshRateMax}};
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006090 constexpr bool kOverridePolicy = false;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006091
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006092 return setDesiredDisplayConfigSpecsInternal(display, policy, kOverridePolicy);
6093 }
6094 });
6095
6096 return future.get();
Ana Krulec234bb162019-11-10 22:55:55 +01006097}
6098
6099status_t SurfaceFlinger::getDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006100 int32_t* outDefaultConfig,
Steven Thomasf734df42020-04-13 21:09:28 -07006101 float* outPrimaryRefreshRateMin,
6102 float* outPrimaryRefreshRateMax,
6103 float* outAppRequestRefreshRateMin,
6104 float* outAppRequestRefreshRateMax) {
Ana Krulec234bb162019-11-10 22:55:55 +01006105 ATRACE_CALL();
6106
Steven Thomasf734df42020-04-13 21:09:28 -07006107 if (!displayToken || !outDefaultConfig || !outPrimaryRefreshRateMin ||
6108 !outPrimaryRefreshRateMax || !outAppRequestRefreshRateMin || !outAppRequestRefreshRateMax) {
Ana Krulec234bb162019-11-10 22:55:55 +01006109 return BAD_VALUE;
6110 }
6111
6112 Mutex::Autolock lock(mStateLock);
6113 const auto display = getDisplayDeviceLocked(displayToken);
6114 if (!display) {
6115 return NAME_NOT_FOUND;
6116 }
6117
6118 if (display->isPrimary()) {
Steven Thomasd4071902020-03-24 16:02:53 -07006119 scheduler::RefreshRateConfigs::Policy policy =
6120 mRefreshRateConfigs->getDisplayManagerPolicy();
6121 *outDefaultConfig = policy.defaultConfig.value();
Steven Thomasf734df42020-04-13 21:09:28 -07006122 *outPrimaryRefreshRateMin = policy.primaryRange.min;
6123 *outPrimaryRefreshRateMax = policy.primaryRange.max;
6124 *outAppRequestRefreshRateMin = policy.appRequestRange.min;
6125 *outAppRequestRefreshRateMax = policy.appRequestRange.max;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006126 return NO_ERROR;
6127 } else if (display->isVirtual()) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006128 return INVALID_OPERATION;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006129 } else {
6130 const auto displayId = display->getId();
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006131 LOG_FATAL_IF(!displayId);
6132
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006133 *outDefaultConfig = getHwComposer().getActiveConfigIndex(*displayId);
6134 auto vsyncPeriod = getHwComposer().getActiveConfig(*displayId)->getVsyncPeriod();
Steven Thomasf734df42020-04-13 21:09:28 -07006135 *outPrimaryRefreshRateMin = 1e9f / vsyncPeriod;
6136 *outPrimaryRefreshRateMax = 1e9f / vsyncPeriod;
6137 *outAppRequestRefreshRateMin = 1e9f / vsyncPeriod;
6138 *outAppRequestRefreshRateMax = 1e9f / vsyncPeriod;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006139 return NO_ERROR;
Ana Krulec234bb162019-11-10 22:55:55 +01006140 }
Ana Krulec0782b882019-10-15 17:34:54 -07006141}
6142
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006143void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08006144 mFlinger->setInputWindowsFinished();
6145}
6146
Alec Mouri9a02eda2020-04-21 17:39:34 -07006147wp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
6148 Mutex::Autolock _l(mStateLock);
6149 return fromHandleLocked(handle);
6150}
6151
6152wp<Layer> SurfaceFlinger::fromHandleLocked(const sp<IBinder>& handle) {
Valerie Hau09e60052019-12-15 14:51:15 -08006153 BBinder* b = nullptr;
6154 if (handle) {
6155 b = handle->localBinder();
6156 }
Robert Carrc0df3122019-04-11 13:18:21 -07006157 if (b == nullptr) {
6158 return nullptr;
6159 }
6160 auto it = mLayersByLocalBinderToken.find(b);
6161 if (it != mLayersByLocalBinderToken.end()) {
Alec Mouri9a02eda2020-04-21 17:39:34 -07006162 return it->second;
Robert Carrc0df3122019-04-11 13:18:21 -07006163 }
6164 return nullptr;
6165}
6166
Dominik Laskowski75848362019-11-11 17:57:20 -08006167void SurfaceFlinger::onLayerFirstRef(Layer* layer) {
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006168 mNumLayers++;
6169 mScheduler->registerLayer(layer);
6170}
6171
6172void SurfaceFlinger::onLayerDestroyed(Layer* layer) {
6173 mNumLayers--;
Valerie Hauc5686802019-11-22 14:18:09 -08006174 removeFromOffscreenLayers(layer);
6175}
6176
6177// WARNING: ONLY CALL THIS FROM LAYER DTOR
6178// Here we add children in the current state to offscreen layers and remove the
6179// layer itself from the offscreen layer list. Since
6180// this is the dtor, it is safe to access the current state. This keeps us
6181// from dangling children layers such that they are not reachable from the
6182// Drawing state nor the offscreen layer list
6183// See b/141111965
6184void SurfaceFlinger::removeFromOffscreenLayers(Layer* layer) {
6185 for (auto& child : layer->getCurrentChildren()) {
6186 mOffscreenLayers.emplace(child.get());
6187 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006188 mOffscreenLayers.erase(layer);
6189}
6190
Alec Mouri4545a8a2019-08-08 20:05:32 -07006191void SurfaceFlinger::bufferErased(const client_cache_t& clientCacheId) {
6192 getRenderEngine().unbindExternalTextureBuffer(clientCacheId.id);
6193}
6194
Vishnu Nair08f6eae2019-11-26 14:01:39 -08006195status_t SurfaceFlinger::setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor,
6196 float lightPosY, float lightPosZ,
6197 float lightRadius) {
6198 Mutex::Autolock _l(mStateLock);
6199 mCurrentState.globalShadowSettings.ambientColor = vec4(ambientColor);
6200 mCurrentState.globalShadowSettings.spotColor = vec4(spotColor);
6201 mCurrentState.globalShadowSettings.lightPos.y = lightPosY;
6202 mCurrentState.globalShadowSettings.lightPos.z = lightPosZ;
6203 mCurrentState.globalShadowSettings.lightRadius = lightRadius;
6204
6205 // these values are overridden when calculating the shadow settings for a layer.
6206 mCurrentState.globalShadowSettings.lightPos.x = 0.f;
6207 mCurrentState.globalShadowSettings.length = 0.f;
Vishnu Nairb13bb952019-11-15 10:24:08 -08006208 return NO_ERROR;
6209}
6210
Lloyd Pique8d9f8362020-02-11 19:13:09 -08006211const std::unordered_map<std::string, uint32_t>& SurfaceFlinger::getGenericLayerMetadataKeyMap()
6212 const {
6213 // TODO(b/149500060): Remove this fixed/static mapping. Please prefer taking
6214 // on the work to remove the table in that bug rather than adding more to
6215 // it.
6216 static const std::unordered_map<std::string, uint32_t> genericLayerMetadataKeyMap{
6217 // Note: METADATA_OWNER_UID and METADATA_WINDOW_TYPE are officially
6218 // supported, and exposed via the
6219 // IVrComposerClient::VrCommand::SET_LAYER_INFO command.
6220 {"org.chromium.arc.V1_0.TaskId", METADATA_TASK_ID},
6221 {"org.chromium.arc.V1_0.CursorInfo", METADATA_MOUSE_CURSOR},
6222 };
6223 return genericLayerMetadataKeyMap;
6224}
6225
Steven Thomas62a4cf82020-01-31 12:04:03 -08006226status_t SurfaceFlinger::setFrameRate(const sp<IGraphicBufferProducer>& surface, float frameRate,
6227 int8_t compatibility) {
6228 if (!ValidateFrameRate(frameRate, compatibility, "SurfaceFlinger::setFrameRate")) {
6229 return BAD_VALUE;
6230 }
6231
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07006232 static_cast<void>(schedule([=] {
Ady Abraham60e42ea2020-03-09 19:17:31 -07006233 Mutex::Autolock lock(mStateLock);
6234 if (authenticateSurfaceTextureLocked(surface)) {
6235 sp<Layer> layer = (static_cast<MonitoredProducer*>(surface.get()))->getLayer();
6236 if (layer->setFrameRate(
6237 Layer::FrameRate(frameRate,
6238 Layer::FrameRate::convertCompatibility(compatibility)))) {
6239 setTransactionFlags(eTraversalNeeded);
6240 }
6241 } else {
6242 ALOGE("Attempt to set frame rate on an unrecognized IGraphicBufferProducer");
6243 return BAD_VALUE;
Steven Thomas62a4cf82020-01-31 12:04:03 -08006244 }
Ady Abraham60e42ea2020-03-09 19:17:31 -07006245 return NO_ERROR;
6246 }));
6247
Steven Thomas62a4cf82020-01-31 12:04:03 -08006248 return NO_ERROR;
6249}
6250
Steven Thomasd4071902020-03-24 16:02:53 -07006251status_t SurfaceFlinger::acquireFrameRateFlexibilityToken(sp<IBinder>* outToken) {
6252 if (!outToken) {
6253 return BAD_VALUE;
6254 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006255
6256 auto future = schedule([this] {
6257 status_t result = NO_ERROR;
6258 sp<IBinder> token;
6259
Steven Thomasd4071902020-03-24 16:02:53 -07006260 if (mFrameRateFlexibilityTokenCount == 0) {
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07006261 const auto display = ON_MAIN_THREAD(getDefaultDisplayDeviceLocked());
Steven Thomasd4071902020-03-24 16:02:53 -07006262
6263 // This is a little racy, but not in a way that hurts anything. As we grab the
6264 // defaultConfig from the display manager policy, we could be setting a new display
6265 // manager policy, leaving us using a stale defaultConfig. The defaultConfig doesn't
6266 // matter for the override policy though, since we set allowGroupSwitching to true, so
6267 // it's not a problem.
6268 scheduler::RefreshRateConfigs::Policy overridePolicy;
6269 overridePolicy.defaultConfig =
6270 mRefreshRateConfigs->getDisplayManagerPolicy().defaultConfig;
6271 overridePolicy.allowGroupSwitching = true;
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006272 constexpr bool kOverridePolicy = true;
6273 result = setDesiredDisplayConfigSpecsInternal(display, overridePolicy, kOverridePolicy);
Steven Thomasd4071902020-03-24 16:02:53 -07006274 }
6275
6276 if (result == NO_ERROR) {
6277 mFrameRateFlexibilityTokenCount++;
6278 // Handing out a reference to the SurfaceFlinger object, as we're doing in the line
6279 // below, is something to consider carefully. The lifetime of the
6280 // FrameRateFlexibilityToken isn't tied to SurfaceFlinger object lifetime, so if this
6281 // SurfaceFlinger object were to be destroyed while the token still exists, the token
6282 // destructor would be accessing a stale SurfaceFlinger reference, and crash. This is ok
6283 // in this case, for two reasons:
6284 // 1. Once SurfaceFlinger::run() is called by main_surfaceflinger.cpp, the only way
6285 // the program exits is via a crash. So we won't have a situation where the
6286 // SurfaceFlinger object is dead but the process is still up.
6287 // 2. The frame rate flexibility token is acquired/released only by CTS tests, so even
6288 // if condition 1 were changed, the problem would only show up when running CTS tests,
6289 // not on end user devices, so we could spot it and fix it without serious impact.
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006290 token = new FrameRateFlexibilityToken(
Steven Thomasd4071902020-03-24 16:02:53 -07006291 [this]() { onFrameRateFlexibilityTokenReleased(); });
6292 ALOGD("Frame rate flexibility token acquired. count=%d",
6293 mFrameRateFlexibilityTokenCount);
6294 }
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006295
6296 return std::make_pair(result, token);
6297 });
6298
6299 status_t result;
6300 std::tie(result, *outToken) = future.get();
Steven Thomasd4071902020-03-24 16:02:53 -07006301 return result;
6302}
6303
6304void SurfaceFlinger::onFrameRateFlexibilityTokenReleased() {
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006305 static_cast<void>(schedule([this] {
Steven Thomasd4071902020-03-24 16:02:53 -07006306 LOG_ALWAYS_FATAL_IF(mFrameRateFlexibilityTokenCount == 0,
6307 "Failed tracking frame rate flexibility tokens");
6308 mFrameRateFlexibilityTokenCount--;
6309 ALOGD("Frame rate flexibility token released. count=%d", mFrameRateFlexibilityTokenCount);
6310 if (mFrameRateFlexibilityTokenCount == 0) {
Dominik Laskowski0a1435d2020-04-21 00:27:31 -07006311 const auto display = ON_MAIN_THREAD(getDefaultDisplayDeviceLocked());
Dominik Laskowskidd4ef272020-04-23 14:02:12 -07006312 constexpr bool kOverridePolicy = true;
6313 status_t result = setDesiredDisplayConfigSpecsInternal(display, {}, kOverridePolicy);
Steven Thomasd4071902020-03-24 16:02:53 -07006314 LOG_ALWAYS_FATAL_IF(result < 0, "Failed releasing frame rate flexibility token");
6315 }
6316 }));
6317}
6318
Dominik Laskowski20134642020-04-20 22:36:44 -07006319void SurfaceFlinger::enableRefreshRateOverlay(bool enable) {
6320 static_cast<void>(schedule([=] {
6321 std::unique_ptr<RefreshRateOverlay> overlay;
6322 if (enable) {
6323 overlay = std::make_unique<RefreshRateOverlay>(*this);
6324 }
6325
6326 {
6327 Mutex::Autolock lock(mStateLock);
6328
6329 // Destroy the layer of the current overlay, if any, outside the lock.
6330 mRefreshRateOverlay.swap(overlay);
6331 if (!mRefreshRateOverlay) return;
6332
6333 if (const auto display = getDefaultDisplayDeviceLocked()) {
6334 mRefreshRateOverlay->setViewport(display->getSize());
6335 }
6336
6337 mRefreshRateOverlay->changeRefreshRate(mRefreshRateConfigs->getCurrentRefreshRate());
6338 }
6339 }));
6340}
6341
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006342} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07006343
Mathias Agopian3f844832013-08-07 21:24:32 -07006344#if defined(__gl_h_)
6345#error "don't include gl/gl.h in this file"
6346#endif
6347
6348#if defined(__gl2_h_)
6349#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08006350#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08006351
6352// TODO(b/129481165): remove the #pragma below and fix conversion issues
6353#pragma clang diagnostic pop // ignored "-Wconversion"